问:
MVC Displaying Database Queries on View
I have an MVC application with many data grids backed by an oracle database. I would like to be able to display the query that is backing each specific grid on the page in some way. The queries are dynamic depending on what parameters are passed to them so I would like to be able to display the final query that goes to the database. I am not sure how I can achieve this without having to write a separate function for every query to be able to return the end result. My only idea is to do something like this:

```<code>public class DatabaseResult<T>
{
    public QueryInformation queryInfo { get; set; }
    public List<T> data { get; set; }
}
public class QueryInformation {
    //various properties about the query
    public string query { get; set; }
}
</code>```

Then in my data provider I will do this:

```<code>    public DatabaseResult<RestProgressGridModel> getGridData(string orgkey, string lvlnumdd, string lvlnum)
    {
        List<RestProgressGridModel> data = new List<RestProgressGridModel>();
        string grid = query.Replace("{orgkey}", orgkey).Replace("{lvlnum}", lvlnum).Replace("{lvlnumdd}", lvlnumdd);
        foreach (DataRow dr in FillDataTableFromQuery(grid).Rows)
        {
            data.Add(new RestProgressGridModel { });
        }
        return new DatabaseResult<RestProgressGridModel> {
            data = data,
            test = new QueryInformation {query = query }
        };
    }
</code>```

From here I'm not sure how I will be able to access this on the view itself. I could store the query into the ViewBag but I am not sure if that is the best approach.

Thanks for the help!

答:
Forgive me if I'm wrong, but aren't you already passing the query to the View?:

```<code>return new DatabaseResult<RestProgressGridModel> {
     data = data,
     test = new QueryInformation {query = query } // shouldn't this be query = new...?
 };
</code>```

Where you're creating a DatabaseResult<RestProgressGridModel>, you're setting the test (which I think should be queryInfo) property, which contains the query itself.

Can't you just use this in the View directly?

```<code><p>@Model.queryInfo.query</p>
</code>```

A couple of other helpful pointers:

In C#, Properties are conventionally named in PascalCase with a Capital letter at the start.

Try to avoid using camelCase, as this conventionally is used for local variables (or private fields, ideally prefixed with an _).

It helps readability for you, and for anyone reading your code.

Title: MVC Displaying Database Queries on View

Body:
I have an MVC application with many data grids backed by an oracle database. I would like to be able to display the query that is backing each specific grid on the page in some way. The queries are dynamic depending on what parameters are passed to them so I would like to be able to display the final query that goes to the database. I am not sure how I can achieve this without having to write a separate function for every query to be able to return the end result. My only idea is to do something like this:

public class DatabaseResult<T>
{
    public QueryInformation queryInfo { get; set; }
    public List<T> data { get; set; }
}
public class QueryInformation {
    //various properties about the query
    public string query { get; set; }
}

Then in my data provider I will do this:

    public DatabaseResult<RestProgressGridModel> getGridData(string orgkey, string lvlnumdd, string lvlnum)
    {
        List<RestProgressGridModel> data = new List<RestProgressGridModel>();
        string grid = query.Replace("{orgkey}", orgkey).Replace("{lvlnum}", lvlnum).Replace("{lvlnumdd}", lvlnumdd);
        foreach (DataRow dr in FillDataTableFromQuery(grid).Rows)
        {
            data.Add(new RestProgressGridModel { });
        }
        return new DatabaseResult<RestProgressGridModel> {
            data = data,
            test = new QueryInformation {query = query }
        };
    }

From here I'm not sure how I will be able to access this on the view itself. I could store the query into the ViewBag but I am not sure if that is the best approach.

Thanks for the help!

Body:
Forgive me if I'm wrong, but aren't you already passing the query to the View?:

return new DatabaseResult<RestProgressGridModel> {
     data = data,
     test = new QueryInformation {query = query } // shouldn't this be query = new...?
 };

Where you're creating a DatabaseResult<RestProgressGridModel>, you're setting the test (which I think should be queryInfo) property, which contains the query itself.

Can't you just use this in the View directly?

<p>@Model.queryInfo.query</p>

A couple of other helpful pointers:

In C#, Properties are conventionally named in PascalCase with a Capital letter at the start.

Try to avoid using camelCase, as this conventionally is used for local variables (or private fields, ideally prefixed with an _).

It helps readability for you, and for anyone reading your code.


来源: stackexchange

问:
Child state not Inheriting resolved dependencies from parent state
Here is my code

```<code>$stateProvider
        .state('admin', {
            abstract: true,
            templateUrl: "views/common/content.html",
            resolve: {
                channel: function($stateParams){
                    return $stateParams.id
                }
            }
        })
        .state('admin.dash',{
            url: "/dash",
            templateUrl: "views/admin/admin_dash.html"
       })
</code>```

and i have many controllers for this admin_dash.html view using ng-controller. And in any of these controllers (child) i am not able to inject 'channel' which is the resolved dependency of the parent state, which should be inherited.

答:
The resolve injectables will not be available to any old ng-controller, but only to the controller specified to the state.

E.g.

```<code>$stateProvider
    .state('admin', {
        abstract: true,
        templateUrl: "views/common/content.html",
        resolve: {
            channel: function($stateParams){
                return $stateParams.id
            }
        }
    })
    .state('admin.dash',{
        url: "/dash",
        templateUrl: "views/admin/admin_dash.html",
        // Injectable here
        controller: function(channel, $rootScope) {
            console.log('Received channel from parent resolve:', channel);
            // If need for ng-controller bound controllers...
            $rootScope.channel = channel;
        }
    })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my code

$stateProvider
        .state('admin', {
            abstract: true,
            templateUrl: "views/common/content.html",
            resolve: {
                channel: function($stateParams){
                    return $stateParams.id
                }
            }
        })
        .state('admin.dash',{
            url: "/dash",
            templateUrl: "views/admin/admin_dash.html"
       })

and i have many controllers for this admin_dash.html view using ng-controller. And in any of these controllers (child) i am not able to inject 'channel' which is the resolved dependency of the parent state, which should be inherited.

Body:
The resolve injectables will not be available to any old ng-controller, but only to the controller specified to the state.

E.g.

$stateProvider
    .state('admin', {
        abstract: true,
        templateUrl: "views/common/content.html",
        resolve: {
            channel: function($stateParams){
                return $stateParams.id
            }
        }
    })
    .state('admin.dash',{
        url: "/dash",
        templateUrl: "views/admin/admin_dash.html",
        // Injectable here
        controller: function(channel, $rootScope) {
            console.log('Received channel from parent resolve:', channel);
            // If need for ng-controller bound controllers...
            $rootScope.channel = channel;
        }
    })


问:
how to create e-mail template for outlook 2010 with a text over an image
I'm trying to create .oft template for outlook 2010 with a text over an image - text should be customisable by the end users...

If I create new e-mail from a html file and save it as template, input is not editable (using just a normal styled paragraph)

If I create new e-mail template directly in outlook, everything is ok for users, but it doesn't send it properly - everything is send as an attachment - so it doesn't display it properly in some mail clients (e.g. gmail).

Is there any bullet proof way how to create e-mail templates for outlook 2010 ?

答:
I made a Fiddle so you can see this code in action: https://jsfiddle.net/wallyglenn/7zLaLrfx/

```<code><div style="background-color:#ff0000; width:600px;">
  <!--[if gte mso 9]>
  <v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
    <v:fill type="tile" src="http://www.gwally.com/news/photos/catintinfoilhat.jpg" color="#ff0000"/>
  </v:background>
  <![endif]-->
  <table height="450" width="600" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td valign="top" align="left" background="http://www.gwally.com/news/photos/catintinfoilhat.jpg">
        <h1 style="text-align: center; color: #ffffff;-webkit-text-stroke-width: 1px; -webkit-text-stroke-color: black; font-family: Arial, san-serif;">
          Background Image with text on top
        </h1>
      </td>
    </tr>
  </table>
</div>
</code>```

The original code was taken from https://backgrounds.cm.

Good luck.

Body:
I made a Fiddle so you can see this code in action: https://jsfiddle.net/wallyglenn/7zLaLrfx/

<div style="background-color:#ff0000; width:600px;">
  <!--[if gte mso 9]>
  <v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
    <v:fill type="tile" src="http://www.gwally.com/news/photos/catintinfoilhat.jpg" color="#ff0000"/>
  </v:background>
  <![endif]-->
  <table height="450" width="600" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td valign="top" align="left" background="http://www.gwally.com/news/photos/catintinfoilhat.jpg">
        <h1 style="text-align: center; color: #ffffff;-webkit-text-stroke-width: 1px; -webkit-text-stroke-color: black; font-family: Arial, san-serif;">
          Background Image with text on top
        </h1>
      </td>
    </tr>
  </table>
</div>

The original code was taken from https://backgrounds.cm.

Good luck.


问:
How to use arbitrary directory as static directory in Reactjs
I have a website written in React.

The website itself works fine.

I also have blog which is based on Wordpress.

When I put blog contents on blog directory, React show the 404 not found page because all contents but static is managed by React.

I think if I could set one more directory called blog as static directory, I can put all Wordpress related files on the directory.

But I was struggling to do that.

Is there any options or setting files for react-scripts build?

like react-scripts build --static-directories static,blog

Could you please help me?

/index.html
/static/* < static contents
/blog/* < also static contents.

Thanks in advance.

[UPDATE] even though i put static file on static directory, I could not access it. It turned out I need to import that static file from Reactjs file...

答:
This is something you probably want to deal with on a server level.

So if you are using express, then you can do something like:

app.use('/static', express.static('public'))


问:
Is try-catching actually this clunky in Java or am I just not aware of the elegant approach?
```<code>public void lock() {
    if (this.isLocked()) return;

    try {
        this.dataOut.flush();
        this.dataOut.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    DataInputStream inputStream =
        new DataInputStream(
        new BufferedInputStream(
        new ByteArrayInputStream(
            this.byteOut.toByteArray())));

    IntStream.Builder intStreamBuilder = IntStream.builder();
    try {
        try {
            while (true) {
                intStreamBuilder.accept(inputStream.readInt());
            }
        } catch (EOFException e) {
            // logic to be executed after stream has been fully read
            int[] pool = intStreamBuilder.build().toArray();
            super.lock(pool);
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
</code>```

What I do here is take an DataOutputStream containing Integers, flush its remaining contents into a ByteArrayOutputStream named this.byteOut and then build an IntStream from it.

I'm from the C# domain and in the process of learning Java, so the code here does not have any actual purpose.

Is there any way to do what I do here more elegantly in Java?

My two main concerns are:

The way I determine that the DataInputStream has been fully read is by catching an EOFException and putting the logic to be executed after reading inside a catch block. I don't like that, since I suppose throwing and catching exceptions is somewhat expensive? Is there a better way to determine that the stream doesn't contain any more Integers?

The fact that I have to wrap a try-catch block around a try-catch block just to be able to call inputStream.close() in the inner finally block. Is there a solution that is not so clunky?

答:
Well the better solution I found thanks to @Oliver Charlesworth is the following:

```<code>    try (DataInputStream inputStream =
        new DataInputStream(
        new BufferedInputStream(
        new ByteArrayInputStream(this.byteOut.toByteArray())))) {
        while (true)
            intStreamBuilder.accept(inputStream.readInt());
    } catch (EOFException e) {
        int[] pool = intStreamBuilder.build().toArray();
        super.lock(pool);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
</code>```

This still has logic inside the catch block the code look definitely cleaner.

However, I cannot come up with a better approach that determines that the InputDataStream has been fully read.

What bugs me about this is that reaching the end of the stream is expected and it would actually be exceptional if no exception was thrown, what IMO defeats the purpose of exceptions in the first place.

I asked a separate question of the possible use of Java NIO's IntBuffer class here. My above snippet could be changed to:

```<code>IntBuffer intBuffer = ByteBuffer.wrap(this.byteOut.toByteArray()).asIntBuffer();
while (intBuffer.hasRemaining()){
    intStreamBuilder.accept(intBuffer.get());
}
int[] pool = intStreamBuilder.build().toArray();
super.lock(pool);
</code>```

Body:
public void lock() {
    if (this.isLocked()) return;

    try {
        this.dataOut.flush();
        this.dataOut.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    DataInputStream inputStream =
        new DataInputStream(
        new BufferedInputStream(
        new ByteArrayInputStream(
            this.byteOut.toByteArray())));

    IntStream.Builder intStreamBuilder = IntStream.builder();
    try {
        try {
            while (true) {
                intStreamBuilder.accept(inputStream.readInt());
            }
        } catch (EOFException e) {
            // logic to be executed after stream has been fully read
            int[] pool = intStreamBuilder.build().toArray();
            super.lock(pool);
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

What I do here is take an DataOutputStream containing Integers, flush its remaining contents into a ByteArrayOutputStream named this.byteOut and then build an IntStream from it.

I'm from the C# domain and in the process of learning Java, so the code here does not have any actual purpose.

Is there any way to do what I do here more elegantly in Java?

My two main concerns are:

The way I determine that the DataInputStream has been fully read is by catching an EOFException and putting the logic to be executed after reading inside a catch block. I don't like that, since I suppose throwing and catching exceptions is somewhat expensive? Is there a better way to determine that the stream doesn't contain any more Integers?

The fact that I have to wrap a try-catch block around a try-catch block just to be able to call inputStream.close() in the inner finally block. Is there a solution that is not so clunky?

Body:
Well the better solution I found thanks to @Oliver Charlesworth is the following:

    try (DataInputStream inputStream =
        new DataInputStream(
        new BufferedInputStream(
        new ByteArrayInputStream(this.byteOut.toByteArray())))) {
        while (true)
            intStreamBuilder.accept(inputStream.readInt());
    } catch (EOFException e) {
        int[] pool = intStreamBuilder.build().toArray();
        super.lock(pool);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

This still has logic inside the catch block the code look definitely cleaner.

However, I cannot come up with a better approach that determines that the InputDataStream has been fully read.

What bugs me about this is that reaching the end of the stream is expected and it would actually be exceptional if no exception was thrown, what IMO defeats the purpose of exceptions in the first place.

I asked a separate question of the possible use of Java NIO's IntBuffer class here. My above snippet could be changed to:

IntBuffer intBuffer = ByteBuffer.wrap(this.byteOut.toByteArray()).asIntBuffer();
while (intBuffer.hasRemaining()){
    intStreamBuilder.accept(intBuffer.get());
}
int[] pool = intStreamBuilder.build().toArray();
super.lock(pool);


问:
Having some problems with XM create
I have a bit of a problem with Xen. Each time I try to run xm create I get the following error:

```<code>dom0:~#  xm create -c staros.xm
Using config file "./staros.xm". Started domain StarOS-3 xenconsole: Could not read tty from store: No such file or directory
</code>```

Is this familiar to anyone?

I  believe my config is in order. At first I suspected the path to qemu-dm wasn't set correctly.

答:
The error you are describing could mean two things:

It is documenting a well known race in xenstore

The psuedo TTY needed to attach to a domain's console is stored in xenstore in several places. The Xen console client establishes an inotify style watch on that value, so that it can reconnect to the console if the backing file descriptor happens to change. However, takes a few seconds for that information to be populated in xenstore from the time that the domain is initially created.

If you post the output of xm info, it would be easy to see if you are dealing with a well known race.

The backing psuedo terminal can't be created

Common reasons for this would be /dev/pts not being mounted. If you run xenstore-ls /local/domain/{domain_id} after starting the domain without the -c option, you will see the contents of the store for that domain. Look for the line (near the bottom) that says

```<code>tty="/dev/pts/{pty}"
</code>```

Verify that the pty does, in fact, exist.

The xen console daemon uses two actual file descriptors to make it happen. The first is a psuedo file descriptor (obtained via xs_fileno()) on that specific piece of information in the node, so it can poll() to see if that information changes. The second is a real FD returned from open() (yes, O_NONBLOCK is passed) which actually reads/writes to the psuedo tty.

It looks like it's not even finding the psuedo FD from xenstore, which means the backing pty is likely existentially challenged.

Title: Having some problems with XM create

Body:
I have a bit of a problem with Xen. Each time I try to run xm create I get the following error:

dom0:~#  xm create -c staros.xm
Using config file "./staros.xm". Started domain StarOS-3 xenconsole: Could not read tty from store: No such file or directory

Is this familiar to anyone?

I  believe my config is in order. At first I suspected the path to qemu-dm wasn't set correctly.

Body:
The error you are describing could mean two things:

It is documenting a well known race in xenstore

The psuedo TTY needed to attach to a domain's console is stored in xenstore in several places. The Xen console client establishes an inotify style watch on that value, so that it can reconnect to the console if the backing file descriptor happens to change. However, takes a few seconds for that information to be populated in xenstore from the time that the domain is initially created.

If you post the output of xm info, it would be easy to see if you are dealing with a well known race.

The backing psuedo terminal can't be created

Common reasons for this would be /dev/pts not being mounted. If you run xenstore-ls /local/domain/{domain_id} after starting the domain without the -c option, you will see the contents of the store for that domain. Look for the line (near the bottom) that says

tty="/dev/pts/{pty}"

Verify that the pty does, in fact, exist.

The xen console daemon uses two actual file descriptors to make it happen. The first is a psuedo file descriptor (obtained via xs_fileno()) on that specific piece of information in the node, so it can poll() to see if that information changes. The second is a real FD returned from open() (yes, O_NONBLOCK is passed) which actually reads/writes to the psuedo tty.

It looks like it's not even finding the psuedo FD from xenstore, which means the backing pty is likely existentially challenged.

ContentLicense: CC BY-SA 2.5


问:
How can I read yaml (Configuration) file as JSON in dropwizard?
I want to parse configuration yaml file as a JSON Object in Dropwizard.
As in Python and Ruby we can directly read yaml file as JSON:

```<code>require 'yaml'
conf = YAML.load_file('some.yml')
puts conf.<some key>
</code>```

I want to follow the same protocol and do not want to make a separate class to map the yaml structure, but not sure how to achieve it in Java.

答:
You can just use the Configuration object from DropWizard, either the default or a custom one that has been created to hold additional parameters. This object is available on the Application class, under the "run" method in particular. Using the DW configuration example:

```<code>public class ExampleConfiguration extends Configuration {
    @Valid
    @NotNull
    private MessageQueueFactory messageQueue = new MessageQueueFactory();

    @JsonProperty("messageQueue")
    public MessageQueueFactory getMessageQueueFactory() {
        return messageQueue;
    }

    @JsonProperty("messageQueue")
    public void setMessageQueueFactory(MessageQueueFactory factory) {
        this.messageQueue = factory;
    }
}
</code>```

You can get/set all the attributes from YAML file as below:

```<code>public class MyApplication extends Application<ExampleConfiguration> {

    ...

    public void run(ExampleConfiguration configuration, Environment environment) {

        configuration.getMessageQueueFactory();
        configuration.getServerFactory();
    }
}
</code>```

Body:
I want to parse configuration yaml file as a JSON Object in Dropwizard.
As in Python and Ruby we can directly read yaml file as JSON:

require 'yaml'
conf = YAML.load_file('some.yml')
puts conf.<some key>

I want to follow the same protocol and do not want to make a separate class to map the yaml structure, but not sure how to achieve it in Java.

Body:
You can just use the Configuration object from DropWizard, either the default or a custom one that has been created to hold additional parameters. This object is available on the Application class, under the "run" method in particular. Using the DW configuration example:

public class ExampleConfiguration extends Configuration {
    @Valid
    @NotNull
    private MessageQueueFactory messageQueue = new MessageQueueFactory();

    @JsonProperty("messageQueue")
    public MessageQueueFactory getMessageQueueFactory() {
        return messageQueue;
    }

    @JsonProperty("messageQueue")
    public void setMessageQueueFactory(MessageQueueFactory factory) {
        this.messageQueue = factory;
    }
}

You can get/set all the attributes from YAML file as below:

public class MyApplication extends Application<ExampleConfiguration> {

    ...

    public void run(ExampleConfiguration configuration, Environment environment) {

        configuration.getMessageQueueFactory();
        configuration.getServerFactory();
    }
}


问:
Correct way to handle undefined declaration files (index.d.ts)
I got following error

```<code>error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'any' type.
  Try `npm install @types/react-native-camera` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-camera';`
</code>```

As a quick fix I created typings/index.d.ts (there is no @types/react-native-camera) file at root of my project and populated it with

```<code>declare module 'react-native-camera';
</code>```

then, in my tsconfig file I added it to my type roots like this

```<code>"typeRoots": ["node_modules/@types", "./typings"],
</code>```

however I am still getting same error when I build, leading me to think that my implementation is incorrect, what did I miss?

Edit, my full tsconfig looks like this

```<code>{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "lib": ["es7"],
    "allowJs": true,
    "checkJs": true,
    "jsx": "react-native",
    "removeComments": true,
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types", "./typings"],
    "experimentalDecorators": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "exclude": ["./node_modules", "./android", "./ios", "./assets", "./__tests__", "./dist"],
  "include": ["./src"]
}
</code>```

答:
The typeRoots options specifies where to look for packages that may contain type information. The documentation keeps saying that the compiler is looking for packages.

I've reproduced the structure you described and got the same error you did. Then I created a react-native-camera under typings and moved index.d.ts there so that I end up with this structure:

```<code>typings/
└── react-native-camera
    └── index.d.ts
</code>```

With this structure, the compilation runs just fine.

Using a typings directory structure is fine, if you want that kind of structure. For some projects I use a typings directory. For other projects, I prefer something simpler: a .d.ts file in the source tree that declares everything that needs declaring. So if I start from the description you give, but dump typings and instead add src/definitions.d.ts containing

```<code>declare module 'react-native-camera';
</code>```

then the code compiles just fine.

It is really a matter of preference what to use. Usually when a project becomes so complex that src/definitions.d.ts ends up being difficult to manage or hard to understand, I move to using a typings directory.

Body:
I got following error

error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'any' type.
  Try `npm install @types/react-native-camera` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-camera';`

As a quick fix I created typings/index.d.ts (there is no @types/react-native-camera) file at root of my project and populated it with

declare module 'react-native-camera';

then, in my tsconfig file I added it to my type roots like this

"typeRoots": ["node_modules/@types", "./typings"],

however I am still getting same error when I build, leading me to think that my implementation is incorrect, what did I miss?

Edit, my full tsconfig looks like this

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "lib": ["es7"],
    "allowJs": true,
    "checkJs": true,
    "jsx": "react-native",
    "removeComments": true,
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types", "./typings"],
    "experimentalDecorators": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "exclude": ["./node_modules", "./android", "./ios", "./assets", "./__tests__", "./dist"],
  "include": ["./src"]
}

Body:
The typeRoots options specifies where to look for packages that may contain type information. The documentation keeps saying that the compiler is looking for packages.

I've reproduced the structure you described and got the same error you did. Then I created a react-native-camera under typings and moved index.d.ts there so that I end up with this structure:

typings/
└── react-native-camera
    └── index.d.ts

With this structure, the compilation runs just fine.

Using a typings directory structure is fine, if you want that kind of structure. For some projects I use a typings directory. For other projects, I prefer something simpler: a .d.ts file in the source tree that declares everything that needs declaring. So if I start from the description you give, but dump typings and instead add src/definitions.d.ts containing

declare module 'react-native-camera';

then the code compiles just fine.

It is really a matter of preference what to use. Usually when a project becomes so complex that src/definitions.d.ts ends up being difficult to manage or hard to understand, I move to using a typings directory.


问:
Regular expression to extract specific part of a URL
I have a vector of URLs and need to extract a certain part of it. I've tried using a regex tester to see if my attempts worked, but they were no good.

The URLs I have are in this format: https://www.baseball-reference.com/teams/MIL/1976.shtml

I ned to extract the three letters after "teams/" (so for the example above, I need "MIL")

Does anyone have any idea how to get the correct regular expression to get this working? Thanks.

答:
Many different ways to achieve this using regexp's. Here's one:</p>

```<code>url <- "https://www.baseball-reference.com/teams/MIL/1976.shtml"

gsub(".+teams/(\\w{3}).+$", "\\1", url);
#[1] "MIL"
</code>```

Body:
Many different ways to achieve this using regexp's. Here's one:

url <- "https://www.baseball-reference.com/teams/MIL/1976.shtml"

gsub(".+teams/(\\w{3}).+$", "\\1", url);
#[1] "MIL"


问:
Stream is not called in android
I have stream:

```<code>Stream.of(coachingAreas)
            .map(coachingArea -> Observable.from(coachingArea.weeks)
            .map(coachingWeekRef -> coachingMap.put(coachingWeekRef.id, coachingWeekRef.version)));
</code>```

every array has data and is not empty, but this line: coachingMap.put(coachingWeekRef.id, coachingWeekRef.version)
is not called. Any idea why?

答:
You haven't performed a terminal operation on the
stream for that reason the stream remains idle. intermediate operations are driven by terminal operations. Essentially terminal operations produce a non-stream result such as a primitive value, an object, a collection etc.

don't do coachingMap.put within the map intermediate operation as  you're introducing a side-effect, rather use the toMap collector.

Assuming both coachingWeekRef.id and coachingWeekRef.version are integers then the whole query would look like this:

```<code>Map<Integer, Integer> resultSet =
     Stream.of(coachingAreas)
           .map(coachingArea -> Observable.from(coachingArea.weeks))
           .collect(Collectors.toMap(ClassName::getId, ClassName::getVersion));
</code>```

or use a lambda expression to extract the map key and value rather than a method reference if you prefer.

Title: Stream is not called in android

Body:
I have stream:

Stream.of(coachingAreas)
            .map(coachingArea -> Observable.from(coachingArea.weeks)
            .map(coachingWeekRef -> coachingMap.put(coachingWeekRef.id, coachingWeekRef.version)));

every array has data and is not empty, but this line: coachingMap.put(coachingWeekRef.id, coachingWeekRef.version)
is not called. Any idea why?

Body:
You haven't performed a terminal operation on the
stream for that reason the stream remains idle. intermediate operations are driven by terminal operations. Essentially terminal operations produce a non-stream result such as a primitive value, an object, a collection etc.

don't do coachingMap.put within the map intermediate operation as  you're introducing a side-effect, rather use the toMap collector.

Assuming both coachingWeekRef.id and coachingWeekRef.version are integers then the whole query would look like this:

Map<Integer, Integer> resultSet =
     Stream.of(coachingAreas)
           .map(coachingArea -> Observable.from(coachingArea.weeks))
           .collect(Collectors.toMap(ClassName::getId, ClassName::getVersion));

or use a lambda expression to extract the map key and value rather than a method reference if you prefer.


问:
Shape problems in keras while trying to output categorical variable
I am using the following, fairly simple code to predict an output variable which may have 3 categories:

```<code>n_factors = 20
np.random.seed = 42

def embedding_input(name, n_in, n_out, reg):
    inp = Input(shape=(1,), dtype='int64', name=name)
    return inp, Embedding(n_in, n_out, input_length=1, W_regularizer=l2(reg))(inp)

user_in, u = embedding_input('user_in', n_users, n_factors, 1e-4)
artifact_in, a = embedding_input('artifact_in', n_artifacts, n_factors, 1e-4)

mt = Input(shape=(31,))
mr = Input(shape=(1,))
sub = Input(shape=(24,))

def onehot(featurename):
    onehot_encoder = OneHotEncoder(sparse=False)
    onehot_encoded = onehot_encoder.fit_transform(Modality_Durations[featurename].reshape(-1, 1))
    trn_onehot_encoded = onehot_encoded[msk]
    val_onehot_encoded = onehot_encoded[~msk]
    return trn_onehot_encoded, val_onehot_encoded

trn_onehot_encoded_mt, val_onehot_encoded_mt = onehot('modality_type')
trn_onehot_encoded_mr, val_onehot_encoded_mr = onehot('roleid')
trn_onehot_encoded_sub, val_onehot_encoded_sub = onehot('subject')
trn_onehot_encoded_quartile, val_onehot_encoded_quartile = onehot('quartile')

# Model
x = merge([u, a], mode='concat')
x = Flatten()(x)
x = merge([x, mt], mode='concat')
x = merge([x, mr], mode='concat')
x = merge([x, sub], mode='concat')
x = Dense(10, activation='relu')(x)
BatchNormalization()
x = Dense(3, activation='softmax')(x)
nn = Model([user_in, artifact_in, mt, mr, sub], x)
nn.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

nn.optimizer.lr = 0.001
nn.fit([trn.member_id, trn.artifact_id, trn_onehot_encoded_mt, trn_onehot_encoded_mr, trn_onehot_encoded_sub], trn_onehot_encoded_quartile,
       batch_size=256,
       epochs=2,
       validation_data=([val.member_id, val.artifact_id, val_onehot_encoded_mt, val_onehot_encoded_mr, val_onehot_encoded_sub], val_onehot_encoded_quartile)
      )
</code>```

Here's the summary of the model:

```<code>____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
user_in (InputLayer)             (None, 1)             0
____________________________________________________________________________________________________
artifact_in (InputLayer)         (None, 1)             0
____________________________________________________________________________________________________
embedding_9 (Embedding)          (None, 1, 20)         5902380     user_in[0][0]
____________________________________________________________________________________________________
embedding_10 (Embedding)         (None, 1, 20)         594200      artifact_in[0][0]
____________________________________________________________________________________________________
merge_25 (Merge)                 (None, 1, 40)         0           embedding_9[0][0]
                                                                   embedding_10[0][0]
____________________________________________________________________________________________________
flatten_7 (Flatten)              (None, 40)            0           merge_25[0][0]
____________________________________________________________________________________________________
input_13 (InputLayer)            (None, 31)            0
____________________________________________________________________________________________________
merge_26 (Merge)                 (None, 71)            0           flatten_7[0][0]
                                                                   input_13[0][0]
____________________________________________________________________________________________________
input_14 (InputLayer)            (None, 1)             0
____________________________________________________________________________________________________
merge_27 (Merge)                 (None, 72)            0           merge_26[0][0]
                                                                   input_14[0][0]
____________________________________________________________________________________________________
input_15 (InputLayer)            (None, 24)            0
____________________________________________________________________________________________________
merge_28 (Merge)                 (None, 96)            0           merge_27[0][0]
                                                                   input_15[0][0]
____________________________________________________________________________________________________
dense_13 (Dense)                 (None, 10)            970         merge_28[0][0]
____________________________________________________________________________________________________
dense_14 (Dense)                 (None, 3)             33          dense_13[0][0]
====================================================================================================
Total params: 6,497,583
Trainable params: 6,497,583
Non-trainable params: 0
_____________________________
</code>```

But on the fit statement, I get the following error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-7de0782d7d5d> in <module>()
      5        batch_size=256,
      6        epochs=2,
----> 7        validation_data=([val.member_id, val.artifact_id, val_onehot_encoded_mt, val_onehot_encoded_mr, val_onehot_encoded_sub], val_onehot_encoded_quartile)
      8       )
      9 # nn.fit([trn.member_id, trn.artifact_id, trn_onehot_encoded_mt, trn_onehot_encoded_mr, trn_onehot_encoded_sub], trn.duration_new,

/home/prateek_dl/anaconda3/lib/python3.5/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
   1520             class_weight=class_weight,
   1521             check_batch_axis=False,
-> 1522             batch_size=batch_size)
   1523         # Prepare validation data.
   1524         do_validation = False

/home/prateek_dl/anaconda3/lib/python3.5/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_axis, batch_size)
   1380                                     output_shapes,
   1381                                     check_batch_axis=False,
-> 1382                                     exception_prefix='target')
   1383         sample_weights = _standardize_sample_weights(sample_weight,
   1384                                                      self._feed_output_names)

/home/prateek_dl/anaconda3/lib/python3.5/site-packages/keras/engine/training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    142                             ' to have shape ' + str(shapes[i]) +
    143                             ' but got array with shape ' +
--> 144                             str(array.shape))
    145     return arrays
    146

ValueError: Error when checking target: expected dense_14 to have shape (None, 1) but got array with shape (1956554, 3)
</code>```

How do I resolve this error? Why is the final layer expecting (None,1) when according to the summary() it has to output (None,3)?

Any help would be greatly appreciated.

答: I fixed the error using categorical_entropy instead of sparse_categorical_entropy.

Body:
I am using the following, fairly simple code to predict an output variable which may have 3 categories:

n_factors = 20
np.random.seed = 42

def embedding_input(name, n_in, n_out, reg):
    inp = Input(shape=(1,), dtype='int64', name=name)
    return inp, Embedding(n_in, n_out, input_length=1, W_regularizer=l2(reg))(inp)

user_in, u = embedding_input('user_in', n_users, n_factors, 1e-4)
artifact_in, a = embedding_input('artifact_in', n_artifacts, n_factors, 1e-4)

mt = Input(shape=(31,))
mr = Input(shape=(1,))
sub = Input(shape=(24,))

def onehot(featurename):
    onehot_encoder = OneHotEncoder(sparse=False)
    onehot_encoded = onehot_encoder.fit_transform(Modality_Durations[featurename].reshape(-1, 1))
    trn_onehot_encoded = onehot_encoded[msk]
    val_onehot_encoded = onehot_encoded[~msk]
    return trn_onehot_encoded, val_onehot_encoded

trn_onehot_encoded_mt, val_onehot_encoded_mt = onehot('modality_type')
trn_onehot_encoded_mr, val_onehot_encoded_mr = onehot('roleid')
trn_onehot_encoded_sub, val_onehot_encoded_sub = onehot('subject')
trn_onehot_encoded_quartile, val_onehot_encoded_quartile = onehot('quartile')

# Model
x = merge([u, a], mode='concat')
x = Flatten()(x)
x = merge([x, mt], mode='concat')
x = merge([x, mr], mode='concat')
x = merge([x, sub], mode='concat')
x = Dense(10, activation='relu')(x)
BatchNormalization()
x = Dense(3, activation='softmax')(x)
nn = Model([user_in, artifact_in, mt, mr, sub], x)
nn.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

nn.optimizer.lr = 0.001
nn.fit([trn.member_id, trn.artifact_id, trn_onehot_encoded_mt, trn_onehot_encoded_mr, trn_onehot_encoded_sub], trn_onehot_encoded_quartile,
       batch_size=256,
       epochs=2,
       validation_data=([val.member_id, val.artifact_id, val_onehot_encoded_mt, val_onehot_encoded_mr, val_onehot_encoded_sub], val_onehot_encoded_quartile)
      )

Here's the summary of the model:

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
user_in (InputLayer)             (None, 1)             0
____________________________________________________________________________________________________
artifact_in (InputLayer)         (None, 1)             0
____________________________________________________________________________________________________
embedding_9 (Embedding)          (None, 1, 20)         5902380     user_in[0][0]
____________________________________________________________________________________________________
embedding_10 (Embedding)         (None, 1, 20)         594200      artifact_in[0][0]
____________________________________________________________________________________________________
merge_25 (Merge)                 (None, 1, 40)         0           embedding_9[0][0]
                                                                   embedding_10[0][0]
____________________________________________________________________________________________________
flatten_7 (Flatten)              (None, 40)            0           merge_25[0][0]
____________________________________________________________________________________________________
input_13 (InputLayer)            (None, 31)            0
____________________________________________________________________________________________________
merge_26 (Merge)                 (None, 71)            0           flatten_7[0][0]
                                                                   input_13[0][0]
____________________________________________________________________________________________________
input_14 (InputLayer)            (None, 1)             0
____________________________________________________________________________________________________
merge_27 (Merge)                 (None, 72)            0           merge_26[0][0]
                                                                   input_14[0][0]
____________________________________________________________________________________________________
input_15 (InputLayer)            (None, 24)            0
____________________________________________________________________________________________________
merge_28 (Merge)                 (None, 96)            0           merge_27[0][0]
                                                                   input_15[0][0]
____________________________________________________________________________________________________
dense_13 (Dense)                 (None, 10)            970         merge_28[0][0]
____________________________________________________________________________________________________
dense_14 (Dense)                 (None, 3)             33          dense_13[0][0]
====================================================================================================
Total params: 6,497,583
Trainable params: 6,497,583
Non-trainable params: 0
_____________________________

But on the fit statement, I get the following error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-7de0782d7d5d> in <module>()
      5        batch_size=256,
      6        epochs=2,
----> 7        validation_data=([val.member_id, val.artifact_id, val_onehot_encoded_mt, val_onehot_encoded_mr, val_onehot_encoded_sub], val_onehot_encoded_quartile)
      8       )
      9 # nn.fit([trn.member_id, trn.artifact_id, trn_onehot_encoded_mt, trn_onehot_encoded_mr, trn_onehot_encoded_sub], trn.duration_new,

/home/prateek_dl/anaconda3/lib/python3.5/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
   1520             class_weight=class_weight,
   1521             check_batch_axis=False,
-> 1522             batch_size=batch_size)
   1523         # Prepare validation data.
   1524         do_validation = False

/home/prateek_dl/anaconda3/lib/python3.5/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_axis, batch_size)
   1380                                     output_shapes,
   1381                                     check_batch_axis=False,
-> 1382                                     exception_prefix='target')
   1383         sample_weights = _standardize_sample_weights(sample_weight,
   1384                                                      self._feed_output_names)

/home/prateek_dl/anaconda3/lib/python3.5/site-packages/keras/engine/training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    142                             ' to have shape ' + str(shapes[i]) +
    143                             ' but got array with shape ' +
--> 144                             str(array.shape))
    145     return arrays
    146

ValueError: Error when checking target: expected dense_14 to have shape (None, 1) but got array with shape (1956554, 3)

How do I resolve this error? Why is the final layer expecting (None,1) when according to the summary() it has to output (None,3)?

Any help would be greatly appreciated.


问:
How can make a proper callback on pdfkit PDF file generation in Node.js?
I am calling a function that generates a PDF and gets me its path. On the callback I'm sending the PDF to the user to download it. Calling:

```<code>create_pdf(data, function(path) {
 res.download(path)
})
</code>```

And this is the function:

```<code>const PDFDocument = require('pdfkit')
function create_pdf(input, callback) {
    let doc = new PDFDocument({ margin: 0 })
    doc.fillColor('Black').fontSize(22)
        .font('Scandia-bold')
        .text(input, 167, 265, {
            align: 'center',
            width: 280
        })
    doc.on('end', function() { callback(path) })
    doc.end()
}
</code>```

But what the user ends up downloading is always a corrupt/damaged PDF while the PDF generated on the server is very fine. Is the problem that my function is sending the path before PDF creation is finished (aka my callback code is wrong)? Or what?

答:
Never mind :) Within the function I had to identify a 'writeStream' and then do the callback when it finishes:</p>

```<code>writeStream = fs.createWriteStream(path)
doc.pipe(writeStream)

writeStream.on('finish', function () {
    callback(path)
})
</code>```

Body:
I am calling a function that generates a PDF and gets me its path. On the callback I'm sending the PDF to the user to download it. Calling:

create_pdf(data, function(path) {
 res.download(path)
})

And this is the function:

const PDFDocument = require('pdfkit')
function create_pdf(input, callback) {
    let doc = new PDFDocument({ margin: 0 })
    doc.fillColor('Black').fontSize(22)
        .font('Scandia-bold')
        .text(input, 167, 265, {
            align: 'center',
            width: 280
        })
    doc.on('end', function() { callback(path) })
    doc.end()
}

But what the user ends up downloading is always a corrupt/damaged PDF while the PDF generated on the server is very fine. Is the problem that my function is sending the path before PDF creation is finished (aka my callback code is wrong)? Or what?

Body:
Never mind :) Within the function I had to identify a 'writeStream' and then do the callback when it finishes:

writeStream = fs.createWriteStream(path)
doc.pipe(writeStream)

writeStream.on('finish', function () {
    callback(path)
})


答:
It's mostly you.
If you don't like the try with resources construct,
you can still combine all of your try statments and stack the catch blocks.

```<code>public void lock()
{
    DataInputStream inputStream = null;
    IntStream.Builder intStreamBuilder;

    if (isLocked())
    {
        return;
    }

    try
    {
        inputStream = new DataInputStream(
            new BufferedInputStream(
                new ByteArrayInputStream(
                    byteOut.toByteArray())));

        intStreamBuilder = IntStream.builder();

        dataOut.flush();
        dataOut.close();

        while (true)
        {
            intStreamBuilder.accept(
                inputStream.readInt());
        }
    }
    catch (IOException exception)
    {
        throw new RuntimeException(exception);
    }
    catch (EOFException ignoredException)
    {
        // logic to be executed after stream has been fully read
        int[] pool = intStreamBuilder.build().toArray();
        super.lock(pool);
    }
    finally
    {
        if (inputSream != null)
        {
            try
            {
                inputStream.close();
            }
            catch (IOException exception)
            {
                throw new RuntimeException(exception);
            }
        }
    }
}
</code>```

The try inside the finally is required.

I prefer the try-with-resources construct.

Title: Is try-catching actually this clunky in Java or am I just not aware of the elegant approach?

Body:
It's mostly you.
If you don't like the try with resources construct,
you can still combine all of your try statments and stack the catch blocks.

public void lock()
{
    DataInputStream inputStream = null;
    IntStream.Builder intStreamBuilder;

    if (isLocked())
    {
        return;
    }

    try
    {
        inputStream = new DataInputStream(
            new BufferedInputStream(
                new ByteArrayInputStream(
                    byteOut.toByteArray())));

        intStreamBuilder = IntStream.builder();

        dataOut.flush();
        dataOut.close();

        while (true)
        {
            intStreamBuilder.accept(
                inputStream.readInt());
        }
    }
    catch (IOException exception)
    {
        throw new RuntimeException(exception);
    }
    catch (EOFException ignoredException)
    {
        // logic to be executed after stream has been fully read
        int[] pool = intStreamBuilder.build().toArray();
        super.lock(pool);
    }
    finally
    {
        if (inputSream != null)
        {
            try
            {
                inputStream.close();
            }
            catch (IOException exception)
            {
                throw new RuntimeException(exception);
            }
        }
    }
}

The try inside the finally is required.

I prefer the try-with-resources construct.


问:
Google play services update to 9.0.0 even though current version is 9.2.1
I'm having an issue with this google play services plugin. It is telling me to update from the current version to a previous one.  I have looked at other threads on here and they all say to put the plugin at the end of the app based gradle, which I already did, but I am still getting the error.

Here is my manifest code:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mikediloreto.findingrestaurants">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name=".MyApplication"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ProfileActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
    </application>
</manifest>
</code>```

And here is the app-based gradle:

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

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.example.mikediloreto.findingrestaurants"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso- core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:9.2.1'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-maps:11.0.4'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Here is the project based build gradle:

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

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

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

Please let me know if you would like me to include any other code.

答:
First of all here is something u shouldnt do

```<code>compile 'com.google.android.gms:play-services-maps:11.0.4'
</code>```

and

```<code>compile 'com.google.android.gms:play-services-auth:9.2.1'
</code>```

its a good practice to have on global variable for libs having the same versions
then u could do something like

```<code>compile "com.google.android.gms:play-services-auth:$google_ver"
</code>```

might be that 11.xxx nd 9.xxx versions r cosing the trouble. Try using 11.0.4 instead of 9.2.1

Body:
I'm having an issue with this google play services plugin. It is telling me to update from the current version to a previous one.  I have looked at other threads on here and they all say to put the plugin at the end of the app based gradle, which I already did, but I am still getting the error.

Here is my manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mikediloreto.findingrestaurants">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name=".MyApplication"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ProfileActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
    </application>
</manifest>

And here is the app-based gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.example.mikediloreto.findingrestaurants"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso- core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:9.2.1'
    compile 'de.hdodenhof:circleimageview:2.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-maps:11.0.4'
}

apply plugin: 'com.google.gms.google-services'

Here is the project based build gradle:

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

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

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

Please let me know if you would like me to include any other code.

Body:
First of all here is something u shouldnt do

compile 'com.google.android.gms:play-services-maps:11.0.4'

and

compile 'com.google.android.gms:play-services-auth:9.2.1'

its a good practice to have on global variable for libs having the same versions
then u could do something like

compile "com.google.android.gms:play-services-auth:$google_ver"

might be that 11.xxx nd 9.xxx versions r cosing the trouble. Try using 11.0.4 instead of 9.2.1


问:
Why do two structures with the same bit sizes differ in size?
I've got two structure that should be identical in size and content:

```<code>from ctypes import *

class struct_1(Structure):
    _fields_ = (
        ('field1', c_int16),
        ('field2', c_int16)
    )

class struct_2(Structure):
    # having _pack_ doesn't appear to do anything as it yields the same result
    _pack_ = 1
    _fields_ = (
        ('field1', c_int64, 16),
        ('field2', c_int64, 16)
    )
</code>```

however sizeof(struct_1) is 4 and sizeof(struct_2) is 8.  When I convert instances of each structure to a bytes array like so:

```<code>p1 = struct_1()
p2 = struct_2()

p1.field1 = 3
p2.field1 = 3

p1.field2 = -3
p2.field2 = -3

print(string_at(addressof(p1), sizeof(struct_1)))
print(string_at(addressof(p2), sizeof(struct_2)))
</code>```

I get the following output:

```<code>b'\x03\x00\xfd\xff'
b'\x03\x00\xfd\xff\x00\x00\x00\x00'
</code>```

Which shows to me that the structure is properly storing the data, but incorrectly setting the size of the structure.  Furthermore, if I add another field after it:

```<code>class struct_1(Structure):
    _fields_ = (
        ('field1', c_int16),
        ('field2', c_int16),
        ('field3', c_int16)
    )

class struct_2(Structure):
    _pack_ = 1
    _fields_ = (
        ('field1', c_int64, 16),
        ('field2', c_int64, 16),
        ('field3', c_int16)
    )
</code>```

and I set the values to those, I get a "padding" in between:

```<code>b'\x03\x00\xfd\xff\xff\x00'
b'\x03\x00\xfd\xff\x00\x00\x00\x00\xff\x00'
</code>```

Body:
I've got two structure that should be identical in size and content:

from ctypes import *

class struct_1(Structure):
    _fields_ = (
        ('field1', c_int16),
        ('field2', c_int16)
    )

class struct_2(Structure):
    # having _pack_ doesn't appear to do anything as it yields the same result
    _pack_ = 1
    _fields_ = (
        ('field1', c_int64, 16),
        ('field2', c_int64, 16)
    )

however sizeof(struct_1) is 4 and sizeof(struct_2) is 8.  When I convert instances of each structure to a bytes array like so:

p1 = struct_1()
p2 = struct_2()

p1.field1 = 3
p2.field1 = 3

p1.field2 = -3
p2.field2 = -3

print(string_at(addressof(p1), sizeof(struct_1)))
print(string_at(addressof(p2), sizeof(struct_2)))

I get the following output:

b'\x03\x00\xfd\xff'
b'\x03\x00\xfd\xff\x00\x00\x00\x00'

Which shows to me that the structure is properly storing the data, but incorrectly setting the size of the structure.  Furthermore, if I add another field after it:

class struct_1(Structure):
    _fields_ = (
        ('field1', c_int16),
        ('field2', c_int16),
        ('field3', c_int16)
    )

class struct_2(Structure):
    _pack_ = 1
    _fields_ = (
        ('field1', c_int64, 16),
        ('field2', c_int64, 16),
        ('field3', c_int16)
    )

and I set the values to those, I get a "padding" in between:

b'\x03\x00\xfd\xff\xff\x00'
b'\x03\x00\xfd\xff\x00\x00\x00\x00\xff\x00'

Body:
When dealing with the ctypes module, everything is going to be byte aligned (8 bits).  To account for the possibility of fields with non-byte aligned bit lengths, ctypes automatically allocates the space with the size of the field selected and then places the sub-fields into the newly byte aligned allocated space.  For example, given the following ctypes Structure:

from ctypes import *

class simple_pkt(Structure):
    _fields_ = (
        ('A', c_int8, 4),
        ('B', c_int8, 4),
        ('C', c_int8)
    )

The end packet produced in memory will be:

+---------------------------------------------------------------+
|                         bit locations                         |
+-------------------------------+-------------------------------+
|               Byte 0          |               Byte 1          |
+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| A | A | A | A | B | B | B | B | C | C | C | C | C | C | C | C |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

This is nice and lined up as expected.  Now, let's look at , if you have two sub-fields whose bit lengths added up aren't byte aligned:

class simple_pkt(Structure):
    _fields_ = (
        ('A', c_int8, 2),
        ('B', c_int8, 4),
        ('C', c_int8)
    )

You'll get empty or spare bits:

+---------------------------------------------------------------+
|                         bit locations                         |
+-------------------------------+-------------------------------+
|             Byte 0            |             Byte 1            |
+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+===+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| A | A | B | B | B | B |   |   | C | C | C | C | C | C | C | C |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

Notice that there is a gap between B and C.  This is the case for all of the c_<int> data types within the ctypes module.  As far as I know, there is no way around this.


问:
NSKeyedArchiver will not archive simple dictionary with enum as value
I am trying to use NSKeyedArchiver to "archive" a simple dictionary. The key is of type String and the value is an enum.

The following example illustrates what I am trying to do:

```<code>import Foundation

enum Friend: String, Codable {
    case Ben, Max
}

let friends: [String: Any] = [ "bestFriend" : Friend.Ben ]
let archivedFriends = NSKeyedArchiver.archivedData(withRootObject: friends)
</code>```

This code can be copied into a playground and the result will be the following error:

error: Execution was interrupted, reason: signal SIGABRT.

Sadly, I was not able to copy the stack trace so I had to create a screenshot:

To test that the enum is indeed the problem I changed the code to the following:

```<code>import Foundation

let friends: [String: Any] = [ "bestFriend" : "Ben" ]
let archivedFriends = NSKeyedArchiver.archivedData(withRootObject: friends)
</code>```

This works so the question is:

What am I missing in my first code example to get NSKeyedArchiver to work with the given dictionary?

答:
Use the raw value instead of using the enum directly.</p>

```<code>let friends: [String: Any] = [ "bestFriend" : Friend.Ben.rawValue]
let archivedFriends = NSKeyedArchiver.archivedData(withRootObject: friends)
</code>```

Body:
I am trying to use NSKeyedArchiver to "archive" a simple dictionary. The key is of type String and the value is an enum.

The following example illustrates what I am trying to do:

import Foundation

enum Friend: String, Codable {
    case Ben, Max
}

let friends: [String: Any] = [ "bestFriend" : Friend.Ben ]
let archivedFriends = NSKeyedArchiver.archivedData(withRootObject: friends)

This code can be copied into a playground and the result will be the following error:

error: Execution was interrupted, reason: signal SIGABRT.

Sadly, I was not able to copy the stack trace so I had to create a screenshot:

To test that the enum is indeed the problem I changed the code to the following:

import Foundation

let friends: [String: Any] = [ "bestFriend" : "Ben" ]
let archivedFriends = NSKeyedArchiver.archivedData(withRootObject: friends)

This works so the question is:

What am I missing in my first code example to get NSKeyedArchiver to work with the given dictionary?

Body:
Use the raw value instead of using the enum directly.

let friends: [String: Any] = [ "bestFriend" : Friend.Ben.rawValue]
let archivedFriends = NSKeyedArchiver.archivedData(withRootObject: friends)


问:
how to add instance to the list and then to the listbox in windows form
I don't know how to add Instances of my Album class from TextBoxes to a List<Album> and then to a ListBox in my WindowsForm.

Here is the code I have written so far but I'm stuck here and I don't know what to do next.

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<Album> AlbumList = new List<Album>();

    private void TrackButton_Click(object sender, EventArgs e)
    {
        addTracks settingsForm = new addTracks();
        settingsForm.ShowDialog();
    }

    private void CreateButton_Click(object sender, EventArgs e)
    {
        Album g = new Album (ASINtextBox.Text, AlbumNametextBox.Text, ArtisttextBox.Text,
            ReleaseDatePicker.Text, LabeltextBox.Text, ImagetextBox.Text);

        AlbumList.Add(g);
    }
}
</code>```

I dont have eny error i just think it is not creating a new list when I'm debuging the program.

This is the code for the class:

```<code>eclass Album
{
    private string ASIN;
    private string AlbumName;
    private string Artist;
    private string ReleaseDate;
    private string Label;
    private string Image;

    public Album(int ASIN)
    {
        this.ASIN = "no value";
        this.AlbumName = "no value";
        this.Artist = "no value";
        this.ReleaseDate = "no value";
        this.Label = "no value";
        this.Image = "no value";
    }

    public Album(string ASIN, string AlbumName, string Artist, string ReleaseDate,
        string Label, string Image)
    {
        this.ASIN = ASIN;
        this.AlbumName = AlbumName;
        this.Artist = Artist;
        this.ReleaseDate = ReleaseDate;
        this.Label = Label;
        this.Image = Image;
    }

    public string aSIN
    {
        get { return this.ASIN; }
        set { ASIN = value; }
    }

    public string albumName
    {
        get { return this.AlbumName; }
        set { AlbumName = value; }
    }

    public string artist
    {
        get { return this.Artist; }
        set { Artist = value; }
    }

    public string createDate
    {
        get { return this.ReleaseDate; }
        set { ReleaseDate = value; }

    }

    public string label
    {
        get { return this.Label; }
        set { Label = value; }
    }

    public string image
    {
        get { return this.Image; }
        set { Image = value; }
    }
}
</code>```

答:
Okay, you've got a few different options, but the easiest is something like this:

```<code>private void RefreshListBox()
{
    myGuiListBox.Items.Clear();
    foreach(Album loopAlbum in this.AlbumList)
    {
        myGuiListBox.Items.Add(loopAlbum.ToString());
    }
}
</code>```

... then, whenever something would change the list box (such as creating a new album and adding it to your List<>), you simply call the RefreshListBox() function.

Body:
I don't know how to add Instances of my Album class from TextBoxes to a List<Album> and then to a ListBox in my WindowsForm.

Here is the code I have written so far but I'm stuck here and I don't know what to do next.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<Album> AlbumList = new List<Album>();

    private void TrackButton_Click(object sender, EventArgs e)
    {
        addTracks settingsForm = new addTracks();
        settingsForm.ShowDialog();
    }

    private void CreateButton_Click(object sender, EventArgs e)
    {
        Album g = new Album (ASINtextBox.Text, AlbumNametextBox.Text, ArtisttextBox.Text,
            ReleaseDatePicker.Text, LabeltextBox.Text, ImagetextBox.Text);

        AlbumList.Add(g);
    }
}

I dont have eny error i just think it is not creating a new list when I'm debuging the program.

This is the code for the class:

eclass Album
{
    private string ASIN;
    private string AlbumName;
    private string Artist;
    private string ReleaseDate;
    private string Label;
    private string Image;

    public Album(int ASIN)
    {
        this.ASIN = "no value";
        this.AlbumName = "no value";
        this.Artist = "no value";
        this.ReleaseDate = "no value";
        this.Label = "no value";
        this.Image = "no value";
    }

    public Album(string ASIN, string AlbumName, string Artist, string ReleaseDate,
        string Label, string Image)
    {
        this.ASIN = ASIN;
        this.AlbumName = AlbumName;
        this.Artist = Artist;
        this.ReleaseDate = ReleaseDate;
        this.Label = Label;
        this.Image = Image;
    }

    public string aSIN
    {
        get { return this.ASIN; }
        set { ASIN = value; }
    }

    public string albumName
    {
        get { return this.AlbumName; }
        set { AlbumName = value; }
    }

    public string artist
    {
        get { return this.Artist; }
        set { Artist = value; }
    }

    public string createDate
    {
        get { return this.ReleaseDate; }
        set { ReleaseDate = value; }

    }

    public string label
    {
        get { return this.Label; }
        set { Label = value; }
    }

    public string image
    {
        get { return this.Image; }
        set { Image = value; }
    }
}

Body:
Okay, you've got a few different options, but the easiest is something like this:

private void RefreshListBox()
{
    myGuiListBox.Items.Clear();
    foreach(Album loopAlbum in this.AlbumList)
    {
        myGuiListBox.Items.Add(loopAlbum.ToString());
    }
}

... then, whenever something would change the list box (such as creating a new album and adding it to your List<>), you simply call the RefreshListBox() function.


问:
Cannot install Ruby with rbenv 2.3.1 in Ubuntu 16.04
While installing ruby with rbenv for Ubuntu 16.04 error regarding the ruby build is shown.
I've tried completely removing the rbenv and again re-installing rbenv, but all i get the following error.

I've followed DigitalOcean's procedure for installing the rbenv as in here, and followed steps listed here for ruby_build. I've also installed all dependencies required for the build.

Still after times of uninstall and install of rbenv problem is the same.

```<code>   ~$ rbenv install 2.3.1
   Downloading ruby-2.3.1.tar.bz2...
   -> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.1.tar.bz2
   Installing ruby-2.3.1...

   BUILD FAILED (Ubuntu 16.04 using ruby-build 20170726-2-g254728e)

   Inspect or clean up the working tree at /tmp/build.20170818162042.1074
   Results logged to /tmp/ruby-build.20170818162042.1074.log

   Last 10 log lines:
   linking shared-object objspace.so
   make[2]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1/ext/objspace'
   installing default date_core libraries
   linking shared-object date_core.so
   make[2]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1/ext/date'
   linking shared-object nkf.so
   make[2]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1/ext/nkf'
   make[1]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1'
   uncommon.mk:203: recipe for target 'build-ext' failed
   make: *** [build-ext] Error 2
</code>```

Result of cat /tmp/ruby-build.20170818162042.1074.log

```<code>In file included from ossl.h:57:0,
                 from ossl_bn.c:11:
/usr/include/openssl/asn1_mac.h:10:2: error: #error "This file is obsolete; please update your software."
 #error "This file is obsolete; please update your software."
  ^
In file included from ossl.h:221:0,
                 from ossl_bn.c:11:
openssl_missing.h:78:35: error: macro "EVP_MD_CTX_create" passed 1 arguments, but takes just 0
 EVP_MD_CTX *EVP_MD_CTX_create(void);
                                   ^
In file included from /usr/include/openssl/x509.h:23:0,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
openssl_missing.h:82:6: error: expected declaration specifiers or ‘...’ before ‘(’ token
 void EVP_MD_CTX_init(EVP_MD_CTX *ctx);
      ^
openssl_missing.h:90:6: error: expected declaration specifiers or ‘...’ before ‘(’ token
 void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx);
      ^
ossl_bn.c: In function ‘ossl_bn_size’:
ossl_bn.c:43:19: error: invalid application of ‘sizeof’ to incomplete type ‘BIGNUM {aka struct bignum_st}’
     return sizeof(BIGNUM);
                   ^
ossl_bn.c: In function ‘ossl_bn_s_generate_prime’:
ossl_bn.c:769:5: warning: ‘BN_generate_prime’ is deprecated [-Wdeprecated-declarations]
     if (!BN_generate_prime(result, num, safe, add, rem, NULL, NULL)) {
     ^
In file included from /usr/include/openssl/bn.h:31:0,
                 from /usr/include/openssl/asn1.h:24,
                 from /usr/include/openssl/objects.h:916,
                 from /usr/include/openssl/evp.h:27,
                 from /usr/include/openssl/x509.h:23,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
/usr/include/openssl/bn.h:285:1: note: declared here
 DEPRECATEDIN_0_9_8(BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe,
 ^
ossl_bn.c: In function ‘ossl_bn_is_prime’:
ossl_bn.c:877:5: warning: ‘BN_is_prime’ is deprecated [-Wdeprecated-declarations]
     switch (BN_is_prime(bn, checks, NULL, ossl_bn_ctx, NULL)) {
     ^
In file included from /usr/include/openssl/bn.h:31:0,
                 from /usr/include/openssl/asn1.h:24,
                 from /usr/include/openssl/objects.h:916,
                 from /usr/include/openssl/evp.h:27,
                 from /usr/include/openssl/x509.h:23,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
/usr/include/openssl/bn.h:291:1: note: declared here
 DEPRECATEDIN_0_9_8(int
 ^
ossl_bn.c: In function ‘ossl_bn_is_prime_fasttest’:
ossl_bn.c:916:5: warning: ‘BN_is_prime_fasttest’ is deprecated [-Wdeprecated-declarations]
     switch (BN_is_prime_fasttest(bn, checks, NULL, ossl_bn_ctx, NULL, do_trial_division)) {
     ^
In file included from /usr/include/openssl/bn.h:31:0,
                 from /usr/include/openssl/asn1.h:24,
                 from /usr/include/openssl/objects.h:916,
                 from /usr/include/openssl/evp.h:27,
                 from /usr/include/openssl/x509.h:23,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
/usr/include/openssl/bn.h:295:1: note: declared here
 DEPRECATEDIN_0_9_8(int
 ^
ossl_bn.c: In function ‘ossl_bn_size’:
ossl_bn.c:44:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
Makefile:301: recipe for target 'ossl_bn.o' failed
</code>```

答:
I was able to successfully build docker image with the following Dockerfile

```<code>FROM ubuntu:16.04

ENV RBENV_ROOT=/usr/local/rbenv
ENV PATH=$RBENV_ROOT/bin:$RBENV_ROOT/shims:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    cmake curl git zlib1g-dev \
    libssl-dev libreadline-dev \
    libyaml-dev libxml2-dev \
    libxslt-dev libsqlite3-dev \
    python-dev libxml2-dev \
    libxslt-dev groff zip \
    pkg-config ca-certificates \
    && apt-get clean

# Install rbenv
RUN git clone https://github.com/sstephenson/rbenv.git /usr/local/rbenv \
    && echo '# rbenv setup' > /etc/profile.d/rbenv.sh \
    && echo 'export RBENV_ROOT=/usr/local/rbenv' >> /etc/profile.d/rbenv.sh \
    && echo 'export PATH="$RBENV_ROOT/bin:$PATH"' >> /etc/profile.d/rbenv.sh \
    && echo 'eval "$(rbenv init -)"' >> /etc/profile.d/rbenv.sh \
    && chmod +x /etc/profile.d/rbenv.sh

ENV RUBY_VERSION=2.3.1

# install ruby-build
RUN mkdir /usr/local/rbenv/plugins \
    && git clone https://github.com/sstephenson/ruby-build.git /usr/local/rbenv/plugins/ruby-build \
    && /usr/local/rbenv/plugins/ruby-build/install.sh \
    && rbenv install ${RUBY_VERSION} \
    && rbenv global ${RUBY_VERSION} \
    && gem install bundler \
    && rbenv rehash
</code>```

Some tests

```<code>$ docker run -it --rm test rbenv version
2.3.1 (set by /usr/local/rbenv/version)

$ docker run -it --rm test ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
</code>```

Body:
While installing ruby with rbenv for Ubuntu 16.04 error regarding the ruby build is shown.
I've tried completely removing the rbenv and again re-installing rbenv, but all i get the following error.

I've followed DigitalOcean's procedure for installing the rbenv as in here, and followed steps listed here for ruby_build. I've also installed all dependencies required for the build.

Still after times of uninstall and install of rbenv problem is the same.

   ~$ rbenv install 2.3.1
   Downloading ruby-2.3.1.tar.bz2...
   -> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.1.tar.bz2
   Installing ruby-2.3.1...

   BUILD FAILED (Ubuntu 16.04 using ruby-build 20170726-2-g254728e)

   Inspect or clean up the working tree at /tmp/build.20170818162042.1074
   Results logged to /tmp/ruby-build.20170818162042.1074.log

   Last 10 log lines:
   linking shared-object objspace.so
   make[2]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1/ext/objspace'
   installing default date_core libraries
   linking shared-object date_core.so
   make[2]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1/ext/date'
   linking shared-object nkf.so
   make[2]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1/ext/nkf'
   make[1]: Leaving directory '/tmp/ruby-build.20170818162042.1074/ruby-2.3.1'
   uncommon.mk:203: recipe for target 'build-ext' failed
   make: *** [build-ext] Error 2

Result of cat /tmp/ruby-build.20170818162042.1074.log

In file included from ossl.h:57:0,
                 from ossl_bn.c:11:
/usr/include/openssl/asn1_mac.h:10:2: error: #error "This file is obsolete; please update your software."
 #error "This file is obsolete; please update your software."
  ^
In file included from ossl.h:221:0,
                 from ossl_bn.c:11:
openssl_missing.h:78:35: error: macro "EVP_MD_CTX_create" passed 1 arguments, but takes just 0
 EVP_MD_CTX *EVP_MD_CTX_create(void);
                                   ^
In file included from /usr/include/openssl/x509.h:23:0,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
openssl_missing.h:82:6: error: expected declaration specifiers or ‘...’ before ‘(’ token
 void EVP_MD_CTX_init(EVP_MD_CTX *ctx);
      ^
openssl_missing.h:90:6: error: expected declaration specifiers or ‘...’ before ‘(’ token
 void EVP_MD_CTX_destroy(EVP_MD_CTX *ctx);
      ^
ossl_bn.c: In function ‘ossl_bn_size’:
ossl_bn.c:43:19: error: invalid application of ‘sizeof’ to incomplete type ‘BIGNUM {aka struct bignum_st}’
     return sizeof(BIGNUM);
                   ^
ossl_bn.c: In function ‘ossl_bn_s_generate_prime’:
ossl_bn.c:769:5: warning: ‘BN_generate_prime’ is deprecated [-Wdeprecated-declarations]
     if (!BN_generate_prime(result, num, safe, add, rem, NULL, NULL)) {
     ^
In file included from /usr/include/openssl/bn.h:31:0,
                 from /usr/include/openssl/asn1.h:24,
                 from /usr/include/openssl/objects.h:916,
                 from /usr/include/openssl/evp.h:27,
                 from /usr/include/openssl/x509.h:23,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
/usr/include/openssl/bn.h:285:1: note: declared here
 DEPRECATEDIN_0_9_8(BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe,
 ^
ossl_bn.c: In function ‘ossl_bn_is_prime’:
ossl_bn.c:877:5: warning: ‘BN_is_prime’ is deprecated [-Wdeprecated-declarations]
     switch (BN_is_prime(bn, checks, NULL, ossl_bn_ctx, NULL)) {
     ^
In file included from /usr/include/openssl/bn.h:31:0,
                 from /usr/include/openssl/asn1.h:24,
                 from /usr/include/openssl/objects.h:916,
                 from /usr/include/openssl/evp.h:27,
                 from /usr/include/openssl/x509.h:23,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
/usr/include/openssl/bn.h:291:1: note: declared here
 DEPRECATEDIN_0_9_8(int
 ^
ossl_bn.c: In function ‘ossl_bn_is_prime_fasttest’:
ossl_bn.c:916:5: warning: ‘BN_is_prime_fasttest’ is deprecated [-Wdeprecated-declarations]
     switch (BN_is_prime_fasttest(bn, checks, NULL, ossl_bn_ctx, NULL, do_trial_division)) {
     ^
In file included from /usr/include/openssl/bn.h:31:0,
                 from /usr/include/openssl/asn1.h:24,
                 from /usr/include/openssl/objects.h:916,
                 from /usr/include/openssl/evp.h:27,
                 from /usr/include/openssl/x509.h:23,
                 from /usr/include/openssl/x509v3.h:14,
                 from ossl.h:58,
                 from ossl_bn.c:11:
/usr/include/openssl/bn.h:295:1: note: declared here
 DEPRECATEDIN_0_9_8(int
 ^
ossl_bn.c: In function ‘ossl_bn_size’:
ossl_bn.c:44:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^
Makefile:301: recipe for target 'ossl_bn.o' failed

Body:
I was able to successfully build docker image with the following Dockerfile

FROM ubuntu:16.04

ENV RBENV_ROOT=/usr/local/rbenv
ENV PATH=$RBENV_ROOT/bin:$RBENV_ROOT/shims:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    cmake curl git zlib1g-dev \
    libssl-dev libreadline-dev \
    libyaml-dev libxml2-dev \
    libxslt-dev libsqlite3-dev \
    python-dev libxml2-dev \
    libxslt-dev groff zip \
    pkg-config ca-certificates \
    && apt-get clean

# Install rbenv
RUN git clone https://github.com/sstephenson/rbenv.git /usr/local/rbenv \
    && echo '# rbenv setup' > /etc/profile.d/rbenv.sh \
    && echo 'export RBENV_ROOT=/usr/local/rbenv' >> /etc/profile.d/rbenv.sh \
    && echo 'export PATH="$RBENV_ROOT/bin:$PATH"' >> /etc/profile.d/rbenv.sh \
    && echo 'eval "$(rbenv init -)"' >> /etc/profile.d/rbenv.sh \
    && chmod +x /etc/profile.d/rbenv.sh

ENV RUBY_VERSION=2.3.1

# install ruby-build
RUN mkdir /usr/local/rbenv/plugins \
    && git clone https://github.com/sstephenson/ruby-build.git /usr/local/rbenv/plugins/ruby-build \
    && /usr/local/rbenv/plugins/ruby-build/install.sh \
    && rbenv install ${RUBY_VERSION} \
    && rbenv global ${RUBY_VERSION} \
    && gem install bundler \
    && rbenv rehash

Some tests

$ docker run -it --rm test rbenv version
2.3.1 (set by /usr/local/rbenv/version)

$ docker run -it --rm test ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]


问:
swift display an image in another view controller when pressed button
How to display an image in another view controller when pressing on button? I have two button and pressing first button, it should show an image, pressing another button, it should show an another image. I don't want the use View Controller for each button.I watched some videos about segues but i couldn't. </p>

答:
Create 2 segues (1 for each button). You do this in storyboard by control dragging from the button to the image view controller. Then click on the segue it self and select Attributes inspector in storyboard and write "firstSegue" as the identifier for the first segue and "secondSegue" as the identifier for the second segue.

add this to the view controller with the buttons:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "firstSegue" {

        if let destinationVC = segue.destination as? NameOfViewControllerWithImage {
            destinationVC.myimage = self.imagetoset
        }
    }
    else if segue.identifier == "secondSegue" {

        if let destinationVC = segue.destination as? NameOfViewControllerWithImage {
            destinationVC.myimage = self.someotherimagetoset
        }
    }

}
</code>```

add an imageView and this code to the view controller with the image

```<code>var myimage: UIImage?
override func viewWillAppear(_ animated: Bool) {
    self.imageView.image = myimage
}
</code>```

Body:
Create 2 segues (1 for each button). You do this in storyboard by control dragging from the button to the image view controller. Then click on the segue it self and select Attributes inspector in storyboard and write "firstSegue" as the identifier for the first segue and "secondSegue" as the identifier for the second segue.

add this to the view controller with the buttons:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "firstSegue" {

        if let destinationVC = segue.destination as? NameOfViewControllerWithImage {
            destinationVC.myimage = self.imagetoset
        }
    }
    else if segue.identifier == "secondSegue" {

        if let destinationVC = segue.destination as? NameOfViewControllerWithImage {
            destinationVC.myimage = self.someotherimagetoset
        }
    }

}

add an imageView and this code to the view controller with the image

var myimage: UIImage?
override func viewWillAppear(_ animated: Bool) {
    self.imageView.image = myimage
}


问:
How to addClass to one button in button group via jQuery?
I have a HTML table with a button group on each row. When the user selects a button I want to highlight that button, and not the others. I'm trying to use a class in order to do this. But, how can I remove this class from the other 2 buttons?

```<code>.selectedAnswer {
  font-weight: bold;
  border: 1px solid blue;
}

 <table>
  <tr>
    <td>
      Question 1
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      Question 2
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      Question 3
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      Question 4
    </td>
    <td>
      <div class="btn-group" role="group" aria-label="..." id="Rating">
        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>
      </div>
    </td>
  </tr>

</table>
</code>```

Here is the jQuery...

```<code>//Set up click event on the Remove button
$('.btn-response').click(function(event) {
  $(this).addClass("selectedAnswer");
});
</code>```

Link: https://jsfiddle.net/webdevguy2/0mzjyvw2/2/

Any suggestions on a better way to do this?

答:
Read about .siblings() in the jQuery API.

Change this:

```<code>$('.btn-response').click(function (event) {
  $(this).addClass("selectedAnswer");
});
</code>```

To this:

```<code>$('.btn-response').click(function (event) {
  $(this).addClass("selectedAnswer").siblings().removeClass("selectedAnswer");
});
</code>```

Body:
I have a HTML table with a button group on each row. When the user selects a button I want to highlight that button, and not the others. I'm trying to use a class in order to do this. But, how can I remove this class from the other 2 buttons?

.selectedAnswer {
  font-weight: bold;
  border: 1px solid blue;
}

      Question 1

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

      Question 2

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

      Question 3

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

      Question 4

        <button type="button" id="btnYes" value="yes" class="btn btn-default btn-response" data-rating="Yes">Yes</button>
        <button type="button" id="btnNo" value="no" class="btn btn-default btn-response" data-rating="No">No</button>
        <button type="button" id="btnNa" value="na" class="btn btn-default btn-response" data-rating="NA">N/A</button>

Here is the jQuery...

//Set up click event on the Remove button
$('.btn-response').click(function(event) {
  $(this).addClass("selectedAnswer");
});

Link: https://jsfiddle.net/webdevguy2/0mzjyvw2/2/

Any suggestions on a better way to do this?

Body:
Read about .siblings() in the jQuery API.

Change this:

$('.btn-response').click(function (event) {
  $(this).addClass("selectedAnswer");
});

To this:

$('.btn-response').click(function (event) {
  $(this).addClass("selectedAnswer").siblings().removeClass("selectedAnswer");
});


问:
PowerShell - Import-CSV and cross reference
I am running a script as below:

```<code>$Users = Import-Csv List.csv

Foreach ($User in $Users) {
 $To = $User.email
 $Name = $User.f_name
 $Domain = $User.l_name
</code>```

I want to be able to check $user.email against List2.csv and if it does exist in List2.csv then to skip this email address

The format of csv's is as follows:

```<code>List.csv is: f_name, l_name, email
List2.csv is: email
</code>```

Another thing, if not too complicated, would be to have wildcard domains in List2.csv.

答:
Does this give you what you want?

```<code>(Import-Csv List.csv |? {$_.email -notin $(Import-Csv List2.csv).email}).email
</code>```

Essentially you're just both CSVs as arrays and using the -notin param to filter.

For wildcards you could experiment with -notlike.

Body:
I am running a script as below:

$Users = Import-Csv List.csv

Foreach ($User in $Users) {
 $To = $User.email
 $Name = $User.f_name
 $Domain = $User.l_name

I want to be able to check $user.email against List2.csv and if it does exist in List2.csv then to skip this email address

The format of csv's is as follows:

List.csv is: f_name, l_name, email
List2.csv is: email

Another thing, if not too complicated, would be to have wildcard domains in List2.csv.

Body:
Does this give you what you want?

(Import-Csv List.csv |? {$_.email -notin $(Import-Csv List2.csv).email}).email

Essentially you're just both CSVs as arrays and using the -notin param to filter.

For wildcards you could experiment with -notlike.


问:
How to change an ImageButton image after a while?
How can i change an ImageButton image after a specified amount of time without touching it, in Android Studio?

Thanks!

答:
Did you write any logic ? Can help you correct your code if you have written anything..
Write a timer and change the image after the time has elapsed. </p>


问:
looping regex in directory and saving output
I was able to run the regex on multiple files, I want to save the output of this like name_of_file_clean.txt.

Trying to find the best way.

```<code>import os, re
import glob

pattern = re.compile(r'(?<=CN=)(.*?)(?=,)')
for file in glob.glob('*.txt'):
    with open(file) as fp:
        for result in pattern.findall(fp.read()):
           print(result)
</code>```

答:
We'll just open the output file and use the print functions file keyword argument to write to the file

```<code>import os, re
import glob

pattern = re.compile(r'(?<=CN=)(.*?)(?=,)')
for file in glob.glob('*.txt'):
    with open(file) as fp:
        with open(file[:-4] + '_clean.txt', 'w') as outfile:
            for result in pattern.findall(fp.read()):
               print(result, file=outfile)
</code>```

Body:
I was able to run the regex on multiple files, I want to save the output of this like name_of_file_clean.txt.

Trying to find the best way.

import os, re
import glob

pattern = re.compile(r'(?<=CN=)(.*?)(?=,)')
for file in glob.glob('*.txt'):
    with open(file) as fp:
        for result in pattern.findall(fp.read()):
           print(result)

Body:
We'll just open the output file and use the print functions file keyword argument to write to the file

import os, re
import glob

pattern = re.compile(r'(?<=CN=)(.*?)(?=,)')
for file in glob.glob('*.txt'):
    with open(file) as fp:
        with open(file[:-4] + '_clean.txt', 'w') as outfile:
            for result in pattern.findall(fp.read()):
               print(result, file=outfile)