问:
Is there a faster way than fread() to read big data?
Hi first of all I already search on stack and google and found posts such at this one :
Quickly reading very large tables as dataframes. While those are helpfull and well answered, I'm looking for more informations.

I am looking for the best way to read/import "big" data that can go up to 50-60GB.
I am currently using the fread() function from data.table and it is the function that is the fastest I know at the moment. The pc/server I work on got a good cpu (work station) and 32 GB RAM, but still datas over 10GB and sometimes near billions observations takes a lot of time to get read.

We already have sql databases but for some reasons we have to work with big data in R.
Is there a way to speed up R or an even better option than fread() when it comes to huge file like this?

Thank you.

Edit : fread("data.txt", verbose = TRUE)

```<code>omp_get_max_threads() = 2
omp_get_thread_limit() = 2147483647
DTthreads = 0
RestoreAfterFork = true
Input contains no \n. Taking this to be a filename to open
[01] Check arguments
  Using 2 threads (omp_get_max_threads()=2, nth=2)
  NAstrings = [<<NA>>]
  None of the NAstrings look like numbers.
  show progress = 1
  0/1 column will be read as integer
[02] Opening the file
  Opening file C://somefolder/data.txt
  File opened, size = 1.083GB (1163081280 bytes).
  Memory mapped ok
[03] Detect and skip BOM
[04] Arrange mmap to be \0 terminated
  \n has been found in the input and different lines can end with different line endings (e.g. mixed \n and \r\n in one file). This is common and ideal.
[05] Skipping initial rows if needed
  Positioned on line 1 starting: <<ID,Dat,No,MX,NOM_TX>>
[06] Detect separator, quoting rule, and ncolumns
  Detecting sep automatically ...
  sep=','  with 100 lines of 5 fields using quote rule 0
  Detected 5 columns on line 1. This line is either column names or first data row. Line starts as: <<ID,Dat,No,MX,NOM_TX>>
  Quote rule picked = 0
  fill=false and the most number of columns found is 5
[07] Detect column types, good nrow estimate and whether first row is column names
  Number of sampling jump points = 100 because (1163081278 bytes from row 1 to eof) / (2 * 5778 jump0size) == 100647
  Type codes (jump 000)    : 5A5AA  Quote rule 0
  Type codes (jump 100)    : 5A5AA  Quote rule 0
  'header' determined to be true due to column 1 containing a string on row 1 and a lower type (int32) in the rest of the 10054 sample rows
  =====
  Sampled 10054 rows (handled \n inside quoted fields) at 101 jump points
  Bytes from first data row on line 2 to the end of last row: 1163081249
  Line length: mean=56.72 sd=20.65 min=25 max=128
  Estimated number of rows: 1163081249 / 56.72 = 20506811
  Initial alloc = 41013622 rows (20506811 + 100%) using bytes/max(mean-2*sd,min) clamped between [1.1*estn, 2.0*estn]
  =====
[08] Assign column names
[09] Apply user overrides on column types
  After 0 type and 0 drop user overrides : 5A5AA
[10] Allocate memory for the datatable
  Allocating 5 column slots (5 - 0 dropped) with 41013622 rows
[11] Read the data
  jumps=[0..1110), chunk_size=1047820, total_size=1163081249
|--------------------------------------------------|
|==================================================|
Read 20935277 rows x 5 columns from 1.083GB (1163081280 bytes) file in 00:31.484 wall clock time
[12] Finalizing the datatable
  Type counts:
         2 : int32     '5'
         3 : string    'A'
=============================
   0.007s (  0%) Memory map 1.083GB file
   0.739s (  2%) sep=',' ncol=5 and header detection
   0.001s (  0%) Column type detection using 10054 sample rows
   1.809s (  6%) Allocation of 41013622 rows x 5 cols (1.222GB) of which 20935277 ( 51%) rows used
  28.928s ( 92%) Reading 1110 chunks (0 swept) of 0.999MB (each chunk 18860 rows) using 2 threads
   +   26.253s ( 83%) Parse to row-major thread buffers (grown 0 times)
   +    2.639s (  8%) Transpose
   +    0.035s (  0%) Waiting
   0.000s (  0%) Rereading 0 columns due to out-of-sample type exceptions
  31.484s        Total
</code>```

答:
Assuming you want your file fully read into R, using database or choosing subset of columns/rows won't be much helpful.

What can be helpful in such case is to:

- ensure that you are using recent version of data.table

- ensure that optimal number of threads is set

use setDTthreads(0L) to use all available threads, by default data.table uses 50% of available threads.

- check output of fread(..., verbose=TRUE), and possibly add it to your question here

- put your file on fast disk, or a RAM disk, and read from there

If your data has a lot of distinct character variables you might not be able get great speed because of the fact that populating R's internal global character cache is single threaded, thus parsing can go fast but creating character vector(s) will be bottleneck.

Body:
Hi first of all I already search on stack and google and found posts such at this one :
Quickly reading very large tables as dataframes. While those are helpfull and well answered, I'm looking for more informations.

I am looking for the best way to read/import "big" data that can go up to 50-60GB.
I am currently using the fread() function from data.table and it is the function that is the fastest I know at the moment. The pc/server I work on got a good cpu (work station) and 32 GB RAM, but still datas over 10GB and sometimes near billions observations takes a lot of time to get read.

We already have sql databases but for some reasons we have to work with big data in R.
Is there a way to speed up R or an even better option than fread() when it comes to huge file like this?

Thank you.

Edit : fread("data.txt", verbose = TRUE)

omp_get_max_threads() = 2
omp_get_thread_limit() = 2147483647
DTthreads = 0
RestoreAfterFork = true
Input contains no \n. Taking this to be a filename to open
[01] Check arguments
  Using 2 threads (omp_get_max_threads()=2, nth=2)
  NAstrings = [<<NA>>]
  None of the NAstrings look like numbers.
  show progress = 1
  0/1 column will be read as integer
[02] Opening the file
  Opening file C://somefolder/data.txt
  File opened, size = 1.083GB (1163081280 bytes).
  Memory mapped ok
[03] Detect and skip BOM
[04] Arrange mmap to be \0 terminated
  \n has been found in the input and different lines can end with different line endings (e.g. mixed \n and \r\n in one file). This is common and ideal.
[05] Skipping initial rows if needed
  Positioned on line 1 starting: <<ID,Dat,No,MX,NOM_TX>>
[06] Detect separator, quoting rule, and ncolumns
  Detecting sep automatically ...
  sep=','  with 100 lines of 5 fields using quote rule 0
  Detected 5 columns on line 1. This line is either column names or first data row. Line starts as: <<ID,Dat,No,MX,NOM_TX>>
  Quote rule picked = 0
  fill=false and the most number of columns found is 5
[07] Detect column types, good nrow estimate and whether first row is column names
  Number of sampling jump points = 100 because (1163081278 bytes from row 1 to eof) / (2 * 5778 jump0size) == 100647
  Type codes (jump 000)    : 5A5AA  Quote rule 0
  Type codes (jump 100)    : 5A5AA  Quote rule 0
  'header' determined to be true due to column 1 containing a string on row 1 and a lower type (int32) in the rest of the 10054 sample rows
  =====
  Sampled 10054 rows (handled \n inside quoted fields) at 101 jump points
  Bytes from first data row on line 2 to the end of last row: 1163081249
  Line length: mean=56.72 sd=20.65 min=25 max=128
  Estimated number of rows: 1163081249 / 56.72 = 20506811
  Initial alloc = 41013622 rows (20506811 + 100%) using bytes/max(mean-2*sd,min) clamped between [1.1*estn, 2.0*estn]
  =====
[08] Assign column names
[09] Apply user overrides on column types
  After 0 type and 0 drop user overrides : 5A5AA
[10] Allocate memory for the datatable
  Allocating 5 column slots (5 - 0 dropped) with 41013622 rows
[11] Read the data
  jumps=[0..1110), chunk_size=1047820, total_size=1163081249
|--------------------------------------------------|
|==================================================|
Read 20935277 rows x 5 columns from 1.083GB (1163081280 bytes) file in 00:31.484 wall clock time
[12] Finalizing the datatable
  Type counts:
         2 : int32     '5'
         3 : string    'A'
=============================
   0.007s (  0%) Memory map 1.083GB file
   0.739s (  2%) sep=',' ncol=5 and header detection
   0.001s (  0%) Column type detection using 10054 sample rows
   1.809s (  6%) Allocation of 41013622 rows x 5 cols (1.222GB) of which 20935277 ( 51%) rows used
  28.928s ( 92%) Reading 1110 chunks (0 swept) of 0.999MB (each chunk 18860 rows) using 2 threads
   +   26.253s ( 83%) Parse to row-major thread buffers (grown 0 times)
   +    2.639s (  8%) Transpose
   +    0.035s (  0%) Waiting
   0.000s (  0%) Rereading 0 columns due to out-of-sample type exceptions
  31.484s        Total


来源: stackexchange

问:
TimePicker in Remove Set time option in Android
Android Time picker in can't remove set time option

I have checked Stack Overflow questions & also check some option remove keyboard set time icon, but not remove that options,  keyboard icon When click keyboard icon for open set time edittext and then clock icon visible for, I want to remove set time edit option in Time picker Android.

答:
As far as I can tell you cannot remove this icon, it is part of the UI on Android O.

In Android O, the time picker (in Calendar, Clock, etc) gets one small added icon at the bottom left: a keyboard. Tapping it switches to text-based entry where you can manually type in the exact time.

if you want really remove it you should create your own TimePickerDialog , read more about this solution here

ContentLicense: CC BY-SA 4.0


问:
Substring whole array content
I'm trying to come up with compact solution to process file which has positional numeric values for multiple categories, let say [2..3] is value for A, [4..5] for B and so on.

I need to sum all those values in one pass if possible, that what I like in Ruby. But I got a problem.

Processing array for ruby without loop with  array.inject(0)

```<code>contentX = ['a12334111','b3215555','c444389663']
content = [  12334111,  3215555 , 44489663]      # this OK

a =  content[1]
b = a.to_s[0..3]  # this string need to add
puts 'a:       ' + a.to_s + '  b:  ' + b.to_s

s = content.inject(:+)
s2 = contentX[0..3].inject(:+) #  Error here, no values calculated

puts 'Sum    ' + s.to_s
puts 'Sum2   ' + s2.to_s

#this is wanted output =================:::::
Sum2  = 888   # (123 + 321 + 444)
</code>```

答:
Just map the input to the three digits needed, convert them to integer and sum:

```<code>['a12334111','b3215555','c444389663'].
  map { |n| n[1...4].to_i }.sum
#⇒ 888
</code>```

Sidenote: Enumerable#sum is the same as inject(&:+).

Title: Substring whole array content

Body:
I'm trying to come up with compact solution to process file which has positional numeric values for multiple categories, let say [2..3] is value for A, [4..5] for B and so on.

I need to sum all those values in one pass if possible, that what I like in Ruby. But I got a problem.

Processing array for ruby without loop with  array.inject(0)

contentX = ['a12334111','b3215555','c444389663']
content = [  12334111,  3215555 , 44489663]      # this OK

a =  content[1]
b = a.to_s[0..3]  # this string need to add
puts 'a:       ' + a.to_s + '  b:  ' + b.to_s

s = content.inject(:+)
s2 = contentX[0..3].inject(:+) #  Error here, no values calculated

puts 'Sum    ' + s.to_s
puts 'Sum2   ' + s2.to_s

#this is wanted output =================:::::
Sum2  = 888   # (123 + 321 + 444)

Body:
Just map the input to the three digits needed, convert them to integer and sum:

['a12334111','b3215555','c444389663'].
  map { |n| n[1...4].to_i }.sum
#⇒ 888

Sidenote: Enumerable#sum is the same as inject(&:+).


问:
Bootstrap 4 Carousel Only Autoplaying Under Certain Conditions
I am attempting to implement a Carousel from Bootstrap in my CRA project. I am essentially using the provided code from the documentation:

```<code><div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="..." alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="..." alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="..." alt="Third slide">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</code>```

It works no problem, the carousel shows up and I am able to scroll through it. However, it does not autoplay when loaded.

Some things I tested that get it to autoplay:

I tab over to something else in my web broswer (blank tab or something), have React do a hot reload (put a new line after an import and saving works), then tab back to my development server. This starts the autoplay no problem.

Manually clicking through ALL the images on the carousel (in any order - 123, 213, 231, etc.) also starts the autoplay after a slight delay.

I'm stumped, but I have seen that Bootstrap's JavaScript can interfere with React's JavaScript. Anyone have any ideas?

答:
In the code that you provided in the question, no mention of autoplay... why not use the Bootstrap's built in autoplay mechanism data-interval="500" - for the specific duration you need, pass the value from React... No need for us to write the JavaScript

.carousel-inner img {
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">

  <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="500">

    <!-- Indicators -->
    <ul class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
    </ul>

    <!-- The slideshow -->
    <div class="carousel-inner">
      <div class="carousel-item active">
        <img src="https://www.w3schools.com/bootstrap4/la.jpg" alt="Los Angeles" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="https://www.w3schools.com/bootstrap4/chicago.jpg" alt="Chicago" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="https://www.w3schools.com/bootstrap4/ny.jpg" alt="New York" width="1100" height="500">
      </div>
    </div>

    <!-- Left and right controls -->

      <span class="carousel-control-prev-icon"></span>

      <span class="carousel-control-next-icon"></span>

  </div>

</div></code>```

Body:
I am attempting to implement a Carousel from Bootstrap in my CRA project. I am essentially using the provided code from the documentation:

    Previous

    Next

It works no problem, the carousel shows up and I am able to scroll through it. However, it does not autoplay when loaded.

Some things I tested that get it to autoplay:

I tab over to something else in my web broswer (blank tab or something), have React do a hot reload (put a new line after an import and saving works), then tab back to my development server. This starts the autoplay no problem.

Manually clicking through ALL the images on the carousel (in any order - 123, 213, 231, etc.) also starts the autoplay after a slight delay.

I'm stumped, but I have seen that Bootstrap's JavaScript can interfere with React's JavaScript. Anyone have any ideas?

Body:
In the code that you provided in the question, no mention of autoplay... why not use the Bootstrap's built in autoplay mechanism data-interval="500" - for the specific duration you need, pass the value from React... No need for us to write the JavaScript

.carousel-inner img {
  width: 100%;
  height: 100%;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">

  <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="500">

    <!-- Indicators -->
    <ul class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
    </ul>

    <!-- The slideshow -->
    <div class="carousel-inner">
      <div class="carousel-item active">
        <img src="https://www.w3schools.com/bootstrap4/la.jpg" alt="Los Angeles" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="https://www.w3schools.com/bootstrap4/chicago.jpg" alt="Chicago" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="https://www.w3schools.com/bootstrap4/ny.jpg" alt="New York" width="1100" height="500">
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="carousel-control-prev" href="#myCarousel" data-slide="prev">
      <span class="carousel-control-prev-icon"></span>
    </a>
    <a class="carousel-control-next" href="#myCarousel" data-slide="next">
      <span class="carousel-control-next-icon"></span>
    </a>
  </div>

</div>


问:
Azure DevOps Pipelines run a Node.js script as a step
What's the easiest way to run a Node.js script as a step in Azure DevOps Pipeline (release step)?

I tried a few approaches and it seems like this is not as straightforward as I'd like it to be. I'm looking for a general approach idea.

My last attempt was adding the script to the source repository under tools/script.js. I need to run it in a release pipeline (after build), from where I can't access the repo directly, so I have added the entire repo as a second build artifact. Now I can reach the script file from the release agent, but I haven't found a way to actually run the script, there seems to be no option to run a Node.js script on an agent in general.

答:
Option 1: Visual Pipeline Editor

1) Create the script file you want to run in your build/release steps

You can add the file to your Azure project repository, e.g. under tools/script.js and add any node modules it needs to run to your package.json, for example:

```<code>npm install --save-dev <module>
</code>```

Commit and push, so your changes are online and Azure can see them.

2) Add your repo as an artifact for your release pipeline

You can skip this for build pipelines as they already have access to the repository.

3) Edit your release pipeline to ensure environment

Add a step to make sure correct Node version is on agent (Node.js Tool Installer):

Add a step to install all required node modules (npm):

4) Add your node script step

Use the Bash step to run your node script, make sure the working directory is set to root of the project (where package.json is located):

Option 2: YAML

you have a script\shell step where you can execute custom commands, just use that to achieve the goal. Agent have node installed on them, one thing you might need to do is use the pick node version step to use the right node version for your script

Example:

```<code>trigger:
- master

pool:
  vmImage: 'Ubuntu-16.04'

steps:
- checkout: self
  persistCredentials: true
  clean: true

- bash: |
    curl $BEDROCK_BUILD_SCRIPT > build.sh
    chmod +x ./build.sh
  displayName: My script download
  env:
    BEDROCK_BUILD_SCRIPT: https://url/yourscript.sh

- task: ShellScript@2
  displayName: My script execution
  inputs:
  scriptPath: build.sh
</code>```

Body:
Option 1: Visual Pipeline Editor

1) Create the script file you want to run in your build/release steps

You can add the file to your Azure project repository, e.g. under tools/script.js and add any node modules it needs to run to your package.json, for example:

npm install --save-dev <module>

Commit and push, so your changes are online and Azure can see them.

2) Add your repo as an artifact for your release pipeline

You can skip this for build pipelines as they already have access to the repository.

3) Edit your release pipeline to ensure environment

Add a step to make sure correct Node version is on agent (Node.js Tool Installer):

Add a step to install all required node modules (npm):

4) Add your node script step

Use the Bash step to run your node script, make sure the working directory is set to root of the project (where package.json is located):

Option 2: YAML

you have a script\shell step where you can execute custom commands, just use that to achieve the goal. Agent have node installed on them, one thing you might need to do is use the pick node version step to use the right node version for your script

Example:

trigger:
- master

pool:
  vmImage: 'Ubuntu-16.04'

steps:
- checkout: self
  persistCredentials: true
  clean: true

- bash: |
    curl $BEDROCK_BUILD_SCRIPT > build.sh
    chmod +x ./build.sh
  displayName: My script download
  env:
    BEDROCK_BUILD_SCRIPT: https://url/yourscript.sh

- task: ShellScript@2
  displayName: My script execution
  inputs:
  scriptPath: build.sh


问:
How to unit test a transaction commit timeout in MySql?
I'm writing a unit test to reproduce the scenario where a timeout is reached when calling Commit on a MySqlTransaction (using C# and MySql Connector/Net), but I just don't find the way to force this kind of timeout. All of my tests will only provoke delays when doing the ExecuteNonQuery call on the command, but no delays ever happen once it hits transacion.Commit().

Is there any way to force a timeout on a commit?

答:
You are aware that you are writing an integration test, if you try to get the server to raise the exception?

If you want a UNIT TEST you should stub & mock all communcation with the outside world -- also you MySqlServer. If you do that, you get the bonus of being able to raise timeouts and other exceptions at will. Further, you will eliminate the risk of unittests changing/destroying data integrity in you database.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Getting error:Operand type clash: nvarchar is incompatible with image
I have image field in tblEmployee for employee's picture.

When i am trying to save employee's detail without image file in uploader it threw and error

"Operand type clash: nvarchar is incompatible with image"

while when i select any picture from dialog box then it works fine.
I am using c# windows applications.

My Code looks like as:

```<code>byte[] bimage=null;
           if(txtPic.Text!="")
            {
               string  image=txtPic.Text;
                Bitmap bmp=new Bitmap(image);
                FileStream fs=new FileStream(image,FileMode.Open,FileAccess.Read);
                bimage=new byte[fs.Length];
                fs.Read(bimage,0,Convert.ToInt32(fs.Length));
                fs.Close();
            }
                cmd = new SqlCommand("sp_insert_new_employee",conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@name",txtName.Text.Trim());
                cmd.Parameters.AddWithValue("@fname",txtFName.Text.Trim());
                cmd.Parameters.AddWithValue("@dob",Convert.ToDateTime(dtDOB.Text));
                cmd.Parameters.AddWithValue("@nic",txtCNIC.Text.Trim());
                cmd.Parameters.AddWithValue("@add",txtAdd.Text.Trim());
                cmd.Parameters.AddWithValue("@emptype",cmbEmpType.SelectedItem.ToString());
                if(bimage!=null)
                  cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = bimage;
                else
                    cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = DBNull.Value;
                cmd.Parameters.AddWithValue("@descr",txtDescr.Text.Trim());
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
                MessageBox.Show("Successfully added....!");`
</code>```

Any one have any idea where am i making mistake?

答:
I solved this problem by using parameter like this :</p>

```<code>    Byte[] imgtype = { 0 };
 if(bimage!=null)
                  cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = bimage;
                else
                    cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = imgtype ;
</code>```

Body:
I have image field in tblEmployee for employee's picture.

When i am trying to save employee's detail without image file in uploader it threw and error

"Operand type clash: nvarchar is incompatible with image"

while when i select any picture from dialog box then it works fine.
I am using c# windows applications.

My Code looks like as:

byte[] bimage=null;
           if(txtPic.Text!="")
            {
               string  image=txtPic.Text;
                Bitmap bmp=new Bitmap(image);
                FileStream fs=new FileStream(image,FileMode.Open,FileAccess.Read);
                bimage=new byte[fs.Length];
                fs.Read(bimage,0,Convert.ToInt32(fs.Length));
                fs.Close();
            }
                cmd = new SqlCommand("sp_insert_new_employee",conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@name",txtName.Text.Trim());
                cmd.Parameters.AddWithValue("@fname",txtFName.Text.Trim());
                cmd.Parameters.AddWithValue("@dob",Convert.ToDateTime(dtDOB.Text));
                cmd.Parameters.AddWithValue("@nic",txtCNIC.Text.Trim());
                cmd.Parameters.AddWithValue("@add",txtAdd.Text.Trim());
                cmd.Parameters.AddWithValue("@emptype",cmbEmpType.SelectedItem.ToString());
                if(bimage!=null)
                  cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = bimage;
                else
                    cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = DBNull.Value;
                cmd.Parameters.AddWithValue("@descr",txtDescr.Text.Trim());
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
                MessageBox.Show("Successfully added....!");`

Any one have any idea where am i making mistake?

Body:
I solved this problem by using parameter like this :

    Byte[] imgtype = { 0 };
 if(bimage!=null)
                  cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = bimage;
                else
                    cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = imgtype ;


问:
Object doesn't support property or method 'find' In IE 11
Some find and findIndex method of my Javascript project is not working in IE 11.
Here package.json

```<code>{
  "name": "form_builder_p1_old",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "babel js -d lib"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/plugin-transform-runtime": "^7.4.4",
    "@babel/plugin-transform-spread": "^7.2.2",
    "@babel/preset-env": "^7.4.5"
  },
  "dependencies": {
    "@babel/polyfill": "^7.4.4",
    "@babel/runtime": "^7.4.5",
    "core-js": "^3.0.1",
    "lodash": "^4.17.11",
    "regenerator-runtime": "^0.13.2"
  }
}
</code>```

and .babelrc

```<code>{
  "presets":[
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "entry",
        "corejs": "^3.0.1"
      }
    ]

  ],
  "plugins": ["@babel/plugin-transform-spread"]
}
</code>```

Babel is working fine in IE. But find methods are not working.
i have try polyfil but no success,
here is my project dir.

Please help me.

Thanks

答:
I solved this problem by adding the following line for core-js@3.

```<code>import 'core-js/stable';
import 'regenerator-runtime/runtime';
</code>```

See @ https://babeljs.io/blog/2019/03/19/7.4.0

Another solution

Add a partial module manually.

```<code>import 'core-js/modules/es.array.find';
</code>```

Body:
Some find and findIndex method of my Javascript project is not working in IE 11.
Here package.json

{
  "name": "form_builder_p1_old",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "babel js -d lib"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/plugin-transform-runtime": "^7.4.4",
    "@babel/plugin-transform-spread": "^7.2.2",
    "@babel/preset-env": "^7.4.5"
  },
  "dependencies": {
    "@babel/polyfill": "^7.4.4",
    "@babel/runtime": "^7.4.5",
    "core-js": "^3.0.1",
    "lodash": "^4.17.11",
    "regenerator-runtime": "^0.13.2"
  }
}

and .babelrc

{
  "presets":[
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "entry",
        "corejs": "^3.0.1"
      }
    ]

  ],
  "plugins": ["@babel/plugin-transform-spread"]
}

Babel is working fine in IE. But find methods are not working.
i have try polyfil but no success,
here is my project dir.

Please help me.

Thanks

Body:
I solved this problem by adding the following line for core-js@3.

import 'core-js/stable';
import 'regenerator-runtime/runtime';

See @ https://babeljs.io/blog/2019/03/19/7.4.0

Another solution

Add a partial module manually.

import 'core-js/modules/es.array.find';


问:
Godot 3.1 telling me that lock() and get_pixel() are nonexistent functions
I'm attempting to generate a height map from a noise texture. As far as I understand, in order to call get_pixel() on an image in this context, the image must first be locked. However, when I attempt to run the program, it exits with the error: Invalid call. Nonexistent function 'lock' in base 'StreamTexture'.

If I attempt to run it without locking the image, I get the error: Invalid call. Nonexistent function 'get_pixel' in base 'StreamTexture'.

I am certain that the instructions that I am following are for the same version of Godot I am running (3.1), so why is the engine telling me that lock() and get_pixel() are nonexistent functions?

My code is here:

```<code>extends Spatial

var width
var height
var heightData = {}
var vertices = PoolVector3Array()
var drawMesh = Mesh.new()

func _ready():
    var noiseTexture = load("res://noiseTexture.png")
    width = noiseTexture.get_width()
    height = noiseTexture.get_height()

    noiseTexture.lock()
    for x in range(0, width):
        for y in range(0, height):
            heightData[Vector2(x,y)] = noiseTexture.get_pixel(x,y).r
    noiseTexture.unlock()

    for x in range(0, width-1):
        for y in range(0, height-1):
            createQuad(x,y)

    var surfTool = SurfaceTool.new()
    surfTool.begin(Mesh.PRIMITIVE_TRIANGLES)

    for i in vertices.size():
        surfTool.add_vertex(vertices[i])

    surfTool.commit(drawMesh)
    $MeshInstance.mesh = drawMesh

func createQuad(x,y):
    #First half
    vertices.push_back(Vector3(x, heightData[Vector2(x,y)], -y))
    vertices.push_back(Vector3(x, heightData[Vector2(x,y+1)], -y-1))
    vertices.push_back(Vector3(x+1, heightData[Vector2(x+1,y+1)], -y-1))
    #Second Half
    vertices.push_back(Vector3(x, heightData[Vector2(x,y)], -y))
    vertices.push_back(Vector3(x+1, heightData[Vector2(x+1,y+1)], -y-1))
    vertices.push_back(Vector3(x+1, heightData[Vector2(x+1,y)], -y))
</code>```

Any help is greatly appreciated.

EDIT - I have (tried) to implement the changes that were suggested in the comments (yet I still don't know what to do with the color variable) and have attached a screenshot of my resulting code, as well as some comments I have made to try and explain to myself why the process SHOULD be working (I think). It also shows my node structure, which is why I opted to display this as an image. However, when I try to run this, the program crashes with the error displayed.

答:
Check the docs;
StreamTexture does not have the method lock.

I think the class you are looking to use is Image. The Texture class is typically intended for drawing on the screen or applying to a Material

```<code>var noiseImage = Image.new()
noiseImage.load("res://noiseTexture.png")
noiseImage.lock() # Lock the image here
var color = noiseImage.get_pixel(10, 10) # Replace with your height map population
</code>```

PS:

Just to let you know, I had a lot of issues with memory usage here so make sure you test that also (C# has bad garbage collector though).
You might need to dispose of the image, surface tool, and array mesh (If you remove the terrain object) to maintain optimum performance.

Body:
I'm attempting to generate a height map from a noise texture. As far as I understand, in order to call get_pixel() on an image in this context, the image must first be locked. However, when I attempt to run the program, it exits with the error: Invalid call. Nonexistent function 'lock' in base 'StreamTexture'.

If I attempt to run it without locking the image, I get the error: Invalid call. Nonexistent function 'get_pixel' in base 'StreamTexture'.

I am certain that the instructions that I am following are for the same version of Godot I am running (3.1), so why is the engine telling me that lock() and get_pixel() are nonexistent functions?

My code is here:

extends Spatial

var width
var height
var heightData = {}
var vertices = PoolVector3Array()
var drawMesh = Mesh.new()

func _ready():
    var noiseTexture = load("res://noiseTexture.png")
    width = noiseTexture.get_width()
    height = noiseTexture.get_height()

    noiseTexture.lock()
    for x in range(0, width):
        for y in range(0, height):
            heightData[Vector2(x,y)] = noiseTexture.get_pixel(x,y).r
    noiseTexture.unlock()

    for x in range(0, width-1):
        for y in range(0, height-1):
            createQuad(x,y)

    var surfTool = SurfaceTool.new()
    surfTool.begin(Mesh.PRIMITIVE_TRIANGLES)

    for i in vertices.size():
        surfTool.add_vertex(vertices[i])

    surfTool.commit(drawMesh)
    $MeshInstance.mesh = drawMesh

func createQuad(x,y):
    #First half
    vertices.push_back(Vector3(x, heightData[Vector2(x,y)], -y))
    vertices.push_back(Vector3(x, heightData[Vector2(x,y+1)], -y-1))
    vertices.push_back(Vector3(x+1, heightData[Vector2(x+1,y+1)], -y-1))
    #Second Half
    vertices.push_back(Vector3(x, heightData[Vector2(x,y)], -y))
    vertices.push_back(Vector3(x+1, heightData[Vector2(x+1,y+1)], -y-1))
    vertices.push_back(Vector3(x+1, heightData[Vector2(x+1,y)], -y))

Any help is greatly appreciated.

EDIT - I have (tried) to implement the changes that were suggested in the comments (yet I still don't know what to do with the color variable) and have attached a screenshot of my resulting code, as well as some comments I have made to try and explain to myself why the process SHOULD be working (I think). It also shows my node structure, which is why I opted to display this as an image. However, when I try to run this, the program crashes with the error displayed.

Body:
Check the docs;
StreamTexture does not have the method lock.

I think the class you are looking to use is Image. The Texture class is typically intended for drawing on the screen or applying to a Material

var noiseImage = Image.new()
noiseImage.load("res://noiseTexture.png")
noiseImage.lock() # Lock the image here
var color = noiseImage.get_pixel(10, 10) # Replace with your height map population

PS:

Just to let you know, I had a lot of issues with memory usage here so make sure you test that also (C# has bad garbage collector though).
You might need to dispose of the image, surface tool, and array mesh (If you remove the terrain object) to maintain optimum performance.


问:
Error: Can't set headers after they are sent. in nodejs
I am running into the error show below on my app,line 413 points to “res.json(stat); // return in JSON format.” in below code, I looked at other posts with similar error but none helped me, why am I hitting this error ?appreciate any guidance on how to fix it?

```<code>app.post('/api/botjobs.json', function(req, res) {
    // console.log(req.body)
    data = req.body;
    var temp = {};
    temp.radar = data.radar;
    temp.request = data.request;
    if(temp.request == 'cloneradar'){
        temp['params.clonetype'] = data.params.clonetype;
    }
    now = new Date();
    data["updated"] = now;
    // console.log('DATA:')
    // console.log(data)
    // console.log('TEMP:')
    // console.log(temp)
    botjobs.findOne(temp, {}, { sort:{'_id': -1}}, function(err, findstat){
        // console.log(findstat)
        // console.log(err)
        // console.log("inside botjobs findOne");
        if(findstat != null){
            // console.log('updating entry')
            //console.log(findstat);
            data['numupdated'] = findstat['numupdated']+1;
            // console.log(data);
            botjobs.update({'_id':findstat['_id']},data,{ upsert : true, multi: true },function(err,stat){
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format
            });

        }
        else{
            // console.log('creating new entry')
            data["created"] = now;
            data['numupdated'] = 0;
            botjobs.create(data,function(err, stat) {
                // console.log(stat);
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format. —> line 413 in route.js
            });
        }

    });

});
</code>```

Error:-

```<code>Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.res.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:134:22)
    at ServerResponse.res.set.res.header (/app/node_modules/express/lib/response.js:595:10)
    at ServerResponse.res.send (/app/node_modules/express/lib/response.js:151:12)
    at ServerResponse.res.json (/app/node_modules/express/lib/response.js:237:15)
    at /app/app/routes.js:413:10
</code>```

答:
You can add a condition like this</p>

```<code>if (err)
{
 res.send(err);
}
else
{
 res.json(stat);
}
</code>```

Body:
I am running into the error show below on my app,line 413 points to “res.json(stat); // return in JSON format.” in below code, I looked at other posts with similar error but none helped me, why am I hitting this error ?appreciate any guidance on how to fix it?

app.post('/api/botjobs.json', function(req, res) {
    // console.log(req.body)
    data = req.body;
    var temp = {};
    temp.radar = data.radar;
    temp.request = data.request;
    if(temp.request == 'cloneradar'){
        temp['params.clonetype'] = data.params.clonetype;
    }
    now = new Date();
    data["updated"] = now;
    // console.log('DATA:')
    // console.log(data)
    // console.log('TEMP:')
    // console.log(temp)
    botjobs.findOne(temp, {}, { sort:{'_id': -1}}, function(err, findstat){
        // console.log(findstat)
        // console.log(err)
        // console.log("inside botjobs findOne");
        if(findstat != null){
            // console.log('updating entry')
            //console.log(findstat);
            data['numupdated'] = findstat['numupdated']+1;
            // console.log(data);
            botjobs.update({'_id':findstat['_id']},data,{ upsert : true, multi: true },function(err,stat){
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format
            });

        }
        else{
            // console.log('creating new entry')
            data["created"] = now;
            data['numupdated'] = 0;
            botjobs.create(data,function(err, stat) {
                // console.log(stat);
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format. —> line 413 in route.js
            });
        }

    });

});

Error:-

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.res.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:134:22)
    at ServerResponse.res.set.res.header (/app/node_modules/express/lib/response.js:595:10)
    at ServerResponse.res.send (/app/node_modules/express/lib/response.js:151:12)
    at ServerResponse.res.json (/app/node_modules/express/lib/response.js:237:15)
    at /app/app/routes.js:413:10

Body:
You can add a condition like this

if (err)
{
 res.send(err);
}
else
{
 res.json(stat);
}


问:
Insert an item into for loop using each_with_index, instead of replacing
Most marketplace website's nowadays have an ad partial injected into the middle of the list, giving users a form to sign up.

Looking to get a better understanding into how each_with_index works and the correct way to insert a div into a list of objects. Let's take a list of, say 10 boxing studios, and using the below code we inject a div into the middle of the list. How do you inject a div without replacing the record entirely?

Expected: the 10 boxing studios with new div in the 6th position (11 items in the list in total)

Actual: 9 boxing studios with the new div replacing one of the boxing studios in the 6th position

```<code>@list.each_with_index do |item, idx|
  if((idx + 1) % 6 == 0)
    # Insert ad partial
  else
  # Print out each object in the list
  end
end
</code>```

Body:
Most marketplace website's nowadays have an ad partial injected into the middle of the list, giving users a form to sign up.

Looking to get a better understanding into how each_with_index works and the correct way to insert a div into a list of objects. Let's take a list of, say 10 boxing studios, and using the below code we inject a div into the middle of the list. How do you inject a div without replacing the record entirely?

Expected: the 10 boxing studios with new div in the 6th position (11 items in the list in total)

Actual: 9 boxing studios with the new div replacing one of the boxing studios in the 6th position

@list.each_with_index do |item, idx|
  if((idx + 1) % 6 == 0)
    # Insert ad partial
  else
  # Print out each object in the list
  end
end

Body:
Use Array#[]:

> list = [1,2,3]
#⇒ [1, 2, 3]
> list[1...1] = 0 # insert at position 1
> list
#⇒ [1, 0, 2, 3]

Insert it each 6th position:

list = [1] * 15
(5...list.size).step(6) { |i| list[i...i] = 0 }
list
#⇒ [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]


问:
Show only posts that user has access
I have this 3 tables, one post can be viewed by more than one user:

users

posts

user_posts

How I can do with Eloquent to show to the users only the posts that he has access?

Thanks

答:
Assuming that

users table contain information of users with id

posts table contains details posts with id, user_id

userpost conatains information about users and the posts that they are accessed to with user_id and post_id.

codes are

//users.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class users extends Model
{
    public function posts()
    {
        return $this->hasMany("App\posts");
    }

    public function userPosts()
    {
        return $this->hasMany("App\userpost");
    }
}

```

<blockquote>
  <p>post model</p>
</blockquote>

<pre class="lang-php prettyprint-override"><code>//posts.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class posts extends Model
{
    public function user()
    {
        return $this->belongsTo("App\users");
    }
}

</code>```

userpost model (here user and post that they are accessed)

//userpost.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class userpost extends Model
{
    public function users(){
        return $this->hasMany("App\users");
    }

    public function posts()
    {
        return $this->hasMany("App\posts","id","post_id");
    }
}
```

<blockquote>
  <p>controller can be written as</p>
</blockquote>

<pre class="lang-php prettyprint-override"><code>//PostViewController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\posts;
use App\users;
use App\userpost;

class PostViewController extends Controller
{
    public function view()
    {
        $user_id = 2; //user_id of the user you want to view
        $posts= userpost::where('user_id', $user_id)->get();

        //return $posts; you can return $posts and view it on "view" by using foreach as shown below
        foreach($users as $user)
        {
            return $user->posts;//posts is the function made in model.
        }

    }

}
</code>```

here foreach loop is done only for once to get only one post as return ends the loop. It is only to show how to get data of post which can be done in view to get data

Title: Show only posts that user has access

Body:
Assuming that

users table contain information of users with id

posts table contains details posts with id, user_id

userpost conatains information about users and the posts that they are accessed to with user_id and post_id.

codes are

//users.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class users extends Model
{
    public function posts()
    {
        return $this->hasMany("App\posts");
    }

    public function userPosts()
    {
        return $this->hasMany("App\userpost");
    }
}

post model

//posts.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class posts extends Model
{
    public function user()
    {
        return $this->belongsTo("App\users");
    }
}

userpost model (here user and post that they are accessed)

//userpost.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class userpost extends Model
{
    public function users(){
        return $this->hasMany("App\users");
    }

    public function posts()
    {
        return $this->hasMany("App\posts","id","post_id");
    }
}

controller can be written as

//PostViewController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\posts;
use App\users;
use App\userpost;

class PostViewController extends Controller
{
    public function view()
    {
        $user_id = 2; //user_id of the user you want to view
        $posts= userpost::where('user_id', $user_id)->get();

        //return $posts; you can return $posts and view it on "view" by using foreach as shown below
        foreach($users as $user)
        {
            return $user->posts;//posts is the function made in model.
        }

    }

}

here foreach loop is done only for once to get only one post as return ends the loop. It is only to show how to get data of post which can be done in view to get data


问:
How do I annotate rust variables' data type without assignment?
I'm new to rust, and I'd like to declare a typed variable without initializing it. Is this possible in Rust? If so, is it advisable or are there better, more rustacean-y ways to do it?

I'm looking at the following code from rustlings which fails to compile because it can't infer the type of x:

    let x;
    if x == 10 {
        println!("Ten!");
    }
```

<p>So, I tried this:</p>

<pre class="lang-rust prettyprint-override"><code>let x: i32;
</code>```

however, now the compiler will throw an error on the comparison line saying that x hadn't been declared.

This works fine, but I was left wondering if one can declare the type without an assignment.

let x: i32 = 10;
```

Or is the correct way to do it involve designing your code to avoid such situations in the first place? I come from a C background and I'm probably a little too comfortable with being lazy with types.

答:
You can do this, provided that the compiler can see that it will always have a value assigned before you try to read from it, and it will only ever be assigned once. This can be helpful in peculiar circumstances. Here's a slightly contrived example.

fn main() {
    let some_cond = false;

    let x;
    let y;
    let z: u8;

    if some_cond {
        x = 1;
        y = 2;
        z = 3;
    } else {
        x = 4;
        y = 5;
        z = 6;
    }

    println!("x = {}", x); // "x = 4"
    println!("y = {}", y); // "y = 5"
    println!("z - 10 = {}", z.wrapping_sub(10)); // "z - 10 = 252"
}
```

Body:
I'm new to rust, and I'd like to declare a typed variable without initializing it. Is this possible in Rust? If so, is it advisable or are there better, more rustacean-y ways to do it?

I'm looking at the following code from rustlings which fails to compile because it can't infer the type of x:

    let x;
    if x == 10 {
        println!("Ten!");
    }

So, I tried this:

let x: i32;

however, now the compiler will throw an error on the comparison line saying that x hadn't been declared.

This works fine, but I was left wondering if one can declare the type without an assignment.

let x: i32 = 10;

Or is the correct way to do it involve designing your code to avoid such situations in the first place? I come from a C background and I'm probably a little too comfortable with being lazy with types.


问:
Should I be storing all my Vue methods and data in one file?
I'm currently using Vue on my web app for object oriented form validation, so that all I need is back-end validation and vue takes care of the rest.

This means that if my app has a lot of forms, forms that are mostly just page specific, I end up with a lot of methods and data in my Vue instance.

```<code>new Vue({
    el: '#mainDiv',

    data: {
        profile_text: '',
        name: ''
        //LOTS OF DATA THAT I'M LEAVING OUT
        errors: new Errors()
    },

    methods: {
        onSubmitSettings() {
            axios.post('/settings', this.$data)
                .then(response => alert('Success!'))
                .catch(error => this.errors.record(error.response.data.errors));
        },
        onSubmitCreate() {
            axios.post('/subchannel/create', this.$data)
                .then(response => alert('Success!'))
                .catch(error => this.errors.record(error.response.data.errors));
        },
        //LOTS OF METHODS THAT I'M LEAVING OUT
    }
});
</code>```

and this is all stored in one JS file.

Should I keep doing it like this? Or should I be storing methods/data meant for only one page to be stored on that page somehow?

答:
Assuming that the code you shared is your main/root Vue instance, it probably is a bad practice to put all these in a single component.

Ideally, your code should have segregation of components between views and components. views are like individual pages which contain most of the business logic whereas components are reusable items like checkboxes, lists, inputs, etc..

The reasons for dividing the app into smaller views are:

Putting everything in a root instance will make your components less-reusable. They are depending on some sort of global state.

This makes modifications harder to track; overall making code less maintainable within the team.

Splitting into smaller views/components will allow you to use other ecosystem tools like vue-router which will further help in maintaining URLs, URL history, etc.

Segregation into smaller components will enable Vue.js to better track change detection producing efficient and performant view updates. UI updates become significantly faster.

In a nutshell, it is about following classical software engineering principles like SOLID, loose coupling, etc. This, in general, is not just confined to Vue.js.

Body:
I'm currently using Vue on my web app for object oriented form validation, so that all I need is back-end validation and vue takes care of the rest.

This means that if my app has a lot of forms, forms that are mostly just page specific, I end up with a lot of methods and data in my Vue instance.

new Vue({
    el: '#mainDiv',

    data: {
        profile_text: '',
        name: ''
        //LOTS OF DATA THAT I'M LEAVING OUT
        errors: new Errors()
    },

    methods: {
        onSubmitSettings() {
            axios.post('/settings', this.$data)
                .then(response => alert('Success!'))
                .catch(error => this.errors.record(error.response.data.errors));
        },
        onSubmitCreate() {
            axios.post('/subchannel/create', this.$data)
                .then(response => alert('Success!'))
                .catch(error => this.errors.record(error.response.data.errors));
        },
        //LOTS OF METHODS THAT I'M LEAVING OUT
    }
});

and this is all stored in one JS file.

Should I keep doing it like this? Or should I be storing methods/data meant for only one page to be stored on that page somehow?


问:
How to check if ANY app is playing any type of media on Android device?
I am working on a remote control for integration between Android TV devices and Smartthings Hub. I want to be able to check if any media app is playing anything on the device (Android TV).
If for example, Youtube or Plex app is playing any movie, then I will show the user "playing" , if no app is playing anything , I will display "stopped"

if any type of media (audio or video) is playing, I have to understand this.

I wanted to engage Android mediaplayer with following code, but it did not work:

```<code>            final MediaPlayer player = new MediaPlayer();
            if(player.isPlaying()) {
                response.send("playing");
            }
            else {
                response.send("stopped");
            }
</code>```

I am not sure if this instance will attach to the active media player and I couldn't find the correct way. What am I missing ?

答:
you should use AudioManager for sound , check the documentation

```<code>AudioManager.isMusicActive();
</code>```

and for video , The SurfaceFlinger process can know that it is receiving frames at a consistent rate, but it can't know if it's a video or just app animation.

The mediaserver process is responsible for managing the hardware video decoders. It can know if a video is being decoded, but it can't know if the video is being displayed. It won't be involved if the app is using a custom software-only decoder.

There isn't an unequivocal way to detect that a video is being played and presented on the display.

Body:
I am working on a remote control for integration between Android TV devices and Smartthings Hub. I want to be able to check if any media app is playing anything on the device (Android TV).
If for example, Youtube or Plex app is playing any movie, then I will show the user "playing" , if no app is playing anything , I will display "stopped"

if any type of media (audio or video) is playing, I have to understand this.

I wanted to engage Android mediaplayer with following code, but it did not work:

            final MediaPlayer player = new MediaPlayer();
            if(player.isPlaying()) {
                response.send("playing");
            }
            else {
                response.send("stopped");
            }

I am not sure if this instance will attach to the active media player and I couldn't find the correct way. What am I missing ?

Body:
you should use AudioManager for sound , check the documentation

AudioManager.isMusicActive();

and for video , The SurfaceFlinger process can know that it is receiving frames at a consistent rate, but it can't know if it's a video or just app animation.

The mediaserver process is responsible for managing the hardware video decoders. It can know if a video is being decoded, but it can't know if the video is being displayed. It won't be involved if the app is using a custom software-only decoder.

There isn't an unequivocal way to detect that a video is being played and presented on the display.


问:
how to use tower-cli to schedule a job
I have an ansible-tower template that I want to run at a specific time in the future. To do this I believe I should run tower-cli schedule create then pass some parameters to the program, however I don't know how to pass the date/time parameter.

I have looked at this document however it doesn't seem to include such a parameter. How does one do this?

答:
It looks like, based on some example issues that they are using the RRULE property from the iCalendar but why they would omit such a crucial detail from every single document in the Internet I can only chalk up to "please buy Tower and pay us all the $$$$$$$$"

Even the help text for schedule.py is abysmally useless.

I hope knowing that it is RFC-5545 compatible helps unstick you from your problem, and I hope you file an issue against tower-cli letting them know that you were not provided very basic information to be successful with their tool.

Title: how to use tower-cli to schedule a job


问:
Bulk insert from Python list/dict to Oracle Database using cx_Oracle executemany()
I am inserting data from a Python dictionary to Oracle DB. I used executemany() from cursor class. I get the following error:

ORA-01036: illegal variable name/number

Also, when I use try/except for executemany() I get an additional error:

cx_Oracle.DatabaseError: DPI-1010: not connected

Environment:
Python: 3.6.7, Oracle: 12c, cx_Oracle: 7.1.2, OS: Ubuntu

I converted the Dictionary data to a List of Dictionary and passed that as the second parameter of executemany(), but get the same errors.
Here is how my list of dictionaries looks like

```<code>    [{'location': 1, 'xxx_id': 917985, 'seq': 758, 'event_time':
    datetime.datetime(2019, 5, 5, 20, 1, 53), 'event_type': 'xxxx', 'number':
    123, 'stop': '40305', 'x': None, 'y': None, 'arrival_time':
    datetime.datetime(2019, 5, 5, 20, 1, 33), 'departure_time':
    datetime.datetime(2019, 5, 5, 20, 2), 'yyy_id': 529934, 'zzz_id': 59359277},
   {'location': 1, 'xxx_id': 917985, 'seq': 759, 'event_time':
   datetime.datetime(2019, 5, 5, 20, 2, 33), 'event_type': 'xxxx', 'number':
   123, 'stop': '40301', 'x': None, 'y': None, 'arrival_time':
   datetime.datetime(2019, 5, 5, 20, 2, 27), 'departure_time':
   datetime.datetime(2019, 5, 5, 20, 2, 50), 'yyy_id': 529930, 'zzz_id': 59279},

   {.......},
   {.......}
   ]
</code>```

Tried other recommendations from stackoverflow, but no luck. the closest to my situation is this one. Insert a list of dictionaries into an SQL table using python

Here is my code I tried

```<code>    sql_insert = '''INSERT INTO TABLE_NAME (LOCATION, XXX_ID, SEQ,
    EVENT_TIME, EVENT_TYPE, NUMBER, STOP, X, Y, ARRIVAL_TIME, DEPARTURE_TIME,
    YYY_ID, ZZZ_ID)
    VALUES(:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13)'''

    for k1, v1 in events.items():
        list_events = []
        for k2, v2 in v1.items():
            x = dict(v2)
            # print(x)
            list_events.append(x)
            cursor = connection.cursor()
        try:
            cursor.executemany(sql_insert, list_events)
            connection.commit()
        except cx_Oracle.DatabaseError as e:
            print(e)
</code>```

I am trying to insert few thousands of records. Any help would be highly appreciable.

答:
See Efficient and Scalable Batch Statement Execution in Python cx_Oracle.

You want something like:

```<code>data = [
    (60, "Parent 60"),
    (70, "Parent 70"),
    (80, "Parent 80"),
    (90, "Parent 90"),
    (100, "Parent 100")
]

cursor.executemany("""
        insert into ParentTable (ParentId, Description)
        values (:1, :2)""", data)
</code>```

Body:
I am inserting data from a Python dictionary to Oracle DB. I used executemany() from cursor class. I get the following error:

ORA-01036: illegal variable name/number

Also, when I use try/except for executemany() I get an additional error:

cx_Oracle.DatabaseError: DPI-1010: not connected

Environment:
Python: 3.6.7, Oracle: 12c, cx_Oracle: 7.1.2, OS: Ubuntu

I converted the Dictionary data to a List of Dictionary and passed that as the second parameter of executemany(), but get the same errors.
Here is how my list of dictionaries looks like

    [{'location': 1, 'xxx_id': 917985, 'seq': 758, 'event_time':
    datetime.datetime(2019, 5, 5, 20, 1, 53), 'event_type': 'xxxx', 'number':
    123, 'stop': '40305', 'x': None, 'y': None, 'arrival_time':
    datetime.datetime(2019, 5, 5, 20, 1, 33), 'departure_time':
    datetime.datetime(2019, 5, 5, 20, 2), 'yyy_id': 529934, 'zzz_id': 59359277},
   {'location': 1, 'xxx_id': 917985, 'seq': 759, 'event_time':
   datetime.datetime(2019, 5, 5, 20, 2, 33), 'event_type': 'xxxx', 'number':
   123, 'stop': '40301', 'x': None, 'y': None, 'arrival_time':
   datetime.datetime(2019, 5, 5, 20, 2, 27), 'departure_time':
   datetime.datetime(2019, 5, 5, 20, 2, 50), 'yyy_id': 529930, 'zzz_id': 59279},

   {.......},
   {.......}
   ]

Tried other recommendations from stackoverflow, but no luck. the closest to my situation is this one. Insert a list of dictionaries into an SQL table using python

Here is my code I tried

    sql_insert = '''INSERT INTO TABLE_NAME (LOCATION, XXX_ID, SEQ,
    EVENT_TIME, EVENT_TYPE, NUMBER, STOP, X, Y, ARRIVAL_TIME, DEPARTURE_TIME,
    YYY_ID, ZZZ_ID)
    VALUES(:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13)'''

    for k1, v1 in events.items():
        list_events = []
        for k2, v2 in v1.items():
            x = dict(v2)
            # print(x)
            list_events.append(x)
            cursor = connection.cursor()
        try:
            cursor.executemany(sql_insert, list_events)
            connection.commit()
        except cx_Oracle.DatabaseError as e:
            print(e)

I am trying to insert few thousands of records. Any help would be highly appreciable.

Body:
See Efficient and Scalable Batch Statement Execution in Python cx_Oracle.

You want something like:

data = [
    (60, "Parent 60"),
    (70, "Parent 70"),
    (80, "Parent 80"),
    (90, "Parent 90"),
    (100, "Parent 100")
]

cursor.executemany("""
        insert into ParentTable (ParentId, Description)
        values (:1, :2)""", data)


问:
Angular focus on input while clicking an element
I have attached the stackblitz below

https://stackblitz.com/edit/angular-dgx3pe

What i am trying to achieve is while clicking on the label element it should focus on the input.Hence the input:focus  class gets activated.What I belive is that it can be achievable through javascript/jquery.But i prefer the angular way to achieve this.

In Brief,these are the two things i am trying to do,

Make focus on the input element when label is clicked.

When the focus is changed to another input element and if the previous element is not empty(If some value is typed in).The label should maintain its position in the top.

HTML

```<code><input class="input" type="text">
<label class="label">Name</label>

<div>
<input class="input" type="text">
<label class="label">Name</label>
</div>
</code>```

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}
```

答:
You can do this with pure markup. You need to add an id to the input and a for element to the label

```<code><input class="input" type="text" id="firstName">
<label class="label" for="firstName" >First Name</label>
</code>```

This is just part of the html spec - labels can be associated with inputs - the out of the box functionality here is that on clicking a label it sets focus to its associated input. id and for attributes must match for this to work.

For the second part of your question, and to reuse your css classes - add matching variables to your component. Use ngClass to add the .go-top class when the variable has a value

In component -

```<code>firstName: string;
</code>```

Then in the html -

```<code>  <input class="input" type="text" id="firstName" [(ngModel)]="firstName">
  <label class="label" for="firstName" [ngClass]="{'go-top': firstName}">First Name</label>
</code>```

Body:
I have attached the stackblitz below

https://stackblitz.com/edit/angular-dgx3pe

What i am trying to achieve is while clicking on the label element it should focus on the input.Hence the input:focus  class gets activated.What I belive is that it can be achievable through javascript/jquery.But i prefer the angular way to achieve this.

In Brief,these are the two things i am trying to do,

Make focus on the input element when label is clicked.

When the focus is changed to another input element and if the previous element is not empty(If some value is typed in).The label should maintain its position in the top.

HTML

<input class="input" type="text">
Name

<input class="input" type="text">
Name

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}

Body:
You can do this with pure markup. You need to add an id to the input and a for element to the label

<input class="input" type="text" id="firstName">
<label class="label" for="firstName" >First Name</label>

This is just part of the html spec - labels can be associated with inputs - the out of the box functionality here is that on clicking a label it sets focus to its associated input. id and for attributes must match for this to work.

For the second part of your question, and to reuse your css classes - add matching variables to your component. Use ngClass to add the .go-top class when the variable has a value

In component -

firstName: string;

Then in the html -

  <input class="input" type="text" id="firstName" [(ngModel)]="firstName">
  <label class="label" for="firstName" [ngClass]="{'go-top': firstName}">First Name</label>


问:
Do I need a Ruby database client for mongodb when I have mongoid?
I've been working on Rails apps with traditional databases, read SQL databases. Am trying to get myself familiar with NoSQL particularly MongoDB.
I need to get a logical mapping between ActiveRecord and Mongoid. In the apps i've worked on in the past, My stack was: ActiveRecord, the pg gem (postgresql client) and postgresql, as the persistent data store. In the NoSQL app, I have Mongoid, and MongoDB. Do i need an equivalent of the pg gem or does mongoid take care of all that?</p>

答:
The equivalent of pg in the MongoDB stack is mongo, the MongoDB Ruby driver.

https://rubygems.org/gems/mongo

Mongoid depends on mongo and uses mongo for low level operations (CRUD, etc.).


问:
Sorting of IEnumerable<T> in MVC 2
My Service layer returns a IEnumerable<ResortsView> to my Controller and I have to provide an option to SORT the results on UI by following criteria: Price (Excluding ZERO Price Items), SupplierName & Rating. Here is the code snippet of my objects/classes:

```<code>[Serializable]
public class ResortsView : SupplierView
{
    public IList<ProductView> ResortProducts { get; set; }
    public string CheckInTime { get; set; }
    public string CheckOutTime { get; set; }
    public virtual IList<ImageView> Images { get; set; }
}

[Serializable]
public class SupplierView
{
    public string SupplierID { get; set; }
    public string SupplierName { get; set; }
    public string Description { get; set; }
    public string Rating { get; set; }
    public string URL { get; set; }
}

[Serializable]
public class ProductView
{
    public string Code { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public ErrorView PricingError { get; set; }
}
</code>```

What is the best way to handle sorting of results inside IEnumerable<ResortsView>?

答:
Use the OrderBy method of the LINQ stack:

```<code>IEnumerable<ResortsView> source = GetResorts();
var model = source.OrderBy(rv => rv.CheckInTime);
</code>```

To order by the lowest, non-zero price in ResortProducts:

```<code>var model = source.OrderBy(rv => rv.ResortProducts.Where(p => p.Price > 0).Min(p => p.Price));
</code>```

Title: Sorting of IEnumerable<T> in MVC 2

Body:
My Service layer returns a IEnumerable<ResortsView> to my Controller and I have to provide an option to SORT the results on UI by following criteria: Price (Excluding ZERO Price Items), SupplierName & Rating. Here is the code snippet of my objects/classes:

[Serializable]
public class ResortsView : SupplierView
{
    public IList<ProductView> ResortProducts { get; set; }
    public string CheckInTime { get; set; }
    public string CheckOutTime { get; set; }
    public virtual IList<ImageView> Images { get; set; }
}

[Serializable]
public class SupplierView
{
    public string SupplierID { get; set; }
    public string SupplierName { get; set; }
    public string Description { get; set; }
    public string Rating { get; set; }
    public string URL { get; set; }
}

[Serializable]
public class ProductView
{
    public string Code { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public ErrorView PricingError { get; set; }
}

What is the best way to handle sorting of results inside IEnumerable<ResortsView>?

Body:
Use the OrderBy method of the LINQ stack:

IEnumerable<ResortsView> source = GetResorts();
var model = source.OrderBy(rv => rv.CheckInTime);

To order by the lowest, non-zero price in ResortProducts:

var model = source.OrderBy(rv => rv.ResortProducts.Where(p => p.Price > 0).Min(p => p.Price));


问:
Where is the live templates for Java in Intellij-IDEA?

I could not find the live templates for Java! Who can tell me how to set? Thanks.

答:
For those of you who have taken Postfix completion for Live templates, it is worth mentioning they are different. from not-choosing pretty good answers from @JB Niznet and @vitfo, I guess that's the case for OP writer. The document, here, says:

Postfix code completion is similar to live templates, it transforms the current expression without selecting it. For example, you can type .if after an expression to invoke the corresponding postfix completion and wrap the expression with an if statement.

You can check out a list of postfix completions:

Open the Preferences window

Click on Editor -> General -> Postfix completion


问:
How IntStream avoid hidden boxing costs
When you have

```<code>Stream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);
</code>```

versus

```<code>IntStream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);
</code>```

How does `IntStream? avoid the hidden boxing costs?

And why is boxing expensive in terms of performance?

答:
IntStream is a specialization of Stream<T> which process int primitive values.

Look at IntStream interface:

```<code>IntStream filter(IntPredicate predicate);
IntStream map(IntUnaryOperator mapper);
...
</code>```

You can see that this interface use only int primitive specialized version of Predicate, Function, Consumer... so it does not require boxing to work with int (because it operates directly with int)

About the performance cost of autoboxing, you can refer to java guide:

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code

It's because, every time you invoke an operation requires both int or Integer or put int to an Integer container, the compiler inject a box/unbox method call for you.

The performance is rather insignificant for normal operations but if you have an intensive loops or time critical lines of code then you should avoid autoboxing.

Title: How IntStream avoid hidden boxing costs

Body:
When you have

Stream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);

versus

IntStream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);

How does `IntStream? avoid the hidden boxing costs?

And why is boxing expensive in terms of performance?

Body:
IntStream is a specialization of Stream<T> which process int primitive values.

Look at IntStream interface:

IntStream filter(IntPredicate predicate);
IntStream map(IntUnaryOperator mapper);
...

You can see that this interface use only int primitive specialized version of Predicate, Function, Consumer... so it does not require boxing to work with int (because it operates directly with int)

About the performance cost of autoboxing, you can refer to java guide:

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code

It's because, every time you invoke an operation requires both int or Integer or put int to an Integer container, the compiler inject a box/unbox method call for you.

The performance is rather insignificant for normal operations but if you have an intensive loops or time critical lines of code then you should avoid autoboxing.


问:
How does react update part of the DOM?
I know that this subject has been discussed a lot obviously, but I'm not sure how to research my question that is rather specific and I hope it follows the rules here.

I know that to decide whether to update the DOM or not, react compares the virtual DOM with the re-rendered one. But I just didn't understand if in case it does decide to update it - does it update all the elements of the specific re-rendered component, or does it know to update only the changed elements of the componenet?

Thanks in advance,

答:
Execution of the render() method does not mean that react also renders the actual DOM.
React keeps two copies of the virtual DOM i.e. the old virtual DOM and the re-rendered virtual DOM which gets created when the render() method is called.

The output of the render() method is a javascript object which is mapped to a DOM element. When a component is changed, we get a new react element. It then compares the new react element and its children in the re-rendered virtual DOM with the element and its children in the old virtual  DOM. If any differences found, it then updates the real DOM only at the places where something has changed (e.g Text of the button has changed) and not update the entire real DOM. If no differences found, the real DOM is not touched.

Title: How does react update part of the DOM?


问:
Is there a functional difference between -OutVariable and variable assignment?
I came across the following bizarre behavior and I was hoping someone could point me to some documentation that can explain why this behavior happens or what is causing it.

I have tried looking at the documentation for New-SelfSignedCertificate to see if there was a remark explaining this or a parameter that "forced" it to complete but didn't find anything useful. https://learn.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps

I also tried searching google for OutVariable vs assignment but didn't find anything helpful either.

Consider the following functions:

function Why-DoesThisFail {
    $cert = New-SelfSignedCertificate -Type Custom -Subject "CN=test" -KeyAlgorithm "RSA" -KeyLength 2048 `
        -CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddDays(1) -KeySpec Signature `
        -KeyExportPolicy NonExportable;

    # Note that this outputs fine.
    Write-Host $cert.Thumbprint;

    # Prints nothing
    Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";
}

function Why-DoesThisPass {
    New-SelfSignedCertificate -Type Custom -Subject "CN=test" -KeyAlgorithm "RSA" -KeyLength 2048 `
        -CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddDays(1) -KeySpec Signature `
        -KeyExportPolicy NonExportable -OutVariable cert;

    # Note that this outputs fine.
    Write-Host $cert.Thumbprint;

    # Prints Cert as expected
    Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";
}

```

Notice that the only difference between the 2 functions is one is using variable assignment and one is using the OutVariable. Is this a behavior of Powershell itself in how it is handling OutVariable vs assignment; or is this because of something that New-SelfSignedCertificate is doing behind the covers? It feels almost as if the Certificate isn't being registered on the machine until after the New-SelfSignedCertificate completes and it doesn't complete for some reason when variable assignment is used. Note that after the function completes and control is returned to Powershell, you can successfully run the last line (replacing the thumbprint with the one written from Write-Host) and retrieve the certificate from the machine.

I'm puzzled.

Thanks for any help!

答:
Your issue, is not with any confusion or context with this?

-OutVariable and variable assignment?

It's because you are using the line in the first one wrong. Double quotes do coerce variable expansion, but in your case you need to change the string interpolation for that dotted $cert variable. So, you are having a misunderstanding about string expansion.

This...

```<code>Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";
</code>```

... should be done this way.

```<code>Get-ChildItem -Path "Cert:\CurrentUser\My\$($cert.Thumbprint)"
</code>```

... otherwise, PowerShell does not know what it is. Also, those semi-colon(s) is never really needed in PowerShell proper. It is a special marker separating distinct code segments. If you had this all on one line, that's at thing, but not how you are using it here.

If you are doing this in the ISE or VSCode, you'll see the color coding change to reflect the which will be expanded and which will not.

See this article.
Powershell String Expansion

Variable Interpolation, or Two Types of Strings Strings with single
  quotes (') are literal strings, meaning there are no special
  characters; every character in the string will output as itself.
  Strings with double quotes (") in powershell will expand variables and
  escape characters inside the string; this is referred to as
  interpolation.

And this one, though it talks to Here-Strings, it still covers the point I am trying to make here.

Variable expansion in strings and here-strings

Now as for your post question...

Is there a functional difference between -OutVariable and variable
  assignment?

...  The send result of either is the same. However, this is the deal...
You can store the output of a command in a variable and at the sametime have this output on the screen. This what Out-Variable also does, whereas variable assignment does no output. Yet it can, if you use variable squeezing. So, this...

```<code>Get-ChildItem -OutVariable files
</code>```

... this ...

```<code>($files = Get-ChildItem)
</code>```

... will do the same thing. Assign the results to the variable, and output to the screen at the same time.

See this ---
3 ways to store and display PowerShell Variable simultaneously

Using -OutVariable parameter

PowerShell Variable squeezing Using

Tee-Object Cmdlet

Lastly, avoid the use of Write-Host, unless you are doing text screen coloring. PowerShell, will output to the screen is the default, unless you tell it otherwise. So, this

```<code>Write-Host $cert.Thumbprint
Write-Host 'Hello'
</code>```

...  and this …

```<code>$cert.Thumbprint
'Hello'
</code>```

... will do the same thing.

If you must use Write-*, because of your chosen coding practice, then choose Write-Output.

Update for Andrei Odegov point / pointer

Yes, they just output hello to the screen. Try it.

```<code>Write-Host 'hello'

# results
hello

'Hello'

# results

Hello
</code>```

As for your link ...

Is your last statement that Write-Host "Hello" and "Hello" do the same
  thing, correct? Look at stackoverflow.com/questions/8755497/…

... these all do the same thing. Output to the screen.

```<code>$count = 5

write-host "count=" + $count

# results
count= + 5

write-host "count = $count"

# results
count = 5

"count =  $count"

# results

count =  5

"count=" + $count

# Results

count=5
</code>```

That first one is why string concatenation can be, well, has issues. I am not the only one who thinks so. See this video.

From the authors ofThe Big book of 'The PowerShell Gotcha's'

Don't Concatenate Strings

https://devops-collective-inc.gitbook.io/the-big-book-of-powershell-gotchas

https://www.youtube.com/results?search_query=don%27t+concatenate+string

Body:
I came across the following bizarre behavior and I was hoping someone could point me to some documentation that can explain why this behavior happens or what is causing it.

I have tried looking at the documentation for New-SelfSignedCertificate to see if there was a remark explaining this or a parameter that "forced" it to complete but didn't find anything useful. https://learn.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps

I also tried searching google for OutVariable vs assignment but didn't find anything helpful either.

Consider the following functions:

function Why-DoesThisFail {
    $cert = New-SelfSignedCertificate -Type Custom -Subject "CN=test" -KeyAlgorithm "RSA" -KeyLength 2048 `
        -CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddDays(1) -KeySpec Signature `
        -KeyExportPolicy NonExportable;

    # Note that this outputs fine.
    Write-Host $cert.Thumbprint;

    # Prints nothing
    Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";
}

function Why-DoesThisPass {
    New-SelfSignedCertificate -Type Custom -Subject "CN=test" -KeyAlgorithm "RSA" -KeyLength 2048 `
        -CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddDays(1) -KeySpec Signature `
        -KeyExportPolicy NonExportable -OutVariable cert;

    # Note that this outputs fine.
    Write-Host $cert.Thumbprint;

    # Prints Cert as expected
    Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";
}

Notice that the only difference between the 2 functions is one is using variable assignment and one is using the OutVariable. Is this a behavior of Powershell itself in how it is handling OutVariable vs assignment; or is this because of something that New-SelfSignedCertificate is doing behind the covers? It feels almost as if the Certificate isn't being registered on the machine until after the New-SelfSignedCertificate completes and it doesn't complete for some reason when variable assignment is used. Note that after the function completes and control is returned to Powershell, you can successfully run the last line (replacing the thumbprint with the one written from Write-Host) and retrieve the certificate from the machine.

I'm puzzled.

Thanks for any help!

Body:
Your issue, is not with any confusion or context with this?

-OutVariable and variable assignment?

It's because you are using the line in the first one wrong. Double quotes do coerce variable expansion, but in your case you need to change the string interpolation for that dotted $cert variable. So, you are having a misunderstanding about string expansion.

This...

Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";

... should be done this way.

Get-ChildItem -Path "Cert:\CurrentUser\My\$($cert.Thumbprint)"

... otherwise, PowerShell does not know what it is. Also, those semi-colon(s) is never really needed in PowerShell proper. It is a special marker separating distinct code segments. If you had this all on one line, that's at thing, but not how you are using it here.

If you are doing this in the ISE or VSCode, you'll see the color coding change to reflect the which will be expanded and which will not.

See this article.
Powershell String Expansion

Variable Interpolation, or Two Types of Strings Strings with single
  quotes (') are literal strings, meaning there are no special
  characters; every character in the string will output as itself.
  Strings with double quotes (") in powershell will expand variables and
  escape characters inside the string; this is referred to as
  interpolation.

And this one, though it talks to Here-Strings, it still covers the point I am trying to make here.

Variable expansion in strings and here-strings

Now as for your post question...

Is there a functional difference between -OutVariable and variable
  assignment?

...  The send result of either is the same. However, this is the deal...
You can store the output of a command in a variable and at the sametime have this output on the screen. This what Out-Variable also does, whereas variable assignment does no output. Yet it can, if you use variable squeezing. So, this...

Get-ChildItem -OutVariable files

... this ...

($files = Get-ChildItem)

... will do the same thing. Assign the results to the variable, and output to the screen at the same time.

See this ---
3 ways to store and display PowerShell Variable simultaneously

Using -OutVariable parameter

PowerShell Variable squeezing Using

Tee-Object Cmdlet

Lastly, avoid the use of Write-Host, unless you are doing text screen coloring. PowerShell, will output to the screen is the default, unless you tell it otherwise. So, this

Write-Host $cert.Thumbprint
Write-Host 'Hello'

...  and this …

$cert.Thumbprint
'Hello'

... will do the same thing.

If you must use Write-*, because of your chosen coding practice, then choose Write-Output.

Update for Andrei Odegov point / pointer

Yes, they just output hello to the screen. Try it.

Write-Host 'hello'

# results
hello

'Hello'

# results

Hello

As for your link ...

Is your last statement that Write-Host "Hello" and "Hello" do the same
  thing, correct? Look at stackoverflow.com/questions/8755497/…

... these all do the same thing. Output to the screen.

$count = 5

write-host "count=" + $count

# results
count= + 5

write-host "count = $count"

# results
count = 5

"count =  $count"

# results

count =  5

"count=" + $count

# Results

count=5

That first one is why string concatenation can be, well, has issues. I am not the only one who thinks so. See this video.

From the authors ofThe Big book of 'The PowerShell Gotcha's'

Don't Concatenate Strings

https://devops-collective-inc.gitbook.io/the-big-book-of-powershell-gotchas

https://www.youtube.com/results?search_query=don%27t+concatenate+string


问:
How to save images with the same name to the different direction using PIL and os.path?
While trying to split the path to get a name, I get the traceback:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?

I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.

```<code>import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
    image_name_and_ext = os.path.splitext(image[0])
    name = image_name_and_ext[0] + '.png'
    name = os.path.splitext(image)[0] + '.png'
    file_path = os.path.join(path, name)
    image.save(file_path, quality=quality_val)
</code>```

答:
By the code above you will get image in thumbnails I recommend to use resize function because from resize you can maintain you aspect ratio that helps you in getting better results.

```<code>image.thumbnail((640, 428), Image.ANTIALIAS)
</code>```

this line of code is converting your thumbnail.which is not good approach of resizing. Try the code below.

```<code>import os
from PIL import Image

PATH = "F:\\FYP DATASET\\images\\outliers Dataset\\Not Outliers\\"
Copy_to_path="F:\\FYP DATASET\\images\\outliers Dataset\\"

for filename in os.listdir(PATH):
    img = Image.open(os.path.join(PATH, filename)) # images are color images
    img = img.resize((224,224), Image.ANTIALIAS)
    img.save(Copy_to_path+filename+'.jpeg')
</code>```

In this code you are taking images directly from folder resize them and saving them to other location with same name. All the images are processing one by one So you need not worry to load all the images at once into the memory.

Body:
While trying to split the path to get a name, I get the traceback:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?

I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.

import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
    image_name_and_ext = os.path.splitext(image[0])
    name = image_name_and_ext[0] + '.png'
    name = os.path.splitext(image)[0] + '.png'
    file_path = os.path.join(path, name)
    image.save(file_path, quality=quality_val)

Body:
By the code above you will get image in thumbnails I recommend to use resize function because from resize you can maintain you aspect ratio that helps you in getting better results.

image.thumbnail((640, 428), Image.ANTIALIAS)

this line of code is converting your thumbnail.which is not good approach of resizing. Try the code below.

import os
from PIL import Image

PATH = "F:\\FYP DATASET\\images\\outliers Dataset\\Not Outliers\\"
Copy_to_path="F:\\FYP DATASET\\images\\outliers Dataset\\"

for filename in os.listdir(PATH):
    img = Image.open(os.path.join(PATH, filename)) # images are color images
    img = img.resize((224,224), Image.ANTIALIAS)
    img.save(Copy_to_path+filename+'.jpeg')

In this code you are taking images directly from folder resize them and saving them to other location with same name. All the images are processing one by one So you need not worry to load all the images at once into the memory.


问:
UNION ALL vs OR condition in sql server query
I have to select some rows based on a not exists condition on a table. If I use a union all as below, it gets executed in less than 1 second.

```<code>SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col1 AND Data2=t.Col2

UNION ALL

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col2 AND Data2=t.Col1

)
</code>```

but if I use an OR condition, it takes close to a minute as SQL server is doing a table lazy pool. Can someone explain it?

```<code>SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE ( (Data1 = t.Col1 AND Data2=t.Col2) OR (Data1 = t.Col2 AND Data2=t.Col1))
)
</code>```

答:
The query plan is also affected by the number of rows in your tables. How many rows are there in table t ?

You could also try:

```<code>SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(
  SELECT 1 FROM TABLE t
  WHERE Data1 = t.Col1 AND Data2=t.Col2
)
AND NOT EXISTS
(
  SELECT 1 FROM TABLE t
  WHERE Data1 = t.Col2 AND Data2=t.Col1
)
</code>```

or (corrected for SQL-Server) this that will use the index:

```<code>WITH tt AS                               <---- a temp table with 2 rows
( SELECT Data1 AS Col1, Data2 AS Col2
  UNION
  SELECT Data2 AS Col1, Data1 AS Col2
)
SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(
  SELECT 1
  FROM TABLE t
    JOIN tt
      ON tt.Col1 = t.Col1 AND tt.Col2=t.Col2
)
</code>```

Body:
I have to select some rows based on a not exists condition on a table. If I use a union all as below, it gets executed in less than 1 second.

SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col1 AND Data2=t.Col2

UNION ALL

SELECT 1 FROM TABLE t
WHERE Data1 = t.Col2 AND Data2=t.Col1

)

but if I use an OR condition, it takes close to a minute as SQL server is doing a table lazy pool. Can someone explain it?

SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(

SELECT 1 FROM TABLE t
WHERE ( (Data1 = t.Col1 AND Data2=t.Col2) OR (Data1 = t.Col2 AND Data2=t.Col1))
)

Body:
The query plan is also affected by the number of rows in your tables. How many rows are there in table t ?

You could also try:

SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(
  SELECT 1 FROM TABLE t
  WHERE Data1 = t.Col1 AND Data2=t.Col2
)
AND NOT EXISTS
(
  SELECT 1 FROM TABLE t
  WHERE Data1 = t.Col2 AND Data2=t.Col1
)

or (corrected for SQL-Server) this that will use the index:

WITH tt AS                               <---- a temp table with 2 rows
( SELECT Data1 AS Col1, Data2 AS Col2
  UNION
  SELECT Data2 AS Col1, Data1 AS Col2
)
SELECT 1 FROM dummyTable
WHERE NOT EXISTS
(
  SELECT 1
  FROM TABLE t
    JOIN tt
      ON tt.Col1 = t.Col1 AND tt.Col2=t.Col2
)


问:
Using Custom Font - Failed to decode downloaded font in Oracle Apex
I'm trying to use some customized font in my application.

So i tried downloading Pacifico and trying to use in my application. But getting Failed to decode downloaded font and the font is not loading

Below is my CSS .

```<code>@font-face {
  font-family: 'MyWebFont';
  src:  url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}
</code>```

This is not working. So i tried converting this to .woff as per suggestions found in web and tried below. Even this is failing. I'm using Chrome 74.0 version . How to solve this?

```<code>@font-face {
  font-family: 'MyWebFont';
  src: url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf'),
       url('#WORKSPACE_IMAGES#Pacifico.woff')  format('woff'),
       url('#WORKSPACE_IMAGES#Pacifico.woff2')  format('woff2');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}
</code>```

答:
Problem here is you need upload the font into /i/

```<code>@font-face {
      font-family: "Pacifico";
      src: url("http://localhost:8080/i/Pacifico.ttf");
    }

body {
    font-family: "Pacifico", serif;
    font-weight: 300 !important;
    line-height: 25px !important;
    font-size: 14px !important;
}
</code>```

I don't know why Apex is not resolving the #WORKSPACE_IMAGES# but you can upload the font in the web server. In my case I'm using tomcat

Body:
I'm trying to use some customized font in my application.

So i tried downloading Pacifico and trying to use in my application. But getting Failed to decode downloaded font and the font is not loading

Below is my CSS .

@font-face {
  font-family: 'MyWebFont';
  src:  url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}

This is not working. So i tried converting this to .woff as per suggestions found in web and tried below. Even this is failing. I'm using Chrome 74.0 version . How to solve this?

@font-face {
  font-family: 'MyWebFont';
  src: url('#WORKSPACE_IMAGES#Pacifico.ttf')  format('ttf'),
       url('#WORKSPACE_IMAGES#Pacifico.woff')  format('woff'),
       url('#WORKSPACE_IMAGES#Pacifico.woff2')  format('woff2');
}

body {
    font-family: 'MyWebFont', sans-serif;
    font-weight: 300;
    line-height: 25px;
    font-size: 14px;
}

Body:
Problem here is you need upload the font into /i/

@font-face {
      font-family: "Pacifico";
      src: url("http://localhost:8080/i/Pacifico.ttf");
    }

body {
    font-family: "Pacifico", serif;
    font-weight: 300 !important;
    line-height: 25px !important;
    font-size: 14px !important;
}

I don't know why Apex is not resolving the #WORKSPACE_IMAGES# but you can upload the font in the web server. In my case I'm using tomcat