问:
Populating a static array using multiple threads
I am trying to populate a static array using multiple threads. The suggested usage of join() in https://stackoverflow.com/a/1492077/10418317 seems to be imposing a specific order on the threads. I want them to run in parallel if they can so as to speed up the whole process

     Assigment

```<code>    public class Assigment {

    public static int minPrime;
    public static int maxPrime;
    public static int[] masterMin = new int[10];
    public static int[] masterMax = new int[10];
    public static void main(String[] args) {
    // TODO code application logic here

    for(int i = 1; i < 11;i++){
     Thread thread = new Thread(new NumGenerator(i));
     thread.start();
     System.out.println("Thread " + i + " generating nums");

    }

    Arrays.sort(masterMin);
     Arrays.sort(masterMax);
     minPrime = masterMin[0];
     maxPrime = masterMax[9];
     System.out.println("<------------------------------>");
     System.out.println("Max Prime is " + maxPrime);
     System.out.println("Min Prime is " + minPrime);
 }

}
</code>```

NumGenerator

```<code>public class NumGenerator implements Runnable {
int[] numbers;
int thrnum;
public NumGenerator(int thrnum){
    this.thrnum = thrnum;
}
@Override
public void run(){
Random rand = new Random();
 numbers = new int[3000];

for(int i = 0; i<3000; i++){
    numbers[i] = rand.nextInt(899999)+1;

     }
Searcher searcher = new Searcher(numbers);
Assigment.masterMax[thrnum-1] = searcher.max;
Assigment.masterMin[thrnum-1] = searcher.min;

}
</code>```

I am trying to sort the array after every thread has completed inputting into it and then print out the first and the last i.e the smallest and the largest values.The problem is that the arrays masterMin and masterMax seem to be still having all zero entries after the supposed population through Assigment.masterMin[thrnum-1] = searcher.min; Searcher is another class which is actually giving me non-zero values for search.max and search.max as expected.

答:
@jhamon has already explained the reason. (That the threads have not completed)

How to solve it? Convert the part where you are starting threads to something like this using ExecutorService.

```<code>ExecutorService svc = Executors.newFixedThreadPool( 10 );
for(int i = 1; i < 11;i++){
 //Thread thread = new Thread(new NumGenerator(i));
 //thread.start();
    svc.submit( () -> new NumGenerator( i ) );
    System.out.println("Thread " + i + " generating nums");
}

svc.shutdown();
svc.awaitTermination( 2, TimeUnit.MINUTES );

//Now, print the values.
</code>```

Body:
I am trying to populate a static array using multiple threads. The suggested usage of join() in https://stackoverflow.com/a/1492077/10418317 seems to be imposing a specific order on the threads. I want them to run in parallel if they can so as to speed up the whole process

     Assigment

    public class Assigment {

    public static int minPrime;
    public static int maxPrime;
    public static int[] masterMin = new int[10];
    public static int[] masterMax = new int[10];
    public static void main(String[] args) {
    // TODO code application logic here

    for(int i = 1; i < 11;i++){
     Thread thread = new Thread(new NumGenerator(i));
     thread.start();
     System.out.println("Thread " + i + " generating nums");

    }

    Arrays.sort(masterMin);
     Arrays.sort(masterMax);
     minPrime = masterMin[0];
     maxPrime = masterMax[9];
     System.out.println("<------------------------------>");
     System.out.println("Max Prime is " + maxPrime);
     System.out.println("Min Prime is " + minPrime);
 }

}

NumGenerator

public class NumGenerator implements Runnable {
int[] numbers;
int thrnum;
public NumGenerator(int thrnum){
    this.thrnum = thrnum;
}
@Override
public void run(){
Random rand = new Random();
 numbers = new int[3000];

for(int i = 0; i<3000; i++){
    numbers[i] = rand.nextInt(899999)+1;

     }
Searcher searcher = new Searcher(numbers);
Assigment.masterMax[thrnum-1] = searcher.max;
Assigment.masterMin[thrnum-1] = searcher.min;

}

I am trying to sort the array after every thread has completed inputting into it and then print out the first and the last i.e the smallest and the largest values.The problem is that the arrays masterMin and masterMax seem to be still having all zero entries after the supposed population through Assigment.masterMin[thrnum-1] = searcher.min; Searcher is another class which is actually giving me non-zero values for search.max and search.max as expected.

Body:
@jhamon has already explained the reason. (That the threads have not completed)

How to solve it? Convert the part where you are starting threads to something like this using ExecutorService.

ExecutorService svc = Executors.newFixedThreadPool( 10 );
for(int i = 1; i < 11;i++){
 //Thread thread = new Thread(new NumGenerator(i));
 //thread.start();
    svc.submit( () -> new NumGenerator( i ) );
    System.out.println("Thread " + i + " generating nums");
}

svc.shutdown();
svc.awaitTermination( 2, TimeUnit.MINUTES );

//Now, print the values.


来源: stackexchange

问:
Reactjs Access class method outside the class but in same file
I have this code and want to access a class method outside the class in AssetsMap array.

```<code>import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background.jpg']
]);

class AssetsManager {

    constructor...

    getConfigValue(key, defaultValue) { ... }

}

</code>```

if I try to access getConfigValue method inside map array somethings like this

```<code>[AssetsEnum.background, 'common/background'+this.getConfigValue()+'.jpg']

</code>```

the console throws error that getConfigValue is not defined. How should I access the method?

答:
To be able to access a class method, you will need to have a reference to the class instance. E.g.

import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

class AssetsManager {

    constructor...

    getConfigValue(key, defaultValue) { ... }

}

const manager = new AssetsManager();

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background' + manager.getConfigValue() + '.jpg']
]);
```

<p>If the <code>getConfigValue</code> method doesn't use properties from the AssetsManager class, you could also make the method <code>static</code>. Then it will become possible to use this method without having an instance of the class.</p>

<pre class="lang-js prettyprint-override"><code>import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background' + AssetsManager.getConfigValue() + '.jpg']
]);

class AssetsManager {

    constructor...

    static getConfigValue(key, defaultValue) { ... }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this code and want to access a class method outside the class in AssetsMap array.

import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background.jpg']
]);

class AssetsManager {

    constructor...

    getConfigValue(key, defaultValue) { ... }

}

if I try to access getConfigValue method inside map array somethings like this

[AssetsEnum.background, 'common/background'+this.getConfigValue()+'.jpg']

the console throws error that getConfigValue is not defined. How should I access the method?

Body:
To be able to access a class method, you will need to have a reference to the class instance. E.g.

import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

class AssetsManager {

    constructor...

    getConfigValue(key, defaultValue) { ... }

}

const manager = new AssetsManager();

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background' + manager.getConfigValue() + '.jpg']
]);

If the getConfigValue method doesn't use properties from the AssetsManager class, you could also make the method static. Then it will become possible to use this method without having an instance of the class.

import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background' + AssetsManager.getConfigValue() + '.jpg']
]);

class AssetsManager {

    constructor...

    static getConfigValue(key, defaultValue) { ... }

}


问:
How can i Change tab background color on selection using javascript?
Although the question is really common I really couldn't quite find a definite answer. I have two tabs 'Tab1' and 'Tab2' I want the color of the active tab to change when the user clicks on it. Is there any way I can do it by pure js?

CSS

```<code>#tab1:hover, #tab2:hover, #tab3:hover {
  background: teal;
}

#tab1Content, #tab2Content, #tab3Content {
  width: 500px;
  height: 100px;
  padding: 20px;
  border: 1px solid #B00098;
  border-radius: 10px;
}

.tab button{
      color:#1e84d8;
    /*margin-bottom: 0 px;*/
    background-color: #e7f6ff;
    float: left;
    cursor: pointer;
    transition: 0.1s;
    width:50%;
    border-top: 1px solid #ebebeb;
    border-left: 1px solid #ebebeb;
    border-right: none;
    border-bottom: 1px solid #20a3eb;
}
      #tab1btn{
                border: 1px solid rgb(19, 18, 18);
                padding: 20px;
                overflow: hidden;
                color: rgb(16, 8, 32);
                font-size: 25px;
                font-style: initial;
                font-family: 'Times New Roman', Times, serif;
            }

      #tab2btn{
                border: 1px solid rgb(19, 18, 18);
                padding: 20px;
                overflow: hidden;
                color: rgb(16, 8, 32);
                font-size: 25px;
                font-style: initial;
                font-family: 'Times New Roman', Times, serif;
            }
</code>```

HTML

```<code><div class="tab" >
  <button  id= "tab1btn"  value="Chasis_1">Chasis 1</button>
  <button  id= "tab2btn" value="Chasis_2" >Chasis 2</button>
</div>
</code>```

答:
You can use this not necessarily you need to use js from what I understood from your question this might be solution you are looking for

https://www.w3schools.com/cssref/sel_focus.asp

It is basically the Css selector focus

So you do element:focus then you can change the color

Body:
Although the question is really common I really couldn't quite find a definite answer. I have two tabs 'Tab1' and 'Tab2' I want the color of the active tab to change when the user clicks on it. Is there any way I can do it by pure js?

CSS

#tab1:hover, #tab2:hover, #tab3:hover {
  background: teal;
}

#tab1Content, #tab2Content, #tab3Content {
  width: 500px;
  height: 100px;
  padding: 20px;
  border: 1px solid #B00098;
  border-radius: 10px;
}

.tab button{
      color:#1e84d8;
    /*margin-bottom: 0 px;*/
    background-color: #e7f6ff;
    float: left;
    cursor: pointer;
    transition: 0.1s;
    width:50%;
    border-top: 1px solid #ebebeb;
    border-left: 1px solid #ebebeb;
    border-right: none;
    border-bottom: 1px solid #20a3eb;
}
      #tab1btn{
                border: 1px solid rgb(19, 18, 18);
                padding: 20px;
                overflow: hidden;
                color: rgb(16, 8, 32);
                font-size: 25px;
                font-style: initial;
                font-family: 'Times New Roman', Times, serif;
            }

      #tab2btn{
                border: 1px solid rgb(19, 18, 18);
                padding: 20px;
                overflow: hidden;
                color: rgb(16, 8, 32);
                font-size: 25px;
                font-style: initial;
                font-family: 'Times New Roman', Times, serif;
            }

HTML

  <button  id= "tab1btn"  value="Chasis_1">Chasis 1</button>
  <button  id= "tab2btn" value="Chasis_2" >Chasis 2</button>


问:
How to add a search bar to a react app that filter data from an api?
I am working on a project however i need to add an input where a user can filter the list of students
by their name (both first and last name), I have gotten the data from the api the issue is figuring out how to filter the data as I am fairly new to react. Some help would be appreciated. Below is what I have so far.</p>

```<code>import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import StudentData from './student_data/StudentData'
import './App.css';

function App() {
  const [students, setStudents] = useState(null);
  const studentdata = 'https://www.hatchways.io/api/assessment/students';

  function getStudents(){
    fetch(studentdata)
      .then(resp => resp.json())
      .then(data => {
        setStudents(data);
      })
  }

  return (
    <div className="App">
      <h1>Students</h1>

      <div>
        <button className="fetch-button" onClick={getStudents}>
          Get Students
        </button>
        <br />
      </div>

      <div className="search" id="search">
          <input type="text" ></input>
      </div>

      {students && students.students.map((student, index) => {
       var total = 0;
       for(var i = 0; i < student.grades.length; i++) {
        var grade = parseInt(student.grades[i]);
        total += grade;
       }
       const avg = total / student.grades.length;
       const average = avg.toString();

      return(
      <div className="student" key={index}>
        <div className="image">
          <img src={student.pic} id="icon"></img>
        </div>

        <div className="text">
          <h3 id="name">{student.firstName} {student.lastName}</h3>
          <p id="detail"><strong>EMAIL:</strong> {student.email}</p>
          <p id="detail"><strong>COMPANY:</strong> {student.company}</p>
          <p id="detail"><strong>SKILL:</strong> {student.skill}</p>
          <p id="detail"><strong>AVERAGE:</strong>: {average}%</p>
        </div>
      </div>

      )}
      )}
    </div>
  );
}

export default App;
</code>```

答:
Modified the code little bit and check this helps with the filter. </p>

```<code>import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [students, setStudents] = useState(null);
  const [filterData, setFilterData ] = useState(null);

  const studentdata = 'https://www.hatchways.io/api/assessment/students';

  function getStudents(){
    fetch(studentdata)
      .then(resp => resp.json())
      .then(data => {
        setFilterData(data.students);
        setStudents(data.students);
      })
  }

  const searchByName = (event) => {
    event.persist();
    // Get the search term
    const searchItem = event.target.value.trim();
    // If search term is empty fill with full students data
    if(!searchItem.trim()) {
      setFilterData(students);
    }
    // Search the name and if it found retun the same array
    const serachIn = (firstName, lastName) => {
      if(firstName.indexOf(searchItem) !== -1 || lastName.indexOf(searchItem) !== -1) {
        return true;
      }
      let fullName = firstName+" "+lastName;
      if(fullName.indexOf(searchItem) !== -1) {
        return true;
      }
      return false;
    };
    // Filter the array
    const filteredData = students.filter((item) => {
      return serachIn(item.firstName, item.lastName);
    });
    // Set the state with filtered data
    setFilterData(filteredData);
  }

   return (
    <div className="App">
      <h1>Students</h1>

      <div>
        <button className="fetch-button" onClick={getStudents}>
          Get Students
        </button>
        <br />
      </div>

      <div className="search" id="search">
          <input type="text" name="serachByName" onChange={(e) => searchByName(e)} ></input>
      </div>

      {filterData && filterData.map((student, index) => {
       var total = 0;
       for(var i = 0; i < student.grades.length; i++) {
        var grade = parseInt(student.grades[i]);
        total += grade;
       }
       const avg = total / student.grades.length;
       const average = avg.toString();

      return(
      <div className="student" key={index}>
        <div className="image">
          <img src={student.pic} id="icon"></img>
        </div>

        <div className="text">
          <h3 id="name">{student.firstName} {student.lastName}</h3>
          <p id="detail"><strong>EMAIL:</strong> {student.email}</p>
          <p id="detail"><strong>COMPANY:</strong> {student.company}</p>
          <p id="detail"><strong>SKILL:</strong> {student.skill}</p>
          <p id="detail"><strong>AVERAGE:</strong>: {average}%</p>
        </div>
      </div>

      )}
      )}
    </div>
  );
}
</code>```

Body:
I am working on a project however i need to add an input where a user can filter the list of students
by their name (both first and last name), I have gotten the data from the api the issue is figuring out how to filter the data as I am fairly new to react. Some help would be appreciated. Below is what I have so far.

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import StudentData from './student_data/StudentData'
import './App.css';

function App() {
  const [students, setStudents] = useState(null);
  const studentdata = 'https://www.hatchways.io/api/assessment/students';

  function getStudents(){
    fetch(studentdata)
      .then(resp => resp.json())
      .then(data => {
        setStudents(data);
      })
  }

  return (

Students

        <button className="fetch-button" onClick={getStudents}>
          Get Students
        </button>

          <input type="text" ></input>

      {students && students.students.map((student, index) => {
       var total = 0;
       for(var i = 0; i < student.grades.length; i++) {
        var grade = parseInt(student.grades[i]);
        total += grade;
       }
       const avg = total / student.grades.length;
       const average = avg.toString();

      return(

{student.firstName} {student.lastName}

EMAIL: {student.email}

COMPANY: {student.company}

SKILL: {student.skill}

AVERAGE:: {average}%

      )}
      )}

  );
}

export default App;

Body:
Modified the code little bit and check this helps with the filter.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [students, setStudents] = useState(null);
  const [filterData, setFilterData ] = useState(null);

  const studentdata = 'https://www.hatchways.io/api/assessment/students';

  function getStudents(){
    fetch(studentdata)
      .then(resp => resp.json())
      .then(data => {
        setFilterData(data.students);
        setStudents(data.students);
      })
  }

  const searchByName = (event) => {
    event.persist();
    // Get the search term
    const searchItem = event.target.value.trim();
    // If search term is empty fill with full students data
    if(!searchItem.trim()) {
      setFilterData(students);
    }
    // Search the name and if it found retun the same array
    const serachIn = (firstName, lastName) => {
      if(firstName.indexOf(searchItem) !== -1 || lastName.indexOf(searchItem) !== -1) {
        return true;
      }
      let fullName = firstName+" "+lastName;
      if(fullName.indexOf(searchItem) !== -1) {
        return true;
      }
      return false;
    };
    // Filter the array
    const filteredData = students.filter((item) => {
      return serachIn(item.firstName, item.lastName);
    });
    // Set the state with filtered data
    setFilterData(filteredData);
  }

   return (
    <div className="App">
      <h1>Students</h1>

      <div>
        <button className="fetch-button" onClick={getStudents}>
          Get Students
        </button>
        <br />
      </div>

      <div className="search" id="search">
          <input type="text" name="serachByName" onChange={(e) => searchByName(e)} ></input>
      </div>

      {filterData && filterData.map((student, index) => {
       var total = 0;
       for(var i = 0; i < student.grades.length; i++) {
        var grade = parseInt(student.grades[i]);
        total += grade;
       }
       const avg = total / student.grades.length;
       const average = avg.toString();

      return(
      <div className="student" key={index}>
        <div className="image">
          <img src={student.pic} id="icon"></img>
        </div>

        <div className="text">
          <h3 id="name">{student.firstName} {student.lastName}</h3>
          <p id="detail"><strong>EMAIL:</strong> {student.email}</p>
          <p id="detail"><strong>COMPANY:</strong> {student.company}</p>
          <p id="detail"><strong>SKILL:</strong> {student.skill}</p>
          <p id="detail"><strong>AVERAGE:</strong>: {average}%</p>
        </div>
      </div>

      )}
      )}
    </div>
  );
}


问:
TcxShellListView - Sorting - C++ Builder 6
I am using a 'TcxShellListView'(ExpressEditorsLibrary 6.59) for displaying the files in a directory. I have the following question:

Is the sorting of TcxShellListView possible?  The only possibility I could find is to use the 'OnCompare' event. But, can someone give me an idea of how to implement the sorting functionality in this event?

I am using C++ Builder 6 in Windows 10.

Thank you in Advance.

答:
Found the solution to this problem from the following thread
Solution

Also, further explanation is provided by the Embarcadero support team in this link:
Explanation to the solution

The sample project given by the support team in the first link will help in implementing the sorting functionality in a TcxShellListView with the help of Jcl libraries.


问:
How i can use context in Singleton?
I need in my Singleton -> Context. I know that I can't passing argument in constructor, because object hasn't constructor.

Then I call it from my Application class.

Here is the code:

```<code>object Singleton {

    var userAgentInfo: String = UserAgentTools.buildUserAgent(context)

    fun initializeSdk() {
        AuthenticatorApiManager.initializeSdk(userAgentInfo)
    }
}
</code>```

答:
Make Application class and write below code.

```<code>companion object {
    private lateinit var sInstance: ApplicationClass
    fun getInstance(): ApplicationClass {
        return sInstance
    }
}
</code>```

Use in object like below.

```<code>ApplicationClass.getInstance()
</code>```

Title: How i can use context in Singleton?

Body:
I need in my Singleton -> Context. I know that I can't passing argument in constructor, because object hasn't constructor.

Then I call it from my Application class.

Here is the code:

object Singleton {

    var userAgentInfo: String = UserAgentTools.buildUserAgent(context)

    fun initializeSdk() {
        AuthenticatorApiManager.initializeSdk(userAgentInfo)
    }
}

Body:
Make Application class and write below code.

companion object {
    private lateinit var sInstance: ApplicationClass
    fun getInstance(): ApplicationClass {
        return sInstance
    }
}

Use in object like below.

ApplicationClass.getInstance()


问:
Safari Button has square corners if the text grows longer
The context is in a Mac's Safari.

I'm creating a HTML button that has dynamic content. It can be "OK" "Cancel" or "I will come back later" depending on the scenario. The max-width property is set to 100px so that it does not grow too long and mess-up the layout. Whenever the button text is longer, the button loses its rounded corners. I've also discovered that the button loses its default style if its style is overridden by CSS... I just the need the button to behave as it is and accommodate the text without losing the rounded corners. Can anyone help me?

thanks in advance!

Added Code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Button</title>
<style>
    button{max-width:150px;}
</style>
</head>
<body>
  <button id="test">Button has a long text to test its capacity</button>
</body>
</html>
</code>```

答:
Option 1:  Update your Safari.  I copy/pasted your exact code into a page and opened in Safari (just downloaded), and it has rounded corners.  I also tried increasing the max-width to 300px, and it still works just fine - rounded corners and all.

Option 2:  Create buttons with rounded corners using HTML/CSS.  THIS SITE is perfect for this - it lets you pick your options, then download the HTML/CSS for the exact button(s) you want - and it's free.  Of course you can then tweak the options yourself, or write it by hand, but - it's a good starting place if you've not made rounded buttons before.

ContentLicense: CC BY-SA 3.0

Body:
The context is in a Mac's Safari.

I'm creating a HTML button that has dynamic content. It can be "OK" "Cancel" or "I will come back later" depending on the scenario. The max-width property is set to 100px so that it does not grow too long and mess-up the layout. Whenever the button text is longer, the button loses its rounded corners. I've also discovered that the button loses its default style if its style is overridden by CSS... I just the need the button to behave as it is and accommodate the text without losing the rounded corners. Can anyone help me?

thanks in advance!

Added Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>Button</title>

  <button id="test">Button has a long text to test its capacity</button>


问:
WPF, Frequently Picture refresh without flicker
I am trying to create a "live-view" from my webcam with WPF, which only gives me JPG snapshots over HTTP.
Every time I update the image source, it flickers.
Anyone has an idea how to fix this?

XAML:

```<code>     <Grid>
        <Image Name="img"/>
    </Grid>
</code>```

C#:

```<code>public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000.0);
            timer.Tick += timer_Tick;
            timer.Start();

        }

        void timer_Tick(object sender, EventArgs e)
        {

            BitmapImage _image = new BitmapImage();
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.None;
            _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            _image.UriSource = new Uri(@"http://0.0.0.0/api/camera/snapshot?width=640&height=480", UriKind.RelativeOrAbsolute);
            _image.EndInit();
            img.Source = _image;
        }
    }
</code>```

答:
The flicker is because the BitmapImage is loaded asynchronously, i.e. after you have assigned it to the Image's Source property. The Image element first becomes empty, and will show an image only after downloading has finished.

In this case you may set the Source property in a DownloadCompleted event handler:

```<code>void timer_Tick(object sender, EventArgs e)
{
    var uri = "http://0.0.0.0/api/camera/snapshot?width=640&height=480";
    var image = new BitmapImage();
    image.BeginInit();
    image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
    image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
    image.UriSource = new Uri(uri);
    image.EndInit();

    if (image.IsDownloading)
    {
        image.DownloadCompleted += (s, ev) => img.Source = image;
    }
    else
    {
        img.Source = image;
    }
}
</code>```

Body:
I am trying to create a "live-view" from my webcam with WPF, which only gives me JPG snapshots over HTTP.
Every time I update the image source, it flickers.
Anyone has an idea how to fix this?

XAML:

     <Grid>
        <Image Name="img"/>
    </Grid>

C#:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000.0);
            timer.Tick += timer_Tick;
            timer.Start();

        }

        void timer_Tick(object sender, EventArgs e)
        {

            BitmapImage _image = new BitmapImage();
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.None;
            _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            _image.UriSource = new Uri(@"http://0.0.0.0/api/camera/snapshot?width=640&height=480", UriKind.RelativeOrAbsolute);
            _image.EndInit();
            img.Source = _image;
        }
    }

Body:
The flicker is because the BitmapImage is loaded asynchronously, i.e. after you have assigned it to the Image's Source property. The Image element first becomes empty, and will show an image only after downloading has finished.

In this case you may set the Source property in a DownloadCompleted event handler:

void timer_Tick(object sender, EventArgs e)
{
    var uri = "http://0.0.0.0/api/camera/snapshot?width=640&height=480";
    var image = new BitmapImage();
    image.BeginInit();
    image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
    image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
    image.UriSource = new Uri(uri);
    image.EndInit();

    if (image.IsDownloading)
    {
        image.DownloadCompleted += (s, ev) => img.Source = image;
    }
    else
    {
        img.Source = image;
    }
}


问:
Delete instance of class from DLL
I am asking for help in implementing the proper freeing of memory in the dll library.

The structure of my project looks like this:

Library.dll:

interface.h -> base class definition with pure virtual methods

implementation.h -> derived class inheriting from public base

implementation.cpp -> derived class methods definition

implementation.h contains also exported functions:

```<code>extern "C" __declspec(dllexport) Base* __stdcall Create()
{
    return new Derived;
}

extern "C" __declspec(dllexport) void __stdcall Delete(Base* B)
{
    delete B;
}
</code>```

Apllication.exe code looks like this:

```<code>#include "interface.h"
#include "windows.h"
#include <iostream>
#include <memory>

typedef Base* (*CREATE_BASE)();
std::unique_ptr<Base> SmartPointer;

int main()
{
    // Load the DLL
    HINSTANCE dll_handle = ::LoadLibrary(TEXT("Library.dll"));
    if (!dll_handle) {
        std::cout << "Unable to load DLL!\n";
        return 1;
    }

    // Get the function from the DLL
    CREATE_BASE Fn = (CREATE_BASE)GetProcAddress(dll_handle, "Create");
    if (!Fn) {
        std::cout << "Unable to load Create from DLL!\n";
        ::FreeLibrary(dll_handle);
        return 1;
    }

// i have possibility to use only C++11 so creation of unique_ptr looks like this:
SmartPointer = std::unique_ptr<Base>(Fn());

// ... do something like SmartPointer->Action();
::FreeLibrary(dll_handle);
return 0;
}
</code>```

The code above works and I can easily initialize the Base object and perform functions from the Derived class. Now i would like to use the exported "Delete" function as a custom pointer deleter now. So I prepared the definition of the type:

typedef void (*DELETE_BASE)(Base* B);

and I would like to use it more or less like this:

```<code>DELETE_BASE DeleteFn=(DELETE_BASE)GetProcAddress(dll_handle,"Delete");
SmartPointer = std::unique_ptr<Base>(Fn(),DeleteFn);
</code>```

However, I get a compiler error that this unique_ptr definition is incorrect. How to fix this?

My current solution is based on:

How to create a shared_ptr in dll and export it via a factory function?

答:
The type of the deleter function must be specified since you want to override the default deleter (refer to std::unique_ptr<>).

Where you have used:

```<code>std::unique_ptr<Base>
</code>```

you would instead want to use:

```<code>std::unique_ptr<Base, DELETE_BASE>
</code>```

Title: Delete instance of class from DLL

Body:
I am asking for help in implementing the proper freeing of memory in the dll library.

The structure of my project looks like this:

Library.dll:

interface.h -> base class definition with pure virtual methods

implementation.h -> derived class inheriting from public base

implementation.cpp -> derived class methods definition

implementation.h contains also exported functions:

extern "C" __declspec(dllexport) Base* __stdcall Create()
{
    return new Derived;
}

extern "C" __declspec(dllexport) void __stdcall Delete(Base* B)
{
    delete B;
}

Apllication.exe code looks like this:

#include "interface.h"
#include "windows.h"
#include <iostream>
#include <memory>

typedef Base* (*CREATE_BASE)();
std::unique_ptr<Base> SmartPointer;

int main()
{
    // Load the DLL
    HINSTANCE dll_handle = ::LoadLibrary(TEXT("Library.dll"));
    if (!dll_handle) {
        std::cout << "Unable to load DLL!\n";
        return 1;
    }

    // Get the function from the DLL
    CREATE_BASE Fn = (CREATE_BASE)GetProcAddress(dll_handle, "Create");
    if (!Fn) {
        std::cout << "Unable to load Create from DLL!\n";
        ::FreeLibrary(dll_handle);
        return 1;
    }

// i have possibility to use only C++11 so creation of unique_ptr looks like this:
SmartPointer = std::unique_ptr<Base>(Fn());

// ... do something like SmartPointer->Action();
::FreeLibrary(dll_handle);
return 0;
}

The code above works and I can easily initialize the Base object and perform functions from the Derived class. Now i would like to use the exported "Delete" function as a custom pointer deleter now. So I prepared the definition of the type:

typedef void (*DELETE_BASE)(Base* B);

and I would like to use it more or less like this:

DELETE_BASE DeleteFn=(DELETE_BASE)GetProcAddress(dll_handle,"Delete");
SmartPointer = std::unique_ptr<Base>(Fn(),DeleteFn);

However, I get a compiler error that this unique_ptr definition is incorrect. How to fix this?

My current solution is based on:

How to create a shared_ptr in dll and export it via a factory function?

Body:
The type of the deleter function must be specified since you want to override the default deleter (refer to std::unique_ptr<>).

Where you have used:

std::unique_ptr<Base>

you would instead want to use:

std::unique_ptr<Base, DELETE_BASE>


问:
Chart.js how to show cursor pointer for labels & legends in line chart
I have the following example of line chart using chart.js. I want to show:

Pointer cursor for legend & labels on hover

Show all the label data on line hover

 var line_chart = new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
            labels: ['May', 'June', 'July'],
            datasets: [{
                    data: [15, 25, 15],
                    label: "My Dataset1",
                    borderColor: "#00F",
                    fill: false
                }, {
                    data: [35, 15, 25],
                    label: "My Dataset2",
                    borderColor: "#F00",
                    fill: false
                }
            ]
        },
        options: {

            tooltips: {
                mode: 'label',
            },
            hover: {
                mode: 'label'
            },
        }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<div style='width:80%'>
<canvas id="line-chart" width="800" height="450"></canvas>
</div></code>```

答:
ChartJs 2 provides onHover and onLeave handlers. We can use them to change the cursor:

```<code>  legend: {
    display: true,
    onHover: function (e) {
      e.target.style.cursor = 'pointer'
    },
    onLeave: function (e) {
      e.target.style.cursor = 'default'
    }
  }
</code>```

Body:
I have the following example of line chart using chart.js. I want to show:

Pointer cursor for legend & labels on hover

Show all the label data on line hover

 var line_chart = new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
            labels: ['May', 'June', 'July'],
            datasets: [{
                    data: [15, 25, 15],
                    label: "My Dataset1",
                    borderColor: "#00F",
                    fill: false
                }, {
                    data: [35, 15, 25],
                    label: "My Dataset2",
                    borderColor: "#F00",
                    fill: false
                }
            ]
        },
        options: {

            tooltips: {
                mode: 'label',
            },
            hover: {
                mode: 'label'
            },
        }
    });

<canvas id="line-chart" width="800" height="450"></canvas>

Body:
ChartJs 2 provides onHover and onLeave handlers. We can use them to change the cursor:

  legend: {
    display: true,
    onHover: function (e) {
      e.target.style.cursor = 'pointer'
    },
    onLeave: function (e) {
      e.target.style.cursor = 'default'
    }
  }


问:
Create stored procedure to move data from stage_table to fact_table
Create stored procedure to move data from stage_table to fact_table. Scheme_name will be populated based on product_code and agency_code. Stage_table has to look up dim_table based on product_code and agency_code. when look up doesn't match, scheme_name to be written as N/A.

Query to be written in SQL Server. I tried writing the query below, but getting subquery returned more than 1 value error. Any help would be appreciated.

Stage_table

```<code>Policy holder.  Phone number
------------------------------
John.            456
Jack.            789
Jaxon.           101
Joshna.          121
Jenifer.         214
Joy.             453
Jordan.          343

Product_code.     Agency_code
-----------------------------
AAA.              PP
SSS.              SS11
SSS.              AA11
VVV.              AA11
VVV.              RR
QQQ.              QQ11
VVV.              VV11
</code>```

Dim_lookup

```<code>Product_code  Agency_code.  Scheme_name
---------------------------------------
AAA.           AA11.        A
QQQ.           QQ11.        Q
VVV.           VV11.        V
SSS.           SS11.        S
</code>```

---query for stage_table to lookup dim_lookup

```<code>UPDATE stage_table set stage_table.scheme_name = (
case
when stage_table.product_code = dim_lookup.product_code and stage_table.agency_code=dim_lookup.agency_code
then dim_lookup.scheme_name

Else 'NA'

END from dim_lookup)
</code>```

---query to create stored procedure to move data to fact_table

```<code>Create procedure Move_table
As
Begin
    Insert into fact_table
    Select*from stage_table
End

Exec Move_table
</code>```

答:
I think the issue is with the part where you assign the scheme.

Try doing an update with join instead:

```<code>UPDATE a
set a.scheme_name = case when a.product_code = b.product_code and b.agency_code=b.agency_code then b.scheme_name Else 'NA' end

from stage_table as a left join dim_lookup as b
on a.product_code = b.product_code and b.agency_code=b.agency_code
</code>```

Body:
Create stored procedure to move data from stage_table to fact_table. Scheme_name will be populated based on product_code and agency_code. Stage_table has to look up dim_table based on product_code and agency_code. when look up doesn't match, scheme_name to be written as N/A.

Query to be written in SQL Server. I tried writing the query below, but getting subquery returned more than 1 value error. Any help would be appreciated.

Stage_table

Policy holder.  Phone number
------------------------------
John.            456
Jack.            789
Jaxon.           101
Joshna.          121
Jenifer.         214
Joy.             453
Jordan.          343

Product_code.     Agency_code
-----------------------------
AAA.              PP
SSS.              SS11
SSS.              AA11
VVV.              AA11
VVV.              RR
QQQ.              QQ11
VVV.              VV11

Dim_lookup

Product_code  Agency_code.  Scheme_name
---------------------------------------
AAA.           AA11.        A
QQQ.           QQ11.        Q
VVV.           VV11.        V
SSS.           SS11.        S

---query for stage_table to lookup dim_lookup

UPDATE stage_table set stage_table.scheme_name = (
case
when stage_table.product_code = dim_lookup.product_code and stage_table.agency_code=dim_lookup.agency_code
then dim_lookup.scheme_name

Else 'NA'

END from dim_lookup)

---query to create stored procedure to move data to fact_table

Create procedure Move_table
As
Begin
    Insert into fact_table
    Select*from stage_table
End

Exec Move_table

Body:
I think the issue is with the part where you assign the scheme.

Try doing an update with join instead:

UPDATE a
set a.scheme_name = case when a.product_code = b.product_code and b.agency_code=b.agency_code then b.scheme_name Else 'NA' end

from stage_table as a left join dim_lookup as b
on a.product_code = b.product_code and b.agency_code=b.agency_code


问:
Namespace notation in CMakeLists.txt?
I've just cloned the libigl repo, and my goal would be to hack one of the examples.
I've starting by moving one of the tutorials in a different folder. However each CMakeLists.txt looks like the following:

```<code>get_filename_component(PROJECT_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
project(${PROJECT_NAME})

add_executable(${PROJECT_NAME}_bin main.cpp)
target_link_libraries(${PROJECT_NAME}_bin igl::core igl::opengl igl::opengl_glfw tutorials)
</code>```

I'm not an expert in CMake but I've never seen syntax like igl::core igl::opengl igl::opengl_glfw,

Can anyone tell me what that means? Is it like a namespace in C++? The toplevel CMake is a project named libigl so it must be related somehow.

答:
From the docs:

The use of double-colons is a common pattern used to namespace
  IMPORTED targets and ALIAS targets. When computing the link
  dependencies of a target, the name of each dependency could either be
  a target, or a file on disk. Previously, if a target was not found
  with a matching name, the name was considered to refer to a file on
  disk. This can lead to confusing error messages if there is a typo in
  what should be a target name.

Furthermore, from here:

A NAMESPACE with double-colons is specified when exporting the
  targets for installation. This convention of double-colons gives CMake
  a hint that the name is an IMPORTED target when it is used by
  downstreams with the target_link_libraries() command. This way, CMake
  can issue a diagnostic if the package providing it has not yet been
  found.

So the namespaces can be used as in the following CMake snippet:

```<code>export(EXPORT ClimbingStatsTargets
  FILE "${CMAKE_CURRENT_BINARY_DIR}/ClimbingStats/ClimbingStatsTargets.cmake"
  NAMESPACE Upstream::
)
</code>```

Title: Namespace notation in CMakeLists.txt?

Body:
I've just cloned the libigl repo, and my goal would be to hack one of the examples.
I've starting by moving one of the tutorials in a different folder. However each CMakeLists.txt looks like the following:

get_filename_component(PROJECT_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
project(${PROJECT_NAME})

add_executable(${PROJECT_NAME}_bin main.cpp)
target_link_libraries(${PROJECT_NAME}_bin igl::core igl::opengl igl::opengl_glfw tutorials)

I'm not an expert in CMake but I've never seen syntax like igl::core igl::opengl igl::opengl_glfw,

Can anyone tell me what that means? Is it like a namespace in C++? The toplevel CMake is a project named libigl so it must be related somehow.

Body:
From the docs:

The use of double-colons is a common pattern used to namespace
  IMPORTED targets and ALIAS targets. When computing the link
  dependencies of a target, the name of each dependency could either be
  a target, or a file on disk. Previously, if a target was not found
  with a matching name, the name was considered to refer to a file on
  disk. This can lead to confusing error messages if there is a typo in
  what should be a target name.

Furthermore, from here:

A NAMESPACE with double-colons is specified when exporting the
  targets for installation. This convention of double-colons gives CMake
  a hint that the name is an IMPORTED target when it is used by
  downstreams with the target_link_libraries() command. This way, CMake
  can issue a diagnostic if the package providing it has not yet been
  found.

So the namespaces can be used as in the following CMake snippet:

export(EXPORT ClimbingStatsTargets
  FILE "${CMAKE_CURRENT_BINARY_DIR}/ClimbingStats/ClimbingStatsTargets.cmake"
  NAMESPACE Upstream::
)


问:
Load two model's weights into one on Keras
What I'm trying to do is loading Keras layers' weights from model A and model B, both with same architecture, to model C. Let me explain:

I know that typical way of loading weights is:

```<code>modelC.load_weights('name.h5')
</code>```

But by doing this you can only load from one model and, as I've said before, I do not want to load all of it. Is there any way you can partially load these weights? If not, how could I solve this?

What I really want would be something like this:

```<code>modelC_weights = 0.2 * modelA_weights + 0.8 * modelB_weights
</code>```

答:
Something ugly but that shoud work:</p>

```<code>modelC.load_weights('name.h5')
weights1 = np.array(modelC.get_weights())

modelC.load_weights('name2.h5')
weights2 = np.array(modelC.get_weights())

modelC.set_weights(0.2 * weights1 + 0.8 * weights2)
</code>```

Body:
What I'm trying to do is loading Keras layers' weights from model A and model B, both with same architecture, to model C. Let me explain:

I know that typical way of loading weights is:

modelC.load_weights('name.h5')

But by doing this you can only load from one model and, as I've said before, I do not want to load all of it. Is there any way you can partially load these weights? If not, how could I solve this?

What I really want would be something like this:

modelC_weights = 0.2 * modelA_weights + 0.8 * modelB_weights

Body:
Something ugly but that shoud work:

modelC.load_weights('name.h5')
weights1 = np.array(modelC.get_weights())

modelC.load_weights('name2.h5')
weights2 = np.array(modelC.get_weights())

modelC.set_weights(0.2 * weights1 + 0.8 * weights2)


问:
Excel web services
Can excel web services be used to create pivot grids from asp.net or silverlight? And if so can i execute custom mdx in them?</p>

答:
This could help:

http://msdn.microsoft.com/en-us/library/ms496823.aspx

it looks like you can have pivot grids

ContentLicense: CC BY-SA 2.5

Title: Excel web services


问:
How to make the link inside Button change color on hover without hovering over link
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

```<code>btn:hover{
color: black;
}
</code>```

This does not work.

```<code>a:hover{
color:black
}
</code>```

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

答:
//Using plain JavaScript with out CSS</p>

<p>  </p>

<p>  </p>

```<code><head>

    <title>

        How to change the background color

        after clicking the button ?

    </title>

</head>

<body style = "text-align:center;">

    <h1 style = "color:green;" >

        GeeksForGeeks

    </h1>

    <p id = "GFG_UP" style =

        "font-size: 16px; font-weight: bold;">

    </p>

    <button onclick = "gfg_Run()">

        Click here

    </button>

    <p id = "GFG_DOWN" style =

        "color:green; font-size: 20px; font-weight: bold;">

    </p>

    <script>

        var el_up = document.getElementById("GFG_UP");

        var el_down = document.getElementById("GFG_DOWN");

        var str = "Click on button to change the background color";

        el_up.innerHTML = str;

        function changeColor(color) {

            document.body.style.background = color;

        }

        function gfg_Run() {

            changeColor('yellow');

            el_down.innerHTML = "Background Color changed";

        }

    </script>

</body>
</code>```

<p>                     </p>

Body:
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

btn:hover{
color: black;
}

This does not work.

a:hover{
color:black
}

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

Body:
//Using plain JavaScript with out CSS

<head>

    <title>

        How to change the background color

        after clicking the button ?

    </title>

</head>

<body style = "text-align:center;">

    <h1 style = "color:green;" >

        GeeksForGeeks

    </h1>

    <p id = "GFG_UP" style =

        "font-size: 16px; font-weight: bold;">

    </p>

    <button onclick = "gfg_Run()">

        Click here

    </button>

    <p id = "GFG_DOWN" style =

        "color:green; font-size: 20px; font-weight: bold;">

    </p>

    <script>

        var el_up = document.getElementById("GFG_UP");

        var el_down = document.getElementById("GFG_DOWN");

        var str = "Click on button to change the background color";

        el_up.innerHTML = str;

        function changeColor(color) {

            document.body.style.background = color;

        }

        function gfg_Run() {

            changeColor('yellow');

            el_down.innerHTML = "Background Color changed";

        }

    </script>

</body>


问:
How to set background of a JButton?
I am trying to set the color of a JButton with the properties in NetBeans with no success. When I select a color, only the border color change:

I have been reading about this and I think it is related to my Look and Feel. I created the project in Netbans as "Java Desktop Application", and I think I am using Nimbus:

```<code>public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            Entrenamiento dialog = new Entrenamiento(new javax.swing.JFrame(), true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);
        }
    });
}
</code>```

I tried to set the background of the JButton in this way:
UIManager.put("Button.background", Color.WHITE);

However it is not working. How can I achieve this? Thanks.

答:
Maybe this is a dumb question, but have you tried just setting the background color via code? Like this:</p>

```<code>yourButton.setOpaque(true);
yourButton.setBackground(Color.WHATEVER);
</code>```

Title: How to set background of a JButton?

Body:
I am trying to set the color of a JButton with the properties in NetBeans with no success. When I select a color, only the border color change:

I have been reading about this and I think it is related to my Look and Feel. I created the project in Netbans as "Java Desktop Application", and I think I am using Nimbus:

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Entrenamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            Entrenamiento dialog = new Entrenamiento(new javax.swing.JFrame(), true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);
        }
    });
}

I tried to set the background of the JButton in this way:
UIManager.put("Button.background", Color.WHITE);

However it is not working. How can I achieve this? Thanks.

Body:
Maybe this is a dumb question, but have you tried just setting the background color via code? Like this:

yourButton.setOpaque(true);
yourButton.setBackground(Color.WHATEVER);


问:
Does Microsoft Edge support composite keypath in indexeddb
Below is sample snippet which will throw Data Error in Edge (v42.17134.1.0) but works fine in Chrome,

```<code>var request = indexedDB.open('test123', 1);
request.onupgradeneeded = () => {
    var db = request.result;
    var store = db.createObjectStore('store',{keyPath: ['col1',
               'col2']});//composite keypath
};
request.onsuccess = (event) => {
    var db = event.target.result;
    var tx = db.transaction('store', 'readwrite');

    tx.objectStore('store').add({'col1': 1, 'col2':2});//Data Error
};
</code>```

There is no issue if the keypath is not composite. Does the Legacy Edge browser support composite keypath?

答:
I have tested it with MS Edge and able to produce the issue. It seems that the composite keypath not support the legacy version of Microsoft Edge or it is Edge default behavior. But it works well in the New Microsoft Edge and Microsoft Edge (chromium) version, because they are chromium based. I will try to submit the feedback regarding this issue. If I get any response, I will try to provide you in the future. Thanks for your understanding

As a workaround, if you want to use composite keypath, I suggest you could try to upgrade the Microsoft Edge and use the New Microsoft Edge or Microsoft Edge (chromium) version.

Body:
Below is sample snippet which will throw Data Error in Edge (v42.17134.1.0) but works fine in Chrome,

var request = indexedDB.open('test123', 1);
request.onupgradeneeded = () => {
    var db = request.result;
    var store = db.createObjectStore('store',{keyPath: ['col1',
               'col2']});//composite keypath
};
request.onsuccess = (event) => {
    var db = event.target.result;
    var tx = db.transaction('store', 'readwrite');

    tx.objectStore('store').add({'col1': 1, 'col2':2});//Data Error
};

There is no issue if the keypath is not composite. Does the Legacy Edge browser support composite keypath?


问:
Form an numpy array from indices and fill with zeroes
I have a nympy array a = np.array([483, 39, 18, 999, 20, 48]

I have an array of indices indices = np.array([2, 3])

I would like to have all the indices of the array and fill the rest of the indices with 0 so I get as a result :

np.array([0, 0, 18, 999, 0, 0])

Thank you for your answer.

答:
Create an all zeros array and copy the values at the desired indices:

import numpy as np

a = np.array([483, 39, 18, 999, 20, 48])
indices = np.array([2, 3])

b = np.zeros_like(a)
b[indices] = a[indices]

# a = b     # if needed

print(a)
print(indices)
print(b)
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>[483  39  18 999  20  48]
[2 3]
[  0   0  18 999   0   0]
</code>```

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
----------------------------------------
```

<hr>

<p><strong>EDIT:</strong> Even better, use <code>np.setdiff1d</code>:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np

a = np.array([483, 39, 18, 999, 20, 48])
indices = np.array([2, 3])

print(a)
print(indices)

a[np.setdiff1d(np.arange(a.shape[0]), indices, True)] = 0

print(a)
</code>```

Output:

[483  39  18 999  20  48]
[2 3]
[  0   0  18 999   0   0]
```

Body:
Create an all zeros array and copy the values at the desired indices:

import numpy as np

a = np.array([483, 39, 18, 999, 20, 48])
indices = np.array([2, 3])

b = np.zeros_like(a)
b[indices] = a[indices]

# a = b     # if needed

print(a)
print(indices)
print(b)

Output:

[483  39  18 999  20  48]
[2 3]
[  0   0  18 999   0   0]

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
----------------------------------------

EDIT: Even better, use np.setdiff1d:

import numpy as np

a = np.array([483, 39, 18, 999, 20, 48])
indices = np.array([2, 3])

print(a)
print(indices)

a[np.setdiff1d(np.arange(a.shape[0]), indices, True)] = 0

print(a)

Output:

[483  39  18 999  20  48]
[2 3]
[  0   0  18 999   0   0]


问:
Scala convert tuple of types to tuple of generic of types
Say I have type a defined as a tuple of types

type a = (Int, String, Int)
```

<p>and I define generic class <code>Foo</code> as</p>

<pre class="lang-scala prettyprint-override"><code>class Foo[A]{}
</code>```

is there any method is Scala (preferably native Scala) that can convert a to b, a tuple of generic of types?

type b = (Foo[Int], Foo[String], Foo[Int])
```

答:
Although this is not really possible with native scala without shapeless or macro on typelevel in scala 2.*, it is possible to create a function that maps the value of type a to value of type b. One thing you should do is to define typeclass trait LiftFoo[T]
which has a single method def lift[T](t: T)(implicit instance: LiftFoo[T]): Foo[T] and make implementations for all types you ever want.

Then you can map your tuple with the polyfunction:

object Bla{
  import shapeless.syntax.std.tuple._
  import shapeless.syntax._
  import shapeless.poly._
  case class Foo[T](t: T)
  trait LiftFoo[T] {
    def liftImpl(t: T): Foo[T]
  }
  object LiftFoo {
    def lift[T](t: T)(implicit instance: LiftFoo[T]): Foo[T] = instance.liftImpl(t)
  }
  implicit val liftInt: LiftFoo[Int] = {Foo(_)}
  implicit val liftString: LiftFoo[String] = {Foo(_)}
  implicit val liftDouble: LiftFoo[Double] = {Foo(_)}

  val a: (Int, Int, String, Double) = ???
  object LiftFooPoly extends Poly1 {
    implicit def onLiftable[T: LiftFoo] = at[T](LiftFoo.lift[T])
  }
  val b = a.map{LiftFooPoly}
}
```

<p>However, scala 3 (i.e. Dotty) will allow do this on type level with type lambdas and match types. Typelambda allows types of form <code>type LiftFoo[T] = [T] =>> Foo[T]</code>
and match types and tuples in scala 3 now ressemble HList and you could recursively traverse through its elements with match types:</p>

```  type TupleLiftFoo[Xs <: Tuple] <: Tuple = Xs match
    case Unit => Unit
    case x *: xs => LiftFoo[x] *: TupleLiftFoo[xs]

```

Body:
Say I have type a defined as a tuple of types

type a = (Int, String, Int)

and I define generic class Foo as

class Foo[A]{}

is there any method is Scala (preferably native Scala) that can convert a to b, a tuple of generic of types?

type b = (Foo[Int], Foo[String], Foo[Int])

Body:
Although this is not really possible with native scala without shapeless or macro on typelevel in scala 2.*, it is possible to create a function that maps the value of type a to value of type b. One thing you should do is to define typeclass trait LiftFoo[T]
which has a single method def lift[T](t: T)(implicit instance: LiftFoo[T]): Foo[T] and make implementations for all types you ever want.

Then you can map your tuple with the polyfunction:

object Bla{
  import shapeless.syntax.std.tuple._
  import shapeless.syntax._
  import shapeless.poly._
  case class Foo[T](t: T)
  trait LiftFoo[T] {
    def liftImpl(t: T): Foo[T]
  }
  object LiftFoo {
    def lift[T](t: T)(implicit instance: LiftFoo[T]): Foo[T] = instance.liftImpl(t)
  }
  implicit val liftInt: LiftFoo[Int] = {Foo(_)}
  implicit val liftString: LiftFoo[String] = {Foo(_)}
  implicit val liftDouble: LiftFoo[Double] = {Foo(_)}

  val a: (Int, Int, String, Double) = ???
  object LiftFooPoly extends Poly1 {
    implicit def onLiftable[T: LiftFoo] = at[T](LiftFoo.lift[T])
  }
  val b = a.map{LiftFooPoly}
}

However, scala 3 (i.e. Dotty) will allow do this on type level with type lambdas and match types. Typelambda allows types of form type LiftFoo[T] = [T] =>> Foo[T]
and match types and tuples in scala 3 now ressemble HList and you could recursively traverse through its elements with match types:

  type TupleLiftFoo[Xs <: Tuple] <: Tuple = Xs match
    case Unit => Unit
    case x *: xs => LiftFoo[x] *: TupleLiftFoo[xs]


问:
How can I add white space to the bottom of a page with JavaScript?
I know it's a really specific question, but I need to add 56px of white space to the bottom of a page using JavaScript - like the actual page is compressed so uses less screen space. Here are some images showing what I want to do (the white space is hard to see because it blends in with the background, but you can still see the actual website is smaller):

I've tried using JavaScript to add in CSS to the page - using some different pieces of code for footers, but whatever I do, either the bar covers some of the page rather than moving the rest up or it just stays at the bottom rather than sticking when the user scrolls. For example this code:

.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: white;
   text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui </p>

<div class="footer">
.
</div></code>```

gives a rough idea of what I want, but unfortunately the website content goes behind it - for example when scrolling the text goes behind it. It depends on the size of the page on your screen, but on my display when I stop the example text at "qui" (like I have done in the example) the bottom of the "q"s are cut off:

I'd also like scrollling content to stop at the top of the white space rather than the bottom of the page. Is this possible?

答:
If you want to add white spaces on the bottom of the page, I think the following would work:

```<code>.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: white;
   text-align: center;
    height: 56px;
}

body{
    margin-bottom : 56px;
}
</code>```

I tried it on w3schools tryit, and the following were the results

Before :

After :

Body:
I know it's a really specific question, but I need to add 56px of white space to the bottom of a page using JavaScript - like the actual page is compressed so uses less screen space. Here are some images showing what I want to do (the white space is hard to see because it blends in with the background, but you can still see the actual website is smaller):

I've tried using JavaScript to add in CSS to the page - using some different pieces of code for footers, but whatever I do, either the bar covers some of the page rather than moving the rest up or it just stays at the bottom rather than sticking when the user scrolls. For example this code:

.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: white;
   text-align: center;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui

.

gives a rough idea of what I want, but unfortunately the website content goes behind it - for example when scrolling the text goes behind it. It depends on the size of the page on your screen, but on my display when I stop the example text at "qui" (like I have done in the example) the bottom of the "q"s are cut off:

I'd also like scrollling content to stop at the top of the white space rather than the bottom of the page. Is this possible?

Body:
If you want to add white spaces on the bottom of the page, I think the following would work:

.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: white;
   text-align: center;
    height: 56px;
}

body{
    margin-bottom : 56px;
}

I tried it on w3schools tryit, and the following were the results

Before :

After :


问:
Nodejs - read line by line from file, perform async action for each line and resume
I'm trying to read a file line by line, perform some action that has a callback and when the function finishes to resume line reading. For example:

```<code>var fs = require('fs');
var readline = require('readline');
var stream = require('stream');
var instream = fs.createReadStream('./phrases.txt');
var outstream = new stream;
var rl = readline.createInterface(instream, outstream);
rl.on('line', function (line) {
  rl.pause();
  setTimeout(function () {
    console.log('resuming');
    rl.resume();
  }, 2000);
});
</code>```

I was under the impression the example above should basically read a line, wait for 2 seconds, console.log and then continue to the next line. What really happens is that it waits for the first 2 seconds and then spews out lots of console.log

答:
I suggest to use stdio for this kind of things, as input stream is paused and resumed automatically and you don't need to worry about your system resources. You'll be able to read really huge files with just a few MBs of memory:

This example prints a line every 2 seconds:

```<code>$ node myprogram.js < file.txt
</code>```

import { read } from 'stdio';

async function onLine (line) {
  console.log(line);
  await sleep(2000);
}

read(onLine)
  .then(() => console.log('finished'));
```

<p>Note I'm using an asynchronous <code>sleep</code> to represent any asynchronous task. It is not included in Node.js by default but it would be as follows:</p>

<pre class="lang-js prettyprint-override"><code>const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
</code>```

Body:
I'm trying to read a file line by line, perform some action that has a callback and when the function finishes to resume line reading. For example:

var fs = require('fs');
var readline = require('readline');
var stream = require('stream');
var instream = fs.createReadStream('./phrases.txt');
var outstream = new stream;
var rl = readline.createInterface(instream, outstream);
rl.on('line', function (line) {
  rl.pause();
  setTimeout(function () {
    console.log('resuming');
    rl.resume();
  }, 2000);
});

I was under the impression the example above should basically read a line, wait for 2 seconds, console.log and then continue to the next line. What really happens is that it waits for the first 2 seconds and then spews out lots of console.log

Body:
I suggest to use stdio for this kind of things, as input stream is paused and resumed automatically and you don't need to worry about your system resources. You'll be able to read really huge files with just a few MBs of memory:

This example prints a line every 2 seconds:

$ node myprogram.js < file.txt

import { read } from 'stdio';

async function onLine (line) {
  console.log(line);
  await sleep(2000);
}

read(onLine)
  .then(() => console.log('finished'));

Note I'm using an asynchronous sleep to represent any asynchronous task. It is not included in Node.js by default but it would be as follows:

const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));


问:
AirBnB React-dates not showing selected range
I'm trying to add AirBnB React-dates. All of functionality working except one thing (Not opening the month of already  selected dates).

When I'm assigning the start and end dates then it selects the range but not showing the selected month. It showing the current month instead.

For example: If I set start date = 2017-05-05 and end date =2017-05-09 then it shows the selection, but in next time calendar picker open it only shows current month, so I have to click the next month, next month to see the previous selected dates;

My code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';

import { DateRangePicker } from 'react-dates';

var SelectedStartDate = moment('2017-05-05');
var SelectedEndDate = moment('2017-05-09');

class HomePageDatePicker extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        focusedInput: null,
        startDate: SelectedStartDate,
        endDate:SelectedEndDate
    };
    this.onDatesChange = this.onDatesChange.bind(this);
    this.onFocusChange = this.onFocusChange.bind(this);
}

onDatesChange({ startDate, endDate }) {

    this.setState({ startDate, endDate });
}

onFocusChange(focusedInput) {
    this.setState({ focusedInput });
}

render() {
    const { focusedInput, startDate, endDate } = this.state;
    return (
        <div>
            <DateRangePicker
                {...this.props}
                onDatesChange={this.onDatesChange}
                onFocusChange={this.onFocusChange}
                focusedInput={focusedInput}
                startDate={startDate}
                endDate={endDate}
                startDateId="datepicker_start_home"
                endDateId="datepicker_end_home"
                startDatePlaceholderText="Check In"
                endDatePlaceholderText="Check Out"
            />
        </div>
    );
    }
}
</code>```

When I open the picker, it shows February instead of May.

答:
Try this prop of DateRangePicker</p>

```<code>initialVisibleMonth={() => startDate}
</code>```

Body:
I'm trying to add AirBnB React-dates. All of functionality working except one thing (Not opening the month of already  selected dates).

When I'm assigning the start and end dates then it selects the range but not showing the selected month. It showing the current month instead.

For example: If I set start date = 2017-05-05 and end date =2017-05-09 then it shows the selection, but in next time calendar picker open it only shows current month, so I have to click the next month, next month to see the previous selected dates;

My code:

import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';

import { DateRangePicker } from 'react-dates';

var SelectedStartDate = moment('2017-05-05');
var SelectedEndDate = moment('2017-05-09');

class HomePageDatePicker extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        focusedInput: null,
        startDate: SelectedStartDate,
        endDate:SelectedEndDate
    };
    this.onDatesChange = this.onDatesChange.bind(this);
    this.onFocusChange = this.onFocusChange.bind(this);
}

onDatesChange({ startDate, endDate }) {

    this.setState({ startDate, endDate });
}

onFocusChange(focusedInput) {
    this.setState({ focusedInput });
}

render() {
    const { focusedInput, startDate, endDate } = this.state;
    return (

            <DateRangePicker
                {...this.props}
                onDatesChange={this.onDatesChange}
                onFocusChange={this.onFocusChange}
                focusedInput={focusedInput}
                startDate={startDate}
                endDate={endDate}
                startDateId="datepicker_start_home"
                endDateId="datepicker_end_home"
                startDatePlaceholderText="Check In"
                endDatePlaceholderText="Check Out"
            />

    );
    }
}

When I open the picker, it shows February instead of May.

Body:
Try this prop of DateRangePicker

initialVisibleMonth={() => startDate}


问:
Value of CSS Property Selenium returning None for all images
I'm trying to scrape all of the images on this site. However, when I run my script and try to get the CSS attribute of 'background-image' to extract the url of each web element, the result is printing out "None". I have no idea why it would be returning None as I print out the web element and the attribute does exist. Any help would be greatly appreciated!</p>

```<code>import re
import selenium
import io
import pandas as pd
import urllib.request
import urllib.parse
import requests
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
import time
from _datetime import datetime
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def parse_style_attribute(style_string):
    if 'background-image' in style_string:
        style_string = style_string.split(' url("')[1].replace('");', '')
        return style_string
    return None

#setup opening url window of website to be scraped
options = webdriver.ChromeOptions()
options.headless=False
prefs = {"profile.default_content_setting_values.notifications" : 2}
options.add_experimental_option("prefs", prefs)
#driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3") #possible issue by not including the file extension
# driver.maximize_window()
# time.sleep(5)
# driver.get("""https://www.tripadvisor.com/""") #get the information from the page

driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3")
driver.maximize_window()

driver.get("https://www.tripadvisor.com/Hotel_Review-g28970-d84078-Reviews-Hyatt_Regency_Washington_on_Capitol_Hill-Washington_DC_District_of_Columbia.html#/media/84078/?albumid=101&type=2&category=101")

time.sleep(1)

#waits for that amount of time
driver.implicitly_wait(12)
#find the searchbar and then plug in the key
#driver.find_element_by_xpath('//*[@class="typeahead_input"]').send_keys("Washington D.C.", Keys.ENTER)
#wait
time.sleep(1)
#list all of the hotels in that page
images = driver.find_elements_by_xpath('//*[@class="media-viewer-tile-gallery-v2-TileGallery__entryInner--JaADY "]')

image_url = []

for i in range(len(images)):
    image_url.append(images[i].value_of_css_property("background-image"))

print("Total Number of images: ", len(images))
# print(images)

firstimage = images[0].get_attribute("innerHTML")
print(firstimage)

for i in range(len(image_url)):
    print(image_url[i])

</code>```

答:
try this. it works for me.</p>

```<code># attach your code as set browser option
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

driver.get(
    "https://www.tripadvisor.com/Hotel_Review-g28970-d84078-Reviews-Hyatt_Regency_Washington_on_Capitol_Hill-Washington_DC_District_of_Columbia.html#/media/84078/?albumid=101&type=2&category=101")

images = WebDriverWait(driver, 20).until(
    EC.presence_of_all_elements_located(
        (By.XPATH, '//*[@class="media-viewer-dt-root-GalleryImageWithOverlay__galleryImage--1Drp0"]')))

image_url = []

for index, image in enumerate(images):
    image_url.append(images[index].value_of_css_property("background-image"))

print(image_url)
</code>```

Body:
I'm trying to scrape all of the images on this site. However, when I run my script and try to get the CSS attribute of 'background-image' to extract the url of each web element, the result is printing out "None". I have no idea why it would be returning None as I print out the web element and the attribute does exist. Any help would be greatly appreciated!

import re
import selenium
import io
import pandas as pd
import urllib.request
import urllib.parse
import requests
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
import time
from _datetime import datetime
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def parse_style_attribute(style_string):
    if 'background-image' in style_string:
        style_string = style_string.split(' url("')[1].replace('");', '')
        return style_string
    return None

#setup opening url window of website to be scraped
options = webdriver.ChromeOptions()
options.headless=False
prefs = {"profile.default_content_setting_values.notifications" : 2}
options.add_experimental_option("prefs", prefs)
#driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3") #possible issue by not including the file extension
# driver.maximize_window()
# time.sleep(5)
# driver.get("""https://www.tripadvisor.com/""") #get the information from the page

driver = webdriver.Chrome("/Users/rishi/Downloads/chromedriver 3")
driver.maximize_window()

driver.get("https://www.tripadvisor.com/Hotel_Review-g28970-d84078-Reviews-Hyatt_Regency_Washington_on_Capitol_Hill-Washington_DC_District_of_Columbia.html#/media/84078/?albumid=101&type=2&category=101")

time.sleep(1)

#waits for that amount of time
driver.implicitly_wait(12)
#find the searchbar and then plug in the key
#driver.find_element_by_xpath('//*[@class="typeahead_input"]').send_keys("Washington D.C.", Keys.ENTER)
#wait
time.sleep(1)
#list all of the hotels in that page
images = driver.find_elements_by_xpath('//*[@class="media-viewer-tile-gallery-v2-TileGallery__entryInner--JaADY "]')

image_url = []

for i in range(len(images)):
    image_url.append(images[i].value_of_css_property("background-image"))

print("Total Number of images: ", len(images))
# print(images)

firstimage = images[0].get_attribute("innerHTML")
print(firstimage)

for i in range(len(image_url)):
    print(image_url[i])

Body:
try this. it works for me.

# attach your code as set browser option
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

driver.get(
    "https://www.tripadvisor.com/Hotel_Review-g28970-d84078-Reviews-Hyatt_Regency_Washington_on_Capitol_Hill-Washington_DC_District_of_Columbia.html#/media/84078/?albumid=101&type=2&category=101")

images = WebDriverWait(driver, 20).until(
    EC.presence_of_all_elements_located(
        (By.XPATH, '//*[@class="media-viewer-dt-root-GalleryImageWithOverlay__galleryImage--1Drp0"]')))

image_url = []

for index, image in enumerate(images):
    image_url.append(images[index].value_of_css_property("background-image"))

print(image_url)


问:
Display data from json file in angular
I Have the following Json file and i want to output data as categories(pizza, pasta) and then sub-categories(pizza margherita, pizza prosciutto) and same for pasta and for each to have choices, exactly as the structure in the file.

This is json file which i wanted to output it. I use ngfor to loop through the array but how to display from first option, both categories?

```<code>    [
    {
    "name" : "Pizza",
    "category": [
        {
            "name": "Pizza Marquerita",
            "choices": [
                {
                    "name": "Crust",
                    "addons" : [
                        {
                            "name": "Crispy"
                        },
                        {
                            "name": "Fluffy"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "Olives"
                        },
                        {
                            "name": "Mushrooms"
                        }
                    ]
                }
            ]
        },
        {
            "name": "Pizza Prosciutto",
            "choices": [
                {
                    "name": "Crust",
                    "addons" : [
                        {
                            "name": "Crispy"
                        },
                        {
                            "name": "Fluffy"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "Olives"
                        },
                        {
                            "name": "Mushrooms"
                        }
                    ]
                }
            ]
        }
    ],
    "choices": [
        {
            "name": "Crust",
            "addons" : [
                {
                    "name": "Crispy"
                },
                {
                    "name": "Fluffy"
                }
            ]
        },
        {
            "name": "Extra Toppings",
            "addons" : [
                {
                    "name": "Olives"
                },
                {
                    "name": "Mushrooms"
                }
            ]
        }
    ]},
    {
    "name" : "Pasta",
    "category": [
        {
            "name": "Spaghetti Bolognese",
            "choices": [
                {
                    "name": "Pasta Type",
                    "addons" : [
                        {
                            "name": "Spaghetti"
                        },
                        {
                            "name": "Tagliatelle"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "extra sea food"
                        },
                        {
                            "name": "truffle"
                        }
                    ]
                }
            ]
        },
        {
            "name": "Spaghetti Frutti di Mare",
            "choices": [
                {
                    "name": "Pasta Type",
                    "addons" : [
                        {
                            "name": "Spaghetti"
                        },
                        {
                            "name": "Tagliatelle"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "extra sea food"
                        },
                        {
                            "name": "truffle"
                        }
                    ]
                }
            ]
        }
    ],
    "choices": [
        {
            "name": "Pasta Type",
            "addons" : [
                {
                    "name": "Spaghetti"
                },
                {
                    "name": "Tagliatelle"
                }
            ]
        },
        {
            "name": "Extra Toppings",
            "addons" : [
                {
                    "name": "extra sea food"
                },
                {
                    "name": "truffle"
                }
            ]
        }
    ]}

]
</code>```

In .ts file i import the file
import data from '../../assets/data.json'; and then declare it as menus: any = data;

in html i want to output data as a card just something simple. If i use it like that. it displays pizza margherita and spaghetti bolognese under pizza

```<code>    <div class="card" style="width: 18rem;">
  <div class="card-body">
    <h5 class="card-title">Restaurant Name</h5>
  </div>
  <div class="card-header">Pizza</div>
  <ul class="list-group list-group-flush">
  <li class="list-group-item" *ngFor="let menu of menus">{{menu.category[0].name}}</li>
  </ul>
  <div class="card-header">Pasta</div>
  <ul class="list-group list-group-flush">
    <li class="list-group-item">test</li>
  </ul>
</div>
</code>```

答:
Just try this code:

```<code><div class="card" style="width: 18rem;">
  <div class="card-body">
    <h5 class="card-title">Restaurant Name</h5>
  </div>
  <div class="card-header">Pizza</div>
  <ul class="list-group list-group-flush">
  <li class="list-group-item" *ngFor="let menu of menus[0].category">{{menu.name}}</li>
  </ul>
  <div class="card-header">Pasta</div>
  <ul class="list-group list-group-flush">
    <li class="list-group-item" *ngFor="let menu1 of menus[1].category">{{menu1.name}}</li>
  </ul>
</div>
</code>```

You have to use correct ngfor elements.

{{menu.category[0].name}} will only give 1st category name of Pizza.

Title: Display data from json file in angular

Body:
I Have the following Json file and i want to output data as categories(pizza, pasta) and then sub-categories(pizza margherita, pizza prosciutto) and same for pasta and for each to have choices, exactly as the structure in the file.

This is json file which i wanted to output it. I use ngfor to loop through the array but how to display from first option, both categories?

    [
    {
    "name" : "Pizza",
    "category": [
        {
            "name": "Pizza Marquerita",
            "choices": [
                {
                    "name": "Crust",
                    "addons" : [
                        {
                            "name": "Crispy"
                        },
                        {
                            "name": "Fluffy"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "Olives"
                        },
                        {
                            "name": "Mushrooms"
                        }
                    ]
                }
            ]
        },
        {
            "name": "Pizza Prosciutto",
            "choices": [
                {
                    "name": "Crust",
                    "addons" : [
                        {
                            "name": "Crispy"
                        },
                        {
                            "name": "Fluffy"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "Olives"
                        },
                        {
                            "name": "Mushrooms"
                        }
                    ]
                }
            ]
        }
    ],
    "choices": [
        {
            "name": "Crust",
            "addons" : [
                {
                    "name": "Crispy"
                },
                {
                    "name": "Fluffy"
                }
            ]
        },
        {
            "name": "Extra Toppings",
            "addons" : [
                {
                    "name": "Olives"
                },
                {
                    "name": "Mushrooms"
                }
            ]
        }
    ]},
    {
    "name" : "Pasta",
    "category": [
        {
            "name": "Spaghetti Bolognese",
            "choices": [
                {
                    "name": "Pasta Type",
                    "addons" : [
                        {
                            "name": "Spaghetti"
                        },
                        {
                            "name": "Tagliatelle"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "extra sea food"
                        },
                        {
                            "name": "truffle"
                        }
                    ]
                }
            ]
        },
        {
            "name": "Spaghetti Frutti di Mare",
            "choices": [
                {
                    "name": "Pasta Type",
                    "addons" : [
                        {
                            "name": "Spaghetti"
                        },
                        {
                            "name": "Tagliatelle"
                        }
                    ]
                },
                {
                    "name": "Extra Toppings",
                    "addons" : [
                        {
                            "name": "extra sea food"
                        },
                        {
                            "name": "truffle"
                        }
                    ]
                }
            ]
        }
    ],
    "choices": [
        {
            "name": "Pasta Type",
            "addons" : [
                {
                    "name": "Spaghetti"
                },
                {
                    "name": "Tagliatelle"
                }
            ]
        },
        {
            "name": "Extra Toppings",
            "addons" : [
                {
                    "name": "extra sea food"
                },
                {
                    "name": "truffle"
                }
            ]
        }
    ]}

]

In .ts file i import the file
import data from '../../assets/data.json'; and then declare it as menus: any = data;

in html i want to output data as a card just something simple. If i use it like that. it displays pizza margherita and spaghetti bolognese under pizza

Restaurant Name

Pizza

{{menu.category[0].name}}

Pasta

test

Body:
Just try this code:

<div class="card" style="width: 18rem;">
  <div class="card-body">
    <h5 class="card-title">Restaurant Name</h5>
  </div>
  <div class="card-header">Pizza</div>
  <ul class="list-group list-group-flush">
  <li class="list-group-item" *ngFor="let menu of menus[0].category">{{menu.name}}</li>
  </ul>
  <div class="card-header">Pasta</div>
  <ul class="list-group list-group-flush">
    <li class="list-group-item" *ngFor="let menu1 of menus[1].category">{{menu1.name}}</li>
  </ul>
</div>

You have to use correct ngfor elements.

{{menu.category[0].name}} will only give 1st category name of Pizza.


问:
Google Cloud Functions Public URL
How to set public route to HTTP GCF?
So, currently the default path something like this.

https://us-central1-poised-breaker-162819.cloudfunctions.net/function-1

But I want to use it in this way

https://myfunction.com

or

https://myfunction.com/thisroute

So actually it is the question of namespacing or even proxying of the requests to appropriate function. How this can be achieved?

Update 1

It seems, like we can use an Endpoints service for that. But it still unclear would it work with GCF or not.

答:
Cloud Endpoints acts as an API gateway for cloud functions.

For Cloud function https://[CLOUD_FUNCTION_REGION].cloudfunctions.net/my-function,

Set project id in Cloud shell

```<code>gcloud config set project [PROJECT_ID]
</code>```

Deploy ESPv2 Beta to Cloud Run. Replace CLOUD_RUN_SERVICE_NAME with the name that you want to use for the service.

```<code>gcloud run deploy CLOUD_RUN_SERVICE_NAME \
   --image="gcr.io/endpoints-release/endpoints-runtime-serverless:2" \
   --allow-unauthenticated \
   --platform managed
</code>```

At the end of command execution, it will have similar details as below

Service [CLOUD_RUN_SERVICE_NAME] revision
  [CLOUD_RUN_SERVICE_NAME-00001-ces] has been deployed and is serving
  100 percent of traffic at
  https://CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app

Note host-name receive from the above command (CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app)

Create YAML file api.yaml with OpenAPI spec config:

  swagger: '2.0'
  info:
    title: Cloud Endpoints + GCF
    description: Sample API on Cloud Endpoints with a Google Cloud Functions backend
    version: 1.0.0
  host: CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app
  schemes:
    - https
  produces:
    - application/json
  paths:
    /thisroute:
      get:
        summary: Custom function route
        x-google-backend:
          address: https://[CLOUD_FUNCTION_REGION].cloudfunctions.net/my-function
        responses:
          '200':
            description: A successful response
            schema:
              type: string
```</li>
<li><p>Deploy Endpoint configuration:</p>

```gcloud endpoints services deploy api.yaml
```

Now, Cloud function request can route through endpoint https://CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app/thisroute.

Also to use custom domain name, need to verifying a domain name. For
that follow steps from here

Title: Google Cloud Functions Public URL

Body:
Cloud Endpoints acts as an API gateway for cloud functions.

For Cloud function https://[CLOUD_FUNCTION_REGION].cloudfunctions.net/my-function,

Set project id in Cloud shell

gcloud config set project [PROJECT_ID]

Deploy ESPv2 Beta to Cloud Run. Replace CLOUD_RUN_SERVICE_NAME with the name that you want to use for the service.

gcloud run deploy CLOUD_RUN_SERVICE_NAME \
   --image="gcr.io/endpoints-release/endpoints-runtime-serverless:2" \
   --allow-unauthenticated \
   --platform managed

At the end of command execution, it will have similar details as below

Service [CLOUD_RUN_SERVICE_NAME] revision
  [CLOUD_RUN_SERVICE_NAME-00001-ces] has been deployed and is serving
  100 percent of traffic at
  https://CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app

Note host-name receive from the above command (CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app)

Create YAML file api.yaml with OpenAPI spec config:

  swagger: '2.0'
  info:
    title: Cloud Endpoints + GCF
    description: Sample API on Cloud Endpoints with a Google Cloud Functions backend
    version: 1.0.0
  host: CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app
  schemes:
    - https
  produces:
    - application/json
  paths:
    /thisroute:
      get:
        summary: Custom function route
        x-google-backend:
          address: https://[CLOUD_FUNCTION_REGION].cloudfunctions.net/my-function
        responses:
          '200':
            description: A successful response
            schema:
              type: string

Deploy Endpoint configuration:

gcloud endpoints services deploy api.yaml

Now, Cloud function request can route through endpoint https://CLOUD_RUN_SERVICE_NAME-65zrpjcu3q-uk.a.run.app/thisroute.

Also to use custom domain name, need to verifying a domain name. For
that follow steps from here