问:
building from source Qpid Messaging API (C++, bindings) [Qpid C++ 1.37.0] - missing files
I am trying to build from sources Qpid Messaging API (C++, bindings).
Build is triggered on RHEL and all prerequisites mentioned on link below are installed.

https://git-wip-us.apache.org/repos/asf?p=qpid-cpp.git;a=blob_plain;f=INSTALL.txt;hb=HEAD

yet when reaching step: make all

what i get is this

error:

```<code>Linking CXX shared library libqpidclient.so
[ 86%] Built target qpidclient
Scanning dependencies of target qpidmessaging
[ 86%] Building CXX object src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o
In file included from /home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/AddressHelper.cpp:22:0:
/home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/PnData.h:27:27: fatal error: proton/engine.h: No such file or directory
 #include <proton/engine.h>
                           ^
compilation terminated.
make[3]: *** [src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o] Error 1
make[2]: *** [src/CMakeFiles/qpidmessaging.dir/all] Error 2
make[1]: *** [examples/messaging/CMakeFiles/client.dir/rule] Error 2
make: *** [client] Error 2
</code>```

that would indicate that "Qpid proton-c " might be missing but its installed....

any ideas ?

答:
As stated in the very INSTALL file you provided the link to:

Note: If Proton is installed in a non-standard location, there are two
ways to locate it:

Recommended: use proton 0.7 or later and use the same install prefix    for both Proton and Qpid.

Using pkg-config: set the PKG_CONFIG_PATH environment variable to    /lib[64]/pkgconfig before running cmake.

I'd go for method 1 and rebuild Proton specifiyng an install prefix to cmake, this way:

```<code>cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local
</code>```

Then use the same prefix for Qpid (i.e. run cmake again, just like the above).

Body:
I am trying to build from sources Qpid Messaging API (C++, bindings).
Build is triggered on RHEL and all prerequisites mentioned on link below are installed.

https://git-wip-us.apache.org/repos/asf?p=qpid-cpp.git;a=blob_plain;f=INSTALL.txt;hb=HEAD

yet when reaching step: make all

what i get is this

error:

Linking CXX shared library libqpidclient.so
[ 86%] Built target qpidclient
Scanning dependencies of target qpidmessaging
[ 86%] Building CXX object src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o
In file included from /home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/AddressHelper.cpp:22:0:
/home/m020390/qpid_cpp/qpid-cpp-1.37.0/src/qpid/messaging/amqp/PnData.h:27:27: fatal error: proton/engine.h: No such file or directory
 #include <proton/engine.h>
                           ^
compilation terminated.
make[3]: *** [src/CMakeFiles/qpidmessaging.dir/qpid/messaging/amqp/AddressHelper.cpp.o] Error 1
make[2]: *** [src/CMakeFiles/qpidmessaging.dir/all] Error 2
make[1]: *** [examples/messaging/CMakeFiles/client.dir/rule] Error 2
make: *** [client] Error 2

that would indicate that "Qpid proton-c " might be missing but its installed....

any ideas ?

Body:
As stated in the very INSTALL file you provided the link to:

Note: If Proton is installed in a non-standard location, there are two
ways to locate it:

Recommended: use proton 0.7 or later and use the same install prefix    for both Proton and Qpid.

Using pkg-config: set the PKG_CONFIG_PATH environment variable to    /lib[64]/pkgconfig before running cmake.

I'd go for method 1 and rebuild Proton specifiyng an install prefix to cmake, this way:

cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local

Then use the same prefix for Qpid (i.e. run cmake again, just like the above).


来源: stackexchange

问:
bootstrap 4 modal-header trying to get badge aligned on right
I'm trying to get the "Banana Score" badge to float right, but to no avail. Does anyone know if this is even possible in Bootstrap 4.

I've tried all sorts of variations around flex, the best I had was a hack using columns, but this looks worse than the example below.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Customer
            Banana Score  4

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

答:
Give h5 width:100% and float:right to banana element.

$('#myModal').on('shown.bs.modal', function () {
      $('#myInput').focus()
    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#exampleModalLabel{
  width:100%
}
.badge-secondary{
  float:right;
  margin-top:6px;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

            Customer
            Banana Score  4

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

ContentLicense: CC BY-SA 3.0

Body:
Give h5 width:100% and float:right to banana element.

$('#myModal').on('shown.bs.modal', function () {
      $('#myInput').focus()
    })

#exampleModalLabel{
  width:100%
}
.badge-secondary{
  float:right;
  margin-top:6px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">
            <span>Customer</span>
            <span id="test" class="badge badge-secondary">Banana Score  <span class="badge badge-light">4</span></span>
            </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


问:
How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?
How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

答:
The easiest way to convert a byte array to a stream is using the MemoryStream class:

```<code>Stream stream = new MemoryStream(byteArray);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

ContentLicense: CC BY-SA 2.5


问:
How to use Angular-Charts JS?
Apart from the documentation I read (usually not helpful), I found some chart examples I want to implement to my page, but it seems not working. I tried to tweak it around but every time it gets load, it always displaying blank on the page.

Here's the code:

```<code><div data-ng-controller="LineCtrl as line">
<canvas> data-sys-chart-line
        data-dataset="line.data"
        width="400"
        height="240"></canvas>
</div>
<script type="text/javascript">
    (function () {
        'use strict';

        function LineCtrl ( ) {
            this.data = {
                labels: ["January", "February", "March", "April", "May", "June"],
            datasets: [
                {
                    fillColor: "rgba(220,220,220,0.2)",
                    strokeColor: "rgba(220,220,220,1)",
                    pointColor: "rgba(220,220,220,1)",
                    data: [40, 10, 60, 70, 20, 20]
                },
                {
                    fillColor: "rgba(151,187,205,0.2)",
                    strokeColor: "rgba(151,187,205,1)",
                    pointColor: "rgba(151,187,205,1)",
                    data: [30, 70, 40, 90, 60, 70]
                }
            ]
        };
    }
})();
</script>
<!-- Includes Dependencies here: AngularJS & Chart.js -->
<script src="script/Chart.js"></script>
<script src="script/angular-chart.min.js"></script>
<script src="script/tc-angular-chartjs.min.js"></script>
<script>
</code>```

I included those .js files under /script folder in my project folder.

答:
i have never used Chart.js before but seems that u are doing it wrong

you have never initialize the chart, by reading the documentation like for 10 second i found that you have to initialize it like this

```<code>var ctx = document.getElementById("here_is_the_canvas_element").getContext('2d');
var myChart = new Chart(ctx, { ... })
</code>```

and you are using Chart.js code before you include the library

Title: How to use Angular-Charts JS?

Body:
Apart from the documentation I read (usually not helpful), I found some chart examples I want to implement to my page, but it seems not working. I tried to tweak it around but every time it gets load, it always displaying blank on the page.

Here's the code:

<canvas> data-sys-chart-line
        data-dataset="line.data"
        width="400"
        height="240"></canvas>

Body:
i have never used Chart.js before but seems that u are doing it wrong

you have never initialize the chart, by reading the documentation like for 10 second i found that you have to initialize it like this

var ctx = document.getElementById("here_is_the_canvas_element").getContext('2d');
var myChart = new Chart(ctx, { ... })

and you are using Chart.js code before you include the library


问:
How to start using composer in your project after installation on Windows 10?
I downloaded the Composer-Setup.exe and run to install Composer using the installer within few mouse clicks.

Opened terminal by typing in cmd. At the command prompt typed in Composer and saw all the information related to Composer which means I've installed Composer successfully on my Windows 10 machine.

I'm using XAMPP for development. So, C:\xampp\htdocs\ is my document root directory.

I created a new directory titled composer_demo in document root. The path of which is C:\xampp\htdocs\composer_demo

Now, I want to use composer in this directory. How should I use it?

I went through the documentation but it's not saying anything clearly whether I've to create the composer.json file manually inside the directory composer_demo or what?

Do I need to write the dependency package manually into composer.json file manually or what like?

```<code>{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}
</code>```

I'm clueless. Please someone give me step-by-step instructions to use the composer inside my newly created directory composer_demo.

Thanks.

答:
run .exe file
give php path to C:\xampp\php
and
give istallation path to C:\xampp\htdocs\composer_demo.

Run shell or cmd

go to your directory. with typing cd C:\xampp\htdocs\composer_demo\

now type your keyword ex:- for install php-ffmpeg composer require php-ffmpeg/php-ffmpeg

Body:
I downloaded the Composer-Setup.exe and run to install Composer using the installer within few mouse clicks.

Opened terminal by typing in cmd. At the command prompt typed in Composer and saw all the information related to Composer which means I've installed Composer successfully on my Windows 10 machine.

I'm using XAMPP for development. So, C:\xampp\htdocs\ is my document root directory.

I created a new directory titled composer_demo in document root. The path of which is C:\xampp\htdocs\composer_demo

Now, I want to use composer in this directory. How should I use it?

I went through the documentation but it's not saying anything clearly whether I've to create the composer.json file manually inside the directory composer_demo or what?

Do I need to write the dependency package manually into composer.json file manually or what like?

{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}

I'm clueless. Please someone give me step-by-step instructions to use the composer inside my newly created directory composer_demo.

Thanks.


问:
How call jQuery function in AngularJS controller?
I have the following html:

```<code><iframe name='iframe1' id="iframe1" src='http://micro.shoretel.com" frameborder='0' width='660' height='450'></iframe>
</code>```

And the jQuery:

```<code>$("iframe").contents().find("element-selector").css("border-color", "blue");
</code>```

I want to do:

```<code>app.controller("myCntrl", function ($scope, angularService, $modal) {

        $scope.deletePrepared = function (itm) {
            var getData = angularService.DeletePrepared(itm.ProductId);
            getData.then(function (msg) {
                GetAllPrepared();
            }, function () {
$("iframe").contents().find("element-selector").css("border-color", "blue");});}});
</code>```

What is the mistake can be?

答:
//THIS IS BOTH WAY COMMUNICATION U CAN CALL FROM JS TO CONTROLLER AND CONTROLLER TO JS
window.call_from_scope = function(){
        alert('CALLED FROM SCOPE')
      var myscope= angular.element(document.querySelector('[ng-app="Profile"]')).scope()
      myscope.return()
  }
var app = angular.module("Profile",[])
app.controller("ProfileCtrl", function($scope){

  $scope.get_name = function(){
        window.call_from_scope()
  }
   $scope.return = function(){
    alert('Called from window')
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Profile" ng-controller="ProfileCtrl">
    <button ng-click="get_name()">Click Here</button>
</body></code>```

Body:
I have the following html:

And the jQuery:

$("iframe").contents().find("element-selector").css("border-color", "blue");

I want to do:

app.controller("myCntrl", function ($scope, angularService, $modal) {

        $scope.deletePrepared = function (itm) {
            var getData = angularService.DeletePrepared(itm.ProductId);
            getData.then(function (msg) {
                GetAllPrepared();
            }, function () {
$("iframe").contents().find("element-selector").css("border-color", "blue");});}});

What is the mistake can be?

Body:
//THIS IS BOTH WAY COMMUNICATION U CAN CALL FROM JS TO CONTROLLER AND CONTROLLER TO JS
window.call_from_scope = function(){
        alert('CALLED FROM SCOPE')
      var myscope= angular.element(document.querySelector('[ng-app="Profile"]')).scope()
      myscope.return()
  }
var app = angular.module("Profile",[])
app.controller("ProfileCtrl", function($scope){

  $scope.get_name = function(){
        window.call_from_scope()
  }
   $scope.return = function(){
    alert('Called from window')
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Profile" ng-controller="ProfileCtrl">
    <button ng-click="get_name()">Click Here</button>
</body>


问:
How to Auto Submit form using PHP
I am currently developing a website where I am facing the following problem:

I tried passing the User id and password to the login page and auto submit the page using a script, which will take the user to the next page. This is just to bypass the login page in my site. This works perfectly fine.

When the "No script" add on is enabled on a Mozilla Firefox browser, the script to auto submit the form is not working. As a result, the login page is getting displayed to the user with the filled in user id and password.

Also, sometimes the user is able to see the login page on the front end when we auto submit the login page.

Are there any possible ways to overcome these two issues?

答: If you already know the user_id and password when the user requests the login page then you could just send a location header</p>

Title: How to Auto Submit form using PHP


问:
Unit for size returned by mlsd method of FTP class
I have following snippet.

```<code>from ftplib import FTP
ftp_connect = FTP(link)
ftp_connect.login()
listing = [elem for elem in ftp_connect.mlsd(exact_source_data_path) if elem[0].endswith('.gz')]
</code>```

I am using this snippet to connect to ftp server and fetch list of files and its facts. This snipped will return something like this:

```<code>[('file_1.gz',   {
    'modify': '20171205190142',
    'perm': 'adfr',
    'size': '1556',
    'type': 'file',
    'unique': '41U2B7801',
    'unix.group': '528',
    'unix.mode': '0444',
    'unix.owner': '14'   }),   ('file_2.gz',   {
    'modify': '20171206190136',
    'perm': 'adfr',
    'size': '902254',
    'type': 'file',
    'unique': '41U2B7804',
    'unix.group': '528',
    'unix.mode': '0444',
    'unix.owner': '14'   })]
</code>```

I would like to know what is the unit of the size? Like size = 1556 Is this in bytes? In KB? The documentation says:

Return a generator object yielding a tuple of two elements for every
  file found in path. First element is the file name, the second one is
  a dictionary containing facts about the file name.

答:
ftplib.FTP.mlsd uses the MLSD command (RFC 3659). Its response contains the size in "octets" (see Wikipedia), so more likely you "Bytes" then "KB"

See https://www.rfc-editor.org/rfc/rfc3659.html#section-7.5

Body:
I have following snippet.

from ftplib import FTP
ftp_connect = FTP(link)
ftp_connect.login()
listing = [elem for elem in ftp_connect.mlsd(exact_source_data_path) if elem[0].endswith('.gz')]

I am using this snippet to connect to ftp server and fetch list of files and its facts. This snipped will return something like this:

[('file_1.gz',   {
    'modify': '20171205190142',
    'perm': 'adfr',
    'size': '1556',
    'type': 'file',
    'unique': '41U2B7801',
    'unix.group': '528',
    'unix.mode': '0444',
    'unix.owner': '14'   }),   ('file_2.gz',   {
    'modify': '20171206190136',
    'perm': 'adfr',
    'size': '902254',
    'type': 'file',
    'unique': '41U2B7804',
    'unix.group': '528',
    'unix.mode': '0444',
    'unix.owner': '14'   })]

I would like to know what is the unit of the size? Like size = 1556 Is this in bytes? In KB? The documentation says:

Return a generator object yielding a tuple of two elements for every
  file found in path. First element is the file name, the second one is
  a dictionary containing facts about the file name.


问:
Failed to resolve google auth dependency
I am attempting to follow the instructions at https://developers.google.com/identity/sign-in/android/start-integrating
to create a Google sign in button for my application. However, when I try to use

```<code>compile 'com.google.android.gms:play-services-auth:11.6.2'
</code>```

I get the error "Could not find com.google.android.gms:play-services-auth:11.6.2". I have followed the advice of similar questions and have made sure that my SDK is up to date but no luck.

The project build:

```<code>buildscript {
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.1.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}
allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}
</code>```

And the app build:

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "theproject.theapp"
        minSdkVersion 19
        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(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'

    compile 'com.google.android.gms:play-services-auth:11.6.2'
    compile 'com.google.android.gms:play-services-maps:9.0.0'
    compile 'com.google.maps:google-maps-services:0.1.20'

    compile 'com.lorentzos.swipecards:library:1.0.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.makeramen:roundedimageview:2.3.0'

    compile 'com.facebook.android:facebook-login:[4,5)'

    testCompile 'junit:junit:4.12'
}
</code>```

Any suggestions? Thanks,

Ian

答:
Just add google() to your gradle repositories list, this is where version 11.6.2 is found for now. Something like that:</p>

```<code>allprojects {
    repositories {
        jcenter()
        google()
        maven { url 'https://jitpack.io' }
    }
}
</code>```

Body:
I am attempting to follow the instructions at https://developers.google.com/identity/sign-in/android/start-integrating
to create a Google sign in button for my application. However, when I try to use

compile 'com.google.android.gms:play-services-auth:11.6.2'

I get the error "Could not find com.google.android.gms:play-services-auth:11.6.2". I have followed the advice of similar questions and have made sure that my SDK is up to date but no luck.

The project build:

buildscript {
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.1.0'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}
allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

And the app build:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "theproject.theapp"
        minSdkVersion 19
        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(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'

    compile 'com.google.android.gms:play-services-auth:11.6.2'
    compile 'com.google.android.gms:play-services-maps:9.0.0'
    compile 'com.google.maps:google-maps-services:0.1.20'

    compile 'com.lorentzos.swipecards:library:1.0.9'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.makeramen:roundedimageview:2.3.0'

    compile 'com.facebook.android:facebook-login:[4,5)'

    testCompile 'junit:junit:4.12'
}

Any suggestions? Thanks,

Ian

Body:
Just add google() to your gradle repositories list, this is where version 11.6.2 is found for now. Something like that:

allprojects {
    repositories {
        jcenter()
        google()
        maven { url 'https://jitpack.io' }
    }
}


问:
How to store image captured using camera.takePicture(null,null,mPicture) so that it can be displayed it in next activity?
I am making a custom camera application in android. I capture the image using

camera.takePicture(null,null,mPicture)" and "Camera.PictureCallBack()

I want to store the image taken from the camera so that I can display it in the next activity. How can it be done?

```<code>    Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);

            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }
};

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}
</code>```

答:
TO open Camera

```<code>Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, SELECT_PICTURE_USING_CAMERA);
</code>```

Then need to implement onActivityResult to get the data.

```<code>public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE_USING_CAMERA) {
            try {
               final File file = new File(outputFileUri.getPath());
            } catch (Exception ex) {
                Log.e("Exception", ex.toString());
            }
        }
    }
}
</code>```

Then you can take the image form the file path to display in the next activity.

Body:
I am making a custom camera application in android. I capture the image using

camera.takePicture(null,null,mPicture)" and "Camera.PictureCallBack()

I want to store the image taken from the camera so that I can display it in the next activity. How can it be done?

    Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);

            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }
};

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}

Body:
TO open Camera

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, SELECT_PICTURE_USING_CAMERA);

Then need to implement onActivityResult to get the data.

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE_USING_CAMERA) {
            try {
               final File file = new File(outputFileUri.getPath());
            } catch (Exception ex) {
                Log.e("Exception", ex.toString());
            }
        }
    }
}

Then you can take the image form the file path to display in the next activity.


问:
How to change label value to be like password field value?
i'm having password like value to be set into label to be shown as ***(as per characters).

```<code><label>password</label>
</code>```

Output of this shown like below,because label value whatever it is.

```<code>password
</code>```

Expected result:

********

In my case its should be converted like ******** (as per no of characters).

Am newbie to js. Any one suggest me key points to do this.

How to convert this to be number of * values as per characters?

答:
For pure Javascript with no jQuery you could use split() to transform string to array and then map() to modify each element based on condition.

var label = document.getElementById('password');

let replaceAll = (str, chars = []) => {
  return str.split('')
  .map(c => c.trim() && !chars.includes(c) ? '*' : c)
  .join('');
}

label.innerHTML = replaceAll(label.textContent, '*');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  margin: 5px;
  padding: 5px;
  border: 1px solid black;
}

span {
  margin: 5px;
  font-weight: bold;
}</code>```

  Field without formatting
  password

  Field with formatting
  password

```

Body:
i'm having password like value to be set into label to be shown as ***(as per characters).

password

Output of this shown like below,because label value whatever it is.

password

Expected result:

********

In my case its should be converted like ******** (as per no of characters).

Am newbie to js. Any one suggest me key points to do this.

How to convert this to be number of * values as per characters?

Body:
For pure Javascript with no jQuery you could use split() to transform string to array and then map() to modify each element based on condition.

var label = document.getElementById('password');

let replaceAll = (str, chars = []) => {
  return str.split('')
  .map(c => c.trim() && !chars.includes(c) ? '*' : c)
  .join('');
}

label.innerHTML = replaceAll(label.textContent, '*');

.container {
  margin: 5px;
  padding: 5px;
  border: 1px solid black;
}

span {
  margin: 5px;
  font-weight: bold;
}

<div class='container'>
  <span>Field without formatting</span>
  <label id='standard'>password</label>
  <hr />
  <span>Field with formatting</span>
  <label id='password'>password</label>
</div>


问:
Converting List<Map<String, List<String>>> to String[][]
I have a use case where I scrape some data, and for some records some keys have multiple values. The final output I want is CSV, which I have a library for, and it expects a 2-dimensional array.

So my input structure looks like List<TreeMap<String, List<String>>> (I use TreeMap to ensure stable key order), and my output needs to be String[][].

I wrote a generic transformation which calculates the number of columns for each key based on max number of values among all records, and leaves empty cells for records that have less than max values, but it turned out more complex than expected.

My question is: can it be written in a more concise/effective (but still generic) way? Especially using Java 8 streams/lambdas etc.?

Sample data and my algorithm follows below (not tested beyond sample data yet):

```<code>package org.example.import;

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<TreeMap<String, List<String>>> rows = new ArrayList<>();
        TreeMap<String, List<String>> row1 = new TreeMap<>();
        row1.put("Title", Arrays.asList("Product 1"));
        row1.put("Category", Arrays.asList("Wireless", "Sensor"));
        row1.put("Price",Arrays.asList("20"));
        rows.add(row1);
        TreeMap<String, List<String>> row2 = new TreeMap<>();
        row2.put("Title", Arrays.asList("Product 2"));
        row2.put("Category", Arrays.asList("Sensor"));
        row2.put("Price",Arrays.asList("35"));
        rows.add(row2);
        TreeMap<String, List<String>> row3 = new TreeMap<>();
        row3.put("Title", Arrays.asList("Product 3"));
        row3.put("Price",Arrays.asList("15"));
        rows.add(row3);

        System.out.println("Input:");
        System.out.println(rows);
        System.out.println("Output:");
        System.out.println(Arrays.deepToString(multiValueListsToArray(rows)));
    }

    public static String[][] multiValueListsToArray(List<TreeMap<String, List<String>>> rows)
    {
        Map<String, IntSummaryStatistics> colWidths = rows.
                stream().
                flatMap(m -> m.entrySet().stream()).
                collect(Collectors.groupingBy(e -> e.getKey(), Collectors.summarizingInt(e -> e.getValue().size())));
        Long tableWidth = colWidths.values().stream().mapToLong(IntSummaryStatistics::getMax).sum();
        String[][] array = new String[rows.size()][tableWidth.intValue()];
        Iterator<TreeMap<String, List<String>>> rowIt = rows.iterator(); // iterate rows
        int rowIdx = 0;
        while (rowIt.hasNext())
        {
            TreeMap<String, List<String>> row = rowIt.next();
            Iterator<String> colIt = colWidths.keySet().iterator(); // iterate columns
            int cellIdx = 0;
            while (colIt.hasNext())
            {
                String col = colIt.next();
                long colWidth = colWidths.get(col).getMax();
                for (int i = 0; i < colWidth; i++) // iterate cells within column
                    if (row.containsKey(col) && row.get(col).size() > i)
                        array[rowIdx][cellIdx + i] = row.get(col).get(i);
                cellIdx += colWidth;
            }
            rowIdx++;
        }
        return array;
    }

}
</code>```

Program output:

```<code>Input:
[{Category=[Wireless, Sensor], Price=[20], Title=[Product 1]}, {Category=[Sensor], Price=[35], Title=[Product 2]}, {Price=[15], Title=[Product 3]}]
Output:
[[Wireless, Sensor, 20, Product 1], [Sensor, null, 35, Product 2], [null, null, 15, Product 3]]
</code>```

答:
As a first step, I wouldn’t focus on new Java 8 features, but rather Java 5+ features. Don’t deal with Iterators when you can use for-each. Generally, don’t iterate over a keySet() to perform a map lookup for every key, as you can iterate over the entrySet() not requiring any lookup. Also, don’t ask for an IntSummaryStatistics when you’re only interested in the maximum value. And don’t iterate over the bigger of two data structures, just to recheck that you’re not beyond the smaller one in each iteration.

```<code>Map<String, Integer> colWidths = rows.
        stream().
        flatMap(m -> m.entrySet().stream()).
        collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().size(), Integer::max));
int tableWidth = colWidths.values().stream().mapToInt(Integer::intValue).sum();
String[][] array = new String[rows.size()][tableWidth];

int rowIdx = 0;
for(TreeMap<String, List<String>> row: rows) {
    int cellIdx = 0;
    for(Map.Entry<String,Integer> e: colWidths.entrySet()) {
        String col = e.getKey();
        List<String> cells = row.get(col);
        int index = cellIdx;
        if(cells != null) for(String s: cells) array[rowIdx][index++]=s;
        cellIdx += colWidths.get(col);
    }
    rowIdx++;
}
return array;
</code>```

We can simplify the loop further by using a map to column positions rather than widths:

```<code>Map<String, Integer> colPositions = rows.
        stream().
        flatMap(m -> m.entrySet().stream()).
        collect(Collectors.toMap(e -> e.getKey(),
                                 e -> e.getValue().size(), Integer::max, TreeMap::new));
int tableWidth = 0;
for(Map.Entry<String,Integer> e: colPositions.entrySet())
    tableWidth += e.setValue(tableWidth);

String[][] array = new String[rows.size()][tableWidth];

int rowIdx = 0;
for(Map<String, List<String>> row: rows) {
    for(Map.Entry<String,List<String>> e: row.entrySet()) {
        int index = colPositions.get(e.getKey());
        for(String s: e.getValue()) array[rowIdx][index++]=s;
    }
    rowIdx++;
}
return array;
</code>```

A header array can be prepended with the following change:

```<code>Map<String, Integer> colPositions = rows.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().size(),
                              Integer::max, TreeMap::new));
String[] header = colPositions.entrySet().stream()
    .flatMap(e -> Collections.nCopies(e.getValue(), e.getKey()).stream())
    .toArray(String[]::new);
int tableWidth = 0;
for(Map.Entry<String,Integer> e: colPositions.entrySet())
    tableWidth += e.setValue(tableWidth);

String[][] array = new String[rows.size()+1][tableWidth];
array[0] = header;

int rowIdx = 1;
for(Map<String, List<String>> row: rows) {
    for(Map.Entry<String,List<String>> e: row.entrySet()) {
        int index = colPositions.get(e.getKey());
        for(String s: e.getValue()) array[rowIdx][index++]=s;
    }
    rowIdx++;
}
return array;
</code>```

Body:
I have a use case where I scrape some data, and for some records some keys have multiple values. The final output I want is CSV, which I have a library for, and it expects a 2-dimensional array.

So my input structure looks like List<TreeMap<String, List<String>>> (I use TreeMap to ensure stable key order), and my output needs to be String[][].

I wrote a generic transformation which calculates the number of columns for each key based on max number of values among all records, and leaves empty cells for records that have less than max values, but it turned out more complex than expected.

My question is: can it be written in a more concise/effective (but still generic) way? Especially using Java 8 streams/lambdas etc.?

Sample data and my algorithm follows below (not tested beyond sample data yet):

package org.example.import;

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<TreeMap<String, List<String>>> rows = new ArrayList<>();
        TreeMap<String, List<String>> row1 = new TreeMap<>();
        row1.put("Title", Arrays.asList("Product 1"));
        row1.put("Category", Arrays.asList("Wireless", "Sensor"));
        row1.put("Price",Arrays.asList("20"));
        rows.add(row1);
        TreeMap<String, List<String>> row2 = new TreeMap<>();
        row2.put("Title", Arrays.asList("Product 2"));
        row2.put("Category", Arrays.asList("Sensor"));
        row2.put("Price",Arrays.asList("35"));
        rows.add(row2);
        TreeMap<String, List<String>> row3 = new TreeMap<>();
        row3.put("Title", Arrays.asList("Product 3"));
        row3.put("Price",Arrays.asList("15"));
        rows.add(row3);

        System.out.println("Input:");
        System.out.println(rows);
        System.out.println("Output:");
        System.out.println(Arrays.deepToString(multiValueListsToArray(rows)));
    }

    public static String[][] multiValueListsToArray(List<TreeMap<String, List<String>>> rows)
    {
        Map<String, IntSummaryStatistics> colWidths = rows.
                stream().
                flatMap(m -> m.entrySet().stream()).
                collect(Collectors.groupingBy(e -> e.getKey(), Collectors.summarizingInt(e -> e.getValue().size())));
        Long tableWidth = colWidths.values().stream().mapToLong(IntSummaryStatistics::getMax).sum();
        String[][] array = new String[rows.size()][tableWidth.intValue()];
        Iterator<TreeMap<String, List<String>>> rowIt = rows.iterator(); // iterate rows
        int rowIdx = 0;
        while (rowIt.hasNext())
        {
            TreeMap<String, List<String>> row = rowIt.next();
            Iterator<String> colIt = colWidths.keySet().iterator(); // iterate columns
            int cellIdx = 0;
            while (colIt.hasNext())
            {
                String col = colIt.next();
                long colWidth = colWidths.get(col).getMax();
                for (int i = 0; i < colWidth; i++) // iterate cells within column
                    if (row.containsKey(col) && row.get(col).size() > i)
                        array[rowIdx][cellIdx + i] = row.get(col).get(i);
                cellIdx += colWidth;
            }
            rowIdx++;
        }
        return array;
    }

}

Program output:

Input:
[{Category=[Wireless, Sensor], Price=[20], Title=[Product 1]}, {Category=[Sensor], Price=[35], Title=[Product 2]}, {Price=[15], Title=[Product 3]}]
Output:
[[Wireless, Sensor, 20, Product 1], [Sensor, null, 35, Product 2], [null, null, 15, Product 3]]

Body:
As a first step, I wouldn’t focus on new Java 8 features, but rather Java 5+ features. Don’t deal with Iterators when you can use for-each. Generally, don’t iterate over a keySet() to perform a map lookup for every key, as you can iterate over the entrySet() not requiring any lookup. Also, don’t ask for an IntSummaryStatistics when you’re only interested in the maximum value. And don’t iterate over the bigger of two data structures, just to recheck that you’re not beyond the smaller one in each iteration.

Map<String, Integer> colWidths = rows.
        stream().
        flatMap(m -> m.entrySet().stream()).
        collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().size(), Integer::max));
int tableWidth = colWidths.values().stream().mapToInt(Integer::intValue).sum();
String[][] array = new String[rows.size()][tableWidth];

int rowIdx = 0;
for(TreeMap<String, List<String>> row: rows) {
    int cellIdx = 0;
    for(Map.Entry<String,Integer> e: colWidths.entrySet()) {
        String col = e.getKey();
        List<String> cells = row.get(col);
        int index = cellIdx;
        if(cells != null) for(String s: cells) array[rowIdx][index++]=s;
        cellIdx += colWidths.get(col);
    }
    rowIdx++;
}
return array;

We can simplify the loop further by using a map to column positions rather than widths:

Map<String, Integer> colPositions = rows.
        stream().
        flatMap(m -> m.entrySet().stream()).
        collect(Collectors.toMap(e -> e.getKey(),
                                 e -> e.getValue().size(), Integer::max, TreeMap::new));
int tableWidth = 0;
for(Map.Entry<String,Integer> e: colPositions.entrySet())
    tableWidth += e.setValue(tableWidth);

String[][] array = new String[rows.size()][tableWidth];

int rowIdx = 0;
for(Map<String, List<String>> row: rows) {
    for(Map.Entry<String,List<String>> e: row.entrySet()) {
        int index = colPositions.get(e.getKey());
        for(String s: e.getValue()) array[rowIdx][index++]=s;
    }
    rowIdx++;
}
return array;

A header array can be prepended with the following change:

Map<String, Integer> colPositions = rows.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().size(),
                              Integer::max, TreeMap::new));
String[] header = colPositions.entrySet().stream()
    .flatMap(e -> Collections.nCopies(e.getValue(), e.getKey()).stream())
    .toArray(String[]::new);
int tableWidth = 0;
for(Map.Entry<String,Integer> e: colPositions.entrySet())
    tableWidth += e.setValue(tableWidth);

String[][] array = new String[rows.size()+1][tableWidth];
array[0] = header;

int rowIdx = 1;
for(Map<String, List<String>> row: rows) {
    for(Map.Entry<String,List<String>> e: row.entrySet()) {
        int index = colPositions.get(e.getKey());
        for(String s: e.getValue()) array[rowIdx][index++]=s;
    }
    rowIdx++;
}
return array;


问:
Error `The code you are testing needs to make 1 more call(s)` in testify package
I am using the testify package for the unit testing in golang. My code contains mocking. while running the test it is getting passed for sometimes and showing error The code you are testing needs to make 1 more call(s) for sometimes, I am unable to figure out the reason why is this happening:

I went through this https://github.com/stretchr/testify/issues/31 but did get what is the problem and how it can be solved?

答:
I read about the goroutine scheduling and come to know that if you are writing the test for the go functions(goroutines) then sometimes they may be called (the case when the test will pass and) and sometimes they may not be called.(the case when the test will fail). To recover from this one should use Gosched() in the test file where we are calling the goroutine.
This happens because go uses cooperative scheduling for the scheduling for the goroutines, which is different from preemptive and non-preemptive. If anyone wants to more about it follow this. https://github.com/golang/go/issues/11462</p>


问:
Reading XML Files using Java, return in a SOAP request
I'm fairly new to using SOAP and Blueprint (Which is just like Spring).
Anyway, I'm just trying to learn the basics atm, doing pretty well so far.

I've run into a small problem when using a Java Class to retrieve a specific node value from an XML file. This works when I run the application as a stand-alone but when I am getting the request using Soap, the value "lastName" returns null.

```<code>public static void main(String[] args) throws XPathExpressionException {

    DocumentBuilderFactory builderFactory =
            DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException p) {
        p.printStackTrace();
    }
    try {
    Document document = builder.parse(new FileInputStream("d:\\input11.xml"));
    XPath xP = XPathFactory.newInstance().newXPath();
    String expression ="/people/person/lastName";
    NodeList nodeList = (NodeList) xP.compile(expression).evaluate(document, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        lastName += nodeList.item(i).getFirstChild().getNodeValue() + " ";
    }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException s) {
        s.printStackTrace();
    }

    System.out.println(lastName);
}

public static String returnLastName(String input){
System.out.println(lastName);

return "LastName: "+lastName +"\n";

}

}
</code>```

And here's my blueprint.xml code:

```<code>    <bean id="lastNameBean" class="com.*****.camelBlueprintTest.XMLCamel" />
    <route id="lastName">
<from uri="cxf:bean:returnLName" />
<bean ref="lastNameBean" method="returnLastName" />
    <log message="The message contains ${body}" />
    <to uri="mock:result" />
</route>
</code>```

So it does actually return the last names when I run the Java application, but in the SOAP request I am getting "LastName: null".

答:
AH!! I've found the error. Silly me. So, I was calling the method in my blueprint "returnLastName" and it was returning null, I didn't realize that this method was called ALONE, so moving my code from the main into the method fixed it like a charm haha.

I feel really silly but it's always the little mistakes that get me.

Body:
I'm fairly new to using SOAP and Blueprint (Which is just like Spring).
Anyway, I'm just trying to learn the basics atm, doing pretty well so far.

I've run into a small problem when using a Java Class to retrieve a specific node value from an XML file. This works when I run the application as a stand-alone but when I am getting the request using Soap, the value "lastName" returns null.

public static void main(String[] args) throws XPathExpressionException {

    DocumentBuilderFactory builderFactory =
            DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException p) {
        p.printStackTrace();
    }
    try {
    Document document = builder.parse(new FileInputStream("d:\\input11.xml"));
    XPath xP = XPathFactory.newInstance().newXPath();
    String expression ="/people/person/lastName";
    NodeList nodeList = (NodeList) xP.compile(expression).evaluate(document, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        lastName += nodeList.item(i).getFirstChild().getNodeValue() + " ";
    }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException s) {
        s.printStackTrace();
    }

    System.out.println(lastName);
}

public static String returnLastName(String input){
System.out.println(lastName);

return "LastName: "+lastName +"\n";

}

}

And here's my blueprint.xml code:

    <bean id="lastNameBean" class="com.*****.camelBlueprintTest.XMLCamel" />
    <route id="lastName">
<from uri="cxf:bean:returnLName" />
<bean ref="lastNameBean" method="returnLastName" />
    <log message="The message contains ${body}" />
    <to uri="mock:result" />
</route>

So it does actually return the last names when I run the Java application, but in the SOAP request I am getting "LastName: null".


问:
Apache Ignite.NET LINQ Failure
Using Apache Ignite .NET 2.3.0

Trying to search using Linq extension (Apache.Ignite.Linq).

Here is a IgniteConfig:

```<code>{
    ClientMode = false,
    JvmInitialMemoryMb = 512,
    JvmMaxMemoryMb = 512,
    MetricsLogFrequency = TimeSpan.Zero, // disable metrics output
    DataStorageConfiguration = new Apache.Ignite.Core.Configuration.DataStorageConfiguration()
    {
        DefaultDataRegionConfiguration = new DataRegionConfiguration()
        {
            Name = "DefaultRegion",
            PersistenceEnabled = true
        },
        StoragePath = _config.Value.Ignite.PersistentStoragePath
     },
     CacheConfiguration = new[]
     {
         new CacheConfiguration
         {
             Name = "securitiesItemsCache",
             ReadThrough = false,
             WriteThrough = false,
             CacheMode = CacheMode.Replicated,
             DataRegionName = "DefaultRegion",
             QueryEntities = new []
             {
                  new QueryEntity(typeof(string), typeof(SecuritiesItem))
             }
         }

    }
</code>```

Getting cache:

```<code>_securitiesCache = _ignite.GetOrCreateCache<string, SecuritiesItem>("securitiesItemsCache");
</code>```

Searching like this:

```<code>_securitiesCache
    .AsCacheQueryable()
    .Where(s => s.Value.SearchString.Contains(query))
    .ToArray()
    .Select(x => x.Value);
</code>```

In this case recieve exception:

Apache.Ignite.Core.Common.IgniteException   HResult=0x80131500

  Message=Failed to parse query: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')    Source=Apache.Ignite.Core   StackTrace:    at
  Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.Error(Void*
  target, Int32 errType, SByte* errClsChars, Int32 errClsCharsLen,
  SByte* errMsgChars, Int32 errMsgCharsLen, SByte* stackTraceChars,
  Int32 stackTraceCharsLen, Void* errData, Int32 errDataLen)    at
  Apache.Ignite.Core.Impl.Unmanaged.IgniteJniNativeMethods.TargetInStreamOutObject(Void*
  ctx, Void* target, Int32 opType, Int64 memPtr)    at
  Apache.Ignite.Core.Impl.PlatformJniTarget.InStreamOutObject(Int32
  type, Action1 writeAction)    at
  Apache.Ignite.Core.Impl.Cache.CacheImpl2.QueryFields[T](SqlFieldsQuery
  qry, Func3 readerFunc)    at
  Remotion.Linq.Clauses.StreamedData.StreamedSequenceInfo.ExecuteQueryModel(QueryModel
  queryModel, IQueryExecutor executor)    at
  Apache.Ignite.Linq.Impl.CacheFieldsQueryProvider.Execute[TResult](Expression
  expression)    at Remotion.Linq.QueryableBase1.GetEnumerator()    at
  System.Collections.Generic.LargeArrayBuilder1.AddRange(IEnumerable1
  items)    at
  System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable1
  source)    at System.Linq.Enumerable.ToArray[TSource](IEnumerable1
  source)    at Core.IgniteServer.SearchSecurities(String query) in
  C:\development\ISSDPService\Core\IgniteServer.cs:line 138    at
  WebService.Providers.IgniteProvider.Search(String query,
  LanguagePrefix lang) in
  C:\development\ISSDPService\WebService\Providers\IgniteProvider.cs:line
  78    at WebService.Controllers.SecuritiesController.Search(String
  query) in
  C:\development\ISSDPService\WebService\Controllers\SecuritiesController.cs:line
  47    at
  Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object
  target, Object[] parameters)    at
  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()

Inner Exception 1: JavaException: class
  org.apache.ignite.IgniteCheckedException: Failed to parse query:
  select _T0._KEY, _T0._VAL from "securitiesItemsCache".SECURITIESITEM
  as _T0 where (_T0.SearchString like '%' || ? || '%')      at
  org.apache.ignite.internal.processors.platform.utils.PlatformUtils.unwrapQueryException(PlatformUtils.java:519)
    at
  org.apache.ignite.internal.processors.platform.cache.PlatformCache.runFieldsQuery(PlatformCache.java:1240)
    at
  org.apache.ignite.internal.processors.platform.cache.PlatformCache.processInStreamOutObject(PlatformCache.java:877)
    at
  org.apache.ignite.internal.processors.platform.PlatformTargetProxyImpl.inStreamOutObject(PlatformTargetProxyImpl.java:79)
  Caused by: javax.cache.CacheException: class
  org.apache.ignite.internal.processors.query.IgniteSQLException: Failed
  to parse query: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')     at
  org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:597)
    at
  org.apache.ignite.internal.processors.cache.GatewayProtectedCacheProxy.query(GatewayProtectedCacheProxy.java:368)
    at
  org.apache.ignite.internal.processors.platform.cache.PlatformCache.runFieldsQuery(PlatformCache.java:1234)
    ... 2 more Caused by: class
  org.apache.ignite.internal.processors.query.IgniteSQLException: Failed
  to parse query: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')     at
  org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1385)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1909)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1907)
    at
  org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2445)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:1914)
    at
  org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:585)
    ... 4 more Caused by: org.h2.jdbc.JdbcSQLException: Столбец
  "_T0.SEARCHSTRING" не найден Column "_T0.SEARCHSTRING" not found; SQL
  statement: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')  [42122-195]    at
  org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)     at
  org.h2.message.DbException.get(DbException.java:155)  at
  org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:147)
    at org.h2.expression.CompareLike.optimize(CompareLike.java:93)  at
  org.h2.command.dml.Select.prepare(Select.java:842)    at
  org.h2.command.Parser.prepareCommand(Parser.java:262)     at
  org.h2.engine.Session.prepareLocal(Session.java:573)  at
  org.h2.engine.Session.prepareCommand(Session.java:514)    at
  org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1204)
    at
  org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:73)
    at
  org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:288)
    at
  org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.prepareStatement(IgniteH2Indexing.java:402)
    at
  org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1365)
    ... 10 more

it says:

Column "_T0.SEARCHSTRING" not found; SQL statement:

But is't new QueryEntity(typeof(string), typeof(SecuritiesItem)) enought fo this?

Resolved

Added description for field programmatically:

```<code>Fields = new []
{
    new QueryField { Name = "SearchString", FieldType = typeof(string)}
}
</code>```

Another problem.

It searching great if query consists only of English letters. But if i enter Russian characters, then nothing finds. Should I convert the text into a specific encoding?

答:
Column "_T0.SEARCHSTRING" not found

You should mark SearchString property with [QuerySqlField].

SQL is opt-in, you should explicitly configure which fields should be available in queries. See https://apacheignite-sql.readme.io/docs/net-schema-and-indexes.

Title: Apache Ignite.NET LINQ Failure

Body:
Using Apache Ignite .NET 2.3.0

Trying to search using Linq extension (Apache.Ignite.Linq).

Here is a IgniteConfig:

{
    ClientMode = false,
    JvmInitialMemoryMb = 512,
    JvmMaxMemoryMb = 512,
    MetricsLogFrequency = TimeSpan.Zero, // disable metrics output
    DataStorageConfiguration = new Apache.Ignite.Core.Configuration.DataStorageConfiguration()
    {
        DefaultDataRegionConfiguration = new DataRegionConfiguration()
        {
            Name = "DefaultRegion",
            PersistenceEnabled = true
        },
        StoragePath = _config.Value.Ignite.PersistentStoragePath
     },
     CacheConfiguration = new[]
     {
         new CacheConfiguration
         {
             Name = "securitiesItemsCache",
             ReadThrough = false,
             WriteThrough = false,
             CacheMode = CacheMode.Replicated,
             DataRegionName = "DefaultRegion",
             QueryEntities = new []
             {
                  new QueryEntity(typeof(string), typeof(SecuritiesItem))
             }
         }

    }

Getting cache:

_securitiesCache = _ignite.GetOrCreateCache<string, SecuritiesItem>("securitiesItemsCache");

Searching like this:

_securitiesCache
    .AsCacheQueryable()
    .Where(s => s.Value.SearchString.Contains(query))
    .ToArray()
    .Select(x => x.Value);

In this case recieve exception:

Apache.Ignite.Core.Common.IgniteException   HResult=0x80131500

  Message=Failed to parse query: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')    Source=Apache.Ignite.Core   StackTrace:    at
  Apache.Ignite.Core.Impl.Unmanaged.UnmanagedCallbacks.Error(Void*
  target, Int32 errType, SByte* errClsChars, Int32 errClsCharsLen,
  SByte* errMsgChars, Int32 errMsgCharsLen, SByte* stackTraceChars,
  Int32 stackTraceCharsLen, Void* errData, Int32 errDataLen)    at
  Apache.Ignite.Core.Impl.Unmanaged.IgniteJniNativeMethods.TargetInStreamOutObject(Void*
  ctx, Void* target, Int32 opType, Int64 memPtr)    at
  Apache.Ignite.Core.Impl.PlatformJniTarget.InStreamOutObject(Int32
  type, Action1 writeAction)    at
  Apache.Ignite.Core.Impl.Cache.CacheImpl2.QueryFields[T](SqlFieldsQuery
  qry, Func3 readerFunc)    at
  Remotion.Linq.Clauses.StreamedData.StreamedSequenceInfo.ExecuteQueryModel(QueryModel
  queryModel, IQueryExecutor executor)    at
  Apache.Ignite.Linq.Impl.CacheFieldsQueryProvider.Execute[TResult](Expression
  expression)    at Remotion.Linq.QueryableBase1.GetEnumerator()    at
  System.Collections.Generic.LargeArrayBuilder1.AddRange(IEnumerable1
  items)    at
  System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable1
  source)    at System.Linq.Enumerable.ToArray[TSource](IEnumerable1
  source)    at Core.IgniteServer.SearchSecurities(String query) in
  C:\development\ISSDPService\Core\IgniteServer.cs:line 138    at
  WebService.Providers.IgniteProvider.Search(String query,
  LanguagePrefix lang) in
  C:\development\ISSDPService\WebService\Providers\IgniteProvider.cs:line
  78    at WebService.Controllers.SecuritiesController.Search(String
  query) in
  C:\development\ISSDPService\WebService\Controllers\SecuritiesController.cs:line
  47    at
  Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object
  target, Object[] parameters)    at
  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()

Inner Exception 1: JavaException: class
  org.apache.ignite.IgniteCheckedException: Failed to parse query:
  select _T0._KEY, _T0._VAL from "securitiesItemsCache".SECURITIESITEM
  as _T0 where (_T0.SearchString like '%' || ? || '%')      at
  org.apache.ignite.internal.processors.platform.utils.PlatformUtils.unwrapQueryException(PlatformUtils.java:519)
    at
  org.apache.ignite.internal.processors.platform.cache.PlatformCache.runFieldsQuery(PlatformCache.java:1240)
    at
  org.apache.ignite.internal.processors.platform.cache.PlatformCache.processInStreamOutObject(PlatformCache.java:877)
    at
  org.apache.ignite.internal.processors.platform.PlatformTargetProxyImpl.inStreamOutObject(PlatformTargetProxyImpl.java:79)
  Caused by: javax.cache.CacheException: class
  org.apache.ignite.internal.processors.query.IgniteSQLException: Failed
  to parse query: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')     at
  org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:597)
    at
  org.apache.ignite.internal.processors.cache.GatewayProtectedCacheProxy.query(GatewayProtectedCacheProxy.java:368)
    at
  org.apache.ignite.internal.processors.platform.cache.PlatformCache.runFieldsQuery(PlatformCache.java:1234)
    ... 2 more Caused by: class
  org.apache.ignite.internal.processors.query.IgniteSQLException: Failed
  to parse query: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')     at
  org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1385)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1909)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1907)
    at
  org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2445)
    at
  org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:1914)
    at
  org.apache.ignite.internal.processors.cache.IgniteCacheProxyImpl.query(IgniteCacheProxyImpl.java:585)
    ... 4 more Caused by: org.h2.jdbc.JdbcSQLException: Столбец
  "_T0.SEARCHSTRING" не найден Column "_T0.SEARCHSTRING" not found; SQL
  statement: select _T0._KEY, _T0._VAL from
  "securitiesItemsCache".SECURITIESITEM as _T0 where (_T0.SearchString
  like '%' || ? || '%')  [42122-195]    at
  org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)     at
  org.h2.message.DbException.get(DbException.java:155)  at
  org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:147)
    at org.h2.expression.CompareLike.optimize(CompareLike.java:93)  at
  org.h2.command.dml.Select.prepare(Select.java:842)    at
  org.h2.command.Parser.prepareCommand(Parser.java:262)     at
  org.h2.engine.Session.prepareLocal(Session.java:573)  at
  org.h2.engine.Session.prepareCommand(Session.java:514)    at
  org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1204)
    at
  org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:73)
    at
  org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:288)
    at
  org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.prepareStatement(IgniteH2Indexing.java:402)
    at
  org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1365)
    ... 10 more

it says:

Column "_T0.SEARCHSTRING" not found; SQL statement:

But is't new QueryEntity(typeof(string), typeof(SecuritiesItem)) enought fo this?

Resolved

Added description for field programmatically:

Fields = new []
{
    new QueryField { Name = "SearchString", FieldType = typeof(string)}
}

Another problem.

It searching great if query consists only of English letters. But if i enter Russian characters, then nothing finds. Should I convert the text into a specific encoding?


答:
There is a bug on old version of binutils.

Building with binutils-2.28 resolved those problems.

Relevent gcc bugzilla : https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82172

Title: flto crash with gcc7.2

Body:
I have a crash with getline in the following code file.
I built gcc7.2 because system updates are not available.

Minimal example :

#include <iostream>

int main(int argc, char *argv[])
{
    std::string line;
    while (std::getline(std::cin, line))
    {
    }
    return 0;
}

On the following lines, GCC_INSTALL_DIR represents the directory where my own gcc is installed
Output :

./a.out
a
*** Error in `./a.out': free(): invalid pointer: 0x0000000000602200 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7cfe1)[0x7f392a8f3fe1]
[GCC_INSTALL_DIR]/generated/lib64/libstdc++.so.6(_ZNSs7reserveEm+0x85)[0x7f392b221cd5]
[GCC_INSTALL_DIR]/generated/lib64/libstdc++.so.6(_ZSt7getlineIcSt11char_traitsIcESaIcEERSt13basic_istreamIT_T0_ES7_RSbIS4_S5_T1_ES4_+0x175)[0x7f392b1fa675]
./a.out[0x40120d]
./a.out[0x4010a9]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7f392a898b15]
./a.out[0x400f29]
======= Memory map: ========
00400000-00402000 r-xp 00000000 08:05 3312183238                         [redacted]/a.out
00601000-00602000 r--p 00001000 08:05 3312183238                         [redacted]/a.out
00602000-00603000 rw-p 00002000 08:05 3312183238                         [redacted]/a.out
008a6000-008d8000 rw-p 00000000 00:00 0                                  [heap]
7f3924000000-7f3924021000 rw-p 00000000 00:00 0
7f3924021000-7f3928000000 ---p 00000000 00:00 0
7f392a877000-7f392aa2d000 r-xp 00000000 08:03 201329280                  /usr/lib64/libc-2.17.so
7f392aa2d000-7f392ac2d000 ---p 001b6000 08:03 201329280                  /usr/lib64/libc-2.17.so
7f392ac2d000-7f392ac31000 r--p 001b6000 08:03 201329280                  /usr/lib64/libc-2.17.so
7f392ac31000-7f392ac33000 rw-p 001ba000 08:03 201329280                  /usr/lib64/libc-2.17.so
7f392ac33000-7f392ac38000 rw-p 00000000 00:00 0
7f392ac38000-7f392ac4e000 r-xp 00000000 08:05 93316545                   [GCC_INSTALL_DIR]/generated/lib64/libgcc_s.so.1
7f392ac4e000-7f392ae4d000 ---p 00016000 08:05 93316545                   [GCC_INSTALL_DIR]/generated/lib64/libgcc_s.so.1
7f392ae4d000-7f392ae4e000 r--p 00015000 08:05 93316545                   [GCC_INSTALL_DIR]/generated/lib64/libgcc_s.so.1
7f392ae4e000-7f392ae4f000 rw-p 00016000 08:05 93316545                   [GCC_INSTALL_DIR]/generated/lib64/libgcc_s.so.1
7f392ae4f000-7f392af50000 r-xp 00000000 08:03 201329288                  /usr/lib64/libm-2.17.so
7f392af50000-7f392b14f000 ---p 00101000 08:03 201329288                  /usr/lib64/libm-2.17.so
7f392b14f000-7f392b150000 r--p 00100000 08:03 201329288                  /usr/lib64/libm-2.17.so
7f392b150000-7f392b151000 rw-p 00101000 08:03 201329288                  /usr/lib64/libm-2.17.so
7f392b151000-7f392b2c3000 r-xp 00000000 08:05 93812046                   [GCC_INSTALL_DIR]/generated/lib64/libstdc++.so.6.0.24
7f392b2c3000-7f392b4c2000 ---p 00172000 08:05 93812046                   [GCC_INSTALL_DIR]/generated/lib64/libstdc++.so.6.0.24
7f392b4c2000-7f392b4cc000 r--p 00171000 08:05 93812046                   [GCC_INSTALL_DIR]/generated/lib64/libstdc++.so.6.0.24
7f392b4cc000-7f392b4ce000 rw-p 0017b000 08:05 93812046                   [GCC_INSTALL_DIR]/generated/lib64/libstdc++.so.6.0.24
7f392b4ce000-7f392b4d2000 rw-p 00000000 00:00 0
7f392b4d2000-7f392b4f3000 r-xp 00000000 08:03 201329241                  /usr/lib64/ld-2.17.so
7f392b6d4000-7f392b6d9000 rw-p 00000000 00:00 0
7f392b6f0000-7f392b6f3000 rw-p 00000000 00:00 0
7f392b6f3000-7f392b6f4000 r--p 00021000 08:03 201329241                  /usr/lib64/ld-2.17.so
7f392b6f4000-7f392b6f5000 rw-p 00022000 08:03 201329241                  /usr/lib64/ld-2.17.so
7f392b6f5000-7f392b6f6000 rw-p 00000000 00:00 0
7fff7363e000-7fff7365f000 rw-p 00000000 00:00 0                          [stack]
7fff7374b000-7fff7374d000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Abandon (core dumped)

[GCC_INSTALL_DIR]/generated/bin/g++ -c -g -I[GCC_INSTALL_DIR]/generated/include/c++/7.2.0 -std=c++17 -flto -o main.o main.cpp -D_GLIBCXX_USE_CXX11_ABI=0 && [GCC_INSTALL_DIR]/generated/bin/g++ -flto main.o

Linked library:

ldd ./a.out
        linux-vdso.so.1 =>  (0x00007ffcf9fe6000)
        libstdc++.so.6 => [GCC_INSTALL_DIR]/generated/lib64/libstdc++.so.6 (0x00007f04a565e000)
        libm.so.6 => /lib64/libm.so.6 (0x00007f04a5342000)
        libgcc_s.so.1 => [GCC_INSTALL_DIR]/generated/lib64/libgcc_s.so.1 (0x00007f04a512b000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f04a4d6a000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f04a59e00

libc version:

ldd --version
    ldd (GNU libc) 2.1700)

Configure option for gcc7.2

$OLD_PWD/gcc-7.2.0/configure --prefix=$OLD_PWD/generated --disable-multilib

Compile command line:

[GCC_INSTALL_DIR]/generated/bin/g++ -c -g -I[GCC_INSTALL_DIR]/generated/include/c++/7.2.0 -std=c++17 -flto -o main.o main.cpp -D_GLIBCXX_USE_CXX11_ABI=0 && [GCC_INSTALL_DIR]/generated/bin/g++ -flto main.o

Valgrind output:

==28919== Memcheck, a memory error detector
==28919== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==28919== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==28919== Command: ./a.out
==28919==
a
==28919== Invalid free() / delete / delete[] / realloc()
==28919==    at 0x4C2B131: operator delete(void*) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==28919==    by 0x4F05CD4: _M_dispose (basic_string.h:3155)
==28919==    by 0x4F05CD4: std::string::reserve(unsigned long) (basic_string.tcc:961)
==28919==    by 0x4EDE674: push_back (basic_string.h:4109)
==28919==    by 0x4EDE674: operator+= (basic_string.h:3966)
==28919==    by 0x4EDE674: std::basic_istream<char, std::char_traits<char> >& std::getline<char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, char) (istream-string.cc:168)
==28919==    by 0x40120C: std::basic_istream<char, std::char_traits<char> >& std::getline<char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&) (in /home/elie/dev/a.out)
==28919==    by 0x4010A8: main (in /home/elie/dev/a.out)
==28919==  Address 0x602200 is 0 bytes inside data symbol "_ZNSs4_Rep20_S_empty_rep_storageE"
==28919==
a
a
==28919==
==28919== HEAP SUMMARY:
==28919==     in use at exit: 72,704 bytes in 1 blocks
==28919==   total heap usage: 2 allocs, 2 frees, 72,730 bytes allocated
==28919==
==28919== LEAK SUMMARY:
==28919==    definitely lost: 0 bytes in 0 blocks
==28919==    indirectly lost: 0 bytes in 0 blocks
==28919==      possibly lost: 0 bytes in 0 blocks
==28919==    still reachable: 72,704 bytes in 1 blocks
==28919==         suppressed: 0 bytes in 0 blocks
==28919== Rerun with --leak-check=full to see details of leaked memory
==28919==
==28919== For counts of detected and suppressed errors, rerun with: -v
==28919== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 1 from 1)

We have to use _GLIBCXX_USE_CXX11_ABI=0 because we interact with an old library.

Removing flto, _GLIBCXX_USE_CXX11_ABI=0 or changing -std=c++17 for -std=c++14 resolves the crash.

Is it a bug with gcc-7.2 or did I miss something ? Should I file a bug-report to gcc ?

I would prefer to avoid the workaround of disabling flto or c++17

Edit :
bug present in gcc7.2 : https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82172


问:
Javascript event listener remove
How can I remove the eventlistener when a page navigates to another page in a single page app?

I'm facing this issue when revisiting that page, not when eventlistener is called

```<code>if (window.addEventListener) {
  window.addEventListener("message", listenMessage, false);
  // console.log("false");
} else {
  window.attachEvent("onmessage", listenMessage);
  //console.log("true");
}
var listenMessage = function(msg) {
/**/
}
</code>```

答:
Use removeEventListener to remove event listeners.

```<code>window.removeEventListener("message", listenMessage, false);
</code>```

And detachEvent in case attachEvent is getting executed

Title: Javascript event listener remove

Body:
How can I remove the eventlistener when a page navigates to another page in a single page app?

I'm facing this issue when revisiting that page, not when eventlistener is called

if (window.addEventListener) {
  window.addEventListener("message", listenMessage, false);
  // console.log("false");
} else {
  window.attachEvent("onmessage", listenMessage);
  //console.log("true");
}
var listenMessage = function(msg) {
/**/
}

Body:
Use removeEventListener to remove event listeners.

window.removeEventListener("message", listenMessage, false);

And detachEvent in case attachEvent is getting executed


问:
Swift 4: How to asynchronously use URLSessionDataTask but have the requests be in a timed queue?
Basically I have some JSON data that I wish to retrieve from a bunch of URL's (all from the same host), however I can only request this data roughly every 2 seconds at minimum and only one at a time or I'll be "time banned" from the server. As you'll see below; while URLSession is very quick it also gets me time banned almost instantly when I have around 700 urls to get through.

How would I go about creating a queue in URLSession (if its functionality supports it) and while having it work asynchronously to my main thread; have it work serially on its own thread and only attempt each item in the queue after 2 seconds have past since it finished the previous request?

```<code>for url in urls {
    get(url: url)
}

func get(url: URL) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            DispatchQueue.main.async {
                print(error.localizedDescription)
            }
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            DispatchQueue.main.async {
                print("Server Error")
            }
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {
                        DispatchQueue.main.async {
                            self.itemsCount.append(count)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}
</code>```

答:
Make DispatchQueue to run your code on threads. You don't need to do this work on Main Thread. So,

```<code>// make serial queue
let queue = DispatchQueue(label: "getData")

// for delay
func wait(seconds: Double, completion: @escaping () -> Void) {
    queue.asyncAfter(deadline: .now() + seconds) { completion() }
}

// usage
for url in urls {
  wait(seconds: 2.0) {
      self.get(url: url) { (itemCount) in
         // update UI related to itemCount
      }
  }
}
</code>```

By the way, Your get(url: url) function is not that great.

```<code>func get(url: URL, completionHandler: @escaping ([Int]) -> Void) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            print(error.localizedDescription)
            /* Don't need to use main thread
                DispatchQueue.main.async {
                    print(error.localizedDescription)
                }
            */
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            print("Server Error")
            /* Don't need to use main thread
                DispatchQueue.main.async {
                    print("Server Error")
                }
            */
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {

                        self.itemsCount.append(count)

                        // append all data that you need and pass it to completion closure
                        DispatchQueue.main.async {
                            completionHandler(self.itemsCount)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}
</code>```

I would recommend you to learn concept of GCD(for thread) and escaping closure(for completion handler).

GCD: https://www.raywenderlich.com/148513/grand-central-dispatch-tutorial-swift-3-part-1

Escaping Closure: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID546

Body:
Basically I have some JSON data that I wish to retrieve from a bunch of URL's (all from the same host), however I can only request this data roughly every 2 seconds at minimum and only one at a time or I'll be "time banned" from the server. As you'll see below; while URLSession is very quick it also gets me time banned almost instantly when I have around 700 urls to get through.

How would I go about creating a queue in URLSession (if its functionality supports it) and while having it work asynchronously to my main thread; have it work serially on its own thread and only attempt each item in the queue after 2 seconds have past since it finished the previous request?

for url in urls {
    get(url: url)
}

func get(url: URL) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            DispatchQueue.main.async {
                print(error.localizedDescription)
            }
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            DispatchQueue.main.async {
                print("Server Error")
            }
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {
                        DispatchQueue.main.async {
                            self.itemsCount.append(count)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}

Body:
Make DispatchQueue to run your code on threads. You don't need to do this work on Main Thread. So,

// make serial queue
let queue = DispatchQueue(label: "getData")

// for delay
func wait(seconds: Double, completion: @escaping () -> Void) {
    queue.asyncAfter(deadline: .now() + seconds) { completion() }
}

// usage
for url in urls {
  wait(seconds: 2.0) {
      self.get(url: url) { (itemCount) in
         // update UI related to itemCount
      }
  }
}

By the way, Your get(url: url) function is not that great.

func get(url: URL, completionHandler: @escaping ([Int]) -> Void) {
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: { (data, response, error) in

        if let error = error {
            print(error.localizedDescription)
            /* Don't need to use main thread
                DispatchQueue.main.async {
                    print(error.localizedDescription)
                }
            */
            return
        }
        let data = data!

        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            print("Server Error")
            /* Don't need to use main thread
                DispatchQueue.main.async {
                    print("Server Error")
                }
            */
            return
        }
        if response.mimeType == "application/json" {
            do {
                let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
                if json["success"] as! Bool == true {
                    if let count = json["total_count"] as? Int {

                        self.itemsCount.append(count)

                        // append all data that you need and pass it to completion closure
                        DispatchQueue.main.async {
                            completionHandler(self.itemsCount)
                        }
                    }
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    })
    task.resume()
}

I would recommend you to learn concept of GCD(for thread) and escaping closure(for completion handler).

GCD: https://www.raywenderlich.com/148513/grand-central-dispatch-tutorial-swift-3-part-1

Escaping Closure: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID546


Title: Pandas Time grouping columns

Body:
I have a df as below:

Index                                Receiver     Length         Retry
1970-01-01 00:00:00.000000000         R1          10             0
1970-01-01 00:00:00.800000000         R1          10             1
1970-01-01 00:00:01.000287000         R2          10             0
1970-01-01 00:00:01.600896000         R2          10             0
1970-01-01 00:00:02.001388000         R1          10             1
1970-01-01 00:00:02.004698000         R1          10             1
1970-01-01 00:00:02.006706000         R2          10             0
1970-01-01 00:00:02.501351000         R2          10             0
1970-01-01 00:00:02.810382000         R1          10             0
1970-01-01 00:00:03.001981000         R1          10             1
1970-01-01 00:00:03.377116000         R1          10             1
1970-01-01 00:00:03.701811000         R2          10             1
1970-01-01 00:00:03.910326000         R2          10             0
1970-01-01 00:00:03.951355000         R2          10             1

I need to group the df by time (1S), and then in each group, add the Length column values if Retry==1 for each R1 and R2.

I used below code, but it seems it ignore rows when there is no Retry=1 for R1 and R2 (i.e. condition is not met).

df2 = df.query("Retry == 1").groupby([pd.Grouper(freq='1S'), 'Receiver']).Length.sum().unstack().fillna(0)

Desired Output is:

Index                        R1    R2
1970-01-01 00:00:00          10    0
1970-01-01 00:00:01          0     0
1970-01-01 00:00:02          20    0
1970-01-01 00:00:03          20    20

Similar problem can be found here.

Body:
You need reindex for add missing datetimes:

df2 = df2.reindex(pd.date_range(df2.index[0], df2.index[-1], freq='1S'), fill_value=0)
print (df2)
Receiver               R1    R2
1970-01-01 00:00:00  10.0   0.0
1970-01-01 00:00:01   0.0   0.0
1970-01-01 00:00:02  20.0   0.0
1970-01-01 00:00:03  20.0  20.0


问:
How To Integrate USB Token Code Signing Certificate With Build Server (Windows Server 2012 R2 Virtual Machine running on Hyper-V)
We want to sign all of our build artifacts - dlls, exe files, setup packages etc.

This was working fine with post-build scripts for the last two years. But since February 2017 all CAs have introduced some hardware options (USB Token or HSMs.

So the idea is somehow to attach the USB token to our Hyper-V but as far as I know USB port is not available to the Guest OS out of the box.

So, what is your experience with this?

答:
Some of the same problems are adressed in this stackoverflow question: Automate Extended Validation (EV) code signing

Perhaps the problem can be solved using Remote signing (one on the answers to the above post) https://stackoverflow.com/a/35369264/34857

I have just read that some Certificates, can be exported, and the problem can be solved by that. As I read it, this is how node.js does it (https://github.com/nodejs/build/issues/874)


问:
Official C++ language and base class library documentations?
I'm newbie on C++. And I have multiple years of C# background.
In C#, official language standard and basic class library documentations can be found on MSDN.
What's the equivalent for C++?

And what's the most basic library of C++? There are many libraries. Boost, STL, ATL, and etc... What's the most basic and I should start from?

答: For a good treatment of the standard library you might want to read Stroustrup's The C++ Programming Language. Also, note that the STL is actually part of the standard library, or well, partly really.</p>


答:
```<code>window.removeEventListener("onmessage", listenMessage);
window.detachEvent("onmessage", listenerMessage); // For IE
</code>```

For more information, read the docs:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/detachEvent

Title: Javascript event listener remove

Body:
window.removeEventListener("onmessage", listenMessage);
window.detachEvent("onmessage", listenerMessage); // For IE

For more information, read the docs:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/detachEvent


问:
I am trying to implement a rating system But I am not not able to pass the values of rating in Vue js?
I gone through the documentation and I tried the following code. I am able to get the data for enquiryDesc but getting null values for rating. I tried several steps and getting null values.

My html form is

```<code><form id="enquiryBox" method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
  <div class="modal-body brbottom-20">
    <div class="clearfix">
      <div class="col-lg-6">
        <div class="form-group required">
          <fieldset class="rating">
            <input v-model="rating" type="radio" id="rating" name="rating" v-bind:value="5" ><label v-bind:value="5" class = "full" for="star5" title="Awesome"></label>
               <input v-model="rating" type="radio" id="rating" name="rating" v-bind:value="4" ><label v-bind:value="4" class="half" for="star4half" title="Pretty good"></label>
               </fieldset>
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group required">
          <label>Enquiry</label>
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="">
    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>
  </div>
</form>
</code>```

My vue js script is as

```<code>enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       $.ajax({
         url: 'https://api/post/add_review/',
         data: data,
         type: "POST",
         dataType: 'json',
         success: function(e) {
           if (e.status) {
             alert("Success")

           } else {
             vm.response = e;

             alert(" Failed")
           }
         }
       });
       return false;
     }
   },
 });
</code>```

My response for console.log(data)

{rating: '', enquiryDesc: "cghjl,./"}

I have used v-model and v-bind:value and now to I am not the values. I am really stuck on these. Is something not initialized? Please help me to have a solution.I have gone through several tutorials and everything says to do in the same way.

答:
You cant use the value attribute in inputs. For Vue is source of truth the v-model value. Just set the default v-model value and particular input will be check automatically.

new Vue({
  el: '#app',
  data () {
    return {
      rating: 3
    }
  },
  methods: {
    send (e) {
      e.preventDefault()
      console.log(this.rating)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <form action="" method="post" @submit="send">
    <fieldset>
      <input type="radio" name="rating" value="5" v-model="rating">
      <input type="radio" name="rating" value="4" v-model="rating">
      <input type="radio" name="rating" value="3" v-model="rating">
      <input type="radio" name="rating" value="2" v-model="rating">
      <input type="radio" name="rating" value="1" v-model="rating">
    </fieldset>
    <button type="submit">Send</button>
  </form>
</div>

<script src="https://unpkg.com/vue@2.5.9/dist/vue.min.js"></script></code>```

Try these changes in your code - in HTML:

```<code><fieldset class="rating">
  <label class="full" for="star5" title="Awesome">5</label>
  <input v-model="rating" type="radio" id="star5" name="rating" value="5">
  <label class="half" for="star4half" title="Pretty good">4</label>
  <input v-model="rating" type="radio" id="star4half" name="rating" value="4">
</fieldset>
</code>```

And in JS:

```<code>enquiryBox = new Vue({
  el: "#enquiryBox",
  data: {
    rating: 5,
    enquiryDesc: '',
  },
  methods: {
    handelSubmit: function (e) {
      const vm = this
      const data = {}

      data['rating'] = this.rating
      data['enquiryDesc'] = this.enquiryDesc

      $.ajax({
        url: 'https://api/post/add_review/',
        data: data,
        type: "POST",
        dataType: 'json',
        success: function (e) {
          if (e.status) {
            alert('Success')
          } else {
            vm.response = e
            alert('Failed')
          }
        }
      })

      return false
    }
  }
})
</code>```

Change the first line also and try it agin:

```<code><form id="enquiryBox" method="post" data-parsley-validate="true" @submit="handelSubmit">
</code>```

Body:
I gone through the documentation and I tried the following code. I am able to get the data for enquiryDesc but getting null values for rating. I tried several steps and getting null values.

My html form is

<form id="enquiryBox" method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">

          <fieldset class="rating">
            <input v-model="rating" type="radio" id="rating" name="rating" v-bind:value="5" >
               <input v-model="rating" type="radio" id="rating" name="rating" v-bind:value="4" >
               </fieldset>

          Enquiry
          <textarea placeholder="Write your enquiry here" rows="7" id="enquiryDesc" name="enquiryDesc" class="form-control required" title="Desc" v-model="enquiryDesc" required="required"></textarea>

    <button id="btn-submit-enquiry" class="btn whiteButton" type="submit">Post Enquiry</button>

</form>

My vue js script is as

enquiryBox = new Vue({
   el: "#enquiryBox",
   data: {
     rating: '',
     enquiryDesc: '',
   },
   methods: {
     handelSubmit: function(e) {
       var vm = this;
       data = {};
       data['rating'] = this.rating;
       data['enquiryDesc'] = this.enquiryDesc;
       console.log(data);

       $.ajax({
         url: 'https://api/post/add_review/',
         data: data,
         type: "POST",
         dataType: 'json',
         success: function(e) {
           if (e.status) {
             alert("Success")

           } else {
             vm.response = e;

             alert(" Failed")
           }
         }
       });
       return false;
     }
   },
 });

My response for console.log(data)

{rating: '', enquiryDesc: "cghjl,./"}

I have used v-model and v-bind:value and now to I am not the values. I am really stuck on these. Is something not initialized? Please help me to have a solution.I have gone through several tutorials and everything says to do in the same way.

Body:
You cant use the value attribute in inputs. For Vue is source of truth the v-model value. Just set the default v-model value and particular input will be check automatically.

new Vue({
  el: '#app',
  data () {
    return {
      rating: 3
    }
  },
  methods: {
    send (e) {
      e.preventDefault()
      console.log(this.rating)
    }
  }
})

<div id="app">
  <form action="" method="post" @submit="send">
    <fieldset>
      <input type="radio" name="rating" value="5" v-model="rating">
      <input type="radio" name="rating" value="4" v-model="rating">
      <input type="radio" name="rating" value="3" v-model="rating">
      <input type="radio" name="rating" value="2" v-model="rating">
      <input type="radio" name="rating" value="1" v-model="rating">
    </fieldset>
    <button type="submit">Send</button>
  </form>
</div>

<script src="https://unpkg.com/vue@2.5.9/dist/vue.min.js"></script>

Try these changes in your code - in HTML:

<fieldset class="rating">
  <label class="full" for="star5" title="Awesome">5</label>
  <input v-model="rating" type="radio" id="star5" name="rating" value="5">
  <label class="half" for="star4half" title="Pretty good">4</label>
  <input v-model="rating" type="radio" id="star4half" name="rating" value="4">
</fieldset>

And in JS:

enquiryBox = new Vue({
  el: "#enquiryBox",
  data: {
    rating: 5,
    enquiryDesc: '',
  },
  methods: {
    handelSubmit: function (e) {
      const vm = this
      const data = {}

      data['rating'] = this.rating
      data['enquiryDesc'] = this.enquiryDesc

      $.ajax({
        url: 'https://api/post/add_review/',
        data: data,
        type: "POST",
        dataType: 'json',
        success: function (e) {
          if (e.status) {
            alert('Success')
          } else {
            vm.response = e
            alert('Failed')
          }
        }
      })

      return false
    }
  }
})

Change the first line also and try it agin:

<form id="enquiryBox" method="post" data-parsley-validate="true" @submit="handelSubmit">


问:
I have not got vendor folder after installation of composer?
I tried twice but I am not getting any directory or any vendor folder inside my composer installation.
Although composer is installed successfully. When I am typing composer in CMD Prompt it is displaying a long list.
When I wrote composer -d in CMD "Invalid working directory specified, does not exist.
I want composer for my PHP localhost Xampp
During Installation I selected php.exe file under php folder of Xampp. Installation was smooth
I am currently on 8.1 Windows 64 bit
Kindly Help me this this issue.</p>

答:
To use Composer on your project you need to run it inside your project folder. You can either use composer require as Muhammed M. suggested or write a composer.json file, but all that inside your project folder, not on composer's folder.

If you have a composer.json file, you will run

```<code>composer install
</code>```

and this will tell composer to install your dependencies. This command will generate your vendor folder with the dependencies inside.

When you run composer commands it will use the XAMP's PHP as you told it to do so during instalation.

Body:
To use Composer on your project you need to run it inside your project folder. You can either use composer require as Muhammed M. suggested or write a composer.json file, but all that inside your project folder, not on composer's folder.

If you have a composer.json file, you will run

composer install

and this will tell composer to install your dependencies. This command will generate your vendor folder with the dependencies inside.

When you run composer commands it will use the XAMP's PHP as you told it to do so during instalation.