问:
How to build a NixOps deployment on hydra
Deploying my NixOps machines takes alot of time, as packages need to build. I want to do the building regularly on my trusted private Hydra instance.

My current approach involves this release.nix file, but it doesn't work out so well.

```<code>{ nixpkgs ? <nixpkgs>, onlySystem ? true, extraModules ? [] }:

let

  nixos = import "${nixpkgs}/nixos";

  buildEnv = conf: (nixos {
    configuration = conf;
  });
  buildTarget = m: let build = buildEnv (buildConf m); in
    if onlySystem then build.system else build.vm;

  buildConf = module: { ... }:
    {
      imports = [ module ] ++ extraModules;
    };

in

{
  machine1 = buildTarget ./machine1/configuration.nix;
  machine2 = buildTarget ./machine2/configuration.nix
  machine3 = buildTarget ./machine3/configuration.nix
  machine4 = buildTarget ./machine4/configuration.nix
}
</code>```

I don't really understand this code, as I copied it from here.

This builds fine if I run nix-build release.nix locally, but on hydra I never get a full build. Sometimes builds don't dequeue (they just don't get build), sometimes they fail with various error messages. As nothing of the hydra problems are reproducible (beside the fact, that I never get a full build), I wonder what the best practice for building a NixOps deployment is.

Please note, that I have unfree packages in my deployment. The option nixpkgs.config.allowUnfree = true; is set on the hydra server.

This is not a question about my hydra failures, but about what would be a good way to build a NixOps deployment with Hydra CI.

答:
As far as I know, there is no way to make this super easy. Your code looks ok, but my method is a slightly different. I only build the toplevel attribute and I construct the NixOS configuration differently.

I build NixOS 'installations' from inside Nix using something like:

```<code>let
  modules = [ ./configuration.nix ];
  nixosSystem = import (pkgs.path + "/nixos/lib/eval-config.nix") {
      inherit (pkgs) system;
      inherit modules;
    };
in
  nixosSystem.config.system.build.toplevel
</code>```

Body:
Deploying my NixOps machines takes alot of time, as packages need to build. I want to do the building regularly on my trusted private Hydra instance.

My current approach involves this release.nix file, but it doesn't work out so well.

{ nixpkgs ? <nixpkgs>, onlySystem ? true, extraModules ? [] }:

let

  nixos = import "${nixpkgs}/nixos";

  buildEnv = conf: (nixos {
    configuration = conf;
  });
  buildTarget = m: let build = buildEnv (buildConf m); in
    if onlySystem then build.system else build.vm;

  buildConf = module: { ... }:
    {
      imports = [ module ] ++ extraModules;
    };

in

{
  machine1 = buildTarget ./machine1/configuration.nix;
  machine2 = buildTarget ./machine2/configuration.nix
  machine3 = buildTarget ./machine3/configuration.nix
  machine4 = buildTarget ./machine4/configuration.nix
}

I don't really understand this code, as I copied it from here.

This builds fine if I run nix-build release.nix locally, but on hydra I never get a full build. Sometimes builds don't dequeue (they just don't get build), sometimes they fail with various error messages. As nothing of the hydra problems are reproducible (beside the fact, that I never get a full build), I wonder what the best practice for building a NixOps deployment is.

Please note, that I have unfree packages in my deployment. The option nixpkgs.config.allowUnfree = true; is set on the hydra server.

This is not a question about my hydra failures, but about what would be a good way to build a NixOps deployment with Hydra CI.

Body:
As far as I know, there is no way to make this super easy. Your code looks ok, but my method is a slightly different. I only build the toplevel attribute and I construct the NixOS configuration differently.

I build NixOS 'installations' from inside Nix using something like:

let
  modules = [ ./configuration.nix ];
  nixosSystem = import (pkgs.path + "/nixos/lib/eval-config.nix") {
      inherit (pkgs) system;
      inherit modules;
    };
in
  nixosSystem.config.system.build.toplevel


来源: stackexchange

问:
Can I mapDispatchToProps without mapStateToProps in Redux?
I am breaking apart Redux' todo example to try to understand it. I read that mapDispatchToProps allows you to map dispatch actions as props, so I thought of rewriting addTodo.js to use mapDispatchToProps instead of calling dispatch(addTodo()). I called it addingTodo(). Something like this:

```<code>import React from 'react';
import {connect} from 'react-redux';
import addTodo from '../actions';

let AddTodo = ({addingTodo}) => {
  let input;
  return (
      <div>
        <form onSubmit={e => {
          e.preventDefault()
          if (!input.value.trim()) {
            return
          }
          addingTodo(input.value)
          input.value = ""
        }}>
          <input ref={node => {
            input = node
          }} />
          <button type="submit">Submit</button>
        </form>
      </div>
  )
}

const mapDispatchToProps = {
  addingTodo: addTodo
}

AddTodo = connect(
  mapDispatchToProps
)(AddTodo)

export default AddTodo
</code>```

However, when I run the app, I get this error: Error: Invalid value of type object for mapStateToProps argument when connecting component AddTodo.. I never used mapStateToProps to begin with on AddTodo component, so I was not sure what was wrong. My gut feeling says that connect() expects mapStateToProps to precede mapDispatchToProps.

The working original looks like this:

```<code>import React from 'react';
import {connect} from 'react-redux';
import addTodo from '../actions';

let AddTodo = ({dispatch}) => {
  let input;
  return (
      <div>
        <form onSubmit={e => {
          e.preventDefault()
          if (!input.value.trim()) {
            return
          }
          dispatch(addTodo(input.value))
          input.value = ""
        }}>
          <input ref={node => {
            input = node
          }} />
          <button type="submit">Submit</button>
        </form>
      </div>
  )
}

AddTodo = connect()(AddTodo)

export default AddTodo
</code>```

Complete repo can be found here.

So my question is, is it possible to do mapDispatchToProps without mapStateToProps? Is what I am trying to do an acceptable practice - if not, why not?

答:
Yes, you can. Just pass null as first argument:

```<code>AddTodo = connect(
    null,
    mapDispatchToProps
)(AddTodo)
</code>```

Yes, it's not just acceptable practice, it's recommended way to trigger actions. Using mapDispatchToProps allows to hide the fact of using redux inside your react components

ContentLicense: CC BY-SA 3.0

Body:
I am breaking apart Redux' todo example to try to understand it. I read that mapDispatchToProps allows you to map dispatch actions as props, so I thought of rewriting addTodo.js to use mapDispatchToProps instead of calling dispatch(addTodo()). I called it addingTodo(). Something like this:

import React from 'react';
import {connect} from 'react-redux';
import addTodo from '../actions';

let AddTodo = ({addingTodo}) => {
  let input;
  return (

        <form onSubmit={e => {
          e.preventDefault()
          if (!input.value.trim()) {
            return
          }
          addingTodo(input.value)
          input.value = ""
        }}>
          <input ref={node => {
            input = node
          }} />
          <button type="submit">Submit</button>
        </form>

  )
}

const mapDispatchToProps = {
  addingTodo: addTodo
}

AddTodo = connect(
  mapDispatchToProps
)(AddTodo)

export default AddTodo

However, when I run the app, I get this error: Error: Invalid value of type object for mapStateToProps argument when connecting component AddTodo.. I never used mapStateToProps to begin with on AddTodo component, so I was not sure what was wrong. My gut feeling says that connect() expects mapStateToProps to precede mapDispatchToProps.

The working original looks like this:

import React from 'react';
import {connect} from 'react-redux';
import addTodo from '../actions';

let AddTodo = ({dispatch}) => {
  let input;
  return (

        <form onSubmit={e => {
          e.preventDefault()
          if (!input.value.trim()) {
            return
          }
          dispatch(addTodo(input.value))
          input.value = ""
        }}>
          <input ref={node => {
            input = node
          }} />
          <button type="submit">Submit</button>
        </form>

  )
}

AddTodo = connect()(AddTodo)

export default AddTodo

Complete repo can be found here.

So my question is, is it possible to do mapDispatchToProps without mapStateToProps? Is what I am trying to do an acceptable practice - if not, why not?

Body:
Yes, you can. Just pass null as first argument:

AddTodo = connect(
    null,
    mapDispatchToProps
)(AddTodo)

Yes, it's not just acceptable practice, it's recommended way to trigger actions. Using mapDispatchToProps allows to hide the fact of using redux inside your react components


问:
How can I convert a range to a string (VBA)?
What is the best way to convert a range of cells to a string?
I have a function that only takes a string as input so I need to convert the range to a string, while retaining as much of the formatting as possible (i.e. it needs to look like a table or list, not just a string of characters).
I've tried working with CStr(), as well as converting from a range to an array and then to a string, but I just get errors.

Edit: Code attempt

```<code>Dim email_answer As Integer
email_answer = MsgBox("Do you want to be emailled a copy of this schedule?", vbYesNo)
If email_answer = vbYes Then

    Dim wb As Workbook
    Dim to_send As Range
    to_send = Range("D3", "D10")

    If Val(Application.Version) < 14 Then Exit Sub

    Set wb = ActiveWorkbook
    With wb
        MailFromMacWithMail body content:=CStr(to_send), _
                    mailsubject:="Schedule", _
                    toaddress:="email address", _
                    ccaddress:="", _
                    bccaddress:="", _
                    attachment:=.FullName, _
                    displaymail:=False
    End With
    Set wb = Nothing
End If
</code>```

答:
I know this question is already almost a year old, but I found a quick solution that works for me:
You do have to create a reference to Microsoft Forms 2.0 Object Library to use the DataObject.</p>

```<code>Public Function GetStringFromRange(RNG As Range) As String
    Dim DOB As New MSForms.DataObject
    RNG.Copy
    DOB.GetFromClipboard
    GetStringFromRange = DOB.GetText
End Function
</code>```

Body:
What is the best way to convert a range of cells to a string?
I have a function that only takes a string as input so I need to convert the range to a string, while retaining as much of the formatting as possible (i.e. it needs to look like a table or list, not just a string of characters).
I've tried working with CStr(), as well as converting from a range to an array and then to a string, but I just get errors.

Edit: Code attempt

Dim email_answer As Integer
email_answer = MsgBox("Do you want to be emailled a copy of this schedule?", vbYesNo)
If email_answer = vbYes Then

    Dim wb As Workbook
    Dim to_send As Range
    to_send = Range("D3", "D10")

    If Val(Application.Version) < 14 Then Exit Sub

    Set wb = ActiveWorkbook
    With wb
        MailFromMacWithMail body content:=CStr(to_send), _
                    mailsubject:="Schedule", _
                    toaddress:="email address", _
                    ccaddress:="", _
                    bccaddress:="", _
                    attachment:=.FullName, _
                    displaymail:=False
    End With
    Set wb = Nothing
End If

Body:
I know this question is already almost a year old, but I found a quick solution that works for me:
You do have to create a reference to Microsoft Forms 2.0 Object Library to use the DataObject.

Public Function GetStringFromRange(RNG As Range) As String
    Dim DOB As New MSForms.DataObject
    RNG.Copy
    DOB.GetFromClipboard
    GetStringFromRange = DOB.GetText
End Function


问:
How do I run a function over and over by using parameters?
My case:

```<code>function randomLetter(){
    var random = letter[Math.floor(Math.random()*26)];
    return random;
}

function randomWord(wordLength){
    var random = randomLetter() + randomLetter() + randomLetter();
    return random;
}
</code>```

How do I write a code that run the randomLetter() function x times using parametes.

Example: I write 3 in the parameter, and the function will give me three random letters.

So instead of writing randomLetter() + randomLetter() + randomLetter(), I will just write randomWord(3), and I will get three random letters.

答:
You can use a for-loop:</p>

```<code>function randomWord(x){

    var random = [];

    for(var a = 0; a < x; a++){
        random[a] = randomLetter();
    }

    return random.join("");
}
</code>```

Body:
My case:

function randomLetter(){
    var random = letter[Math.floor(Math.random()*26)];
    return random;
}

function randomWord(wordLength){
    var random = randomLetter() + randomLetter() + randomLetter();
    return random;
}

How do I write a code that run the randomLetter() function x times using parametes.

Example: I write 3 in the parameter, and the function will give me three random letters.

So instead of writing randomLetter() + randomLetter() + randomLetter(), I will just write randomWord(3), and I will get three random letters.

Body:
You can use a for-loop:

function randomWord(x){

    var random = [];

    for(var a = 0; a < x; a++){
        random[a] = randomLetter();
    }

    return random.join("");
}


问:
Reparing inconsistency when read_repair_chance = 0
What I understand is that read_repair_chance is a probabilistic chance to trigger a ReadRepair over all the replicas. If an inconsistency is found the most recent update would serve to repair the data.

ReadRepairs are too expensive for me because most of my read CL is ONE.
So I choose read_repair_chance = 0 and dclocal_read_repair_chance = 0 too.

But sometimes I use QUORUM instead of ONE. Read QUORUM is reached when two replicas respond, but the two records can be different. Cassandra return the one with the most recent timestamp. Does it try to repair the other one ?

答:
But sometimes I use QUORUM instead of ONE. Read QUORUM is reached when
  two replicas respond, but the two records can be different. Cassandra
  return the one with the most recent timestamp. Does it try to repair
  the other one?

Assuming that my RF is 3 and write and read CL are QUORUM. What I mean
  saying that 'wanted CL is reached' is that two replicas at least
  respond, this is QUORUM. But nothing proves that the two records are
  identical. Cassandra returns the one with the most recent timestamp.
  But my question is does it try to repair the other record?

The answer is YES.

Cassandra will try to repair the other one, even though read_repair_chance = 0 and dclocal_read_repair_chance = 0.

It is called 'digest mismatch'. The only way to avoid read repair is reading at LOCAL_ONE or ONE where no digest mismatch can occur.

See  CASSANDRA-13910 CASSANDRA-11409 CASSANDRA-13863

http://thelastpickle.com/blog/2016/12/08/TWCS-part1.html


答:
```<code>temp = gsub("\\D+", "", df$ID)
data.frame(ID = unique(temp), do.call(cbind, lapply(X = c("l", "r"),
    FUN = function(f) setNames(object = data.frame(sapply(X = names(df)[-1],
        FUN = function(cx) sapply(X = unique(temp),
            FUN = function(rx) df[df$ID == paste0(rx,f),cx]))),
        nm = paste(names(df)[-1], f, sep = "_")))))
#  ID X1_l X2_l X3_l X4_l X1_r X2_r X3_r X4_r
#1  1    1    5    9   13    2    6   10   14
#2  2    4    8   12   16    3    7   11   15
</code>```

Title: reduce number of rows by cbinding data, also rename columns

Body:
I want to "partially" make the data.frame "wider"
Not really succeeding in doing so.

data looks like

 ID X1 X2 X3 X4
 1l  1  5  9 13
 1r  2  6 10 14
 2r  3  7 11 15
 2l  4  8 12 16

desired output

 ID X1_l X2_l X3_l X4_l X1_r X2_r X3_r X4_r
  1    1    5    9   13    2    6   10   14
  2    4    8   12   16    3    7   11   15

rep data

df <- data.frame(ID=c("1l","1r","2r","2l"),matrix(1:16,ncol=4))

please note:

the order of l and r are not always the same. As shown in the example. So no cheating possible here. We could do a natural sort to solve that but let's don't do it. Possibly there is a single r or l number. So for e.g., there exists 18l but NOT 18r.

My try is to first split the data up by same numbers: Like so

split(x = df,f = sub("[lr]","",df$ID))

Any fast solutions for a problem like that?

Edit

@Arkun

Error Message:

    Error: Duplicate identifiers for rows (7561, 7562), (7581, 7582), (7599, 7600), (7619, 7620), (7563, 7564), (7583, 7584), (7601, 7602), (7621, 7622), (7565, 7566), (7585, 7586), (7603, 7604), (7623, 7624), (7567, 7568), (7587, 7588), (7605, 7606), (7625, 7626), (7569, 7570), (7607, 7608), (7571, 7572), (7589, 7590), (7609, 7610), (7573, 7574), (7591, 7592), (7611, 7612), (7575, 7576), (7593, 7594), (7613, 7614), (7577, 7578), (7595, 7596), (7615, 7616), (7579, 7580), (7597, 7598), (7617, 7618), (6577, 6578), (6597, 6598), (6615, 6616), (6635, 6636), (6579, 6580), (6599, 6600), (6617, 6618), (6637, 6638), (6581, 6582), (6601, 6602), (6619, 6620), (6639, 6640), (6583, 6584), (6603, 6604), (6621, 6622), (6641, 6642), (6585, 6586), (6623, 6624), (6587, 6588), (6605, 6606), (6625, 6626), (6589, 6590), (6607, 6608), (6627, 6628), (6591, 6592), (6609, 6610), (6629, 6630), (6593, 6594), (6611, 6612), (6631, 6632), (6595, 6596), (6613, 6614), (6633, 6634), (7643, 7644), (7663, 7664), (7681, 76
In addition: Warning message:
Too many values at 66 locations: 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, ...

About the real data:

43 patients (1r,1l, ... 43r,43l)
About 112 Variables. First after ID is called v2_1_prot and last v2_80_CK

So i replaced the part of x1:x4 with v2_1_prot:v2_80_CK. Am I doing something wrong here?

I checked my ID variable there are not duplicates so far.

all_pat_rbind2$ID %>% count %>% extract2("freq") %>% max # is equal to one


问:
DB2 Select Value from final table DELETE
I haven't used the SELECT FROM FINAL TABLE clause much, but I was wondering if there was a way in DB2 to be able to select a value from a column in the same statement that I will be deleting that row.

I wasn't able to get an example working super quickly, and I was just curious if someone had a yes or no to this simple question.

Example:

```<code>SELECT COLUMN1 FROM FINAL TABLE (
    DELETE FROM [table]
     WHERE [condition]
)
</code>```

答:
FINAL TABLE is not supported for DELETE.

Check out this list for suppoted combinations:

OLD TABLE (only for UPDATE / DELETE)

NEW TABLE (only for UPDATE / INSERT)

FINAL TABLE (only for UPDATE / INSERT)

Body:
I haven't used the SELECT FROM FINAL TABLE clause much, but I was wondering if there was a way in DB2 to be able to select a value from a column in the same statement that I will be deleting that row.

I wasn't able to get an example working super quickly, and I was just curious if someone had a yes or no to this simple question.

Example:

SELECT COLUMN1 FROM FINAL TABLE (
    DELETE FROM [table]
     WHERE [condition]
)


问:
Are there any alternatives to adjustsFontSizeToFit for Android?
I am using flex in Text field to display my values/range. For IOS I am using the properties adjustsFontSizeToFit and minimumFontScale props for Text to achieve the ideal font size and scaling. I want the same scaling to be enabled for Android. Does anyone use any tricks for Android?</p>

```<code><View style={{flex: 40}}>
  {
   (Platform.OS === 'ios') ?
    <Text style={{flex: 1, paddingRight: 2}} adjustsFontSizeToFit
    minimumFontScale={0.5}>
     //if decimal value exists show range
     (pointFivePart_1 === '5') ?
        <Text style={{ flexDirection: 'row' }} >
          <Text style={styles.mainValueStyle}>{first_1}</Text>
          <Text style=styles.decimalValueStyle}> .pointFivePart_1}</Text>
          <Text style={styles.mainValueStyle}>°</Text>
         </Text>
         : <Text style={styles.mainValueStyle} >{min}°</Text>
        }
        //if two values then show the second value as range
{// render largest value if different than min
            (maxSet === minSet) ? null : (
                (pointFivePart_2 === '5') ?
                <Text style={{ flexDirection: 'row' }} >
                    <Text style={styles.mainValueStyle}> - {first_2}</Text>
                    <Text style={styles.decimalValueStyle}>.{pointFivePart_2}</Text>
                    <Text style={styles.mainValueStyle}>°</Text>
                    </Text>
                :
                    <Text style={styles.mainValueStyle} > - {maxSet}°</Text>
                    )
                }
                </Text>
                :
                //same styling for android
</code>```

答:
@aaltaf In android I generally define dimension of TextView into dimension file inside values and for font generally use default font from fontfamily

here is an example...

```<code><TextView
   android:id="@+id/shipment_text_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="@dimen/send_two_dp"
   android:gravity="center_vertical"
   android:text="@{locationViewModel.sameDayShipmentText}"
   android:textColor="@color/black"
   android:textSize="@dimen/send_fourteen_sp"
   android:fontFamily="sans-serif"
   tools:text="6-8 hour delivery" />
</code>```

Hope it will helped :)

Body:
I am using flex in Text field to display my values/range. For IOS I am using the properties adjustsFontSizeToFit and minimumFontScale props for Text to achieve the ideal font size and scaling. I want the same scaling to be enabled for Android. Does anyone use any tricks for Android?

<View style={{flex: 40}}>
  {
   (Platform.OS === 'ios') ?
    <Text style={{flex: 1, paddingRight: 2}} adjustsFontSizeToFit
    minimumFontScale={0.5}>
     //if decimal value exists show range
     (pointFivePart_1 === '5') ?
        <Text style={{ flexDirection: 'row' }} >
          <Text style={styles.mainValueStyle}>{first_1}</Text>
          <Text style=styles.decimalValueStyle}> .pointFivePart_1}</Text>
          <Text style={styles.mainValueStyle}>°</Text>
         </Text>
         : <Text style={styles.mainValueStyle} >{min}°</Text>
        }
        //if two values then show the second value as range
{// render largest value if different than min
            (maxSet === minSet) ? null : (
                (pointFivePart_2 === '5') ?
                <Text style={{ flexDirection: 'row' }} >
                    <Text style={styles.mainValueStyle}> - {first_2}</Text>
                    <Text style={styles.decimalValueStyle}>.{pointFivePart_2}</Text>
                    <Text style={styles.mainValueStyle}>°</Text>
                    </Text>
                :
                    <Text style={styles.mainValueStyle} > - {maxSet}°</Text>
                    )
                }
                </Text>
                :
                //same styling for android

Body:
@aaltaf In android I generally define dimension of TextView into dimension file inside values and for font generally use default font from fontfamily

here is an example...

<TextView
   android:id="@+id/shipment_text_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="@dimen/send_two_dp"
   android:gravity="center_vertical"
   android:text="@{locationViewModel.sameDayShipmentText}"
   android:textColor="@color/black"
   android:textSize="@dimen/send_fourteen_sp"
   android:fontFamily="sans-serif"
   tools:text="6-8 hour delivery" />

Hope it will helped :)


问:
Bash as a C lib?
I've got a project where I want to do some stuff that would be trivial in bash but where I want/need a binary with has zero external dependencies. So, has anyone written a self contained lib (i.e. not a wrapper around system()) that lets you do bash like stuff from inside C?

Off hand, the things I expect to need are: cp, rm, wget, tftp, ar, tar, guzip and maybe dpkg but I think I can side step that one.

To answer the comments: I'm looking for something along the lines of a statically linked busy-box but where I don't need a shell file as a program for it and where things I don't use automatically don't even get linked in.

答: You need busybox.</p>

ContentLicense: CC BY-SA 2.5

Title: Bash as a C lib?

Body: You need busybox.


问:
Handlebars template not working properly
I am testing out Handlebars templates in my express/node.js app. I wrote the following template & .js files but they are not working properly. The page displays the unordered list's 3 bullets, but does not contain the data. Does anyone know what might be going on? My console & terminal do not return any errors.</p>

```<code><head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" src="javascript/templating.js"></script>
</head>

<h1>Hello World</h1>
<script id="handlebars-test" type="text/x-handlebars-template">
    <ul>
    <li>{{firstName}}</li>
    <li>{{twitter}}</li>
    <li>{{jobTitle}}</li>
    </ul>
</script>
<div id="main"></div>

$(document).ready(function() {
console.log('yo!!');
var source = $("#handlebars-test").html();
var template = Handlebars.compile(source);

var data = {
    twitter: 'fasdfasdf',
    jobTitle: 'loser',
    firstName: 'bye'
}

console.log(data);
$("#main").append(template(data));
});
</code>```

答:
Hi you should call the script at the end.
This code works fine

```<code>   <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js" type="text/javascript" charset="utf-8"></script>
    </head>

    <h1>Hello World</h1>
    <script id="handlebars-test" type="text/x-handlebars-template">
        <ul>
        <li>{{firstName}}</li>
        <li>{{twitter}}</li>
        <li>{{jobTitle}}</li>
        </ul>
    </script>
    <div id="main"></div>
    <script type="text/javascript">
      $(document).ready(function() {
            var source = $("#handlebars-test").html();
            var template = Handlebars.compile(source);

            var data = {
                twitter: 'fasdfasdf',
                jobTitle: 'loser',
                firstName: 'bye'
            }
            var theCompiledHtml = template(data);

            // Add the compiled html to the page
            $('#main').html(theCompiledHtml);
        });
    </script>
</code>```

Body:
I am testing out Handlebars templates in my express/node.js app. I wrote the following template & .js files but they are not working properly. The page displays the unordered list's 3 bullets, but does not contain the data. Does anyone know what might be going on? My console & terminal do not return any errors.

Hello World

$(document).ready(function() {
console.log('yo!!');
var source = $("#handlebars-test").html();
var template = Handlebars.compile(source);

var data = {
    twitter: 'fasdfasdf',
    jobTitle: 'loser',
    firstName: 'bye'
}

console.log(data);
$("#main").append(template(data));
});

Body:
Hi you should call the script at the end.
This code works fine

   <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js" type="text/javascript" charset="utf-8"></script>
    </head>

    <h1>Hello World</h1>
    <script id="handlebars-test" type="text/x-handlebars-template">
        <ul>
        <li>{{firstName}}</li>
        <li>{{twitter}}</li>
        <li>{{jobTitle}}</li>
        </ul>
    </script>
    <div id="main"></div>
    <script type="text/javascript">
      $(document).ready(function() {
            var source = $("#handlebars-test").html();
            var template = Handlebars.compile(source);

            var data = {
                twitter: 'fasdfasdf',
                jobTitle: 'loser',
                firstName: 'bye'
            }
            var theCompiledHtml = template(data);

            // Add the compiled html to the page
            $('#main').html(theCompiledHtml);
        });
    </script>


问:
How to Get all uppercase characters from cell in excel?
I want all capital letters ..
JUST LIKE,
Casey Richard Omar W= CROW ,...

Processing of Dimensional Stone = PDS

like all capital letters or shortname

答:
It seems that this question is more about how to create a short name, with the initials of the names.

If that is the case then try this formula:

```<code>    = CONCATENATE( LEFT( $A1 ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 1 ) ), 1 ), "" ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 2 ) ), 1 ), "" ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 3 ) ), 1 ), "" ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 4 ) ), 1 ), "" ) )
</code>```

If the name has more than four words then you can just add more lines, like:

```<code>    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", # ) ), 1 ), "" ),
</code>```

were # represents the word number

If any of the words contain the character ‡, just changed it to any other uncommon character.

Body:
It seems that this question is more about how to create a short name, with the initials of the names.

If that is the case then try this formula:

    = CONCATENATE( LEFT( $A1 ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 1 ) ), 1 ), "" ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 2 ) ), 1 ), "" ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 3 ) ), 1 ), "" ),
    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", 4 ) ), 1 ), "" ) )

If the name has more than four words then you can just add more lines, like:

    IFERROR( MID( $A1, 1 + SEARCH( "‡", SUBSTITUTE( $A1, " ", "‡", # ) ), 1 ), "" ),

were # represents the word number

If any of the words contain the character ‡, just changed it to any other uncommon character.


问:
Nested resource: controller spec doesn't call the wanted action
I have a ReportsController, nested in ProjectsController, with a #show method:

```<code>def show
  # Some stuff

  do_something(@report)
end
</code>```

Routes:

```<code>resources :projects do
  resources :reports
end
</code>```

I need to test that the do_something method is called:

```<code>  it 'calls do_something' do
    expect(controller).to receive(:do_something)

    project = create :project
    report = create :report, project: project

    get :show, params: {project_id: project.id, id: report.id}
  end
</code>```

I placed binding.pry within the #show action, but this doesn't get called. So what's wrong with my spec?

答:
The problem was that I wasn't logged in:</p>

```<code>  before do
    @user = create :user, :admin
    sign_in_as @user
  end
</code>```

Body:
I have a ReportsController, nested in ProjectsController, with a #show method:

def show
  # Some stuff

  do_something(@report)
end

Routes:

resources :projects do
  resources :reports
end

I need to test that the do_something method is called:

  it 'calls do_something' do
    expect(controller).to receive(:do_something)

    project = create :project
    report = create :report, project: project

    get :show, params: {project_id: project.id, id: report.id}
  end

I placed binding.pry within the #show action, but this doesn't get called. So what's wrong with my spec?

Body:
The problem was that I wasn't logged in:

  before do
    @user = create :user, :admin
    sign_in_as @user
  end


问:
Connect to local PostgreSQL server on Linux
How can I connect to a local PostgreSQL database server on Ubuntu Linux from a .NET Core application with Npgsql?

I'm using this connection string on Windows:

Server=localhost;User ID=webdev;Password=webdev;Database=dbname

I'm using this shell command on Linux:

psql dbname

Now I've tried with this connection string on Linux:

Server=/var/run/postgresql;Database=dbname

But I got this error:

Cannot assign requested address /var/run/postgresql/.s.PGSQL.5432

If I try this connection string on Linux:

Server=localhost;Database=dbname

Then I get this error:

Connection refused

How does this work? I'd like to take advantage of password-less login from the same local system account.

答:
I haven't changed the port on which PostgreSQL listens. And I wouldn't have thought that the TCP port has anything to do with the local UNIX socket connection. But in Postgres it does, and the package maintainers at Postgres for their official Ubuntu package have changed the port in their config from 5432 to 5433. I have no idea why, but I've corrected that in /etc/postgresql/10/main/postgresql.conf and restarted the server:

```<code>port = 5432
</code>```

Now I can connect to the server with the intended connection string. And with psql and with psql -h /var/run/postgresql as mentioned in the comments.

This seems to be a bug in the package configuration. Easy to fix, hard to find.

Body:
I haven't changed the port on which PostgreSQL listens. And I wouldn't have thought that the TCP port has anything to do with the local UNIX socket connection. But in Postgres it does, and the package maintainers at Postgres for their official Ubuntu package have changed the port in their config from 5432 to 5433. I have no idea why, but I've corrected that in /etc/postgresql/10/main/postgresql.conf and restarted the server:

port = 5432

Now I can connect to the server with the intended connection string. And with psql and with psql -h /var/run/postgresql as mentioned in the comments.

This seems to be a bug in the package configuration. Easy to fix, hard to find.


问:
Use log4j2 for multiple classes
I found many link that helped me building the logger. Some here in SO and others in other pages.

This answer here: https://stackoverflow.com/questions/7624895/how-to-use-log4j-with-multiple-classes#= is the best that I have found.
It is already some years old thought and some things now are different.

My goal is to have one single logger shared among all of the java classes that print messages to the log, both console and file.

I am using LOG4J2: http://logging.apache.org/log4j/2.x/manual/configuration.html

main():

```<code>import org.apache.logging.log4j.Logger;

public class App {
    private static final Logger LOGGER = Logger.getLogger("GLOBAL");
    public static void main(){
        ...calling other classes
  }
}
</code>```

anyOtherClass:

```<code>import org.apache.logging.log4j.Logger;
public class secondClass {
    private final Logger LOGGER = Logger.getLogger("GLOBAL");
    public void writeLog(){
      LOGGER.log(Level.INFO, "A simple string");
  }
}
</code>```

log4j.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Properties>
        <Property name="basePath">/var/log</Property>
    </Properties>

    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/myApp.log" filePattern="${basePath}/myApp-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

       <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="java.util.logging.Logger" level="ALL" additivity="true">
            <appender-ref ref="fileLogger" level="ALL" />
        </Logger>
        <Root level="ALL" additivity="false">
            <appender-ref ref="console" />
        </Root>
    </Loggers>
</Configuration>
</code>```

I (more or less) know that I should use LogManager, truth is I should call it as:

```<code>private static final Logger logger = LogManager.getLogger(MyApp.class);
</code>```

or, in the main(), probably like this:

```<code>private static Logger LOGGER = null;

@BeforeClass
public static void setLogger() {
    System.setProperty("log4j.configurationFile","log4j.xml");
    LOGGER = LogManager.getLogger();
}
</code>```

Because, I believe, using LogManager I can point the Log to the xml file for its settings.
But when I build it and run it, the CLI rage quits at the first ever LOG, reporting: Exception in thread "main" java.lang.NullPointerException at myapp.modules.Database.<init>(Database.java:67)

Expected Result:
All I want to do is being able to have the log on all of my classes and that this is written to a file.
I just can't get this working. And when I do not use LogManager, I only see the logs on console but no file is created.
I'm using both Windows and Linux (that's why /var/log/ but I change it to C:\ too).

Other website I used:
https://howtodoinjava.com/log4j2/configure-log4j2-for-junit/

Log4J loggers for different classes <-- did not help me

..And many other search results are more than 6 years old.

POM.xml:

```<code><dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.10.0</version>
</dependency>
</code>```

答:
You're wrong on several levels: you're mixing JDK's logger with Log4j2's Logger, you're not logging to several appenders, etc.

Here's what you should do:

/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>log4j2test</artifactId>
    <version>0.1</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
    </dependencies>
</project>
```

<p>This is basically the only place where you have no error.</p>

<h3><code>/src/main/java/so47656300/App.java</code></h3>

```package so47656300;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class App {

  private static final Logger logger = LogManager.getLogger(App.class);

  public static void main(String[] args) {
    logger.info("App.main - starting");
    new SecondClass();
    logger.info("App.main - ending");
  }
}
```

<p>Here, your error was to use <code>java.util.logger.Logger</code> instead of <code>org.apache.logging.log4j.Logger</code>.</p>

<h3><code>/src/main/java/so47656300/SecondClass.java</code></h3>

```package so47656300;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SecondClass {

  private static final Logger logger = LogManager.getLogger(SecondClass.class);

  public SecondClass() {
    logger.info("SecondClass - starting");
    logger.info("SecondClass - ending");
  }
}
```

<p>Here, your error was also to use the wrong <code>Logger</code> class. Use only classes from <code>org.apache.logging.log4j.*</code>.</p>

<h3><code>/src/main/resources/log4j2.xml</code></h3>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="basePath">/var/log</Property>
    </Properties>
    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/myApp.log" filePattern="${basePath}/myApp-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="console"/>
            <AppenderRef ref="fileLogger"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

Here, your errors are the following:

Wrong file name: Log4J 2 requires a name log4j2.xml. For your tests, create a file /src/test/resources/log4j2-test.xml.

You want only one logger, so use only one: the root one. You created several, but you don't need them.

Add appenders to the logger (the Root-one)

Output

Console

```<code>[INFO ] 2017-12-05 16:52:32.218 [main] App - App.main - starting
[INFO ] 2017-12-05 16:52:32.221 [main] SecondClass - SecondClass - starting
[INFO ] 2017-12-05 16:52:32.222 [main] SecondClass - SecondClass - ending
[INFO ] 2017-12-05 16:52:32.222 [main] App - App.main - ending
</code>```

/var/log/myApp.log

```<code>[INFO ] 2017-12-05 16:52:32.218 [main] App - App.main - starting
[INFO ] 2017-12-05 16:52:32.221 [main] SecondClass - SecondClass - starting
[INFO ] 2017-12-05 16:52:32.222 [main] SecondClass - SecondClass - ending
[INFO ] 2017-12-05 16:52:32.222 [main] App - App.main - ending
</code>```

Title: Use log4j2 for multiple classes

Body:
I found many link that helped me building the logger. Some here in SO and others in other pages.

This answer here: https://stackoverflow.com/questions/7624895/how-to-use-log4j-with-multiple-classes#= is the best that I have found.
It is already some years old thought and some things now are different.

My goal is to have one single logger shared among all of the java classes that print messages to the log, both console and file.

I am using LOG4J2: http://logging.apache.org/log4j/2.x/manual/configuration.html

main():

import org.apache.logging.log4j.Logger;

public class App {
    private static final Logger LOGGER = Logger.getLogger("GLOBAL");
    public static void main(){
        ...calling other classes
  }
}

anyOtherClass:

import org.apache.logging.log4j.Logger;
public class secondClass {
    private final Logger LOGGER = Logger.getLogger("GLOBAL");
    public void writeLog(){
      LOGGER.log(Level.INFO, "A simple string");
  }
}

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Properties>
        <Property name="basePath">/var/log</Property>
    </Properties>

    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/myApp.log" filePattern="${basePath}/myApp-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

       <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="java.util.logging.Logger" level="ALL" additivity="true">
            <appender-ref ref="fileLogger" level="ALL" />
        </Logger>
        <Root level="ALL" additivity="false">
            <appender-ref ref="console" />
        </Root>
    </Loggers>
</Configuration>

I (more or less) know that I should use LogManager, truth is I should call it as:

private static final Logger logger = LogManager.getLogger(MyApp.class);

or, in the main(), probably like this:

private static Logger LOGGER = null;

@BeforeClass
public static void setLogger() {
    System.setProperty("log4j.configurationFile","log4j.xml");
    LOGGER = LogManager.getLogger();
}

Because, I believe, using LogManager I can point the Log to the xml file for its settings.
But when I build it and run it, the CLI rage quits at the first ever LOG, reporting: Exception in thread "main" java.lang.NullPointerException at myapp.modules.Database.<init>(Database.java:67)

Expected Result:
All I want to do is being able to have the log on all of my classes and that this is written to a file.
I just can't get this working. And when I do not use LogManager, I only see the logs on console but no file is created.
I'm using both Windows and Linux (that's why /var/log/ but I change it to C:\ too).

Other website I used:
https://howtodoinjava.com/log4j2/configure-log4j2-for-junit/

Log4J loggers for different classes <-- did not help me

..And many other search results are more than 6 years old.

POM.xml:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.10.0</version>
</dependency>

Body:
You're wrong on several levels: you're mixing JDK's logger with Log4j2's Logger, you're not logging to several appenders, etc.

Here's what you should do:

/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>log4j2test</artifactId>
    <version>0.1</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
    </dependencies>
</project>

This is basically the only place where you have no error.

/src/main/java/so47656300/App.java

package so47656300;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class App {

  private static final Logger logger = LogManager.getLogger(App.class);

  public static void main(String[] args) {
    logger.info("App.main - starting");
    new SecondClass();
    logger.info("App.main - ending");
  }
}

Here, your error was to use java.util.logger.Logger instead of org.apache.logging.log4j.Logger.

/src/main/java/so47656300/SecondClass.java

package so47656300;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SecondClass {

  private static final Logger logger = LogManager.getLogger(SecondClass.class);

  public SecondClass() {
    logger.info("SecondClass - starting");
    logger.info("SecondClass - ending");
  }
}

Here, your error was also to use the wrong Logger class. Use only classes from org.apache.logging.log4j.*.

/src/main/resources/log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="basePath">/var/log</Property>
    </Properties>
    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/myApp.log" filePattern="${basePath}/myApp-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="console"/>
            <AppenderRef ref="fileLogger"/>
        </Root>
    </Loggers>
</Configuration>

Here, your errors are the following:

Wrong file name: Log4J 2 requires a name log4j2.xml. For your tests, create a file /src/test/resources/log4j2-test.xml.

You want only one logger, so use only one: the root one. You created several, but you don't need them.

Add appenders to the logger (the Root-one)

Output

Console

[INFO ] 2017-12-05 16:52:32.218 [main] App - App.main - starting
[INFO ] 2017-12-05 16:52:32.221 [main] SecondClass - SecondClass - starting
[INFO ] 2017-12-05 16:52:32.222 [main] SecondClass - SecondClass - ending
[INFO ] 2017-12-05 16:52:32.222 [main] App - App.main - ending

/var/log/myApp.log

[INFO ] 2017-12-05 16:52:32.218 [main] App - App.main - starting
[INFO ] 2017-12-05 16:52:32.221 [main] SecondClass - SecondClass - starting
[INFO ] 2017-12-05 16:52:32.222 [main] SecondClass - SecondClass - ending
[INFO ] 2017-12-05 16:52:32.222 [main] App - App.main - ending


问:
Why is garbage collector allowed to collect seemingly referenced objects with a finalizer?
This question is basically why we need GC.KeepAlive() in the first place.

Here's where we need it. We have a wrapper for some unmanaged resource

```<code>public class CoolWrapper
{
     public CoolWrapper()
     {
         coolResourceHandle = UnmanagedWinApiCode.CreateCoolResource();
         if (coolResourceHandle == IntPtr.Zero)
         {
             // something went wrong, throw exception
         }
     }

     ~CoolWrapper()
     {
         UnmanagedWinApiCode.DestroyCoolResource(coolResource);
     }

     public void DoSomething()
     {
         var result = UnmanagedWinApiCode.DoSomething(coolResource);
         if (result == 0)
         {
             // something went wrong, throw exception
         }
     }

     private IntPtr coolResourceHandle;
}
</code>```

and our code uses that wrapper:

```<code>var wrapper = CoolWrapper();
wrapper.DoSomething();
</code>```

and if this code is run in Release configuration and not under debugger then it may so happen that code optimizer sees that the reference is not actually used after this code and also that coolResourceHandle member variable is not accessed (by managed code) after it was read inside DoSomething() and its value was passed into unmanaged code and so the following happens:

DoSomething() is called

coolResourceHandle is read

garbage collection suddenly starts

~CoolWrapper() runs

UnmanagedWinApiCode.DestroyCoolResource() runs and the resource is destroyed, the resource handle is invalidated

UnmanagedWinApiCode.DoSomething() runs using the value which now refers to a non-existing object (or maybe another object is created and assigned that handle)

The situation described above is actually possible and it's a race between a method of the object and a running garbage collection. No matter there's a local variable of reference type on stack - optimized code ignores that reference and the object becomes eligible for garbage collection immediately after coolResourceHandle was read inside DoSomething().

So, to prevent this we use GC.KeepAlive():

```<code>var wrapper = CoolWrapper();
wrapper.DoSomething();
GC.KeepAlive(wrapper);
</code>```

which makes the object non-eligible for GC until GC.KeepAlive() is invoked.

This of course requires that all users use GC.KeepAlive() everywhere which they will forget, so the right place is CoolWrapper.DoSomething():

```<code> public void DoSomething()
 {
     var result = UnmanagedWinApiCode.DoSomething(coolResource);
     GC.KeepAlive(this);
     if (result == 0)
     {
         // something went wrong, throw exception
     }
 }
</code>```

and this basically prevents the objects from getting eligible for GC while there's a method of this object running.

Why is this needed? Why wouldn't GC ignore the objects which have a method running at that moment and also have a finalizer? This would make life much easier yet we need to use GC.KeepAlive() instead.

Why is such aggressive collection allowed instead of ignoring objects which have methods currently running and a finalizer (and so likely to have problems in case there's a race as described above)?

答:
Finalizers don't "collect" anything.  Instead, they prevent objects from being collected and notify objects that they would have been collected but for the existence of an active finalizers.  Note that if object X holds a reference to Y, Y will be uncollectable if either X or Y has an active finalizer.  Y's finalizer (if it exists) will have no way of knowing whether it's the only thing keeping Y alive, or whether other finalizers may exist that would also keep Y alive.

A fundamental principle is that objects exist as long as any reference to them exists anywhere; as soon as the last reference to an object ceases to exist, the object will as well.  The GC does not destroy objects; instead, it reclaims memory that was formerly used by objects that have ceased to exist.  If an object has an active finalizer, a reference to it will be kept in a special list of objects that have active finalizer; as long as that reference exists, the object will do so as well.  When a GC is performed, the system marks all the objects that would exist even in the absence of that list, and once that's done it produces a queue of objects that are on that list but haven't been marked.  After that, it will start calling finalizers of objects on that queue.

Body:
This question is basically why we need GC.KeepAlive() in the first place.

Here's where we need it. We have a wrapper for some unmanaged resource

public class CoolWrapper
{
     public CoolWrapper()
     {
         coolResourceHandle = UnmanagedWinApiCode.CreateCoolResource();
         if (coolResourceHandle == IntPtr.Zero)
         {
             // something went wrong, throw exception
         }
     }

     ~CoolWrapper()
     {
         UnmanagedWinApiCode.DestroyCoolResource(coolResource);
     }

     public void DoSomething()
     {
         var result = UnmanagedWinApiCode.DoSomething(coolResource);
         if (result == 0)
         {
             // something went wrong, throw exception
         }
     }

     private IntPtr coolResourceHandle;
}

and our code uses that wrapper:

var wrapper = CoolWrapper();
wrapper.DoSomething();

and if this code is run in Release configuration and not under debugger then it may so happen that code optimizer sees that the reference is not actually used after this code and also that coolResourceHandle member variable is not accessed (by managed code) after it was read inside DoSomething() and its value was passed into unmanaged code and so the following happens:

DoSomething() is called

coolResourceHandle is read

garbage collection suddenly starts

~CoolWrapper() runs

UnmanagedWinApiCode.DestroyCoolResource() runs and the resource is destroyed, the resource handle is invalidated

UnmanagedWinApiCode.DoSomething() runs using the value which now refers to a non-existing object (or maybe another object is created and assigned that handle)

The situation described above is actually possible and it's a race between a method of the object and a running garbage collection. No matter there's a local variable of reference type on stack - optimized code ignores that reference and the object becomes eligible for garbage collection immediately after coolResourceHandle was read inside DoSomething().

So, to prevent this we use GC.KeepAlive():

var wrapper = CoolWrapper();
wrapper.DoSomething();
GC.KeepAlive(wrapper);

which makes the object non-eligible for GC until GC.KeepAlive() is invoked.

This of course requires that all users use GC.KeepAlive() everywhere which they will forget, so the right place is CoolWrapper.DoSomething():

 public void DoSomething()
 {
     var result = UnmanagedWinApiCode.DoSomething(coolResource);
     GC.KeepAlive(this);
     if (result == 0)
     {
         // something went wrong, throw exception
     }
 }

and this basically prevents the objects from getting eligible for GC while there's a method of this object running.

Why is this needed? Why wouldn't GC ignore the objects which have a method running at that moment and also have a finalizer? This would make life much easier yet we need to use GC.KeepAlive() instead.

Why is such aggressive collection allowed instead of ignoring objects which have methods currently running and a finalizer (and so likely to have problems in case there's a race as described above)?


问:
Android Emulator won't run application started from eclipse
I have followed the "Hello World" example from Google's Android developer's guide. When I try to run the application in the SDK emulator, nothing happens. The emulator startd up nicely, but after that nothing happens. I can't even see the application in the app tray.

I am using Eclipse with the Android add-on installed.

答:
Had the same problem, the console log stalled after:

Launching a new emulator with Virtual Device

and the emulator never showed the HelloAndroid application. I finally figured it out!
In Eclipse go to

Run --> Run Configurations

Then change the Launch Action for your application (e.g. HelloAndroid) from "Launch Default Activity" to "Launch:" and then select your application from the pull-down menu. This did the trick for me.

HTH,
   Sven


问:
Detect if default back button in navigation bar is pressed
I know that there are answers to this like make custom button and then make action but I don't want to change the default back button with arrow and I also tried like this:

```<code>override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}
</code>```

Here the problem is that this function gets called even if I press on save button that I also have in that view controller. I need to detect only when the back button is pressed

答:
If the answer provided by Xcoder does not do what you want check this one

https://stackoverflow.com/a/37230710/1152683

It consists in creating an custom button, but with the arrow.  Check the answer for the whole code

The usage is pretty simple

```<code>weak var weakSelf = self

// Assign back button with back arrow and text (exactly like default back button)
navigationItem.leftBarButtonItems = CustomBackButton.createWithText("YourBackButtonTitle", color: UIColor.yourColor(), target: weakSelf, action: #selector(YourViewController.tappedBackButton))

// Assign back button with back arrow and image
navigationItem.leftBarButtonItems = CustomBackButton.createWithImage(UIImage(named: "yourImageName")!, color: UIColor.yourColor(), target: weakSelf, action: #selector(YourViewController.tappedBackButton))

func tappedBackButton() {

    // Do your thing

}
</code>```

EDIT:

Keeping the original button

Knowing that, for you this isn't working

```<code>override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}
</code>```

I can only assume that when tapping the save button you're navigating to the previous screen there for you must add a flag inside that function and then add a condition to that function like so

```<code>override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController && !save {
       // back pressed
    }
}
</code>```

being the save variable a Bool that becomes true when the save button is tapped

Body:
I know that there are answers to this like make custom button and then make action but I don't want to change the default back button with arrow and I also tried like this:

override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}

Here the problem is that this function gets called even if I press on save button that I also have in that view controller. I need to detect only when the back button is pressed

Body:
If the answer provided by Xcoder does not do what you want check this one

https://stackoverflow.com/a/37230710/1152683

It consists in creating an custom button, but with the arrow.  Check the answer for the whole code

The usage is pretty simple

weak var weakSelf = self

// Assign back button with back arrow and text (exactly like default back button)
navigationItem.leftBarButtonItems = CustomBackButton.createWithText("YourBackButtonTitle", color: UIColor.yourColor(), target: weakSelf, action: #selector(YourViewController.tappedBackButton))

// Assign back button with back arrow and image
navigationItem.leftBarButtonItems = CustomBackButton.createWithImage(UIImage(named: "yourImageName")!, color: UIColor.yourColor(), target: weakSelf, action: #selector(YourViewController.tappedBackButton))

func tappedBackButton() {

    // Do your thing

}

EDIT:

Keeping the original button

Knowing that, for you this isn't working

override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
     print("something")
    }
}

I can only assume that when tapping the save button you're navigating to the previous screen there for you must add a flag inside that function and then add a condition to that function like so

override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController && !save {
       // back pressed
    }
}

being the save variable a Bool that becomes true when the save button is tapped


问:
Hibernate with Kotlin: @ManyToOne(fetch = FetchType.LAZY)
I am using Hibernate with Kotlin and I am having an issue with FetchType.LAZY on @ManyToOne relations. Consider following:

```<code>@ManyToOne(fetch = FetchType.LAZY)
open var event: Event?
</code>```

The problem is that when FetchType.LAZY is used, the fetched Event will be of class Event_$$_jvst_... with JavaassistLazyInitializer on it. But the event will never be initialized, everything will be null or empty.

Once the FetchType.LAZY is removed, everything works correctly.

This didn't happen in Java.

I tried to add open on the var so that the Event can be correctly proxied. No effect.

All the @Entity classes are of course open as well. If the open keyword is removed, there will be no proxy created and so no laziness.

My guess is that Hibernate cannot easily proxy these default kotlin getters. Is there a way to solve it?

答:
I write a simple example to check your problem, and all works fine.

```<code>import org.hibernate.CacheMode
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.hibernate.Transaction
import org.hibernate.boot.MetadataSources
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
import org.hibernate.cfg.Environment
import java.util.*
import javax.persistence.*

fun main(args: Array<String>) {
    val standardServiceRegistryBuilder = StandardServiceRegistryBuilder()

    val settings = HashMap<String, String>().apply {
        put(Environment.DRIVER, "org.h2.Driver")
        put(Environment.URL, "jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1")
        put(Environment.USER, "sa")
        put(Environment.PASS, "sa")
        put(Environment.DIALECT, "org.hibernate.dialect.H2Dialect")
        put(Environment.SHOW_SQL, "true")
        put(Environment.HBM2DDL_AUTO, "create")
    }

    val sessionFactory = standardServiceRegistryBuilder.applySettings(settings)
            .build()
            .let {
                MetadataSources(it).apply {
                    addAnnotatedClass(History::class.java)
                    addAnnotatedClass(Event::class.java)
                }
            }
            .run { metadataBuilder.build() }
            .run { sessionFactoryBuilder.build() }

    sessionFactory.inSession {
        inTransaction { session ->
            session.save(Event(1, "event description"))

            session.save(History(1, Event(1), "history description"))
        }
    }

    sessionFactory.inSession {
        inTransaction { session ->
            val entity = session.get(Event::class.java, 1L)

            println("=============1=============")
            println(entity)
        }
    }

    sessionFactory.inSession {
        inTransaction { session ->
            val entity = session.load(History::class.java, 1L)

            println("=============2=============")
            println(entity)
        }
    }
}

private fun SessionFactory.inSession(function: Session.() -> Unit) {
    val session = this.openSession()

    session.function()

    session.close()
}

private fun Session.inTransaction(function: Transaction.(s: Session) -> Unit) {
    val transaction = this.beginTransaction()

    transaction.function(this)

    transaction.commit()
}

@Entity
open class History(
        @Id
        open var id: Long? = null,

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "eventId")
        open var event: Event? = null,

        open var description: String = ""
) {
    override fun toString(): String {
        return "History(id=$id, event=$event, description='$description')"
    }
}

@Entity
open class Event(
        @Id
        open var id: Long? = null,
        open var description: String? = null,

        @OneToMany(fetch = FetchType.LAZY, mappedBy = "event")
        open var history: MutableSet<History>? = null
) {
    override fun toString(): String {
        return "Event(id=$id, description='$description', history=${history?.size})"
    }
}
</code>```

Logs looks like this:

```<code>2017-12-05 18:43:03 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.2.12.Final}
2017-12-05 18:43:03 [main] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
2017-12-05 18:43:03 [main] INFO  o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-12-05 18:43:04 [main] WARN  o.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2017-12-05 18:43:04 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1]
2017-12-05 18:43:04 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {password=****, user=sa}
2017-12-05 18:43:04 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false
2017-12-05 18:43:04 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
2017-12-05 18:43:04 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-12-05 18:43:04 [main] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.5.Final
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by javassist.util.proxy.SecurityActions (file:/Users/evgenyzaharov/.gradle/caches/modules-2/files-2.1/org.javassist/javassist/3.20.0-GA/a9cbcdfb7e9f86fbc74d3afae65f2248bfbf82a0/javassist-3.20.0-GA.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of javassist.util.proxy.SecurityActions
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Hibernate: drop table Event if exists
2017-12-05 18:43:04 [main] INFO  org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@56913163] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table History if exists
Hibernate: create table Event (id bigint not null, description varchar(255), primary key (id))
2017-12-05 18:43:04 [main] INFO  org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@e8e0dec] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table History (id bigint not null, description varchar(255), eventId bigint, primary key (id))
Hibernate: alter table History add constraint FK2yaqfgh2x1lsxcpbuifmd245k foreign key (eventId) references Event
2017-12-05 18:43:04 [main] INFO  o.h.t.s.internal.SchemaCreatorImpl - HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@6c15e8c7'
Hibernate: select event_.id, event_.description as descript2_0_ from Event event_ where event_.id=?
Hibernate: insert into Event (description, id) values (?, ?)
Hibernate: insert into History (description, eventId, id) values (?, ?, ?)
Hibernate: update History set description=?, eventId=? where id=?
Hibernate: select event0_.id as id1_0_0_, event0_.description as descript2_0_0_ from Event event0_ where event0_.id=?
=============1=============
Hibernate: select history0_.eventId as eventId3_1_0_, history0_.id as id1_1_0_, history0_.id as id1_1_1_, history0_.description as descript2_1_1_, history0_.eventId as eventId3_1_1_ from History history0_ where history0_.eventId=?
Event(id=1, description='event description', history=1)
=============2=============
Hibernate: select history0_.id as id1_1_0_, history0_.description as descript2_1_0_, history0_.eventId as eventId3_1_0_ from History history0_ where history0_.id=?
Hibernate: select event0_.id as id1_0_0_, event0_.description as descript2_0_0_ from Event event0_ where event0_.id=?
Hibernate: select history0_.eventId as eventId3_1_0_, history0_.id as id1_1_0_, history0_.id as id1_1_1_, history0_.description as descript2_1_1_, history0_.eventId as eventId3_1_1_ from History history0_ where history0_.eventId=?
History(id=1, event=Event(id=1, description='event description', history=1), description='history description')
</code>```

Lazy initialisation start to load field data only after explicit getting a value.

Hope this will help you.

Body:
I am using Hibernate with Kotlin and I am having an issue with FetchType.LAZY on @ManyToOne relations. Consider following:

@ManyToOne(fetch = FetchType.LAZY)
open var event: Event?

The problem is that when FetchType.LAZY is used, the fetched Event will be of class Event_$$_jvst_... with JavaassistLazyInitializer on it. But the event will never be initialized, everything will be null or empty.

Once the FetchType.LAZY is removed, everything works correctly.

This didn't happen in Java.

I tried to add open on the var so that the Event can be correctly proxied. No effect.

All the @Entity classes are of course open as well. If the open keyword is removed, there will be no proxy created and so no laziness.

My guess is that Hibernate cannot easily proxy these default kotlin getters. Is there a way to solve it?

Body:
I write a simple example to check your problem, and all works fine.

import org.hibernate.CacheMode
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.hibernate.Transaction
import org.hibernate.boot.MetadataSources
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
import org.hibernate.cfg.Environment
import java.util.*
import javax.persistence.*

fun main(args: Array<String>) {
    val standardServiceRegistryBuilder = StandardServiceRegistryBuilder()

    val settings = HashMap<String, String>().apply {
        put(Environment.DRIVER, "org.h2.Driver")
        put(Environment.URL, "jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1")
        put(Environment.USER, "sa")
        put(Environment.PASS, "sa")
        put(Environment.DIALECT, "org.hibernate.dialect.H2Dialect")
        put(Environment.SHOW_SQL, "true")
        put(Environment.HBM2DDL_AUTO, "create")
    }

    val sessionFactory = standardServiceRegistryBuilder.applySettings(settings)
            .build()
            .let {
                MetadataSources(it).apply {
                    addAnnotatedClass(History::class.java)
                    addAnnotatedClass(Event::class.java)
                }
            }
            .run { metadataBuilder.build() }
            .run { sessionFactoryBuilder.build() }

    sessionFactory.inSession {
        inTransaction { session ->
            session.save(Event(1, "event description"))

            session.save(History(1, Event(1), "history description"))
        }
    }

    sessionFactory.inSession {
        inTransaction { session ->
            val entity = session.get(Event::class.java, 1L)

            println("=============1=============")
            println(entity)
        }
    }

    sessionFactory.inSession {
        inTransaction { session ->
            val entity = session.load(History::class.java, 1L)

            println("=============2=============")
            println(entity)
        }
    }
}

private fun SessionFactory.inSession(function: Session.() -> Unit) {
    val session = this.openSession()

    session.function()

    session.close()
}

private fun Session.inTransaction(function: Transaction.(s: Session) -> Unit) {
    val transaction = this.beginTransaction()

    transaction.function(this)

    transaction.commit()
}

@Entity
open class History(
        @Id
        open var id: Long? = null,

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "eventId")
        open var event: Event? = null,

        open var description: String = ""
) {
    override fun toString(): String {
        return "History(id=$id, event=$event, description='$description')"
    }
}

@Entity
open class Event(
        @Id
        open var id: Long? = null,
        open var description: String? = null,

        @OneToMany(fetch = FetchType.LAZY, mappedBy = "event")
        open var history: MutableSet<History>? = null
) {
    override fun toString(): String {
        return "Event(id=$id, description='$description', history=${history?.size})"
    }
}

Logs looks like this:

2017-12-05 18:43:03 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.2.12.Final}
2017-12-05 18:43:03 [main] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
2017-12-05 18:43:03 [main] INFO  o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-12-05 18:43:04 [main] WARN  o.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2017-12-05 18:43:04 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1]
2017-12-05 18:43:04 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {password=****, user=sa}
2017-12-05 18:43:04 [main] INFO  o.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false
2017-12-05 18:43:04 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
2017-12-05 18:43:04 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-12-05 18:43:04 [main] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.5.Final
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by javassist.util.proxy.SecurityActions (file:/Users/evgenyzaharov/.gradle/caches/modules-2/files-2.1/org.javassist/javassist/3.20.0-GA/a9cbcdfb7e9f86fbc74d3afae65f2248bfbf82a0/javassist-3.20.0-GA.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of javassist.util.proxy.SecurityActions
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Hibernate: drop table Event if exists
2017-12-05 18:43:04 [main] INFO  org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@56913163] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table History if exists
Hibernate: create table Event (id bigint not null, description varchar(255), primary key (id))
2017-12-05 18:43:04 [main] INFO  org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@e8e0dec] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table History (id bigint not null, description varchar(255), eventId bigint, primary key (id))
Hibernate: alter table History add constraint FK2yaqfgh2x1lsxcpbuifmd245k foreign key (eventId) references Event
2017-12-05 18:43:04 [main] INFO  o.h.t.s.internal.SchemaCreatorImpl - HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@6c15e8c7'
Hibernate: select event_.id, event_.description as descript2_0_ from Event event_ where event_.id=?
Hibernate: insert into Event (description, id) values (?, ?)
Hibernate: insert into History (description, eventId, id) values (?, ?, ?)
Hibernate: update History set description=?, eventId=? where id=?
Hibernate: select event0_.id as id1_0_0_, event0_.description as descript2_0_0_ from Event event0_ where event0_.id=?
=============1=============
Hibernate: select history0_.eventId as eventId3_1_0_, history0_.id as id1_1_0_, history0_.id as id1_1_1_, history0_.description as descript2_1_1_, history0_.eventId as eventId3_1_1_ from History history0_ where history0_.eventId=?
Event(id=1, description='event description', history=1)
=============2=============
Hibernate: select history0_.id as id1_1_0_, history0_.description as descript2_1_0_, history0_.eventId as eventId3_1_0_ from History history0_ where history0_.id=?
Hibernate: select event0_.id as id1_0_0_, event0_.description as descript2_0_0_ from Event event0_ where event0_.id=?
Hibernate: select history0_.eventId as eventId3_1_0_, history0_.id as id1_1_0_, history0_.id as id1_1_1_, history0_.description as descript2_1_1_, history0_.eventId as eventId3_1_1_ from History history0_ where history0_.eventId=?
History(id=1, event=Event(id=1, description='event description', history=1), description='history description')

Lazy initialisation start to load field data only after explicit getting a value.

Hope this will help you.


问:
Java can't decrypt string encrypted in PHP
Hello everyone i have string encrypted in PHP by openssl_encrypt with algorithm 'aes-256-cbc'

Key: C4E30455853D4949A8E91B2C366BE9DE

Vector: 5686044872102713

Encrypted string: ak9YSTd6RXU5TENocUxQUGxieVhpZ3VqSlFiQUdndGZrbVJvbEliTGZjZz0=

And here is my Java function for decrypt:

```<code>public static String Decrypt_AES_FromBase64(String AEncryptedText, String AKey32Bytes, String AVectorNum16Bytes) {
        try {
            byte[] vEncryptedBytes = Base64.getDecoder().decode(AEncryptedText);

            Key SecretKey = new SecretKeySpec(AKey32Bytes.getBytes(), "AES");
            IvParameterSpec vSpec = new IvParameterSpec(AVectorNum16Bytes.getBytes());

            Cipher vCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            vCipher.init(Cipher.DECRYPT_MODE, SecretKey, vSpec);

            return new String(vCipher.doFinal(vEncryptedBytes));
        } catch (Exception e) {
                Common.mContext.getLogger().log(e.toString());
            return "";
        }
    }
</code>```

When i try to decrypt i have error:

```<code>javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
</code>```

Can somebody tell what the wrong?

答:
The encrypted string AKey32Bytes is double Base64 encoded.

Instead of AKey32Bytes.getBytes() you need to double Base64 decode the encrypted data to binary.

Encrypted string:

ak9YSTd6RXU5TENocUxQUGxieVhpZ3VqSlFiQUdndGZrbVJvbEliTGZjZz0=

After one Base64 decode:

jOXI7zEu9LChqLPPlbyXigujJQbAGgtfkmRolIbLfcg=

After a second Base64 decode (displayed in hex because it is not binary):

8CE5C8EF312EF4B0A1A8B3CF95BC978A0BA32506C01A0B5F9264689486CB7DC8

That is what needs to be provided to the decryption function.

The decrypted result is:

(in hex) 257531362A2179704B40577255516272

(in ASCII): "%u16*!ypK@WrUQbr" (all valid ASCII characters)

Note: there is a full block of PKCS#7 padding (in hex): 10101010101010101010101010101010

As much as it pains me to say this, from the correct padding I can assume the decryption was successful.

See Cryptomathic AES CALCULATOR

Body:
Hello everyone i have string encrypted in PHP by openssl_encrypt with algorithm 'aes-256-cbc'

Key: C4E30455853D4949A8E91B2C366BE9DE

Vector: 5686044872102713

Encrypted string: ak9YSTd6RXU5TENocUxQUGxieVhpZ3VqSlFiQUdndGZrbVJvbEliTGZjZz0=

And here is my Java function for decrypt:

public static String Decrypt_AES_FromBase64(String AEncryptedText, String AKey32Bytes, String AVectorNum16Bytes) {
        try {
            byte[] vEncryptedBytes = Base64.getDecoder().decode(AEncryptedText);

            Key SecretKey = new SecretKeySpec(AKey32Bytes.getBytes(), "AES");
            IvParameterSpec vSpec = new IvParameterSpec(AVectorNum16Bytes.getBytes());

            Cipher vCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            vCipher.init(Cipher.DECRYPT_MODE, SecretKey, vSpec);

            return new String(vCipher.doFinal(vEncryptedBytes));
        } catch (Exception e) {
                Common.mContext.getLogger().log(e.toString());
            return "";
        }
    }

When i try to decrypt i have error:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

Can somebody tell what the wrong?


问:
EF Core set column on adding value of child property
I have a Link and Content, News entities.

```<code>**Link**: Id, Url, RowId, Discriminator
**Content**: Id, Text, Link
**News**: Id, Date, Text, Link
</code>```

When I adding new Content or News I want automatically set RowId to inserted Id.
That's need to correctry resolve entity by Link.Url

So if I have Link.Discriminator and Link.RowId I can for sure determine which entity (Content or News) by Id I need.

Help me to resolve this.

答:
As far as I understand it this should be approximately what you're after.</p>

```<code>public void AddContent(string Text, string Link)
{
    var content = new Content {
        Text = Text,
        Link = Link
        };

    //The id is collected when you add the Entity to the context
    dbContext.SaveChanges();

    dbContext.Link.Add(new Link {
        Url = <whatever>,
        RowId = content.Id,
        Discriminator = "Content"
    });

    dbContext.SaveChanges();
}
</code>```

Body:
I have a Link and Content, News entities.

**Link**: Id, Url, RowId, Discriminator
**Content**: Id, Text, Link
**News**: Id, Date, Text, Link

When I adding new Content or News I want automatically set RowId to inserted Id.
That's need to correctry resolve entity by Link.Url

So if I have Link.Discriminator and Link.RowId I can for sure determine which entity (Content or News) by Id I need.

Help me to resolve this.

Body:
As far as I understand it this should be approximately what you're after.

public void AddContent(string Text, string Link)
{
    var content = new Content {
        Text = Text,
        Link = Link
        };

    //The id is collected when you add the Entity to the context
    dbContext.SaveChanges();

    dbContext.Link.Add(new Link {
        Url = <whatever>,
        RowId = content.Id,
        Discriminator = "Content"
    });

    dbContext.SaveChanges();
}


问:
Display Network Encryption Type in Tshark?
I've been using tshark to gather some basic information on networks near where I live. I've got tshark to display the bssid, ssid, and rssi but I was wondering if there was also a way to display the networks encryption type as well. I'm using the following command:

```<code>tshark -i wlan1mon -l -T fields -e wlan.bssid -e wlan.ssid -e radiotap.dbm_antsignal -Y 'wlan.ssid' | grep -v "ff:ff:ff"
</code>```

and this is and example of the output I get:

```<code>00:11:22:33:44:55   Bell Wireless    -74,-74
66:77:88:99:00:22   Dlink            -83,-83
33:44:55:66:77:88   NetflixNChill    -68,-83
</code>```

Ideally I'd want the output to look more like this:

```<code>00:11:22:33:44:55   Bell Wireless   WPA  -74,-74
66:77:88:99:00:22   Dlink           WPA2 -83,-83
33:44:55:66:77:88   NetflixNChill   Open -68,-83
</code>```

Any help would be greatly appreciated!

答:
Maybe -e wlan.rsn.pcs.type and -e wlan.rsn.gcs.type are what you're looking for?  Those are for the Pairwise Cipher Suite type" and "Group Cipher Suite type", respectively.

In case those aren't the fields you're interested in, or in case you want to include additional fields, you can find a complete list of display filters, including wlan filters, online at the Wireshark Display Filter Reference page.

You can also get this information from:

Wireshark itself via "View -> Internals -> Supported Protocols -> ...", but unfortunately the sorting leaves much to be desired there.

tshark using the tshark -G fields command, but this output isn't very user-friendly either.

Body:
I've been using tshark to gather some basic information on networks near where I live. I've got tshark to display the bssid, ssid, and rssi but I was wondering if there was also a way to display the networks encryption type as well. I'm using the following command:

tshark -i wlan1mon -l -T fields -e wlan.bssid -e wlan.ssid -e radiotap.dbm_antsignal -Y 'wlan.ssid' | grep -v "ff:ff:ff"

and this is and example of the output I get:

00:11:22:33:44:55   Bell Wireless    -74,-74
66:77:88:99:00:22   Dlink            -83,-83
33:44:55:66:77:88   NetflixNChill    -68,-83

Ideally I'd want the output to look more like this:

00:11:22:33:44:55   Bell Wireless   WPA  -74,-74
66:77:88:99:00:22   Dlink           WPA2 -83,-83
33:44:55:66:77:88   NetflixNChill   Open -68,-83

Any help would be greatly appreciated!


问:
How do I remove the title bar only for one Activity?
How to get one single ACTIVITY without Title?

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

This code is in styles.xml ! when i am using "NoActionBar" then all activity show no title bar,

答: Apply the theme without an ActionBar only for the specific Activity that requires it. It has to be set in the manifest.xml in the Activity tag: android:theme="@style/<YourAppThemeWithoutActionbarHere>"

Body:
How to get one single ACTIVITY without Title?

This code is in styles.xml ! when i am using "NoActionBar" then all activity show no title bar,


问:
Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"
I have a directory apkmirror-scraper-compose with the following structure:

```<code>.
├── docker-compose.yml
├── privoxy
│   ├── config
│   └── Dockerfile
├── scraper
│   ├── Dockerfile
│   ├── newnym.py
│   └── requirements.txt
└── tor
    └── Dockerfile
</code>```

I'm trying to run the following docker-compose.yml:

```<code>version: '3'

services:
  privoxy:
    build: ./privoxy
    ports:
      - "8118:8118"
    links:
      - tor

  tor:
    build:
      context: ./tor
      args:
        password: ""
    ports:
      - "9050:9050"
      - "9051:9051"

  scraper:
    build: ./scraper
    links:
      - tor
      - privoxy
</code>```

where the Dockerfile for tor is

```<code>FROM alpine:latest
EXPOSE 9050 9051
ARG password
RUN apk --update add tor
RUN echo "ControlPort 9051" >> /etc/tor/torrc
RUN echo "HashedControlPassword $(tor --quiet --hash-password $password)" >> /etc/tor/torrc
CMD ["tor"]
</code>```

that for privoxy is

```<code>FROM alpine:latest
EXPOSE 8118
RUN apk --update add privoxy
COPY config /etc/privoxy/config
CMD ["privoxy", "--no-daemon"]
</code>```

where config consists of the two lines

```<code>listen-address 0.0.0.0:8118
forward-socks5 / tor:9050 .
</code>```

and the Dockerfile for scraper is

```<code>FROM python:2.7-alpine
ADD . /scraper
WORKDIR /scraper
RUN pip install -r requirements.txt
CMD ["python", "newnym.py"]
</code>```

where requirements.txt contains the single line requests. Finally, the program newnym.py is designed to simply test whether changing the IP address using Tor is working:

```<code>from time import sleep, time

import requests as req
import telnetlib

def get_ip():
    IPECHO_ENDPOINT = 'http://ipecho.net/plain'
    HTTP_PROXY = 'http://privoxy:8118'
    return req.get(IPECHO_ENDPOINT, proxies={'http': HTTP_PROXY}).text

def request_ip_change():
    tn = telnetlib.Telnet('tor', 9051)
    tn.read_until("Escape character is '^]'.", 2)
    tn.write('AUTHENTICATE ""\r\n')
    tn.read_until("250 OK", 2)
    tn.write("signal NEWNYM\r\n")
    tn.read_until("250 OK", 2)
    tn.write("quit\r\n")
    tn.close()

if __name__ == '__main__':
    dts = []
    try:
        while True:
            ip = get_ip()
            t0 = time()
            request_ip_change()
            while True:
                new_ip = get_ip()
                if new_ip == ip:
                    sleep(1)
                else:
                    break
            dt = time() - t0
            dts.append(dt)
            print("{} -> {} in ~{}s".format(ip, new_ip, int(dt)))
    except KeyboardInterrupt:
        print("Stopping...")
        print("Average: {}".format(sum(dts) / len(dts)))
</code>```

The docker-compose build builds successfully, but if I try docker-compose up, I get the following error message:

```<code>Creating network "apkmirrorscrapercompose_default" with the default driver
ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network
</code>```

I tried searching for help on this error message, but couldn't find any. What is causing this error?

答:
You can try

```<code>$sudo service network-manager restart
</code>```

Worked for me.

Body:
I have a directory apkmirror-scraper-compose with the following structure:

.
├── docker-compose.yml
├── privoxy
│   ├── config
│   └── Dockerfile
├── scraper
│   ├── Dockerfile
│   ├── newnym.py
│   └── requirements.txt
└── tor
    └── Dockerfile

I'm trying to run the following docker-compose.yml:

version: '3'

services:
  privoxy:
    build: ./privoxy
    ports:
      - "8118:8118"
    links:
      - tor

  tor:
    build:
      context: ./tor
      args:
        password: ""
    ports:
      - "9050:9050"
      - "9051:9051"

  scraper:
    build: ./scraper
    links:
      - tor
      - privoxy

where the Dockerfile for tor is

FROM alpine:latest
EXPOSE 9050 9051
ARG password
RUN apk --update add tor
RUN echo "ControlPort 9051" >> /etc/tor/torrc
RUN echo "HashedControlPassword $(tor --quiet --hash-password $password)" >> /etc/tor/torrc
CMD ["tor"]

that for privoxy is

FROM alpine:latest
EXPOSE 8118
RUN apk --update add privoxy
COPY config /etc/privoxy/config
CMD ["privoxy", "--no-daemon"]

where config consists of the two lines

listen-address 0.0.0.0:8118
forward-socks5 / tor:9050 .

and the Dockerfile for scraper is

FROM python:2.7-alpine
ADD . /scraper
WORKDIR /scraper
RUN pip install -r requirements.txt
CMD ["python", "newnym.py"]

where requirements.txt contains the single line requests. Finally, the program newnym.py is designed to simply test whether changing the IP address using Tor is working:

from time import sleep, time

import requests as req
import telnetlib

def get_ip():
    IPECHO_ENDPOINT = 'http://ipecho.net/plain'
    HTTP_PROXY = 'http://privoxy:8118'
    return req.get(IPECHO_ENDPOINT, proxies={'http': HTTP_PROXY}).text

def request_ip_change():
    tn = telnetlib.Telnet('tor', 9051)
    tn.read_until("Escape character is '^]'.", 2)
    tn.write('AUTHENTICATE ""\r\n')
    tn.read_until("250 OK", 2)
    tn.write("signal NEWNYM\r\n")
    tn.read_until("250 OK", 2)
    tn.write("quit\r\n")
    tn.close()

if __name__ == '__main__':
    dts = []
    try:
        while True:
            ip = get_ip()
            t0 = time()
            request_ip_change()
            while True:
                new_ip = get_ip()
                if new_ip == ip:
                    sleep(1)
                else:
                    break
            dt = time() - t0
            dts.append(dt)
            print("{} -> {} in ~{}s".format(ip, new_ip, int(dt)))
    except KeyboardInterrupt:
        print("Stopping...")
        print("Average: {}".format(sum(dts) / len(dts)))

The docker-compose build builds successfully, but if I try docker-compose up, I get the following error message:

Creating network "apkmirrorscrapercompose_default" with the default driver
ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network

I tried searching for help on this error message, but couldn't find any. What is causing this error?

Body:
You can try

$sudo service network-manager restart

Worked for me.