问:
Continuous Integration and deployment of multiple projects in single git repository
I'm wondering if there is some good way to make CI/CD for single git repository that contains many projects. I often work with microservices, but I always preferred to have separate repo for each project and thanks to that I had separate pipelines for each repo. Now I'm in situation where all microservices are in single repo and I would like to know if there is some good way to make it work. The question is general because I don't have any CI tool right now, probably going to use Gitlab CI or Jenkins if I'm gonna need something more complex. </p>

答:
Yes it is possible, but you need to understand that your pipeline can be too big depending how many microservices you have in this repo

look here: https://docs.gitlab.com/ee/ci/yaml/#onlyexcept-basic

you are able to add a lot of only/except conditions to avoid or force some specific steps

example

build only if folder x is changed
test only if microservice x was built.... except if branch is example


来源: stackexchange

问:
How can I sort the letters of a word according to the order of occurrences compatible with Java 7?
I need to print all the letters that appear in the word, rearranged so that the letters that appear most frequently are found at the beginning.

The word can contain up to 100,000 characters.

If there are letters that appear the same number of times, the smallest ones will be displayed first after alphabetical sorting.

Some classes and operations are slow in Java. For this reason, it is recommended to use BufferedReader and BufferedWriter.

Concatenation using String is slow.

Input: instructions

Output : iinnssttcour

```<code>public class Main {
public static void main(String[] args) throws IOException {
 String line;
 BufferedReader reader = new BufferedReader(new
 InputStreamReader(System.in));
 line = reader.readLine();

     StringBuilder sb = new StringBuilder();
     Map<Character, Integer> charCountMap = new HashMap<>();

     int len = line.length();

      for(int i = 0; i < len; i++) {
           char ch = line.charAt(i);
           charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
      }

      charCountMap.entrySet().stream()
                  .sorted(Map.Entry.<Character,
     Integer>comparingByValue().reversed())
                 .forEach(record -> {
                    Character key = record.getKey();
                    int value = record.getValue();

                    for(int i = 0; i < value; i++) {
                          sb.append(key);
                     }
        });

        sb.toString();
        System.out.println(sb);
     }
  }
</code>```

My second solution is working too slow.

```<code>public class Main {
public static void main(String[] args) throws IOException {
String inputString;
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
inputString = reader.readLine();
if(reader != null)
 reader.close();
    int[] letterArray = new int[26];
    char[] letters = new char[26];
    for(int i=0;i<=25;i++)
        letters[i] = (char)(97+i);
    for(int i=0; i< inputString.length(); i++)
        letterArray[inputString.charAt(i) - 97] +=1 ;
    for(int i=0; i<=24;i++)
        for(int j=i+1;j<=25;j++){
            if(letterArray[i] <letterArray[j] || (letterArray[i] ==
               letterArray[j] && letters[i] > letters[j])){
                int temp = letterArray[i];
                letterArray[i] = letterArray[j];
                letterArray[j] = temp;
                char temp2;
                temp2 = letters[i];
                letters[i] = letters[j];
                letters[j] = temp2;}
        }
      String outputString = new String();
        for(int i=0;i<=25;i++){
            for(int j = 0; j<letterArray[i]; j++)
                outputString += letters[i];}
     System.out.println(outputString);}
     }
</code>```

答: You are almost there. Need to sort your Map by value reversed, then by key.</p>

ContentLicense: CC BY-SA 4.0

Body:
I need to print all the letters that appear in the word, rearranged so that the letters that appear most frequently are found at the beginning.

The word can contain up to 100,000 characters.

If there are letters that appear the same number of times, the smallest ones will be displayed first after alphabetical sorting.

Some classes and operations are slow in Java. For this reason, it is recommended to use BufferedReader and BufferedWriter.

Concatenation using String is slow.

Input: instructions

Output : iinnssttcour

public class Main {
public static void main(String[] args) throws IOException {
 String line;
 BufferedReader reader = new BufferedReader(new
 InputStreamReader(System.in));
 line = reader.readLine();

     StringBuilder sb = new StringBuilder();
     Map<Character, Integer> charCountMap = new HashMap<>();

     int len = line.length();

      for(int i = 0; i < len; i++) {
           char ch = line.charAt(i);
           charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
      }

      charCountMap.entrySet().stream()
                  .sorted(Map.Entry.<Character,
     Integer>comparingByValue().reversed())
                 .forEach(record -> {
                    Character key = record.getKey();
                    int value = record.getValue();

                    for(int i = 0; i < value; i++) {
                          sb.append(key);
                     }
        });

        sb.toString();
        System.out.println(sb);
     }
  }

My second solution is working too slow.

public class Main {
public static void main(String[] args) throws IOException {
String inputString;
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
inputString = reader.readLine();
if(reader != null)
 reader.close();
    int[] letterArray = new int[26];
    char[] letters = new char[26];
    for(int i=0;i<=25;i++)
        letters[i] = (char)(97+i);
    for(int i=0; i< inputString.length(); i++)
        letterArray[inputString.charAt(i) - 97] +=1 ;
    for(int i=0; i<=24;i++)
        for(int j=i+1;j<=25;j++){
            if(letterArray[i] <letterArray[j] || (letterArray[i] ==
               letterArray[j] && letters[i] > letters[j])){
                int temp = letterArray[i];
                letterArray[i] = letterArray[j];
                letterArray[j] = temp;
                char temp2;
                temp2 = letters[i];
                letters[i] = letters[j];
                letters[j] = temp2;}
        }
      String outputString = new String();
        for(int i=0;i<=25;i++){
            for(int j = 0; j<letterArray[i]; j++)
                outputString += letters[i];}
     System.out.println(outputString);}
     }


问:
convert Uint8Array into Uint16Array in NodeJs
I have an Uint8Array that i would like to convert into an Uint16Array so that each consecutive pair of element in the Uint8Array is converted in a Uint16 value. At the end, the uint16Array is thus half the size of the Uint8Array. I thus want to cast the whole array, not each values.

the only solution i found keeps the same lenght and change the underlying type of each element of the array. So it does not 'cast' the array but each element of the array, which is not what i want.

答: Your current solution should work fine. The "underlying type" of each element in a Uint8Array is number, just like in a Uint16Array. Therefore, casting the whole array should preserve the types of the values.


问:
Cannot find a version of 'com.google.code.findbugs:jsr305' that satisfies the version constraints
When generated signed APK for realse i get this error message:

```<code>Cannot find a version of 'com.google.code.findbugs:jsr305' that satisfies the version constraints:
   Dependency path 'XX:app:unspecified' --> 'androidx.test.espresso:espresso-core:3.1.2-alpha01' --> 'com.google.code.findbugs:jsr305:2.0.1'
   Constraint path 'XX:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
</code>```

This is my app:gradle

```<code>android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.XX.XX"
    minSdkVersion 25
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

 }

 dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.guava:guava:22.0-android'

testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.2-alpha01'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.2-alpha01'
}
</code>```

However if i build for debug it works fine, but when i generate signed release I get this message, ive tried to google but didnt seem to find the right answer.

答:
This is working for me thanks to StackOverflow

past inside app.gradle file

```<code> android
 {
    configurations.all
    {
      resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
 }
</code>```

Body:
When generated signed APK for realse i get this error message:

Cannot find a version of 'com.google.code.findbugs:jsr305' that satisfies the version constraints:
   Dependency path 'XX:app:unspecified' --> 'androidx.test.espresso:espresso-core:3.1.2-alpha01' --> 'com.google.code.findbugs:jsr305:2.0.1'
   Constraint path 'XX:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9

This is my app:gradle

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.XX.XX"
    minSdkVersion 25
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

 }

 dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.guava:guava:22.0-android'

testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.2-alpha01'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.2-alpha01'
}

However if i build for debug it works fine, but when i generate signed release I get this message, ive tried to google but didnt seem to find the right answer.

Body:
This is working for me thanks to StackOverflow

past inside app.gradle file

 android
 {
    configurations.all
    {
      resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
 }


问:
Material-ui's Switch component onChange handler is not firing
I've put some Switches in an app and they work fine. Then I put the Switches in another app, but they don't work when clicked.

Both apps are using the same component. Here it is working in one app:

And here's the other app, not working:

In the second app, the onChange handler doesn't seem to ever fire.

The code in both apps looks like the following:

```<code><Switch
  checked={(console.log('checked:', status === 'visible'), status === 'visible')}
  onChange={(e, c) => console.log('event:', e, c)}
/>
</code>```

In the first app I see the output of those console.logs, while in the second app I only see the initial console.log of the checked prop, but I never see any of the onChange prop.

I checked if any ancestor elements have click handlers, and I didn't find any that are returning false, calling stopPropagation, or calling preventDefault.

Notice in the gif that when I click, the ripple effect still works, so click handling is obviously still working.

Any ideas why onChange may not be firing?

UPDATE! I replaced the switches with regular <input type="checkbox"> elements, and it works great! See:

Looks to me like something is wrong with material-ui's <Switch> component. I have a hunch that I will investigate when I get a chance: there might be more than one React singleton in the application. I'll be back to post an update.

答:
in Switch component, changing onChange to onClick worked for me:</p>

```<code><Switch
    checked={this.state.active}
    onClick={() => this.handleToggle('active')}
    value="active"
    inputProps={{ 'aria-label': 'secondary checkbox' }}
/>
</code>```

Body:
I've put some Switches in an app and they work fine. Then I put the Switches in another app, but they don't work when clicked.

Both apps are using the same component. Here it is working in one app:

And here's the other app, not working:

In the second app, the onChange handler doesn't seem to ever fire.

The code in both apps looks like the following:

<Switch
  checked={(console.log('checked:', status === 'visible'), status === 'visible')}
  onChange={(e, c) => console.log('event:', e, c)}
/>

In the first app I see the output of those console.logs, while in the second app I only see the initial console.log of the checked prop, but I never see any of the onChange prop.

I checked if any ancestor elements have click handlers, and I didn't find any that are returning false, calling stopPropagation, or calling preventDefault.

Notice in the gif that when I click, the ripple effect still works, so click handling is obviously still working.

Any ideas why onChange may not be firing?

UPDATE! I replaced the switches with regular <input type="checkbox"> elements, and it works great! See:

Looks to me like something is wrong with material-ui's <Switch> component. I have a hunch that I will investigate when I get a chance: there might be more than one React singleton in the application. I'll be back to post an update.

Body:
in Switch component, changing onChange to onClick worked for me:

<Switch
    checked={this.state.active}
    onClick={() => this.handleToggle('active')}
    value="active"
    inputProps={{ 'aria-label': 'secondary checkbox' }}
/>


问:
Decentralized API calls using multiple Chainlink oracles in solidity
I am using Chainlink nodes to get data in my smart contract. I’ve read I can choose as many nodes as I’d like to get trustless data into my contract, but a the moment it seems to be a manual process for me to make API calls to each node, and my contract is huge, with a massive list of addresses and jobIDs.

```<code>solidity
address[] public oracles;
address[] public jobs;
function loop_through() public {
// does a for loop through each oracle and jobID and calls the get_weather_today function with each.
}
function get_weather_today(address _address, bytes32 _jobID)
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(_jobID, address(this), this.fulfill.selector);
    req.add("get", "weather_URL");
    req.add("path", "today");
    sendChainlinkRequestTo(_address, req, ORACLE_PAYMENT);
  }
</code>```

Is there a better way?

答:
You can use a precoordinator to launch a network of nodes proxy, that you can pretend is a single oracle itself.

The precoordinator allows you to choose whichever nodes you want to get your API calls, and fans the call our to each node. This way you can make a single chainlink request to multiple nodes with one request.

You can deploy a precoordinator by running this code:

```<code>pragma solidity ^0.5.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.5/PreCoordinator.sol";
</code>```

Or you can use another precoordinator. Once you have a precoordinator contract address, you can combine oracles and jobs to make a service agreement, which is basically the node networks.

```<code>                                    ____ Request sent to node
                                   /
Precoordinator -> Service Agreement
                                   \___ Request sent to node
</code>```

You can create the service agreement by interacting with the contract. Or interacting with it directly in remix or some other IDE.

Body:
I am using Chainlink nodes to get data in my smart contract. I’ve read I can choose as many nodes as I’d like to get trustless data into my contract, but a the moment it seems to be a manual process for me to make API calls to each node, and my contract is huge, with a massive list of addresses and jobIDs.

solidity
address[] public oracles;
address[] public jobs;
function loop_through() public {
// does a for loop through each oracle and jobID and calls the get_weather_today function with each.
}
function get_weather_today(address _address, bytes32 _jobID)
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(_jobID, address(this), this.fulfill.selector);
    req.add("get", "weather_URL");
    req.add("path", "today");
    sendChainlinkRequestTo(_address, req, ORACLE_PAYMENT);
  }

Is there a better way?

Body:
You can use a precoordinator to launch a network of nodes proxy, that you can pretend is a single oracle itself.

The precoordinator allows you to choose whichever nodes you want to get your API calls, and fans the call our to each node. This way you can make a single chainlink request to multiple nodes with one request.

You can deploy a precoordinator by running this code:

pragma solidity ^0.5.0;
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.5/PreCoordinator.sol";

Or you can use another precoordinator. Once you have a precoordinator contract address, you can combine oracles and jobs to make a service agreement, which is basically the node networks.

                                    ____ Request sent to node
                                   /
Precoordinator -> Service Agreement
                                   \___ Request sent to node

You can create the service agreement by interacting with the contract. Or interacting with it directly in remix or some other IDE.


问:
ng command not found everytime i logged to GCP Cloud Shell
I noticed everytime i login Google Cloud Shell, my 'ng' command is not recognized

```<code>weilies@cloudshell:~/dev (cloud-xp)$ cd sunny-app/
weilies@cloudshell:~/dev/sunny-app (cloud-xp)$ ng serve -disable-host-check
-bash: ng: command not found
</code>```

I have to reinstall them with command then i got back my ng command.
weilies@cloudshell:~ (cloud-xp)$ ng --version

```<code>     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 9.1.7
Node: 10.14.2
OS: linux x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.7
@angular-devkit/core         9.1.7
@angular-devkit/schematics   9.1.7
@schematics/angular          9.1.7
@schematics/update           0.901.7
rxjs                         6.5.4
</code>```

But one thing i noticed, the installation return with error (but it doesn't stop me running my angular app, so i simply ignored)

```<code>weilies@cloudshell:~ (cloud-xp)$ npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/usr/local/nvm/versions/node/v10.14.2/bin/ng -> /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.1.7 postinstall /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.1.7
added 271 packages from 206 contributors in 15.296s
</code>```

It is just annoying i need to install angular/cli everytime i login GCP Clould shell. Isn't ng installed globally with a -g flag?

答: Cloud Shell VMs are ephemeral and are discarded at the end of each session (your Cloud Shell home directory, however, is persistent).  However, it is possible to add a script to customize the Cloud Shell environment on startup.  Please follow the directions in Cloud Shell documentation.</p>

Body:
I noticed everytime i login Google Cloud Shell, my 'ng' command is not recognized

weilies@cloudshell:~/dev (cloud-xp)$ cd sunny-app/
weilies@cloudshell:~/dev/sunny-app (cloud-xp)$ ng serve -disable-host-check
-bash: ng: command not found

I have to reinstall them with command then i got back my ng command.
weilies@cloudshell:~ (cloud-xp)$ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 9.1.7
Node: 10.14.2
OS: linux x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.901.7
@angular-devkit/core         9.1.7
@angular-devkit/schematics   9.1.7
@schematics/angular          9.1.7
@schematics/update           0.901.7
rxjs                         6.5.4

But one thing i noticed, the installation return with error (but it doesn't stop me running my angular app, so i simply ignored)

weilies@cloudshell:~ (cloud-xp)$ npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/usr/local/nvm/versions/node/v10.14.2/bin/ng -> /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.1.7 postinstall /usr/local/nvm/versions/node/v10.14.2/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.1.7
added 271 packages from 206 contributors in 15.296s

It is just annoying i need to install angular/cli everytime i login GCP Clould shell. Isn't ng installed globally with a -g flag?


问:
div with innerhtml and variable
I need to put a link inside a div or  together with a variable value coming from a function in javascript.

function getRadios(){
      var radios = $("input[name='radio']:checked").val()
      return radios;
  }
var resultado = getRadios();
var jogar = document.getElementsById('jogar');

jogar.innerHTML = 'click';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar"></div></code>```

I need the radio value to be inserted in the url I'm using ajax.

答:
You can do this pretty easily without jQuery. Just write a function that will get run each time the input is clicked.

const jogar = document.getElementById('jogar');

const radios = document.querySelectorAll('input[name="radio"]');

const setLink = function(val) {
  let link = "somepage.htm?varName=" + val;
  jogar.querySelector('a').setAttribute('href', link);
};

radios.forEach( r => r.addEventListener('change', e => {
  const resultado = e.target.value;
  setLink( resultado );
}));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar">
  click
</div></code>```

And here the same thing, but a more compact way to do it:

const jogar = document.getElementById('jogar');
const radios = document.querySelectorAll('input[name="radio"]');
radios.forEach( r => r.addEventListener('change', e => {
  let link = "somepage.htm?varName=" + e.target.value;
  jogar.querySelector('a').setAttribute('href', link);
}));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar">
  click
</div></code>```

Title: div with innerhtml and variable

Body:
I need to put a link inside a div or  together with a variable value coming from a function in javascript.

function getRadios(){
      var radios = $("input[name='radio']:checked").val()
      return radios;
  }
var resultado = getRadios();
var jogar = document.getElementsById('jogar');

jogar.innerHTML = 'click';

<input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>

I need the radio value to be inserted in the url I'm using ajax.

Body:
You can do this pretty easily without jQuery. Just write a function that will get run each time the input is clicked.

const jogar = document.getElementById('jogar');

const radios = document.querySelectorAll('input[name="radio"]');

const setLink = function(val) {
  let link = "somepage.htm?varName=" + val;
  jogar.querySelector('a').setAttribute('href', link);
};

radios.forEach( r => r.addEventListener('change', e => {
  const resultado = e.target.value;
  setLink( resultado );
}));

<input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar">
  <a href="#">click</a>
</div>

And here the same thing, but a more compact way to do it:

const jogar = document.getElementById('jogar');
const radios = document.querySelectorAll('input[name="radio"]');
radios.forEach( r => r.addEventListener('change', e => {
  let link = "somepage.htm?varName=" + e.target.value;
  jogar.querySelector('a').setAttribute('href', link);
}));

<input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar">
  <a href="#">click</a>
</div>


问:
Hiding DefaultProperty
Is there any way to hide DefaultProperty?

Let's say I have such class:

```<code>public class CustomNode extends HBox {

    //Things

}
</code>```

As we know, default property for HBox is children, so default property for my CustomNode is also children.

Is there any way to hide/remove the default property without creating a new one? (I'd like to extend, so other ways are not okay for me)

I want to do this, because I don't want to have chance to make a mistake in FXML coding.

答:
No. You cannot do that with inheritance. When you extends the HBox class (or any class) you really say that your CustomNode is-a HBox, that is the relationship.

Maybe you can introduce you own interface is that makes more sense to you.

Title: Hiding DefaultProperty

Body:
Is there any way to hide DefaultProperty?

Let's say I have such class:

public class CustomNode extends HBox {

    //Things

}

As we know, default property for HBox is children, so default property for my CustomNode is also children.

Is there any way to hide/remove the default property without creating a new one? (I'd like to extend, so other ways are not okay for me)

I want to do this, because I don't want to have chance to make a mistake in FXML coding.


问:
c++ how to correctly implement parallel ifstream reading
First of, what I am trying to do. I have a class that can deal with a particular type of large files on storage. By dealing with it, I mean basically the following:

```<code>class Large {
  std::ifstream file;
  Large(const char* fname) : file(fname) {
    // read file header, create an index of stuff that's inside, that sort of stuff
    ...
  }

  void read_a_part(int which_part) const {
    // read from ifstream, which unfortunately modifies its state
    fstream.read(...)
  }

  ...
}
</code>```

Now, this is all pseudo code, since I am interested in best practice and not a single particular solution. Function read_a_state will not compile, since it modifies the object state but is declared const.

In what I am trying to achieve, I am not modifying my File (I only read from it), nor am I modifying the instance of Large. Therefore all functions should be declared const and should also be reentrant for parallel work. It seems this cannot be done with a single ifstream as a member of Large. The solutions of not marking the file accessing member functions of Large as const or making the member file mutable are no good. Such solutions are not reentrant. Since ifstream also cannot be copied, it seems it has to be created anew for each call to read_a_part. Therefore, the only working solution that I see is moving file from being a member to being an internal variable of read_a_part (and most other member functions of this class). But is this a good solution performance-wise? Will thousands of calls to ifstream ctor not cause problem with the operating system? Is there not a better way?

答:
Disks perform best on sequential access (even SSDs). Parallelizing disk I/O therefore will most likely lead to a reduction of overall throughput.

Having said that, two possible solutions:

Read the file sequentially then hand off the parts to a thread pool for further processing.

Serialize file access using a mutex:

```<code>class Large {
  std::ifstream file;
  mutable std::mutex mtx;
public:
  Large(const char* fname) : file(fname) {
    // read file header, create an index of stuff that's inside, that sort of stuff
    ...
  }

  Part read_a_part(int which_part) const {
    Part part;
    std::lock_guard<std::mutex> lock(mtx);
    file.seekg(which_part * part_size);
    file.read(...&part...);
    return part;
  }

}
</code>```

Not sure if/why your read_a_part() must be const. If not, then you can just remove const and remove mutable from the mutex.

Body:
First of, what I am trying to do. I have a class that can deal with a particular type of large files on storage. By dealing with it, I mean basically the following:

class Large {
  std::ifstream file;
  Large(const char* fname) : file(fname) {
    // read file header, create an index of stuff that's inside, that sort of stuff
    ...
  }

  void read_a_part(int which_part) const {
    // read from ifstream, which unfortunately modifies its state
    fstream.read(...)
  }

  ...
}

Now, this is all pseudo code, since I am interested in best practice and not a single particular solution. Function read_a_state will not compile, since it modifies the object state but is declared const.

In what I am trying to achieve, I am not modifying my File (I only read from it), nor am I modifying the instance of Large. Therefore all functions should be declared const and should also be reentrant for parallel work. It seems this cannot be done with a single ifstream as a member of Large. The solutions of not marking the file accessing member functions of Large as const or making the member file mutable are no good. Such solutions are not reentrant. Since ifstream also cannot be copied, it seems it has to be created anew for each call to read_a_part. Therefore, the only working solution that I see is moving file from being a member to being an internal variable of read_a_part (and most other member functions of this class). But is this a good solution performance-wise? Will thousands of calls to ifstream ctor not cause problem with the operating system? Is there not a better way?

Body:
Disks perform best on sequential access (even SSDs). Parallelizing disk I/O therefore will most likely lead to a reduction of overall throughput.

Having said that, two possible solutions:

Read the file sequentially then hand off the parts to a thread pool for further processing.

Serialize file access using a mutex:

class Large {
  std::ifstream file;
  mutable std::mutex mtx;
public:
  Large(const char* fname) : file(fname) {
    // read file header, create an index of stuff that's inside, that sort of stuff
    ...
  }

  Part read_a_part(int which_part) const {
    Part part;
    std::lock_guard<std::mutex> lock(mtx);
    file.seekg(which_part * part_size);
    file.read(...&part...);
    return part;
  }

}

Not sure if/why your read_a_part() must be const. If not, then you can just remove const and remove mutable from the mutex.


问:
C++: initialize vs assignment?
I'm reading Stroustrups C++ 4th Ed. Page 153 and have questions about initialization vs assignment.  It's my understanding that initialization is occurs in the constructor and assignment in operator= overloaded function.  Is this correct?

Also, I don't recall seeing the brackets i.e. int count {1} in his 1998 3rd Ed. book.  Should I be defining variables like counters using int count {1} or int count = 1?  Seems like an awkward difference from C if using the brackets.

Thanks for your guidance

```<code>void f() {
   int count {1}; // initialize count to 1
   const char∗ name {"Bjarne"}; // name is a    variable that points to a constant (§7.5)
   count = 2; // assign 2 to count
   name = "Marian";
}
</code>```

答:
initialize means you write the variable for the first time and give it an initial value like int x=5;
but assignment means that you already had a variable and you change its value like when you come later and
set x=10;
now you assignment  number 10 at variable x </p>

Title: C++: initialize vs assignment?

Body:
I'm reading Stroustrups C++ 4th Ed. Page 153 and have questions about initialization vs assignment.  It's my understanding that initialization is occurs in the constructor and assignment in operator= overloaded function.  Is this correct?

Also, I don't recall seeing the brackets i.e. int count {1} in his 1998 3rd Ed. book.  Should I be defining variables like counters using int count {1} or int count = 1?  Seems like an awkward difference from C if using the brackets.

Thanks for your guidance

void f() {
   int count {1}; // initialize count to 1
   const char∗ name {"Bjarne"}; // name is a    variable that points to a constant (§7.5)
   count = 2; // assign 2 to count
   name = "Marian";
}


问:
how to count the frequency of letters in text excluding whitespace and numbers?
Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}</p>

```<code>def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
</code>```

答:
```<code>def count_letters(text):
  result = {}
  for letter in text:
    #check if it alphabet or something else
    # Check if the letter needs to be counted or not
    if letter.isalpha():
      result[letter.lower()]=result.get(letter.lower(),0)+1
    # Add or increment the value in the dictionary
  return result
</code>```
```<code>print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}
</code>```
```<code>print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
</code>```
```<code>print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
</code>```

Body:
Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

Body:
def count_letters(text):
  result = {}
  for letter in text:
    #check if it alphabet or something else
    # Check if the letter needs to be counted or not
    if letter.isalpha():
      result[letter.lower()]=result.get(letter.lower(),0)+1
    # Add or increment the value in the dictionary
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}


问:
MaxDB - User does not access tables
I have created a new user in a MaxDb database. I assign a role that has access to all the tables in roleprivileges but the user can not see these tables.

The user can access the tables if I assign permissions directly to the tables in tableprivileges.

The role has access, other users have this role assigned and they see all the tables.

What can be failing?

答:
Assuming this deals indeed with MaxDB, and not with Oracle:
In contrast to privileges, roles need to be activated for a user session. Assigning is not enough. It is done by command SET ROLE <role>.
A role may also be activated as default for every new session, with command:
ALTER USER <user> DEFAULT ROLE <role>.
You can also activate all roles assigned to the user, like this:
 ALTER USER <user> DEFAULT ROLE ALL.

ContentLicense: CC BY-SA 3.0

Title: MaxDB - User does not access tables


问:
How can I be sure if nobody changed master branch while I'm working on other branch? (Git)
guys!

I made a new branch and worked in there for a while. That time my coworker changed some code in the master BUT the problem is a lot of code was changed and now we can't merge all these stuff into the master cause my code doesn't fit the new changes in master.

How should we deal with these kind of situations? Should we better discuss our zones of responsibilities and design out interfaces more independently?

Cause sometimes I rely on a code base in a master branch but also sometimes classes of functions change there, so code I write doesn't work anymore (for example, some method in a master code was removed but I used it into my branch).

Don't let my head explode, give me your feedback please!

答:
The perpetual race condition, and rebase

It's not a "situation". Having the main branch change while you are working on a side branch is normal.

To put it another way: you are always in a race condition with the usage of the main branch. That is part of life. It's normal. Do not try to avoid it.

You can lessen the apparent impact of this constant race condition by rebasing your branch onto the main branch just before merging or pull request or whatever you are doing. But note this largely just moves the impact to a different location; it makes for a nicer tree and a better chance of no conflict during the merge itself.

Merge conflicts

and now we can't merge all these stuff into the master cause my code doesn't fit the new changes in master

Okay, that part is just wrong. Of course you can merge into master. You just can't merge into master automatically. There are conflicts and you have to resolve them. Okay, resolve them! It's not rocket science.

Again: merge conflicts are normal. You need to accept them and learn to deal with them.

The real issue here is the name. A merge is the creation of a commit. What you are doing is asking git to create the commit automatically because you are too lazy or too human / fallible to do it yourself. Git will do so, but sometimes it will say, "I can't do this part automatically, you'll have to help me by doing it manually." So you do, and there's the commit, all done. If we called this something like "automatic / manual commit creation" instead using words like merge and conflict, we wouldn't get so tied up in knots about it.

And this relates to what I said in part one of my answer. If there are conflicts, they will emerge during the rebase just as surely as they would have emerged during the merge later. And you will resolve them. It's not a big deal, and it's good because you've moved the onus of dealing with the conflicts onto your own machine, so that the conflict won't occur (or probably won't) at merge time.

Rebase early and often

Cause sometimes I rely on a code base in a master branch but also sometimes classes of functions change there, so code I write doesn't work anymore (for example, some method in a master code was removed but I used it into my branch).

The way to deal with that is to do what I said in the first part, often. Every hour or two, commit what you're doing on the branch, switch to the main branch, and pull. Now switch back to the branch and rebase it onto the main branch. Now you have acquired whatever is new in the main branch, as part of your branch. If your code no longer works, you will know instantly and you can update it.


问:
Flutter Google Sign in data save to Firebase Cloud Firestore
I've implemented google_sign_in package in my flutter application.
I'm registering with google and saving the data in Cloud Firestore Database. I can save the data properly.

What I want is that, the next time someone try use register with google again with the same email it will check from database and show that he already have an account and ask to 'login' with google instead.

The reason I'm trying to do this is that, I will update the user data and logout.

And if I login/register again with the same Google email it replaces my updated data with details from google profile. I want the updated data in the Firestore to stay, not update each time I login.

Can anyone help me with this please. Thanks!

答:
This Function returns true if the user is new , already stored in users collection

```<code>`Future<bool> isNewUser(FirebaseUser user) async {
QuerySnapshot result = await firestore
        .collection("users")
        .where("email", isEqualTo: user.email)
        .getDocuments();
    final List<DocumentSnapshot> docs = result.documents;
    return docs.length == 0 ? true : false;
  }`
</code>```

first cheek if the users is new using the above function the if the user is new
add the user detail to users collection like

```<code>`Future<void> addUserToDb(FirebaseUser currentuser) async {
    user = User(
        uid: currentuser.uid,
        email: currentuser.email,
        name: currentuser.displayName,
        profilePhoto: currentuser.photoUrl,
         );
    firestore
        .collection("users")
        .document(currentuser.uid)
        .setData(user.toMap(user));
  }`
</code>```

and if the user is not a new user show login screen

Body:
This Function returns true if the user is new , already stored in users collection

`Future<bool> isNewUser(FirebaseUser user) async {
QuerySnapshot result = await firestore
        .collection("users")
        .where("email", isEqualTo: user.email)
        .getDocuments();
    final List<DocumentSnapshot> docs = result.documents;
    return docs.length == 0 ? true : false;
  }`

first cheek if the users is new using the above function the if the user is new
add the user detail to users collection like

`Future<void> addUserToDb(FirebaseUser currentuser) async {
    user = User(
        uid: currentuser.uid,
        email: currentuser.email,
        name: currentuser.displayName,
        profilePhoto: currentuser.photoUrl,
         );
    firestore
        .collection("users")
        .document(currentuser.uid)
        .setData(user.toMap(user));
  }`

and if the user is not a new user show login screen


问:
how to make login data available in certain View Controller when login using Google using Firebase Auth?
I have followed all the steps provided from official documentation in here to implement google sign in for iOS.

so I have LoginVC that has google sign in button, when that button is clicked, then it will show login page created by google. here is the IB action for google login button

```<code>@IBAction func googleButtonDidPressed(_ sender: Any) {
        GIDSignIn.sharedInstance().signIn()
}
</code>```

after the user login successfully, it will back to LoginVC from Google Login Page. I want to perform another action in LoginVC after the user login successfully.

the problem is, when the user login successfully, it will trigger a method below in App Delegate. but I need GIDGooleUser data in LoginVC not in appdelegate

```<code>extension AppDelegate : GIDSignInDelegate {

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

       // this method called after the user login successfully
       // i need user: GIDGoogleUser in my LoginVC

    }

}
</code>```

I need that GIDGooleUser to get credential , and then that credential will be used to sign in to get AuthDataResult and FirebaseUser

so how to make notify my LoginVC when login is successful and bring GIDGooleUser to my LoginVC ?

答:
Sample code:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let error = error {
            print("(error.localizedDescription)")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: googleSignInNotification), object: nil, userInfo: ["result" : false])
        } else {
            let userId:String = user.userID
            let idToken:String = user.authentication.idToken
            let fullName:String = user.profile.name
            let givenName:String = user.profile.givenName
            let familyName:String = user.profile.familyName
            let email:String = user.profile.email
      let imageUrl:String=user.profile.imageURL(withDimension:100).absoluteString
       let userDetailsDictionary: [String:String] = ["FirstName": givenName, "LastName": familyName, "Gender": "", "DOB" : "", "GoogleID": userId, "FacebookID": "", "Email": email,"ProfilePicUrl" : imageUrl]

NotificationCenter.default.post(name: NSNotification.Name(rawValue: googleSignInNotification), object: nil, userInfo: ["result" : true])
        }

```<code>}
</code>```

Body:
I have followed all the steps provided from official documentation in here to implement google sign in for iOS.

so I have LoginVC that has google sign in button, when that button is clicked, then it will show login page created by google. here is the IB action for google login button

@IBAction func googleButtonDidPressed(_ sender: Any) {
        GIDSignIn.sharedInstance().signIn()
}

after the user login successfully, it will back to LoginVC from Google Login Page. I want to perform another action in LoginVC after the user login successfully.

the problem is, when the user login successfully, it will trigger a method below in App Delegate. but I need GIDGooleUser data in LoginVC not in appdelegate

extension AppDelegate : GIDSignInDelegate {

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

       // this method called after the user login successfully
       // i need user: GIDGoogleUser in my LoginVC

    }

}

I need that GIDGooleUser to get credential , and then that credential will be used to sign in to get AuthDataResult and FirebaseUser

so how to make notify my LoginVC when login is successful and bring GIDGooleUser to my LoginVC ?

Body:
Sample code:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let error = error {
            print("(error.localizedDescription)")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: googleSignInNotification), object: nil, userInfo: ["result" : false])
        } else {
            let userId:String = user.userID
            let idToken:String = user.authentication.idToken
            let fullName:String = user.profile.name
            let givenName:String = user.profile.givenName
            let familyName:String = user.profile.familyName
            let email:String = user.profile.email
      let imageUrl:String=user.profile.imageURL(withDimension:100).absoluteString
       let userDetailsDictionary: [String:String] = ["FirstName": givenName, "LastName": familyName, "Gender": "", "DOB" : "", "GoogleID": userId, "FacebookID": "", "Email": email,"ProfilePicUrl" : imageUrl]

NotificationCenter.default.post(name: NSNotification.Name(rawValue: googleSignInNotification), object: nil, userInfo: ["result" : true])
        }

}


问:
What can cause a kotlin.TypeCastException for an Activity?
In the Google Play console, I look at the error report and see the following:

```<code>kotlin.TypeCastException:
  at com.app.android.ui.SplashFragment.loadAds (SplashFragment.java:111)
  at com.app.android.ui.SplashFragment$requestConsentInfoUpdate$1.onConsentInfoUpdated (SplashFragment.java:68)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:277)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:188)
  at android.os.AsyncTask.finish (AsyncTask.java:632)
  at android.os.AsyncTask.access$600 (AsyncTask.java:177)
  at android.os.AsyncTask$InternalHandler.handleMessage (AsyncTask.java:645)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:145)
  at android.app.ActivityThread.main (ActivityThread.java:5942)
  at java.lang.reflect.Method.invoke (Method.java)
  at java.lang.reflect.Method.invoke (Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1400)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1195)
</code>```

Google also provides additional. error information:

I tried to run the application on different versions of Android, but I didn’t get an error

The application consists of one activity (MainActivity) and several fragments.

Method in SplashFragment where the error appears:

```<code>fun loadAds() {
        (activity as MainActivity).forceShowAd(callback = { // <- вот тут возникает исключение
            Log.i(TAG, "load ads");
            (activity as MainActivity).toMain()
        })
    }
</code>```

The called method in MainActivity:

```<code>fun forceShowAd(callback: () -> Unit) {
        Log.i(TAG, "forceShowAd")
        run {
            val mInterstitialAd = InterstitialAd(this)
            mInterstitialAd.apply {
                adUnitId = getString(R.string.admob_inter)
                adListener = object : AdListener() {
                    override fun onAdLoaded() {
                        callback()
                        show()
                    }

                    override fun onAdFailedToLoad(p0: Int) {
                        super.onAdFailedToLoad(p0)
                        var mStartAppAd = StartAppAd(applicationContext)
                        mStartAppAd.loadAd(object : AdEventListener {
                            override fun onReceiveAd(ad: Ad) {
                                mStartAppAd.showAd()
                                callback()
                            }
                            override fun onFailedToReceiveAd(ad: Ad) {
                                callback()
                            }
                        })
                    }
                }
                loadAd(getAdRequest())
            }
        }

    }
</code>```

This is how SplashFragment starts in MainActivity:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                    .replace(R.id.container, SplashFragment.newInstance())
                    .commit()
        }
    }
</code>```

Based on the life cycle of the application, while the fragment is running, activity should also work. But at the same time, as I understand it, at the time the exception was thrown activity == null

What could cause the exception problem? This problem occurs already on 6% of devices

答:
Your loadAds() call appears to be happening as a result of an asynchronous operation (onConsentInfoUpdated() being triggered by an AsyncTask). You have no idea how long that asynchronous operation will take, and you have no idea what state your activity/fragment might be in at that time. For example, perhaps the user pressed BACK and destroyed MainActivity before loadAds() got called.

You need to handle the cases where activity is null or where the activity itself has been destroyed (isFinishing or isDestroyed are true).

Body:
In the Google Play console, I look at the error report and see the following:

kotlin.TypeCastException:
  at com.app.android.ui.SplashFragment.loadAds (SplashFragment.java:111)
  at com.app.android.ui.SplashFragment$requestConsentInfoUpdate$1.onConsentInfoUpdated (SplashFragment.java:68)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:277)
  at com.google.ads.consent.ConsentInformation$ConsentInfoUpdateTask.onPostExecute (ConsentInformation.java:188)
  at android.os.AsyncTask.finish (AsyncTask.java:632)
  at android.os.AsyncTask.access$600 (AsyncTask.java:177)
  at android.os.AsyncTask$InternalHandler.handleMessage (AsyncTask.java:645)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:145)
  at android.app.ActivityThread.main (ActivityThread.java:5942)
  at java.lang.reflect.Method.invoke (Method.java)
  at java.lang.reflect.Method.invoke (Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1400)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1195)

Google also provides additional. error information:

I tried to run the application on different versions of Android, but I didn’t get an error

The application consists of one activity (MainActivity) and several fragments.

Method in SplashFragment where the error appears:

fun loadAds() {
        (activity as MainActivity).forceShowAd(callback = { // <- вот тут возникает исключение
            Log.i(TAG, "load ads");
            (activity as MainActivity).toMain()
        })
    }

The called method in MainActivity:

fun forceShowAd(callback: () -> Unit) {
        Log.i(TAG, "forceShowAd")
        run {
            val mInterstitialAd = InterstitialAd(this)
            mInterstitialAd.apply {
                adUnitId = getString(R.string.admob_inter)
                adListener = object : AdListener() {
                    override fun onAdLoaded() {
                        callback()
                        show()
                    }

                    override fun onAdFailedToLoad(p0: Int) {
                        super.onAdFailedToLoad(p0)
                        var mStartAppAd = StartAppAd(applicationContext)
                        mStartAppAd.loadAd(object : AdEventListener {
                            override fun onReceiveAd(ad: Ad) {
                                mStartAppAd.showAd()
                                callback()
                            }
                            override fun onFailedToReceiveAd(ad: Ad) {
                                callback()
                            }
                        })
                    }
                }
                loadAd(getAdRequest())
            }
        }

    }

This is how SplashFragment starts in MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                    .replace(R.id.container, SplashFragment.newInstance())
                    .commit()
        }
    }

Based on the life cycle of the application, while the fragment is running, activity should also work. But at the same time, as I understand it, at the time the exception was thrown activity == null

What could cause the exception problem? This problem occurs already on 6% of devices


问:
pyspark how to load compressed snappy file
I have compressed a file using python-snappy and put it in my hdfs store.  I am now trying to read it in like so but I get the following traceback.  I can't find an example of how to read the file in so I can process it.  I can read the text file (uncompressed) version fine.  Should I be using sc.sequenceFile ?  Thanks!

```<code>I first compressed the file and pushed it to hdfs

python-snappy -m snappy -c gene_regions.vcf gene_regions.vcf.snappy
hdfs dfs -put gene_regions.vcf.snappy /

I then added the following to spark-env.sh
export SPARK_EXECUTOR_MEMORY=16G
export HADOOP_HOME=/usr/local/hadoop

export JAVA_LIBRARY_PATH=$JAVA_LIBRARY_PATH:$HADOOP_HOME/lib/native
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HADOOP_HOME/lib/native
export SPARK_LIBRARY_PATH=$SPARK_LIBRARY_PATH:$HADOOP_HOME/lib/native
export SPARK_CLASSPATH=$SPARK_CLASSPATH:$HADOOP_HOME/lib/lib/snappy-java-1.1.1.8-SNAPSHOT.jar

I then launch my spark master and slave and finally my ipython notebook where I am executing the code below.

a_file = sc.textFile("hdfs://master:54310/gene_regions.vcf.snappy")
a_file.first()
</code>```

ValueError                                Traceback (most recent call last)
 in ()
----> 1 a_file.first()

/home/user/Software/spark-1.3.0-bin-hadoop2.4/python/pyspark/rdd.pyc in first(self)
   1244         if rs:
   1245             return rs[0]
-> 1246         raise ValueError("RDD is empty")
   1247
   1248     def isEmpty(self):

ValueError: RDD is empty

```<code>Working code (uncompressed) text file
a_file = sc.textFile("hdfs://master:54310/gene_regions.vcf")
a_file.first()
</code>```

output:
u'##fileformat=VCFv4.1'

答: Not sure exactly which snappy codec my files have, but spark.read.text worked without incident for me.

Body:
I have compressed a file using python-snappy and put it in my hdfs store.  I am now trying to read it in like so but I get the following traceback.  I can't find an example of how to read the file in so I can process it.  I can read the text file (uncompressed) version fine.  Should I be using sc.sequenceFile ?  Thanks!

I first compressed the file and pushed it to hdfs

python-snappy -m snappy -c gene_regions.vcf gene_regions.vcf.snappy
hdfs dfs -put gene_regions.vcf.snappy /

I then added the following to spark-env.sh
export SPARK_EXECUTOR_MEMORY=16G
export HADOOP_HOME=/usr/local/hadoop

export JAVA_LIBRARY_PATH=$JAVA_LIBRARY_PATH:$HADOOP_HOME/lib/native
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HADOOP_HOME/lib/native
export SPARK_LIBRARY_PATH=$SPARK_LIBRARY_PATH:$HADOOP_HOME/lib/native
export SPARK_CLASSPATH=$SPARK_CLASSPATH:$HADOOP_HOME/lib/lib/snappy-java-1.1.1.8-SNAPSHOT.jar

I then launch my spark master and slave and finally my ipython notebook where I am executing the code below.

a_file = sc.textFile("hdfs://master:54310/gene_regions.vcf.snappy")
a_file.first()

ValueError                                Traceback (most recent call last)
 in ()
----> 1 a_file.first()

/home/user/Software/spark-1.3.0-bin-hadoop2.4/python/pyspark/rdd.pyc in first(self)
   1244         if rs:
   1245             return rs[0]
-> 1246         raise ValueError("RDD is empty")
   1247
   1248     def isEmpty(self):

ValueError: RDD is empty

Working code (uncompressed) text file
a_file = sc.textFile("hdfs://master:54310/gene_regions.vcf")
a_file.first()

output:
u'##fileformat=VCFv4.1'


问:
Rasperry Pi4 does not show the Hostname
I´m using Raspberry Pi 4 and Windows 10 machine
And I setup a custom hostname in the raspberry by $ sudo raspi-config
and then when I use hostname in the raspberry it is given me the new hostname.
But I´m traying to get this hostname from my Windows machine and it is not give my.

```<code>pi@PLC:~ $ hostname -I
169.254.100.158 192.168.1.72 fd18:5644:3369:d200:f282:15d1:9085:858

pi@PLC:~ $ hostname

PLC
</code>```

When I ping my raspberry or nmap or arp -a does not given me any Host-name response any suggestion.
For example when I ping to 8.8.8.8 C:\Users\n-orb>ping -a 8.8.8.8 it is given me the Hostname but if I ping the Raspberry it is not given me the hostname.

```<code>C:\Users\n-orb>ping -a 8.8.8.8
ping to dns.google [8.8.8.8] with 32 bytes

C:\Users\n-orb>ping -a 168.254.100.158
ping to 168.254.100.158 with 32 bytes

C:\Users\n-orb>ping 192.168.1.72
ping to 192.168.1.72 with 32 bytes
</code>```

Does anyone know how to get the hostname.?

答:
Resolving an IP address to a hostname is done via Reverse DNS Lookup. Reverse DNS Lookup is actually nothing special, it's just normal DNS Lookup in the "magic" sub-domain in-addr.arpa.

When you try to resolve the IP address 192.168.1.72 to a hostname, what is actually happening, is that the DNS resolver is trying to resolve the PTR record for the hostname 71.1.168.192.in-addr.arpa.

So, when you want your IP address 192.168.1.72 to resolve to the hostname PLC, you need to configure your DNS server so that it responds to a PTR query for 71.1.168.192.in-addr.arpa. with the response PLC in exactly the same way that, for the other direction, you set up your DNS server so that it responds to an A query for PLC with the response 192.168.1.72.

Title: Rasperry Pi4 does not show the Hostname

Body:
I´m using Raspberry Pi 4 and Windows 10 machine
And I setup a custom hostname in the raspberry by $ sudo raspi-config
and then when I use hostname in the raspberry it is given me the new hostname.
But I´m traying to get this hostname from my Windows machine and it is not give my.

pi@PLC:~ $ hostname -I
169.254.100.158 192.168.1.72 fd18:5644:3369:d200:f282:15d1:9085:858

pi@PLC:~ $ hostname

PLC

When I ping my raspberry or nmap or arp -a does not given me any Host-name response any suggestion.
For example when I ping to 8.8.8.8 C:\Users\n-orb>ping -a 8.8.8.8 it is given me the Hostname but if I ping the Raspberry it is not given me the hostname.

C:\Users\n-orb>ping -a 8.8.8.8
ping to dns.google [8.8.8.8] with 32 bytes

C:\Users\n-orb>ping -a 168.254.100.158
ping to 168.254.100.158 with 32 bytes

C:\Users\n-orb>ping 192.168.1.72
ping to 192.168.1.72 with 32 bytes

Does anyone know how to get the hostname.?


问:
Creating a difference column
I have a dataframe with prices for several items.

```<code>items st.price b.price s.price
item1 10.50    8.00    12.00
item2  9.00    7.50    11.50
item3 22.00    20.00   25.00
item4 19.00    17.00   22.00
item5 55.00    53.00   57.00
</code>```

I want to create a new column difference that indicates the difference of the highest price of the item and extract the sum of the other 2 prices.

```<code>EDIT: EXPECTED OUTPUT
    items st.price b.price s.price difference
    item1 10.50    8.00    12.00    -6.5
    item2  9.00    7.50    11.50    -5
    item3 22.00    20.00   25.00    -19
    item4 19.00    17.00   22.00    -14
    item5 55.00    53.00   57.00    -51
</code>```

答:
May be, we can use apply to get the max of each row and then subtract from the sum of the rest

```<code>df1$difference <- apply(df1[-1], 1, function(x) {
       i1 <- which.max(x)
      x[i1]- sum(x[-i1])})
</code>```

Or using a vectorized option with pmax to get the max of each row, replace the numeric columns where the value is not equal to 'mx' with NA, apply the rowSums and get the difference between the 'mx' and this output

```<code>mx <- do.call(pmax, df1[-1])
mx  - rowSums(replace(df1[-1], df1[-1] == mx, NA), na.rm = TRUE)
#[1]  -6.5  -5.0 -17.0 -14.0 -51.0
</code>```

data

```<code>df1 <- structure(list(items = c("item1", "item2", "item3", "item4",
"item5"), st.price = c(10.5, 9, 22, 19, 55), b.price = c(8, 7.5,
20, 17, 53), s.price = c(12, 11.5, 25, 22, 57)), class = "data.frame",
row.names = c(NA,
-5L))
</code>```

Title: Creating a difference column

Body:
I have a dataframe with prices for several items.

items st.price b.price s.price
item1 10.50    8.00    12.00
item2  9.00    7.50    11.50
item3 22.00    20.00   25.00
item4 19.00    17.00   22.00
item5 55.00    53.00   57.00

I want to create a new column difference that indicates the difference of the highest price of the item and extract the sum of the other 2 prices.

EDIT: EXPECTED OUTPUT
    items st.price b.price s.price difference
    item1 10.50    8.00    12.00    -6.5
    item2  9.00    7.50    11.50    -5
    item3 22.00    20.00   25.00    -19
    item4 19.00    17.00   22.00    -14
    item5 55.00    53.00   57.00    -51

Body:
May be, we can use apply to get the max of each row and then subtract from the sum of the rest

df1$difference <- apply(df1[-1], 1, function(x) {
       i1 <- which.max(x)
      x[i1]- sum(x[-i1])})

Or using a vectorized option with pmax to get the max of each row, replace the numeric columns where the value is not equal to 'mx' with NA, apply the rowSums and get the difference between the 'mx' and this output

mx <- do.call(pmax, df1[-1])
mx  - rowSums(replace(df1[-1], df1[-1] == mx, NA), na.rm = TRUE)
#[1]  -6.5  -5.0 -17.0 -14.0 -51.0

data

df1 <- structure(list(items = c("item1", "item2", "item3", "item4",
"item5"), st.price = c(10.5, 9, 22, 19, 55), b.price = c(8, 7.5,
20, 17, 53), s.price = c(12, 11.5, 25, 22, 57)), class = "data.frame",
row.names = c(NA,
-5L))


问:
High Level Design for Installation and Upgrade Application
I need to write a very simple WinForms application, but I often get stuck in over analytical mode with these. I get stuck on Yes, No, Retry loops, and with very little thinking to do about the actions of the application, I start thinking about the 'workflow' of the application. Should I just have a method for each task, and call each one sequentially, after checking that the previous didn't raise an 'abort' flag?

Should I implement a simple ITask interface, and a class for each task, then loop through an ordered collection of tasks? Should I use this as a simple introduction to Windows Workflow? The scope of this application and its set of tasks is guaranteed to grow, so my first option of hard coding the tasks is the nastiest, but given the size of the app, maintenance can quite easily be done by just changing the code; the executable is always deployed with the upgrade materials, and not permanently deployed.

答: Do the simplest thing. You can always refactor later.</p>

OwnerDisplayName: ProfK

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Peter Lillevold


问:
PHP - flock() automatic release in versions since 5.3.2
As the Manual states

https://www.php.net/manual/en/function.flock.php

On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).
```

As far as I understand the lock isn't released automatically since version 5.3.2. Is that correct?

Furtheron this leads to the question if the lock is released while the script execution has been aborted by the client (by HTTP request or CLI).

答:
The lock isn't released automatically since 5.3.2

If you terminate the script before unlocking. PHP won't unlock it. You then have to relay on the OS to do so.

In short: always unlock

Body:
As the Manual states

https://www.php.net/manual/en/function.flock.php

On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).

As far as I understand the lock isn't released automatically since version 5.3.2. Is that correct?

Furtheron this leads to the question if the lock is released while the script execution has been aborted by the client (by HTTP request or CLI).


问:
Rails: Run a method when user left the edit view through the browser back button
Is there a possibility to detect if a user has exited the edit view (edit action) without saving through the back button of the browser and then run a method to set the value of a field in the database? I tried after_action on the edit action but this fires directly after rendering the edit view.</p>

答:
Hitting the back button in a web browser won't involve Rails, but rendering the component to which it is being sent will.

You can save the data of the input fields in the browser's local storage or cookies and then have a before_action: in the controller they were sent to with the back button that looks for the presence of such value.
( This solution involves some javascript )

Then, you can query accordingly to determine if those values should be saved in the database.

Note: If you need to cover not only the back button scenario, but also any other controller to which the user might navigate to in your app, you may add the before_action to somewhere else, like application_controller.


问:
Least Similar with Gensim Doc2Vec
The most_similar method finds the top-N most similar words.

Is there a method or a way to find the N least similar words?

答:
You could get the full ranked list of all vectors by similarity, using a topn parameter as large as the full set of vectors. Then look at just the last N. For example:

import sys
all_sims = vec_model.most_similar(target_value, topn=sys.maxsize)
last_10 = list(reversed(all_sims[-10:]))
```

However, note:

This will require a bit more sorting, & momentarily need a lot more memory, to return the full list before trimming it to the last few

These are unlikely to be especially meaningful, as either words or documents, to human perception. That is, it's unlikely to be a word's or document's 'opposite' in the senses we perceive. Such opposites, or indeed any words/docs that are interestingly contrasted with an origin point, are usually going to be quite close to the origin in the high-dimensional space, just shifted in some meaningful way. (For example, a word's antonyms are far closer to the word than the most-dissimilar words this will find.)

Title: Least Similar with Gensim Doc2Vec

Body:
You could get the full ranked list of all vectors by similarity, using a topn parameter as large as the full set of vectors. Then look at just the last N. For example:

import sys
all_sims = vec_model.most_similar(target_value, topn=sys.maxsize)
last_10 = list(reversed(all_sims[-10:]))

However, note:

This will require a bit more sorting, & momentarily need a lot more memory, to return the full list before trimming it to the last few

These are unlikely to be especially meaningful, as either words or documents, to human perception. That is, it's unlikely to be a word's or document's 'opposite' in the senses we perceive. Such opposites, or indeed any words/docs that are interestingly contrasted with an origin point, are usually going to be quite close to the origin in the high-dimensional space, just shifted in some meaningful way. (For example, a word's antonyms are far closer to the word than the most-dissimilar words this will find.)


问:
Invalid command name in Tcl when using format
I'm running the following commands

```<code>set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"
</code>```

and I get the following error:

```<code>full_pin_name is invalid command name "A" B
</code>```

when top_cell equals A and encoded_name equals B.

Why is this happening?

答:
Try repeating this in a plain Tcl shell, it works.  Something is different in your Tcl shell.

Try

```<code>info body set
</code>```

and

```<code>info body format
</code>```

If either report something other than set isn't a procedure or format isn't a procedure then you have your culprit.

Body:
I'm running the following commands

set full_pin_name [format "%s %s" $top_cell $encoded_name]
puts "full_pin_name is $full_pin_name"

and I get the following error:

full_pin_name is invalid command name "A" B

when top_cell equals A and encoded_name equals B.

Why is this happening?

Body:
Try repeating this in a plain Tcl shell, it works.  Something is different in your Tcl shell.

Try

info body set

and

info body format

If either report something other than set isn't a procedure or format isn't a procedure then you have your culprit.


问:
how to save an array as a grayscale image with matplotlib/numpy?
I am trying to save a numpy array of dimensions 128x128 pixels into a grayscale image.
I simply thought that the pyplot.imsave function would do the job but it's not, it somehow converts my array into an RGB image.
I tried to force the colormap to Gray during conversion but eventhough the saved image appears in grayscale, it still has a 128x128x4 dimension.
Here is a code sample I wrote to show the behaviour :

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mplimg
from matplotlib import cm

x_tot = 10e-3
nx = 128

x = np.arange(-x_tot/2, x_tot/2, x_tot/nx)

[X, Y] = np.meshgrid(x,x)
R = np.sqrt(X**2 + Y**2)

diam = 5e-3
I = np.exp(-2*(2*R/diam)**4)

plt.figure()
plt.imshow(I, extent = [-x_tot/2, x_tot/2, -x_tot/2, x_tot/2])

print I.shape

plt.imsave('image.png', I)
I2 = plt.imread('image.png')
print I2.shape

mplimg.imsave('image2.png',np.uint8(I), cmap = cm.gray)
testImg = plt.imread('image2.png')
print testImg.shape
</code>```

In both cases the results of the "print" function are (128,128,4).

Can anyone explain why the imsave function is creating those dimensions eventhough my input array is of a luminance type?
And of course, does anyone have a solution to save the array into a standard grayscale format?

Thanks!

答:
There is also a possibility to use scikit-image, then there is no need to convert numpy array into a PIL object.</p>

```<code>from skimage import io
io.imsave('output.tiff', I.astype(np.uint16))
</code>```

Body:
I am trying to save a numpy array of dimensions 128x128 pixels into a grayscale image.
I simply thought that the pyplot.imsave function would do the job but it's not, it somehow converts my array into an RGB image.
I tried to force the colormap to Gray during conversion but eventhough the saved image appears in grayscale, it still has a 128x128x4 dimension.
Here is a code sample I wrote to show the behaviour :

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mplimg
from matplotlib import cm

x_tot = 10e-3
nx = 128

x = np.arange(-x_tot/2, x_tot/2, x_tot/nx)

[X, Y] = np.meshgrid(x,x)
R = np.sqrt(X**2 + Y**2)

diam = 5e-3
I = np.exp(-2*(2*R/diam)**4)

plt.figure()
plt.imshow(I, extent = [-x_tot/2, x_tot/2, -x_tot/2, x_tot/2])

print I.shape

plt.imsave('image.png', I)
I2 = plt.imread('image.png')
print I2.shape

mplimg.imsave('image2.png',np.uint8(I), cmap = cm.gray)
testImg = plt.imread('image2.png')
print testImg.shape

In both cases the results of the "print" function are (128,128,4).

Can anyone explain why the imsave function is creating those dimensions eventhough my input array is of a luminance type?
And of course, does anyone have a solution to save the array into a standard grayscale format?

Thanks!

Body:
There is also a possibility to use scikit-image, then there is no need to convert numpy array into a PIL object.

from skimage import io
io.imsave('output.tiff', I.astype(np.uint16))


问:
Is there a way to use a selenium webdriver without showing the browser?
I tried searching for a solution on this site because there is a question that is almost the same as mine. This sadly this didn't work for me. The code below is what I have right now... Is it possible to start the webdriver without actually showing the process?

```<code># Options
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')

# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")

# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1600, 800)
driver.get(url)
</code>```

Edit:
I fixed it by replacing with the code in the answer:

```<code>driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)
</code>```

I still get an error:

```<code>C:/Users/ducov/PycharmProjects/bot/app.py:18: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)
</code>```

But I don't think that matters

答:
You should put execute_path and chrome_options in same line.

```<code>driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)
</code>```

ps: in your code, you run 2 Chrome instances, one is webdriver.Chrome('/Users/ducov/Downloads/chromedriver'), and another is webdriver.Chrome(chrome_options=options)

Body:
I tried searching for a solution on this site because there is a question that is almost the same as mine. This sadly this didn't work for me. The code below is what I have right now... Is it possible to start the webdriver without actually showing the process?

# Options
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')

# Gegevens
password = input("Please give us a password you want to use for all your account(s): ")

# Start de driver
url = 'https://twitter.com/?lang=en-gb'
driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1600, 800)
driver.get(url)

Edit:
I fixed it by replacing with the code in the answer:

driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver')
driver = webdriver.Chrome(chrome_options=options)

I still get an error:

C:/Users/ducov/PycharmProjects/bot/app.py:18: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)

But I don't think that matters

Body:
You should put execute_path and chrome_options in same line.

driver = webdriver.Chrome('/Users/ducov/Downloads/chromedriver', chrome_options=options)

ps: in your code, you run 2 Chrome instances, one is webdriver.Chrome('/Users/ducov/Downloads/chromedriver'), and another is webdriver.Chrome(chrome_options=options)


问:
Executing remote script by curl doesn't work
I'm trying to run one script (which installs and setups Postgres DB) from another script (test.sh). The problem is that the script which is called inside my script is remote (online on GitHub) and it doesn't work.

I tried to call the script three different ways.

locally - works

remotely using bash <(curl... - raises error

remotely using curl ... | bash -s - downloads script and hangs...

test.sh

```<code>#!/bin/bash

# this works correctly (it's the same but local)
sudo bash postgres/setup.sh

# this raises "bash: /dev/fd/63: No such file or directory"
sudo bash <(curl -s https://raw.githubusercontent.com/milano-slesarik/sh-ubuntu-instant/master/postgres/setup.sh)

# this hangs
curl https://raw.githubusercontent.com/milano-slesarik/sh-ubuntu-instant/master/postgres/setup.sh | sudo bash -s
</code>```

The last one probably downloads the script but then hangs...

```<code>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1532  100  1532    0     0   8281      0 --:--:-- --:--:-- --:--:--  8281
</code>```

Do you know how to make it work?
I want my scripts to be online so I don't have to clone/download then all the time.

答:
The reason why it hangs when you run curl -s $script |bash -s seems to be a misbehaviour in the script itself, at least as long as you run it like that. You can debug this by adding the -x flag to the bash command. Then you can see the following message spawning in an endless loop, due to the while statement contained in the script:

```<code>++ read -p 'Do you wan'\''t to install postgres? [y/n]: ' yn
++ case $yn in
</code>```

Also, as long as you are running the script this way, to avoid this behaviour I would remove those lines in which the script is expecting some kind of user input. If that is not the case, the easiest way is just to download it via curl and then run it locally from your terminal.

Body:
I'm trying to run one script (which installs and setups Postgres DB) from another script (test.sh). The problem is that the script which is called inside my script is remote (online on GitHub) and it doesn't work.

I tried to call the script three different ways.

locally - works

remotely using bash <(curl... - raises error

remotely using curl ... | bash -s - downloads script and hangs...

test.sh

#!/bin/bash

# this works correctly (it's the same but local)
sudo bash postgres/setup.sh

# this raises "bash: /dev/fd/63: No such file or directory"
sudo bash <(curl -s https://raw.githubusercontent.com/milano-slesarik/sh-ubuntu-instant/master/postgres/setup.sh)

# this hangs
curl https://raw.githubusercontent.com/milano-slesarik/sh-ubuntu-instant/master/postgres/setup.sh | sudo bash -s

The last one probably downloads the script but then hangs...

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1532  100  1532    0     0   8281      0 --:--:-- --:--:-- --:--:--  8281

Do you know how to make it work?
I want my scripts to be online so I don't have to clone/download then all the time.

Body:
The reason why it hangs when you run curl -s $script |bash -s seems to be a misbehaviour in the script itself, at least as long as you run it like that. You can debug this by adding the -x flag to the bash command. Then you can see the following message spawning in an endless loop, due to the while statement contained in the script:

++ read -p 'Do you wan'\''t to install postgres? [y/n]: ' yn
++ case $yn in

Also, as long as you are running the script this way, to avoid this behaviour I would remove those lines in which the script is expecting some kind of user input. If that is not the case, the easiest way is just to download it via curl and then run it locally from your terminal.


问:
How do I configure CDK to deploy to the correct region?
I'm trying to deploy a simple stack to AWS using CDK. Unfortunately though when I'm running it through my GitHub actions workflow it seems to be deploying to the wrong region and I can't work out why...

The contents of my bin\cdk.js look like (sample account):

```<code>#!/usr/bin/env node

const cdk = require("@aws-cdk/core");
const { CdkStack } = require("../lib/cdk-stack");

const app = new cdk.App();
new CdkStack(app, "CdkStack", { account: "000000000001", region: "eu-west-1" });

</code>```

This looks correct to my eyes following the docs. I haven't defined anything anywhere else as far as I'm aware. If I run a cdk bootstrap the CloudFormation is generated. The only reference to region is:

"environment": "aws://unknown-account/unknown-region",

Am I missing something totally obvious here? The way I've got it configured in my pipeline is simply using:

```<code>            - name: CDK Deploy
              env:
                  AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID}}
                  AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY}}
              run: |
                  npm install -g aws-cdk
                  cdk bootstrap
                  cdk deploy --require-approval never
</code>```

答:
You can set the default region as an environment variable in the pipeline configuration:</p>
```<code>- name: CDK Deploy
  env:
    AWS_DEFAULT_REGION: eu-west-1
    ...
  run: |
    npm install -g aws-cdk
    cdk bootstrap
    cdk deploy --require-approval never
</code>```

Body:
I'm trying to deploy a simple stack to AWS using CDK. Unfortunately though when I'm running it through my GitHub actions workflow it seems to be deploying to the wrong region and I can't work out why...

The contents of my bin\cdk.js look like (sample account):

#!/usr/bin/env node

const cdk = require("@aws-cdk/core");
const { CdkStack } = require("../lib/cdk-stack");

const app = new cdk.App();
new CdkStack(app, "CdkStack", { account: "000000000001", region: "eu-west-1" });

This looks correct to my eyes following the docs. I haven't defined anything anywhere else as far as I'm aware. If I run a cdk bootstrap the CloudFormation is generated. The only reference to region is:

"environment": "aws://unknown-account/unknown-region",

Am I missing something totally obvious here? The way I've got it configured in my pipeline is simply using:

            - name: CDK Deploy
              env:
                  AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID}}
                  AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY}}
              run: |
                  npm install -g aws-cdk
                  cdk bootstrap
                  cdk deploy --require-approval never

Body:
You can set the default region as an environment variable in the pipeline configuration:

- name: CDK Deploy
  env:
    AWS_DEFAULT_REGION: eu-west-1
    ...
  run: |
    npm install -g aws-cdk
    cdk bootstrap
    cdk deploy --require-approval never


问:
How to enable Log-in page in Spring Security?
I'm using this tutorial as a base of my app security.

Given tutorial allows user to log-in via http://localhost:8080/login using http POST method to send username and password.

Now, I know that Spring-Security comes with built in Log-in mechanism. Is there a simple way to somehow access and enable this build in login page?

This is how configuration looks like:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            // this disables session creation on Spring Security
     .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
</code>```

Looking forward for your answers!

答:
This page is created by default if you use spring security. Everything you need is to add 2 dependecies to classpath of your spring boot application:

1. Web

2. Security

I created a link for you: https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.3.0.RELEASE&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=demo&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.demo&dependencies=web,security

If you go by this link and click "Generate" at the bottom of the page - a new empty spring boot project will be downloaded as archive. If you unpack it, build and execute you will see in console output:

It means spring security is enabled and password is created. You will see default login page by url: http://localhost:8080/

You can use username "user" and password generated by spring in console output for login.

Your article uses JWT tokens for authorization, but default spring security mechanism relies on sessions. So, this form should be configured another way, like in this article: https://www.baeldung.com/spring-security-login

Body:
I'm using this tutorial as a base of my app security.

Given tutorial allows user to log-in via http://localhost:8080/login using http POST method to send username and password.

Now, I know that Spring-Security comes with built in Log-in mechanism. Is there a simple way to somehow access and enable this build in login page?

This is how configuration looks like:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            // this disables session creation on Spring Security
     .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Looking forward for your answers!


问:
Styling tabs in android like the google open source contacts
I'm having troubles trying to style my tabs in android.

I want to make them look exactly the same as whats in the open source android contacts list (see https://android.googlesource.com/platform/packages/apps/Contacts
 ).

Problem is that when they display on the screen it looks a bit different to the contacts app.

When it should look like this:

Notice how the background colors are a little bit different and the text colors are different.

Not sure why this is the case as its basically the same code and icons.

My tab layout code is the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="0dp">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="0dp" />
    </LinearLayout>
</TabHost>
</code>```

Which doesn't contain anything special there.. and the TabActivity is as follows:

```<code>public class TabbedActivity extends TabActivity implements
        TabHost.OnTabChangeListener {

    private TabHost tabHost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final Intent intent = getIntent();

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.tab);

        tabHost = getTabHost();
        tabHost.setOnTabChangedListener(this);

        setupLatestTab();
        setupSavedTab();

        tabHost.setCurrentTab(0);
    }

    private void setupLatestTab() {

        Intent intent = new Intent().setClass(this, ResultsActivity.class);

        tabHost.addTab(tabHost
                .newTabSpec("latest")
                .setIndicator("Latest",
                        getResources().getDrawable(R.drawable.ic_tab_recent))
                .setContent(intent));
    }

    private void setupSavedTab() {

        Intent intent = new Intent().setClass(this, ResultsActivity.class);

        tabHost.addTab(tabHost
                .newTabSpec("saved")
                .setIndicator("Saved",
                        getResources().getDrawable(R.drawable.ic_tab_starred))
                .setContent(intent));
    }

    @Override
    public void onTabChanged(String tabId) {
        // Because we're using Activities as our tab children, we trigger
        // onWindowFocusChanged() to let them know when they're active. This may
        // seem to duplicate the purpose of onResume(), but it's needed because
        // onResume() can't reliably check if a keyguard is active.
        Activity activity = getLocalActivityManager().getActivity(tabId);
        if (activity != null) {
            activity.onWindowFocusChanged(true);
        }
    }

}
</code>```

I am using the same images from the drawable folders too.

I know i can set the background of tabs manually by doing something like this in the tabactivity

```<code>tabHost.getTabWidget().getChildAt(index).setBackgroundColor(Color.parseColor("#ff202020"));
</code>```

But the contacts app isn't doing this sort of thing anywhere (most of the top tab code is in DialtactsActivity), so just want to do what the open source app is doing when displaying tabs - i'm not sure how and why the contacts application tabs look much better when im basically using the same code and resources.

I guess im just missing something trivial??

答:
This turned out to be a problem with my minimum android version not being specified ..

Added:

```<code><uses-sdk android:minSdkVersion="8" />
</code>```

to the androidmanifest and it worked fine. I guess it was reverting to the old tabs look and feel in earlier versions of android.

Body:
I'm having troubles trying to style my tabs in android.

I want to make them look exactly the same as whats in the open source android contacts list (see https://android.googlesource.com/platform/packages/apps/Contacts
 ).

Problem is that when they display on the screen it looks a bit different to the contacts app.

When it should look like this:

Notice how the background colors are a little bit different and the text colors are different.

Not sure why this is the case as its basically the same code and icons.

My tab layout code is the following:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="0dp">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="0dp" />
    </LinearLayout>
</TabHost>

Which doesn't contain anything special there.. and the TabActivity is as follows:

public class TabbedActivity extends TabActivity implements
        TabHost.OnTabChangeListener {

    private TabHost tabHost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final Intent intent = getIntent();

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.tab);

        tabHost = getTabHost();
        tabHost.setOnTabChangedListener(this);

        setupLatestTab();
        setupSavedTab();

        tabHost.setCurrentTab(0);
    }

    private void setupLatestTab() {

        Intent intent = new Intent().setClass(this, ResultsActivity.class);

        tabHost.addTab(tabHost
                .newTabSpec("latest")
                .setIndicator("Latest",
                        getResources().getDrawable(R.drawable.ic_tab_recent))
                .setContent(intent));
    }

    private void setupSavedTab() {

        Intent intent = new Intent().setClass(this, ResultsActivity.class);

        tabHost.addTab(tabHost
                .newTabSpec("saved")
                .setIndicator("Saved",
                        getResources().getDrawable(R.drawable.ic_tab_starred))
                .setContent(intent));
    }

    @Override
    public void onTabChanged(String tabId) {
        // Because we're using Activities as our tab children, we trigger
        // onWindowFocusChanged() to let them know when they're active. This may
        // seem to duplicate the purpose of onResume(), but it's needed because
        // onResume() can't reliably check if a keyguard is active.
        Activity activity = getLocalActivityManager().getActivity(tabId);
        if (activity != null) {
            activity.onWindowFocusChanged(true);
        }
    }

}

I am using the same images from the drawable folders too.

I know i can set the background of tabs manually by doing something like this in the tabactivity

tabHost.getTabWidget().getChildAt(index).setBackgroundColor(Color.parseColor("#ff202020"));

But the contacts app isn't doing this sort of thing anywhere (most of the top tab code is in DialtactsActivity), so just want to do what the open source app is doing when displaying tabs - i'm not sure how and why the contacts application tabs look much better when im basically using the same code and resources.

I guess im just missing something trivial??

Body:
This turned out to be a problem with my minimum android version not being specified ..

Added:

<uses-sdk android:minSdkVersion="8" />

to the androidmanifest and it worked fine. I guess it was reverting to the old tabs look and feel in earlier versions of android.


问:
Create a .csv file in every folder using PowerShell
I have a directory with about 600 folders. In every each folder I need to create a .csv file and have 2 predefined values inside (valueA and valueB). I managed to do that by writing:

```<code>Get-ChildItem -Recurse -Directory |
ForEach-Object {
  New-Item -ItemType file -Path "$($_.FullName)" -Name "$($_.Name).csv
}
</code>```

It works great, however I would like to have this files .csv files created with 2 values already inside: valueA and valueB as I mentioned above. Any suggestions how can I achieve that?

答:
If I understand correctly, you want two columns created, not rows.

Try

```<code>Get-ChildItem -Recurse -Directory |
ForEach-Object {
    $out = Join-Path -Path $_.FullName -ChildPath  ('{0}.csv' -f $_.Name)
    "" | Select-Object ValueA, ValueB |
    Export-Csv -Path $out -NoTypeInformation
}
</code>```

Hope this helps

Body:
I have a directory with about 600 folders. In every each folder I need to create a .csv file and have 2 predefined values inside (valueA and valueB). I managed to do that by writing:

Get-ChildItem -Recurse -Directory |
ForEach-Object {
  New-Item -ItemType file -Path "$($_.FullName)" -Name "$($_.Name).csv
}

It works great, however I would like to have this files .csv files created with 2 values already inside: valueA and valueB as I mentioned above. Any suggestions how can I achieve that?

Body:
If I understand correctly, you want two columns created, not rows.

Try

Get-ChildItem -Recurse -Directory |
ForEach-Object {
    $out = Join-Path -Path $_.FullName -ChildPath  ('{0}.csv' -f $_.Name)
    "" | Select-Object ValueA, ValueB |
    Export-Csv -Path $out -NoTypeInformation
}

Hope this helps