问:
Trying to change the content of a page without reloading after passing a value to a variable on submit
Retrieving data from an API using Php. This my code:

```<code><?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>
</code>```

Html code:

```<code> <div id="get_text" >
<div><em>CHECK YOUR POINTS</em></div>
<div ><em>Enter mobile number</em></div>
<form action='' method='POST' id='search-form'>
<div>
<input type='search' name='search' id="sub1" />
</div>
<div>
<button type="submit"  id="sub" >Submit</button>
</div>
</form>
</div>

<div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>
</code>```

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

```<code> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript">
     $(document).ready(function () {
    $("#show_text").hide();
    $("#sub").on("click", function (e) {
        e.preventDefault();
        $.ajax({
            url: 'aristocracy-test.php',
            method: 'POST',
            data : $("#get_text").serialize(), //pass your form elements as key-value pairs
            success: function (response) {
                $("#show_text").show();
                $("#get_text").hide();
            }
        });
    });
});
 </script>
</code>```

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.

答:
You are not getting in your div with id show_text because you did not insert the new data in it :

You need to call $("#show_text").html(response); in order to set new data something like:

```<code>    success: function (response) {
        $("#show_text").show();
        $("#show_text").html(response);
        $("#get_text").hide();
    }
});
</code>```

Also it will remove anything in that div so :

```<code><div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>
</code>```

becomes :

```<code><div id="show_text" >
    //HERE WILL BE YOUR NEW DATA WHICH CAME FROM AJAX
</div>
</code>```

UPDATE

You are not sending proper data in your ajax params:

```<code>data : $("#get_text").serialize(),
</code>```

This wont do.

change it to :

```<code>data:{
search : $('#sub1').val()
}
</code>```

Body:
Retrieving data from an API using Php. This my code:

<?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>

Html code:

CHECK YOUR POINTS

Enter mobile number

<form action='' method='POST' id='search-form'>

<input type='search' name='search' id="sub1" />

<button type="submit"  id="sub" >Submit</button>

</form>

YOUR CURRENT POINTS ARE

<form action='' method='GET' id='result'>

<input type='text' name='points' value="<?php echo $inner; ?>"/>

</form>

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.

Body:
You are not getting in your div with id show_text because you did not insert the new data in it :

You need to call $("#show_text").html(response); in order to set new data something like:

    success: function (response) {
        $("#show_text").show();
        $("#show_text").html(response);
        $("#get_text").hide();
    }
});

Also it will remove anything in that div so :

<div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>

becomes :

<div id="show_text" >
    //HERE WILL BE YOUR NEW DATA WHICH CAME FROM AJAX
</div>

UPDATE

You are not sending proper data in your ajax params:

data : $("#get_text").serialize(),

This wont do.

change it to :

data:{
search : $('#sub1').val()
}


来源: stackexchange

问:
Google Map is stop showing After upgrade gradle version

Bellow is my Manifests file meta data

```<code> <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="HERE IS MY API KEY" />
</code>```

Here is MY Gradle file

```<code> compileSdkVersion 24
buildToolsVersion "24.0.0"

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile project(':DatePicker')
compile project(':agendacalendarview')
compile files('libs/acra-4.5.0.jar')
compile project(':MaterialCalenderView')
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.sothree.slidinguppanel:library:3.3.0'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.sothree.slidinguppanel:library:3.3.0'
compile 'com.android.support:design:24.2.1'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.hbb20:ccp:1.4'
compile 'com.github.scottyab:showhidepasswordedittext:0.8'
compile 'com.vistrav:ask:2.4'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.android.volley:volley:1.0.0'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpmime:4.2.3'

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okio:okio:1.7.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.7'
compile 'org.apmem.tools:layouts:1.10@aar'
compile 'com.google.firebase:firebase-messaging:10.0.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.mani:ThinDownloadManager:1.2.4'
compile 'com.jakewharton:butterknife:7.0.0'
compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.github.lzyzsd:circleprogress:1.1.0@aar'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.tbuonomo:slidingpuzzleloading:1.0.1'
testCompile 'junit:junit:4.12'
</code>```

}

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

Here is my Project Gradle

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'me.tatarka:gradle-retrolambda:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
</code>```

I have tried to upgrade all latest code from MAP API

But It's not working now. Also i am used android studio version 2.3

Here is my App Code for only MAP

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

```<code>private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
</code>```

}

XML for MAP view

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.squincy.inhup.Activity.MapsActivity" />
</code>```

答: Hi @pmrajnai13 your google map api key is missing in your AndroidManifest.xml file.Add that google map api key.</p>

ContentLicense: CC BY-SA 3.0

Body:
Bellow is my Manifests file meta data

 <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="HERE IS MY API KEY" />

Here is MY Gradle file

 compileSdkVersion 24
buildToolsVersion "24.0.0"

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile project(':DatePicker')
compile project(':agendacalendarview')
compile files('libs/acra-4.5.0.jar')
compile project(':MaterialCalenderView')
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.sothree.slidinguppanel:library:3.3.0'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.sothree.slidinguppanel:library:3.3.0'
compile 'com.android.support:design:24.2.1'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.hbb20:ccp:1.4'
compile 'com.github.scottyab:showhidepasswordedittext:0.8'
compile 'com.vistrav:ask:2.4'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.android.volley:volley:1.0.0'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpmime:4.2.3'

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okio:okio:1.7.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.7'
compile 'org.apmem.tools:layouts:1.10@aar'
compile 'com.google.firebase:firebase-messaging:10.0.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.mani:ThinDownloadManager:1.2.4'
compile 'com.jakewharton:butterknife:7.0.0'
compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.github.lzyzsd:circleprogress:1.1.0@aar'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.tbuonomo:slidingpuzzleloading:1.0.1'
testCompile 'junit:junit:4.12'

}

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

Here is my Project Gradle

dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'me.tatarka:gradle-retrolambda:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

I have tried to upgrade all latest code from MAP API

But It's not working now. Also i am used android studio version 2.3

Here is my App Code for only MAP

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

}

XML for MAP view

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.squincy.inhup.Activity.MapsActivity" />


问:
Who sent you?
I have a series of input forms, all of them take a different form action. Each of those validates input. If ok, they go to different success pages. If fail, I want the form action/validation pages to set $_SESSION['error_messages'] and go to a common page which displays the errors and has a "resubmit" button.

Question ... how to get error form the resubmit button back to one of many possible input forms?

Edit: I don't see how $_SERVER['HTTP_REFERER'] is going to work. Again: form --> validation --> error_page

So, I guess that validation has to set  a session variable from $_SERVER['HTTP_REFERER']

答:
I'm assuming that you're using the same script, if not please post your code:

Input page:

```<code><?php
/* this is the form page header */

/* parsing & filtering input */

if( my_form_is_valid($input_data) )
   give_the_answer();
else
   header('Location:' . $_POST['request_uri'] . '&status=error');  //make sure that's the first output

/* follow the DOM */
?>

<form id="myform">
   <!-- some fields -->
   <input type="hidden" name="request_uri" id="request_uri" value=<?=$_SERVER['REQUEST_URI']; ?>" />
</form>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Who sent you?

Body:
I'm assuming that you're using the same script, if not please post your code:

Input page:

<?php
/* this is the form page header */

/* parsing & filtering input */

if( my_form_is_valid($input_data) )
   give_the_answer();
else
   header('Location:' . $_POST['request_uri'] . '&status=error');  //make sure that's the first output

/* follow the DOM */
?>

<form id="myform">
   <!-- some fields -->
   <input type="hidden" name="request_uri" id="request_uri" value=<?=$_SERVER['REQUEST_URI']; ?>" />
</form>


问:
Check if files exists
I need to check if files mentioned in a text file exists or not and if they do not exist, then I need to place a dummy file at that location.

I used this which gives me the missing files, can somebody help me how to create these files?

```<code>Import-Csv .\Book3.csv | ForEach {
    If (Test-Path -Path $_.File) {
        Write-Output "$($_.File) exists"
    } Else {
        Write-Output "$($_.File) does NOT exist"
        $_.File | Out-File .\missingFiles.txt -Append
    }
}
</code>```

答:
This will create a blank file when it does not exist</p>

```<code>Import-Csv .\Book3.csv | ForEach {
    If (Test-Path -Path $_.File) {
        Write-Output "$($_.File) exists"
    } Else {
        Write-Output "$($_.File) does NOT exist"
        $_.File | Out-File .\missingFiles.txt -Append
        New-Item -Path $_.File -ItemType "file"
    }
}
</code>```

Title: Check if files exists

Body:
I need to check if files mentioned in a text file exists or not and if they do not exist, then I need to place a dummy file at that location.

I used this which gives me the missing files, can somebody help me how to create these files?

Import-Csv .\Book3.csv | ForEach {
    If (Test-Path -Path $_.File) {
        Write-Output "$($_.File) exists"
    } Else {
        Write-Output "$($_.File) does NOT exist"
        $_.File | Out-File .\missingFiles.txt -Append
    }
}

Body:
This will create a blank file when it does not exist

Import-Csv .\Book3.csv | ForEach {
    If (Test-Path -Path $_.File) {
        Write-Output "$($_.File) exists"
    } Else {
        Write-Output "$($_.File) does NOT exist"
        $_.File | Out-File .\missingFiles.txt -Append
        New-Item -Path $_.File -ItemType "file"
    }
}


问:
Loading OpenCV library in Linux?
So I built a vision library on windows, and I've ran it on Windows and it ran okay. I used the command:

```<code>java -jar LiftTracker.jar
</code>```

I transferred the .jar file I built on windows over to a Raspberry Pi, and did a make install to install the opencv libraries. Once I did that, I tried to do the same command as above and came up with the error:

```<code>java.lang.UnsatisfiedLinkError: no opencv_java310 in java.library.path.
</code>```

I did some research and found that I could run this command along side the -jar command

```<code>java -Djava.library.path=/path/to/dir
</code>```

That still did not work. Is it the way that I am importing the system library? The way I'm importing it in the code is by:

```<code>static{

    System.loadLibrary("opencv_java310");

}
</code>```

I think the main reason that it's not working is because of the way I installed opencv. Any ideas?

Thanks!

答:
You need to add "libopencv_java320.so" to your java project libs. It is around 1mb additional library.

You can generate this .so file from sources as per documentation: https://opencv-java-tutorials.readthedocs.io/en/latest/01-installing-opencv-for-java.html#install-opencv-3-x-under-linux

another way is to build sources manually using terminal cmake (it will download around 4gb of opencv sources), should be easy: download the source from opencv: http://opencv.org/releases.html Unzip it and inside unpacked directory create a /build directory like this ../opencv-3.2.0/build/. Make sure you have cmake installed (Debian/Ubuntu apt get install cmake). Open terminal in previously created /build folder and type: cmake -DBUILD_SHARED_LIBS=OFF .. after operation finishes type make -j8 and after that "libopencv_java_320" should be generated for 3.2.0 version - copy this .so into your java project. Last type make install from the same build directory to install 3.2.0 libs on the system (you might want to previously remove older version if necessary). More info here: https://elbauldelprogramador.com/en/compile-opencv-3.2-with-java-intellij-idea/

same as above approach but automated will be by using this script: https://github.com/milq/milq/blob/master/scripts/bash/install-opencv.sh Script does also install opencv on the linux system. Took it from this source: http://milq.github.io/install-opencv-ubuntu-debian/ It does much more then 2nd approach, should be easiest to make.

After installing opencv libs in system and copying libopencv_java320.so into your java project you can remove sources (it is almost 4gb after all).

Then you can use below code in your main method to load windows .dll (if you previously added it too) and linux .so:

```<code>String libName = "";
if (SystemUtils.IS_OS_WINDOWS) {
    libName = "opencv_java320.dll";
} else if (SystemUtils.IS_OS_LINUX) {
    libName = "libopencv_java320.so";
}
System.load(new File("./libs/".concat(libName)).getAbsolutePath());
</code>```

Title: Loading OpenCV library in Linux?

Body:
So I built a vision library on windows, and I've ran it on Windows and it ran okay. I used the command:

java -jar LiftTracker.jar

I transferred the .jar file I built on windows over to a Raspberry Pi, and did a make install to install the opencv libraries. Once I did that, I tried to do the same command as above and came up with the error:

java.lang.UnsatisfiedLinkError: no opencv_java310 in java.library.path.

I did some research and found that I could run this command along side the -jar command

java -Djava.library.path=/path/to/dir

That still did not work. Is it the way that I am importing the system library? The way I'm importing it in the code is by:

static{

    System.loadLibrary("opencv_java310");

}

I think the main reason that it's not working is because of the way I installed opencv. Any ideas?

Thanks!

Body:
You need to add "libopencv_java320.so" to your java project libs. It is around 1mb additional library.

You can generate this .so file from sources as per documentation: https://opencv-java-tutorials.readthedocs.io/en/latest/01-installing-opencv-for-java.html#install-opencv-3-x-under-linux

another way is to build sources manually using terminal cmake (it will download around 4gb of opencv sources), should be easy: download the source from opencv: http://opencv.org/releases.html Unzip it and inside unpacked directory create a /build directory like this ../opencv-3.2.0/build/. Make sure you have cmake installed (Debian/Ubuntu apt get install cmake). Open terminal in previously created /build folder and type: cmake -DBUILD_SHARED_LIBS=OFF .. after operation finishes type make -j8 and after that "libopencv_java_320" should be generated for 3.2.0 version - copy this .so into your java project. Last type make install from the same build directory to install 3.2.0 libs on the system (you might want to previously remove older version if necessary). More info here: https://elbauldelprogramador.com/en/compile-opencv-3.2-with-java-intellij-idea/

same as above approach but automated will be by using this script: https://github.com/milq/milq/blob/master/scripts/bash/install-opencv.sh Script does also install opencv on the linux system. Took it from this source: http://milq.github.io/install-opencv-ubuntu-debian/ It does much more then 2nd approach, should be easiest to make.

After installing opencv libs in system and copying libopencv_java320.so into your java project you can remove sources (it is almost 4gb after all).

Then you can use below code in your main method to load windows .dll (if you previously added it too) and linux .so:

String libName = "";
if (SystemUtils.IS_OS_WINDOWS) {
    libName = "opencv_java320.dll";
} else if (SystemUtils.IS_OS_LINUX) {
    libName = "libopencv_java320.so";
}
System.load(new File("./libs/".concat(libName)).getAbsolutePath());


问:
Google Chrome Plugin: How to detect URL of selected tab
I am trying to attempt my first Google Chrome Extension and have a question.  My end goal is to be able to select a button which will perform the following:

Grab the current URL of the selected tab (Ex: www.google.com)

Open a new tab using the URL from step 1 and appending a query string to the end (Ex: www.google.com?filter=0)

Currently, I was able to figure out how to open a create a new tab which loads a specified URL.  What I am unsure of how to detect the URL from the selected tab and load that value in the new tab.  Suggestions?  Thanks in advance!!

Code below:

[popup.html]

```<code>    <html>
<head>

<style>

body {
  min-width:175px;
  overflow-x:hidden;
}

</style>

<script>

 function createTab() {
  chrome.tabs.create({'url': 'http://www.google.com'});
 }

 function show_alert()
 {
 alert("I am an alert box!");
 }

</script>
</head>

<body>

<input type="button" onclick="createTab()" value="Create New Tab" />
<hr/>
<input type="button" onclick="show_alert()" value="Show alert box" />

</body>
</html>
</code>```

[manifest.json]

```<code>{
  "name": "IGX Plugin",
  "version": "1.0",
  "description": "IGX Plugin",

  "browser_action": {
    "default_icon": "favicon.ico",
 "popup": "popup.html"
  },
  "permissions": [
    "tabs"
  ]

}
</code>```

答:
chrome.tabs.getSelected has been deprecated. so we should use tabs.query({active: true}... instead:

```<code>chrome.tabs.query({active: true}, tabs => alert(tabs[0].url));
</code>```

Body:
I am trying to attempt my first Google Chrome Extension and have a question.  My end goal is to be able to select a button which will perform the following:

Grab the current URL of the selected tab (Ex: www.google.com)

Open a new tab using the URL from step 1 and appending a query string to the end (Ex: www.google.com?filter=0)

Currently, I was able to figure out how to open a create a new tab which loads a specified URL.  What I am unsure of how to detect the URL from the selected tab and load that value in the new tab.  Suggestions?  Thanks in advance!!

Code below:

[popup.html]

<input type="button" onclick="createTab()" value="Create New Tab" />

<input type="button" onclick="show_alert()" value="Show alert box" />

[manifest.json]

{
  "name": "IGX Plugin",
  "version": "1.0",
  "description": "IGX Plugin",

  "browser_action": {
    "default_icon": "favicon.ico",
 "popup": "popup.html"
  },
  "permissions": [
    "tabs"
  ]

}

Body:
chrome.tabs.getSelected has been deprecated. so we should use tabs.query({active: true}... instead:

chrome.tabs.query({active: true}, tabs => alert(tabs[0].url));


问:
ko.computed do not fire function upon instantiating
Hi is there a way to not fire the function when instantiating a ko.computed

example is

i have this ko.computed

```<code>ko.computed(function(){ alert(this.Test); } , this);
</code>```

so basically if i instantiated this computed this will fire the function defined there
is there a way not to fire it upon instantiation? and only fire it when dependency change?

答:
You need to set the deferEvaluation option:

deferEvaluation — Optional. If this option is true, then the value of the computed observable will not be evaluated until something actually attempts to access its value or manually subscribes to it. By default, a computed observable has its value determined immediately during creation.

```<code>ko.computed(function(){ alert(this.Test); } , this, { deferEvaluation: true });
</code>```

Body:
Hi is there a way to not fire the function when instantiating a ko.computed

example is

i have this ko.computed

ko.computed(function(){ alert(this.Test); } , this);

so basically if i instantiated this computed this will fire the function defined there
is there a way not to fire it upon instantiation? and only fire it when dependency change?

Body:
You need to set the deferEvaluation option:

deferEvaluation — Optional. If this option is true, then the value of the computed observable will not be evaluated until something actually attempts to access its value or manually subscribes to it. By default, a computed observable has its value determined immediately during creation.

ko.computed(function(){ alert(this.Test); } , this, { deferEvaluation: true });


问:
Access variables returned from function in django view with name of variable
I have a view in django that has a filter that uses two dates. I want to calculate the dates in a separate function to tidy it up a bit and return them to the view.

```<code>def index(request):
    function = month()
    objectcount = Entry.objects.filter(entrydate__range=(function[0], function[1])).count() #bleurgh!
    context = {
        "objectcount": objectcount,
    }
    return render(request, 'entry/index.html', context)

def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)

    return first_of_month, last_of_month
</code>```

This works fine, but I have to access the variables using function[0] and function[1].

How can I pass these variables so they are accessed from the index view using names - like first_of_month and last_of_month?

答:
Maybe you write like this

```<code>def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)
    resp_data ={"first_of_month":first_of_month,"last_of_month":last_of_month}
    return resp_data
</code>```

function["first_of_month"]
function["last_of_month"]

Body:
I have a view in django that has a filter that uses two dates. I want to calculate the dates in a separate function to tidy it up a bit and return them to the view.

def index(request):
    function = month()
    objectcount = Entry.objects.filter(entrydate__range=(function[0], function[1])).count() #bleurgh!
    context = {
        "objectcount": objectcount,
    }
    return render(request, 'entry/index.html', context)

def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)

    return first_of_month, last_of_month

This works fine, but I have to access the variables using function[0] and function[1].

How can I pass these variables so they are accessed from the index view using names - like first_of_month and last_of_month?

Body:
Maybe you write like this

def month():
    today = datetime.datetime.now().date()
    first_of_month = "{}-{}-01".format(today.year, today.month)
    last = calendar.monthrange(today.year, today.month)[1]
    last_of_month = "{}-{}-{}".format(today.year, today.month, last)
    resp_data ={"first_of_month":first_of_month,"last_of_month":last_of_month}
    return resp_data

function["first_of_month"]
function["last_of_month"]


问:
How to flatten a nested JSON data structure into an object with key value pairs
The strings that are coming from source is coming in fragmented JSON object in JSON object.I want to convert this JSON structure to flat JSON structure

```<code>{
    "nest": {
        "a": {
            "b": {
                "h": {
                    "i": {
                        "all.css": "1",
                        "j": {
                            "k": {
                                "l": {
                                    "lr.png": "2",
                                    "c.png": "3"
                                },
                                ".png": "4"
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

I tried to do it but I could only get up to 1 key value pair,
what i want is {"abhiall.css":"1","abhijkllr.png":"2","abhijklc.png":"3" ..and so on.
Thanks

答:
For array of objects I did the following
Note : make sure the Objects Array passed in is n>0 at least </p>

```<code>flatten(objects, target, path) {
let me = this;
let retArray = [];
for(let x=0; x < objects.length; x++) {

  let object = objects[x];
  path = path || '';
  target={};

  target = me.flattenHelper(object, target, path);

  retArray.push(target);
}
return retArray;}
</code>```

<p>..</p>

```<code>flattenHelper(object, target, path){
let me = this;
Object.keys(object).forEach(function (key) {
  console.log("key : "+ key + " : object : " +  (object[key] && typeof object[key] === 'object') + " path : " + path);
  if (object[key] && typeof object[key] === 'object') {
      me.flattenHelper(object[key], target, path + key);
  }
  target[path + key] = object[key];
  console.log(target);
});
return target;}
</code>```

Body:
The strings that are coming from source is coming in fragmented JSON object in JSON object.I want to convert this JSON structure to flat JSON structure

{
    "nest": {
        "a": {
            "b": {
                "h": {
                    "i": {
                        "all.css": "1",
                        "j": {
                            "k": {
                                "l": {
                                    "lr.png": "2",
                                    "c.png": "3"
                                },
                                ".png": "4"
                            }
                        }
                    }
                }
            }
        }
    }
}

I tried to do it but I could only get up to 1 key value pair,
what i want is {"abhiall.css":"1","abhijkllr.png":"2","abhijklc.png":"3" ..and so on.
Thanks

Body:
For array of objects I did the following
Note : make sure the Objects Array passed in is n>0 at least

flatten(objects, target, path) {
let me = this;
let retArray = [];
for(let x=0; x < objects.length; x++) {

  let object = objects[x];
  path = path || '';
  target={};

  target = me.flattenHelper(object, target, path);

  retArray.push(target);
}
return retArray;}

..

flattenHelper(object, target, path){
let me = this;
Object.keys(object).forEach(function (key) {
  console.log("key : "+ key + " : object : " +  (object[key] && typeof object[key] === 'object') + " path : " + path);
  if (object[key] && typeof object[key] === 'object') {
      me.flattenHelper(object[key], target, path + key);
  }
  target[path + key] = object[key];
  console.log(target);
});
return target;}


问:
Azure web api Unauthorized 401
I have some code that used to call Azure Scheduler to get a token,  then using that token, make restful calls.  Works a treat.

So i decided to adopt the code into a new app but this time call my own web api hosted on azure. The API is registered in Active directory I have created a secret key etc.  When i initiliaze my static httpclient it fetches a token succesfully.

But when i make a call to the API using the token for auth, the response is a 401 "unauthorized",  below is the code.

```<code> public static class SchedulerHttpClient
{
    const string SPNPayload = "resource={0}&client_id={1}&grant_type=client_credentials&client_secret={2}";

    private static Lazy<Task<HttpClient>> _Client = new Lazy<Task<HttpClient>>(async () =>
    {
        string baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
        var client = new HttpClient();
        client.BaseAddress = new Uri(baseAddress);
        await MainAsync(client).ConfigureAwait(false);
        return client;
    });

    public static Task<HttpClient> ClientTask => _Client.Value;

    private static async Task MainAsync(HttpClient client)
    {
        string tenantId = ConfigurationManager.AppSettings["AzureTenantId"];
        string clientId = ConfigurationManager.AppSettings["AzureClientId"];
        string clientSecret = ConfigurationManager.AppSettings["AzureClientSecret"];

        string token = await AcquireTokenBySPN(client, tenantId, clientId, clientSecret).ConfigureAwait(false);

        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); //TODO ssmith: const or localization
    }

    private static async Task<string> AcquireTokenBySPN(HttpClient client, string tenantId, string clientId, string clientSecret)
    {
        var payload = String.Format(SPNPayload,
                                    WebUtility.UrlEncode(ConfigurationManager.AppSettings["ARMResource"]),
                                    WebUtility.UrlEncode(clientId),
                                    WebUtility.UrlEncode(clientSecret));

        var body = await HttpPost(client, tenantId, payload).ConfigureAwait(false);
        return body.access_token;
    }

    private static async Task<dynamic> HttpPost(HttpClient client, string tenantId, string payload)
    {
        var address = String.Format(ConfigurationManager.AppSettings["TokenEndpoint"], tenantId);
        var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
        using (var response = await client.PostAsync(address, content).ConfigureAwait(false))
        {
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine("Status:  {0}", response.StatusCode);
                Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync().ConfigureAwait(false));
            }//TODO: start removing tests

            response.EnsureSuccessStatusCode();

            return await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
        }
    }
}
</code>```

The above code is the class that creates a httpclient and gets its authorization.

```<code>public virtual async Task<T> GetAsync(string apiURL)
    {
        try
        {
            _client = await SchedulerHttpClient.ClientTask;
            var response = await _client.GetAsync(apiURL);
            response.EnsureSuccessStatusCode();
            var responseContent = await response.Content.ReadAsAsync<T>().ConfigureAwait(false);

            return responseContent;
        }
        catch (Exception e)
        {
            return default(T);
        }
    }
</code>```

The above code is a quick lift of my old code simply to test if i can get any results. but as stated it returns a 401.

My question is, is my old code to get authorization incorrect?

```<code><add key="ARMResource" value="https://management.core.windows.net/" />
<add key="TokenEndpoint" value="https://login.windows.net/{0}/oauth2/token" />
<add key="BaseAddress" value="https://mysite.azurewebsites.net" />
</code>```

答:
As suspected, This particular issue was cause by the incorrect "ARMresource" in the case of a web api it required me to change it to the client id.

Source of answer

Seems my issue was the same, however i suspect i may be able to omit the resource entirely from my SPNPayload string.

Title: Azure web api Unauthorized 401

Body:
I have some code that used to call Azure Scheduler to get a token,  then using that token, make restful calls.  Works a treat.

So i decided to adopt the code into a new app but this time call my own web api hosted on azure. The API is registered in Active directory I have created a secret key etc.  When i initiliaze my static httpclient it fetches a token succesfully.

But when i make a call to the API using the token for auth, the response is a 401 "unauthorized",  below is the code.

 public static class SchedulerHttpClient
{
    const string SPNPayload = "resource={0}&client_id={1}&grant_type=client_credentials&client_secret={2}";

    private static Lazy<Task<HttpClient>> _Client = new Lazy<Task<HttpClient>>(async () =>
    {
        string baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
        var client = new HttpClient();
        client.BaseAddress = new Uri(baseAddress);
        await MainAsync(client).ConfigureAwait(false);
        return client;
    });

    public static Task<HttpClient> ClientTask => _Client.Value;

    private static async Task MainAsync(HttpClient client)
    {
        string tenantId = ConfigurationManager.AppSettings["AzureTenantId"];
        string clientId = ConfigurationManager.AppSettings["AzureClientId"];
        string clientSecret = ConfigurationManager.AppSettings["AzureClientSecret"];

        string token = await AcquireTokenBySPN(client, tenantId, clientId, clientSecret).ConfigureAwait(false);

        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); //TODO ssmith: const or localization
    }

    private static async Task<string> AcquireTokenBySPN(HttpClient client, string tenantId, string clientId, string clientSecret)
    {
        var payload = String.Format(SPNPayload,
                                    WebUtility.UrlEncode(ConfigurationManager.AppSettings["ARMResource"]),
                                    WebUtility.UrlEncode(clientId),
                                    WebUtility.UrlEncode(clientSecret));

        var body = await HttpPost(client, tenantId, payload).ConfigureAwait(false);
        return body.access_token;
    }

    private static async Task<dynamic> HttpPost(HttpClient client, string tenantId, string payload)
    {
        var address = String.Format(ConfigurationManager.AppSettings["TokenEndpoint"], tenantId);
        var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
        using (var response = await client.PostAsync(address, content).ConfigureAwait(false))
        {
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine("Status:  {0}", response.StatusCode);
                Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync().ConfigureAwait(false));
            }//TODO: start removing tests

            response.EnsureSuccessStatusCode();

            return await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
        }
    }
}

The above code is the class that creates a httpclient and gets its authorization.

public virtual async Task<T> GetAsync(string apiURL)
    {
        try
        {
            _client = await SchedulerHttpClient.ClientTask;
            var response = await _client.GetAsync(apiURL);
            response.EnsureSuccessStatusCode();
            var responseContent = await response.Content.ReadAsAsync<T>().ConfigureAwait(false);

            return responseContent;
        }
        catch (Exception e)
        {
            return default(T);
        }
    }

The above code is a quick lift of my old code simply to test if i can get any results. but as stated it returns a 401.

My question is, is my old code to get authorization incorrect?

<add key="ARMResource" value="https://management.core.windows.net/" />
<add key="TokenEndpoint" value="https://login.windows.net/{0}/oauth2/token" />
<add key="BaseAddress" value="https://mysite.azurewebsites.net" />


问:
Bind WebAPI properties without action parameter
A lot of our Web API action patterns have the following pattern:

```<code>public IHttpActionResult GetDetails(Guid customerGuid)
{
    Customer customer = customerRetriever.FromGuid(customerGuid);

    if (customer == null)
        return NotFound();

    // Do Stuff....
}
</code>```

I want to move all the customer lookup boiler plate out of the action method. I created an action filter attribute to do this, by looking at the value of the action argument and setting a request property:

```<code>KeyValuePair<String, Object> argument = actionContext.ActionArguments.Single(kvp => kvp.Key.Equals(ParameterName));
Guid customerGuid = (Guid)argument.Value;
// Do customer lookup, return 404 if needed
// Add customer to request properties
</code>```

This works, but i still need to include the now redundant Guid in my action signature. If i remove this, my approach for finding the Guid value fails. Is there a way to bind a value from the URI, without having that value as an action parameter?

答:
You have to pass customerGuid as queryString parameter like http://localhost:61374/api/values?customerGuid=D09584F2-0B81-4855-8F33-567F4EF8096C
 Then you can fetch query string value in action filter as:

```<code>  public class CustomFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var queryStringValues = actionContext.Request.GetQueryNameValuePairs();
        var customerGuid = queryStringValues.FirstOrDefault(x => x.Key == "customerGuid").Value;
        //Your logic
    }
}
</code>```

Now there is no need to specify params in API method

```<code>public IHttpActionResult GetDetails()
{
  //Do stuff
}
</code>```

Body:
A lot of our Web API action patterns have the following pattern:

public IHttpActionResult GetDetails(Guid customerGuid)
{
    Customer customer = customerRetriever.FromGuid(customerGuid);

    if (customer == null)
        return NotFound();

    // Do Stuff....
}

I want to move all the customer lookup boiler plate out of the action method. I created an action filter attribute to do this, by looking at the value of the action argument and setting a request property:

KeyValuePair<String, Object> argument = actionContext.ActionArguments.Single(kvp => kvp.Key.Equals(ParameterName));
Guid customerGuid = (Guid)argument.Value;
// Do customer lookup, return 404 if needed
// Add customer to request properties

This works, but i still need to include the now redundant Guid in my action signature. If i remove this, my approach for finding the Guid value fails. Is there a way to bind a value from the URI, without having that value as an action parameter?

Body:
You have to pass customerGuid as queryString parameter like http://localhost:61374/api/values?customerGuid=D09584F2-0B81-4855-8F33-567F4EF8096C
 Then you can fetch query string value in action filter as:

  public class CustomFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var queryStringValues = actionContext.Request.GetQueryNameValuePairs();
        var customerGuid = queryStringValues.FirstOrDefault(x => x.Key == "customerGuid").Value;
        //Your logic
    }
}

Now there is no need to specify params in API method

public IHttpActionResult GetDetails()
{
  //Do stuff
}


问:
Is there ever a situation where server-side includes are a better choice than PHP?
I'm asking in regards to otherwise-static webpages which include files like headers, footers, etc. Obviously building a dynamic site with SSI would be better done with PHP.

Is there ever any reason to do

```<code><!--#include virtual="../quote.txt" -->
</code>```

instead of

```<code><?php include("../quote.txt"); ?>
</code>```

(or the equivalent in another language)?

I'm asking because I've been given the task of updating a website which is currently using SSI for including the same header on different pages.

答: There are some circumstances where SSI can really be helpfull e.g. when an application caches rendered pages and you need to clear the cache but don't want to clear all pages cause of a simple menu change. Then you could just replace the menu or several menus by an ssi include and just clear the menu files on a change an leave the cached pages intact.</p>

Body:
I'm asking in regards to otherwise-static webpages which include files like headers, footers, etc. Obviously building a dynamic site with SSI would be better done with PHP.

Is there ever any reason to do

instead of

<?php include("../quote.txt"); ?>

(or the equivalent in another language)?

I'm asking because I've been given the task of updating a website which is currently using SSI for including the same header on different pages.


问:
Error on import of mp4 file with Jest
In my react-native project, I use react-native-video to play mp4 files. Everything works fine, except that I get an error when I run my unit tests with Jest.

It raises this error when I import the mp4 file: SyntaxError: Unexpected token ILLEGAL. I suppose that there is a special character in the file and that the JavaScript interpreter doesn't like it.

I want to make sure that my video player works. Is there a way to test the player without having this error on the import?

答:
I would suggest to mock this file, in your jest settings (docs)

```<code>{
  "jest": {
    "moduleNameMapper": {
      "\\.mp4$": "<rootDir>/__mocks__/fileMock.js",
    }
  }
}
</code>```

__mocks__/fileMock.js:

```<code>module.exports = 'test-file-stub';
</code>```

Title: Error on import of mp4 file with Jest

Body:
I would suggest to mock this file, in your jest settings (docs)

{
  "jest": {
    "moduleNameMapper": {
      "\\.mp4$": "<rootDir>/__mocks__/fileMock.js",
    }
  }
}

__mocks__/fileMock.js:

module.exports = 'test-file-stub';


问:
How to create schema using model interfaces with type script mongoose
In my project using technologies are Nodejs,Mongoose, Express,Type script

I want to create below-mentioned JSON format collection in Mongodb

```<code>{
  "emp_id": "001",
  "login_id": "venue@abc.com",
  "password": "venue123",
  "role_id": 6,
  "role_name": "TechLead",
  "emp_ext": 456;
  "leave_details": {
   "leave_transactions": [
      {
        "leave_from_date": "14-10-2016",
        "leave_from_part": "noon",
        "leave_to_date": "16-10-2016",
        "leave_to_part": "full",
        "total_no_of_days": 2.5,
        "leave_approved_by_id": "87",
        "leave_approved_date": "14-10-2016",
        "leave_applied_on": "13-10-2016",
        "leave_status": "approved",
        "leave_type": "EL",
        "leave_desc": "going to hometown"
      },
      {
        "leave_from_date": "18-11-2016",
        "leave_from_part": "full",
        "leave_to_date": "19-11-2016",
        "leave_to_part": "full",
        "total_no_of_days": 2,
        "leave_approved_by_id": "115",
        "leave_approved_date": "17-11-2016",
        "leave_applied_on": "17-11-2016",
        "leave_status": "approved",
        "leave_type": "CL",
        "leave_desc": "not feeling well",
        "rejected_reason":""
      }
      ]
  }
}
</code>```

To create above structure created below model interfaces and classes

```<code>import mongoose = require("mongoose");
import IJoiningDetailsModel = require('./JoiningDetailsModel');
import ILeaveDetailsModel = require('./LeaveDetailsModel');

interface EmployeeMasterModel extends mongoose.Document {
    emp_id: number;
    login_id: string;
    name: string;
    password: string;
    role_id: number;
    role_name: string;
    emp_ext: number;
    leave_details: ILeaveDetailsModel;
}

export = EmployeeMasterModel;

import IEmployeeMasterModel = require('./interfaces/EmployeeMasterModel');
import JoiningDetailsModel = require('./JoiningDetailsModel');
import IJoiningDetailsModel = require('./interfaces/JoiningDetailsModel');
import ILeaveDetailsModel = require('./interfaces/LeaveDetailsModel');

class EmployeeMasterModel {

    private employeeModel: IEmployeeMasterModel;

    constructor(employeeModel: IEmployeeMasterModel) {
        this.employeeModel = employeeModel;
    }
    get name (): string {
        return this.employeeModel.name;
    }

    get email (): string {
        return this.employeeModel.login_id;
    }

    get password (): string {
        return this.employeeModel.password;
    }

     get leave_details (): ILeaveDetailsModel {
        return this.employeeModel.leave_details;
    }

}
Object.seal(EmployeeMasterModel);
export =  EmployeeMasterModel;

import mongoose = require("mongoose");

import mongoose = require("mongoose");
import ILeaveTransactionModel = require('./LeaveTransactionModel');
interface LeaveDetailsModel extends mongoose.Document {

    leaveTransactionModel: ILeaveTransactionModel;
}

export = LeaveDetailsModel;

import ILeaveDetailsModel = require('./interfaces/LeaveDetailsModel');
import ILeaveTransactionModel = require('./interfaces/LeaveTransactionModel');

class LeaveDetailsModel {

    private leaveDetailsModel: ILeaveDetailsModel;

    constructor(leaveDetailsModel: ILeaveDetailsModel) {
        this.leaveDetailsModel = leaveDetailsModel;
    }
      get leaveTransactionModel (): ILeaveTransactionModel {
        return this.leaveDetailsModel.leaveTransactionModel;
    }

}
Object.seal(LeaveDetailsModel);
export =  LeaveDetailsModel;

import mongoose = require("mongoose");

interface LeaveTransactionModel extends mongoose.Document {
    leave_from_date:Date;
    leave_from_part : string;
    leave_to_date : Date;
    leave_to_part :string;
    total_no_of_days :number;
    leave_type :string;
    leave_desc:string;
    rejected_reason:string;
    leave_approved_by_id:number;
    leave_approved_date:Date;
    leave_applied_on:Date;
    leave_status:string;
}

export = LeaveTransactionModel;

import ILeaveTransactionModel = require('./interfaces/LeaveTransactionModel');

class LeaveTransactionModel {

    private leaveTransactionModel: ILeaveTransactionModel;

    constructor(leaveTransactionModel: ILeaveTransactionModel) {
        this.leaveTransactionModel = leaveTransactionModel;
    }
    get leave_from_date (): Date {
        return this.leaveTransactionModel.leave_from_date;
    }

    set leave_from_date(leave_from_date : Date){
      this.leaveTransactionModel.leave_from_date = leave_from_date;
    }
    get leave_from_part (): string {
        return this.leaveTransactionModel.leave_from_part;
    }

    get leave_to_date (): Date {
        return this.leaveTransactionModel.leave_to_date;
    }

    get leave_to_part (): string {
        return this.leaveTransactionModel.leave_to_part;
    }

    get total_no_of_days () : number{
        return this.leaveTransactionModel.total_no_of_days;
    }
    get leave_type (): string {
        return this.leaveTransactionModel.leave_type;
    }
      get leave_desc (): string {
        return this.leaveTransactionModel.leave_desc;
    }
  get rejected_reason (): string {
        return this.leaveTransactionModel.rejected_reason;
    }

  get leave_status (): string {
        return this.leaveTransactionModel.leave_status;
    }

     get leave_approved_by_id () : number{
        return this.leaveTransactionModel.leave_approved_by_id;
    }
     get leave_approved_date (): Date {
        return this.leaveTransactionModel.leave_approved_date;
    }
    get leave_applied_on (): Date {
        return this.leaveTransactionModel.leave_applied_on;
    }

}
Object.seal(LeaveTransactionModel);
export =  LeaveTransactionModel;
</code>```

Schema class

```<code>import DataAccess = require('../DataAccess');
import IEmployeeMasterModel = require("./../../model/interfaces/EmployeeMasterModel");

var mongoose = DataAccess.mongooseInstance;
var mongooseConnection = DataAccess.mongooseConnection;

class EmployeeMasterSchema {

    static get schema () {
    // Employee leave transactions(request/approve/cancel) schema declaration
        var LeaveTransactionsSchema = mongoose.Schema({
            leave_from_date: {
                type: Date,
                required: false
            },
            leave_from_part: {
                type: String
            },
            leave_to_date: {
                type: Date,
                required: false
            },
            leave_to_part: {
                type: String
            },
            total_no_of_days: {
                type: String,
                required: false
            },
            leave_type: {
                type: String,
                required: false
            },
            leave_desc: {
                type: String,
                required: false
            },
            rejected_reason: {
                type: String
            },
            leave_approved_by_id: {
                type: Number,
                required: false
            },
            leave_approved_date: {
                type: Date
            },
            leave_applied_on: {
                type:Date,
                required: false
            },
            leave_status: {
                type: String,
                required: false
            }
        });

        // Employee leave details schema declaration
        var LeaveDetailsSchema = mongoose.Schema({
            leave_transactions: {
                type: [ LeaveTransactionsSchema ]
            }
        });

        // Employee master schema declaration
        var schema =  mongoose.Schema({
            emp_id : {
                type: Number,
                required: false
            },
            login_id: {
                type: String,
                required: false
            },
            password: {
                type: String,
                required: false
            },
            role_id: {
                type: Number
            },
            role_name: {
                type: String
            },
            emp_ext: {
                type: Number
            },
                        leave_details: {
                type: [ LeaveDetailsSchema ]
            }
        });

        return schema;
    }
}

var schema = mongooseConnection.model<IEmployeeMasterModel>("employee", EmployeeMasterSchema.schema);
export = schema;
</code>```

when i get request below method gets called ,for testing purpose setting data to ILeaveTransactionModel but when i try to set the ILeaveTransactionModel  to  not working ...   How to set ILeaveTransactionModel  into ILeaveDetailsModel.thanks in advance

```<code>import express = require("express");
import LeaveTraBusiness = require("./../app/business/LeaveTraBusiness");
import IBaseController = require("./BaseController");
import LeaveTransactionModel = require("./../app/model/LeaveTransactionModel");
import ILeaveDetailsModel = require("./../app/model/interfaces/LeaveDetailsModel");
import ILeaveTransactionModel = require("./../app/model/interfaces/LeaveTransactionModel");

// tslint:disable-next-line:one-line
export class LeaveTraController implements IBaseController<LeaveTraBusiness>{
  leaveTra :any;
create(req: express.Request, res: express.Response): void {

 try {
            console.log(req.body.leave_desc);
          this.leaveTra = <ILeaveTransactionModel>{
                leave_from_date:new Date(),
                leave_from_part : "Full",
                leave_to_date : new Date(),
                leave_to_part :"half",
                 total_no_of_days :5,
                leave_type :"SL",
                leave_desc:"No comme",
                rejected_reason:"No comme",
                leave_approved_by_id:121,
                leave_approved_date:new Date(),
                leave_applied_on:new Date(),
                leave_status:"Active"
           };

            console.log(JSON.stringify(this.leaveTra));
            let leaveTraBusiness = new LeaveTraBusiness();
          //Here i want to set leaveTra to ILeaveDetailsModel
            let leaveDetailsModel : <ILeaveDetailsModel>{leaveTra};
            leaveTraBusiness.create(leaveDetailsModel, (error, result) => {
                if (error)
                   res.send({"error": "error"});
                else
                   res.send(result);
            });
        }
        catch (e)  {
            console.log(e);
            res.send({"error": "error in your request"});

        }
    }

}
</code>```

答:
Sorry, I did mistake in setting "leaveTra" to  , below code solved my problem

let leaveDetailsModel = {
                leaveTransactionModel: leaveTra
            };

Body:
In my project using technologies are Nodejs,Mongoose, Express,Type script

I want to create below-mentioned JSON format collection in Mongodb

{
  "emp_id": "001",
  "login_id": "venue@abc.com",
  "password": "venue123",
  "role_id": 6,
  "role_name": "TechLead",
  "emp_ext": 456;
  "leave_details": {
   "leave_transactions": [
      {
        "leave_from_date": "14-10-2016",
        "leave_from_part": "noon",
        "leave_to_date": "16-10-2016",
        "leave_to_part": "full",
        "total_no_of_days": 2.5,
        "leave_approved_by_id": "87",
        "leave_approved_date": "14-10-2016",
        "leave_applied_on": "13-10-2016",
        "leave_status": "approved",
        "leave_type": "EL",
        "leave_desc": "going to hometown"
      },
      {
        "leave_from_date": "18-11-2016",
        "leave_from_part": "full",
        "leave_to_date": "19-11-2016",
        "leave_to_part": "full",
        "total_no_of_days": 2,
        "leave_approved_by_id": "115",
        "leave_approved_date": "17-11-2016",
        "leave_applied_on": "17-11-2016",
        "leave_status": "approved",
        "leave_type": "CL",
        "leave_desc": "not feeling well",
        "rejected_reason":""
      }
      ]
  }
}

To create above structure created below model interfaces and classes

import mongoose = require("mongoose");
import IJoiningDetailsModel = require('./JoiningDetailsModel');
import ILeaveDetailsModel = require('./LeaveDetailsModel');

interface EmployeeMasterModel extends mongoose.Document {
    emp_id: number;
    login_id: string;
    name: string;
    password: string;
    role_id: number;
    role_name: string;
    emp_ext: number;
    leave_details: ILeaveDetailsModel;
}

export = EmployeeMasterModel;

import IEmployeeMasterModel = require('./interfaces/EmployeeMasterModel');
import JoiningDetailsModel = require('./JoiningDetailsModel');
import IJoiningDetailsModel = require('./interfaces/JoiningDetailsModel');
import ILeaveDetailsModel = require('./interfaces/LeaveDetailsModel');

class EmployeeMasterModel {

    private employeeModel: IEmployeeMasterModel;

    constructor(employeeModel: IEmployeeMasterModel) {
        this.employeeModel = employeeModel;
    }
    get name (): string {
        return this.employeeModel.name;
    }

    get email (): string {
        return this.employeeModel.login_id;
    }

    get password (): string {
        return this.employeeModel.password;
    }

     get leave_details (): ILeaveDetailsModel {
        return this.employeeModel.leave_details;
    }

}
Object.seal(EmployeeMasterModel);
export =  EmployeeMasterModel;

import mongoose = require("mongoose");

import mongoose = require("mongoose");
import ILeaveTransactionModel = require('./LeaveTransactionModel');
interface LeaveDetailsModel extends mongoose.Document {

    leaveTransactionModel: ILeaveTransactionModel;
}

export = LeaveDetailsModel;

import ILeaveDetailsModel = require('./interfaces/LeaveDetailsModel');
import ILeaveTransactionModel = require('./interfaces/LeaveTransactionModel');

class LeaveDetailsModel {

    private leaveDetailsModel: ILeaveDetailsModel;

    constructor(leaveDetailsModel: ILeaveDetailsModel) {
        this.leaveDetailsModel = leaveDetailsModel;
    }
      get leaveTransactionModel (): ILeaveTransactionModel {
        return this.leaveDetailsModel.leaveTransactionModel;
    }

}
Object.seal(LeaveDetailsModel);
export =  LeaveDetailsModel;

import mongoose = require("mongoose");

interface LeaveTransactionModel extends mongoose.Document {
    leave_from_date:Date;
    leave_from_part : string;
    leave_to_date : Date;
    leave_to_part :string;
    total_no_of_days :number;
    leave_type :string;
    leave_desc:string;
    rejected_reason:string;
    leave_approved_by_id:number;
    leave_approved_date:Date;
    leave_applied_on:Date;
    leave_status:string;
}

export = LeaveTransactionModel;

import ILeaveTransactionModel = require('./interfaces/LeaveTransactionModel');

class LeaveTransactionModel {

    private leaveTransactionModel: ILeaveTransactionModel;

    constructor(leaveTransactionModel: ILeaveTransactionModel) {
        this.leaveTransactionModel = leaveTransactionModel;
    }
    get leave_from_date (): Date {
        return this.leaveTransactionModel.leave_from_date;
    }

    set leave_from_date(leave_from_date : Date){
      this.leaveTransactionModel.leave_from_date = leave_from_date;
    }
    get leave_from_part (): string {
        return this.leaveTransactionModel.leave_from_part;
    }

    get leave_to_date (): Date {
        return this.leaveTransactionModel.leave_to_date;
    }

    get leave_to_part (): string {
        return this.leaveTransactionModel.leave_to_part;
    }

    get total_no_of_days () : number{
        return this.leaveTransactionModel.total_no_of_days;
    }
    get leave_type (): string {
        return this.leaveTransactionModel.leave_type;
    }
      get leave_desc (): string {
        return this.leaveTransactionModel.leave_desc;
    }
  get rejected_reason (): string {
        return this.leaveTransactionModel.rejected_reason;
    }

  get leave_status (): string {
        return this.leaveTransactionModel.leave_status;
    }

     get leave_approved_by_id () : number{
        return this.leaveTransactionModel.leave_approved_by_id;
    }
     get leave_approved_date (): Date {
        return this.leaveTransactionModel.leave_approved_date;
    }
    get leave_applied_on (): Date {
        return this.leaveTransactionModel.leave_applied_on;
    }

}
Object.seal(LeaveTransactionModel);
export =  LeaveTransactionModel;

Schema class

import DataAccess = require('../DataAccess');
import IEmployeeMasterModel = require("./../../model/interfaces/EmployeeMasterModel");

var mongoose = DataAccess.mongooseInstance;
var mongooseConnection = DataAccess.mongooseConnection;

class EmployeeMasterSchema {

    static get schema () {
    // Employee leave transactions(request/approve/cancel) schema declaration
        var LeaveTransactionsSchema = mongoose.Schema({
            leave_from_date: {
                type: Date,
                required: false
            },
            leave_from_part: {
                type: String
            },
            leave_to_date: {
                type: Date,
                required: false
            },
            leave_to_part: {
                type: String
            },
            total_no_of_days: {
                type: String,
                required: false
            },
            leave_type: {
                type: String,
                required: false
            },
            leave_desc: {
                type: String,
                required: false
            },
            rejected_reason: {
                type: String
            },
            leave_approved_by_id: {
                type: Number,
                required: false
            },
            leave_approved_date: {
                type: Date
            },
            leave_applied_on: {
                type:Date,
                required: false
            },
            leave_status: {
                type: String,
                required: false
            }
        });

        // Employee leave details schema declaration
        var LeaveDetailsSchema = mongoose.Schema({
            leave_transactions: {
                type: [ LeaveTransactionsSchema ]
            }
        });

        // Employee master schema declaration
        var schema =  mongoose.Schema({
            emp_id : {
                type: Number,
                required: false
            },
            login_id: {
                type: String,
                required: false
            },
            password: {
                type: String,
                required: false
            },
            role_id: {
                type: Number
            },
            role_name: {
                type: String
            },
            emp_ext: {
                type: Number
            },
                        leave_details: {
                type: [ LeaveDetailsSchema ]
            }
        });

        return schema;
    }
}

var schema = mongooseConnection.model<IEmployeeMasterModel>("employee", EmployeeMasterSchema.schema);
export = schema;

when i get request below method gets called ,for testing purpose setting data to ILeaveTransactionModel but when i try to set the ILeaveTransactionModel  to  not working ...   How to set ILeaveTransactionModel  into ILeaveDetailsModel.thanks in advance

import express = require("express");
import LeaveTraBusiness = require("./../app/business/LeaveTraBusiness");
import IBaseController = require("./BaseController");
import LeaveTransactionModel = require("./../app/model/LeaveTransactionModel");
import ILeaveDetailsModel = require("./../app/model/interfaces/LeaveDetailsModel");
import ILeaveTransactionModel = require("./../app/model/interfaces/LeaveTransactionModel");

// tslint:disable-next-line:one-line
export class LeaveTraController implements IBaseController<LeaveTraBusiness>{
  leaveTra :any;
create(req: express.Request, res: express.Response): void {

 try {
            console.log(req.body.leave_desc);
          this.leaveTra = <ILeaveTransactionModel>{
                leave_from_date:new Date(),
                leave_from_part : "Full",
                leave_to_date : new Date(),
                leave_to_part :"half",
                 total_no_of_days :5,
                leave_type :"SL",
                leave_desc:"No comme",
                rejected_reason:"No comme",
                leave_approved_by_id:121,
                leave_approved_date:new Date(),
                leave_applied_on:new Date(),
                leave_status:"Active"
           };

            console.log(JSON.stringify(this.leaveTra));
            let leaveTraBusiness = new LeaveTraBusiness();
          //Here i want to set leaveTra to ILeaveDetailsModel
            let leaveDetailsModel : <ILeaveDetailsModel>{leaveTra};
            leaveTraBusiness.create(leaveDetailsModel, (error, result) => {
                if (error)
                   res.send({"error": "error"});
                else
                   res.send(result);
            });
        }
        catch (e)  {
            console.log(e);
            res.send({"error": "error in your request"});

        }
    }

}


问:
Javascript return statement inside filter function, get uniques. Why code works?
I have a big array of objects where I need to get the unique values for some keys.
I have the code working, but I would like to understand it.

Object

```<code>{
"cor": {
    "id": 89,
    "code": "192"
},
"tamanho": {
    "id": 74,
    "code": "L"
},
"price": "56,34",
"prevPrice": "93,90",
"stock": 0
}
</code>```

And this is the iteration that return only unique values.
What I can't understand is the return statement, how does javasacript reads it?

```<code>var tamanhos = [];
data.grelha.filter(function(el, i, arr) {
  return tamanhos.indexOf(el.tamanho.id) == -1 && tamanhos.push(el.tamanho.id);
});
</code>```

Thanks a lot!

答:
this is a json datas. Json values can use array. I think, you know arrays. So Arrays has multi areas. Like :
[val1]
[val1, val2]
[val1, val2, val3]
[val1, val2, val3, .....]

we can take values as column name. Example for c#:

array[] names = new array["mesut", "joa"]

you have javascript arrays

Body:
I have a big array of objects where I need to get the unique values for some keys.
I have the code working, but I would like to understand it.

Object

{
"cor": {
    "id": 89,
    "code": "192"
},
"tamanho": {
    "id": 74,
    "code": "L"
},
"price": "56,34",
"prevPrice": "93,90",
"stock": 0
}

And this is the iteration that return only unique values.
What I can't understand is the return statement, how does javasacript reads it?

var tamanhos = [];
data.grelha.filter(function(el, i, arr) {
  return tamanhos.indexOf(el.tamanho.id) == -1 && tamanhos.push(el.tamanho.id);
});

Thanks a lot!


问:
SEND JSON ARRAY RETROFIT 2 (ANDROID)
I'm novice and know there are many post for this question but i don't find my answer.

So, I need to upgrade a user and his agenda with retrofit2 and the Request "PATCH". But, i don't know how do that with Retrofit2.

Even with my research ... Nothing work !

Can you help me please ?

Thx for advance :D

Here is what I have to send :

```<code>{
    "gender": "M",
    "trainerName": "Patrick",
    "laterality": "L",
    "email": "xxxx@gmail.com",
    "phoneNumber": "XXXXX",
    "agendaWeekDays": [
        {
            "position": 1,
            "startSeconds": 648000,
            "endSeconds": 72000
        },
        {
            "position": 2,
            "startSeconds": 0,
            "endSeconds": 459
        }
    ]
}
</code>```

The response is Just :

```<code>{
  "success"
}
</code>```

my REQUEST

```<code>public interface Minterface {
@FormUrlEncoded
@PATCH("api/members/current")
Call<String> test(
        @Field("access_token") String access_token,
        @Field("agendaWeekDays") ArrayList<Agenda> agendaWeekDays);
}
</code>```

Agenda.class :

```<code>public class Agenda
{

    @SerializedName("position")
    @Expose
    private Integer position;
    @SerializedName("startSeconds")
    @Expose
    private Integer startSeconds;
    @SerializedName("endSeconds")
    @Expose
    private Integer endSeconds;

    public Integer getPosition() {
        return position;
    }

    public void setPosition(Integer position) {
        this.position = position;
    }

    public Integer getStartSeconds() {
        return startSeconds;
    }

    public void setStartSeconds(Integer startSeconds) {
        this.startSeconds = startSeconds;
    }

    public Integer getEndSeconds() {
        return endSeconds;
    }

    public void setEndSeconds(Integer endSeconds) {
        this.endSeconds = endSeconds;
    }
}
</code>```

答:
```<code>public class Example {

@SerializedName("gender")
@Expose
private String gender;
@SerializedName("trainerName")
@Expose
private String trainerName;
@SerializedName("laterality")
@Expose
private String laterality;
@SerializedName("email")
@Expose
private String email;
@SerializedName("phoneNumber")
@Expose
private String phoneNumber;
@SerializedName("agendaWeekDays")
@Expose
private List<AgendaWeekDay> agendaWeekDays = null;

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getTrainerName() {
return trainerName;
}

public void setTrainerName(String trainerName) {
this.trainerName = trainerName;
}

public String getLaterality() {
return laterality;
}

public void setLaterality(String laterality) {
this.laterality = laterality;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public List<AgendaWeekDay> getAgendaWeekDays() {
return agendaWeekDays;
}

public void setAgendaWeekDays(List<AgendaWeekDay> agendaWeekDays) {
this.agendaWeekDays = agendaWeekDays;
}

}

public class AgendaWeekDay {

@SerializedName("position")
@Expose
private Integer position;
@SerializedName("startSeconds")
@Expose
private Integer startSeconds;
@SerializedName("endSeconds")
@Expose
private Integer endSeconds;

public Integer getPosition() {
return position;
}

public void setPosition(Integer position) {
this.position = position;
}

public Integer getStartSeconds() {
return startSeconds;
}

public void setStartSeconds(Integer startSeconds) {
this.startSeconds = startSeconds;
}

public Integer getEndSeconds() {
return endSeconds;
}

public void setEndSeconds(Integer endSeconds) {
this.endSeconds = endSeconds;
}

}
</code>```

After that where you want to send it via retrofit create object o example class

```<code>Example example = new Example();
</code>```

After that set values to this object as :

```<code>example.setGender("M");
.
.
.
example.setAgendaWeekDays(your arraylist);
</code>```

then

```<code>retrofit.method(token,example).enqueue(new Callback<Void>()
{
@Override
public void onResponse(Call<Void> call, Response<Void> response)
{
                                            if(response.message().equalsIgnoreCase("OK"))
{
}
else
{}
</code>```

Then define your method as:

```<code>@POST("link here")
    Call<Void> method(@Header("Authorization") String authorization, @Body Example example);
</code>```

It will work.

Title: SEND JSON ARRAY RETROFIT 2 (ANDROID)

Body:
I'm novice and know there are many post for this question but i don't find my answer.

So, I need to upgrade a user and his agenda with retrofit2 and the Request "PATCH". But, i don't know how do that with Retrofit2.

Even with my research ... Nothing work !

Can you help me please ?

Thx for advance :D

Here is what I have to send :

{
    "gender": "M",
    "trainerName": "Patrick",
    "laterality": "L",
    "email": "xxxx@gmail.com",
    "phoneNumber": "XXXXX",
    "agendaWeekDays": [
        {
            "position": 1,
            "startSeconds": 648000,
            "endSeconds": 72000
        },
        {
            "position": 2,
            "startSeconds": 0,
            "endSeconds": 459
        }
    ]
}

The response is Just :

{
  "success"
}

my REQUEST

public interface Minterface {
@FormUrlEncoded
@PATCH("api/members/current")
Call<String> test(
        @Field("access_token") String access_token,
        @Field("agendaWeekDays") ArrayList<Agenda> agendaWeekDays);
}

Agenda.class :

public class Agenda
{

    @SerializedName("position")
    @Expose
    private Integer position;
    @SerializedName("startSeconds")
    @Expose
    private Integer startSeconds;
    @SerializedName("endSeconds")
    @Expose
    private Integer endSeconds;

    public Integer getPosition() {
        return position;
    }

    public void setPosition(Integer position) {
        this.position = position;
    }

    public Integer getStartSeconds() {
        return startSeconds;
    }

    public void setStartSeconds(Integer startSeconds) {
        this.startSeconds = startSeconds;
    }

    public Integer getEndSeconds() {
        return endSeconds;
    }

    public void setEndSeconds(Integer endSeconds) {
        this.endSeconds = endSeconds;
    }
}

Body:
public class Example {

@SerializedName("gender")
@Expose
private String gender;
@SerializedName("trainerName")
@Expose
private String trainerName;
@SerializedName("laterality")
@Expose
private String laterality;
@SerializedName("email")
@Expose
private String email;
@SerializedName("phoneNumber")
@Expose
private String phoneNumber;
@SerializedName("agendaWeekDays")
@Expose
private List<AgendaWeekDay> agendaWeekDays = null;

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getTrainerName() {
return trainerName;
}

public void setTrainerName(String trainerName) {
this.trainerName = trainerName;
}

public String getLaterality() {
return laterality;
}

public void setLaterality(String laterality) {
this.laterality = laterality;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public List<AgendaWeekDay> getAgendaWeekDays() {
return agendaWeekDays;
}

public void setAgendaWeekDays(List<AgendaWeekDay> agendaWeekDays) {
this.agendaWeekDays = agendaWeekDays;
}

}

public class AgendaWeekDay {

@SerializedName("position")
@Expose
private Integer position;
@SerializedName("startSeconds")
@Expose
private Integer startSeconds;
@SerializedName("endSeconds")
@Expose
private Integer endSeconds;

public Integer getPosition() {
return position;
}

public void setPosition(Integer position) {
this.position = position;
}

public Integer getStartSeconds() {
return startSeconds;
}

public void setStartSeconds(Integer startSeconds) {
this.startSeconds = startSeconds;
}

public Integer getEndSeconds() {
return endSeconds;
}

public void setEndSeconds(Integer endSeconds) {
this.endSeconds = endSeconds;
}

}

After that where you want to send it via retrofit create object o example class

Example example = new Example();

After that set values to this object as :

example.setGender("M");
.
.
.
example.setAgendaWeekDays(your arraylist);

then

retrofit.method(token,example).enqueue(new Callback<Void>()
{
@Override
public void onResponse(Call<Void> call, Response<Void> response)
{
                                            if(response.message().equalsIgnoreCase("OK"))
{
}
else
{}

Then define your method as:

@POST("link here")
    Call<Void> method(@Header("Authorization") String authorization, @Body Example example);

It will work.


问:
Split 64-bit value to four 16-bit
I have 64 bit values like this:

1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111
  1101 0011

Decimal value of given stream of number is -45.

I want to split in four 16-bit values:

1111 1111 1111 1111

1111 1111 1111 1111

1111 1111 1111 1111

1111 1111 1101 0011

The input value is signed long.

How to do that in Java?

So far I've tried on this way:

```<code>long[] buf = new long[4];
buf[0] =  (l&0xFF);
buf[1] =  (l&0xFF >> 16) & 0XFF;
buf[2] =  (l&0xFF >> 32) & 0XFF;
buf[3] =  (l&0xFF >> 48) & 0XFF;
</code>```

But I think that I mess something with bit shifting logic.

EDIT

The correct solution thanks to @Eugene is:

```<code>long l = 45;

long[] buf = new long[4];
buf[0] =  (l & 0xFFFF);
buf[1] =  l  >> 16 & 0XFFFF;
buf[2] =  l  >> 32 & 0XFFFF;
buf[3] =  l  >> 48 & 0XFFFF;

long result = ( buf[3] & 0xFFFF) << 48 | ( buf[2] & 0xFFFF) << 32 | (buf[1] & 0xFFFF) << 16 | (buf[0] & 0xFFFF);

System.out.println("Decimal: " + result);
System.out.println("Binary: "Long.toBinaryString(result));
</code>```

答:
EDIT

you are almost correct (I did way too much typing thinking that you needs the basics also, my bad).

All you have to change is: buf[1] =  l  >> 16 & 0xFFFF;

I could have written it differently, but that is probably the easiest to understand:

```<code> long t = Long.parseUnsignedLong("1111111111111111111111111111111111111111111111111111111111010011", 2);

    long twoPower16 = Long.parseLong("1111111111111111", 2);

    long one = t & twoPower16;
    long two = t >> 16 & twoPower16;
    long thr = t >> 32 & twoPower16;
    long fou = t >> 48 & twoPower16;

    System.out.println(Long.toBinaryString(one));
    System.out.println(Long.toBinaryString(two));
    System.out.println(Long.toBinaryString(thr));
    System.out.println(Long.toBinaryString(fou));
</code>```

When you do an & operation(it's called a mask), for example :

```<code>   0101
   0011
   ----
   0001 --> you are keeping the last two bits here
</code>```

and the >> is a shift operator. You tell how many bits to shift:

```<code> System.out.println(7 >> 1); // 3
</code>```

That's actually 0111 >> 1 --> 0011, you have shifted 7 on bit to the left.

Title: Split 64-bit value to four 16-bit

Body:
I have 64 bit values like this:

1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111
  1101 0011

Decimal value of given stream of number is -45.

I want to split in four 16-bit values:

1111 1111 1111 1111

1111 1111 1111 1111

1111 1111 1111 1111

1111 1111 1101 0011

The input value is signed long.

How to do that in Java?

So far I've tried on this way:

long[] buf = new long[4];
buf[0] =  (l&0xFF);
buf[1] =  (l&0xFF >> 16) & 0XFF;
buf[2] =  (l&0xFF >> 32) & 0XFF;
buf[3] =  (l&0xFF >> 48) & 0XFF;

But I think that I mess something with bit shifting logic.

EDIT

The correct solution thanks to @Eugene is:

long l = 45;

long[] buf = new long[4];
buf[0] =  (l & 0xFFFF);
buf[1] =  l  >> 16 & 0XFFFF;
buf[2] =  l  >> 32 & 0XFFFF;
buf[3] =  l  >> 48 & 0XFFFF;

long result = ( buf[3] & 0xFFFF) << 48 | ( buf[2] & 0xFFFF) << 32 | (buf[1] & 0xFFFF) << 16 | (buf[0] & 0xFFFF);

System.out.println("Decimal: " + result);
System.out.println("Binary: "Long.toBinaryString(result));

Body:
EDIT

you are almost correct (I did way too much typing thinking that you needs the basics also, my bad).

All you have to change is: buf[1] =  l  >> 16 & 0xFFFF;

I could have written it differently, but that is probably the easiest to understand:

 long t = Long.parseUnsignedLong("1111111111111111111111111111111111111111111111111111111111010011", 2);

    long twoPower16 = Long.parseLong("1111111111111111", 2);

    long one = t & twoPower16;
    long two = t >> 16 & twoPower16;
    long thr = t >> 32 & twoPower16;
    long fou = t >> 48 & twoPower16;

    System.out.println(Long.toBinaryString(one));
    System.out.println(Long.toBinaryString(two));
    System.out.println(Long.toBinaryString(thr));
    System.out.println(Long.toBinaryString(fou));

When you do an & operation(it's called a mask), for example :

   0101
   0011
   ----
   0001 --> you are keeping the last two bits here

and the >> is a shift operator. You tell how many bits to shift:

 System.out.println(7 >> 1); // 3

That's actually 0111 >> 1 --> 0011, you have shifted 7 on bit to the left.


问:
PERL: When I add just the "use JSON::RPC::Client" to my script but not use it I get an error
So

here is the import lines of my script...when I uncomment the JSON::RPC line I get the error listed below. I'm not even using the library in the script and still get the error listed below

```<code>#!/usr/bin/perl -w

use Data::Dumper;
use Mail::MboxParser;
use Mail::MboxParser::Mail;
use Mail::Box::Manager;
use Email::Delete qw[delete_message];
use POSIX;
use Date::Calc qw(:all);
#use JSON::RPC::Client;
use strict;
</code>```

--

```<code> /usr/bin/perl: symbol lookup error:  /usr/local/lib64/perl5/auto/Storable/Storable.so: undefined symbol: Perl_Istack_sp_ptr
</code>```

On the perl 5.10 box:

```<code>perl -MStorable -wle'print $ARGV[0]->VERSION' Storable
2.30
</code>```

On the perl 5.16 box:

```<code>perl -MStorable -wle'print $ARGV[0]->VERSION' Storable
perl: symbol lookup error: /usr/local/lib64/perl5/auto/Storable/Storable.so: undefined symbol: Perl_Istack_sp_ptr
</code>```

答:
(I can't find a module called JSON::RPC::Client on CPAN, so some of this is guesswork. Where did the module come from?)

The reason why you're getting those errors when you just uncomment the use line is that Perl will then try to load the library. And the load is failing.

It looks like your library has an XS component. That is to say, it's not written in Pure Perl. Part of it is a Perl wrapper around a library written in another language (probably C).

Perl guarantees that XS libraries written for a given major version of Perl (in this case 5.10) will work for all minor releases under that same major version number (so any 5.10.x). But major releases will usually break that binary compatibility. An XS module built for Perl 5.10.x will not usually work with Perl 5.16.x.

The solution is to rebuild the module for your new version of Perl. I hope you know where the source code is, because (as I mentioned earlier) it's not on CPAN.

Body:
So

here is the import lines of my script...when I uncomment the JSON::RPC line I get the error listed below. I'm not even using the library in the script and still get the error listed below

#!/usr/bin/perl -w

use Data::Dumper;
use Mail::MboxParser;
use Mail::MboxParser::Mail;
use Mail::Box::Manager;
use Email::Delete qw[delete_message];
use POSIX;
use Date::Calc qw(:all);
#use JSON::RPC::Client;
use strict;

--

 /usr/bin/perl: symbol lookup error:  /usr/local/lib64/perl5/auto/Storable/Storable.so: undefined symbol: Perl_Istack_sp_ptr

On the perl 5.10 box:

perl -MStorable -wle'print $ARGV[0]->VERSION' Storable
2.30

On the perl 5.16 box:

perl -MStorable -wle'print $ARGV[0]->VERSION' Storable
perl: symbol lookup error: /usr/local/lib64/perl5/auto/Storable/Storable.so: undefined symbol: Perl_Istack_sp_ptr


问:
SQL Server: Combine multiple rows into one with no overlap but new columns
I have a Table "Details" like this:

```<code>    ID         |        BookID         |        Genre
    _____________________________________________________
    1          |         12            |         AB
    1          |         05            |         AC
    2          |         12            |         AB
    2          |         08            |         BB
</code>```

Is there any way to combine the rows in this format:

```<code>    ID  | BookID1 | Genre1  | BookID2 | Genre2
    _____________________________________________________
    1   | 12      | AB      | 05      |   AC
    2   | 12      | AB      | 08      |   BB
</code>```

I need to do it in such a format to add the respective columns to a stored procedure.

I generally would love to include some code or attempts but I'm clueless at this moment.

Not a Duplicate of the below:
T-SQL dynamic pivot

1st difference im not using tsql

2nd difference is the structure of the table which can't be applied to mine.

My values are not going to be column headers instead they are gonna generate new columns such as :

```<code>    ID  | BookID1 | Genre1  | BookID2 | Genre2  | BookID3 | Genre3  | BookID4 | Genre4
    1   | 05      | Horror  | 12      | Horror  | 03      | Drama   |         |
    2   | 05      | Horror  | 15      | Advent  | 03      | Drama   | 112     | RomCom
</code>```

3rd Im not able to grasp the structure since I have zero knowledge of pivot tables

答:
For all those with a case similar to mine.

The below link is a huge help :

https://community.spiceworks.com/topic/973727-sql-how-to-convert-multiple-rows-into-single-rows-with-more-columns

Body:
I have a Table "Details" like this:

    ID         |        BookID         |        Genre
    _____________________________________________________
    1          |         12            |         AB
    1          |         05            |         AC
    2          |         12            |         AB
    2          |         08            |         BB

Is there any way to combine the rows in this format:

    ID  | BookID1 | Genre1  | BookID2 | Genre2
    _____________________________________________________
    1   | 12      | AB      | 05      |   AC
    2   | 12      | AB      | 08      |   BB

I need to do it in such a format to add the respective columns to a stored procedure.

I generally would love to include some code or attempts but I'm clueless at this moment.

Not a Duplicate of the below:
T-SQL dynamic pivot

1st difference im not using tsql

2nd difference is the structure of the table which can't be applied to mine.

My values are not going to be column headers instead they are gonna generate new columns such as :

    ID  | BookID1 | Genre1  | BookID2 | Genre2  | BookID3 | Genre3  | BookID4 | Genre4
    1   | 05      | Horror  | 12      | Horror  | 03      | Drama   |         |
    2   | 05      | Horror  | 15      | Advent  | 03      | Drama   | 112     | RomCom

3rd Im not able to grasp the structure since I have zero knowledge of pivot tables


问:
Do pushdown parsers scan tokens or single characters?
I am currently a bit confused about what kind of input pushdown automations excpect. I know the concept behind them (transitions, states, stacks, symbols, popping etc) but I dont really understand what:

A) The alphabet is for if we need all characters from a-z and 0-9 since we are parsing tokens not individual characters such as the typical 101 or ABAB examples.

B) Does the pushdown even accept tokens. For example: if the token "TOK_IF" is found then go to next transition or state.

Could you enlighten me about points A and B? Im really confused.

答:
A (deterministic) pushdown-automaton can be used to parse a (deterministic) context-free language.
It is possible to define the grammar of this language over single characters, which make up the text to parse. This however needs a vast amount of states.

Hence, it is more efficient (and easier to formulate and comprehend the grammar) to pre-parse keywords and identifiers to tokens (usually by a lexer) and treat these tokens as a single entity. Lexers can be implemented much faster than using the pushdown-automaton and a large number of states to do the same job.


问:
Spring JavaConfig for java.util.Properties field

Can you please tell me how to use Spring Javaconfig to directly load/autowire a properties file to a java.util.Properties field?

Thanks!

Later edit - still searching for the answer:
Is it possible to load with Spring JavaConfig a properties file directly into a java.util.Properties field?

答:
application.yml:

```<code>root-something:
    my-properties:
        key1: val1
        key2: val2
</code>```

Your type-safe pojo:

```<code>import java.util.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "root-something")
public class RootSomethingPojo {

    private Properties myProperties;
</code>```

Your container configuration:

```<code>@Configuration
@EnableConfigurationProperties({ RootSomethingPojo .class })
public class MySpringConfiguration {
</code>```

This will inject the key-value pairs directly into the myProperties field.

Body:
application.yml:

root-something:
    my-properties:
        key1: val1
        key2: val2

Your type-safe pojo:

import java.util.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "root-something")
public class RootSomethingPojo {

    private Properties myProperties;

Your container configuration:

@Configuration
@EnableConfigurationProperties({ RootSomethingPojo .class })
public class MySpringConfiguration {

This will inject the key-value pairs directly into the myProperties field.


问:
How to show and hide side menu in angular2
In my application i have to implement hide and show side menu. By default the page menu is open while clicking the toggle menu i have to hide the side menu. How can i implement this.

what i have is:

app.component.html, nav.component.html

        Name

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

<p>Myservice.ts</p>

```export class GlobalService {
public collapse;

constructor() { }

setValue(val: boolean) {
    this.collapse = val;
}

getValue() {
    return this.collapse;
}
```

<p>EDIT</p>

<p>app.component.html</p>

```

```

<p>app.component.ts</p>

```import { GlobalService } from "path";

export class AppComponent {
toggle() {
this.globalService.setValue(false);

 }
}
```

how can i hide this list(in nav.html) while clicking menu toggle (app.compnent.html)? Any help will really appreciable. i am new to angular.

答:
You can create a service and preferably make a static variable inside to get and set the visibility state of the menu. By this you could directly set and get the variable by using ComponentName.variableName.

to play with the visibility you could use(Sorry if there is any syntax errors)
1> Set the document.getelementbyid("idofelement").display= none or block
2>use *ngIf="someboolean" where you should set the boolean in your ts file

Body:
In my application i have to implement hide and show side menu. By default the page menu is open while clicking the toggle menu i have to hide the side menu. How can i implement this.

what i have is:

app.component.html, nav.component.html

        Name

Myservice.ts

export class GlobalService {
public collapse;

constructor() { }

setValue(val: boolean) {
    this.collapse = val;
}

getValue() {
    return this.collapse;
}

EDIT

app.component.html

app.component.ts

import { GlobalService } from "path";

export class AppComponent {
toggle() {
this.globalService.setValue(false);

 }
}

how can i hide this list(in nav.html) while clicking menu toggle (app.compnent.html)? Any help will really appreciable. i am new to angular.


问:
Vim : Override equalprg with a command with argument
I would like to override the = vim operator with clang-format using my own style sheet for C/C++ files:
This idea is to make a clang-format -i -style=~/.my_own_clang_format_config inside vim.

I tried the following commands without success:
(from Ansi C support in Vim) :set equalprg=clang-format --> Does not take any indentation

set equalprg="clang-format -style='~/.my_own_clang_format_config'" --> a echom &equalprg returns an empty string

set equalprg='clang-format -i -style=~/.my_own_clang_format_config' --> Unknown option: -i

I tried also to add some shellescape after the = but it is not interpreted... Any idea?

[EDIT] : -style='.my_own_clang_format_config' is not a valid option for clang-format. I had to use the following option :
clang-format -style='file' and add my custom .clang_format in my folder (or the root folder of my project) to make it work without vim.

答:
All you need is to escape the whitespaces since that interferes from calling the command within the vim command line mode.

```<code>set equalprg=clang-format\ -i\ -style='~/.my_own_clang_format_config'
</code>```

Edit: The whitespace is used to determine multiple arguments to the command being called, in this case :set. Escaping them enables VIM to interpret the latter to be a single coherent statement assigning the vim option equalprg.

Body:
All you need is to escape the whitespaces since that interferes from calling the command within the vim command line mode.

set equalprg=clang-format\ -i\ -style='~/.my_own_clang_format_config'

Edit: The whitespace is used to determine multiple arguments to the command being called, in this case :set. Escaping them enables VIM to interpret the latter to be a single coherent statement assigning the vim option equalprg.


问:
Clean up open and closed brackets in RDD using Scala
after doing few transformations on a file using spark and scala i got an result like the below

```<code>(451,M,(BC-B,(21104246,321.50)))
(454,M,(OC,(21104751,361.00)))
(147,M,(OC,(20404588,340.00)))
(155,M,(BC-B,(20405733,347.00)))
</code>```

but I need to remove the brackets and expecting the output as the below because I need to convert the rdd to dataframe

```<code>454,M,OC,21104751,361.00
451,M,BC-B,21104246,321.50
147,M,OC,20404588,340.00
155,M,BC-B,20405733,347.00
</code>```

any help is appreciable!!!

答:
You can just pattern match it out:</p>

```<code>rdd.map{case (a,b,(c,(d,e))) => (a,b,c,d,e)}.toDF()
</code>```

Body:
after doing few transformations on a file using spark and scala i got an result like the below

(451,M,(BC-B,(21104246,321.50)))
(454,M,(OC,(21104751,361.00)))
(147,M,(OC,(20404588,340.00)))
(155,M,(BC-B,(20405733,347.00)))

but I need to remove the brackets and expecting the output as the below because I need to convert the rdd to dataframe

454,M,OC,21104751,361.00
451,M,BC-B,21104246,321.50
147,M,OC,20404588,340.00
155,M,BC-B,20405733,347.00

any help is appreciable!!!

Body:
You can just pattern match it out:

rdd.map{case (a,b,(c,(d,e))) => (a,b,c,d,e)}.toDF()


问:
How to close vim editor with non-zero return value?
I have an alias bed="vim ~/.bashrc && . ~/.bashrc" in my .bashrc. Now every now and then I'd like to run bed but return the vim with an exit status 1 so the source command doesn't execute.

答:
Found the answer here : How to exit the Vim editor?

You can do :cq to exit with a non-zero exit code.


问:
Data mining engines and frameworks?
What opensource/free data mining engines and frameworks do you know and use for textual data?

Thank you for any advice!

答: RapidMiner is free and open source and runs on windows, mac, linux, and is a nice graphical workflow based program. It runs all Weka code, and integrates with R.</p>

Title: Data mining engines and frameworks?