问:
Subtracting a number of years from a Date
Say I have code: date('Y')."-".date('m')."-".date('d') How would I go about removing a number of years from the date that piece of code gives me?

答:
```<code>$date = strtotime('-2 years');
</code>```

And since your printing code is nothing but a convoluted version of this:

```<code>echo date('Y-m-d', $date);
</code>```

... you could simplify everything into a one-liner:

```<code>echo date('Y-m-d', strtotime('-2 years'));
</code>```

Body:
$date = strtotime('-2 years');

And since your printing code is nothing but a convoluted version of this:

echo date('Y-m-d', $date);

... you could simplify everything into a one-liner:

echo date('Y-m-d', strtotime('-2 years'));


来源: stackexchange

问:
VBA : Insert new column to the left of all columns up until the last column
I'm trying to insert a column next to each column starting from D, my issue is that the number of columns will change so I need to identify the last column within the code.

Whenever I run the below it doesn't seem to be identifying the last column correctly.

```<code>Sub InsertColumnsv2()
  Dim iLastCol As Long
  Dim StartCell As Range

  Set StartCell = Range("A1")

  iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column

  For colx = 4 To iLastCol Step 2
    ActiveSheet.UsedRange
    iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
    Columns(colx).Insert Shift:=xlToRight
  Next colx
End Sub
</code>```

答:
A better way to solve your insert problem is start from the finish to the start.</p>

```<code>Sub InsertColumnsv2()
  Dim iLastCol As Long
  Dim StartCell As Range

  Set StartCell = Range("A1")

  iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column

  For colx = iLastCol  To 4 Step -1
      Columns(colx).Insert Shift:=xlToRight
  Next colx
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to insert a column next to each column starting from D, my issue is that the number of columns will change so I need to identify the last column within the code.

Whenever I run the below it doesn't seem to be identifying the last column correctly.

Sub InsertColumnsv2()
  Dim iLastCol As Long
  Dim StartCell As Range

  Set StartCell = Range("A1")

  iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column

  For colx = 4 To iLastCol Step 2
    ActiveSheet.UsedRange
    iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
    Columns(colx).Insert Shift:=xlToRight
  Next colx
End Sub

Body:
A better way to solve your insert problem is start from the finish to the start.

Sub InsertColumnsv2()
  Dim iLastCol As Long
  Dim StartCell As Range

  Set StartCell = Range("A1")

  iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column

  For colx = iLastCol  To 4 Step -1
      Columns(colx).Insert Shift:=xlToRight
  Next colx
End Sub


问:
Is it possible to use Spring to create a console application?
Currently researching this topic. Is it possible to use the benefits of Spring to form a Console application? I mean, with scopes, autowiring and etc(found a bunch of examples of a basic "Set the context, init and go", but nothing more)?

Can't find any tutorials or helpful information on this topic.

答:
CommandLineRunner example. If you run this Spring Boot, the run method will be the entry point.

```<code>package com.mkyong;

import com.mkyong.service.HelloMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import static java.lang.System.exit;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    @Autowired
    private HelloMessageService helloService;

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

        //disabled banner, don't want to see the spring logo
        SpringApplication app = new SpringApplication(SpringBootConsoleApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

    }

    // Put your logic here.
    @Override
    public void run(String... args) throws Exception {

        if (args.length > 0) {
            System.out.println(helloService.getMessage(args[0].toString()));
        } else {
            System.out.println(helloService.getMessage());
        }

        exit(0);
    }
}
</code>```

Details

Body:
CommandLineRunner example. If you run this Spring Boot, the run method will be the entry point.

package com.mkyong;

import com.mkyong.service.HelloMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import static java.lang.System.exit;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    @Autowired
    private HelloMessageService helloService;

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

        //disabled banner, don't want to see the spring logo
        SpringApplication app = new SpringApplication(SpringBootConsoleApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

    }

    // Put your logic here.
    @Override
    public void run(String... args) throws Exception {

        if (args.length > 0) {
            System.out.println(helloService.getMessage(args[0].toString()));
        } else {
            System.out.println(helloService.getMessage());
        }

        exit(0);
    }
}

Details


问:
Adding columns in table
I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total on the table when data is being fetched.

Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?

PS: with my code, it only displays the total of the current column of the table

Table

```<code><tbody>
    @foreach($items as $items)
        <tr>
            <td>{{$item>id }}</td>
            <td>{{$item->quantity}}</td>
            <td>{{ $item->price}}</td>
            <td>{{ $item->quantity * $item->price}}</td>
        </tr>
    @endforeach
    <p>Sum: {{ $item->quantity * $item->price}}</p>
</tbody>
</code>```

答:
I assume here $items is a Illuminate\Support\Collection.  You can calculate a sum using a closure:

```<code>$items->sum( function ($item) {
    return $item->quantity * $item->price;
});
</code>```

Or in your blade template:

```<code>{{ $items->sum( function ($item) {
    return $item->quantity * $item->price;
}); }}
</code>```

See Laravel Collections docs.

Title: Adding columns in table

Body:
I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total on the table when data is being fetched.

Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?

PS: with my code, it only displays the total of the current column of the table

Table

    @foreach($items as $items)

            {{$item>id }}
            {{$item->quantity}}
            {{ $item->price}}
            {{ $item->quantity * $item->price}}

    @endforeach

Sum: {{ $item->quantity * $item->price}}

Body:
I assume here $items is a Illuminate\Support\Collection.  You can calculate a sum using a closure:

$items->sum( function ($item) {
    return $item->quantity * $item->price;
});

Or in your blade template:

{{ $items->sum( function ($item) {
    return $item->quantity * $item->price;
}); }}

See Laravel Collections docs.


问:
Laravel displaying many to many relationship items
I have set up a many to many relationship in Laravel and have the database table populated with data.  The relationship setup looks like this...

```<code>users.php
---------
   public function houses()
    {
        return $this->belongsToMany('App\House')
        ->withTimestamps();
    }

house.php
---------
public function users()
    {
        return $this->belongsToMany('App\User')
        ->withTimestamps();
    }
</code>```

In my /house/show.blade.php I am trying to display the saved connections like this...

```<code>$houses = House::with('App\User')->all();

foreach ($houses as $house) {
    echo 'Found House';
}
</code>```

It is giving me an error saying that $houses can not be found.  Where am I going wrong?

答:
You should indicate the relationship in the with method like this :

```<code>$houses = House::with('users')->get();
</code>```

And one more thing it's better to get houses in the controller and pass them to the view :

```<code>$houses = House::with('users')->get();
return view('someView')->withHouses($houses);
</code>```

And in the view do it like this :

```<code>@foreach ($houses as $house)
    {{ $house->addres }}
@endforeach
</code>```

To get only the houses taht has the users try this :

```<code>$houses = House::has('users')->get();
</code>```

And to add some conditions on the users you can do it like this :

```<code>$houses = House::whereHas('users', function ($query) {
    $query->where('name', 'some user name'); // to add some conditions on the user :)
})->get();
</code>```

Body:
I have set up a many to many relationship in Laravel and have the database table populated with data.  The relationship setup looks like this...

users.php
---------
   public function houses()
    {
        return $this->belongsToMany('App\House')
        ->withTimestamps();
    }

house.php
---------
public function users()
    {
        return $this->belongsToMany('App\User')
        ->withTimestamps();
    }

In my /house/show.blade.php I am trying to display the saved connections like this...

$houses = House::with('App\User')->all();

foreach ($houses as $house) {
    echo 'Found House';
}

It is giving me an error saying that $houses can not be found.  Where am I going wrong?

Body:
You should indicate the relationship in the with method like this :

$houses = House::with('users')->get();

And one more thing it's better to get houses in the controller and pass them to the view :

$houses = House::with('users')->get();
return view('someView')->withHouses($houses);

And in the view do it like this :

@foreach ($houses as $house)
    {{ $house->addres }}
@endforeach

To get only the houses taht has the users try this :

$houses = House::has('users')->get();

And to add some conditions on the users you can do it like this :

$houses = House::whereHas('users', function ($query) {
    $query->where('name', 'some user name'); // to add some conditions on the user :)
})->get();


问:
Rerurn null if subquery hasn't value sql
If this query hasn't B values, but has A values, can I have null where there are no values?

```<code>SELECT A, B
FROM
(SELECT title as A
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'),

(SELECT title as B
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')
</code>```

For example, this table must be show

```<code>  A        B
---------------
Computer  null
</code>```

But now it show the values only if Id has Type A and Type B

答:
```<code>SELECT A, B
FROM
(SELECT title as A
FROM TABLE
INNER JOIN TABLE2 ON TABLE_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A')AA
left join
(SELECT title as B
FROM TABLE
INNER JOIN TABLE2 ON TABLE_TABLE2_ID = TABLE2_ID
INNER JOIN TABLE3 ON TABLE_TABLE3_ID = TABLE3_ID
WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')BB
on AA.A=BB.B

Hope this will solve your problem...
</code>```

Body:
If this query hasn't B values, but has A values, can I have null where there are no values?

SELECT A, B
FROM
(SELECT title as A
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'A'),

(SELECT title as B
 FROM TABLE1
 INNER JOIN TABLE2 ON TABLE1_TABLE2_ID = TABLE2_ID
 INNER JOIN TABLE3 ON TABLE1_TABLE3_ID = TABLE3_ID
 WHERE TABLE_TABLE3_ID = 2008 AND TABLE_TYP LIKE 'B')

For example, this table must be show

  A        B
---------------
Computer  null

But now it show the values only if Id has Type A and Type B


问:
Django: Filtering the Distinct Data
I'm trying to build a messaging app. Here's my model,

```<code>class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is what I tried in view,

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
</code>```

In the template,

```<code>{% for abc in data %}
    {{ abc.receiver }} <br/>
{% endfor %}
</code>```

How to get distinct users and re-order them based upon new messages as we see on social media platforms?

答:
you can try this code</p>

```<code>inbox_message = Message.objects.filter.objects.filter(receiver=request.user).order_by('-created_at')

outbox_message = Message.objects.filter.objects.filter(sender=request.user).order_by('-created_at')
</code>```

Title: Django: Filtering the Distinct Data

Body:
I'm trying to build a messaging app. Here's my model,

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in view,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))

In the template,

{% for abc in data %}
    {{ abc.receiver }}

{% endfor %}

How to get distinct users and re-order them based upon new messages as we see on social media platforms?

Body:
you can try this code

inbox_message = Message.objects.filter.objects.filter(receiver=request.user).order_by('-created_at')

outbox_message = Message.objects.filter.objects.filter(sender=request.user).order_by('-created_at')


问:
How to use an array in actionscript?
```<code>var fruit:Array = new Array();

var frName:String;

var i:Number;

save_btn.addEventListener(MouseEvent.CLICK, storeName);

function storeName(Event:MouseEvent)
{

 frName = name_txt.text;

 fruit[i] = frName;

 i++;
}

detail_btn.addEventListener(MouseEvent.CLICK, dispName);

function dispName(Event:MouseEvent)

{

 for(i=0; i<=1; i++)

 {
  trace(fruit[i]);
 }
}
</code>```

The script has two buttons: one for saving the text in a fruit array and the other for displaying the text.

However, when I click the display button, the script shows undefined as output in actionscript. Please help.

答:
declaring i as a global variable is making things difficult. Perhaps try rewritting like so:</p>

```<code>var fruit:Array = new Array();

save_btn.addEventListener(MouseEvent.CLICK, storeName);

function storeName(Event:MouseEvent){
  fruit.push(name_txt.text);
}

detail_btn.addEventListener(MouseEvent.CLICK, dispName);

function dispName(Event:MouseEvent){
  for(var f:String in fruit){
    trace(f);
  }
}
</code>```

Title: How to use an array in actionscript?

Body:
var fruit:Array = new Array();

var frName:String;

var i:Number;

save_btn.addEventListener(MouseEvent.CLICK, storeName);

function storeName(Event:MouseEvent)
{

 frName = name_txt.text;

 fruit[i] = frName;

 i++;
}

detail_btn.addEventListener(MouseEvent.CLICK, dispName);

function dispName(Event:MouseEvent)

{

 for(i=0; i<=1; i++)

 {
  trace(fruit[i]);
 }
}

The script has two buttons: one for saving the text in a fruit array and the other for displaying the text.

However, when I click the display button, the script shows undefined as output in actionscript. Please help.

Body:
declaring i as a global variable is making things difficult. Perhaps try rewritting like so:

var fruit:Array = new Array();

save_btn.addEventListener(MouseEvent.CLICK, storeName);

function storeName(Event:MouseEvent){
  fruit.push(name_txt.text);
}

detail_btn.addEventListener(MouseEvent.CLICK, dispName);

function dispName(Event:MouseEvent){
  for(var f:String in fruit){
    trace(f);
  }
}

ContentLicense: CC BY-SA 2.5


问:
get youtube video basic info in java youtube api v3?
To be precise I want to get a youtube video Basic info such as: Views, Likes, Dislikes.

I found this question about: Get view count using Google Youtube API

But I am getting the error at Auth.HTTP_TRANSPORT and Auth.JSON_FACTORY class doesn't exist error.

By your request my code:

```<code> import com.google.api.client.googleapis.json.GoogleJsonResponseException;
 import com.google.api.client.http.HttpRequest;
 import com.google.api.client.http.HttpRequestInitializer;
 import com.google.api.services.youtube.YouTube;
 import com.google.api.services.youtube.model.Video;
 import com.google.api.services.youtube.model.VideoListResponse;

 import java.io.IOException;
 import java.math.BigInteger;

public class DBConnect {
    public String getyoutubeitemfull_details(String URI) throws SQLException, IOException{
        try {
            YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) throws IOException {
                }
        }).setApplicationName("APP_ID").build();

            String apiKey = "API_KEY";
            YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
            listVideosRequest.setId("lf_wVfwpfp8"); // add list of video IDs here
            listVideosRequest.setKey(apiKey);
            VideoListResponse listResponse = listVideosRequest.execute();

            Video video = listResponse.getItems().get(0);

            BigInteger viewCount = video.getStatistics().getViewCount();

            System.out.println(" ViewCount: " + viewCount);
              System.out.println("\n-------------------------------------------------------------\n");

        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
        System.out.println("Youtube");
        return null;
    }
}
</code>```

答:
For Future generation.

In order to get basic info of a youtube video based on its ID This would work:

```<code>import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoListResponse;

import duck.reg.pack.Auth;
import java.io.IOException;
import java.math.BigInteger;

public class DBConnect {

    public String getyoutubeitemfull_details() throws SQLException, IOException{
        try {
            YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) throws IOException {
                }
            }).setApplicationName("APP_ID").build();

            String apiKey = "Your Private Api Key"; // you can get it from https://console.cloud.google.com/apis/credentials
            YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
            listVideosRequest.setId("yVcMc9HVXvc"); // add list of video IDs here
            listVideosRequest.setKey(apiKey);
            VideoListResponse listResponse = listVideosRequest.execute();

            Video video = listResponse.getItems().get(0);

            BigInteger viewCount = video.getStatistics().getViewCount();
            BigInteger Likes = video.getStatistics().getLikeCount();
            BigInteger DisLikes = video.getStatistics().getDislikeCount();
            BigInteger Comments = video.getStatistics().getCommentCount();
            System.out.println("[View Count] " + viewCount);
            System.out.println("[Likes] " + Likes);
            System.out.println("[Dislikes] " + DisLikes);
            System.out.println("[Comments] " + Comments);

        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return null;
    }
}
</code>```

Note: duck.reg.pack.Auth is required for the API to work, but normally Auth class doesn't come with the youtube API libs. So what you can do is to create a new class calling it Auth and Copy/Paste bellow code:

Auth.java:

```<code>import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.StoredCredential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStore;
import com.google.api.client.util.store.FileDataStoreFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

/**
 * Shared class used by every sample. Contains methods for authorizing a user and caching credentials.
 */
public class Auth {

    /**
     * Define a global instance of the HTTP transport.
     */
    public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    /**
     * Define a global instance of the JSON factory.
     */
    public static final JsonFactory JSON_FACTORY = new JacksonFactory();

    /**
     * This is the directory that will be used under the user's home directory where OAuth tokens will be stored.
     */
    private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";

    /**
     * Authorizes the installed application to access user's protected data.
     *
     * @param scopes              list of scopes needed to run youtube upload.
     * @param credentialDatastore name of the credential datastore to cache OAuth tokens
     */
    public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

        // Load client secrets.
        Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

        // Checks that the defaults have been replaced (Default = "Enter X here").
        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println(
                "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                        + "into src/main/resources/client_secrets.json");
            System.exit(1);
        }

        // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
            .build();

        // Build the local server and bind it to port 8080
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
    }
}
</code>```

Then just call getyoutubeitemfull_details as:

```<code>DBConnect youtube_binfo = new DBConnect();
youtube_info.getyoutubeitemfull_details();
</code>```

Thanks to @Stultuske with helping me finding my solution.

Body:
To be precise I want to get a youtube video Basic info such as: Views, Likes, Dislikes.

I found this question about: Get view count using Google Youtube API

But I am getting the error at Auth.HTTP_TRANSPORT and Auth.JSON_FACTORY class doesn't exist error.

By your request my code:

 import com.google.api.client.googleapis.json.GoogleJsonResponseException;
 import com.google.api.client.http.HttpRequest;
 import com.google.api.client.http.HttpRequestInitializer;
 import com.google.api.services.youtube.YouTube;
 import com.google.api.services.youtube.model.Video;
 import com.google.api.services.youtube.model.VideoListResponse;

 import java.io.IOException;
 import java.math.BigInteger;

public class DBConnect {
    public String getyoutubeitemfull_details(String URI) throws SQLException, IOException{
        try {
            YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) throws IOException {
                }
        }).setApplicationName("APP_ID").build();

            String apiKey = "API_KEY";
            YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
            listVideosRequest.setId("lf_wVfwpfp8"); // add list of video IDs here
            listVideosRequest.setKey(apiKey);
            VideoListResponse listResponse = listVideosRequest.execute();

            Video video = listResponse.getItems().get(0);

            BigInteger viewCount = video.getStatistics().getViewCount();

            System.out.println(" ViewCount: " + viewCount);
              System.out.println("\n-------------------------------------------------------------\n");

        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
        System.out.println("Youtube");
        return null;
    }
}

Body:
For Future generation.

In order to get basic info of a youtube video based on its ID This would work:

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoListResponse;

import duck.reg.pack.Auth;
import java.io.IOException;
import java.math.BigInteger;

public class DBConnect {

    public String getyoutubeitemfull_details() throws SQLException, IOException{
        try {
            YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) throws IOException {
                }
            }).setApplicationName("APP_ID").build();

            String apiKey = "Your Private Api Key"; // you can get it from https://console.cloud.google.com/apis/credentials
            YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
            listVideosRequest.setId("yVcMc9HVXvc"); // add list of video IDs here
            listVideosRequest.setKey(apiKey);
            VideoListResponse listResponse = listVideosRequest.execute();

            Video video = listResponse.getItems().get(0);

            BigInteger viewCount = video.getStatistics().getViewCount();
            BigInteger Likes = video.getStatistics().getLikeCount();
            BigInteger DisLikes = video.getStatistics().getDislikeCount();
            BigInteger Comments = video.getStatistics().getCommentCount();
            System.out.println("[View Count] " + viewCount);
            System.out.println("[Likes] " + Likes);
            System.out.println("[Dislikes] " + DisLikes);
            System.out.println("[Comments] " + Comments);

        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return null;
    }
}

Note: duck.reg.pack.Auth is required for the API to work, but normally Auth class doesn't come with the youtube API libs. So what you can do is to create a new class calling it Auth and Copy/Paste bellow code:

Auth.java:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.StoredCredential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStore;
import com.google.api.client.util.store.FileDataStoreFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

/**
 * Shared class used by every sample. Contains methods for authorizing a user and caching credentials.
 */
public class Auth {

    /**
     * Define a global instance of the HTTP transport.
     */
    public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    /**
     * Define a global instance of the JSON factory.
     */
    public static final JsonFactory JSON_FACTORY = new JacksonFactory();

    /**
     * This is the directory that will be used under the user's home directory where OAuth tokens will be stored.
     */
    private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";

    /**
     * Authorizes the installed application to access user's protected data.
     *
     * @param scopes              list of scopes needed to run youtube upload.
     * @param credentialDatastore name of the credential datastore to cache OAuth tokens
     */
    public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

        // Load client secrets.
        Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

        // Checks that the defaults have been replaced (Default = "Enter X here").
        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println(
                "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                        + "into src/main/resources/client_secrets.json");
            System.exit(1);
        }

        // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
            .build();

        // Build the local server and bind it to port 8080
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
    }
}

Then just call getyoutubeitemfull_details as:

DBConnect youtube_binfo = new DBConnect();
youtube_info.getyoutubeitemfull_details();

Thanks to @Stultuske with helping me finding my solution.


问:
DB2/Cursor program working in cobol
My requirement is to delete data from db2 table which contains duplicate phone num(invalid phone num, set of 16 phone numbers which is hardcoded).And one phone num should be retained , that depends on sequence number(minimum value).

consider main table has following data : PHONE_TAB

```<code>Client_Id   Phone_num  Seq_num
 1234        45678       15   --- delete
 4444        55555       45
 1234        45678       10   ---should be retained
 5555        22222       25
 1234        45678       20   ---  delete
 1234        45678       11   ---  delete
</code>```

Note : also i have to move the rows which will be deleted to output tape file before deleting to take backup.

Have come up with the below logic,
Declaring cursor :

```<code>EXEC SQL
  DECLARE CUR1 CURSOR WITH HOLD FOR
   SELECT * FROM PHONE_TAB WHERE PHONE_NUM = 45678
END-EXEC
</code>```

FETCH-PARA

```<code>EXEC SQL
 FETCH CUR1 INTO :DCLGEN_CLIENT_ID
                :DCLGEN_PHONE_NUM
                :DCLGEN_SEQ_NUM
END-EXEC
</code>```

VALIDATE-PARA

```<code>EXEC SQL
 SELECT MIN(SEQ_NUM) FROM PHONE_TAB
 WHERE CLIENT_ID = :DCLGEN_CLIENT_ID
       PHONE_NUM = :DCLGEN_PHONE_NUM GROUP BY CLIENT_ID AND PHONE_NUM
       INTO WS_MIN
END-EXEC

EVALUATE TRUE
 WHEN SEQ_NUM > WS_MIN
      PERFORM BACKUP-PARA
 WHEN OTHER
      PERFORM FETCH-PARA
</code>```

Finally , DELETE-PARA

```<code>EXEC SQL
  DELETE FROM PHONE_TAB WHERE CURRENT CURSOR
END-EXEC
</code>```

Can someone tell me whether this logic is right ?
My doubt is whether it will do mass deletion without taking backup to tape file?

Thanks

答:
You can delete them all in one go with the following SQL

```<code>DELETE FROM PHONE_TAB A
 WHERE EXISTS (SELECT 1 FROM PHONE_TAB B
                WHERE A.PHONE_NUM = B.PHONE_NUM AND
                      A.SEQ_NUM > B.SEQ_NUM)
</code>```

It works by deleting all rows where another row exists that has the same phone number and a lower sequence number.

You can check that it deletes the right rows by first running it with a select, like this

```<code>SELECT * FROM PHONE_TAB A
 WHERE EXISTS (SELECT 1 FROM PHONE_TAB B
                WHERE A.PHONE_NUM = B.PHONE_NUM AND
                      A.SEQ_NUM > B.SEQ_NUM)
</code>```

If you need to backup the rows, you can run the select and then delete the rows.

Title: DB2/Cursor program working in cobol

Body:
My requirement is to delete data from db2 table which contains duplicate phone num(invalid phone num, set of 16 phone numbers which is hardcoded).And one phone num should be retained , that depends on sequence number(minimum value).

consider main table has following data : PHONE_TAB

Client_Id   Phone_num  Seq_num
 1234        45678       15   --- delete
 4444        55555       45
 1234        45678       10   ---should be retained
 5555        22222       25
 1234        45678       20   ---  delete
 1234        45678       11   ---  delete

Note : also i have to move the rows which will be deleted to output tape file before deleting to take backup.

Have come up with the below logic,
Declaring cursor :

EXEC SQL
  DECLARE CUR1 CURSOR WITH HOLD FOR
   SELECT * FROM PHONE_TAB WHERE PHONE_NUM = 45678
END-EXEC

FETCH-PARA

EXEC SQL
 FETCH CUR1 INTO :DCLGEN_CLIENT_ID
                :DCLGEN_PHONE_NUM
                :DCLGEN_SEQ_NUM
END-EXEC

VALIDATE-PARA

EXEC SQL
 SELECT MIN(SEQ_NUM) FROM PHONE_TAB
 WHERE CLIENT_ID = :DCLGEN_CLIENT_ID
       PHONE_NUM = :DCLGEN_PHONE_NUM GROUP BY CLIENT_ID AND PHONE_NUM
       INTO WS_MIN
END-EXEC

EVALUATE TRUE
 WHEN SEQ_NUM > WS_MIN
      PERFORM BACKUP-PARA
 WHEN OTHER
      PERFORM FETCH-PARA

Finally , DELETE-PARA

EXEC SQL
  DELETE FROM PHONE_TAB WHERE CURRENT CURSOR
END-EXEC

Can someone tell me whether this logic is right ?
My doubt is whether it will do mass deletion without taking backup to tape file?

Thanks

Body:
You can delete them all in one go with the following SQL

DELETE FROM PHONE_TAB A
 WHERE EXISTS (SELECT 1 FROM PHONE_TAB B
                WHERE A.PHONE_NUM = B.PHONE_NUM AND
                      A.SEQ_NUM > B.SEQ_NUM)

It works by deleting all rows where another row exists that has the same phone number and a lower sequence number.

You can check that it deletes the right rows by first running it with a select, like this

SELECT * FROM PHONE_TAB A
 WHERE EXISTS (SELECT 1 FROM PHONE_TAB B
                WHERE A.PHONE_NUM = B.PHONE_NUM AND
                      A.SEQ_NUM > B.SEQ_NUM)

If you need to backup the rows, you can run the select and then delete the rows.


问:
"Symbol not found" error, (possibly) due to recent upgrade to R2017b?
I'm getting an error when I try to use imerode() from the command line, e.g.

```<code>test=magic([100 100])>200;
imclose(test,strel('disk',10,0));
</code>```

I get this error:

Error using images.internal.morphmex Invalid MEX-file
  '/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64':
  dlopen(/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64,
  6): Symbol not found: _OSAtomicDecrement32Barrier   Referenced from:
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib

  Expected in: /usr/lib/libSystem.B.dylib  in
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib.

Error in images.internal.morphop (line 103)
          B = images.internal.morphmex(mex_method, B, nhood, height, unpacked_M);

Error in imdilate (line 135) B =
  images.internal.morphop(A,se,'dilate',mfilename,varargin{:});

Error in imclose (line 82)
      outputImage = imerode(imdilate(inputImage,se,packopt,M),se,packopt,M);

I'm on OS X 10.9.5, with MATLAB R2017b.
I've checked that morphmex.mexmaci64 is there in the given path (above).
Not sure where /./ refers to, but libcudart.8.0.dylib is in maci64 folder.
Not sure where /usr/lib/... is.

EDIT

I have uninstalled R2017b and installed R2017a (why not, just in case...) and when trying to run the same code, I now get this error (which seems worse...)

       Segmentation violation detected at Mon Nov 13 13:44:29 2017

Configuration:   Crash Decoding      : Disabled - No sandbox or build
  area path   Crash Mode          : continue (default)   Current
  Graphics Driver: Unknown hardware    Current Visual      : Quartz

  Default Encoding    : ISO-8859-1   Deployed            : false   Host
  Name           : eduroam-206-52.nomadic.bris.ac.uk   MATLAB
  Architecture : maci64   MATLAB Entitlement ID: 1803495   MATLAB Root

  : /Applications/MATLAB_R2017a.app   MATLAB Version      : 9.2.0.556344
  (R2017a)   OpenGL              : hardware   Operating System    :
  Darwin 13.4.0 Darwin Kernel Version 13.4.0: Mon Jan 11 18:17:34 PST
  2016; root:xnu-2422.115.15~1/RELEASE_X86_64 x86_64   Processor ID

  : x86 Family 6 Model 69 Stepping 1, GenuineIntel   Virtual Machine

  : Java 1.7.0_75-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit
  Server VM mixed mode   Window System       : Quartz

Fault Count: 2

Abnormal termination: Trace trap

Can upload error file for rest of message (too long to paste here).

Thanks in advance.

答:
Looks like an installation problem or maybe it is due to the update.

Try to run the following commands in your console:

```<code>restoredefaultpath();
rehash toolboxcache;
</code>```

If everything works without errors, then run:

```<code>savepath();
</code>```

Body:
I'm getting an error when I try to use imerode() from the command line, e.g.

test=magic([100 100])>200;
imclose(test,strel('disk',10,0));

I get this error:

Error using images.internal.morphmex Invalid MEX-file
  '/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64':
  dlopen(/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64,
  6): Symbol not found: _OSAtomicDecrement32Barrier   Referenced from:
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib

  Expected in: /usr/lib/libSystem.B.dylib  in
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib.

Error in images.internal.morphop (line 103)
          B = images.internal.morphmex(mex_method, B, nhood, height, unpacked_M);

Error in imdilate (line 135) B =
  images.internal.morphop(A,se,'dilate',mfilename,varargin{:});

Error in imclose (line 82)
      outputImage = imerode(imdilate(inputImage,se,packopt,M),se,packopt,M);

I'm on OS X 10.9.5, with MATLAB R2017b.
I've checked that morphmex.mexmaci64 is there in the given path (above).
Not sure where /./ refers to, but libcudart.8.0.dylib is in maci64 folder.
Not sure where /usr/lib/... is.

EDIT

I have uninstalled R2017b and installed R2017a (why not, just in case...) and when trying to run the same code, I now get this error (which seems worse...)

       Segmentation violation detected at Mon Nov 13 13:44:29 2017

Configuration:   Crash Decoding      : Disabled - No sandbox or build
  area path   Crash Mode          : continue (default)   Current
  Graphics Driver: Unknown hardware    Current Visual      : Quartz

  Default Encoding    : ISO-8859-1   Deployed            : false   Host
  Name           : eduroam-206-52.nomadic.bris.ac.uk   MATLAB
  Architecture : maci64   MATLAB Entitlement ID: 1803495   MATLAB Root

  : /Applications/MATLAB_R2017a.app   MATLAB Version      : 9.2.0.556344
  (R2017a)   OpenGL              : hardware   Operating System    :
  Darwin 13.4.0 Darwin Kernel Version 13.4.0: Mon Jan 11 18:17:34 PST
  2016; root:xnu-2422.115.15~1/RELEASE_X86_64 x86_64   Processor ID

  : x86 Family 6 Model 69 Stepping 1, GenuineIntel   Virtual Machine

  : Java 1.7.0_75-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit
  Server VM mixed mode   Window System       : Quartz

Fault Count: 2

Abnormal termination: Trace trap

Can upload error file for rest of message (too long to paste here).

Thanks in advance.

Body:
Looks like an installation problem or maybe it is due to the update.

Try to run the following commands in your console:

restoredefaultpath();
rehash toolboxcache;

If everything works without errors, then run:

savepath();


答:
Try running it backwards instead</p>

```<code>Sub InsertColumnsv2()
    Dim iLastCol As Long
    Dim colx As Long

    iLastCol = Cells(1, Columns.Count).End(xlToLeft).Column

    For colx = iLastCol To 4 Step -1
        Columns(colx).Insert Shift:=xlToRight
    Next colx
End Sub
</code>```

Title: VBA : Insert new column to the left of all columns up until the last column

Body:
I'm trying to insert a column next to each column starting from D, my issue is that the number of columns will change so I need to identify the last column within the code.

Whenever I run the below it doesn't seem to be identifying the last column correctly.

Sub InsertColumnsv2()
  Dim iLastCol As Long
  Dim StartCell As Range

  Set StartCell = Range("A1")

  iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column

  For colx = 4 To iLastCol Step 2
    ActiveSheet.UsedRange
    iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
    Columns(colx).Insert Shift:=xlToRight
  Next colx
End Sub

Body:
Try running it backwards instead

Sub InsertColumnsv2()
    Dim iLastCol As Long
    Dim colx As Long

    iLastCol = Cells(1, Columns.Count).End(xlToLeft).Column

    For colx = iLastCol To 4 Step -1
        Columns(colx).Insert Shift:=xlToRight
    Next colx
End Sub


问:
Detect GPS in case if Disabled
I want to detect user trip and when trip is started, I have to get LatLng in every 5 seconds. I am using Google FusedLocationAPI and My problem is until My GPS is enabled then its calculating all distance but Once I disabled GPS the its stucked. How can I Show pending trip if user Disabled GPS in mid of trip ?

My Service class is :

```<code>public class TripStartedService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static long UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 5;
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    public GoogleApiClient mGoogleApiClient;
    public LocationRequest mLocationRequest;

    private PendingIntent mPendingIntent;
    IBinder mBinder = new TripStartedService.LocalBinder();
    public static boolean isGPSOn = false;

    @Override
    public void onCreate() {
        super.onCreate();
        Intent mIntentService = new Intent(this, TripStartedIntent.class);
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i("", "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }

    private void createLocationRequest() {
        Log.i("TRIP_START_Request", "createLocationRequest()");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("", "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {
        String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy();
        Log.i("", "onLocationChanged: " + message);
    }

    private void startLocationUpdates() {
        Log.i("", "Started Location Updates");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isGPSOn = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (mGoogleApiClient.isConnected()) {
            Log.i("GPS init" + " onStartCmd", "Connected");
            return START_STICKY;
        }

        if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
            Log.i("Connceti" + " onStartCmd", "GoogleApiClient not Connected");
            mGoogleApiClient.connect();
        }

        return START_STICKY;
    }

    private class LocalBinder extends Binder {
        public TripStartedService getServerInstance() {
            return TripStartedService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    public void stopLocationUpdates() {
        Log.i("", "Stopped Location Updates");
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
    }
}
</code>```

And My Calculation Class is

```<code> if (isGPSOn) {

            try {
                LocDatabaseHelper database = new LocDatabaseHelper(activity);
                Timestamp timestamp_start = new Timestamp(System.currentTimeMillis());
                Timestamp timestamp_end = new Timestamp(System.currentTimeMillis());

                final int TRIP_START_ID = 0;
                ContentValues contentValues = new ContentValues();

                final ArrayList<TripDistanceModels> trip_list_values = database.getTripDistance();

                try {
                    Location loc1 = new Location("");
                    loc1.setLatitude(Double.parseDouble(trip_list_values.get(0).getLatitude()));
                    loc1.setLongitude(Double.parseDouble(trip_list_values.get(0).getLongitude()));

                    Location loc2 = new Location("");
                    loc2.setLatitude(Double.parseDouble(trip_list_values.get(1).getLatitude()));
                    loc2.setLongitude(Double.parseDouble(trip_list_values.get(1).getLongitude()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                contentValues.put(TRIP_STARTED_ID, TRIP_START_ID);
                contentValues.put(TRIP_STARTED_LATTITUDE, start_trip_location.getLatitude());
                contentValues.put(TRIP_STARTED_LONGITUDE, start_trip_location.getLongitude());
                contentValues.put(TRIP_STARTED_TIMESTAMP, String.valueOf(timestamp_start));
                contentValues.put(TRIP_END_TIMESTAMP, String.valueOf(timestamp_end));
                database.tripInsertionOnDetect(TRIP_START_ID, start_trip_location.getLatitude(), start_trip_location.getLongitude(), timestamp_start, timestamp_end, "pending status");
                Log.d("TRIP STARTRED", contentValues.toString());

                final int trip_counts = database.getRowCountForTripStarted();
                final int back_counts = database.getRowCountForBackground();
                Log.e("TRip Database Rows Size", "" + trip_counts + "\t \tBackGroundTable Rows : " + back_counts + "\tGPS>>>: " + Boolean.toString(isGPSOn));
                activity.stopService(new Intent(activity, BackgroundLocationService.class));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
</code>```

答:
You should add a broadcast receiver to detect if the gps is enabled or disable : </p>

```<code>   private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
                LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {

                    if (isGpsEnabled) {
                        //Here code when gps is enabled

                    } else {
                        //Here code when gps is disabled

                    }
                }
            }
        }
    };
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        registerReceiver(gpsReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
       //here other code ...
        return super.onStartCommand(intent, flags, startId);
    }
</code>```

Title: Detect GPS in case if Disabled

Body:
I want to detect user trip and when trip is started, I have to get LatLng in every 5 seconds. I am using Google FusedLocationAPI and My problem is until My GPS is enabled then its calculating all distance but Once I disabled GPS the its stucked. How can I Show pending trip if user Disabled GPS in mid of trip ?

My Service class is :

public class TripStartedService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static long UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 5;
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    public GoogleApiClient mGoogleApiClient;
    public LocationRequest mLocationRequest;

    private PendingIntent mPendingIntent;
    IBinder mBinder = new TripStartedService.LocalBinder();
    public static boolean isGPSOn = false;

    @Override
    public void onCreate() {
        super.onCreate();
        Intent mIntentService = new Intent(this, TripStartedIntent.class);
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i("", "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }

    private void createLocationRequest() {
        Log.i("TRIP_START_Request", "createLocationRequest()");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("", "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {
        String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy();
        Log.i("", "onLocationChanged: " + message);
    }

    private void startLocationUpdates() {
        Log.i("", "Started Location Updates");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isGPSOn = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (mGoogleApiClient.isConnected()) {
            Log.i("GPS init" + " onStartCmd", "Connected");
            return START_STICKY;
        }

        if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
            Log.i("Connceti" + " onStartCmd", "GoogleApiClient not Connected");
            mGoogleApiClient.connect();
        }

        return START_STICKY;
    }

    private class LocalBinder extends Binder {
        public TripStartedService getServerInstance() {
            return TripStartedService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    public void stopLocationUpdates() {
        Log.i("", "Stopped Location Updates");
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
    }
}

And My Calculation Class is

 if (isGPSOn) {

            try {
                LocDatabaseHelper database = new LocDatabaseHelper(activity);
                Timestamp timestamp_start = new Timestamp(System.currentTimeMillis());
                Timestamp timestamp_end = new Timestamp(System.currentTimeMillis());

                final int TRIP_START_ID = 0;
                ContentValues contentValues = new ContentValues();

                final ArrayList<TripDistanceModels> trip_list_values = database.getTripDistance();

                try {
                    Location loc1 = new Location("");
                    loc1.setLatitude(Double.parseDouble(trip_list_values.get(0).getLatitude()));
                    loc1.setLongitude(Double.parseDouble(trip_list_values.get(0).getLongitude()));

                    Location loc2 = new Location("");
                    loc2.setLatitude(Double.parseDouble(trip_list_values.get(1).getLatitude()));
                    loc2.setLongitude(Double.parseDouble(trip_list_values.get(1).getLongitude()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                contentValues.put(TRIP_STARTED_ID, TRIP_START_ID);
                contentValues.put(TRIP_STARTED_LATTITUDE, start_trip_location.getLatitude());
                contentValues.put(TRIP_STARTED_LONGITUDE, start_trip_location.getLongitude());
                contentValues.put(TRIP_STARTED_TIMESTAMP, String.valueOf(timestamp_start));
                contentValues.put(TRIP_END_TIMESTAMP, String.valueOf(timestamp_end));
                database.tripInsertionOnDetect(TRIP_START_ID, start_trip_location.getLatitude(), start_trip_location.getLongitude(), timestamp_start, timestamp_end, "pending status");
                Log.d("TRIP STARTRED", contentValues.toString());

                final int trip_counts = database.getRowCountForTripStarted();
                final int back_counts = database.getRowCountForBackground();
                Log.e("TRip Database Rows Size", "" + trip_counts + "\t \tBackGroundTable Rows : " + back_counts + "\tGPS>>>: " + Boolean.toString(isGPSOn));
                activity.stopService(new Intent(activity, BackgroundLocationService.class));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

Body:
You should add a broadcast receiver to detect if the gps is enabled or disable :

   private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
                LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {

                    if (isGpsEnabled) {
                        //Here code when gps is enabled

                    } else {
                        //Here code when gps is disabled

                    }
                }
            }
        }
    };
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        registerReceiver(gpsReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
       //here other code ...
        return super.onStartCommand(intent, flags, startId);
    }


问:
JMeter read the second sheet of CSV
How can I make JMeter read the second sheet of my CSV?

I want to use CSV Data Set Config.

Normally, it reads the first line of the first sheet but is there any way to be a bit more flexible?

答:
CSV file format doesn't have "sheets", it is a normal plain text file using delimiters in order to represent structured data.

If you are trying to get data from i.e. Microsoft Excel file type - unfortunately you won't be able to do it using CSV Data Set Config. The easiest would be exporting data as separate plain-text CSV files.

If you don't have the possibility to do the export you still can access the data from Excel files but it will be a little bit more tricky as you will have to use JSR223 Test Elements, Groovy language and Apache POI libraries

More information:

Busy Developers' Guide to HSSF and XSSF Features

How to Extract Data From Files With JMeter

Title: JMeter read the second sheet of CSV


问:
Parse nested data using SCALA
I have the dataframe as follows :

```<code>ColA  ColB     ColC
1     [2,3,4] [5,6,7]
</code>```

I need to convert it to the below

```<code>ColA ColB ColC
1    2    5
1    3    6
1    4    7
</code>```

Can someone please help with the Code in SCALA?

答:
You can also use a combination of posexplode and lateral view from HiveQL

```<code>sqlContext.sql("""
select 1 as colA, array(2,3,4) as colB, array(5,6,7) as colC
""").registerTempTable("test")

sqlContext.sql("""
select
    colA , b as colB, c as colC
from
    test
lateral view
    posexplode(colB) columnB as seqB, b
lateral view
    posexplode(colC) columnC as seqC, c
where
    seqB = seqC
""" ).show

+----+----+----+
|colA|colB|colC|
+----+----+----+
|   1|   2|   5|
|   1|   3|   6|
|   1|   4|   7|
+----+----+----+
</code>```

 Credits: https://stackoverflow.com/a/40614822/7224597 ;)

Title: Parse nested data using SCALA

Body:
I have the dataframe as follows :

ColA  ColB     ColC
1     [2,3,4] [5,6,7]

I need to convert it to the below

ColA ColB ColC
1    2    5
1    3    6
1    4    7

Can someone please help with the Code in SCALA?

Body:
You can also use a combination of posexplode and lateral view from HiveQL

sqlContext.sql("""
select 1 as colA, array(2,3,4) as colB, array(5,6,7) as colC
""").registerTempTable("test")

sqlContext.sql("""
select
    colA , b as colB, c as colC
from
    test
lateral view
    posexplode(colB) columnB as seqB, b
lateral view
    posexplode(colC) columnC as seqC, c
where
    seqB = seqC
""" ).show

+----+----+----+
|colA|colB|colC|
+----+----+----+
|   1|   2|   5|
|   1|   3|   6|
|   1|   4|   7|
+----+----+----+

 Credits: https://stackoverflow.com/a/40614822/7224597 ;)


问:
Display incoming xml request in Rails
Hey guys,
Is there an easy way to display the complete xml request I'm getting posted to one of my methods?
Thanks a lot</p>

答:
I'm inferring a bit, but you probably want request.body.

An easy, though slightly dirty, way to view it is to raise it as an error in your controller: raise request.body

Title: Display incoming xml request in Rails


问:
What to do with the dead thread (not a deadlock)?
In our application there is a subsystem listening for file system changes, including those over the network. Sometimes, probably when the network is under stress, a listening thread can get stuck. I emphasize, that the discussion here is not about deadlock caused by incorrect thread synchronization. Thread get stuck either in a very first call to CreateFile, or in a subsequent call to File System API. The question is, what to do with such a thread.

I can determine that a given thread is inactive during some period of time, and to terminate it. But authoritative people say it is very bad, though I do not understand why to keep a dead thread is better than to terminate it. Then I thought, that I could at least release some resources allocated in the thread, for example, file handles.

So I created a thread-cleaner, which closes file handles and frees memory allocated by the dead thread. But soon I was amazed to find, that the cleaner thread got stuck itself in a call to CloseHandle API. I was really shocked, since I was sure that CloseHandle cannot get stuck.

Now I'm completely at a loss, because if the application continues to work long enough, and the network or part of it still has problems, then I can end up with many dead threads, holding a lot of system resources!

答:
"Thread.Sleep(0) is occasionally useful in production code for
  advanced performance tweaks. It's also an excellent diagnostic tool
  for helping to uncover thread safety issues: if inserting
  Thread.Sleep(0) anywhere in your code makes or breaks the program, you
  almost certainly have a bug."

see https://msdn.microsoft.com/en-us/library/orm-9780596527570-03-19.aspx


问:
AnyLogic: Calculating the sum of all values in a collection
I have an agent-based simulation where I have a collection called collection_dailyInfection which has the numbers of new infections that arise on a daily basis. The collection looks a bit like this:

Day 1: 0

Day 2: 3

Day 4: 3

Day 5: 6

Day 6: 1

.  .  .

I'm now trying to write a function that adds up the total number of infections on any particular day. For example: on Day 6- total infections = 0+3+3+6+1 = 13.

The syntax for calculating the sum is:
double sum( collection, value ) - Returns the sum of values in the given collection.

For my particular example, this would be double sum( collection_dailyInfection, *value*), but I'm not sure what I should put in the 'value' argument. Could some help me out please?

答:
Value should be an integer, It will denote that day till which you want the total number of infections.

For example in this case the value of value should be 6. Since you want to the total number of infections till 6th day.

Here is a working demo of what you wanted

```<code>import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{

    public static void main (String[] args) throws java.lang.Exception
    {
        ArrayList<Integer> list;
        Scanner sc=new Scanner(System.in);
        list=new ArrayList<Integer>();  /* this list will hold all the values*/
        int total=sc.nextInt(); /* total number of values in the list */
        int value=sc.nextInt(); /* the day till which you want the total infection */

        for(int i=0;i<total;i++)  /*taking input in the list */
            list.add(sc.nextInt());

        double sum=calculateSum(list,value); /* function to compute sum*/

        System.out.println(sum);
    }

    static double calculateSum(ArrayList<Integer> list,int value)
    {
        double sum=0.0;
        for(int j=0;j<value;j++) /* calculates sum from day 1 till value*/
            sum=sum+list.get(j);
        return sum;
    }

}
</code>```

Body:
Value should be an integer, It will denote that day till which you want the total number of infections.

For example in this case the value of value should be 6. Since you want to the total number of infections till 6th day.

Here is a working demo of what you wanted

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{

    public static void main (String[] args) throws java.lang.Exception
    {
        ArrayList<Integer> list;
        Scanner sc=new Scanner(System.in);
        list=new ArrayList<Integer>();  /* this list will hold all the values*/
        int total=sc.nextInt(); /* total number of values in the list */
        int value=sc.nextInt(); /* the day till which you want the total infection */

        for(int i=0;i<total;i++)  /*taking input in the list */
            list.add(sc.nextInt());

        double sum=calculateSum(list,value); /* function to compute sum*/

        System.out.println(sum);
    }

    static double calculateSum(ArrayList<Integer> list,int value)
    {
        double sum=0.0;
        for(int j=0;j<value;j++) /* calculates sum from day 1 till value*/
            sum=sum+list.get(j);
        return sum;
    }

}


问:
Proper way to instantiate an NSDecimalNumber from float or double
I'm looking for the best way to instantiate an NSDecimalNumber from a double or short.  There are the following NSNumber class and instance methods...

```<code>+NSNumber numberWithFloat
+NSNumber numberWithDouble
-NSNumber initWithFloat
-NSNumber initWithDouble
</code>```

but these appear to return NSNumber.  On the other side, NSDecimalNumber defines the following:

```<code>+NSDecimalNumber decimalNumberWithMantissa:exponent:isNegative:
+NSDecimalNumber decimalNumberWithDecimal:
</code>```

There are a few possibilities here on which way to go.  Xcode generates a warning if you have a NSDecimalNumber set to the return value of the NSNumber convenience methods above.

Would appreciate input on the cleanest and correct way to go...

答:
Or may be you could define a macro to shorten code</p>

```<code>#define DECIMAL(x) [[NSDecimalNumber alloc]initWithDouble:x]

budget.amount = DECIMAL(5000.00);
</code>```

Body:
I'm looking for the best way to instantiate an NSDecimalNumber from a double or short.  There are the following NSNumber class and instance methods...

+NSNumber numberWithFloat
+NSNumber numberWithDouble
-NSNumber initWithFloat
-NSNumber initWithDouble

but these appear to return NSNumber.  On the other side, NSDecimalNumber defines the following:

+NSDecimalNumber decimalNumberWithMantissa:exponent:isNegative:
+NSDecimalNumber decimalNumberWithDecimal:

There are a few possibilities here on which way to go.  Xcode generates a warning if you have a NSDecimalNumber set to the return value of the NSNumber convenience methods above.

Would appreciate input on the cleanest and correct way to go...

Body:
Or may be you could define a macro to shorten code

#define DECIMAL(x) [[NSDecimalNumber alloc]initWithDouble:x]

budget.amount = DECIMAL(5000.00);


问:
How to scroll horizontal linearly from right to left on mouse wheel?
I have more than 6 articles and First I have to display 3 articles and when the user scrolls the mouse wheel than it linearly scrolls from right to left side.
Even I also want to hide the scrollbar.

Would you help me out in this?

I tried code but the same issue. Please check it.

jQuery(function ($) {
    $.fn.hScroll = function (amount) {
        amount = amount || 120;
        $(this).bind("DOMMouseScroll mousewheel", function (event) {
            var oEvent = event.originalEvent,
                direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta,
                position = $(this).scrollLeft();
            position += direction > 0 ? -amount : amount;
            $(this).scrollLeft(position);
            event.preventDefault();
        })
    };
});

$(document).ready(function() {
    $('.full_screen_100').hScroll(60); // You can pass (optionally) scrolling amount
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.horizontal_scroll .full_screen_100
{
 width: 100%;
 background-color: #fff;
   overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px;
}
.horizontal_scroll .full_screen_100 article{
 width: 33%;
 height: 100%;
  display: inline-block;
  border-left: solid 1px #E2E2E2;
   display: table-cell;

}
#left_scroll{
 overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px
}</code>```

01
Lorem ipsum dolor sit amet,

02
Lorem ipsum dolor sit amet,

03
Lorem ipsum dolor sit amet,

04
Lorem ipsum dolor sit amet,

05
Lorem ipsum dolor sit amet,

06
Lorem ipsum dolor sit amet,

答:
Vanilla JS

(function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gentags {
position:relative;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow-x: scroll;
overflow-y: hidden;
}

#gentags > div{
    overflow: hidden;
    width:200%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 16.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}</code>```

01
Lorem ipsum dolor sit amet,

02
Lorem ipsum dolor sit amet,

03
Lorem ipsum dolor sit amet,

04
Lorem ipsum dolor sit amet,

05
Lorem ipsum dolor sit amet,

06
Lorem ipsum dolor sit amet,

```

Body:
I have more than 6 articles and First I have to display 3 articles and when the user scrolls the mouse wheel than it linearly scrolls from right to left side.
Even I also want to hide the scrollbar.

Would you help me out in this?

I tried code but the same issue. Please check it.

jQuery(function ($) {
    $.fn.hScroll = function (amount) {
        amount = amount || 120;
        $(this).bind("DOMMouseScroll mousewheel", function (event) {
            var oEvent = event.originalEvent,
                direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta,
                position = $(this).scrollLeft();
            position += direction > 0 ? -amount : amount;
            $(this).scrollLeft(position);
            event.preventDefault();
        })
    };
});

$(document).ready(function() {
    $('.full_screen_100').hScroll(60); // You can pass (optionally) scrolling amount
});

.horizontal_scroll .full_screen_100
{
 width: 100%;
 background-color: #fff;
   overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px;
}
.horizontal_scroll .full_screen_100 article{
 width: 33%;
 height: 100%;
  display: inline-block;
  border-left: solid 1px #E2E2E2;
   display: table-cell;

}
#left_scroll{
 overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px
}

01
Lorem ipsum dolor sit amet,

02
Lorem ipsum dolor sit amet,

03
Lorem ipsum dolor sit amet,

04
Lorem ipsum dolor sit amet,

05
Lorem ipsum dolor sit amet,

06
Lorem ipsum dolor sit amet,

Body:
Vanilla JS

(function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();

#gentags {
position:relative;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow-x: scroll;
overflow-y: hidden;
}

#gentags > div{
    overflow: hidden;
    width:200%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 16.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}

<div id="gentags">
<div class="horizontal_scroll">
  <div class="full_screen_100" id="left_scroll">
   <article><div><p class="scroll_number">01</p><span class="page_slogan">Lorem ipsum dolor sit amet, </span></div></article>
   <article><div><p class="scroll_number">02</p><span class="page_slogan">Lorem ipsum dolor sit amet, </span></div></article>
   <article><div><p class="scroll_number">03</p><span class="page_slogan">Lorem ipsum dolor sit amet, </span></div></article>
   <article><div><p class="scroll_number">04</p><span class="page_slogan">Lorem ipsum dolor sit amet, </span></div></article>
   <article><div><p class="scroll_number">05</p><span class="page_slogan">Lorem ipsum dolor sit amet, </span></div></article>
   <article><div><p class="scroll_number">06</p><span class="page_slogan">Lorem ipsum dolor sit amet, </span></div></article>
 </div>
</div>
</div>


问:
React Js: Uncaught (in promise) SyntaxError:
I am trying to do a POST request through fetch in reactjs. I went through some docs but my error not solved.Can anyone please help me out?

Here is my reactjs code:

```<code> handleSubmit(e) {
       e.preventDefault();
       var self = this;

       const payload = {
       id: 111,
       studentName: 'param',
       age: 24,
       emailId: 2
    };
    fetch({
       method: 'POST',
       url: 'http://localhost:8083/students',
       body: payload,
       headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
     })
       .then(function(response) {
           return response.json()
         }).then(function(body) {
           console.log(body);
         });
     }

  }
</code>```

If any one familiar with reactjs, just give a simple example how to call post request.Either by using fetch or axios.

答:
Well I answered a similar question just now. here.

Well the great thing about React is that it's just Javascript.

So all you need is something to do a POST do your server!

You can use the native fetch function or a full-on library like axios

Examples using both could be:

```<code>// Using ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();
</code>```

```<code>// Using normal promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };
</code>```

```<code>// AXIOS example straight from their Github
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do a POST request through fetch in reactjs. I went through some docs but my error not solved.Can anyone please help me out?

Here is my reactjs code:

 handleSubmit(e) {
       e.preventDefault();
       var self = this;

       const payload = {
       id: 111,
       studentName: 'param',
       age: 24,
       emailId: 2
    };
    fetch({
       method: 'POST',
       url: 'http://localhost:8083/students',
       body: payload,
       headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
     })
       .then(function(response) {
           return response.json()
         }).then(function(body) {
           console.log(body);
         });
     }

  }

If any one familiar with reactjs, just give a simple example how to call post request.Either by using fetch or axios.

Body:
Well I answered a similar question just now. here.

Well the great thing about React is that it's just Javascript.

So all you need is something to do a POST do your server!

You can use the native fetch function or a full-on library like axios

Examples using both could be:

// Using ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();

// Using normal promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };

// AXIOS example straight from their Github
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


问:
MySQL count value by ID
Not sure if the title explains what I am trying to do correctly however I was unable to word it.

I am trying to create an output for a some graphs. The output I am aiming for is just the total value of some rows in a mySQL table grouped by a category ID. My tables are as follows:

```<code>Transactions:

TransactiondID | TransactionName |TransactionCategory| Value
*************************************************************
       1       |  GenericText1   |      1            | 30
       2       |  GenericText2   |      1            | 38
       3       |  GenericText2   |      2            | 38
</code>```

And my Reference Data for TransactionCategory

```<code>TranCatID | TransCatName
*************************
    1     | Tranportation
    2     | Petrol
</code>```

So what I want to do is do is a SUM of the value field by each category. So I would get an output of.

```<code>Category       | Value
****************************
Transportation | 68
Petrol         | 30
</code>```

I got this but it does not work. I think it is completely incorrect but wanted to show my attempt.

```<code>SELECT SUM( `TransactionValue`) AS Value,
transaction_category.transaction_category
FROM Transactions
JOIN transaction_category on Transactions.TransactionID = transaction_category_id
</code>```

答:
You can use this :

```<code>SELECT tc.TransCatName Category, SUM(t.Value) as Value
FROM TransactionCategory tc
LEFT JOIN Transactions t ON tc.TranCatID = t.TransactionCategory
group by tc.TransCatName
</code>```

SQL HERE

OUTPUT

```<code>Category       | Value
-----------------------
Petrol         | 38
Transportation | 68
</code>```

Please notice the SUM for PETROL, it should 38 as above, which is wrongly written 30 in your question description!

Title: MySQL count value by ID

Body:
Not sure if the title explains what I am trying to do correctly however I was unable to word it.

I am trying to create an output for a some graphs. The output I am aiming for is just the total value of some rows in a mySQL table grouped by a category ID. My tables are as follows:

Transactions:

TransactiondID | TransactionName |TransactionCategory| Value
*************************************************************
       1       |  GenericText1   |      1            | 30
       2       |  GenericText2   |      1            | 38
       3       |  GenericText2   |      2            | 38

And my Reference Data for TransactionCategory

TranCatID | TransCatName
*************************
    1     | Tranportation
    2     | Petrol

So what I want to do is do is a SUM of the value field by each category. So I would get an output of.

Category       | Value
****************************
Transportation | 68
Petrol         | 30

I got this but it does not work. I think it is completely incorrect but wanted to show my attempt.

SELECT SUM( `TransactionValue`) AS Value,
transaction_category.transaction_category
FROM Transactions
JOIN transaction_category on Transactions.TransactionID = transaction_category_id

Body:
You can use this :

SELECT tc.TransCatName Category, SUM(t.Value) as Value
FROM TransactionCategory tc
LEFT JOIN Transactions t ON tc.TranCatID = t.TransactionCategory
group by tc.TransCatName

SQL HERE

OUTPUT

Category       | Value
-----------------------
Petrol         | 38
Transportation | 68

Please notice the SUM for PETROL, it should 38 as above, which is wrongly written 30 in your question description!


问:
Question about styling Navbar tabs in css (Wordpress)
I'm trying to style navbar tabs. I have two pieces of code that work, but I need more control over the individual tabs and not sure how to do it.

These tabs are under the header and at the far right. And I'm trying to round the bottom left corner of only the first tab. The two code snippets below both round the bottom left of every tab in the nav bar.

I'd like to figure out the proper code that would give me control over each tab and allow me to style each tab individually. The 2 snippets below get me halfway there, just not sure which is better to be improved on or what to add.

```<code>.custom .menu, .custom .menu a, .custom .menu li ul {
-moz-border-radius-bottomleft:.5em; font-weight:bold;
-webkit-border-bottom-left-radius:.5em; font-weight:bold;
-moz-border-radius-bottomright:.0em;
-webkit-border-bottom-right-radius:.0em;}
</code>```

Or this:

```<code>/* Remove the border from the far left. */
ul.menu{border-left:0;}

/* Add the left border back in. If you change the color of the nav border in the WordPress admin panel, you will also have to manually change the left border color below. */
ul.menu li.tab-1 a{
    border-left:1px solid #CCC;
    -moz-border-radius-topleft:.5em;
    -webkit-border-top-left-radius:.5em;}

/* This creates the rounded borders. */
ul.menu li.tab a{
    -moz-border-radius-bottomleft:.5em; font-weight:bold;
    -webkit-border-bottom-left-radius:.5em; font-weight:bold;
    -moz-border-radius-topright:.0em;
    -webkit-border-top-right-radius:.0em;}
</code>```

Thanks for any help

答:
You might be over-engineering here - have you considered using the CSS :first-child pseudoclass? Failing that, how about rounding the bottom left of the
 rather than the first
? From what you've explained, both of these would achieve your desired results without writing a line of PHP.

Body:
I'm trying to style navbar tabs. I have two pieces of code that work, but I need more control over the individual tabs and not sure how to do it.

These tabs are under the header and at the far right. And I'm trying to round the bottom left corner of only the first tab. The two code snippets below both round the bottom left of every tab in the nav bar.

I'd like to figure out the proper code that would give me control over each tab and allow me to style each tab individually. The 2 snippets below get me halfway there, just not sure which is better to be improved on or what to add.

.custom .menu, .custom .menu a, .custom .menu li ul {
-moz-border-radius-bottomleft:.5em; font-weight:bold;
-webkit-border-bottom-left-radius:.5em; font-weight:bold;
-moz-border-radius-bottomright:.0em;
-webkit-border-bottom-right-radius:.0em;}

Or this:

/* Remove the border from the far left. */
ul.menu{border-left:0;}

/* Add the left border back in. If you change the color of the nav border in the WordPress admin panel, you will also have to manually change the left border color below. */
ul.menu li.tab-1 a{
    border-left:1px solid #CCC;
    -moz-border-radius-topleft:.5em;
    -webkit-border-top-left-radius:.5em;}

/* This creates the rounded borders. */
ul.menu li.tab a{
    -moz-border-radius-bottomleft:.5em; font-weight:bold;
    -webkit-border-bottom-left-radius:.5em; font-weight:bold;
    -moz-border-radius-topright:.0em;
    -webkit-border-top-right-radius:.0em;}

Thanks for any help

Body: You might be over-engineering here - have you considered using the CSS :first-child pseudoclass? Failing that, how about rounding the bottom left of the <ul> rather than the first <li>? From what you've explained, both of these would achieve your desired results without writing a line of PHP.


问:
Laravel displaying many to many relationship items
I have set up a many to many relationship in Laravel and have the database table populated with data.  The relationship setup looks like this...

```<code>users.php
---------
   public function houses()
    {
        return $this->belongsToMany('App\House')
        ->withTimestamps();
    }

house.php
---------
public function users()
    {
        return $this->belongsToMany('App\User')
        ->withTimestamps();
    }
</code>```

In my /house/show.blade.php I am trying to display the saved connections like this...

```<code>$houses = House::with('App\User')->all();

foreach ($houses as $house) {
    echo 'Found House';
}
</code>```

It is giving me an error saying that $houses can not be found.  Where am I going wrong?

答:
You should try this:

```<code>$houses = House::with('users')->get();

foreach ($houses as $house) {
    echo 'Found House';
}
</code>```

OR

In controller:

```<code>use House;

$houses = House::with('users')->get();
return view('someView',compact('houses'));
</code>```

In Blade file:

```<code>@foreach ($houses as $house)
    {{ $house->name }}
@endforeach
</code>```

Body:
I have set up a many to many relationship in Laravel and have the database table populated with data.  The relationship setup looks like this...

users.php
---------
   public function houses()
    {
        return $this->belongsToMany('App\House')
        ->withTimestamps();
    }

house.php
---------
public function users()
    {
        return $this->belongsToMany('App\User')
        ->withTimestamps();
    }

In my /house/show.blade.php I am trying to display the saved connections like this...

$houses = House::with('App\User')->all();

foreach ($houses as $house) {
    echo 'Found House';
}

It is giving me an error saying that $houses can not be found.  Where am I going wrong?

Body:
You should try this:

$houses = House::with('users')->get();

foreach ($houses as $house) {
    echo 'Found House';
}

OR

In controller:

use House;

$houses = House::with('users')->get();
return view('someView',compact('houses'));

In Blade file:

@foreach ($houses as $house)
    {{ $house->name }}
@endforeach


问:
How to import a text file with multiple layouts into SQL with SSIS
I'm fairly new to SSIS, any help would be much appreciated!

I need to import a comma delimited text file.
The rows in the file have different layouts.
The value of the first column specifies the layout.

For example:

Layout 1: Name, Surname, Age, ID

Layout 2: ID, Salary

So column names and data types differ completely.

Is there a way to import such a file without using a script task in SSIS?

答:
You can use flat file source from the SSIS toolbox/Other sources. Check  https://learn.microsoft.com/en-us/sql/integration-services/connection-manager/flat-file-connection-manager for more information
Edited: After you changed your question, I undrestood better. Script task is the only solution, as you have to build a logic.

```<code>public override void CreateNewOutputRows()
{
    // Create the StreamReader object to read the input file
    System.IO.StreamReader reader = new System.IO.StreamReader(this.Variables.vInputFilename);

    // Loop through the file to read each line
    while (!reader.EndOfStream)
    {
        // Read one line
        string line = reader.ReadLine();

        // Break the file apart into atomic elements
        string[] items = line.Split('|');

        /*
            Each line should match one of three record types. When matched to
            the correct type, a new row in that output will be created and the
            columns from the file will be written to the appropriate output cols
        */

        // Record type 1 is Manager
        if (items[0] == "Layout 1")
        {
            OutputBuffer0.AddRow();

        }

        // Layout 2
        else if (items[0] == "Layout 2")
        {
            OutputBuffer1.AddRow();

        }
    }
}
</code>```

Then based on the output you connect the relevant tables.Let me know if it works :)

Body:
You can use flat file source from the SSIS toolbox/Other sources. Check  https://learn.microsoft.com/en-us/sql/integration-services/connection-manager/flat-file-connection-manager for more information
Edited: After you changed your question, I undrestood better. Script task is the only solution, as you have to build a logic.

public override void CreateNewOutputRows()
{
    // Create the StreamReader object to read the input file
    System.IO.StreamReader reader = new System.IO.StreamReader(this.Variables.vInputFilename);

    // Loop through the file to read each line
    while (!reader.EndOfStream)
    {
        // Read one line
        string line = reader.ReadLine();

        // Break the file apart into atomic elements
        string[] items = line.Split('|');

        /*
            Each line should match one of three record types. When matched to
            the correct type, a new row in that output will be created and the
            columns from the file will be written to the appropriate output cols
        */

        // Record type 1 is Manager
        if (items[0] == "Layout 1")
        {
            OutputBuffer0.AddRow();

        }

        // Layout 2
        else if (items[0] == "Layout 2")
        {
            OutputBuffer1.AddRow();

        }
    }
}

Then based on the output you connect the relevant tables.Let me know if it works :)


问:
Getting additional input from SlackClient using python
One of the issues is I’m running into is getting additional data from a command in slack. I don’t want to use Slash commands because I can’t expose my localhost to the world.

Example:

```<code>@mybot do
</code>```

Will return, let’s say “I’m doing something”. However I want to be able to do something like

```<code>@mybot do 2
</code>```

Where 2 is a parameter in the back end. Basically what I’m trying to do is have it where the user can say @mybot do 2 and it will get data from the database where the ID is 2. You could make it a 3, 4, 5 etc and the command will pull the information from the database. I have found where I can make it match the exact “do” command, though I can’t get it to read the follow on data. I was following this tutorial. Any help will be great.

if you see weird symbols it’s because I’m doing this from an iPhone and I have that stupid bug where the turns I (eye) into I

答:
How to get "additional information"

You will get the complete input string in the text property, e.g. "do 2". All you need to do is split the string into words. I am not a Python developer, but apparently split() will do the job.

Exposing your localhost

I would strongly recommend to go ahead and expose your localhost with a VPN tunnel. It makes development so much easier. You can use ngrok to securely expose your localhost to Slack.

"Dont want to use slash commands"

You will always need an app (e.g. Python script) on an exposed host for any custom functionality to work with Slack. Actually, slash commands are easier to implement then Event API and RTM, so I would recommend it for your case.

Body:
One of the issues is I’m running into is getting additional data from a command in slack. I don’t want to use Slash commands because I can’t expose my localhost to the world.

Example:

@mybot do

Will return, let’s say “I’m doing something”. However I want to be able to do something like

@mybot do 2

Where 2 is a parameter in the back end. Basically what I’m trying to do is have it where the user can say @mybot do 2 and it will get data from the database where the ID is 2. You could make it a 3, 4, 5 etc and the command will pull the information from the database. I have found where I can make it match the exact “do” command, though I can’t get it to read the follow on data. I was following this tutorial. Any help will be great.

if you see weird symbols it’s because I’m doing this from an iPhone and I have that stupid bug where the turns I (eye) into I