问:
Database design for Likes and Total Likes
I have created a basic like system for my system. The likes are stored in the below format

```<code>user_id, post_id, liked_at
</code>```

I want to keep the total likes in the database (as it will help in getting total post likes when retrieving post lists)

```<code>post_id, total_likes
</code>```

I'm currently having 2 options for making these function.

Creating a view to generate post-wise total likes

Trigger to update total likes

what is the best way to go?

答:
Since you will probably invoke the "LIKE" code from only one place in your code, it is a tossup:

Code it in your app code (either inline or in a subroutine)

Have STORED PROCEDURE Like(user_id, post_id)

Use a TRIGGER, then insert one place, and have it do the other insert/update

VIEW

The first two 'feel' better; I tend to avoid "side effects"; they bite me a year later after I have forgotten about them.

I guess my favorite is a subroutine or a stored proc -- this isolates all the actions for LIKEing in a single place; it helps cleanly structure the entire system.

Body:
I have created a basic like system for my system. The likes are stored in the below format

user_id, post_id, liked_at

I want to keep the total likes in the database (as it will help in getting total post likes when retrieving post lists)

post_id, total_likes

I'm currently having 2 options for making these function.

Creating a view to generate post-wise total likes

Trigger to update total likes

what is the best way to go?


来源: stackexchange

问:
Movie searching site using TMDb and axios npm
I'm trying to make a movie searching site using TMDb and axios npm. What am I doing wrong?
Search works fine, but I can't access the movies themselves.

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.Search;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `

${movie.original_title}

              Movie Details

        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `

${movie.Title}

Genre: ${movie.genres.Name}

Released: ${movie.release_date}

Rated: ${movie.vote_average}

Review: ${movie.overview}

Plot

            ${movie.Plot}

            View TMDb
            Go Back To Search

      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />

        MovieInfo

Search For Any Movie

      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>

```

--More details, because I have more code:

Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.

答:
Just replace response.data.Search by response.data.results

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.results;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `

${movie.original_title}

              Movie Details

        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `

${movie.Title}

Genre: ${movie.genres.Name}

Released: ${movie.release_date}

Rated: ${movie.vote_average}

Review: ${movie.overview}

Plot

            ${movie.Plot}

            View TMDb
            Go Back To Search

      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />

        MovieInfo

Search For Any Movie

      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>

```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a movie searching site using TMDb and axios npm. What am I doing wrong?
Search works fine, but I can't access the movies themselves.

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.Search;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `

${movie.original_title}

              Movie Details

        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `

${movie.Title}

Genre: ${movie.genres.Name}

Released: ${movie.release_date}

Rated: ${movie.vote_average}

Review: ${movie.overview}

Plot

            ${movie.Plot}

            View TMDb
            Go Back To Search

      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />

        MovieInfo

Search For Any Movie

      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>

--More details, because I have more code:

Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.

Body:
Just replace response.data.Search by response.data.results

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.results;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `
          <div class="col-md-3">
            <div class="well text-center">
              <img src="${movie.poster_path}">
              <h5>${movie.original_title}</h5>
              <a onclick="https://www.themoviedb.org/movie/('${movie.id}')" class="btn btn-primary" href="#">Movie Details</a>
            </div>
          </div>
        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `
        <div class="row">
          <div class="col-md-4">
            <img src="${movie.Poster}" class="thumbnail">
          </div>
          <div class="col-md-8">
            <h2>${movie.Title}</h2>
            <ul class="list-group">
              <li class="list-group-item"><strong>Genre:</strong> ${movie.genres.Name}</li>
              <li class="list-group-item"><strong>Released:</strong> ${movie.release_date}</li>
              <li class="list-group-item"><strong>Rated:</strong> ${movie.vote_average}</li>
              <li class="list-group-item"><strong>Review:</strong> ${movie.overview}</li>
            </ul>
          </div>
        </div>
        <div class="row">
          <div class="well">
            <h3>Plot</h3>
            ${movie.Plot}
            <hr>
            <a href="http://imdb.com/title/${movie.imdbID}" target="_blank" class="btn btn-primary">View TMDb</a>
            <a href="index.html" class="btn btn-default">Go Back To Search</a>
          </div>
        </div>
      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />
</head>

<body>
  <nav class="navbar navbar-default">
    <div class="container">
      <div class="navbar-header">
        <a class="navbar-brand" href="index.html">MovieInfo</a>
      </div>
    </div>
  </nav>

  <div class="container">
    <div class="jumbotron">
      <h3 class="text-center">Search For Any Movie</h3>
      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>
    </div>
  </div>

  <div class="container">
    <div id="movies" class="row"></div>
  </div>

  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="js/main.js"></script>
</body>

</html>


问:
Flutter: Custom name for screenshot image
I am following the following flutter package to take a screenshot of my one app page:

https://pub.dev/packages/screenshot

I have successfully implemented the example and I can see my screenshots in the gallery.

My issue is that I would like to be able to NAME those images when they are stored in the gallery using some sort of numbering system. e.g. INV_0001, INV_0002.

Is there a way to do this in code? I have the following code that successfully takes the screenshot, but does not rename the file.

CODE

```<code>_imageGallerySaver() async {
    final directory = (await getApplicationDocumentsDirectory()).path; //from path_provide package
    String fileName = "Bob";
    String pathName = '$directory/$fileName.png';

    //print(path);
    screenshotController
        .capture(
      path: pathName,
    ).then((File image) async {
      print("image: $image");
      setState(() {
        _imageFile = image;
      });
      print(pathName);
      final result =
      await ImageGallerySaver.saveImage(image.readAsBytesSync());
      print("File Saved to Gallery. result: $result");
      //print("path: $path");
    }).catchError((onError) {
      print(onError);
    });
  }
</code>```

SNIPPET

```<code>print("File Saved to Gallery. result: $result");
</code>```

results in the following output:

```<code>File Saved to Gallery. result: file:///storage/emulated/0/app_name/1581602261670.png
</code>```

I would like to rename the "1581602261670" part, if possible. Thank you

答:
Can't rename files using this method. Need to use a package called Gallery Saver:
 https://pub.dev/packages/gallery_saver

This package allows you to set your own file name and save to the gallery.

Body:
I am following the following flutter package to take a screenshot of my one app page:

https://pub.dev/packages/screenshot

I have successfully implemented the example and I can see my screenshots in the gallery.

My issue is that I would like to be able to NAME those images when they are stored in the gallery using some sort of numbering system. e.g. INV_0001, INV_0002.

Is there a way to do this in code? I have the following code that successfully takes the screenshot, but does not rename the file.

CODE

_imageGallerySaver() async {
    final directory = (await getApplicationDocumentsDirectory()).path; //from path_provide package
    String fileName = "Bob";
    String pathName = '$directory/$fileName.png';

    //print(path);
    screenshotController
        .capture(
      path: pathName,
    ).then((File image) async {
      print("image: $image");
      setState(() {
        _imageFile = image;
      });
      print(pathName);
      final result =
      await ImageGallerySaver.saveImage(image.readAsBytesSync());
      print("File Saved to Gallery. result: $result");
      //print("path: $path");
    }).catchError((onError) {
      print(onError);
    });
  }

SNIPPET

print("File Saved to Gallery. result: $result");

results in the following output:

File Saved to Gallery. result: file:///storage/emulated/0/app_name/1581602261670.png

I would like to rename the "1581602261670" part, if possible. Thank you


问:
How can i get text from display none Element using java selenium

I need to get text of the element in an image but that element is not displaying on a web page.

答:
You can try with JS. It is not depends on what is element state either it is visible or not</p>

```<code>JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement element=driver.findElement(By.xpath("//div[@class='_3716Tfxt']"));
String text = (String) js.executeScript(“return arguments[0].text;”, element);
</code>```

Body:
You can try with JS. It is not depends on what is element state either it is visible or not

JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement element=driver.findElement(By.xpath("//div[@class='_3716Tfxt']"));
String text = (String) js.executeScript(“return arguments[0].text;”, element);


问:
Android Apache POI error when reading Microsoft Word document: org.apache.xmlbeans.SchemaTypeLoaderException Cannot resolve type for handle
I am trying to use Apache POI in my Android application so that I can read Microsoft Word files. I am integrating the POIA library which enables Apache POI usage on Android (https://github.com/SUPERCILEX/poi-android). However, when I run my code and read in a Word file, I receive the following error:

Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot
  resolve type for handle _XY_Q=space|R=space

Below is my code (I am receiving error on the first line):

```<code>var document = XWPFDocument(uri?.let { contentResolver.openInputStream(it) });
var extractor = XWPFWordExtractor(document);
var documentText = extractor.text; // Retrieve the document's text
</code>```

At runtime I have the following code:

```<code>super.onCreate(savedInstanceState)
System.setProperty("org.apache.poi.javax.xml.stream.XMLInputFactory", "com.fasterxml.aalto.stax.InputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLOutputFactory", "com.fasterxml.aalto.stax.OutputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLEventFactory", "com.fasterxml.aalto.stax.EventFactoryImpl")
</code>```

Below is my gradle (project-level):

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.60'
    repositories {
        google()
        jcenter()

    }
    ext {
        poiVersion = '3.17'
    }
    dependencies {
        classpath 'com.android.tools:r8:1.4.93'
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Below is my gradle (app-level):

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

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    implementation ("com.github.SUPERCILEX.poi-android:poi:$poiVersion") {
        exclude group: 'stax', module: 'stax-api'
    }
}
</code>```

Below is the full stack trace:

```<code>I/System.out: Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot resolve type for handle _XY_Q=space|R=space@http://www.w3.org/XML/1998/namespace (schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2.cttext7f5btype) - code 13
</code>```

IMPORTANT: I am trying to read in the contents of a Word file the USER SELECTED, not a Word file from a hardcoded path.

Please include ALL the relevant code in your answer, and your code should work on Android API 22.

答:
owner of the lib here. poi-android has only been tested with Excel files and is tailored to work well with proguard to minimize binary size for an app I wrote.

If I had to guess, this is causing your issue. For a more generic version of POI, use https://github.com/centic9/poi-on-android (which is what my lib is based off of). You'll have to include the JAR from the releases section into your source tree and add this Gradle dependency: implementation files('path/to/file.jar'). However, as you'll notice, the lib is quite large (13MB+), hence the reasoning behind modifying POI to my use case. I would recommend forking one of the libs and tailoring it to your use case.

Body:
I am trying to use Apache POI in my Android application so that I can read Microsoft Word files. I am integrating the POIA library which enables Apache POI usage on Android (https://github.com/SUPERCILEX/poi-android). However, when I run my code and read in a Word file, I receive the following error:

Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot
  resolve type for handle _XY_Q=space|R=space

Below is my code (I am receiving error on the first line):

var document = XWPFDocument(uri?.let { contentResolver.openInputStream(it) });
var extractor = XWPFWordExtractor(document);
var documentText = extractor.text; // Retrieve the document's text

At runtime I have the following code:

super.onCreate(savedInstanceState)
System.setProperty("org.apache.poi.javax.xml.stream.XMLInputFactory", "com.fasterxml.aalto.stax.InputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLOutputFactory", "com.fasterxml.aalto.stax.OutputFactoryImpl")
System.setProperty("org.apache.poi.javax.xml.stream.XMLEventFactory", "com.fasterxml.aalto.stax.EventFactoryImpl")

Below is my gradle (project-level):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.60'
    repositories {
        google()
        jcenter()

    }
    ext {
        poiVersion = '3.17'
    }
    dependencies {
        classpath 'com.android.tools:r8:1.4.93'
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

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

task clean(type: Delete) {
    delete rootProject.buildDir
}

Below is my gradle (app-level):

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    implementation ("com.github.SUPERCILEX.poi-android:poi:$poiVersion") {
        exclude group: 'stax', module: 'stax-api'
    }
}

Below is the full stack trace:

I/System.out: Exception: org.apache.xmlbeans.SchemaTypeLoaderException: Cannot resolve type for handle _XY_Q=space|R=space@http://www.w3.org/XML/1998/namespace (schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2.cttext7f5btype) - code 13

IMPORTANT: I am trying to read in the contents of a Word file the USER SELECTED, not a Word file from a hardcoded path.

Please include ALL the relevant code in your answer, and your code should work on Android API 22.


问:
how to call file with a dict and pass it to class object?
I need to call one Object (of class 'Configurator') with a number of dict-entries. The call is from command line. So I expected to do like below. But it seems not to work.
Is there a major mistake in design?

1st file:

initiator.py

```<code>from configurator import Configurator

def program1(**kwargs):
    sampleInstance = Configurator(kwargs)

if __name__ == '__main__':
    kwargs = dict([arg.split('=', maxsplit=1) for arg in sys.argv[1:]])
    program1(kwargs)
</code>```

2nd file:

configurator.py

```<code>class Configurator:
    def __init__(self, **kwargs):
        print(kwargs)
</code>```

Input:

```<code>python .\initiator.py myValue1="Hello", myValue2="World"
</code>```

Output:

```<code>program1(kwargs)
    TypeError: program1() takes 0 positional arguments but 1 was given
</code>```

答:
Try :</p>

```<code>from configurator import Configurator
import sys

def program1(**kwargs):
    sampleInstance = Configurator(kwargs)

if __name__ == '__main__':
    kwargs = dict([arg.split('=', maxsplit=1) for arg in sys.argv[1:]])
    program1(**kwargs)
</code>```

Body:
I need to call one Object (of class 'Configurator') with a number of dict-entries. The call is from command line. So I expected to do like below. But it seems not to work.
Is there a major mistake in design?

1st file:

initiator.py

from configurator import Configurator

def program1(**kwargs):
    sampleInstance = Configurator(kwargs)

if __name__ == '__main__':
    kwargs = dict([arg.split('=', maxsplit=1) for arg in sys.argv[1:]])
    program1(kwargs)

2nd file:

configurator.py

class Configurator:
    def __init__(self, **kwargs):
        print(kwargs)

Input:

python .\initiator.py myValue1="Hello", myValue2="World"

Output:

program1(kwargs)
    TypeError: program1() takes 0 positional arguments but 1 was given

Body:
Try :

from configurator import Configurator
import sys

def program1(**kwargs):
    sampleInstance = Configurator(kwargs)

if __name__ == '__main__':
    kwargs = dict([arg.split('=', maxsplit=1) for arg in sys.argv[1:]])
    program1(**kwargs)


问:
Flink keyBy operator directly going into a sink
I have this data pipeline:
stream.map(..).keyBy().addSink(...)
If I have this, when it hits the sink, am I guaranteed that each key is guaranteed to be operated on by a single task manager in the sink operation?

I've seen a lot of examples online where they do keyBy first, then some window then reduce, but never doing the partition of keyBy and then tacking on a sink.

答:
Flink doesn't provide any guarantee about "operated on by a single Task Manager". One Task Manager can have 1...n slots, and your Flink cluster has 1..N Task Managers, and you don't have any control over which slot an operator sub-task will use.

I think what you're asking is whether each record will be written out once - if so, then yes.

Side point - you don't need a keyBy() to distribute the records to the parallel sink operators. If the parallelism of the map() is the same as the sink, then data will be pipelined (no network re-distribution) between those two. If the parallelism is different then a random partitioning will happen over the network.


问:
transfer variable betweet two php page
i have 3 page the first is html where i use  then i send the data to the second page (php) with post where i have some condition, then i will send the data again for the third php page where i will put it in table (html)
my probleme is the data don't send to the third php page

the 2nd page

```<code>if(isset($_POST['matier']) and isset($_POST['semaine']))
{
    $matier = $_POST['matier'] ;
    $semain = $_POST['semaine'] ;

    header('Location:EmploiMetierSemaine.php?'.$matier.' & '.$semaine);
}
</code>```

the third page

```<code><?php

                $matier = $_GET['m'] ;
                $semaine = $_GET['s'] ;
?>
</code>```

any help please

答:
Nowdays If in same case you need to pass a values to multiple pages consecutive with redirection, maybe it's better to review and redesign your program. in other word it's like you are doing something in wrong way.

However, your 2th page must be somthing like this:

```<code>$matier = $_POST['matier'] ?? NUll;
$semain = $_POST['semaine'] ?? NUll;

header('Location:EmploiMetierSemaine.php?m='.$matier.'&s'.$semaine);
</code>```

And use $_GET on 3th page.

Title: transfer variable betweet two php page

Body:
i have 3 page the first is html where i use  then i send the data to the second page (php) with post where i have some condition, then i will send the data again for the third php page where i will put it in table (html)
my probleme is the data don't send to the third php page

the 2nd page

if(isset($_POST['matier']) and isset($_POST['semaine']))
{
    $matier = $_POST['matier'] ;
    $semain = $_POST['semaine'] ;

    header('Location:EmploiMetierSemaine.php?'.$matier.' & '.$semaine);
}

the third page

<?php

                $matier = $_GET['m'] ;
                $semaine = $_GET['s'] ;
?>

any help please

Body:
Nowdays If in same case you need to pass a values to multiple pages consecutive with redirection, maybe it's better to review and redesign your program. in other word it's like you are doing something in wrong way.

However, your 2th page must be somthing like this:

$matier = $_POST['matier'] ?? NUll;
$semain = $_POST['semaine'] ?? NUll;

header('Location:EmploiMetierSemaine.php?m='.$matier.'&s'.$semaine);

And use $_GET on 3th page.


问:
Multiple DatePickers in same activity
I am absolutely new to the Android platform and have been building an application while learning the development process.

Currently, I am working on an activity in which i need to deploy 2 date pickers. One is a "Start Date" and the other is an "End date". I have been following the DatePicker tutorial on the android developers page here: http://developer.android.com/resources/tutorials/views/hello-datepicker.html

For one DatePicker, it works just fine.

Now my problem is, when I replicate the whole process for a second date picker, it shows up just fine on the emulator as well as on the handset. But when no matter which button I press to select the dates, only the first TextView is updated and the second TextView keeps showing the current date.

Here is the code:

```<code>package com.datepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class datepicker extends Activity {

private TextView mDateDisplay;
private TextView endDateDisplay;
private Button mPickDate;
private Button endPickDate;
private int mYear;
private int mMonth;
private int mDay;

static final int START_DATE_DIALOG_ID = 0;
static final int END_DATE_DIALOG_ID = 0;

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /*  capture our View elements for the start date function   */
    mDateDisplay = (TextView) findViewById(R.id.startdateDisplay);
    mPickDate = (Button) findViewById(R.id.startpickDate);

    /* add a click listener to the button   */
    mPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(START_DATE_DIALOG_ID);
        }
    });

    /* get the current date */
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    /* display the current date (this method is below)  */
    updateStartDisplay();

 /* capture our View elements for the end date function */
    endDateDisplay = (TextView) findViewById(R.id.enddateDisplay);
    endPickDate = (Button) findViewById(R.id.endpickDate);

    /* add a click listener to the button   */
    endPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(END_DATE_DIALOG_ID);
        }
    });

    /* get the current date */
    final Calendar c1 = Calendar.getInstance();
    mYear = c1.get(Calendar.YEAR);
    mMonth = c1.get(Calendar.MONTH);
    mDay = c1.get(Calendar.DAY_OF_MONTH);

    /* display the current date (this method is below)  */
    updateEndDisplay();
}

private void updateEndDisplay() {
    endDateDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));

}

private void updateStartDisplay() {
    mDateDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));

}
</code>```

/* the callback received when the user "sets" the date in the dialog for the start date function    */

```<code> private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateStartDisplay();
            }
        };

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case START_DATE_DIALOG_ID:
        return new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
    }
    return null;
}
/* the callback received when the user "sets" the date in the dialog for the end date function  */

private DatePickerDialog.OnDateSetListener endDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateStartDisplay();
            }
        };

protected Dialog onCreateDialog1(int id) {
    switch (id) {
    case END_DATE_DIALOG_ID:
        return new DatePickerDialog(this,
                    endDateSetListener,
                    mYear, mMonth, mDay);
    }
    return null;
}
</code>```

}

Please advise on the changes required for the code.

答:
I had to implement 2 date pickers for the starting date of a trip and an ending date of it. I used a boolean flag to know which text view to fill with the picked date from the date picker dialog. Below, a visual representation of the code.

```<code>public class AddTrip extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

    private boolean startOrEnd = true;
    private Button startDateBtn;
    private Button endDateBtn;
    private TextView startDateText;
    private TextView endDateText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_trip);

        initAll();

        startDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
                startOrEnd = true;
            }
        });

        endDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
                startOrEnd = false;
            }
        });
    }

    public void initAll(){
        startDateBtn = findViewById(R.id.idstartDateBtn);
        endDateBtn = findViewById(R.id.idendDateBtn);
        startDateText = findViewById(R.id.startDateText);
        endDateText = findViewById(R.id.endDateText);
    }

    private void showDatePickerDialog() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                this,
                Calendar.getInstance().get(Calendar.YEAR),
                Calendar.getInstance().get(Calendar.MONTH),
                Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String date = "month/day/year: " + month + "/" + dayOfMonth + "/" + year;
        if (startOrEnd) {
            startDateText.setText(date);
        } else {
            endDateText.setText(date);
        }
    }
}

</code>```

ContentLicense: CC BY-SA 3.0

Title: Multiple DatePickers in same activity

Body:
I am absolutely new to the Android platform and have been building an application while learning the development process.

Currently, I am working on an activity in which i need to deploy 2 date pickers. One is a "Start Date" and the other is an "End date". I have been following the DatePicker tutorial on the android developers page here: http://developer.android.com/resources/tutorials/views/hello-datepicker.html

For one DatePicker, it works just fine.

Now my problem is, when I replicate the whole process for a second date picker, it shows up just fine on the emulator as well as on the handset. But when no matter which button I press to select the dates, only the first TextView is updated and the second TextView keeps showing the current date.

Here is the code:

package com.datepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class datepicker extends Activity {

private TextView mDateDisplay;
private TextView endDateDisplay;
private Button mPickDate;
private Button endPickDate;
private int mYear;
private int mMonth;
private int mDay;

static final int START_DATE_DIALOG_ID = 0;
static final int END_DATE_DIALOG_ID = 0;

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /*  capture our View elements for the start date function   */
    mDateDisplay = (TextView) findViewById(R.id.startdateDisplay);
    mPickDate = (Button) findViewById(R.id.startpickDate);

    /* add a click listener to the button   */
    mPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(START_DATE_DIALOG_ID);
        }
    });

    /* get the current date */
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    /* display the current date (this method is below)  */
    updateStartDisplay();

 /* capture our View elements for the end date function */
    endDateDisplay = (TextView) findViewById(R.id.enddateDisplay);
    endPickDate = (Button) findViewById(R.id.endpickDate);

    /* add a click listener to the button   */
    endPickDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showDialog(END_DATE_DIALOG_ID);
        }
    });

    /* get the current date */
    final Calendar c1 = Calendar.getInstance();
    mYear = c1.get(Calendar.YEAR);
    mMonth = c1.get(Calendar.MONTH);
    mDay = c1.get(Calendar.DAY_OF_MONTH);

    /* display the current date (this method is below)  */
    updateEndDisplay();
}

private void updateEndDisplay() {
    endDateDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));

}

private void updateStartDisplay() {
    mDateDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mMonth + 1).append("-")
                .append(mDay).append("-")
                .append(mYear).append(" "));

}

/* the callback received when the user "sets" the date in the dialog for the start date function    */

 private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateStartDisplay();
            }
        };

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case START_DATE_DIALOG_ID:
        return new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
    }
    return null;
}
/* the callback received when the user "sets" the date in the dialog for the end date function  */

private DatePickerDialog.OnDateSetListener endDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateStartDisplay();
            }
        };

protected Dialog onCreateDialog1(int id) {
    switch (id) {
    case END_DATE_DIALOG_ID:
        return new DatePickerDialog(this,
                    endDateSetListener,
                    mYear, mMonth, mDay);
    }
    return null;
}

}

Please advise on the changes required for the code.

Body:
I had to implement 2 date pickers for the starting date of a trip and an ending date of it. I used a boolean flag to know which text view to fill with the picked date from the date picker dialog. Below, a visual representation of the code.

public class AddTrip extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

    private boolean startOrEnd = true;
    private Button startDateBtn;
    private Button endDateBtn;
    private TextView startDateText;
    private TextView endDateText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_trip);

        initAll();

        startDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
                startOrEnd = true;
            }
        });

        endDateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
                startOrEnd = false;
            }
        });
    }

    public void initAll(){
        startDateBtn = findViewById(R.id.idstartDateBtn);
        endDateBtn = findViewById(R.id.idendDateBtn);
        startDateText = findViewById(R.id.startDateText);
        endDateText = findViewById(R.id.endDateText);
    }

    private void showDatePickerDialog() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                this,
                Calendar.getInstance().get(Calendar.YEAR),
                Calendar.getInstance().get(Calendar.MONTH),
                Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String date = "month/day/year: " + month + "/" + dayOfMonth + "/" + year;
        if (startOrEnd) {
            startDateText.setText(date);
        } else {
            endDateText.setText(date);
        }
    }
}


问:
Are there any optimizations to factorial calculations?
Both the iterative and recursive versions run at linear time complexity.  Are there any optimizations that can be made?</p>

```<code>// O(n)
function factorial (n) {
  let ret = 1;
  for(let i = 2; i <= n; i++) {
    ret = ret * i;
  }
  return ret;
}

// O(n)
function factorialR (n) {
  if( n === 0 || n === 1 ) {
    return 1;
  } else {
    return n * factorialR(n - 1);
  }
}
</code>```

答:
Unless you are doing research, the interviewer will likely want to test the way you think.

Showing both the iterative and recursive version with explanation of the Big O should be adequate for starters.

If asked to optimize, qualify with a use case and suggest memoization if applicable.

If asked to optimize with out memoization do the chicken dance.

Body:
Both the iterative and recursive versions run at linear time complexity.  Are there any optimizations that can be made?

// O(n)
function factorial (n) {
  let ret = 1;
  for(let i = 2; i <= n; i++) {
    ret = ret * i;
  }
  return ret;
}

// O(n)
function factorialR (n) {
  if( n === 0 || n === 1 ) {
    return 1;
  } else {
    return n * factorialR(n - 1);
  }
}


问:
Python - Render a Slanted Font
This question is inline with the answer in my previous question in Stackoverflow.

I am creating a program that converts a text to image. I want to render it in using the font OCR A. But since OCR A font, has no corresponding font file for italics, I have to do the slanting of the upright font manually.

Upright Font

Slanted Font

Below is my initial code :

```<code> from PIL import Image
 from PIL import ImageDraw
 from PIL import ImageFont
 import numpy as np

 #Returns the text size in terms of width and height.
 def getSize(txt, font):
     testImg = Image.new('RGB', (1, 1))
     testDraw = ImageDraw.Draw(testImg)
     return testDraw.textsize(txt, font)

 text = 'CNN Font Recognition Model'
 font_size = 12
 font = ImageFont.truetype('ocra.ttf' , font_size)
 #ocra.ttf is a font file for OCR A Regular font (I have to render it slanted)

 width, height = getSize(text, font)

 #Creates an image with white background of constant size.
 img = Image.new('RGB',(width, height), 'white')
 d = ImageDraw.Draw(img)
 d.text((0,0), text, fill='black', font=font)
 img.save('slanted_ocr_a.png')
</code>```

How do I manually slant the upright OCR A font? Thanks.
You can download a sample ocra.ttf file here.

答:
This answer to a similar question is probably the easiest way, although it is not exactly what you want to do. Basically you render the upright font into an image then slant (shear) the entire image using PIL's Image.transform method.

To accomplish exactly what you are asking (slanting the font before imaging it) is possible, but would require a lot of work overriding PIL's truetype scheme to have the underlying font engine (FreeType) perform the slant transformation at the font level. PIL's truetype interface simply doesn't have a way to express a transform, so you'd have to override/patch it to pass that all the way down to FreeType where the font is set up.

Another option might be to skip PIL's truetype scheme and use a Python font-rendering library that allows you to set the font transform directly, then scrape the pixel data from that into your PIL Image. One such library is freetype-py.

Title: Python - Render a Slanted Font

Body:
This question is inline with the answer in my previous question in Stackoverflow.

I am creating a program that converts a text to image. I want to render it in using the font OCR A. But since OCR A font, has no corresponding font file for italics, I have to do the slanting of the upright font manually.

Upright Font

Slanted Font

Below is my initial code :

 from PIL import Image
 from PIL import ImageDraw
 from PIL import ImageFont
 import numpy as np

 #Returns the text size in terms of width and height.
 def getSize(txt, font):
     testImg = Image.new('RGB', (1, 1))
     testDraw = ImageDraw.Draw(testImg)
     return testDraw.textsize(txt, font)

 text = 'CNN Font Recognition Model'
 font_size = 12
 font = ImageFont.truetype('ocra.ttf' , font_size)
 #ocra.ttf is a font file for OCR A Regular font (I have to render it slanted)

 width, height = getSize(text, font)

 #Creates an image with white background of constant size.
 img = Image.new('RGB',(width, height), 'white')
 d = ImageDraw.Draw(img)
 d.text((0,0), text, fill='black', font=font)
 img.save('slanted_ocr_a.png')

How do I manually slant the upright OCR A font? Thanks.
You can download a sample ocra.ttf file here.


问:
Pass files to another asp.net core webapi from another webapi
Existed asp.net core Api is look like below

```<code>public async Task<IActionResult> UploadAsync()
{
    IFormFile file = null;

    var files = Request.Form.Files;
    if (files.Count > 0)
    {
        file = Request.Form.Files[0];

        var fileText = new StringBuilder();
        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            while (reader.Peek() >= 0)
                fileText.AppendLine(reader.ReadLine());
        }
        int stagingDetailId = await _stagingMarketProvider.GetV1StagingStatusDetailId();

        var result = await SaveStagingMarketsAsync(_fileProvider.ReadImportedMarkets(fileText.ToString()));

        return Ok(result);
    }

    return Ok();

}
</code>```

Now to consume that api from another asp.net core webapi, I have to pass those files through Request object only, I can't change any existed Api code because of business.

答:
Solution 1: Applicable if you want your client to get redirected to other API

Assuming the API caller understands HTTP 302 and can act accordingly, the 302 redirect should help you.

```<code>public IActionResult Post()
{
    return Redirect("http://file-handler-api/action");
}
</code>```

From documentation, Redirect method returns 302 or 301 response to client.

Solution 2:  C# Code To Post a File Using HttpClient

Below c# code is from this blog post.  This is simple code which creates HttpClient object and tries to send the file to a web API.

As you are doing this from one API to another, you will have to save file first at temporary location.  That temporary location will be parameter to this method.

Also, After upload you may want to delete the file if it is not required.   This private method you can call after file upload to your first API is complete.

```<code>private async Task<string> UploadFile(string filePath)
{
    _logger.LogInformation($"Uploading a text file [{filePath}].");
    if (string.IsNullOrWhiteSpace(filePath))
    {
        throw new ArgumentNullException(nameof(filePath));
    }

    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"File [{filePath}] not found.");
    }
    using var form = new MultipartFormDataContent();
    using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(filePath));
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    form.Add(fileContent, "file", Path.GetFileName(filePath));
    form.Add(new StringContent("789"), "userId");
    form.Add(new StringContent("some comments"), "comment");
    form.Add(new StringContent("true"), "isPrimary");

    var response = await _httpClient.PostAsync($"{_url}/api/files", form);
    response.EnsureSuccessStatusCode();
    var responseContent = await response.Content.ReadAsStringAsync();
    var result = JsonSerializer.Deserialize<FileUploadResult>(responseContent);
    _logger.LogInformation("Uploading is complete.");
    return result.Guid;
}
</code>```

Hope this helps you.

Body:
Existed asp.net core Api is look like below

public async Task<IActionResult> UploadAsync()
{
    IFormFile file = null;

    var files = Request.Form.Files;
    if (files.Count > 0)
    {
        file = Request.Form.Files[0];

        var fileText = new StringBuilder();
        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            while (reader.Peek() >= 0)
                fileText.AppendLine(reader.ReadLine());
        }
        int stagingDetailId = await _stagingMarketProvider.GetV1StagingStatusDetailId();

        var result = await SaveStagingMarketsAsync(_fileProvider.ReadImportedMarkets(fileText.ToString()));

        return Ok(result);
    }

    return Ok();

}

Now to consume that api from another asp.net core webapi, I have to pass those files through Request object only, I can't change any existed Api code because of business.

Body:
Solution 1: Applicable if you want your client to get redirected to other API

Assuming the API caller understands HTTP 302 and can act accordingly, the 302 redirect should help you.

public IActionResult Post()
{
    return Redirect("http://file-handler-api/action");
}

From documentation, Redirect method returns 302 or 301 response to client.

Solution 2:  C# Code To Post a File Using HttpClient

Below c# code is from this blog post.  This is simple code which creates HttpClient object and tries to send the file to a web API.

As you are doing this from one API to another, you will have to save file first at temporary location.  That temporary location will be parameter to this method.

Also, After upload you may want to delete the file if it is not required.   This private method you can call after file upload to your first API is complete.

private async Task<string> UploadFile(string filePath)
{
    _logger.LogInformation($"Uploading a text file [{filePath}].");
    if (string.IsNullOrWhiteSpace(filePath))
    {
        throw new ArgumentNullException(nameof(filePath));
    }

    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"File [{filePath}] not found.");
    }
    using var form = new MultipartFormDataContent();
    using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(filePath));
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    form.Add(fileContent, "file", Path.GetFileName(filePath));
    form.Add(new StringContent("789"), "userId");
    form.Add(new StringContent("some comments"), "comment");
    form.Add(new StringContent("true"), "isPrimary");

    var response = await _httpClient.PostAsync($"{_url}/api/files", form);
    response.EnsureSuccessStatusCode();
    var responseContent = await response.Content.ReadAsStringAsync();
    var result = JsonSerializer.Deserialize<FileUploadResult>(responseContent);
    _logger.LogInformation("Uploading is complete.");
    return result.Guid;
}

Hope this helps you.


问:
Arrays.fill with multidimensional array in Java
How can I fill a multidimensional array in Java without using a loop? I've tried:

```<code>double[][] arr = new double[20][4];
Arrays.fill(arr, 0);
</code>```

This results in java.lang.ArrayStoreException: java.lang.Double

答:
Arrays.fill works only with one-dimensional array

Source of java.util.Arrays:

```<code>public static void fill(Object[] a, Object val) {
        int i = 0;

        for(int len = a.length; i < len; ++i) {
            a[i] = val;
        }
</code>```

Use own loops for initialization array

Body:
How can I fill a multidimensional array in Java without using a loop? I've tried:

double[][] arr = new double[20][4];
Arrays.fill(arr, 0);

This results in java.lang.ArrayStoreException: java.lang.Double

Body:
Arrays.fill works only with one-dimensional array

Source of java.util.Arrays:

public static void fill(Object[] a, Object val) {
        int i = 0;

        for(int len = a.length; i < len; ++i) {
            a[i] = val;
        }

Use own loops for initialization array


问:
gitlab ci error could not translate host name "postgres" to address: Name does not resolve
I use gitlab-ci in my rails app, it ran correctly till yesterday
but it does not pass due to:

```<code>rake aborted!
PG::ConnectionBad: could not translate host name "postgres" to address: Name does not resolve
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `initialize'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `new'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `connect'
....
Tasks: TOP => db:schema:load => db:check_protected_environments
</code>```

.gitlab-ci.yml :

```<code>rspec:
  stage: test
  services:
    - postgres:10
  variables:
    DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB"
    POSTGRES_DB: db_test
    RAILS_ENV: test
  before_script:
    - ruby -v
  script:
    - cp config/application.sample.yml config/application.yml
    - cp config/database.sample.yml config/database.yml
    - bundle exec rake db:schema:load
    - bundle exec rspec spec

</code>```

It seems it can not find the postgres service running or for some reason the database service is not running correctly, I guess some internals has changed in gitlab-ci.

答:
EDIT: This was an intended change to the images, you now must set a password or configure further:

If you know that you want to be insecure (i.e. any one can connect without a password from anywhere), then POSTGRES_HOST_AUTH_METHOD=trust is how you opt in to that.

This seems to have been introduced when the docker images were upgraded to the new releases.

You can pull the 10.11 image instead to avoid this problem for the time being:

```<code>services:
- postgres:10.11
</code>```

Not sure why this is happening, but we are experiencing the same since the last docker image update. I have found this to also be the case going from 12.1 to 12.2.

Body:
I use gitlab-ci in my rails app, it ran correctly till yesterday
but it does not pass due to:

rake aborted!
PG::ConnectionBad: could not translate host name "postgres" to address: Name does not resolve
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `initialize'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `new'
/usr/local/bundle/gems/pg-1.1.4/lib/pg.rb:56:in `connect'
....
Tasks: TOP => db:schema:load => db:check_protected_environments

.gitlab-ci.yml :

rspec:
  stage: test
  services:
    - postgres:10
  variables:
    DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB"
    POSTGRES_DB: db_test
    RAILS_ENV: test
  before_script:
    - ruby -v
  script:
    - cp config/application.sample.yml config/application.yml
    - cp config/database.sample.yml config/database.yml
    - bundle exec rake db:schema:load
    - bundle exec rspec spec

It seems it can not find the postgres service running or for some reason the database service is not running correctly, I guess some internals has changed in gitlab-ci.

Body:
EDIT: This was an intended change to the images, you now must set a password or configure further:

If you know that you want to be insecure (i.e. any one can connect without a password from anywhere), then POSTGRES_HOST_AUTH_METHOD=trust is how you opt in to that.

This seems to have been introduced when the docker images were upgraded to the new releases.

You can pull the 10.11 image instead to avoid this problem for the time being:

services:
- postgres:10.11

Not sure why this is happening, but we are experiencing the same since the last docker image update. I have found this to also be the case going from 12.1 to 12.2.


问:
Apache Flink - Can not create Hourly/Daily Log File with Log4j
I can not create daily and also hourly log file (especially for taskexecutor log) with log4j

Here is the my log4j.properties

```<code># This affects logging for both user code and Flink
log4j.rootLogger=INFO, file

# Uncomment this if you want to _only_ change Flink's logging
#log4j.logger.org.apache.flink=INFO

# The following lines keep the log level of common libraries/connectors on
# log level INFO. The root logger does not override this. You have to manually
# change the log levels here.
log4j.logger.akka=INFO
log4j.logger.org.apache.kafka=INFO
log4j.logger.org.apache.hadoop=INFO
log4j.logger.org.apache.zookeeper=INFO

# Log all infos in the given file
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${log.file}
log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH
log4j.appender.file.append=false
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n
</code>```

${log.file} points to :

2020-02-13 17:40:51,105 INFO  org.apache.flink.runtime.taskexecutor.TaskManagerRunner       -     -Dlog.file=/.../flink-1.9.1/log/flink-tarantula-taskexecutor-0-...log
```

<ul>
<li><p>In the meantime there is a logback.xml configuration also(which one flink uses ? )</p></li>
<li><p>logback.xml file :</p></li>
</ul>

<pre class="lang-xml prettyprint-override"><code><configuration>
    <appender name="file" class="ch.qos.logback.core.FileAppender">
        <file>${log.file}</file>
        <append>false</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{60} %X{sourceThread} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- This affects logging for both user code and Flink -->
    <root level="INFO">
        <appender-ref ref="file"/>
    </root>

    <!-- Uncomment this if you want to only change Flink's logging -->
    <!--<logger name="org.apache.flink" level="INFO">-->
        <!--<appender-ref ref="file"/>-->
    <!--</logger>-->

    <!-- The following lines keep the log level of common libraries/connectors on
         log level INFO. The root logger does not override this. You have to manually
         change the log levels here. -->
    <logger name="akka" level="INFO">
        <appender-ref ref="file"/>
    </logger>
    <logger name="org.apache.kafka" level="INFO">
        <appender-ref ref="file"/>
    </logger>
    <logger name="org.apache.hadoop" level="INFO">
        <appender-ref ref="file"/>
    </logger>
    <logger name="org.apache.zookeeper" level="INFO">
        <appender-ref ref="file"/>
    </logger>

    <!-- Suppress the irrelevant (wrong) warnings from the Netty channel handler -->
    <logger name="org.apache.flink.shaded.akka.org.jboss.netty.channel.DefaultChannelPipeline" level="ERROR">
        <appender-ref ref="file"/>
    </logger>
</configuration>
</code>```

here is the flink/lib folder
apache-log4j-extras-1.2.17.jar  flink-dist_2.11-1.9.1.jar  flink-table_2.11-1.9.1.jar  flink-table-blink_2.11-1.9.1.jar  log4j-1.2.17.jar  slf4j-log4j12-1.7.15.jar

Solution Finally

After all tried, I found the solution, I could not create daily log file because of this statement was blocking creating daily file(s).

```<code>log4j.logger.org.apache.flink.shaded.akka.org.jboss.netty.channel.DefaultChannelPipeline=ERROR, filelog4j.rootLogger=INFO, file
</code>```

Example of creating logs at midday and midnight of each day.

```<code>log4j.category.org.apache.flink.shaded.akka.org.jboss.netty.channel.DefaultChannelPipeline=ERROR, nettyFileAppender
log4j.rootLogger=INFO, file

# Uncomment this if you want to _only_ change Flink's logging
#log4j.logger.org.apache.flink=INFO

# The following lines keep the log level of common libraries/connectors on
# log level INFO. The root logger does not override this. You have to manually
# change the log levels here.
log4j.logger.akka=INFO
log4j.logger.org.apache.kafka=INFO
log4j.logger.org.apache.hadoop=INFO
log4j.logger.org.apache.zookeeper=INFO

# Log all infos in the given file
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=${log.file}
log4j.appender.file.append=false
log4j.appender.file.DatePattern='.'yyyy-MM-dd-a
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n

# Suppress the irrelevant (wrong) warnings from the Netty channel handler
log4j.appender.nettyFileAppender=org.apache.log4j.FileAppender
log4j.appender.nettyFileAppender.file=/path/to/nettyLog/nettyChannelIrrelevant.log
log4j.appender.nettyFileAppender.append=false
log4j.appender.nettyFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.nettyFileAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n
</code>```

答:
You don't specify how you provide your log4j.properties file. But a common issue is that someone has this file in their jar, and it gets ignored, because Flink will use the conf/log4j.properties file located on the cluster.

And assuming your jar doesn't include anything other than classes from the slf4j-api jar, then Flink will pick up the slf4j-log4j12.jar in flink/lib (since that's on the classpath), and thus use log4j (not logback), so the logback.xml configuration file is ignored.

Body:
I can not create daily and also hourly log file (especially for taskexecutor log) with log4j

Here is the my log4j.properties

# This affects logging for both user code and Flink
log4j.rootLogger=INFO, file

# Uncomment this if you want to _only_ change Flink's logging
#log4j.logger.org.apache.flink=INFO

# The following lines keep the log level of common libraries/connectors on
# log level INFO. The root logger does not override this. You have to manually
# change the log levels here.
log4j.logger.akka=INFO
log4j.logger.org.apache.kafka=INFO
log4j.logger.org.apache.hadoop=INFO
log4j.logger.org.apache.zookeeper=INFO

# Log all infos in the given file
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${log.file}
log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH
log4j.appender.file.append=false
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n

${log.file} points to :

2020-02-13 17:40:51,105 INFO  org.apache.flink.runtime.taskexecutor.TaskManagerRunner       -     -Dlog.file=/.../flink-1.9.1/log/flink-tarantula-taskexecutor-0-...log

In the meantime there is a logback.xml configuration also(which one flink uses ? )

logback.xml file :

<configuration>
    <appender name="file" class="ch.qos.logback.core.FileAppender">
        <file>${log.file}</file>
        <append>false</append>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{60} %X{sourceThread} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="file"/>
    </root>

    <logger name="akka" level="INFO">
        <appender-ref ref="file"/>
    </logger>
    <logger name="org.apache.kafka" level="INFO">
        <appender-ref ref="file"/>
    </logger>
    <logger name="org.apache.hadoop" level="INFO">
        <appender-ref ref="file"/>
    </logger>
    <logger name="org.apache.zookeeper" level="INFO">
        <appender-ref ref="file"/>
    </logger>

    <logger name="org.apache.flink.shaded.akka.org.jboss.netty.channel.DefaultChannelPipeline" level="ERROR">
        <appender-ref ref="file"/>
    </logger>
</configuration>

here is the flink/lib folder
apache-log4j-extras-1.2.17.jar  flink-dist_2.11-1.9.1.jar  flink-table_2.11-1.9.1.jar  flink-table-blink_2.11-1.9.1.jar  log4j-1.2.17.jar  slf4j-log4j12-1.7.15.jar

Solution Finally

After all tried, I found the solution, I could not create daily log file because of this statement was blocking creating daily file(s).

log4j.logger.org.apache.flink.shaded.akka.org.jboss.netty.channel.DefaultChannelPipeline=ERROR, filelog4j.rootLogger=INFO, file

Example of creating logs at midday and midnight of each day.

log4j.category.org.apache.flink.shaded.akka.org.jboss.netty.channel.DefaultChannelPipeline=ERROR, nettyFileAppender
log4j.rootLogger=INFO, file

# Uncomment this if you want to _only_ change Flink's logging
#log4j.logger.org.apache.flink=INFO

# The following lines keep the log level of common libraries/connectors on
# log level INFO. The root logger does not override this. You have to manually
# change the log levels here.
log4j.logger.akka=INFO
log4j.logger.org.apache.kafka=INFO
log4j.logger.org.apache.hadoop=INFO
log4j.logger.org.apache.zookeeper=INFO

# Log all infos in the given file
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=${log.file}
log4j.appender.file.append=false
log4j.appender.file.DatePattern='.'yyyy-MM-dd-a
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n

# Suppress the irrelevant (wrong) warnings from the Netty channel handler
log4j.appender.nettyFileAppender=org.apache.log4j.FileAppender
log4j.appender.nettyFileAppender.file=/path/to/nettyLog/nettyChannelIrrelevant.log
log4j.appender.nettyFileAppender.append=false
log4j.appender.nettyFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.nettyFileAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %-60c %x - %m%n


问:
Instagram displaying lasts posts in IONIC 4 applications
I've developed an IONIC 4 application which uses as backend an Wordpress site. All good until I decided to display on a page my lasts instagram photos. ( So nothing fancy, just some gallery with lasts photos)

The thing is, on Wordpress I have an Instagram plugin which does that, and I'd like to know If I can use the already generated token from Wordpress in my IONIC 4 application.

The Wordpress plugin is called Edge instagram widget, and basicly I've already done the steps necessary for authenticating my website, and retrieve a valid Instagram token.

答:
Digging more here on SO, I stumbled upon the answer to my question. Actually the Instagram token is in my site database, so using it with this anwser will retrive last media posts on instagram.

You can format the output in html or json, depending how you want to treat the results.

Thank you SO


问:
Width and Height not doing effect when trying to resize an image inside a div
I'm trying to resize my image inside a form but width and height are not doing any effect.

```<code>.sectionForm {
        display: table;
        margin: 0 auto;
        background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
        width: 100px;
        height: 100px;
    }
</code>```

.sectionForm {
  display: table;
  margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
  width: 100px;
  height: 100px;
}

.sectionForm form {
  width: 400px;
  box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
  border-radius: 40px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 66px 0 50px 0;
}

footer {
  height: 1500px;
}

.footer-content {
  display: flex;
  flex-direction: column;
  display: table;
  margin: 0 auto;
}

.form-container input {
  border: none;
  border-bottom: 1px solid #828282;
  padding: 26px 0;
  margin-bottom: 100px;
  font-size: 20px;
  color: #4F4F4F;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sectionForm">
  <form>
    <div class="form-container">
      <input type="text" id="fname" name="fname" value="Nome">
      <input type="text" id="lname" name="lname" value="E-mail">
      <input type="text" id="lname" name="lname" value="Assunto">

    </div>
  </form>
</div></code>```

答:
What you need in this case is not width and height, but background-size.

Try using background-size: 100px 100px; one is for width and the other one is for height. You can also use percentages or background-size: cover and background-size: contain depending on your needs.

Body:
I'm trying to resize my image inside a form but width and height are not doing any effect.

.sectionForm {
        display: table;
        margin: 0 auto;
        background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
        width: 100px;
        height: 100px;
    }

.sectionForm {
  display: table;
  margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
  width: 100px;
  height: 100px;
}

.sectionForm form {
  width: 400px;
  box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
  border-radius: 40px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 66px 0 50px 0;
}

footer {
  height: 1500px;
}

.footer-content {
  display: flex;
  flex-direction: column;
  display: table;
  margin: 0 auto;
}

.form-container input {
  border: none;
  border-bottom: 1px solid #828282;
  padding: 26px 0;
  margin-bottom: 100px;
  font-size: 20px;
  color: #4F4F4F;
}

  <form>

      <input type="text" id="fname" name="fname" value="Nome">
      <input type="text" id="lname" name="lname" value="E-mail">
      <input type="text" id="lname" name="lname" value="Assunto">

  </form>


问:
java - live view on collection contained within a collection contained within ... etc
I have a class A which can contain many instances of class B which may in turn contain many instances of Class C, which can contain many instances of class D

Now, in class A I have a method getAllD. Currently every time this is called there is a lot of iterating that takes place, and a rather large list is freshly created and returned. This cannot be very efficient.

I was wondering how I could do this better. This question Combine multiple Collections into a single logical Collection? seems to touch upon a similar topic, but I'm not really sure how I could apply it to my situation.

All comments are much appreciated!

答:
Actually, I think Iterables.concat (or IteratorChain from Apache Commons) would work fine for your case:

```<code>class A {
    Collection<B> children;
    Iterator<D> getAllD() {
        Iterator<Iterator<D>> iters = new ArrayList<Iterator<D>>();
        for (B child : children) {
            iters.add(child.getAllD());
        }
        Iterator<D> iter = Iterables.concat(iters);
        return iter;
    }
}
class B {
    Collection<C> children;
    Iterator<D> getAllD() {
        Iterator<Iterator<D>> iters = new ArrayList<Iterator<D>>();
        for (C child : children) {
            iters.add(child.getAllD());
        }
        Iterator<D> iter = Iterables.concat(iters);
        return iter;
    }
}
class C {
    Collection<D> children;
    Iterator<D> getAllD() {
        Iterator<D> iter = children.iterator();
        return iter;
    }
}
</code>```

Body:
Actually, I think Iterables.concat (or IteratorChain from Apache Commons) would work fine for your case:

class A {
    Collection<B> children;
    Iterator<D> getAllD() {
        Iterator<Iterator<D>> iters = new ArrayList<Iterator<D>>();
        for (B child : children) {
            iters.add(child.getAllD());
        }
        Iterator<D> iter = Iterables.concat(iters);
        return iter;
    }
}
class B {
    Collection<C> children;
    Iterator<D> getAllD() {
        Iterator<Iterator<D>> iters = new ArrayList<Iterator<D>>();
        for (C child : children) {
            iters.add(child.getAllD());
        }
        Iterator<D> iter = Iterables.concat(iters);
        return iter;
    }
}
class C {
    Collection<D> children;
    Iterator<D> getAllD() {
        Iterator<D> iter = children.iterator();
        return iter;
    }
}


问:
finding whats wrong with my code,solving a easy competitive problem
QN;Here is the question.i dont know where my algorithm is wrong.help me find pls

Given an array A of N length. We need to calculate the next greater element for each element in given array. If next greater element is not available in given array then we need to fill ‘_’ at that index place.

Input:
The first line contains an integer T, the number of test cases. For each test case, the first line contains an integer n, the size of the array. Next line contains n space separated integers denoting the elements of the array.

Output:
For each test case, the output is an array that displays next greater element to element at that index.

```<code>Constraints:
1 <= T <= 100
1 <= N <= 100
-106 <= Ai <= 106

Example:
Input
2
9
6 3 9 8 10 2 1 15 7
4
13 6 7 12

Output:
7 6 10 9 15 3 2 _ 8
_ 7 12 13
</code>```

Explanation:
Testcase 1: Here every element of the array has next greater element but at index 7, 15 is the greatest element of given array and no other element is greater from 15 so at the index of 15 we fill with ''.
Testcase 2: Here, at index 0, 13 is the greatest value in given array and no other array element is greater from 13 so at index 0 we fill ''.

My solution:

```<code>//NOT SOLVED YET
#include<iostream>
using namespace std;
int main()
{
    int a[10]={6 ,3 ,9, 8 ,10, 2 ,1, 15, 7};
    int b[10],flag=0,big=-1,i,j;
    for(i=0;i<10;i++)
    {
        for(j=0;j<10;j++)
        {
            if(i==j)continue;
            if((a[j]>a[i]) && (flag==0))
            {
                big=a[j];
                flag=1;
            }
            else if(a[j]<big && big>a[i] && flag==1)
                big=a[j];

        }
        if(big==-1)cout<<'_';
        else cout<<big<<' ';
        big=-1;
        flag=0;
    }

}
</code>```

the output i get is:

```<code> 2 2 2 2 7 1 0 _ 2 1
</code>```

答:
To expand on what others have mentioned - that you currently have an O(N^2) algorithm, and this can be done more efficiently.

I don't think you can get O(N) here, but here is a plan for an O(N log N) algorithm:

For each test case:

Load the Ai values into two arrays, let's call them X and Y

Sort the Y array

Iterate over X and for each element of X do a binary search into Y to find the next larger value of Ai: use that as the output, or use _ if you did not find one

I recommend, for practice purposes, implementing this both using the C++ standard library, using https://en.cppreference.com/w/cpp/algorithm/sort and https://en.cppreference.com/w/cpp/algorithm/upper_bound , and implementing the above two functions yourself, see: https://en.wikipedia.org/wiki/Quicksort

Body:
QN;Here is the question.i dont know where my algorithm is wrong.help me find pls

Given an array A of N length. We need to calculate the next greater element for each element in given array. If next greater element is not available in given array then we need to fill ‘_’ at that index place.

Input:
The first line contains an integer T, the number of test cases. For each test case, the first line contains an integer n, the size of the array. Next line contains n space separated integers denoting the elements of the array.

Output:
For each test case, the output is an array that displays next greater element to element at that index.

Constraints:
1 <= T <= 100
1 <= N <= 100
-106 <= Ai <= 106

Example:
Input
2
9
6 3 9 8 10 2 1 15 7
4
13 6 7 12

Output:
7 6 10 9 15 3 2 _ 8
_ 7 12 13

Explanation:
Testcase 1: Here every element of the array has next greater element but at index 7, 15 is the greatest element of given array and no other element is greater from 15 so at the index of 15 we fill with ''.
Testcase 2: Here, at index 0, 13 is the greatest value in given array and no other array element is greater from 13 so at index 0 we fill ''.

My solution:

//NOT SOLVED YET
#include<iostream>
using namespace std;
int main()
{
    int a[10]={6 ,3 ,9, 8 ,10, 2 ,1, 15, 7};
    int b[10],flag=0,big=-1,i,j;
    for(i=0;i<10;i++)
    {
        for(j=0;j<10;j++)
        {
            if(i==j)continue;
            if((a[j]>a[i]) && (flag==0))
            {
                big=a[j];
                flag=1;
            }
            else if(a[j]<big && big>a[i] && flag==1)
                big=a[j];

        }
        if(big==-1)cout<<'_';
        else cout<<big<<' ';
        big=-1;
        flag=0;
    }

}

the output i get is:

 2 2 2 2 7 1 0 _ 2 1


问:
Gradle : why this build.gradle.kts script fails to produce any java class?
Below is a build.gradle.kts script which applies to kotlin code located at src/main/kotlin.

It is an attempt of the translation from a groovy script which runs correctly.

The gradlew build steps has no error, but fails to produce any java class from the kotlin code. What instruction is missing ?

```<code>buildscript {

    repositories {
        jcenter()
    }

    dependencies {
        classpath(kotlin("gradle-plugin", version = "1.2.70"))
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.70")
        classpath("com.github.ben-manes:gradle-versions-plugin:0.20.0")
    }
}

plugins {
    jacoco
    java
    application
    "com.github.ben-manes.versions"
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

jacoco {
 toolVersion = "0.8.1"
}

repositories {
    jcenter()
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-stdlib:1.2.70")
    implementation("com.squareup.moshi:moshi:1.4.0")
    implementation("com.squareup.okhttp3:okhttp:3.11.0")

    testImplementation("junit:junit:4.12")
    testImplementation("org.mockito:mockito-core:2.12.0")
    testImplementation("com.squareup.okhttp3:mockwebserver:3.11.0")
    testImplementation("org.assertj:assertj-core:3.10.0")
}

application {
    mainClassName = "io.ipfs.kotlin.MainKt"
}
</code>```

答:
You've added the Kotlin plugin to the build script here:

```<code>buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath(kotlin("gradle-plugin", version = "1.2.70"))
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.70")
        classpath("com.github.ben-manes:gradle-versions-plugin:0.20.0")
    }
}
</code>```

but you have not applied it

```<code>plugins {
    jacoco
    java
    application
    "com.github.ben-manes.versions"
    // No kotlin plugin actually applied here!
}
</code>```

Actually, buildscript Kotlin configuration is not needed, as the Kotlin plugin is published to the Gradle's plugins directory. So you can just apply it as simple as:

```<code>plugins {
    kotlin("jvm").version("1.2.70")
}
</code>```

Body:
Below is a build.gradle.kts script which applies to kotlin code located at src/main/kotlin.

It is an attempt of the translation from a groovy script which runs correctly.

The gradlew build steps has no error, but fails to produce any java class from the kotlin code. What instruction is missing ?

buildscript {

    repositories {
        jcenter()
    }

    dependencies {
        classpath(kotlin("gradle-plugin", version = "1.2.70"))
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.70")
        classpath("com.github.ben-manes:gradle-versions-plugin:0.20.0")
    }
}

plugins {
    jacoco
    java
    application
    "com.github.ben-manes.versions"
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}

jacoco {
 toolVersion = "0.8.1"
}

repositories {
    jcenter()
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-stdlib:1.2.70")
    implementation("com.squareup.moshi:moshi:1.4.0")
    implementation("com.squareup.okhttp3:okhttp:3.11.0")

    testImplementation("junit:junit:4.12")
    testImplementation("org.mockito:mockito-core:2.12.0")
    testImplementation("com.squareup.okhttp3:mockwebserver:3.11.0")
    testImplementation("org.assertj:assertj-core:3.10.0")
}

application {
    mainClassName = "io.ipfs.kotlin.MainKt"
}

Body:
You've added the Kotlin plugin to the build script here:

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath(kotlin("gradle-plugin", version = "1.2.70"))
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.70")
        classpath("com.github.ben-manes:gradle-versions-plugin:0.20.0")
    }
}

but you have not applied it

plugins {
    jacoco
    java
    application
    "com.github.ben-manes.versions"
    // No kotlin plugin actually applied here!
}

Actually, buildscript Kotlin configuration is not needed, as the Kotlin plugin is published to the Gradle's plugins directory. So you can just apply it as simple as:

plugins {
    kotlin("jvm").version("1.2.70")
}