问:
Using spark_apply in sparklyr to add weighted random normal vectors to multiple DF columns
I'm new to sparklyr and I'm trying to add random normal vectors weighted by another vector to a large number of columns of a spark df. This is an example I've tried with mtcars.

```<code>library(sparklyr)
library(dplyr)
sc1 <- spark_connect(master = "local")

mtc_df = select(mtcars, vs:carb)
mtc_sdf = sdf_copy_to(sc1, mtc_df, name = "mtc_sdf", overwrite = TRUE)

tf_df <- function(df1){
    df1 %>%
        mutate_at(vars(am:carb), funs(. + vs * rnorm(32, 100, 1)))
}

tf_df(mtc_df) # works

mtc_sdf %>%
    spark_apply(function(d) tf_df(d), memory = TRUE) # doesn't work
</code>```

I get the following error:

```<code>Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
  cannot open file 'C:\....\filea54a7656c3_spark.log': Permission denied
</code>```

I also tried to adapt the example on https://spark.rstudio.com/ but got the same error.

```<code>mtc_sdf %>%
    spark_apply(function(data) {
        data[2:4] + data[1]*rnorm(32*3,100,1)
    })
</code>```

Any help would be much appreciated.

答:
I'm trying to add random normal vectors weighted by another vector to a large number of columns of a spark df

I would recommend skipping spark_apply and using Spark's own randn (which gives ~N(0, 1)):

```<code>mtc_sdf %>% mutate_at(vars(am:carb), funs(. + vs * (randn() * 1 + 100)))
</code>```

# Source:   lazy query [?? x 4]
# Database: spark_connection
      vs        am     gear      carb
   <dbl>     <dbl>    <dbl>     <dbl>
 1     0   1.00000   4.0000   4.00000
 2     0   1.00000   4.0000   4.00000
 3     1 101.36894 103.1954  98.80757
 4     1 100.79066 102.6765 100.91702
 5     0   0.00000   3.0000   2.00000
 6     1 100.07964 103.1568 100.54303
 7     0   0.00000   3.0000   4.00000
 8     1 101.90050 103.0402 101.46825
 9     1  99.63565 103.7781 101.65752
10     1  99.72587 102.3854 105.09205
```

<p>Regarding your code:</p>

<ul>
<li>Problem you experience looks like permission issue. Please make sure that Spark user has all required permission and <code>winutilis</code> are properly used.</li>
<li><p>Function used with <code>spark_apply</code>:</p>

<blockquote>
  <p>transforms a data frame partition into a data frame. </p>
</blockquote>

<p>So you cannot hard code number of rows. You should rather use something like <code>rnorm(nrow(df1), 100, 1))</code>.</p></li>
<li><p><code>sparklyr</code> doesn't seem to properly serialize functions referenced by name so you might have to inline the function or wrap it in a package:</p>

```mtc_sdf %>%
  spark_apply(function(df) dplyr::mutate_at(
    df, dplyr::vars(am:carb), dplyr::funs(. + vs * rnorm(nrow(df), 100, 1))))
```

<pre class="lang-none prettyprint-override"><code># Source:   table<sparklyr_tmp_34ce7faa2d33> [?? x 4]
# Database: spark_connection
      vs        am     gear      carb
   <dbl>     <dbl>    <dbl>     <dbl>
 1     0   1.00000   4.0000   4.00000
 2     0   1.00000   4.0000   4.00000
 3     1 100.59678 101.9111 100.99830
 4     1  98.87146 104.8058  99.20102
 5     0   0.00000   3.0000   2.00000
 6     1  99.38243 102.8664 100.37921
 7     0   0.00000   3.0000   4.00000
 8     1  98.99019 103.4996 101.69110
 9     1  99.33687 102.3849 103.38833
10     1 100.02103 104.9381 102.07139
# ... with more rows
</code>```

Also please not that packages from the driver are not attached automatically so you have to do it manually or reference library functions using fully qualified names.

Body:
I'm new to sparklyr and I'm trying to add random normal vectors weighted by another vector to a large number of columns of a spark df. This is an example I've tried with mtcars.

library(sparklyr)
library(dplyr)
sc1 <- spark_connect(master = "local")

mtc_df = select(mtcars, vs:carb)
mtc_sdf = sdf_copy_to(sc1, mtc_df, name = "mtc_sdf", overwrite = TRUE)

tf_df <- function(df1){
    df1 %>%
        mutate_at(vars(am:carb), funs(. + vs * rnorm(32, 100, 1)))
}

tf_df(mtc_df) # works

mtc_sdf %>%
    spark_apply(function(d) tf_df(d), memory = TRUE) # doesn't work

I get the following error:

Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
  cannot open file 'C:\....\filea54a7656c3_spark.log': Permission denied

I also tried to adapt the example on https://spark.rstudio.com/ but got the same error.

mtc_sdf %>%
    spark_apply(function(data) {
        data[2:4] + data[1]*rnorm(32*3,100,1)
    })

Any help would be much appreciated.

Body:
I'm trying to add random normal vectors weighted by another vector to a large number of columns of a spark df

I would recommend skipping spark_apply and using Spark's own randn (which gives ~N(0, 1)):

mtc_sdf %>% mutate_at(vars(am:carb), funs(. + vs * (randn() * 1 + 100)))

# Source:   lazy query [?? x 4]
# Database: spark_connection
      vs        am     gear      carb
   <dbl>     <dbl>    <dbl>     <dbl>
 1     0   1.00000   4.0000   4.00000
 2     0   1.00000   4.0000   4.00000
 3     1 101.36894 103.1954  98.80757
 4     1 100.79066 102.6765 100.91702
 5     0   0.00000   3.0000   2.00000
 6     1 100.07964 103.1568 100.54303
 7     0   0.00000   3.0000   4.00000
 8     1 101.90050 103.0402 101.46825
 9     1  99.63565 103.7781 101.65752
10     1  99.72587 102.3854 105.09205

Regarding your code:

Problem you experience looks like permission issue. Please make sure that Spark user has all required permission and winutilis are properly used.

Function used with spark_apply:

transforms a data frame partition into a data frame.

So you cannot hard code number of rows. You should rather use something like rnorm(nrow(df1), 100, 1)).

sparklyr doesn't seem to properly serialize functions referenced by name so you might have to inline the function or wrap it in a package:

mtc_sdf %>%
  spark_apply(function(df) dplyr::mutate_at(
    df, dplyr::vars(am:carb), dplyr::funs(. + vs * rnorm(nrow(df), 100, 1))))

# Source:   table<sparklyr_tmp_34ce7faa2d33> [?? x 4]
# Database: spark_connection
      vs        am     gear      carb
   <dbl>     <dbl>    <dbl>     <dbl>
 1     0   1.00000   4.0000   4.00000
 2     0   1.00000   4.0000   4.00000
 3     1 100.59678 101.9111 100.99830
 4     1  98.87146 104.8058  99.20102
 5     0   0.00000   3.0000   2.00000
 6     1  99.38243 102.8664 100.37921
 7     0   0.00000   3.0000   4.00000
 8     1  98.99019 103.4996 101.69110
 9     1  99.33687 102.3849 103.38833
10     1 100.02103 104.9381 102.07139
# ... with more rows

Also please not that packages from the driver are not attached automatically so you have to do it manually or reference library functions using fully qualified names.


来源: stackexchange

问:
Is it possible to send a message to all threads?
I'm using message queues (provided by windows) to help several threads in my program communicate. However, I need to send a message to all threads in my program at once. Is there any function to do this?</p>

答:
Plain thread messages (without a window) are unreliable in Windows --- there are circumstances under which they get swallowed without a trace, and without your thread getting a chance to handle them. I therefore like to have a top-level window per thread for the message target, since window-targetted messages always get processed by the window procedure for that window. You can make it a message-only window (with a parent of HWND_MESSAGE) if you don't need a visible window for that thread.

Once you have a window for each thread, you can just enumerate the windows with EnumWindows or EnumChildWindows, and send messages to the ones you want. Or, you can keep a list of thread message windows, and send a message to each. There is no simple way to send a message to all threads in a process.

ContentLicense: CC BY-SA 2.5


问:
Pandas: Selecting value from preceding row and different column
I need to make a new dataframe from an existing one. The example below will explain what I mean. For each value in column2 and column3 I need to make a new row that includes the value from column1 that precedes it. I'm not sure how to select that value using pandas.

```<code>index column1 column2 column3
  0    shop1
  1             34       0
  2             32       0
  3             35       1
  4    shop2
  5             52       1
  6             57       0
</code>```

Resulting dataframe:

```<code>index column1 column2 column3
  0    shop1    34       0
  1    shop1    32       0
  2    shop1    35       1
  3    shop2    52       1
  4    shop2    57       0
</code>```

I've searched stackoverflow and the pandas documentation, but cannot find how to do this. Any help is appreciated, thank you.

答:
Use ffill() and dropna:

```<code>df.assign(column1=df.column1.ffill()).dropna()
</code>```

Output:

```<code>   index column1  column2  column3
1      1   shop1     34.0      0.0
2      2   shop1     32.0      0.0
3      3   shop1     35.0      1.0
5      5   shop2     52.0      1.0
6      6   shop2     57.0      0.0
</code>```

And, if you want to cleanup index:

df.assign(column1=df.column1.ffill()).dropna().drop('index',1).reset_index(drop=True)

```<code>  column1  column2  column3
0   shop1     34.0      0.0
1   shop1     32.0      0.0
2   shop1     35.0      1.0
3   shop2     52.0      1.0
4   shop2     57.0      0.0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to make a new dataframe from an existing one. The example below will explain what I mean. For each value in column2 and column3 I need to make a new row that includes the value from column1 that precedes it. I'm not sure how to select that value using pandas.

index column1 column2 column3
  0    shop1
  1             34       0
  2             32       0
  3             35       1
  4    shop2
  5             52       1
  6             57       0

Resulting dataframe:

index column1 column2 column3
  0    shop1    34       0
  1    shop1    32       0
  2    shop1    35       1
  3    shop2    52       1
  4    shop2    57       0

I've searched stackoverflow and the pandas documentation, but cannot find how to do this. Any help is appreciated, thank you.

Body:
Use ffill() and dropna:

df.assign(column1=df.column1.ffill()).dropna()

Output:

   index column1  column2  column3
1      1   shop1     34.0      0.0
2      2   shop1     32.0      0.0
3      3   shop1     35.0      1.0
5      5   shop2     52.0      1.0
6      6   shop2     57.0      0.0

And, if you want to cleanup index:

df.assign(column1=df.column1.ffill()).dropna().drop('index',1).reset_index(drop=True)

  column1  column2  column3
0   shop1     34.0      0.0
1   shop1     32.0      0.0
2   shop1     35.0      1.0
3   shop2     52.0      1.0
4   shop2     57.0      0.0


答:
If those are blanks you would need to make N/A first

```<code>import pandas as pd

df = pd.DataFrame(dict(column1=["shop1","","","shop2",""],column2=["",34,32,"",35]))
df = df.mask(df == '')
df.column1 = df.column1.fillna(method='pad')
df = df.dropna(axis=0,how='any').reset_index(drop=True)

print(df)
</code>```

Returns:

```<code>  column1 column2
0   shop1      34
1   shop1      32
2   shop2      35
</code>```

Title: Pandas: Selecting value from preceding row and different column

Body:
If those are blanks you would need to make N/A first

import pandas as pd

df = pd.DataFrame(dict(column1=["shop1","","","shop2",""],column2=["",34,32,"",35]))
df = df.mask(df == '')
df.column1 = df.column1.fillna(method='pad')
df = df.dropna(axis=0,how='any').reset_index(drop=True)

print(df)

Returns:

  column1 column2
0   shop1      34
1   shop1      32
2   shop2      35


问:
Reading "Awkward" CSV Files with FSharp CsvParser
I have a large file (200K - 300K lines of text).
It's almost but not quite a CSV file.

The column headers are on the second row, there's a row of dummy text

before that.

There are rows interspersed with the actual data rows. They have
commas, but most of the columns are blank. They aren't relevant to me.

I need to read this file efficiently, and parse the lines that actually are
valid, as CSV data.

My first idea was to write a clean procedure that strips out the first line, and the blank lines, leaving only the headers and details that I want
in a CSV File that the CsvParser can read.

This is easy enough, just ReadLine from a StreamReader, I can keep or disregard each line just by looking at it as a string.

Now though I have a new issue.

There is a column in the valid data that I can use to disregard a whole lot more rows.

If I read the Cleaned file using the CsvParser it's easy to filter by that column.

But, I don't really want to waste writing the rows I don't need to the Clean file.

I'd like to be able to check that Column, while Cleaning the File. But, at that point I'm working with strings representing entire lines. It's not easy to get at the specific column I want.

I can't Split on ',' there may be commas in the text of other columns.
I'm ending up writing the Csv Parsing Logic, that I was using CsvParser for in the first place.

Ideally, I'd like to read in the existing file, clean out the lines that I can based on strings, then somehow parse the resulting seq using the CsvParser.

I see CsvFile can Load from Streams and Readers, but I'm not sure that's much help.

Any suggestions or am I just asking too much? Should I just deal with the extra filtering on loading the Cleaned File?

答:
You can avoid doing most of the work of parsing by using the CsvFile class directly.

The F# Data documentation has some extended examples that show how to do this in some detail.

Skipping over lines at the start of a file is handled by the skipRows parameter. Passing the ignoreErrors parameter will also ignore rows that fail to parse.

```<code>open FSharp.Data
let csv = CsvFile.Load(file, skipRows=1, ignoreErrors=true)
for row in csv.Rows do
    printfn "%s" row.GetColumn "Name"
</code>```

If you have to do more complex filtering of rows, a simple approach that doesn't require temporary files is to filter the results of File.ReadLines and pass that to CsvFile.Parse.

The example below skips a six-line prelude, reads in lines until it hits a blank line, uses CsvFile to parse the data, and finally filters the resulting rows to those of interest.

```<code>let tableA =
    File.ReadLines(file)
    |> Seq.skip(6)
    |> Seq.takeWhile(fun l -> String.length l > 0)
    |> String.concat "\n"

let csv = CsvFile.Parse(tableA)
for row in csv.Rows.Filter(fun row -> row?Close.AsFloat() > row?Open.AsFloat()) do
    printfn "%s" row.GetColumn "Name"
</code>```

Body:
You can avoid doing most of the work of parsing by using the CsvFile class directly.

The F# Data documentation has some extended examples that show how to do this in some detail.

Skipping over lines at the start of a file is handled by the skipRows parameter. Passing the ignoreErrors parameter will also ignore rows that fail to parse.

open FSharp.Data
let csv = CsvFile.Load(file, skipRows=1, ignoreErrors=true)
for row in csv.Rows do
    printfn "%s" row.GetColumn "Name"

If you have to do more complex filtering of rows, a simple approach that doesn't require temporary files is to filter the results of File.ReadLines and pass that to CsvFile.Parse.

The example below skips a six-line prelude, reads in lines until it hits a blank line, uses CsvFile to parse the data, and finally filters the resulting rows to those of interest.

let tableA =
    File.ReadLines(file)
    |> Seq.skip(6)
    |> Seq.takeWhile(fun l -> String.length l > 0)
    |> String.concat "\n"

let csv = CsvFile.Parse(tableA)
for row in csv.Rows.Filter(fun row -> row?Close.AsFloat() > row?Open.AsFloat()) do
    printfn "%s" row.GetColumn "Name"


问:
Android User Interface Scaling
I have a project I am working on where the UI I have developed looks great on a 7" tablet, but the moment I try to use the app on a 10" tablet there is a lot of extra space to the right and bottom of my UI elements. Is there a way to scale UI elements to be bigger based on the size of the screen?

I need the UI to look exactly the same on every resolution possible. It should be noted that I am restricted to Eclipse and am programming on an older version of Android because the utilities I have been supplied with are older utilities.

Wish I could supply a screenshot, but I 100% cannot.

答:
You can use different layouts for different screen sizes.
    layout-sw600dp ( for 7 inch tablets)
    layout-sw720dp ( for 10 inch tablets)

The system will automatically pick the layout per current device size. Just make sure to have the same layout name and id of the components in the layouts or it might cause exceptions if mismatch is found.

If you want completely different layouts for different sizes ( file names still have to be the same ), you can determine which kind of device it is, you can follow the description in the following's accepted answer.

Determine if the device is a smartphone or tablet?

Now using the above method, you can find appropriate views using IDs or whatever way you prefer without causing exception. I personally just change the dimensions of things and keep the ids same.

Title: Android User Interface Scaling


问:
Handling layouts using nested Vue.js components
We have been using Vue.js at my company for the last few months and we're really liking it! We are using Element UI for the UI and vue-router for routing. Based on the structure of our data, we nest our routes several layers deep. It looks something like this:

```<code>App ->
    Line ->
        Type ->
            Component1
            Component2
            Component3
</code>```

Our designer would like to be able to control layouts on a per-page basis, even all the way down inside of Component*. For instance, in Component1 there may be a layout with a sidebar and footer and in Component2 there would be no sidebar but the footer would be hidden.

We've found this complicated based on the nested structure. Instead of components showing up as distinct blocks on a page they are nested inside of each other. We could un-nest each Vue route, but then we run the risk of duplicating logic through a lot of the pages that are at the same level.

What's are some good ways to handle layouts in a nested structure such as this?

答:
It sounds like layouts are being specified independently of component build, so you would want to make it as orthogonal as possible.

Additional data can be added to routes in the meta property.

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { hiddenFeatures: {sidebar: true, footer: false} }
  },
  ...
```

<p>On App component, watch for route changes and set visibility flags based on the additional configuration.</p>

<pre class="lang-js prettyprint-override"><code>export default {
  name: 'app',
  data() {
    return {
      ...
      hiddenFeatures: {}
    };
  },
  watch: {
    '$route': function (route) {
      this.hiddenFeatures = route.meta.hiddenFeatures || {}
    }
  },
}
</code>```

In the App template, use conditional rendering

<template>

      <sidebar v-if="!hiddenFeatures.sidebar"></sidebar>
```

By getting the logic the right way round, you can avoid having to add properties to every single route, just (e.g) those you want to hide.

Body:
We have been using Vue.js at my company for the last few months and we're really liking it! We are using Element UI for the UI and vue-router for routing. Based on the structure of our data, we nest our routes several layers deep. It looks something like this:

App ->
    Line ->
        Type ->
            Component1
            Component2
            Component3

Our designer would like to be able to control layouts on a per-page basis, even all the way down inside of Component*. For instance, in Component1 there may be a layout with a sidebar and footer and in Component2 there would be no sidebar but the footer would be hidden.

We've found this complicated based on the nested structure. Instead of components showing up as distinct blocks on a page they are nested inside of each other. We could un-nest each Vue route, but then we run the risk of duplicating logic through a lot of the pages that are at the same level.

What's are some good ways to handle layouts in a nested structure such as this?

Body:
It sounds like layouts are being specified independently of component build, so you would want to make it as orthogonal as possible.

Additional data can be added to routes in the meta property.

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { hiddenFeatures: {sidebar: true, footer: false} }
  },
  ...

On App component, watch for route changes and set visibility flags based on the additional configuration.

export default {
  name: 'app',
  data() {
    return {
      ...
      hiddenFeatures: {}
    };
  },
  watch: {
    '$route': function (route) {
      this.hiddenFeatures = route.meta.hiddenFeatures || {}
    }
  },
}

In the App template, use conditional rendering

<template>
  <div id="app">
    <div class="container-fluid">
      <sidebar v-if="!hiddenFeatures.sidebar"></sidebar>

By getting the logic the right way round, you can avoid having to add properties to every single route, just (e.g) those you want to hide.


问:
How to get user information from ldap?
I am using apache shiro for ldap authentification:

```<code>Factory<SecurityManager> ldapFactory = new IniSecurityManagerFactory("classpath:active.ini");
SecurityManager sManager = ldapFactory.getInstance();
SecurityUtils.setSecurityManager(sManager);

Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
            try {
                currentUser.login(token);
            } catch (UnknownAccountException ex) {
                logger.info("Unknown user");
            } catch (IncorrectCredentialsException ex) {
                logger.info("Incorrect credentials");
            } catch (LockedAccountException ex) {
                logger.info("Account is Locked");
            } catch (AuthenticationException ex) {
                logger.info("Authentication Exception");
            }
        }

        logger.info("User [" + currentUser.getPrincipal() +"] logged succesfully");
        currentUser.logout();
</code>```

Calling currentUser.getPrincipal(), I've got only email address from the logged user.

How to get more user information, for example lastname, firstname, etc?

答:
getPrincipal() only returns the subject's identifier. Try to use getPrincipals() instead.

Object getPrincipal()

  Returns this Subject's application-wide uniquely identifying
  principal, or null if this Subject is anonymous.

PrincipalCollection getPrincipals()

  Returns this Subject's principals
  (identifying attributes) in the form of a PrincipalCollection or null
  if this Subject is anonymous

Apache Shiro API (JavaDoc)

Title: How to get user information from ldap?

Body:
I am using apache shiro for ldap authentification:

Factory<SecurityManager> ldapFactory = new IniSecurityManagerFactory("classpath:active.ini");
SecurityManager sManager = ldapFactory.getInstance();
SecurityUtils.setSecurityManager(sManager);

Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
            try {
                currentUser.login(token);
            } catch (UnknownAccountException ex) {
                logger.info("Unknown user");
            } catch (IncorrectCredentialsException ex) {
                logger.info("Incorrect credentials");
            } catch (LockedAccountException ex) {
                logger.info("Account is Locked");
            } catch (AuthenticationException ex) {
                logger.info("Authentication Exception");
            }
        }

        logger.info("User [" + currentUser.getPrincipal() +"] logged succesfully");
        currentUser.logout();

Calling currentUser.getPrincipal(), I've got only email address from the logged user.

How to get more user information, for example lastname, firstname, etc?


问:
Saving a json file in Javascript by overwrighting the previous one
I am a beginner in JS and trying to generate a json format file and saving it through this code

```<code><script>
    var jsonArr=[];
//Generating 5 random test data for json array
for(var i = 0; i < 5; i++) {
    jsonArr.push({
        team: "teamA",
        matchname: "Match1",
        score: "32"
    });  }
json_str = JSON.stringify(jsonArr); //stringify json

//Save file function
saveFile('yourfilename.json', "data:application/json", new Blob([json_str],{type:""}));

function saveFile (name, type, data) {
    if (data != null && navigator.msSaveBlob)
        return navigator.msSaveBlob(new Blob([data], { type: type }), name);

    var a = $("<a style='display: none;'/>");
    var url = window.URL.createObjectURL(new Blob([data], {type: type}));
    a.attr("href", url);
    a.attr("download", name);
    $("body").append(a);
    a[0].click();
    setTimeout(function(){  // fixes firefox html removal bug
        window.URL.revokeObjectURL(url);
        a.remove();
    }, 500);
}

</script>
</code>```

This code is working but i want to save this file to a specific directory with overwriting the previous saved file.If anybody can help?
Thanks

答: It isn't possible with Javascript to access the file system of the client. You can only prompt the user with a download dialog or force a download to the default download directory.</p>

Body:
I am a beginner in JS and trying to generate a json format file and saving it through this code

This code is working but i want to save this file to a specific directory with overwriting the previous saved file.If anybody can help?
Thanks


问:
Link error when using lex and yacc output in Visual Studio
I am using this windows version of flex (lex) and bison (yacc) to port my query compiler from linux to Windows.
The output files, lex.yy.c, y.tab.c and y.tab.h are getting generated properly.
However, I am getting the following link error.

```<code>Error 29 error LNK2001: unresolved external symbol _yylval G:\Project\lex.yy.obj QC
Error 30 error LNK1120: 1 unresolved externals G:\Project\QC.exe QC
</code>```

I tried copying the above files generated by the original linux versions of flex and yacc to Visual studio project folder. But that too gives the same link error.

答:
This could happen because you're mixing C++ and C files together in one project.  So if you're including y.tab.h into a .cpp file then make sure it has extern "C" { ... } around it.  Like this:

```<code>extern "C"
{
    #include "y.tab.h"
}
</code>```

Update:  From your comment I understood that y.tab.c is y.tab.cc now.  This causes a link time error.  This could be fixed by either making both files C++ (or C).  Or by changing yylval declaration in y.tab.h to

```<code>#ifdef __cplusplus
extern "C" YYSTYPE  yylval;
#endif
</code>```

Body:
I am using this windows version of flex (lex) and bison (yacc) to port my query compiler from linux to Windows.
The output files, lex.yy.c, y.tab.c and y.tab.h are getting generated properly.
However, I am getting the following link error.

Error 29 error LNK2001: unresolved external symbol _yylval G:\Project\lex.yy.obj QC
Error 30 error LNK1120: 1 unresolved externals G:\Project\QC.exe QC

I tried copying the above files generated by the original linux versions of flex and yacc to Visual studio project folder. But that too gives the same link error.

Body:
This could happen because you're mixing C++ and C files together in one project.  So if you're including y.tab.h into a .cpp file then make sure it has extern "C" { ... } around it.  Like this:

extern "C"
{
    #include "y.tab.h"
}

Update:  From your comment I understood that y.tab.c is y.tab.cc now.  This causes a link time error.  This could be fixed by either making both files C++ (or C).  Or by changing yylval declaration in y.tab.h to

#ifdef __cplusplus
extern "C" YYSTYPE  yylval;
#endif


问:
Encounter the symbol when expecting one of the following in oracle procedure
I have below procedure where I am getting error as 'PLS-00103: Encountered the symbol "." when expecting one of the following:;'. This error is occurring at the line after the commit statement.

I am quite new to writing procedures so I am not really understanding where the issue occurs. Also there might be an issue in the insert using the select query as I am outputting data from a cursor and also I am using a select query.

```<code>CREATE OR REPLACE PROCEDURE TEST
IS
TST VARCHAR2(4000):= NULL;
IN_SEQ_NO NUMBER;

CURSOR C_DB IS
 SELECT NAME, ID
    from REC_PROC;

BEGIN

select IDH_SEQ.nextval INTO IN_SEQ_NO from dual;

COMMIT;

END LOOP;

END TEST;
</code>```

答:
Add FOR rec IN C_DB LOOP instruction to your procedure:

```<code>CREATE OR REPLACE PROCEDURE TEST
IS
    TST       VARCHAR2(4000):= NULL;
    IN_SEQ_NO NUMBER;

    CURSOR C_DB IS
    SELECT NAME,
           ID
      FROM REC_PROC;

BEGIN
    FOR rec IN C_DB
    LOOP
        SELECT IDH_SEQ.nextval INTO IN_SEQ_NO from dual;
        COMMIT;
    END LOOP;
END TEST;
</code>```

or remove END LOOP;:

```<code>CREATE OR REPLACE PROCEDURE TEST
IS
    TST       VARCHAR2(4000):= NULL;
    IN_SEQ_NO NUMBER;

    CURSOR C_DB IS
    SELECT NAME,
           ID
      FROM REC_PROC;

BEGIN
    SELECT IDH_SEQ.nextval INTO IN_SEQ_NO from dual;
    COMMIT;
END TEST;
</code>```

Body:
I have below procedure where I am getting error as 'PLS-00103: Encountered the symbol "." when expecting one of the following:;'. This error is occurring at the line after the commit statement.

I am quite new to writing procedures so I am not really understanding where the issue occurs. Also there might be an issue in the insert using the select query as I am outputting data from a cursor and also I am using a select query.

CREATE OR REPLACE PROCEDURE TEST
IS
TST VARCHAR2(4000):= NULL;
IN_SEQ_NO NUMBER;

CURSOR C_DB IS
 SELECT NAME, ID
    from REC_PROC;

BEGIN

select IDH_SEQ.nextval INTO IN_SEQ_NO from dual;

COMMIT;

END LOOP;

END TEST;

Body:
Add FOR rec IN C_DB LOOP instruction to your procedure:

CREATE OR REPLACE PROCEDURE TEST
IS
    TST       VARCHAR2(4000):= NULL;
    IN_SEQ_NO NUMBER;

    CURSOR C_DB IS
    SELECT NAME,
           ID
      FROM REC_PROC;

BEGIN
    FOR rec IN C_DB
    LOOP
        SELECT IDH_SEQ.nextval INTO IN_SEQ_NO from dual;
        COMMIT;
    END LOOP;
END TEST;

or remove END LOOP;:

CREATE OR REPLACE PROCEDURE TEST
IS
    TST       VARCHAR2(4000):= NULL;
    IN_SEQ_NO NUMBER;

    CURSOR C_DB IS
    SELECT NAME,
           ID
      FROM REC_PROC;

BEGIN
    SELECT IDH_SEQ.nextval INTO IN_SEQ_NO from dual;
    COMMIT;
END TEST;


问:
case statement with multiple cases doing same operation
I need to use a case statement with the control signal being 4 bits. I have multiple cases of those 4 bits doing the same operation, how do I make the code more concise?

For ex:

```<code>  casez (fbe)  //fbe is defined as logic [3:0] fbe;
   4'b0000: begin
    // operation a
   end
   4'b???1 : begin
    // operation b
   end
</code>```

Operation a and operation b are exactly identical. How do I collapse these 2 into a single case? Something like (fbe == 4'b0000) | (fbe == 4'b???1) into a single case?

答:
In SystemVerilog, you should use the case (expression) inside statement. (§12.5.4 Set membership case statement). This lets you use the same kind of lists of expressions that the inside operator uses, like a range of values. It also has asymmetrical wildcard matching. This means only Z's in the case item become wildcards, not Z's in the case expression. For example

```<code>case (fbe) inside
  4'b0000, 4'b0??1: begin end // 0, and 1,3,7
  [9:11]: begin end // 9,10,11
  default: begin end //2,4,6,8,12-15
endcase
</code>```

If fbe was 4'bz000 for some reason, the default would be taken. casez would have matched 4'b0000.

Body:
I need to use a case statement with the control signal being 4 bits. I have multiple cases of those 4 bits doing the same operation, how do I make the code more concise?

For ex:

  casez (fbe)  //fbe is defined as logic [3:0] fbe;
   4'b0000: begin
    // operation a
   end
   4'b???1 : begin
    // operation b
   end

Operation a and operation b are exactly identical. How do I collapse these 2 into a single case? Something like (fbe == 4'b0000) | (fbe == 4'b???1) into a single case?

Body:
In SystemVerilog, you should use the case (expression) inside statement. (§12.5.4 Set membership case statement). This lets you use the same kind of lists of expressions that the inside operator uses, like a range of values. It also has asymmetrical wildcard matching. This means only Z's in the case item become wildcards, not Z's in the case expression. For example

case (fbe) inside
  4'b0000, 4'b0??1: begin end // 0, and 1,3,7
  [9:11]: begin end // 9,10,11
  default: begin end //2,4,6,8,12-15
endcase

If fbe was 4'bz000 for some reason, the default would be taken. casez would have matched 4'b0000.


问:
Manipulating Opacity and Text in D3.js
I'm trying to write a function that changes text a div, using dot-chaining and D3.

I want to select my outer div, transition it's opacity to 0, select the inner div and change the text, and then transition the outer div back to 1. So the entire thing looks something like this:

```<code>d3.select("div#outer").transition()
    .duration(200)
    .style("opacity",0)
    .transition()
    .duration(200)
    .style("opacity",1)

d3.select("div#inner").transition().delay(200).text("This is the new text")
</code>```

There's got to be a better way of doing this. Is there a way for me to combine these two selections? Ideally I would make this all one function and just call it accordingly.

答:
You could modify the inner div from within the transition on the outer div, just listen for the end for the transition that sets the outer div's opacity to zero:

```<code>d3.select("div#outer").transition()
    .duration(200)
    .style("opacity",0)
    .on("end", function() {
      d3.select("#innerDiv").html("This is new text")
    })
    .transition()
    .duration(200)
    .style("opacity",1)
</code>```

Which looks like (slowed down):

d3.select("div#outer").transition()
    .duration(2000)
    .style("opacity",0)
    .on("end", function() {
      d3.select("#inner").html("This is new text")
    })
    .transition()
    .duration(2000)
    .style("opacity",1)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#outer {
  padding: 50px;
  background-color: #ccc;
}</code>```

Some text

```

Title: Manipulating Opacity and Text in D3.js

Body:
I'm trying to write a function that changes text a div, using dot-chaining and D3.

I want to select my outer div, transition it's opacity to 0, select the inner div and change the text, and then transition the outer div back to 1. So the entire thing looks something like this:

d3.select("div#outer").transition()
    .duration(200)
    .style("opacity",0)
    .transition()
    .duration(200)
    .style("opacity",1)

d3.select("div#inner").transition().delay(200).text("This is the new text")

There's got to be a better way of doing this. Is there a way for me to combine these two selections? Ideally I would make this all one function and just call it accordingly.

Body:
You could modify the inner div from within the transition on the outer div, just listen for the end for the transition that sets the outer div's opacity to zero:

d3.select("div#outer").transition()
    .duration(200)
    .style("opacity",0)
    .on("end", function() {
      d3.select("#innerDiv").html("This is new text")
    })
    .transition()
    .duration(200)
    .style("opacity",1)

Which looks like (slowed down):

d3.select("div#outer").transition()
    .duration(2000)
    .style("opacity",0)
    .on("end", function() {
      d3.select("#inner").html("This is new text")
    })
    .transition()
    .duration(2000)
    .style("opacity",1)

#outer {
  padding: 50px;
  background-color: #ccc;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

<div id="outer">
  <div id="inner">Some text </div>
</div>


问:
Applescript to move incoming pictures to other folder with delay
I'm an applescript noob. So I don't know anything about this type of coding.

I want to make a script for a watch folder. I work with an image program that processes images. The process takes a second to create the jpg. So the folder has to wait for a few seconds to move the image to another file.

So this is what I'm looking for: Empty folder - jpg in the folder - wait 2 sec - move jpg to another folder - empty folder.

Thank you!

答:
This AppleScript will accomplish what you asked.  By the very nature of AppleScript, reading it should be very self explanatory as to what each line does:

```<code>    on adding folder items to ThisFolder after receiving SomeFiles
        set ThatFolder to POSIX file "/path/to/new/folder"

        delay 2

        repeat with TheFile in SomeFiles
            tell application "Finder" to ¬
                if name extension of (TheFile as alias) is in {"JPG", "JPEG"} then ¬
                    move TheFile to ThatFolder
        end repeat
    end adding folder items to
</code>```

This is designed to run as a folder action, which makes the folder you choose automatically monitored by MacOS so that, whenever it detects a change to that folder, it executes the script attached to it.  In this instance—as you can infer from the first line of the script—this will automatically run each time a file is added to the folder in question.

To set up a folder action:

Copy the AppleScript above into Script Editor.  Edit the second line to replace "/path/to/new/folder" with the path to the new folder into which you want your jpegs to be moved (keep the quotes).  I wouldn't bother trying to run the script from inside the editor—it won't work.  The path you type out must be in full, i.e. "/Users/Richard/Pictures/Processed" and not "~/Pictures/Processed".

Save it as whatever you like.  However, it must be saved in the following directory: ~/Library/Scripts/Folder Action Scripts where ~ indicates your Home folder (i.e. /Users/Richard/ or whatever it is).  If the folder "Folder Action Scripts" doesn't exist, create it.

Close Script Editor.  Navigate to the folder that is going to be watched, i.e. the folder that your images will be waiting initially.  Now navigate one level up, into the directory containing said folder.

Right-click on the folder and hover over the Services menu item at the bottom.  Then select Folder Actions Setup...

Enable folder actions by checking the box at the top.  If you folder doesn't already appear in the left-hand list, you can add it.  Then, in the right-hand list, click the '+' at the bottom and the script you just saved should be one of many in the list of scripts that pop up.  Select it and add it.

Make sure the check boxes next to your watched folder and your chosen script are both checked, and you're done.

Now, whenever the folder receives any files whatsoever, that script is executed.  The script will move any files with extensions .jpg or .jpeg into your new folder.  Just make sure the new folder already exists (I didn't incorporate a line to create it if it doesn't; the script will just throw an error and your image won't be moved).

Body:
This AppleScript will accomplish what you asked.  By the very nature of AppleScript, reading it should be very self explanatory as to what each line does:

    on adding folder items to ThisFolder after receiving SomeFiles
        set ThatFolder to POSIX file "/path/to/new/folder"

        delay 2

        repeat with TheFile in SomeFiles
            tell application "Finder" to ¬
                if name extension of (TheFile as alias) is in {"JPG", "JPEG"} then ¬
                    move TheFile to ThatFolder
        end repeat
    end adding folder items to

This is designed to run as a folder action, which makes the folder you choose automatically monitored by MacOS so that, whenever it detects a change to that folder, it executes the script attached to it.  In this instance—as you can infer from the first line of the script—this will automatically run each time a file is added to the folder in question.

To set up a folder action:

Copy the AppleScript above into Script Editor.  Edit the second line to replace "/path/to/new/folder" with the path to the new folder into which you want your jpegs to be moved (keep the quotes).  I wouldn't bother trying to run the script from inside the editor—it won't work.  The path you type out must be in full, i.e. "/Users/Richard/Pictures/Processed" and not "~/Pictures/Processed".

Save it as whatever you like.  However, it must be saved in the following directory: ~/Library/Scripts/Folder Action Scripts where ~ indicates your Home folder (i.e. /Users/Richard/ or whatever it is).  If the folder "Folder Action Scripts" doesn't exist, create it.

Close Script Editor.  Navigate to the folder that is going to be watched, i.e. the folder that your images will be waiting initially.  Now navigate one level up, into the directory containing said folder.

Right-click on the folder and hover over the Services menu item at the bottom.  Then select Folder Actions Setup...

Enable folder actions by checking the box at the top.  If you folder doesn't already appear in the left-hand list, you can add it.  Then, in the right-hand list, click the '+' at the bottom and the script you just saved should be one of many in the list of scripts that pop up.  Select it and add it.

Make sure the check boxes next to your watched folder and your chosen script are both checked, and you're done.

Now, whenever the folder receives any files whatsoever, that script is executed.  The script will move any files with extensions .jpg or .jpeg into your new folder.  Just make sure the new folder already exists (I didn't incorporate a line to create it if it doesn't; the script will just throw an error and your image won't be moved).


问:
Debian/mariadb limit? Nothing helped ! SQLSTATE[HY000] [1135] Can't create a new thread (errno 11 "Resource temporarily unavailable");
I tried to solve this problem for 2 months.
I already increased all limits that I heard of and still nothing.
Problem is that mariadb (previously the same happend with mysql 5.5.x) is having threads limit about 4500-4900 threads at one time.
When my software tries to create more connections and all threads are used i get this error:

SQLSTATE[HY000] [1135] Can't create a new thread (errno 11 "Resource temporarily unavailable");

Now, here are configs and limits that i have currently on server.
The server is Debian 9

Htop number of processes:
See image

Mysql connections:
[OK] Highest usage of available connections: 59% (4890/8200)

root:~# cat /proc/sys/kernel/threads-max

```<code>944163
</code>```

root# cat /proc/$( pgrep -o mysql )/limits

```<code>Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             472081               472081               processes
Max open files            16364                16364                files
Max locked memory         65536                65536                bytes
Max address space         unlimited            unlimited            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       472081               472081               signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us

ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 472081
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 65536
cpu time               (seconds, -t) unlimited
max user processes              (-u) 472081
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
</code>```

cat /etc/mysql/mariadb.conf.d/50-server.cnf | grep -v "#"

```<code>[server]
[mysqld]
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
key_buffer_size     = 1G
max_allowed_packet  = 64M
thread_stack        = 16M
thread_cache_size       = 4096
myisam_recover_options  = BACKUP
max_connections        = 8200
max_connect_errors     = 10000000
query_cache_limit   = 1G
query_cache_size        = 30G
slow_query_log = 1
long_query_time = 1
slow_query_log_file = /var/log/mysql/slow-query.log
log_queries_not_using_indexes
table_open_cache = 65536
open_files_limit = 65536
key_buffer_size = 512M
table_cache = 4096
max_heap_table_size = 512M
innodb_buffer_pool_size = 20G
innodb_log_file_size = 2G
innodb_log_buffer_size = 64M
read_rnd_buffer_size=1M
sort_buffer_size=1G
skip_name_resolve
log_error = /var/log/mysql/error.log
expire_logs_days    = 10
max_binlog_size   = 100M
character-set-server  = utf8mb4
collation-server      = utf8mb4_general_ci

[embedded]
[mariadb]
[mariadb-10.1]
</code>```

cat /etc/security/limits.conf

```<code>root soft  nofile 65536
root hard  nofile 65536
root soft stack 65536
root hard stack 65536

www-data soft nofile 65536
www-data hard nofile 65536

mysql soft nofile 65536
mysql hard nofile 65536
mysql soft nproc 65536
mysql hard nproc 65536
mysql soft stack 65536
mysql hard stack 65536

nobody soft nofile 65536
nobody hard nofile 65536

*          soft     nproc          40960
*          hard     nproc          40960
*          soft     nofile         40960
*          hard     nofile         40960
* soft stack 65536
* hard stack 65536

# End of file
</code>```

cat /etc/sysctl.conf

```<code># Disable IPv6 autoconf
net.ipv6.conf.all.autoconf = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.eth2.autoconf = 0
net.ipv6.conf.all.accept_ra_defrtr = 0
net.ipv6.conf.default.accept_ra_defrtr = 0
net.ipv6.conf.eth2.accept_ra_defrtr = 0
net.ipv6.conf.all.accept_ra_pinfo = 0
net.ipv6.conf.default.accept_ra_pinfo = 0
net.ipv6.conf.eth2.accept_ra_pinfo = 0
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
net.ipv6.conf.eth2.accept_ra = 0

net.core.somaxconn=1024
#kernel.sched_migration_cost_ns = 5000000

# Number of times SYNACKs for passive TCP connection.
net.ipv4.tcp_synack_retries = 2

# Allowed local port range
net.ipv4.ip_local_port_range = 1024 65535

# Protect Against TCP Time-Wait
net.ipv4.tcp_rfc1337 = 1

# Decrease the time default value for tcp_fin_timeout connection
net.ipv4.tcp_fin_timeout = 15

# Decrease the time default value for connections to keep alive
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15

### TUNING NETWORK PERFORMANCE ###

# Default Socket Receive Buffer
net.core.rmem_default = 31457280

# Maximum Socket Receive Buffer
net.core.rmem_max = 16777216

# Default Socket Send Buffer
net.core.wmem_default = 31457280

# Maximum Socket Send Buffer
net.core.wmem_max = 16777216

# Increase number of incoming connections
net.core.somaxconn = 4096

# Increase number of incoming connections backlog
net.core.netdev_max_backlog = 65536

# Increase the maximum amount of option memory buffers
net.core.optmem_max = 25165824

# Increase the maximum total buffer-space allocatable
# This is measured in units of pages (4096 bytes)
net.ipv4.tcp_mem = 65536 131072 262144
net.ipv4.udp_mem = 65536 131072 262144

# Increase the read-buffer space allocatable
net.ipv4.tcp_rmem = 8192 87380 16777216
net.ipv4.udp_rmem_min = 16384

# Increase the write-buffer-space allocatable
net.ipv4.tcp_wmem = 8192 65536 16777216
net.ipv4.udp_wmem_min = 16384

# Increase the tcp-time-wait buckets pool size to prevent simple DOS attacks
net.ipv4.tcp_max_tw_buckets = 1440000
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1

fs.file-max = 500000
net.ipv4.tcp_max_syn_backlog = 20480
</code>```

I found something here:

```<code>root@baza:~# systemctl status mysql
● mariadb.service - MariaDB database server
   Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2017-10-26 17:02:27 CEST; 1 months 11 days ago
  Process: 12508 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 12284 ExecStartPost=/etc/mysql/debian-start (code=exited, status=0/SUCCESS)
  Process: 12106 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`/usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment
_WSREP_START_POSITION=$VAR || exit 1 (code=exited, status=0/SUCCESS)
  Process: 12102 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 12099 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
 Main PID: 12244 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 4915 (limit: 4915)
   CGroup: /system.slice/mariadb.service
           └─12244 /usr/sbin/mysqld

paź 26 17:02:23 baza systemd[1]: Starting MariaDB database server...
paź 26 17:02:24 baza mysqld[12244]: 2017-10-26 17:02:24 140040257753664 [Note] /usr/sbin/mysqld (mysqld 10.1.26-MariaDB-0+deb9u1) starting as process 12244 ...
paź 26 17:02:24 baza mysqld[12244]: 2017-10-26 17:02:24 140040257753664 [Warning] Could not increase number of max_open_files to more than 16364 (request: 16403)
paź 26 17:02:27 baza systemd[1]: Started MariaDB database server.
</code>```

Then:
systemctl show -all | grep Tasks
DefaultTasksAccounting=yes
DefaultTasksMax=4915

Solved

Solved by adding those: (stupid default limit of 4915 threads)
DefaultTasksMax=infinity to /etc/systemd/system.conf
TasksMax=infinity to /etc/systemd/system/mysql.service

答:
Threads is not the real problem!

What version of MySQL?  For virtually all versions, query_cache_size = 30G is VERY bad on performance.  Don't go past about 50M.

Really bad:  Load avg = 11; Connections = 4890/8200.  Dozens of active connections is usually too many -- MySQL stumbles over itself, and no throughput declines while latency goes through the roof.

I usually suggest throttling things at the client, so as to avoid the thundering hurd inside MySQL.

Threads_running = 64 -- That confirms my fears above.

key_buffer_size = 1G -- If you are not using MyISAM (and you should not be), this is wasting a lot of RAM.  A reasonable size is 40M.

You have the slow log turned on.  What does pk-query-digest (or mysqldumpslow -s t) say are the worst few queries?

How much RAM?  I see more than 50GB committed -- do you have 115GB?  If not, then the IOPs are in swapping.  This is deadly for performance.

Please provide the settings and status as discussed here.  I fear there will be more ugly surprises.

There is probably more.  Please act on some of what I have said, then I will pursue this further.

ContentLicense: CC BY-SA 4.0

Body:
I tried to solve this problem for 2 months.
I already increased all limits that I heard of and still nothing.
Problem is that mariadb (previously the same happend with mysql 5.5.x) is having threads limit about 4500-4900 threads at one time.
When my software tries to create more connections and all threads are used i get this error:

SQLSTATE[HY000] [1135] Can't create a new thread (errno 11 "Resource temporarily unavailable");

Now, here are configs and limits that i have currently on server.
The server is Debian 9

Htop number of processes:
See image

Mysql connections:
[OK] Highest usage of available connections: 59% (4890/8200)

root:~# cat /proc/sys/kernel/threads-max

944163

root# cat /proc/$( pgrep -o mysql )/limits

Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             472081               472081               processes
Max open files            16364                16364                files
Max locked memory         65536                65536                bytes
Max address space         unlimited            unlimited            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       472081               472081               signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us

ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 472081
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65536
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 65536
cpu time               (seconds, -t) unlimited
max user processes              (-u) 472081
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

cat /etc/mysql/mariadb.conf.d/50-server.cnf | grep -v "#"

[server]
[mysqld]
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
key_buffer_size     = 1G
max_allowed_packet  = 64M
thread_stack        = 16M
thread_cache_size       = 4096
myisam_recover_options  = BACKUP
max_connections        = 8200
max_connect_errors     = 10000000
query_cache_limit   = 1G
query_cache_size        = 30G
slow_query_log = 1
long_query_time = 1
slow_query_log_file = /var/log/mysql/slow-query.log
log_queries_not_using_indexes
table_open_cache = 65536
open_files_limit = 65536
key_buffer_size = 512M
table_cache = 4096
max_heap_table_size = 512M
innodb_buffer_pool_size = 20G
innodb_log_file_size = 2G
innodb_log_buffer_size = 64M
read_rnd_buffer_size=1M
sort_buffer_size=1G
skip_name_resolve
log_error = /var/log/mysql/error.log
expire_logs_days    = 10
max_binlog_size   = 100M
character-set-server  = utf8mb4
collation-server      = utf8mb4_general_ci

[embedded]
[mariadb]
[mariadb-10.1]

cat /etc/security/limits.conf

root soft  nofile 65536
root hard  nofile 65536
root soft stack 65536
root hard stack 65536

www-data soft nofile 65536
www-data hard nofile 65536

mysql soft nofile 65536
mysql hard nofile 65536
mysql soft nproc 65536
mysql hard nproc 65536
mysql soft stack 65536
mysql hard stack 65536

nobody soft nofile 65536
nobody hard nofile 65536

*          soft     nproc          40960
*          hard     nproc          40960
*          soft     nofile         40960
*          hard     nofile         40960
* soft stack 65536
* hard stack 65536

# End of file

cat /etc/sysctl.conf

# Disable IPv6 autoconf
net.ipv6.conf.all.autoconf = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.eth2.autoconf = 0
net.ipv6.conf.all.accept_ra_defrtr = 0
net.ipv6.conf.default.accept_ra_defrtr = 0
net.ipv6.conf.eth2.accept_ra_defrtr = 0
net.ipv6.conf.all.accept_ra_pinfo = 0
net.ipv6.conf.default.accept_ra_pinfo = 0
net.ipv6.conf.eth2.accept_ra_pinfo = 0
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
net.ipv6.conf.eth2.accept_ra = 0

net.core.somaxconn=1024
#kernel.sched_migration_cost_ns = 5000000

# Number of times SYNACKs for passive TCP connection.
net.ipv4.tcp_synack_retries = 2

# Allowed local port range
net.ipv4.ip_local_port_range = 1024 65535

# Protect Against TCP Time-Wait
net.ipv4.tcp_rfc1337 = 1

# Decrease the time default value for tcp_fin_timeout connection
net.ipv4.tcp_fin_timeout = 15

# Decrease the time default value for connections to keep alive
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15

### TUNING NETWORK PERFORMANCE ###

# Default Socket Receive Buffer
net.core.rmem_default = 31457280

# Maximum Socket Receive Buffer
net.core.rmem_max = 16777216

# Default Socket Send Buffer
net.core.wmem_default = 31457280

# Maximum Socket Send Buffer
net.core.wmem_max = 16777216

# Increase number of incoming connections
net.core.somaxconn = 4096

# Increase number of incoming connections backlog
net.core.netdev_max_backlog = 65536

# Increase the maximum amount of option memory buffers
net.core.optmem_max = 25165824

# Increase the maximum total buffer-space allocatable
# This is measured in units of pages (4096 bytes)
net.ipv4.tcp_mem = 65536 131072 262144
net.ipv4.udp_mem = 65536 131072 262144

# Increase the read-buffer space allocatable
net.ipv4.tcp_rmem = 8192 87380 16777216
net.ipv4.udp_rmem_min = 16384

# Increase the write-buffer-space allocatable
net.ipv4.tcp_wmem = 8192 65536 16777216
net.ipv4.udp_wmem_min = 16384

# Increase the tcp-time-wait buckets pool size to prevent simple DOS attacks
net.ipv4.tcp_max_tw_buckets = 1440000
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1

fs.file-max = 500000
net.ipv4.tcp_max_syn_backlog = 20480

I found something here:

root@baza:~# systemctl status mysql
● mariadb.service - MariaDB database server
   Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2017-10-26 17:02:27 CEST; 1 months 11 days ago
  Process: 12508 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 12284 ExecStartPost=/etc/mysql/debian-start (code=exited, status=0/SUCCESS)
  Process: 12106 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`/usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment
_WSREP_START_POSITION=$VAR || exit 1 (code=exited, status=0/SUCCESS)
  Process: 12102 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 12099 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
 Main PID: 12244 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 4915 (limit: 4915)
   CGroup: /system.slice/mariadb.service
           └─12244 /usr/sbin/mysqld

paź 26 17:02:23 baza systemd[1]: Starting MariaDB database server...
paź 26 17:02:24 baza mysqld[12244]: 2017-10-26 17:02:24 140040257753664 [Note] /usr/sbin/mysqld (mysqld 10.1.26-MariaDB-0+deb9u1) starting as process 12244 ...
paź 26 17:02:24 baza mysqld[12244]: 2017-10-26 17:02:24 140040257753664 [Warning] Could not increase number of max_open_files to more than 16364 (request: 16403)
paź 26 17:02:27 baza systemd[1]: Started MariaDB database server.

Then:
systemctl show -all | grep Tasks
DefaultTasksAccounting=yes
DefaultTasksMax=4915

Solved

Solved by adding those: (stupid default limit of 4915 threads)
DefaultTasksMax=infinity to /etc/systemd/system.conf
TasksMax=infinity to /etc/systemd/system/mysql.service


问:
Why PS didn't saved informations in these txt files?
I didn't got any errors and powershell made these files, but they are empty. What did i wrong?       </p>

```<code>$Services = Get-Service
Foreach ($Proces in $Services) {
If($Proces.status -eq "running") { Out-File $Proces >> "C:\proces.txt"}
If($Proces.status -eq "stopped") { Out-File $Proces >> "C:\proces2.txt"}
}
</code>```

答:
>> is the append redirect operator, which is basically the same as Out-File -Append. So it is like calling Out-File twice.

With the command Out-File $Proces >> "C:\proces.txt" you pass in no input object to Out-File. So you write a blank file to $Proces. Then take the output of that command (nothing) and write that to C:\proces.txt, which creates the second blank file.

So you will want to decide on using Out-File -Append or >>

Here is your code using just Out-File:

```<code>$Services = Get-Service
Foreach ($Service in $Services) {
    If ($Service.Status -eq "Running") { Out-File -InputObject $Service -Path "C:\proces.txt" -Append}
    If ($Service.Status -eq "Stopped") { Out-File -InputObject $Service -Path "C:\proces2.txt" -Append }
}
</code>```

Here is your code using just >>:

```<code>$Services = Get-Service
Foreach ($Service in $Services) {
    If ($Service.Status -eq "Running") { $Service >> "C:\proces.txt" }
    If ($Service.Status -eq "Stopped") { $Service >> "C:\proces2.txt" }
}
</code>```

There are many other ways to do what you are attempting

Here is a way using the Where-Object cmdlet rather than a loop/conditional

```<code>$Services = Get-Service
$Services | Where-Object {$_.Status -eq "Running"} | Out-File "C:\proces.txt" -Append
$Services | Where-Object {$_.Status -eq "Stopped"} | Out-File "C:\proces2.txt" -Append
</code>```

Here is a way using the .where() method using split

```<code>$Running,$Stopped = (Get-Service).Where({$_.Status -eq 'Running'},'Split')
$Running | Out-File "C:\proces.txt" -Append
$Stopped | Out-File "C:\proces2.txt" -Append
</code>```

Body:
I didn't got any errors and powershell made these files, but they are empty. What did i wrong?

$Services = Get-Service
Foreach ($Proces in $Services) {
If($Proces.status -eq "running") { Out-File $Proces >> "C:\proces.txt"}
If($Proces.status -eq "stopped") { Out-File $Proces >> "C:\proces2.txt"}
}

Body:
>> is the append redirect operator, which is basically the same as Out-File -Append. So it is like calling Out-File twice.

With the command Out-File $Proces >> "C:\proces.txt" you pass in no input object to Out-File. So you write a blank file to $Proces. Then take the output of that command (nothing) and write that to C:\proces.txt, which creates the second blank file.

So you will want to decide on using Out-File -Append or >>

Here is your code using just Out-File:

$Services = Get-Service
Foreach ($Service in $Services) {
    If ($Service.Status -eq "Running") { Out-File -InputObject $Service -Path "C:\proces.txt" -Append}
    If ($Service.Status -eq "Stopped") { Out-File -InputObject $Service -Path "C:\proces2.txt" -Append }
}

Here is your code using just >>:

$Services = Get-Service
Foreach ($Service in $Services) {
    If ($Service.Status -eq "Running") { $Service >> "C:\proces.txt" }
    If ($Service.Status -eq "Stopped") { $Service >> "C:\proces2.txt" }
}

There are many other ways to do what you are attempting

Here is a way using the Where-Object cmdlet rather than a loop/conditional

$Services = Get-Service
$Services | Where-Object {$_.Status -eq "Running"} | Out-File "C:\proces.txt" -Append
$Services | Where-Object {$_.Status -eq "Stopped"} | Out-File "C:\proces2.txt" -Append

Here is a way using the .where() method using split

$Running,$Stopped = (Get-Service).Where({$_.Status -eq 'Running'},'Split')
$Running | Out-File "C:\proces.txt" -Append
$Stopped | Out-File "C:\proces2.txt" -Append


问:
How do I initialize an array of a non-built-in type in a c++ constructor initializer list?
In C++, I am trying to initialize an array of a non-built-in type in a constructor initializer list.  Starting from the code:

```<code>class bar {
  int i1,i2;
public:
  bar(i1,i2);
}
class foo {
  bar bar1,bar2;
public:
  foo(int a, int b, int c, int d) : bar1(a,b),bar2(c,d) {};
}
</code>```

I would like to replace bar1 and bar2 with an array:

```<code>bar allbars[2];
</code>```

How to I change the initializer list to initialize allbars?

答:
Create a proper constructor for bar first.

```<code>class bar {
  int i1,i2;
public:
  bar(int one, int two)
  : i1(one)
  , i2(two)
  {};
};

class foo {
  bar allbars[2];
public:
  foo(int a, int b, int c, int d)
  : allbars{ bar(a,b), bar(c,d) }
  {};
};
</code>```

Body:
In C++, I am trying to initialize an array of a non-built-in type in a constructor initializer list.  Starting from the code:

class bar {
  int i1,i2;
public:
  bar(i1,i2);
}
class foo {
  bar bar1,bar2;
public:
  foo(int a, int b, int c, int d) : bar1(a,b),bar2(c,d) {};
}

I would like to replace bar1 and bar2 with an array:

bar allbars[2];

How to I change the initializer list to initialize allbars?

Body:
Create a proper constructor for bar first.

class bar {
  int i1,i2;
public:
  bar(int one, int two)
  : i1(one)
  , i2(two)
  {};
};

class foo {
  bar allbars[2];
public:
  foo(int a, int b, int c, int d)
  : allbars{ bar(a,b), bar(c,d) }
  {};
};


问:
JPA How to create Query with ManytoOne relationship?
The basic question:
 If I have an entity B with ManyToOne field x linked to another entity A, how do I get all the instances of B that have A in their x field?

More specifically:

Consider the following entites:

```<code>public class User {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "USER_ID")
 private Key id;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
 private List<Message> messages;
}

ic class Message {
 @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column (name="MESSAGE_ID")
    private Key id;
    @ManyToOne(fetch = FetchType.LAZY)
    private User owner;
    private int status;
}
</code>```

I already have this query prepared

```<code>Query query = em.createQuery("SELECT m from Message m WHERE m.owner = :us");
</code>```

Here is the api for a method I want to build:

Input: User u, Status s

Output: List of all message with owner u and status s.

I know I am supposed to build a query using EntityMenager but what is the proper syntax? What do I put in the part (*"SELECT m FROM Message m WHERE owner = _ AND status="+status*).

when I tried this:

```<code>Query query = em.createQuery("SELECT m from Message m "
+"WHERE m.owner.id = :ownerId");
</code>```

I got the follwing error:

```<code>javax.persistence.PersistenceException:
SELECT FROM Message m WHERE m.owner.username = :ownerID:
Can only reference properties of a sub-object if the sub-object is embedded.
</code>```

Thanks in advance....

答:
You can query against object fields using a '.' notation. For example, you can get the messages with a particular owner by asking for "m.owner.id = ?", or messages with an owner in a specific state by asking for "m.owner.address.state.id = ?"</p>

```<code>Query q = em.createQuery(" FROM package.Message m WHERE m.owner.id = :ownerId AND m.status = :status")
            .setParameter("ownerId", user.id)
            .setParameter("status", status)
            .getResultList();
</code>```

Body:
The basic question:
 If I have an entity B with ManyToOne field x linked to another entity A, how do I get all the instances of B that have A in their x field?

More specifically:

Consider the following entites:

public class User {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "USER_ID")
 private Key id;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
 private List<Message> messages;
}

ic class Message {
 @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column (name="MESSAGE_ID")
    private Key id;
    @ManyToOne(fetch = FetchType.LAZY)
    private User owner;
    private int status;
}

I already have this query prepared

Query query = em.createQuery("SELECT m from Message m WHERE m.owner = :us");

Here is the api for a method I want to build:

Input: User u, Status s

Output: List of all message with owner u and status s.

I know I am supposed to build a query using EntityMenager but what is the proper syntax? What do I put in the part (*"SELECT m FROM Message m WHERE owner = _ AND status="+status*).

when I tried this:

Query query = em.createQuery("SELECT m from Message m "
+"WHERE m.owner.id = :ownerId");

I got the follwing error:

javax.persistence.PersistenceException:
SELECT FROM Message m WHERE m.owner.username = :ownerID:
Can only reference properties of a sub-object if the sub-object is embedded.

Thanks in advance....

Body:
You can query against object fields using a '.' notation. For example, you can get the messages with a particular owner by asking for "m.owner.id = ?", or messages with an owner in a specific state by asking for "m.owner.address.state.id = ?"

Query q = em.createQuery(" FROM package.Message m WHERE m.owner.id = :ownerId AND m.status = :status")
            .setParameter("ownerId", user.id)
            .setParameter("status", status)
            .getResultList();


问:
Capture and save image with Kotlin in Android Studio
I need help with Kotlin. I need to capture and save an image in my media store.

My code:

```<code>class MainActivity : AppCompatActivity() {
    var ListadeProductos = ArrayList<Notas>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        camera.setOnClickListener {

            val intentCamera = Intent("android.media.action.IMAGE_CAPTURE")
            startActivity(intentCamera)
        }
    }
}
</code>```

答:
I think maybe the next code can help you half way. Just capture the image from camera and display it in an ImageView.

I used it (found in Creating camera intent app using Kotlin on android - Displaying thumbnail).

```<code>val CAMERA_REQUEST_CODE = 0
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    button.setOnClickListener {
        val callCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (callCameraIntent.resolveActivity(packageManager) != null) {
            startActivityForResult(callCameraIntent, CAMERA_REQUEST_CODE)
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when(requestCode) {
        CAMERA_REQUEST_CODE -> {
            if (resultCode == Activity.RESULT_OK && data != null) {
                imageView.setImageBitmap(data.extras.get("data") as Bitmap)
            }
        }
        else -> {
            Toast.makeText(this, "Unrecognized request code", Toast.LENGTH_SHORT)
        }
    }
}
</code>```

Body:
I need help with Kotlin. I need to capture and save an image in my media store.

My code:

class MainActivity : AppCompatActivity() {
    var ListadeProductos = ArrayList<Notas>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        camera.setOnClickListener {

            val intentCamera = Intent("android.media.action.IMAGE_CAPTURE")
            startActivity(intentCamera)
        }
    }
}

Body:
I think maybe the next code can help you half way. Just capture the image from camera and display it in an ImageView.

I used it (found in Creating camera intent app using Kotlin on android - Displaying thumbnail).

val CAMERA_REQUEST_CODE = 0
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    button.setOnClickListener {
        val callCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (callCameraIntent.resolveActivity(packageManager) != null) {
            startActivityForResult(callCameraIntent, CAMERA_REQUEST_CODE)
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when(requestCode) {
        CAMERA_REQUEST_CODE -> {
            if (resultCode == Activity.RESULT_OK && data != null) {
                imageView.setImageBitmap(data.extras.get("data") as Bitmap)
            }
        }
        else -> {
            Toast.makeText(this, "Unrecognized request code", Toast.LENGTH_SHORT)
        }
    }
}


问:
Constantly Updating JavaFX GUI
I'm currently working on a project where I convert the time into base 10 time (essentially it will end up displaying a percentage of the day that has passed. ex: 12:00 noon would be displayed as 50.00 in base 10 time). Currently, I know my algorithm is correct since it prints out correctly if I print it to the console, but for some reason, I can't get my GUI to display. If I get rid of the part where I attempt to constantly update the GUI to display the correct numbers, the GUI displays fine, but with no numbers. My code is as follows:

```<code>package ClockPackage;

import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        Application.launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
            final double TEXTFIELD_LAYOUT_Y = 200;

            //Background Pane
            background = new Pane();

            //First digit textField
            firstDigit = new Text();
            firstDigit.setLayoutX(17);
            firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            firstDigit.setStyle("-fx-font-size: 96pt;");

            //Second digit textField
            secondDigit = new Text();
            secondDigit.setLayoutX(117);
            secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            secondDigit.setStyle("-fx-font-size: 96pt;");

            //Middle decimal
            middleDecimal = new Text(".");
            middleDecimal.setLayoutX(219);
            middleDecimal.setLayoutY(210);
            middleDecimal.setStyle("-fx-font-size: 72pt;");

            //Third digit textField
            thirdDigit = new Text();
            thirdDigit.setLayoutX(250);
            thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            thirdDigit.setStyle("-fx-font-size: 96pt;");

            //Fourth digit textField
            fourthDigit = new Text();
            fourthDigit.setLayoutX(362);
            fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            fourthDigit.setStyle("-fx-font-size: 96pt;");

            /* Adding the Nodes to the Pane */
            background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

            /* Setting the Scene */
            Scene scene = new Scene(background, 470, 258);
            primaryStage.setTitle("Base 10 Clock");
            primaryStage.setScene(scene);
            primaryStage.show();

            /*
             * Calculates the time in base 10 time and calls the 4 methods
             * to set the GUI display.
             *
             * In a constant while loop in order to continuously update
             * the GUI.
             */
            Calendar now;
            double currentTime;
            String timeString;
            long timestamp;
            while(true) {
                /* Sleep for 8.64 seconds since that is how long it is between
                increments of 0.01 in base 10 time. */
                Thread.sleep(8640);
                now = Calendar.getInstance();
                timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                currentTime = timestamp/86400.0;
                timeString = "" + currentTime;
                setFirstDigit(timeString.charAt(2));
                setSecondDigit(timeString.charAt(3));
                setThirdDigit(timeString.charAt(4));
                setFourthDigit(timeString.charAt(5));
            }
    }
}
</code>```

Does anyone have any idea how I would go about making the GUI both show up and update the numbers constantly? I can't figure out how to get it to do both. I've seen where people use buttons to update data, but I haven't seen where the display is constantly automatically updated.

Thanks!

答:
Replace:

```<code>    Calendar now;
    double currentTime;
    String timeString;
    long timestamp;
    while (true)
    {
        /* Sleep for 8.64 seconds since that is how long it is between
            increments of 0.01 in base 10 time. */
        Thread.sleep(8640);
        now = Calendar.getInstance();
        timestamp = now.get(Calendar.HOUR_OF_DAY) * 60 * 60 + now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND);
        currentTime = timestamp / 86400.0;
        timeString = "" + currentTime;
        setFirstDigit(timeString.charAt(2));
        setSecondDigit(timeString.charAt(3));
        setThirdDigit(timeString.charAt(4));
        setFourthDigit(timeString.charAt(5));
    }
</code>```

with:

```<code>        Timeline overEightSeconsWonder = new Timeline(new KeyFrame(Duration.seconds(8.64), (ActionEvent event) ->
        {
            Calendar now = Calendar.getInstance();
            long timestamp = now.get(Calendar.HOUR_OF_DAY) * 60 * 60 + now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND);
            double currentTime = timestamp / 86400.0;
            String timeString = "" + currentTime;
            setFirstDigit(timeString.charAt(2));
            setSecondDigit(timeString.charAt(3));
            setThirdDigit(timeString.charAt(4));
            setFourthDigit(timeString.charAt(5));
        }));
        overEightSeconsWonder.setCycleCount(Timeline.INDEFINITE);
        overEightSeconsWonder.play();
</code>```

Title: Constantly Updating JavaFX GUI

Body:
I'm currently working on a project where I convert the time into base 10 time (essentially it will end up displaying a percentage of the day that has passed. ex: 12:00 noon would be displayed as 50.00 in base 10 time). Currently, I know my algorithm is correct since it prints out correctly if I print it to the console, but for some reason, I can't get my GUI to display. If I get rid of the part where I attempt to constantly update the GUI to display the correct numbers, the GUI displays fine, but with no numbers. My code is as follows:

package ClockPackage;

import java.util.Calendar;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ClockView extends Application {
    Pane background;
    static Text firstDigit;
    static Text secondDigit;
    static Text thirdDigit;
    static Text fourthDigit;
    Text middleDecimal;

    /* Sets the first digit of the base 10 time to the passed through char. */
    static void setFirstDigit(char x1) {
        String digitString = "";
        digitString += x1;
        firstDigit.setText(digitString);
    }

    /* Sets the second digit of the base 10 time to the passed through char. */
    static void setSecondDigit(char x2) {
        String digitString = "";
        digitString += x2;
        secondDigit.setText(digitString);
    }

    /* Sets the third digit of the base 10 time to the passed through char. */
    static void setThirdDigit(char y1) {
        String digitString = "";
        digitString += y1;
        thirdDigit.setText(digitString);
    }

    /* Sets the fourth digit of the base 10 time to the passed through char. */
    static void setFourthDigit(char y2) {
        String digitString = "";
        digitString += y2;
        fourthDigit.setText(digitString);
    }

    /* Main Method that Launches the GUI */
    public static void main(String[] args) {
        Application.launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
            final double TEXTFIELD_LAYOUT_Y = 200;

            //Background Pane
            background = new Pane();

            //First digit textField
            firstDigit = new Text();
            firstDigit.setLayoutX(17);
            firstDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            firstDigit.setStyle("-fx-font-size: 96pt;");

            //Second digit textField
            secondDigit = new Text();
            secondDigit.setLayoutX(117);
            secondDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            secondDigit.setStyle("-fx-font-size: 96pt;");

            //Middle decimal
            middleDecimal = new Text(".");
            middleDecimal.setLayoutX(219);
            middleDecimal.setLayoutY(210);
            middleDecimal.setStyle("-fx-font-size: 72pt;");

            //Third digit textField
            thirdDigit = new Text();
            thirdDigit.setLayoutX(250);
            thirdDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            thirdDigit.setStyle("-fx-font-size: 96pt;");

            //Fourth digit textField
            fourthDigit = new Text();
            fourthDigit.setLayoutX(362);
            fourthDigit.setLayoutY(TEXTFIELD_LAYOUT_Y);
            fourthDigit.setStyle("-fx-font-size: 96pt;");

            /* Adding the Nodes to the Pane */
            background.getChildren().addAll(firstDigit, secondDigit, middleDecimal, thirdDigit, fourthDigit);

            /* Setting the Scene */
            Scene scene = new Scene(background, 470, 258);
            primaryStage.setTitle("Base 10 Clock");
            primaryStage.setScene(scene);
            primaryStage.show();

            /*
             * Calculates the time in base 10 time and calls the 4 methods
             * to set the GUI display.
             *
             * In a constant while loop in order to continuously update
             * the GUI.
             */
            Calendar now;
            double currentTime;
            String timeString;
            long timestamp;
            while(true) {
                /* Sleep for 8.64 seconds since that is how long it is between
                increments of 0.01 in base 10 time. */
                Thread.sleep(8640);
                now = Calendar.getInstance();
                timestamp = now.get(Calendar.HOUR_OF_DAY)*60*60 + now.get(Calendar.MINUTE)*60 + now.get(Calendar.SECOND);
                currentTime = timestamp/86400.0;
                timeString = "" + currentTime;
                setFirstDigit(timeString.charAt(2));
                setSecondDigit(timeString.charAt(3));
                setThirdDigit(timeString.charAt(4));
                setFourthDigit(timeString.charAt(5));
            }
    }
}

Does anyone have any idea how I would go about making the GUI both show up and update the numbers constantly? I can't figure out how to get it to do both. I've seen where people use buttons to update data, but I haven't seen where the display is constantly automatically updated.

Thanks!

Body:
Replace:

    Calendar now;
    double currentTime;
    String timeString;
    long timestamp;
    while (true)
    {
        /* Sleep for 8.64 seconds since that is how long it is between
            increments of 0.01 in base 10 time. */
        Thread.sleep(8640);
        now = Calendar.getInstance();
        timestamp = now.get(Calendar.HOUR_OF_DAY) * 60 * 60 + now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND);
        currentTime = timestamp / 86400.0;
        timeString = "" + currentTime;
        setFirstDigit(timeString.charAt(2));
        setSecondDigit(timeString.charAt(3));
        setThirdDigit(timeString.charAt(4));
        setFourthDigit(timeString.charAt(5));
    }

with:

        Timeline overEightSeconsWonder = new Timeline(new KeyFrame(Duration.seconds(8.64), (ActionEvent event) ->
        {
            Calendar now = Calendar.getInstance();
            long timestamp = now.get(Calendar.HOUR_OF_DAY) * 60 * 60 + now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND);
            double currentTime = timestamp / 86400.0;
            String timeString = "" + currentTime;
            setFirstDigit(timeString.charAt(2));
            setSecondDigit(timeString.charAt(3));
            setThirdDigit(timeString.charAt(4));
            setFourthDigit(timeString.charAt(5));
        }));
        overEightSeconsWonder.setCycleCount(Timeline.INDEFINITE);
        overEightSeconsWonder.play();


问:
java.nio.BufferOverflowException constructing byte[]
I'm building a byte array to identify an M-Bus Master and i need to do it using the secondary address.

To do it i need to build a byte[] with the identification of the address:

Identification Number (4 bytes) – A number ranging from 00000000 to
99999999 to identify the meter.

Manufacturer ID (2 bytes) – Three letters that identify the
manufacturer.

Version (1 byte) – Specifies the version of the device. The version
is manufacturer specific.

Device type (1 byte) – This field codes the device type (e.g.
electricity meter, cold water meter)

If my math is not failing me this has a total of 8 bytes.

So here is my code to do it:

```<code>public static void main(String[] args) {
    // TODO code application logic here
    MBusSerialBuilder builder = MBusConnection.newSerialBuilder("COM4").setBaudrate(2400);
    try (MBusConnection mBusConnection = builder.build()) {
        // read/write
        int primaryAddress = 253;

        byte[] idNum = ByteBuffer.allocate(4).putInt(46152604).array();
        byte version = 0xFF & 88; //only need a byte not a 4 byte int
        byte deviceType = 0xFF & 13; //only need a byte not a 4 byte int
        short manuID = createManuID("ZRI");
        //builds the message without overflow now
        byte[] data = ByteBuffer.allocate(8).put(idNum).putShort(manuID).put(version).put(deviceType).array();

        mBusConnection.write(primaryAddress, data);
        VariableDataStructure vds = mBusConnection.read(primaryAddress);
        System.out.println(vds);
    } catch (IOException ex) {
        System.out.println(ex.getLocalizedMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

Note previouslly i had

```<code>byte[] manId = ByteBuffer.allocate(2).putChar('Z').putChar('R').putChar('I').array();
</code>```

And it was returning me java.nio.BufferOverflowException.

With the recent changes the error is now on data declaration.

Even if i alloc 50 bytes

```<code>byte[] data = ByteBuffer.allocate(50).put(idNum).put(manId).putInt(88).putInt(13).array();
</code>```

Diferent error

```<code>java.lang.IndexOutOfBoundsException
</code>```

Here is some info i extracted from a log file of the seller's program.

```<code>MBus Tx_raw-><11><68><b><b><68><53><fd><52><4><26><15><46><ff><ff><ff><ff><23><16>
MBus Rx_raw-><0><aa><1><e5><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0>
MBus Tx_raw-><5><10><7b><fd><78><16>
MBus Rx_raw-><0><aa><b7><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><a><27><2c><82><4><6c><21><21><82><a><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><a><6><0><0><0><0><4><13><4a><30><0><0>
MBus consecutive Frame [183]-><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><a><27><2c><82><4><6c><21><21><82><a><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><a><6><0><0><0><0><4><13><4a><30><0><0><2><59><8a><7><2><5d><bc><7><2><61><ce><ff><4><3b><bf><2><0><0><4><2d><4><0><0><0><4><26><b><8><0><0><84><10><6><2><0><0><0><84><14><6><0><0><0><0><84><1a><6><0><0><0><0><84><40><14><c1><6><0><0><84><44><14><0><0><0><0><84><4a><14><a9><0><0><0><84><80><40><14><10><0><0><0><84><84><40><14><0><0><0><0><84><8a><40><14><0><0><0><0><84><c0><40><14><e3><0><0><0><84><c4><40><14><0><0><0><0><84><ca><40><14><0><0><0><0><1b><16>

Readout insert->INSERT INTO LETTURE_CONTATORI_TEMP VALUES(NULL,'OK','1','1','510','07/12/2017 10:16:23','','','1512641783','0','07/12/2017 10:52','01/01/2017','01/12/2017','0','0','0','12362','1930','1980','-50','703','4','2059','2','0','0','1729','0','169','16','0','0','227','0','0','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
</code>```

答:
The BB isn't large enough.

You don't need all this. Allocate one ByteBuffer large enough for all the data, and then call all the puts you need. Or use a DataOutputStream.

Body:
I'm building a byte array to identify an M-Bus Master and i need to do it using the secondary address.

To do it i need to build a byte[] with the identification of the address:

Identification Number (4 bytes) – A number ranging from 00000000 to
99999999 to identify the meter.

Manufacturer ID (2 bytes) – Three letters that identify the
manufacturer.

Version (1 byte) – Specifies the version of the device. The version
is manufacturer specific.

Device type (1 byte) – This field codes the device type (e.g.
electricity meter, cold water meter)

If my math is not failing me this has a total of 8 bytes.

So here is my code to do it:

public static void main(String[] args) {
    // TODO code application logic here
    MBusSerialBuilder builder = MBusConnection.newSerialBuilder("COM4").setBaudrate(2400);
    try (MBusConnection mBusConnection = builder.build()) {
        // read/write
        int primaryAddress = 253;

        byte[] idNum = ByteBuffer.allocate(4).putInt(46152604).array();
        byte version = 0xFF & 88; //only need a byte not a 4 byte int
        byte deviceType = 0xFF & 13; //only need a byte not a 4 byte int
        short manuID = createManuID("ZRI");
        //builds the message without overflow now
        byte[] data = ByteBuffer.allocate(8).put(idNum).putShort(manuID).put(version).put(deviceType).array();

        mBusConnection.write(primaryAddress, data);
        VariableDataStructure vds = mBusConnection.read(primaryAddress);
        System.out.println(vds);
    } catch (IOException ex) {
        System.out.println(ex.getLocalizedMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Note previouslly i had

byte[] manId = ByteBuffer.allocate(2).putChar('Z').putChar('R').putChar('I').array();

And it was returning me java.nio.BufferOverflowException.

With the recent changes the error is now on data declaration.

Even if i alloc 50 bytes

byte[] data = ByteBuffer.allocate(50).put(idNum).put(manId).putInt(88).putInt(13).array();

Diferent error

java.lang.IndexOutOfBoundsException

Here is some info i extracted from a log file of the seller's program.

MBus Tx_raw-><11><68><68><53><fd><52><4><26><15><46><ff><ff><ff><ff><23><16>
MBus Rx_raw-><0><aa><1><e5><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0>
MBus Tx_raw-><5><10><7b><fd><78><16>
MBus Rx_raw-><0><aa><b7><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><27><2c><82><4><6c><21><21><82><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><6><0><0><0><0><4><13><4a><30><0><0>
MBus consecutive Frame [183]-><68><b1><b1><68><8><0><72><4><26><15><46><49><6a><88><d><29><0><0><0><4><6d><34><27><2c><82><4><6c><21><21><82><6c><21><2c><4><6><0><0><0><0><84><4><6><0><0><0><0><84><6><0><0><0><0><4><13><4a><30><0><0><2><59><8a><7><2><5d><bc><7><2><61><ce><ff><4><3b><bf><2><0><0><4><2d><4><0><0><0><4><26><8><0><0><84><10><6><2><0><0><0><84><14><6><0><0><0><0><84><1a><6><0><0><0><0><84><40><14><c1><6><0><0><84><44><14><0><0><0><0><84><4a><14><a9><0><0><0><84><80><40><14><10><0><0><0><84><84><40><14><0><0><0><0><84><8a><40><14><0><0><0><0><84><c0><40><14><e3><0><0><0><84><c4><40><14><0><0><0><0><84><ca><40><14><0><0><0><0><1b><16>

Readout insert->INSERT INTO LETTURE_CONTATORI_TEMP VALUES(NULL,'OK','1','1','510','07/12/2017 10:16:23','','','1512641783','0','07/12/2017 10:52','01/01/2017','01/12/2017','0','0','0','12362','1930','1980','-50','703','4','2059','2','0','0','1729','0','169','16','0','0','227','0','0','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');


问:
Chromecast - Cast Dialogue doesn't have shadow and can't cancel from outside touch
I just recently started working with the Cast SDK and while following the guide to setting it up (found here: https://developers.google.com/cast/docs/android_sender_integrate). I integrated the cast button onto my example app, however for some reason it does not look like how it's suppose (?) to look?

For example, my app's cast dialogue:
My example app Picture

vs an example app that follows the design standards (https://github.com/googlecast/CastVideos-android):
CastVideos-Android Picture

If you notice, the CastVideos-Android one has a back-shadow associated with the dialogue and can be dismissed by pressing anywhere on the screen.

Here is all of my code since it's a very basic implementation (I wrote it in Kotlin):

MainActivity class:

```<code>class MainActivity : AppCompatActivity() {
private var castContext: CastContext? = null

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

    castContext = CastContext.getSharedInstance(this)
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    super.onCreateOptionsMenu(menu)
    menuInflater.inflate(R.menu.main, menu)

    CastButtonFactory.setUpMediaRouteButton(applicationContext, menu, R.id.media_route_menu_item)

    return true
}
</code>```

CastOptionsProvider class:

```<code>class CastOptionsProvider : OptionsProvider {
override fun getCastOptions(context: Context?): CastOptions {
    return CastOptions.Builder()
            .setReceiverApplicationId(context?.getString(R.string.app_id))
            .build()
}

override fun getAdditionalSessionProviders(context: Context?): MutableList<SessionProvider>? {
    return null
}
</code>```

}

Any help will be appreciated!

Thanks in advance.

答:
Updating support library version to 27.0.2 in project gradle should fix the issue.

```<code>compile 'com.android.support:appcompat-v7:27.0.2'
compile 'com.android.support:mediarouter-v7:27.0.2'
compile 'com.android.support:recyclerview-v7:27.0.2'
</code>```

Support Library Version history: https://developer.android.com/topic/libraries/support-library/revisions.html#27-0-2

Body:
I just recently started working with the Cast SDK and while following the guide to setting it up (found here: https://developers.google.com/cast/docs/android_sender_integrate). I integrated the cast button onto my example app, however for some reason it does not look like how it's suppose (?) to look?

For example, my app's cast dialogue:
My example app Picture

vs an example app that follows the design standards (https://github.com/googlecast/CastVideos-android):
CastVideos-Android Picture

If you notice, the CastVideos-Android one has a back-shadow associated with the dialogue and can be dismissed by pressing anywhere on the screen.

Here is all of my code since it's a very basic implementation (I wrote it in Kotlin):

MainActivity class:

class MainActivity : AppCompatActivity() {
private var castContext: CastContext? = null

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

    castContext = CastContext.getSharedInstance(this)
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    super.onCreateOptionsMenu(menu)
    menuInflater.inflate(R.menu.main, menu)

    CastButtonFactory.setUpMediaRouteButton(applicationContext, menu, R.id.media_route_menu_item)

    return true
}

CastOptionsProvider class:

class CastOptionsProvider : OptionsProvider {
override fun getCastOptions(context: Context?): CastOptions {
    return CastOptions.Builder()
            .setReceiverApplicationId(context?.getString(R.string.app_id))
            .build()
}

override fun getAdditionalSessionProviders(context: Context?): MutableList<SessionProvider>? {
    return null
}

}

Any help will be appreciated!

Thanks in advance.

Body:
Updating support library version to 27.0.2 in project gradle should fix the issue.

compile 'com.android.support:appcompat-v7:27.0.2'
compile 'com.android.support:mediarouter-v7:27.0.2'
compile 'com.android.support:recyclerview-v7:27.0.2'

Support Library Version history: https://developer.android.com/topic/libraries/support-library/revisions.html#27-0-2