问:
Using video.js is it possible to get current HLS timestamp?
I have an application which is embedding a live stream in it. To cater for delays I'd like to know what is the current timestamp of the stream and compare it with the time on the server.

What I have tested up till now is checking the difference between the buffered time of the video with the current time of the video:

player.bufferedEnd() - player.currentTime()

However I'd like to compare the time with the server instead and to do so I need to get the timestamp of the last requested .ts file.

So, my question is using video.js, is there some sort of hook to get the timestamp of the last requested .ts file?

Video.js version: 7.4.1

答:
I had managed to solve this issue, however please bear with me I don't remember where I had found the documentation for this bit of code.

In my case I was working in an Angular application, I had a video component responsible for loading a live stream with the use of video.js. Anyway let's see some code...

Video initialisation

private videoInit() {
    this.player = videojs('video', {
        aspectRatio: this.videoStream.aspectRatio,
        controls: true,
        autoplay: false,
        muted: true,
        html5: {
            hls: {
                overrideNative: true
            }
        }
    });

    this.player.src({
        src: '://some-stream-url.com',
        type: 'application/x-mpegURL'
    });

    // on video play callback
    this.player.on('play', () => {
        this.saveHlsObject();
    });
}
```

<p><strong>Save HLS Object</strong></p>

<pre class="lang-js prettyprint-override"><code>private saveHlsObject() {
    if (this.player !== undefined) {
        this.playerHls = (this.player.tech() as any).hls;

        // get and syncing server time...
        // make some request to get server time...
        // then calculate difference...
        this.diff = serverTime.getTime() - this.getVideoTime().getTime();
    }
}
</code>```

Get Timestamp of Video Segment

// access the player's playlists, get the last segment and extract time
// in my case URI of segments were for example: 1590763989033.ts
private getVideoTime(): Date {
    const targetMedia = this.playerHls.playlists.media();

    const lastSegment = targetMedia.segments[0];

    const uri: string = lastSegment.uri;
    const segmentTimestamp: number = +uri.substring(0, uri.length - 3);

    return new Date(segmentTimestamp);
}
```

So above the main point is the getVideoTime function. The time of a segment can be found in the segment URI, so that function extracts the time from the segment URI and then converts it to a Date object. Now to be honest, I don't know if this URI format is something that's a standard for HLS or something that was set for the particular stream I was connecting to. Hope this helps, and sorry I don't have any more specific information!

Body:
I had managed to solve this issue, however please bear with me I don't remember where I had found the documentation for this bit of code.

In my case I was working in an Angular application, I had a video component responsible for loading a live stream with the use of video.js. Anyway let's see some code...

Video initialisation

private videoInit() {
    this.player = videojs('video', {
        aspectRatio: this.videoStream.aspectRatio,
        controls: true,
        autoplay: false,
        muted: true,
        html5: {
            hls: {
                overrideNative: true
            }
        }
    });

    this.player.src({
        src: '://some-stream-url.com',
        type: 'application/x-mpegURL'
    });

    // on video play callback
    this.player.on('play', () => {
        this.saveHlsObject();
    });
}

Save HLS Object

private saveHlsObject() {
    if (this.player !== undefined) {
        this.playerHls = (this.player.tech() as any).hls;

        // get and syncing server time...
        // make some request to get server time...
        // then calculate difference...
        this.diff = serverTime.getTime() - this.getVideoTime().getTime();
    }
}

Get Timestamp of Video Segment

// access the player's playlists, get the last segment and extract time
// in my case URI of segments were for example: 1590763989033.ts
private getVideoTime(): Date {
    const targetMedia = this.playerHls.playlists.media();

    const lastSegment = targetMedia.segments[0];

    const uri: string = lastSegment.uri;
    const segmentTimestamp: number = +uri.substring(0, uri.length - 3);

    return new Date(segmentTimestamp);
}

So above the main point is the getVideoTime function. The time of a segment can be found in the segment URI, so that function extracts the time from the segment URI and then converts it to a Date object. Now to be honest, I don't know if this URI format is something that's a standard for HLS or something that was set for the particular stream I was connecting to. Hope this helps, and sorry I don't have any more specific information!


来源: stackexchange

问:
Remove firebase notification from android device (sever side)
I am using firebase for notification. I want to send notification to the group of users... If any one of them press accept notification action button then, the same notification must be remove from the other users device. Is it possible to do using firebase.

Ex. I want to send notification to 5 delivery boys for collecting parcel from XYZ place, if any of them accept the collecting parcel order notification then the same notification must be remove from other 4 delivery boys autometically.

I study and practically done an example of https://firebase.google.com/docs/cloud-messaging/android/device-group Notification send to all 5 del. boys but notification still there after accepting the collecting order.
Please, help.

答:
Firebase Cloud Messaging has two distinct types of messages:

Notification messages that are handled and displayed by the OS when the app is not active, and handled by your application code when the app is active.

Data messages that are always handled by your application code, which can then choose to display or update UI notifications as needed.

What you're describing sounds like you want to use data messages only, and then use Android's notification UI/API to display, update, or hide a notification.

ContentLicense: CC BY-SA 4.0


问:
FAILURE: Build failed with an exception.(for flutter)
i'm trying to create my first flutter app but when i run it it gives me this error

FAILURE: Build failed with an exception.

What went wrong:
Could not open settings remapped class cache for b4ieilm7vkknhwvoai8y4gzba (C:\Users\Emre.gradle\caches\5.6.2\scripts-remapped\settings_1vci5hthrjrgkv26gortq0d7w\b4ieilm7vkknhwvoai8y4gzba\settings8410a2d21ed2f87c8a0398566330ee52).

Could not open settings generic class cache for settings file 'C:\JavaDemos\sea_ok\android\settings.gradle' (C:\Users\Emre.gradle\caches\5.6.2\scripts\b4ieilm7vkknhwvoai8y4gzba\settings\settings8410a2d21ed2f87c8a0398566330ee52).
  BUG! exception in phase 'semantic analysis' in source unit 'BuildScript' Unsupported class file major version 57

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at help.gradle.org

BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1

答:
Look at the answer here: Flutter build error for the first time :Could not open settings remapped class cache for 7yvt6la2007dno98lt3rzbguf

The problem is most likely the Java version you have installed.


问:
Gatsby site serving on EC2 with pm2 node with aws classic load balancer needs https
I am running a Gatsby site in development mode as a dev server on EC2 with a loadbalancer pointing from port 80 to 8000. I have setup a cname on my domain dns to point to the load balancer this works fine. However I need to display this page as an iframe in sanity.io as a web preview and it requires https.

I've read through this https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-create-https-ssl-load-balancer.html and most of it is pretty straight forward for the most part.

What I have done so far is created a listener for 443 https on the loadbalancer and added https 443 to the security group. i have succsufully issued a certificate to the subdomain I am using with aws and attached it to the loadbalancer listener.

Gatsby has a article about custom certs for development mode here https://www.gatsbyjs.org/docs/local-https/#custom-key-and-certificate-files What I am looking for is the cert file, the authority file and the key file in order to pass this command below

Where in the aws certificate manager do I find these files. I think that is the last piece I need to get https working, correct me if I am wrong.

thanks ahead of time.

gatsby develop --https --key-file ../relative/path/to/key.key --cert-file ../relative/path/to/cert.crt --ca-file ../relative/path/to/ca.crt

This is the process I used to request my certficate and it says it's issued
https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html

But how do I use it with the custom https command with gatsby?

There is a export option but it says only for private keys. Do I need to create a private key and then I can export these files I need?

Do I even need to run https on gatsby's side. I watched a video using apache and no change was made to the apache server to get https working with the loadbalancer.

Here is a screenshot of my loadbalancer listenr

Here is a image of my security groups

If I run the --https for gatsby develop it breaks my site I can no longer visit it via the loadbalancer or port 8000. So not sure what to do here.

答:
I would suggest not to encrypt the connection between your ELB and the EC2 instances. If your EC2 instances are not publicly reachable, but only through the load balancer instead, it is best practice to terminate the SSL connection on the load balancer. No need to encrypt HTTP requests inside an AWS VPC (i.e. between ELB and target instances).

You can create a load balancer that listens on both the HTTP (80) and HTTPS (443) ports. If you specify that the HTTPS listener sends requests to the instances on port 80, the load balancer terminates the requests and communication from the load balancer to the instances is not encrypted. [1]

There is some discussion (e.g. on the blog of Kevin Burke) whether it is necessary to encrypt traffic inside a VPC. [2] However, most people are probably not doing it.

What it means for you: Use the same instance protocol for your targets as before: HTTP via port 8000 for both listeners. Do not set up SSL for your Gatsby service. Use a plain HTTP server config instead. No changes are necessary to ELB targets when using SSL termination on the load balancer.

References

[1] https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-create-https-ssl-load-balancer.html

[2] https://acloud.guru/forums/aws-certified-security-specialty/discussion/-Ld2pfsORD6ns5dDK5Y7/tlsssl-termination?answer=-LecNy4QX6fviP_ryd7x


问:
Convert if/else statement to ?: operator C#
I would like to reduce my code to something better. That's why I'm trying to convert if/else statement to operator ?:

My actual code looks like this :

```<code>if (resultat.CodeAlgo != null)
 {
    worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString();
 }
else
 {
    worksheet.Cells[ligne, 7].Value = string.Empty;
}
</code>```

I tried to convert to :

```<code>resultat.CodeAlgo != null
  ? worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString()
  : worksheet.Cells[ligne, 7].Value = string.Empty;
</code>```

But it said :

Only assignment, call, increment, decrement, and new object statement can be used as a statement.

First time I'm using this operator and I don't understand why my simplification is wrong ?

答:
You assign the value to worksheet.Cells[ligne, 7].Value. so the code should be </p>

```<code>worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo != null ? resultat.CodeAlgo.ToString() : string.Empty;
</code>```

Body:
I would like to reduce my code to something better. That's why I'm trying to convert if/else statement to operator ?:

My actual code looks like this :

if (resultat.CodeAlgo != null)
 {
    worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString();
 }
else
 {
    worksheet.Cells[ligne, 7].Value = string.Empty;
}

I tried to convert to :

resultat.CodeAlgo != null
  ? worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString()
  : worksheet.Cells[ligne, 7].Value = string.Empty;

But it said :

Only assignment, call, increment, decrement, and new object statement can be used as a statement.

First time I'm using this operator and I don't understand why my simplification is wrong ?

Body:
You assign the value to worksheet.Cells[ligne, 7].Value. so the code should be

worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo != null ? resultat.CodeAlgo.ToString() : string.Empty;


问:
SQL - Counting based on distinct column item
I have a table including a Teams and a Risk column.
Risks can be Critical, High, Medium or Low. Team vary.

I want to crate a query at which for each team I will get the count of Risk = .
e.g -

```<code>|Team|Count_Critical|Count_High|Count_Medium|Count_Low| (Each team will be only in a single row).
      |T-1 |    3         |   5      |   8        |    5    |
      |T-2 |    1         |   0      |   0        |    89   |
</code>```

Please show me how.

答:
You seem to want conditional aggregation:</p>

```<code>select team,
       sum(case when risk = 'Critical' then 1 else 0 end) as critical,
       sum(case when risk = 'High' then 1 else 0 end) as high,
       sum(case when risk = 'Medium' then 1 else 0 end) as medium,
       sum(case when risk = 'Low' then 1 else 0 end) as low
from t
group by team;
</code>```

Body:
I have a table including a Teams and a Risk column.
Risks can be Critical, High, Medium or Low. Team vary.

I want to crate a query at which for each team I will get the count of Risk = .
e.g -

|Team|Count_Critical|Count_High|Count_Medium|Count_Low| (Each team will be only in a single row).
      |T-1 |    3         |   5      |   8        |    5    |
      |T-2 |    1         |   0      |   0        |    89   |

Please show me how.

Body:
You seem to want conditional aggregation:

select team,
       sum(case when risk = 'Critical' then 1 else 0 end) as critical,
       sum(case when risk = 'High' then 1 else 0 end) as high,
       sum(case when risk = 'Medium' then 1 else 0 end) as medium,
       sum(case when risk = 'Low' then 1 else 0 end) as low
from t
group by team;


问:
Iterating through Array of objects containing arrays

 const endpoint =
        'https://raw.githubusercontent.com/FormidableLabs/radon-typeahead/master/demo/car-models.json';
      const cars = [];
      //fetch the data on the cars, convert the json raw into json and the add it to the array cars
      fetch(endpoint)
        .then((blob) => blob.json())
        .then((data) => cars.push(...data));

      function findMatches(wordToMatch, cars) {
        return cars.filter((Carbrand) => {
          //check if the brand matches what was searched
          //create a regular expression
          const regex = new RegExp(wordToMatch, 'gi');
          return Carbrand.brand.match(regex);
        });
      }

      function displayMatches() {
        const matchArray = findMatches(this.value, cars);
        const htmlCars = matchArray
          .map((carBrand) => {
            return `

${carBrand.brand}

          `;
          })
          .join('');

        const htmlModels = matchArray.map((carBrands) => {
          carBrands.models.map((carModels) => {
            //return carModels + 'this';
            //console.log('li ' + carModels);
            return
            `

${carModels}

            `;
          });
        });
        console.log('htmlModels ' + htmlModels);
        suggestions.innerHTML = htmlCars + htmlModels;
      }

      const searchInput = document.querySelector('.search');
      const suggestions = document.querySelector('.suggestions');

      searchInput.addEventListener('change', displayMatches);
      searchInput.addEventListener('keyup', displayMatches);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8" />

    <title>Car filter</title>
    <meta name="description" content="The HTML5 Herald" />
    <meta name="author" content="SitePoint" />

    <link rel="stylesheet" href="css/styles.css?v=1.0" />
  </head>
  <style></style>
  <body>
    <form class="search-form">
      <input type="text" class="search" placeholder="City or State" />
      <ul class="suggestions">
        <li>Filter for a car</li>
        <li>or a state</li>
      </ul>
    </form>
    </body>
</html></code>```

I'm trying to iterate through and array made of objects that contain keys and Arrays. I'm nesting a map function to display an array that is in the object. I'm trying to get it in a html list

Here is an example of the object.

```<code>{
    "brand": "Acura",
    "models": [
      "2.2CL",
      "2.3CL",
      "3.0CL",
      "3.2CL",
      "ILX",
      "Integra",
      "Legend",
      "MDX",
      "NSX",
      "RDX",
      "3.5 RL",
      "RL",
      "RSX",
      "SLX",
      "2.5TL",
      "3.2TL",
      "TL",
      "TSX",
      "Vigor",
      "ZDX"
    ]
</code>```

The first part getting the car brand works, I'm just struggling to get it to display the models that are in an array.

If I console.log 'carModels'I can see the models as strings but trying to return them is not working. I see ,,,,,, in my console.

findMatches returns an array of matches which works fine.

What I am trying to do is display results for a car brand and then in a nested list all the models of that brand, using a nested map inside my function. Its's working when console logging but I cant seem to return the results.

答:
Something like this?

const cars = {
  "ACURA" : [
    "2.2CL",
    "2.3CL",
    "3.0CL",
    "3.2CL",
    "ILX",
    "Integra",
    "Legend",
    "MDX",
    "NSX",
    "RDX",
    "3.5 RL",
    "RL",
    "RSX",
    "SLX",
    "2.5TL",
    "3.2TL",
    "TL",
    "TSX",
    "Vigor",
    "ZDX"
  ],
  BMW : [ 318, 320, 428 ]
}

function displayMatches() {
  let carLI = [];
  let modelLI = [];
  Object.keys(cars)
    .filter(car => car.indexOf(this.value.toUpperCase())===0)
    .forEach(car => { console.log(car)
      carLI.push(`<li>${car}</li>`);
      modelLI = cars[car].map(model => `<li>${model}</li>`);
    })

  document.getElementById("cars").innerHTML=carLI.join("");
  document.getElementById("models").innerHTML=modelLI.join("");
}

window.addEventListener("load",function() {
  document.getElementById("search").addEventListener("input",displayMatches)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="search" autocomplete="off"/>
<ul id="cars"></ul>
<ul id="models"></ul></code>```

Body:
 const endpoint =
        'https://raw.githubusercontent.com/FormidableLabs/radon-typeahead/master/demo/car-models.json';
      const cars = [];
      //fetch the data on the cars, convert the json raw into json and the add it to the array cars
      fetch(endpoint)
        .then((blob) => blob.json())
        .then((data) => cars.push(...data));

      function findMatches(wordToMatch, cars) {
        return cars.filter((Carbrand) => {
          //check if the brand matches what was searched
          //create a regular expression
          const regex = new RegExp(wordToMatch, 'gi');
          return Carbrand.brand.match(regex);
        });
      }

      function displayMatches() {
        const matchArray = findMatches(this.value, cars);
        const htmlCars = matchArray
          .map((carBrand) => {
            return `

${carBrand.brand}

          `;
          })
          .join('');

        const htmlModels = matchArray.map((carBrands) => {
          carBrands.models.map((carModels) => {
            //return carModels + 'this';
            //console.log('li ' + carModels);
            return
            `

${carModels}

            `;
          });
        });
        console.log('htmlModels ' + htmlModels);
        suggestions.innerHTML = htmlCars + htmlModels;
      }

      const searchInput = document.querySelector('.search');
      const suggestions = document.querySelector('.suggestions');

      searchInput.addEventListener('change', displayMatches);
      searchInput.addEventListener('keyup', displayMatches);

<!DOCTYPE html>

    <meta charset="utf-8" />

    <title>Car filter</title>
    <meta name="description" content="The HTML5 Herald" />
    <meta name="author" content="SitePoint" />

    <link rel="stylesheet" href="css/styles.css?v=1.0" />

    <form class="search-form">
      <input type="text" class="search" placeholder="City or State" />

Filter for a car

or a state

    </form>

I'm trying to iterate through and array made of objects that contain keys and Arrays. I'm nesting a map function to display an array that is in the object. I'm trying to get it in a html list

Here is an example of the object.

{
    "brand": "Acura",
    "models": [
      "2.2CL",
      "2.3CL",
      "3.0CL",
      "3.2CL",
      "ILX",
      "Integra",
      "Legend",
      "MDX",
      "NSX",
      "RDX",
      "3.5 RL",
      "RL",
      "RSX",
      "SLX",
      "2.5TL",
      "3.2TL",
      "TL",
      "TSX",
      "Vigor",
      "ZDX"
    ]

The first part getting the car brand works, I'm just struggling to get it to display the models that are in an array.

If I console.log 'carModels'I can see the models as strings but trying to return them is not working. I see ,,,,,, in my console.

findMatches returns an array of matches which works fine.

What I am trying to do is display results for a car brand and then in a nested list all the models of that brand, using a nested map inside my function. Its's working when console logging but I cant seem to return the results.

Body:
Something like this?

const cars = {
  "ACURA" : [
    "2.2CL",
    "2.3CL",
    "3.0CL",
    "3.2CL",
    "ILX",
    "Integra",
    "Legend",
    "MDX",
    "NSX",
    "RDX",
    "3.5 RL",
    "RL",
    "RSX",
    "SLX",
    "2.5TL",
    "3.2TL",
    "TL",
    "TSX",
    "Vigor",
    "ZDX"
  ],
  BMW : [ 318, 320, 428 ]
}

function displayMatches() {
  let carLI = [];
  let modelLI = [];
  Object.keys(cars)
    .filter(car => car.indexOf(this.value.toUpperCase())===0)
    .forEach(car => { console.log(car)
      carLI.push(`<li>${car}</li>`);
      modelLI = cars[car].map(model => `<li>${model}</li>`);
    })

  document.getElementById("cars").innerHTML=carLI.join("");
  document.getElementById("models").innerHTML=modelLI.join("");
}

window.addEventListener("load",function() {
  document.getElementById("search").addEventListener("input",displayMatches)
})

<input type="text" id="search" autocomplete="off"/>
<ul id="cars"></ul>
<ul id="models"></ul>


问:
Keras: Error when checking input of cnn model
I'm trying to create a CNN model for image classification, however, I'm getting an error with the input shape and I don´t understand why. Please, see below the code:

```<code>import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
import numpy as np

#CREATING 3 DATAFRAMES FROM 3 .TXT FILES
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
# CHANGING TYPE OF TARGET ATTRIBUTE
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#DATA AUGMENTATION
datagen=ImageDataGenerator()
train_datagen = ImageDataGenerator(
    rotation_range=5,
    zoom_range=0.1)

#Generating train, test and validation datasets with RGB, Batch = 32.
train=train_datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
test=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
#No data augmentation to the validation set
validation=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb', batch_size=32)
</code>```

And now is when I start designing the CNN model:

```<code>from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D, BatchNormalization
from keras.constraints import maxnorm

#CNN model
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(32, 250, 250, 3)))
</code>```

As you can see the input_shape is 32 (batch), 250 x 250 image size and 3 channels because of RGB. However, I get the following error:

```<code>ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5
</code>```

答: The problem is the input_shape of the Conv2D layer, you don't have to set the batch size. Change input_shape=(32, 250, 250, 3) to input_shape=(250, 250, 3).

Body:
I'm trying to create a CNN model for image classification, however, I'm getting an error with the input shape and I don´t understand why. Please, see below the code:

import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
import numpy as np

#CREATING 3 DATAFRAMES FROM 3 .TXT FILES
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
# CHANGING TYPE OF TARGET ATTRIBUTE
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#DATA AUGMENTATION
datagen=ImageDataGenerator()
train_datagen = ImageDataGenerator(
    rotation_range=5,
    zoom_range=0.1)

#Generating train, test and validation datasets with RGB, Batch = 32.
train=train_datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
test=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
#No data augmentation to the validation set
validation=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb', batch_size=32)

And now is when I start designing the CNN model:

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D, BatchNormalization
from keras.constraints import maxnorm

#CNN model
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(32, 250, 250, 3)))

As you can see the input_shape is 32 (batch), 250 x 250 image size and 3 channels because of RGB. However, I get the following error:

ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5


问:
How do I display tiff files on Silverlight?
How do I display tiff files on a Silverlight application?  I can display any image format except tiff, can anyone help me?  Thanks.</p>

答: Why don't you try TiffLight?  It is a Silverlight control that allows native display of Tiff files in Silverlight.</p>

ContentLicense: CC BY-SA 3.0


问:
PyODBC SQL Anywhere 17 Conect to Sybase Kernel Dies
I am Working on Ubuntu 18.04 when I am using Pyodbc connection with SQL Anywhere 17 Driver to connect to a Sybase DB, while trying to establish connection my Jupyter notebook Dies.
The expectation is, I should be able to run this code in Ubunt and connect to a Sybase DB.

I can connect and run query from Windows without problems(using DSN).

I have been working with other driver and SQL Server, MySQL and MariaDB and I have not encountered any problems.
I believe connection to Sybase database needs SQLANYWHERE DRVIER.

If Someone knows how get the connection string which is passed from pyodbc to the server when I use a DSN?(maybe this could give me an idea to know what i'm doing wrong).

Some advice?

Code run in windows without problems

```<code>import pyodbc
import pandas as pd

cnxn = pyodbc.connect("DSN=RevDSN")
print(cnxn)
data = pd.DataFrame(pd.read_sql_query(query, cnxn))
cnxn.close()
</code>```

答:
Since I didn't find a good explanation I am putting this here.

I installed the client from

https://archive.sap.com/documents/docs/DOC-35857

then followed the basic instructions from

https://wiki.scn.sap.com/wiki/display/SQLANY/Installing+SQL+Anywhere+17+on+Ubuntu+14.04

The ODBC Client will not ask for the keys

As the documentation says the important part is running the sa_config.sh and making sure that the exports happen.

Lastly edit the /etc/odbcinst.ini file and add the driver.

For example

```<code>[SQL Anywhere 17]
Driver=/opt/sqlanywhere17/lib64/libdbodbc17.so
TDS_Version=5.0
UsageCount=1
</code>```

Then I used this connection string

```<code>import pyodbc
cnxn = pyodbc.connect('Driver={SQL Anywhere 17};LINKS=TCPIP{HOST=<server ip here>};PORT=2638;UID=admin;PWD=<password here>;ENG=<engine name>;DBN=<database name>;')
cursor = cnxn.cursor()
cursor.execute("select top 10 * from dba.<table name>")
for row in cursor:
     print(row)
</code>```

And it worked.

Body:
I am Working on Ubuntu 18.04 when I am using Pyodbc connection with SQL Anywhere 17 Driver to connect to a Sybase DB, while trying to establish connection my Jupyter notebook Dies.
The expectation is, I should be able to run this code in Ubunt and connect to a Sybase DB.

I can connect and run query from Windows without problems(using DSN).

I have been working with other driver and SQL Server, MySQL and MariaDB and I have not encountered any problems.
I believe connection to Sybase database needs SQLANYWHERE DRVIER.

If Someone knows how get the connection string which is passed from pyodbc to the server when I use a DSN?(maybe this could give me an idea to know what i'm doing wrong).

Some advice?

Code run in windows without problems

import pyodbc
import pandas as pd

cnxn = pyodbc.connect("DSN=RevDSN")
print(cnxn)
data = pd.DataFrame(pd.read_sql_query(query, cnxn))
cnxn.close()

Body:
Since I didn't find a good explanation I am putting this here.

I installed the client from

https://archive.sap.com/documents/docs/DOC-35857

then followed the basic instructions from

https://wiki.scn.sap.com/wiki/display/SQLANY/Installing+SQL+Anywhere+17+on+Ubuntu+14.04

The ODBC Client will not ask for the keys

As the documentation says the important part is running the sa_config.sh and making sure that the exports happen.

Lastly edit the /etc/odbcinst.ini file and add the driver.

For example

[SQL Anywhere 17]
Driver=/opt/sqlanywhere17/lib64/libdbodbc17.so
TDS_Version=5.0
UsageCount=1

Then I used this connection string

import pyodbc
cnxn = pyodbc.connect('Driver={SQL Anywhere 17};LINKS=TCPIP{HOST=<server ip here>};PORT=2638;UID=admin;PWD=<password here>;ENG=<engine name>;DBN=<database name>;')
cursor = cnxn.cursor()
cursor.execute("select top 10 * from dba.<table name>")
for row in cursor:
     print(row)

And it worked.


答:
You could just add a dict to your unique list if it is not already contained within it (note that I'm assuming you meant for the third item to have an 'E' in its deck list, otherwise it would not be a duplicate):

```<code>x = [
 {'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
 {'101': ['A'],
  '102': ['C'],
  '103': ['B'],
  '104': ['D'],
  '105': ['E'],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
{'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}
]

unique_solutions = []
for d in x:
    if d not in unique_solutions:
        unique_solutions.append(d)
</code>```

Or, you could create something like a HashDict class which implements hashes (in my example, using tuples, but this could be done in different ways) and create a set:

```<code>class HashDict(dict):
    def __init__(self, d):
        for k, v in d.items():
            self[k] = v

    def __hash__(self):
        return hash(tuple((k, tuple(v)) for k, v in self.items()))

hdx = [HashDict(d) for d in x]
unique_solutions = list(set(hdx))
</code>```

Both examples result in

```<code>>>> print(unique_solutions)
[{'101': ['A', 'B'], '102': ['C'], '103': ['D'], '104': [], '105': [], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}, {'101': ['A'], '102': ['C'], '103': ['B'], '104': ['D'], '105': ['E'], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}]
</code>```

Title: Python - List of unique dictionaries where each dictionary value is a list

Body:
Let's say I got a list of dictionaries like this:

[
 {'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
 {'101': ['A'],
  '102': ['C'],
  '103': ['B'],
  '104': ['D'],
  '105': ['E'],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
{'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E','F', 'G', 'H', 'I', 'J', 'K', 'L']}
]

and I need to obtain a list of unique dictionaries (removing the duplicates):

[
 {'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
 {'101': ['A'],
  '102': ['C'],
  '103': ['B'],
  '104': ['D'],
  '105': ['E'],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}
]

I tried

unique_solutions = list(set(val for dic in full_solutions_list for val in dic.values()))

But the 'list' type of dictionary values are unhashable.

What would be an efficient way to do this? (the number of dictionaries is relatively large).

Body:
You could just add a dict to your unique list if it is not already contained within it (note that I'm assuming you meant for the third item to have an 'E' in its deck list, otherwise it would not be a duplicate):

x = [
 {'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
 {'101': ['A'],
  '102': ['C'],
  '103': ['B'],
  '104': ['D'],
  '105': ['E'],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
{'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}
]

unique_solutions = []
for d in x:
    if d not in unique_solutions:
        unique_solutions.append(d)

Or, you could create something like a HashDict class which implements hashes (in my example, using tuples, but this could be done in different ways) and create a set:

class HashDict(dict):
    def __init__(self, d):
        for k, v in d.items():
            self[k] = v

    def __hash__(self):
        return hash(tuple((k, tuple(v)) for k, v in self.items()))

hdx = [HashDict(d) for d in x]
unique_solutions = list(set(hdx))

Both examples result in

>>> print(unique_solutions)
[{'101': ['A', 'B'], '102': ['C'], '103': ['D'], '104': [], '105': [], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}, {'101': ['A'], '102': ['C'], '103': ['B'], '104': ['D'], '105': ['E'], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}]


问:
OrderBy on mix of DateTime and DBNull values throws error
I want to order a list of my 'SortObject' class. This class is meant to imitate a DataGrid Row by holding arbitrary data organized in a dictionary (named 'Cells'), where the key is analogous to a DataGrid Column. It is enforced that any given key is associated with only one data type, for example the key "Name" will only have values of the String type.

My code (below) actually works for a majority of the cases I've used:

```<code>// public Dictionary<string, object> Cells { get; set; } <-- relevant field from 'SortObject'

List<SortObject> sortObjects = GetSortObjects(); // This is simplified, the data has a few different sources
IOrderedEnumerable<SortObject> orderedList = sortObjects.OrderBy(p => p.Cells["ArbitraryKey"]);
SortObject firstObject = sortedList.First();

// other work with 'orderedList' follows
</code>```

The problem occurs when I'm trying to OrderBy objects of the DateTime type, and some of those objects are not set and default to 'System.DBNull'. In this case an exception is thrown when calling 'sortedList.First()' or in any of the later references to 'sortedList'. The exception is simple: "Object must be of type DateTime", which seems to be a consequence of OrderBy trying to compare the type DateTime to the type DBNull.

I've tried two solutions that haven't worked so far:

Attempt One: Set DBNull to new DateTime. In theory this should work, but I would need to create not simply DateTime type objects, but objects of any arbitrary type on the fly. (I'd also need to take note of these SortObjects and set their data back to DBNull once I had the order correct; I can't be actually changing data after all).

Attempt Two: Organize just DBNull, then just DateTime, then slap them together. Again this might work in theory, but the "other work" mentioned in the code snippet is extensive, including reordering using ThenBy() an arbitrary number of times on any key(s). Doubling its complexity is not an elegant solution and I consider it a backup.

What is the best way to resolve this?

PS: For OrderBy and DateTime I'm using the Microsoft .NET Framework v4.6.2

答:
Change the OrderBy statement to OrderBy(v => v is DBNull ? null : v)

OrderBy can handle nulls, but not dbNulls.

That code should work for all the data types

Body:
I want to order a list of my 'SortObject' class. This class is meant to imitate a DataGrid Row by holding arbitrary data organized in a dictionary (named 'Cells'), where the key is analogous to a DataGrid Column. It is enforced that any given key is associated with only one data type, for example the key "Name" will only have values of the String type.

My code (below) actually works for a majority of the cases I've used:

// public Dictionary<string, object> Cells { get; set; } <-- relevant field from 'SortObject'

List<SortObject> sortObjects = GetSortObjects(); // This is simplified, the data has a few different sources
IOrderedEnumerable<SortObject> orderedList = sortObjects.OrderBy(p => p.Cells["ArbitraryKey"]);
SortObject firstObject = sortedList.First();

// other work with 'orderedList' follows

The problem occurs when I'm trying to OrderBy objects of the DateTime type, and some of those objects are not set and default to 'System.DBNull'. In this case an exception is thrown when calling 'sortedList.First()' or in any of the later references to 'sortedList'. The exception is simple: "Object must be of type DateTime", which seems to be a consequence of OrderBy trying to compare the type DateTime to the type DBNull.

I've tried two solutions that haven't worked so far:

Attempt One: Set DBNull to new DateTime. In theory this should work, but I would need to create not simply DateTime type objects, but objects of any arbitrary type on the fly. (I'd also need to take note of these SortObjects and set their data back to DBNull once I had the order correct; I can't be actually changing data after all).

Attempt Two: Organize just DBNull, then just DateTime, then slap them together. Again this might work in theory, but the "other work" mentioned in the code snippet is extensive, including reordering using ThenBy() an arbitrary number of times on any key(s). Doubling its complexity is not an elegant solution and I consider it a backup.

What is the best way to resolve this?

PS: For OrderBy and DateTime I'm using the Microsoft .NET Framework v4.6.2


问:
Python: Add or remove timezone hours from a timestamp and get actual time
In Python, I need to get the actual time of a given string timestamp converted to a different timezone without timezone information. I am using pytz to do this. But all I get is the given DateTime with the timezone information appended to it.

Base datetime : 2020-05-29 19:00:00 (A string datetime without timezone info)

Requirement: When this time is converted to (US Zipcode 90071) -0700 timezone,
it should return "2020-05-29 12:00:00", not "2020-05-29 19:00:00-0700"

Code:

```<code>import pytz
from datetime import datetime
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder

date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zip = "90071"

search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zip)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])
tz = pytz.timezone(timezone)
new_timestamp = tz.localize(date_time_obj)

new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')
</code>```

But this returns 2020-05-29 19:00:00.000000-0700. I need to retrieve a DateTime object/string with the actual time shown in that timezone without a timezone chunk attached to the end of the DateTime.

答:
Assuming your "Base datetime" refers to UTC, you have to add a tzinfo=UTC first before you convert to another timezone. Also, avoid overwriting built-ins like zip. Example using dateutil:

```<code>from datetime import datetime
import dateutil
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder

date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zipcode = "90071"

search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zipcode)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])

# localize to UTC first
date_time_obj = date_time_obj.replace(tzinfo=dateutil.tz.UTC)

# now localize to timezone of the zipcode:
new_timestamp = date_time_obj.astimezone(dateutil.tz.gettz(timezone))

new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')
# '05/29/2020 12:00:00'
</code>```

If you need to use pytz, make sure to use localize instead of replace (even though UTC is an exception).

Sidenote: If your "Base datetime" refers to local time (operating system), you could obtain that timezone by

```<code>import time
import dateutil
localtzname = time.tzname[time.daylight]
tz = dateutil.tz.gettz(localtzname)
</code>```

Body:
In Python, I need to get the actual time of a given string timestamp converted to a different timezone without timezone information. I am using pytz to do this. But all I get is the given DateTime with the timezone information appended to it.

Base datetime : 2020-05-29 19:00:00 (A string datetime without timezone info)

Requirement: When this time is converted to (US Zipcode 90071) -0700 timezone,
it should return "2020-05-29 12:00:00", not "2020-05-29 19:00:00-0700"

Code:

import pytz
from datetime import datetime
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder

date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zip = "90071"

search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zip)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])
tz = pytz.timezone(timezone)
new_timestamp = tz.localize(date_time_obj)

new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')

But this returns 2020-05-29 19:00:00.000000-0700. I need to retrieve a DateTime object/string with the actual time shown in that timezone without a timezone chunk attached to the end of the DateTime.

Body:
Assuming your "Base datetime" refers to UTC, you have to add a tzinfo=UTC first before you convert to another timezone. Also, avoid overwriting built-ins like zip. Example using dateutil:

from datetime import datetime
import dateutil
from uszipcode import SearchEngine
from timezonefinder import TimezoneFinder

date_time_obj = datetime.strptime("2020-05-29 19:00:00", '%Y-%m-%d %H:%M:%S')
zipcode = "90071"

search = SearchEngine(simple_zipcode=True)
zipcode = search.by_zipcode(zipcode)
zipcode = zipcode.to_dict()
tf = TimezoneFinder(in_memory=True)
timezone = tf.timezone_at(lng=zipcode['lng'], lat=zipcode['lat'])

# localize to UTC first
date_time_obj = date_time_obj.replace(tzinfo=dateutil.tz.UTC)

# now localize to timezone of the zipcode:
new_timestamp = date_time_obj.astimezone(dateutil.tz.gettz(timezone))

new_timestamp_str = datetime.strftime(new_timestamp, '%m/%d/%Y %H:%M:%S')
# '05/29/2020 12:00:00'

If you need to use pytz, make sure to use localize instead of replace (even though UTC is an exception).

Sidenote: If your "Base datetime" refers to local time (operating system), you could obtain that timezone by

import time
import dateutil
localtzname = time.tzname[time.daylight]
tz = dateutil.tz.gettz(localtzname)


问:
How to change datetime values into a separately formatted value
I have a data set, which unfortunately has sporadic DateTime values, rather than int or str.

How could I go about editing the values, by iterating through the database and replacing the 2019-05-03 00:00:00 into 5-3, for example?

I have tried a few for loops but to no avail. Is there a pandas shortcut?

```<code>,age,menopause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quad,irradiat,Class
0,40-49,premeno,15-19,0-2,yes,3,right,left_up,no,recurrence-events
1,50-59,ge40,15-19,0-2,no,1,right,central,no,no-recurrence-events
2,50-59,ge40,35-39,0-2,no,2,left,left_low,no,recurrence-events
3,40-49,premeno,35-39,0-2,yes,3,right,left_low,yes,no-recurrence-events
4,40-49,premeno,30-34,2019-05-03 00:00:00,yes,2,left,right_up,no,recurrence-events
5,50-59,premeno,25-29,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
6,50-59,ge40,40-44,0-2,no,3,left,left_up,no,no-recurrence-events
7,40-49,premeno,2014-10-01 00:00:00,0-2,no,2,left,left_up,no,no-recurrence-events
8,40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
9,40-49,ge40,40-44,15-17,yes,2,right,left_up,yes,no-recurrence-events
10,50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
11,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
12,50-59,ge40,30-34,0-2,no,1,right,central,no,no-recurrence-events
13,50-59,ge40,25-29,0-2,no,2,right,left_up,no,no-recurrence-events
14,40-49,premeno,25-29,0-2,no,2,left,left_low,yes,recurrence-events
15,30-39,premeno,20-24,0-2,no,3,left,central,no,no-recurrence-events
16,50-59,premeno,2014-10-01 00:00:00,2019-05-03 00:00:00,no,1,right,left_up,no,no-recurrence-events
17,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
18,50-59,premeno,40-44,0-2,no,2,left,left_up,no,no-recurrence-events
19,50-59,ge40,20-24,0-2,no,3,left,left_up,no,no-recurrence-events
20,50-59,lt40,20-24,0-2,?,1,left,left_low,no,recurrence-events
21,60-69,ge40,40-44,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
22,50-59,ge40,15-19,0-2,no,2,right,left_low,no,no-recurrence-events
23,40-49,premeno,2014-10-01 00:00:00,0-2,no,1,right,left_up,no,no-recurrence-events
24,30-39,premeno,15-19,2019-08-06 00:00:00,yes,3,left,left_low,yes,recurrence-events
25,50-59,ge40,20-24,2019-05-03 00:00:00,yes,2,right,left_up,no,no-recurrence-events
</code>```

Body:
I have a data set, which unfortunately has sporadic DateTime values, rather than int or str.

How could I go about editing the values, by iterating through the database and replacing the 2019-05-03 00:00:00 into 5-3, for example?

I have tried a few for loops but to no avail. Is there a pandas shortcut?

,age,menopause,tumor-size,inv-nodes,node-caps,deg-malig,breast,breast-quad,irradiat,Class
0,40-49,premeno,15-19,0-2,yes,3,right,left_up,no,recurrence-events
1,50-59,ge40,15-19,0-2,no,1,right,central,no,no-recurrence-events
2,50-59,ge40,35-39,0-2,no,2,left,left_low,no,recurrence-events
3,40-49,premeno,35-39,0-2,yes,3,right,left_low,yes,no-recurrence-events
4,40-49,premeno,30-34,2019-05-03 00:00:00,yes,2,left,right_up,no,recurrence-events
5,50-59,premeno,25-29,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
6,50-59,ge40,40-44,0-2,no,3,left,left_up,no,no-recurrence-events
7,40-49,premeno,2014-10-01 00:00:00,0-2,no,2,left,left_up,no,no-recurrence-events
8,40-49,premeno,0-4,0-2,no,2,right,right_low,no,no-recurrence-events
9,40-49,ge40,40-44,15-17,yes,2,right,left_up,yes,no-recurrence-events
10,50-59,premeno,25-29,0-2,no,2,left,left_low,no,no-recurrence-events
11,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
12,50-59,ge40,30-34,0-2,no,1,right,central,no,no-recurrence-events
13,50-59,ge40,25-29,0-2,no,2,right,left_up,no,no-recurrence-events
14,40-49,premeno,25-29,0-2,no,2,left,left_low,yes,recurrence-events
15,30-39,premeno,20-24,0-2,no,3,left,central,no,no-recurrence-events
16,50-59,premeno,2014-10-01 00:00:00,2019-05-03 00:00:00,no,1,right,left_up,no,no-recurrence-events
17,60-69,ge40,15-19,0-2,no,2,right,left_up,no,no-recurrence-events
18,50-59,premeno,40-44,0-2,no,2,left,left_up,no,no-recurrence-events
19,50-59,ge40,20-24,0-2,no,3,left,left_up,no,no-recurrence-events
20,50-59,lt40,20-24,0-2,?,1,left,left_low,no,recurrence-events
21,60-69,ge40,40-44,2019-05-03 00:00:00,no,2,right,left_up,yes,no-recurrence-events
22,50-59,ge40,15-19,0-2,no,2,right,left_low,no,no-recurrence-events
23,40-49,premeno,2014-10-01 00:00:00,0-2,no,1,right,left_up,no,no-recurrence-events
24,30-39,premeno,15-19,2019-08-06 00:00:00,yes,3,left,left_low,yes,recurrence-events
25,50-59,ge40,20-24,2019-05-03 00:00:00,yes,2,right,left_up,no,no-recurrence-events

Body:
Here is one way

df['inv-nodes']=df['inv-nodes'].str.extract('(\d{4})-(\d{2}-\d{2})')[1].fillna(df['tumor-size'])

0     15-19
1     15-19
2     35-39
3     35-39
4     30-34
5     25-29
6     40-44
7     10-01
8       0-4
9     40-44
10    25-29
11    15-19
12    30-34
13    25-29
14    25-29
15    20-24
16    10-01
17    15-19
18    40-44
19    20-24
20    20-24
21    40-44
22    15-19
23    10-01
24    15-19
25    20-24


问:
animating multiple text using react
I'm trying to fade in and fade out multiple texts using jquery in react but I'm getting the error that Line 46:6:  'jquery' is not defined  no-undef even though I did npm i jquery --save. How do I run this small piece of jquery code with react or is there any library through which I can achieve a similar effect?

this is the effect that I was trying to add into the react project -> codepen

```<code>import React, { useEffect } from "react";
import $ from "jquery";
import "./App.css";
export const App = () => {
  (function ($) {
    $.fn.extend({
      rotaterator: function (options) {
        var defaults = {
          fadeSpeed: 900,
          pauseSpeed: 900,
          child: null,
        };

        var options = $.extend(defaults, options);

        return this.each(function () {
          var o = options;
          var obj = $(this);
          var items = $(obj.children(), obj);
          items.each(function () {
            $(this).hide();
          });
          if (!o.child) {
            var next = $(obj).children(":first");
          } else {
            var next = o.child;
          }
          $(next).fadeIn(o.fadeSpeed, function () {
            $(next)
              .delay(o.pauseSpeed)
              .fadeOut(o.fadeSpeed, function () {
                var next = $(this).next();
                if (next.length == 0) {
                  next = $(obj).children(":first");
                }
                $(obj).rotaterator({
                  child: next,
                  fadeSpeed: o.fadeSpeed,
                  pauseSpeed: o.pauseSpeed,
                });
              });
          });
        });
      },
    });
  })(jquery);

  $(document).ready(function () {
    $("#rotate").rotaterator({ fadeSpeed: 900, pauseSpeed: 200 });
  });
  return (
 <div className="awards">
        <div className="awardHead">Awards</div>
        <img
          src="./images/trophy.jpg"
          width="300px"
          alt=""
          className="awardPhoto"
        />
        <div id="rotate">
          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
          <div>
           <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>

          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
        </div>
      </div>
);
};
</code>```

答:
You import jQuery as $ but then reference it as jquery at line 46 of your code, despite the fact that you've neither declared nor defined a variable named jquery  Just pass the $ instead:

import React, { useEffect } from "react";
import $ from "jquery";
import "./App.css";
export const App = () => {
  (function ($) {
    $.fn.extend({
      rotaterator: function (options) {
        var defaults = {
          fadeSpeed: 900,
          pauseSpeed: 900,
          child: null,
        };

        var options = $.extend(defaults, options);

        return this.each(function () {
          var o = options;
          var obj = $(this);
          var items = $(obj.children(), obj);
          items.each(function () {
            $(this).hide();
          });
          if (!o.child) {
            var next = $(obj).children(":first");
          } else {
            var next = o.child;
          }
          $(next).fadeIn(o.fadeSpeed, function () {
            $(next)
              .delay(o.pauseSpeed)
              .fadeOut(o.fadeSpeed, function () {
                var next = $(this).next();
                if (next.length == 0) {
                  next = $(obj).children(":first");
                }
                $(obj).rotaterator({
                  child: next,
                  fadeSpeed: o.fadeSpeed,
                  pauseSpeed: o.pauseSpeed,
                });
              });
          });
        });
      },
    });
  })($); // <== this here was previously an undeclared var of `jquery`

  $(document).ready(function () {
    $("#rotate").rotaterator({ fadeSpeed: 900, pauseSpeed: 200 });
  });
  return (

Awards

BEST Company

hello

BEST Company

hello

BEST Company

hello

BEST Company

hello

BEST Company

hello

);
};
```

Title: animating multiple text using react

Body:
I'm trying to fade in and fade out multiple texts using jquery in react but I'm getting the error that Line 46:6:  'jquery' is not defined  no-undef even though I did npm i jquery --save. How do I run this small piece of jquery code with react or is there any library through which I can achieve a similar effect?

this is the effect that I was trying to add into the react project -> codepen

import React, { useEffect } from "react";
import $ from "jquery";
import "./App.css";
export const App = () => {
  (function ($) {
    $.fn.extend({
      rotaterator: function (options) {
        var defaults = {
          fadeSpeed: 900,
          pauseSpeed: 900,
          child: null,
        };

        var options = $.extend(defaults, options);

        return this.each(function () {
          var o = options;
          var obj = $(this);
          var items = $(obj.children(), obj);
          items.each(function () {
            $(this).hide();
          });
          if (!o.child) {
            var next = $(obj).children(":first");
          } else {
            var next = o.child;
          }
          $(next).fadeIn(o.fadeSpeed, function () {
            $(next)
              .delay(o.pauseSpeed)
              .fadeOut(o.fadeSpeed, function () {
                var next = $(this).next();
                if (next.length == 0) {
                  next = $(obj).children(":first");
                }
                $(obj).rotaterator({
                  child: next,
                  fadeSpeed: o.fadeSpeed,
                  pauseSpeed: o.pauseSpeed,
                });
              });
          });
        });
      },
    });
  })(jquery);

  $(document).ready(function () {
    $("#rotate").rotaterator({ fadeSpeed: 900, pauseSpeed: 200 });
  });
  return (

Awards

BEST Company

hello

BEST Company

hello

BEST Company

hello

BEST Company

hello

BEST Company

hello

);
};

Body:
You import jQuery as $ but then reference it as jquery at line 46 of your code, despite the fact that you've neither declared nor defined a variable named jquery  Just pass the $ instead:

import React, { useEffect } from "react";
import $ from "jquery";
import "./App.css";
export const App = () => {
  (function ($) {
    $.fn.extend({
      rotaterator: function (options) {
        var defaults = {
          fadeSpeed: 900,
          pauseSpeed: 900,
          child: null,
        };

        var options = $.extend(defaults, options);

        return this.each(function () {
          var o = options;
          var obj = $(this);
          var items = $(obj.children(), obj);
          items.each(function () {
            $(this).hide();
          });
          if (!o.child) {
            var next = $(obj).children(":first");
          } else {
            var next = o.child;
          }
          $(next).fadeIn(o.fadeSpeed, function () {
            $(next)
              .delay(o.pauseSpeed)
              .fadeOut(o.fadeSpeed, function () {
                var next = $(this).next();
                if (next.length == 0) {
                  next = $(obj).children(":first");
                }
                $(obj).rotaterator({
                  child: next,
                  fadeSpeed: o.fadeSpeed,
                  pauseSpeed: o.pauseSpeed,
                });
              });
          });
        });
      },
    });
  })($); // <== this here was previously an undeclared var of `jquery`

  $(document).ready(function () {
    $("#rotate").rotaterator({ fadeSpeed: 900, pauseSpeed: 200 });
  });
  return (
 <div className="awards">
        <div className="awardHead">Awards</div>
        <img
          src="./images/trophy.jpg"
          width="300px"
          alt=""
          className="awardPhoto"
        />
        <div id="rotate">
          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
          <div>
           <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>

          <div>
            <h2 className="smallAwardHead">BEST Company</h2>
            <p>hello</p>
          </div>
        </div>
      </div>
);
};


问:
Spring HbaseTemplate keeping connection alive
I managed to integrate Hbase into a Spring app using HbaseTemplate:

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ItemRepositoryImpl implements ItemRepository {

    @Autowired
    private HbaseTemplate hbaseTemplate;

    @Override
    public List<Item> findAll() {
        Scan scan = new Scan();
        scan.addColumn(CF, CQ);
        hbaseTemplate.find("TABLE_NAME", scan, (result, rowNum) -> {
            return new Item(...)
        });
    }
}
</code>```

However, the connection to Hbase is opened every time I run findAll() (and closed just after). I read somewhere that the way to keep the connection alive is to use Connection and Table for calls to Hbase. The problem is that HbaseTemplate uses HConnection and HTableInterface.

How can I keep my connection alive using HbaseTemplate? Initiating a new connection is very time-consuming and I'd like to do it only once. Alternatively is there any other way to connect to Hbase from a Spring app?

I'm using:

```<code>org.springframework.data:spring-data-hadoop:2.5.0.RELEASE
org.apache.hbase:hbase-client:1.1.2
</code>```

答:
I found two solutions to this problem:

Custom HbaseTemplate which extends HbaseAccessor and implements HbaseOperations

The best way seems to be to create a custom class which extends HbaseAccessor and implements HbaseOperations in the similar way as the original HbaseTemplate does, but using the newer API (ie. Table instead of HTableInterface etc.)

One of the examples how it's implemented can be found in the easyhbase project.

Injecting Connection instead of HbaseTemplate

The other solution is to inject Connection to the repository and do all the heavy lifting there:

```<code>import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.stream.Collectors;
import java.stream.StreamSupport;

@Component
public class ItemRepositoryImpl implements ItemRepository {

    @Autowired
    private Connection connection;

    @Override
    public List<Item> findAll() throws IOException {
        Scan scan = new Scan();
        scan.addColumn(CF, CQ);
        try (Table table = connection.getTable(TableName.valueOf(TABLE_NAME))) {
            return StreamSupport
                .stream(table.getScanner(scan).spliterator, false)
                .map(...)
                .collect(Collectors.toList());
        }
    }
}
</code>```

The Connection @Bean can be configured like that:

```<code>@Configuration
public class HbaseConfiguration {

    @Bean
    public Connection() throws IOException {
        org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
        // configuration setup
        return ConnectionFactory.createConnection(conf);
    }

}
</code>```

Body:
I managed to integrate Hbase into a Spring app using HbaseTemplate:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ItemRepositoryImpl implements ItemRepository {

    @Autowired
    private HbaseTemplate hbaseTemplate;

    @Override
    public List<Item> findAll() {
        Scan scan = new Scan();
        scan.addColumn(CF, CQ);
        hbaseTemplate.find("TABLE_NAME", scan, (result, rowNum) -> {
            return new Item(...)
        });
    }
}

However, the connection to Hbase is opened every time I run findAll() (and closed just after). I read somewhere that the way to keep the connection alive is to use Connection and Table for calls to Hbase. The problem is that HbaseTemplate uses HConnection and HTableInterface.

How can I keep my connection alive using HbaseTemplate? Initiating a new connection is very time-consuming and I'd like to do it only once. Alternatively is there any other way to connect to Hbase from a Spring app?

I'm using:

org.springframework.data:spring-data-hadoop:2.5.0.RELEASE
org.apache.hbase:hbase-client:1.1.2

Body:
I found two solutions to this problem:

Custom HbaseTemplate which extends HbaseAccessor and implements HbaseOperations

The best way seems to be to create a custom class which extends HbaseAccessor and implements HbaseOperations in the similar way as the original HbaseTemplate does, but using the newer API (ie. Table instead of HTableInterface etc.)

One of the examples how it's implemented can be found in the easyhbase project.

Injecting Connection instead of HbaseTemplate

The other solution is to inject Connection to the repository and do all the heavy lifting there:

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.stream.Collectors;
import java.stream.StreamSupport;

@Component
public class ItemRepositoryImpl implements ItemRepository {

    @Autowired
    private Connection connection;

    @Override
    public List<Item> findAll() throws IOException {
        Scan scan = new Scan();
        scan.addColumn(CF, CQ);
        try (Table table = connection.getTable(TableName.valueOf(TABLE_NAME))) {
            return StreamSupport
                .stream(table.getScanner(scan).spliterator, false)
                .map(...)
                .collect(Collectors.toList());
        }
    }
}

The Connection @Bean can be configured like that:

@Configuration
public class HbaseConfiguration {

    @Bean
    public Connection() throws IOException {
        org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
        // configuration setup
        return ConnectionFactory.createConnection(conf);
    }

}


问:
MATLAB fftfilt equivalent for Python
I am trying to traslate the following function created in MATLAB into Python,

```<code>function output_phase = fix_phasedata180(phase_data_degrees, averaging_length)

x = exp(sqrt(-1)*phase_data_degrees*2/180*pi);
N = averaging_length;
b = 1/sqrt(N)*ones(1,N);
y = fftfilt(b,x);y = fftfilt(b,y(end:-1:1));y = y(end:-1:1); # This is a quick implementation of filtfilt using fftfilt instead of filter
output_phase = (phase_data_degrees-(round(mod(phase_data_degrees/180*pi-unwrap(angle(y))/2,2*pi)*180/pi/180)*180));
temp = mod(output_phase(1),90);
output_phase = output_phase-output_phase(1)+temp;
output_phase = mod(output_phase,360);
s = find(output_phase>= 180);
output_phase(s) = output_phase(s)-360;
</code>```

So, I am trying to implement this function defined in MATLAB into Python here

```<code>def fix_phasedata180(data_phase, averaging_length):
    x = np.exp(1j*data_phase*2./180.*np.pi)
    N = averaging_length
    b = 1./np.sqrt(N)*np.ones(N)
    y = fftfilt(b,x)
    y = fftfilt(b,y[::-1])
    y = y[::-1]
    output_phase = data_phase - np.array(map(round,((data_phase/180.*np.pi-np.unwrap(np.angle(y))/2.)%(2.*np.pi))*180./np.pi/180.))*180
    temp = output_phase[0]%90
    output_phase = output_phase-output_phase[0]+temp
    s = output_phase[output_phase >= 180]
    for s in range(len(output_phase)):
        output_phase[s] = output_phase[s]-360
    return output_phase
</code>```

I was thinking that the function fftfilt was a clone of fftfilt in MATLAB, when I run I have the following error

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-40-eb6944fd1053> in <module>()
      4 N = averaging_length
      5 b = 1./np.sqrt(N)*np.ones(N)
----> 6 y = fftfilt(b,x)

D:/folder/fftfilt.pyc in fftfilt(b, x, *n)
     66         k = min([i+N_fft,N_x])
     67         yt = ifft(fft(x[i:il],N_fft)*H,N_fft) # Overlap..
---> 68         y[i:k] = y[i:k] + yt[:k-i]            # and add
     69         i += L
     70     return y

ValueError: could not broadcast input array from shape (0,0) into shape (0)
</code>```

So, my question is: are there any equivalent to MATLAB fftfilt in Python? The aim of my function output_phase is to correct the fast variations in a phase signal and then correct n*90 degrees shifts, showed bellow

答:
This is a bit late but I found the answer to this while translating some matlab code of my own.

TLDR: Use mode="full" for any of the convolve functions in scipy.signal

I leaned on scipy's recipes to guide me through this. The rest of my answer is effectively a summary of that page. Matlabs fftfilt function can be replaced with any of the convolve functions mentioned in the cookbook (np.convolve, scipy.signal.convolve, .oaconvolve, .fttconvolve), if you pass mode='full'.

```<code>import numpy as np
from numpy import convolve as np_convolve
from scipy.signal import fftconvolve, lfilter, firwin
from scipy.signal import convolve as sig_convolve

# Create the m by n data to be filtered.
m = 1
n = 2 ** 18
x = np.random.random(size=(m, n))

ntaps_list = 2 ** np.arange(2, 14)
for ntaps in ntaps_list:
    # Create a FIR filter.
    b = firwin(ntaps, [0.05, 0.95], width=0.05, pass_zero=False)
    conv_result = sig_convolve(x, b[np.newaxis, :], mode='full')
</code>```

Happy filtering!

Title: MATLAB fftfilt equivalent for Python

Body:
I am trying to traslate the following function created in MATLAB into Python,

function output_phase = fix_phasedata180(phase_data_degrees, averaging_length)

x = exp(sqrt(-1)*phase_data_degrees*2/180*pi);
N = averaging_length;
b = 1/sqrt(N)*ones(1,N);
y = fftfilt(b,x);y = fftfilt(b,y(end:-1:1));y = y(end:-1:1); # This is a quick implementation of filtfilt using fftfilt instead of filter
output_phase = (phase_data_degrees-(round(mod(phase_data_degrees/180*pi-unwrap(angle(y))/2,2*pi)*180/pi/180)*180));
temp = mod(output_phase(1),90);
output_phase = output_phase-output_phase(1)+temp;
output_phase = mod(output_phase,360);
s = find(output_phase>= 180);
output_phase(s) = output_phase(s)-360;

So, I am trying to implement this function defined in MATLAB into Python here

def fix_phasedata180(data_phase, averaging_length):
    x = np.exp(1j*data_phase*2./180.*np.pi)
    N = averaging_length
    b = 1./np.sqrt(N)*np.ones(N)
    y = fftfilt(b,x)
    y = fftfilt(b,y[::-1])
    y = y[::-1]
    output_phase = data_phase - np.array(map(round,((data_phase/180.*np.pi-np.unwrap(np.angle(y))/2.)%(2.*np.pi))*180./np.pi/180.))*180
    temp = output_phase[0]%90
    output_phase = output_phase-output_phase[0]+temp
    s = output_phase[output_phase >= 180]
    for s in range(len(output_phase)):
        output_phase[s] = output_phase[s]-360
    return output_phase

I was thinking that the function fftfilt was a clone of fftfilt in MATLAB, when I run I have the following error

ValueError                                Traceback (most recent call last)
<ipython-input-40-eb6944fd1053> in <module>()
      4 N = averaging_length
      5 b = 1./np.sqrt(N)*np.ones(N)
----> 6 y = fftfilt(b,x)

D:/folder/fftfilt.pyc in fftfilt(b, x, *n)
     66         k = min([i+N_fft,N_x])
     67         yt = ifft(fft(x[i:il],N_fft)*H,N_fft) # Overlap..
---> 68         y[i:k] = y[i:k] + yt[:k-i]            # and add
     69         i += L
     70     return y

ValueError: could not broadcast input array from shape (0,0) into shape (0)

So, my question is: are there any equivalent to MATLAB fftfilt in Python? The aim of my function output_phase is to correct the fast variations in a phase signal and then correct n*90 degrees shifts, showed bellow

Body:
This is a bit late but I found the answer to this while translating some matlab code of my own.

TLDR: Use mode="full" for any of the convolve functions in scipy.signal

I leaned on scipy's recipes to guide me through this. The rest of my answer is effectively a summary of that page. Matlabs fftfilt function can be replaced with any of the convolve functions mentioned in the cookbook (np.convolve, scipy.signal.convolve, .oaconvolve, .fttconvolve), if you pass mode='full'.

import numpy as np
from numpy import convolve as np_convolve
from scipy.signal import fftconvolve, lfilter, firwin
from scipy.signal import convolve as sig_convolve

# Create the m by n data to be filtered.
m = 1
n = 2 ** 18
x = np.random.random(size=(m, n))

ntaps_list = 2 ** np.arange(2, 14)
for ntaps in ntaps_list:
    # Create a FIR filter.
    b = firwin(ntaps, [0.05, 0.95], width=0.05, pass_zero=False)
    conv_result = sig_convolve(x, b[np.newaxis, :], mode='full')

Happy filtering!


问:
Empty Square Brackets in Javascript?
I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks:

```<code>useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);
</code>```

I am curious what the square brackets [] at the end do? According to this site https://reactjs.org/docs/hooks-effect.html, we can use useEffect() without them.

答: We put an empty [], if we want the code inside useEffect to run only once. Without empty [], the code inside the useEffect will run on every render

Title: Empty Square Brackets in Javascript?

Body:
I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks:

useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);

I am curious what the square brackets [] at the end do? According to this site https://reactjs.org/docs/hooks-effect.html, we can use useEffect() without them.


答:
You need to assign result of ternary operation

```<code>worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo != null
                ?  resultat.CodeAlgo.ToString()
                :  string.Empty;
</code>```

or you can use  null coalescing operator ??,

```<code>worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo?.ToString() ?? string.Empty;
</code>```

Ternary Operator ?:

Syntax of ternary operator:

```<code> output = condition ? expression 1 : expression 2;
</code>```

If condition is true then result of expression 1 get assigned to output variable otherwise expression 2 will be assigned.

Null coalescing operator ?? (From MSDN)

operator ?? returns the value of its left-hand operand if it isn't
  null; otherwise, it evaluates the right-hand operand and returns its
  result. The ?? operator doesn't evaluate its right-hand operand if the
  left-hand operand evaluates to non-null.

Null conditional operator ?.

If you notice in second solution, I used ?. operator, this operator is called as null conditional operator. This operator execute only if resultat.CodeAlgo is not-null. It will return null if resultat.CodeAlgo is null, this will help us to avoid null reference exception.

Title: Convert if/else statement to ?: operator C#

Body:
I would like to reduce my code to something better. That's why I'm trying to convert if/else statement to operator ?:

My actual code looks like this :

if (resultat.CodeAlgo != null)
 {
    worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString();
 }
else
 {
    worksheet.Cells[ligne, 7].Value = string.Empty;
}

I tried to convert to :

resultat.CodeAlgo != null
  ? worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo.ToString()
  : worksheet.Cells[ligne, 7].Value = string.Empty;

But it said :

Only assignment, call, increment, decrement, and new object statement can be used as a statement.

First time I'm using this operator and I don't understand why my simplification is wrong ?

Body:
You need to assign result of ternary operation

worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo != null
                ?  resultat.CodeAlgo.ToString()
                :  string.Empty;

or you can use  null coalescing operator ??,

worksheet.Cells[ligne, 7].Value = resultat.CodeAlgo?.ToString() ?? string.Empty;

Ternary Operator ?:

Syntax of ternary operator:

 output = condition ? expression 1 : expression 2;

If condition is true then result of expression 1 get assigned to output variable otherwise expression 2 will be assigned.

Null coalescing operator ?? (From MSDN)

operator ?? returns the value of its left-hand operand if it isn't
  null; otherwise, it evaluates the right-hand operand and returns its
  result. The ?? operator doesn't evaluate its right-hand operand if the
  left-hand operand evaluates to non-null.

Null conditional operator ?.

If you notice in second solution, I used ?. operator, this operator is called as null conditional operator. This operator execute only if resultat.CodeAlgo is not-null. It will return null if resultat.CodeAlgo is null, this will help us to avoid null reference exception.


问:
When should we go for Spark-sql and when should we go for Spark RDD
On which scenario we should prefer spark RDD to write a solution and on which scenario we should choose to go for spark-sql. I know spark-sql gives better performance and it works best with structure and semistructure data. But what else factors are there that we need to take into consideration while choosing betweeen spark Rdd and spark-sql.</p>

答:
I don't see much reasons to still use RDDs.

Assuming you are using JVM based language, you can use DataSet that is the mix of SparkSQL+RDD (DataFrame == DataSet[Row]), according to spark documentation:

Dataset is a new interface added in Spark 1.6 that provides the benefits of RDDs (strong typing, ability to use powerful lambda functions) with the benefits of Spark SQL’s optimized execution engine.

The problem is python is not support DataSet so, you will use RDD and lose spark-sql optimization when you work with non-structed data.


问:
How to use Robot Framework Scripts for Load Testing or performance testing
I have python scripts which are based on Robot Framework and were generally developed for Functional Testing. How can I achieve the Load Testing?
How to approach this problem? should I use Jmeter in order to run load testing (if yes then how is it possible) or there are some other methods available?</p>

答:
If you're a programmer and your team has a good culture of software and code review.

Instead of Jmeter, you have another choice Taurus

Taurus can consume configuration files written in JSON or YAML. But it also supports Jmeter.

It will be easier for code review and construct your own load test.

Some material you can read:

YAMLTutorial:

https://gettaurus.org/docs/YAMLTutorial/

Automating Performance Tests with Taurus:

https://www.youtube.com/watch?v=DN0VNnG-lzs

Simple load test example with Taurus:
https://medium.com/@s6307/how-to-design-a-good-load-test-with-jmeter-and-taurus-like-a-pro-part-1-1d1b32fd77be


问:
no matching function for call to 'std::vector<std.. '
The question I am solving states: I have to take T test cases. For each test case I have to take string as an input, then I need to arrange the input string as: string at even position {double space} string at odd position (example: input - StackOverflow, output - Sakvrlw tcOefo). I've written the following code where I am taking input for all test cases and storing it in a vector. Then I am assigning the elements of vector to another declared string s.

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int T,i;
     cout << "Enter no. of test cases: ";
     cin >> T;

     vector<string> v;
     vector<string> odd;
     vector<string> even;
     string str;

     for(int i=0; i<T; i++){
        cin >> str;
        v.push_back(str);
     }

     string s;

     for(i=0; i<v.size(); i++){
        s = v.at(i);

        for(i=0; i<s.size(); i++){
            if(i==0){
                even.push_back(s[i]);  //*This is where I am getting error*.
            }else if(i==1){
                odd.push_back(s[i]);
            }else{
                if(i%2==0){
                    even.push_back(s[i]);
                }else{
                    odd.push_back(s[i]);
                }
            }
        }

        for(i=0; i<even.size(); i++){
            cout << even.at(i);
        }

        cout << "  ";

        for(i=0; i<odd.size(); i++){
            cout << odd.at(i);
        }

        cout << endl;

        even.clear();
        odd.clear();
        s.clear();
     }

     return 0;
}

</code>```

While compiling the above code I'm getting "no matching error for call std::vector...".
What exactly am I doing wrong?

答:
I am getting the following error when compiling your code:

main.cpp:34:36: error: no matching function for call to ‘std::vector >::push_back(char&)’.

This happens because even is a vector<string>, and s[i] is a char. You are trying to insert a char into a vector of strings, and that is not possible, as they are different types.

If I understood your problem properly, even and odd must both be either vector<char> or string, not vector<string>.

Change the declarations to:

```<code>string odd;
string even;
</code>```

This also allows you to replace the printing:

```<code>for(i=0; i<even.size(); i++) {
    cout << even.at(i);
}
</code>```

With:

```<code>cout << even;
</code>```

Body:
The question I am solving states: I have to take T test cases. For each test case I have to take string as an input, then I need to arrange the input string as: string at even position {double space} string at odd position (example: input - StackOverflow, output - Sakvrlw tcOefo). I've written the following code where I am taking input for all test cases and storing it in a vector. Then I am assigning the elements of vector to another declared string s.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int T,i;
     cout << "Enter no. of test cases: ";
     cin >> T;

     vector<string> v;
     vector<string> odd;
     vector<string> even;
     string str;

     for(int i=0; i<T; i++){
        cin >> str;
        v.push_back(str);
     }

     string s;

     for(i=0; i<v.size(); i++){
        s = v.at(i);

        for(i=0; i<s.size(); i++){
            if(i==0){
                even.push_back(s[i]);  //*This is where I am getting error*.
            }else if(i==1){
                odd.push_back(s[i]);
            }else{
                if(i%2==0){
                    even.push_back(s[i]);
                }else{
                    odd.push_back(s[i]);
                }
            }
        }

        for(i=0; i<even.size(); i++){
            cout << even.at(i);
        }

        cout << "  ";

        for(i=0; i<odd.size(); i++){
            cout << odd.at(i);
        }

        cout << endl;

        even.clear();
        odd.clear();
        s.clear();
     }

     return 0;
}

While compiling the above code I'm getting "no matching error for call std::vector...".
What exactly am I doing wrong?

Body:
I am getting the following error when compiling your code:

main.cpp:34:36: error: no matching function for call to ‘std::vector >::push_back(char&)’.

This happens because even is a vector<string>, and s[i] is a char. You are trying to insert a char into a vector of strings, and that is not possible, as they are different types.

If I understood your problem properly, even and odd must both be either vector<char> or string, not vector<string>.

Change the declarations to:

string odd;
string even;

This also allows you to replace the printing:

for(i=0; i<even.size(); i++) {
    cout << even.at(i);
}

With:

cout << even;


问:
How do you do "wrap_content" (Android XML syntax) in iOS Swift
I am an Android developer trying to learn iOS development in Swift. I was wondering how you achieve "wrap_content" in Xcode. Any ideas? What are the variables to change in the attribute inspector?</p>

答:
You can use a trick with constraints to achieve wrap-content. For example :

```<code>let maximumWidth = frame / 4  //For example
yourView.widthAnchor.constraint(lessThanOrEqualToConstant: maximumWidth).isActive = true
</code>```

The "maximumWidth" depends on your UI and your design and you can change it.

Also, you should set "lineBreakMode" in StoryBoard or in code like :

```<code>yourBtn.titleLabel?.lineBreakMode = .byCharWrapping //For UIButton or
yourTxt.textContainer.lineBreakMode = .byCharWrapping //For UITextView
</code>```

Body:
You can use a trick with constraints to achieve wrap-content. For example :

let maximumWidth = frame / 4  //For example
yourView.widthAnchor.constraint(lessThanOrEqualToConstant: maximumWidth).isActive = true

The "maximumWidth" depends on your UI and your design and you can change it.

Also, you should set "lineBreakMode" in StoryBoard or in code like :

yourBtn.titleLabel?.lineBreakMode = .byCharWrapping //For UIButton or
yourTxt.textContainer.lineBreakMode = .byCharWrapping //For UITextView


问:
Finding a sick day before or after a vacation and it might be across a weekend
This is what I'm trying to sort out and any direction would be appreciated.

Employee 6 took a vacation day on Friday 08/16/2019 but called in Sick on Thursday 08/15/2019.

Employee 10 took Vacation Monday through Thursday 08/12/2019-08/15/2019 then called in Sick on 08/16/2019

Employee 14 took vacation Monday through Friday 08/05/2019-08/09/2019 then called in Sick the following Monday 08/12/2019.

Employee 23 called in sick on Friday 08/02/2019 before starting vacation on 08/05/2019 – 08/09/2019.

I do have code that looks for a pattern, in this case looking for 3 consecutive sick days to make sure it isn't an FMLA case but I can't sort out the logic to check for the SK day before or after a PT day.

```<code>DECLARE @var_StartDate DATETIME = '10/28/2018' -- Set the start date
DECLARE @var_EndDate DATETIME = '10/26/2019';  --Set the end date

--:OUT"C:\Data\3_consecutive_Sick_Days.csv"

SELECT
        EMPLOYEEID
       ,CONVERT(VARCHAR(10),MIN(ABSENCEDATE),101) AS Absence_Start
       ,LEFT(DATENAME(DW,MIN(ABSENCEDATE)),3) AS Start_DOW
       ,CONVERT(VARCHAR(10),MAX(ABSENCEDATE),101) AS Absence_End
       ,LEFT(DATENAME(DW,MAX(ABSENCEDATE)),3) AS End_DOW
       ,COUNT(EMPLOYEEID) AS Count
       ,PAYCODENAME

FROM (SELECT A.EMPLOYEEID, A.ABSENCEDATE,A.PAYCODENAME,SUM(COL) OVER(PARTITION BY EMPLOYEEID, PAYCODENAME ORDER BY ABSENCEDATE) AS GRP
      FROM (SELECT A.*,
            CASE WHEN DATEDIFF(DAY,LAG(ABSENCEDATE) OVER(PARTITION BY EMPLOYEEID, PAYCODENAME ORDER BY ABSENCEDATE),ABSENCEDATE)=1
                --OR (DATEPART(WEEKDAY,[ABSENCEDATE])=2 AND DATEPART(WEEKDAY,LAG([ABSENCEDATE]) OVER(PARTITION BY EMPLOYEEID,PAYCODENAME ORDER BY ABSENCEDATE))=6)
            THEN 0 ELSE 1 END AS COL
            FROM VP_ABSENCE A
                      WHERE   ABSENCEDATE BETWEEN @var_StartDate AND @var_EndDate
                              AND PAYCODENAME IN ('SK')
                              AND A.TIMEINSECONDS > 0

                ) A ) A

GROUP BY EMPLOYEEID, PAYCODENAME, GRP
HAVING DATEDIFF(DAY,MIN(ABSENCEDATE), MAX(ABSENCEDATE)) >2
ORDER BY EMPLOYEEID, CONVERT(VARCHAR(10),MIN(ABSENCEDATE),101)
</code>```

I would like the output result to be:

```
6, SK, 08/15/2019, PT, 08/16/2019, NULL
10, SK, 08/16/2019, PT, 08/12/2019, 08/15/2019
14, SK, 08/12/2019, PT, 08/05/2019, 08/09/2019
23, SK, 08/02/2019, PT, 08/05/2019, 08/09/2019
```

Data set below....

```<code>Emp        Date            DOW    Code    Hours     Wages
6          08/15/2019      Thu    SK      8.000000  0.000000
6          08/16/2019      Fri    PT      8.000000  0.000000
10         08/12/2019      Mon    PT      8.000000  0.000000
10         08/13/2019      Tue    PT      8.000000  0.000000
10         08/14/2019      Wed    PT      8.000000  0.000000
10         08/15/2019      Thu    PT      8.000000  0.000000
10         08/16/2019      Fri    SK      8.000000  0.000000
13         08/08/2019      Thu    PT      1.000000  0.000000
13         08/09/2019      Fri    PT      2.000000  0.000000
14         08/05/2019      Mon    PT      8.000000  0.000000
14         08/06/2019      Tue    PT      8.000000  0.000000
14         08/07/2019      Wed    PT      8.000000  0.000000
14         08/08/2019      Thu    PT      8.000000  0.000000
14         08/09/2019      Fri    PT      8.000000  0.000000
14         08/12/2019      Mon    SK      8.000000  0.000000
16         08/12/2019      Mon    PT      8.000000  0.000000
16         09/06/2019      Fri    PT      3.000000  0.000000
16         09/13/2019      Fri    PT      2.000000  0.000000
21         08/05/2019      Mon    PT      8.000000  0.000000
21         08/09/2019      Fri    PT      8.000000  0.000000
21         08/16/2019      Fri    PT      8.000000  0.000000
21         09/03/2019      Tue    PT      8.000000  0.000000
21         09/04/2019      Wed    PT      8.000000  0.000000
21         09/05/2019      Thu    PT      8.000000  0.000000
23         08/02/2019      Fri    SK      8.000000  0.000000
23         08/05/2019      Mon    PT      8.000000  0.000000
23         08/06/2019      Tue    PT      8.000000  0.000000
23         08/07/2019      Wed    PT      8.000000  0.000000
23         08/08/2019      Thu    PT      8.000000  0.000000
23         08/09/2019      Fri    PT      8.000000  0.000000
</code>```

答:
The best solution is to create a calendar table (date dimension)  that contains all the dates and columns like dayOfTheWeek, isHoliday etc.
That will make it much easier.

Then you can use this table to join with your absence table.
e.g.

```<code>WITH CTE_abs
as (

    SELECT dat.theDate,allEmployees.emp,isnull(ab.code,'WD') as code,row_number() over (partition by allEmployees.emp order by dat.theDate) as seq
    FROM dbo.alldates dat
    CROSS JOIN  (   SELECT DISTINCT emp
                    FROM dbo.absences
                ) allEmployees
    LEFT JOIN dbo.absences ab
        on ab.emp = allEmployees.emp
        and ab.absenceDate = dat.theDate
    WHERE dat.theDate between '2019-08-01' and '2019-08-31'
    and dat.TheDayName not in ('sunday','saturday')

)
SELECT *
from CTE_abs abs1
join CTE_abs abs2
    on abs1.emp = abs2.emp
    and abs1.seq = abs2.seq-1
WHERE abs1.code <> abs2.code
and abs1.code in ('SK','PT')
and abs2.code in ( 'SK','PT' )
</code>```

Body:
This is what I'm trying to sort out and any direction would be appreciated.

Employee 6 took a vacation day on Friday 08/16/2019 but called in Sick on Thursday 08/15/2019.

Employee 10 took Vacation Monday through Thursday 08/12/2019-08/15/2019 then called in Sick on 08/16/2019

Employee 14 took vacation Monday through Friday 08/05/2019-08/09/2019 then called in Sick the following Monday 08/12/2019.

Employee 23 called in sick on Friday 08/02/2019 before starting vacation on 08/05/2019 – 08/09/2019.

I do have code that looks for a pattern, in this case looking for 3 consecutive sick days to make sure it isn't an FMLA case but I can't sort out the logic to check for the SK day before or after a PT day.

DECLARE @var_StartDate DATETIME = '10/28/2018' -- Set the start date
DECLARE @var_EndDate DATETIME = '10/26/2019';  --Set the end date

--:OUT"C:\Data\3_consecutive_Sick_Days.csv"

SELECT
        EMPLOYEEID
       ,CONVERT(VARCHAR(10),MIN(ABSENCEDATE),101) AS Absence_Start
       ,LEFT(DATENAME(DW,MIN(ABSENCEDATE)),3) AS Start_DOW
       ,CONVERT(VARCHAR(10),MAX(ABSENCEDATE),101) AS Absence_End
       ,LEFT(DATENAME(DW,MAX(ABSENCEDATE)),3) AS End_DOW
       ,COUNT(EMPLOYEEID) AS Count
       ,PAYCODENAME

FROM (SELECT A.EMPLOYEEID, A.ABSENCEDATE,A.PAYCODENAME,SUM(COL) OVER(PARTITION BY EMPLOYEEID, PAYCODENAME ORDER BY ABSENCEDATE) AS GRP
      FROM (SELECT A.*,
            CASE WHEN DATEDIFF(DAY,LAG(ABSENCEDATE) OVER(PARTITION BY EMPLOYEEID, PAYCODENAME ORDER BY ABSENCEDATE),ABSENCEDATE)=1
                --OR (DATEPART(WEEKDAY,[ABSENCEDATE])=2 AND DATEPART(WEEKDAY,LAG([ABSENCEDATE]) OVER(PARTITION BY EMPLOYEEID,PAYCODENAME ORDER BY ABSENCEDATE))=6)
            THEN 0 ELSE 1 END AS COL
            FROM VP_ABSENCE A
                      WHERE   ABSENCEDATE BETWEEN @var_StartDate AND @var_EndDate
                              AND PAYCODENAME IN ('SK')
                              AND A.TIMEINSECONDS > 0

                ) A ) A

GROUP BY EMPLOYEEID, PAYCODENAME, GRP
HAVING DATEDIFF(DAY,MIN(ABSENCEDATE), MAX(ABSENCEDATE)) >2
ORDER BY EMPLOYEEID, CONVERT(VARCHAR(10),MIN(ABSENCEDATE),101)

I would like the output result to be:

6, SK, 08/15/2019, PT, 08/16/2019, NULL
10, SK, 08/16/2019, PT, 08/12/2019, 08/15/2019
14, SK, 08/12/2019, PT, 08/05/2019, 08/09/2019
23, SK, 08/02/2019, PT, 08/05/2019, 08/09/2019

Data set below....

Emp        Date            DOW    Code    Hours     Wages
6          08/15/2019      Thu    SK      8.000000  0.000000
6          08/16/2019      Fri    PT      8.000000  0.000000
10         08/12/2019      Mon    PT      8.000000  0.000000
10         08/13/2019      Tue    PT      8.000000  0.000000
10         08/14/2019      Wed    PT      8.000000  0.000000
10         08/15/2019      Thu    PT      8.000000  0.000000
10         08/16/2019      Fri    SK      8.000000  0.000000
13         08/08/2019      Thu    PT      1.000000  0.000000
13         08/09/2019      Fri    PT      2.000000  0.000000
14         08/05/2019      Mon    PT      8.000000  0.000000
14         08/06/2019      Tue    PT      8.000000  0.000000
14         08/07/2019      Wed    PT      8.000000  0.000000
14         08/08/2019      Thu    PT      8.000000  0.000000
14         08/09/2019      Fri    PT      8.000000  0.000000
14         08/12/2019      Mon    SK      8.000000  0.000000
16         08/12/2019      Mon    PT      8.000000  0.000000
16         09/06/2019      Fri    PT      3.000000  0.000000
16         09/13/2019      Fri    PT      2.000000  0.000000
21         08/05/2019      Mon    PT      8.000000  0.000000
21         08/09/2019      Fri    PT      8.000000  0.000000
21         08/16/2019      Fri    PT      8.000000  0.000000
21         09/03/2019      Tue    PT      8.000000  0.000000
21         09/04/2019      Wed    PT      8.000000  0.000000
21         09/05/2019      Thu    PT      8.000000  0.000000
23         08/02/2019      Fri    SK      8.000000  0.000000
23         08/05/2019      Mon    PT      8.000000  0.000000
23         08/06/2019      Tue    PT      8.000000  0.000000
23         08/07/2019      Wed    PT      8.000000  0.000000
23         08/08/2019      Thu    PT      8.000000  0.000000
23         08/09/2019      Fri    PT      8.000000  0.000000

Body:
The best solution is to create a calendar table (date dimension)  that contains all the dates and columns like dayOfTheWeek, isHoliday etc.
That will make it much easier.

Then you can use this table to join with your absence table.
e.g.

WITH CTE_abs
as (

    SELECT dat.theDate,allEmployees.emp,isnull(ab.code,'WD') as code,row_number() over (partition by allEmployees.emp order by dat.theDate) as seq
    FROM dbo.alldates dat
    CROSS JOIN  (   SELECT DISTINCT emp
                    FROM dbo.absences
                ) allEmployees
    LEFT JOIN dbo.absences ab
        on ab.emp = allEmployees.emp
        and ab.absenceDate = dat.theDate
    WHERE dat.theDate between '2019-08-01' and '2019-08-31'
    and dat.TheDayName not in ('sunday','saturday')

)
SELECT *
from CTE_abs abs1
join CTE_abs abs2
    on abs1.emp = abs2.emp
    and abs1.seq = abs2.seq-1
WHERE abs1.code <> abs2.code
and abs1.code in ('SK','PT')
and abs2.code in ( 'SK','PT' )