问:
2 Vectors under for loop
I have a dataframe df with ID column. I am trying to make all possible combination between another vector called dates

```<code>df

ID
Asda
Dsaa
Fasd
Das

dates <- seq(as.Date("2019-12-27"), as.Date(" "), by=1)
</code>```

I have written a following for loop. But I get only below result

```<code>for (i in df$ID) {
  for (j in dates) {
    new_value <- c(i, j)
  }
}
</code>```

Result below

```<code>new_value
        ID        Date
      "Das"     "18258"
</code>```

Expected result is : Can i get all combination of ID and dates?

答:
It is not a for loop but for the sake of completeness (expand.grid and mergeare R base nice answers) here is another solution using tidyr::crossing(). I am not sure why you would do so here since it is harder to optimise (see here a nice article from Miles Mcbain for-loops ).

dfr <- data.frame(id = paste0("id", 1:10), dates = seq.Date(from = as.Date("2019-12-27"), by = 1, length.out = 10 ) )
dfr
#>      id      dates
#> 1   id1 2019-12-27
#> 2   id2 2019-12-28
#> 3   id3 2019-12-29
#> 4   id4 2019-12-30
#> 5   id5 2019-12-31
#> 6   id6 2020-01-01
#> 7   id7 2020-01-02
#> 8   id8 2020-01-03
#> 9   id9 2020-01-04
#> 10 id10 2020-01-05

tidyr::crossing(dfr$id, dfr$dates)
#> # A tibble: 100 x 2
#>    `dfr$id` `dfr$dates`
#>    <fct>    <date>
#>  1 id1      2019-12-27
#>  2 id1      2019-12-28
#>  3 id1      2019-12-29
#>  4 id1      2019-12-30
#>  5 id1      2019-12-31
#>  6 id1      2020-01-01
#>  7 id1      2020-01-02
#>  8 id1      2020-01-03
#>  9 id1      2020-01-04
#> 10 id1      2020-01-05
#> # ... with 90 more rows
```

Title: 2 Vectors under for loop

Body:
I have a dataframe df with ID column. I am trying to make all possible combination between another vector called dates

df

ID
Asda
Dsaa
Fasd
Das

dates <- seq(as.Date("2019-12-27"), as.Date(" "), by=1)

I have written a following for loop. But I get only below result

for (i in df$ID) {
  for (j in dates) {
    new_value <- c(i, j)
  }
}

Result below

new_value
        ID        Date
      "Das"     "18258"

Expected result is : Can i get all combination of ID and dates?


来源: stackexchange

问:
What's the best practice for these kinds of routes?
I have a Job model that belongs_to three users (customer, employee, and qa). The customer is set to current_user when the job is created, but the employee and qa users pick their jobs from the pool of unclaimed jobs.

The way I have this implemented currently is as follows: match 'jobs/:id/assign/:type/:user_id' => 'jobs#assign' with an assign method with a case statement on params[:type]. So, for example, jobs/1/assign/qa/1 assigns user 1 as the qa for job 1.

This works, but it seems sloppy and I'd like to replace it with something cleaner. Is there a common convention for situations like this?

Edit: Users can have both employee and qa roles simultaneously. That's what's making me feel forcing into such a complex route.

```<code>class User < ActiveRecord::Base
  has_many :submitted_jobs,  :class_name => 'Job', :foreign_key => 'customer_id'
  has_many :assigned_jobs,   :class_name => 'Job', :foreign_key => 'employee_id'
  has_many :reviewed_jobs,   :class_name => 'Job', :foreign_key => 'qa_id'

class Job < ActiveRecord::Base
  belongs_to :customer, :class_name => 'User', :foreign_key => 'customer_id'
  belongs_to :employee, :class_name => 'User', :foreign_key => 'employee_id'
  belongs_to :qa,       :class_name => 'User', :foreign_key => 'qa_id'
</code>```

答:
You might consider a more RESTful approach to your problem. Two of the things RESTful Best Practices cites as "classic beginner's mistakes" is to "strongly mirror your ActiveRecord data model to choose your resources" and to "add custom methods if the standard ones don't fit."

Nouns are the new verbs

Change your way of explaining the scenario, an action

Use a noun to describe the action

The noun given to your scenario is the resource you're looking for

A user subscribes to a group -> A subscription is created

The project is validated by its owner -> A project validation is created

The user deactivates his account -> A user account activation is deleted

You could easily create a "Job Assignment" resource (not necessarily a separate model) and, for example, create one with the right parameters. In rough pseudo-Rails:

```<code># routes
resources :job_assignments, :only => [:create, :delete] # or whatever you need

# job_assignments_controller
class JobAssignmentsController < ApplicationController
  def create
    user = User.find(params[:user_id])
    job  = Job.find(params[:job_id])
    user.assign(job, params[:job_type]) # handle model logic
  end

  def destroy
    user = User.find(params[:user_id])
    job  = Job.find(params[:job_id])
    user.unassign(job, params[:job_type]) # handle model logic
  end
end
</code>```

There are some good examples in the presentation (starting on slide 32).

ContentLicense: CC BY-SA 3.0

Body:
I have a Job model that belongs_to three users (customer, employee, and qa). The customer is set to current_user when the job is created, but the employee and qa users pick their jobs from the pool of unclaimed jobs.

The way I have this implemented currently is as follows: match 'jobs/:id/assign/:type/:user_id' => 'jobs#assign' with an assign method with a case statement on params[:type]. So, for example, jobs/1/assign/qa/1 assigns user 1 as the qa for job 1.

This works, but it seems sloppy and I'd like to replace it with something cleaner. Is there a common convention for situations like this?

Edit: Users can have both employee and qa roles simultaneously. That's what's making me feel forcing into such a complex route.

class User < ActiveRecord::Base
  has_many :submitted_jobs,  :class_name => 'Job', :foreign_key => 'customer_id'
  has_many :assigned_jobs,   :class_name => 'Job', :foreign_key => 'employee_id'
  has_many :reviewed_jobs,   :class_name => 'Job', :foreign_key => 'qa_id'

class Job < ActiveRecord::Base
  belongs_to :customer, :class_name => 'User', :foreign_key => 'customer_id'
  belongs_to :employee, :class_name => 'User', :foreign_key => 'employee_id'
  belongs_to :qa,       :class_name => 'User', :foreign_key => 'qa_id'

Body:
You might consider a more RESTful approach to your problem. Two of the things RESTful Best Practices cites as "classic beginner's mistakes" is to "strongly mirror your ActiveRecord data model to choose your resources" and to "add custom methods if the standard ones don't fit."

Nouns are the new verbs

Change your way of explaining the scenario, an action

Use a noun to describe the action

The noun given to your scenario is the resource you're looking for

A user subscribes to a group -> A subscription is created

The project is validated by its owner -> A project validation is created

The user deactivates his account -> A user account activation is deleted

You could easily create a "Job Assignment" resource (not necessarily a separate model) and, for example, create one with the right parameters. In rough pseudo-Rails:

# routes
resources :job_assignments, :only => [:create, :delete] # or whatever you need

# job_assignments_controller
class JobAssignmentsController < ApplicationController
  def create
    user = User.find(params[:user_id])
    job  = Job.find(params[:job_id])
    user.assign(job, params[:job_type]) # handle model logic
  end

  def destroy
    user = User.find(params[:user_id])
    job  = Job.find(params[:job_id])
    user.unassign(job, params[:job_type]) # handle model logic
  end
end

There are some good examples in the presentation (starting on slide 32).


问:
Ground Truth and training data set
I want to know the relation between training data set, testing data set, and gound truth. I know the meaning of each one separately but I cannot see the relation between them especially ground truth and training data.</p>

答: Suppose we need to train a machine to classify apples from oranges. The machine-learning way is to "show" the machine some examples of oranges and apples (training set),based on which it identifies the rest as either oranges or apples (restrict yourself to apples and oranges only!). Now, the ground-truth is the labels you adjudged as apples and oranges(in the training set).</p>

Title: Ground Truth and training data set

ContentLicense: CC BY-SA 4.0


问:
I integrated a template into my angular project and I encountered a problem in these two files : core.min.js and script.js
index.html

```<code><html class="wide wow-animation" lang="en">
<body>

  <app-root></app-root>

  <!-- Javascript-->
   <script src="assets/js/core.min.js"></script>
   <script src="assets/js/script.js"></script>

 </body>
 </html>
</code>```

The error displayed at the console

The hierarchy of my files

--> The template is displayed but neither navbar nor carousel works .

答:
External javascript files should be added to the angular.json file under "scripts":

```<code>"scripts": [
  "assets/js/core.min.js",
  "assets/js/script.js"
]
</code>```

Official docs: https://angular.io/guide/workspace-config#style-script-config

From the docs:

An array entry for the styles and scripts options can be a simple path string, or an object that points to an extra entry-point file. The associated builder will load that file and its dependencies as a separate bundle during the build. With a configuration object, you have the option of naming the bundle for the entry point, using a bundleName field.

The bundle is injected by default, but you can set inject to false to exclude the bundle from injection. For example, the following object values create and name a bundle that contains styles and scripts, and excludes it from injection:

Finally, you are using jQuery, which I would avoid in Angular if at all possible. You're proabably going to encounter some issues along the way.

Body:
index.html

  <app-root></app-root>

The error displayed at the console

The hierarchy of my files

--> The template is displayed but neither navbar nor carousel works .

Body:
External javascript files should be added to the angular.json file under "scripts":

"scripts": [
  "assets/js/core.min.js",
  "assets/js/script.js"
]

Official docs: https://angular.io/guide/workspace-config#style-script-config

From the docs:

An array entry for the styles and scripts options can be a simple path string, or an object that points to an extra entry-point file. The associated builder will load that file and its dependencies as a separate bundle during the build. With a configuration object, you have the option of naming the bundle for the entry point, using a bundleName field.

The bundle is injected by default, but you can set inject to false to exclude the bundle from injection. For example, the following object values create and name a bundle that contains styles and scripts, and excludes it from injection:

Finally, you are using jQuery, which I would avoid in Angular if at all possible. You're proabably going to encounter some issues along the way.


问:
HOw to convert jquery to react js
I have jquery code how we can convert it to React js
I want to achieve onfocus and onblur on input to add and remove class on specific div.

Anyone have any idea how we can achieve this.

```<code>$("input#password").focus(function() {
  $("#overlay").addClass("newoverlay");
}).blur(function() {
  $("#overlay").removeClass("newoverlay");
});
</code>```

HTML

```<code><div id="overlay" class="">Focus/Blur</div>
<input type="txt" id="password"/>
</code>```

答:
If it is not needed to apply a certain class you can simply use css only with the focus selector. See here https://www.w3schools.com/cssref/sel_focus.asp

For example

#overlay:focus {
 some-property: true;
}
```

Then import the css file in your react setup. (For example with create-react-app)

Title: HOw to convert jquery to react js

Body:
I have jquery code how we can convert it to React js
I want to achieve onfocus and onblur on input to add and remove class on specific div.

Anyone have any idea how we can achieve this.

$("input#password").focus(function() {
  $("#overlay").addClass("newoverlay");
}).blur(function() {
  $("#overlay").removeClass("newoverlay");
});

HTML

Focus/Blur

<input type="txt" id="password"/>

Body:
If it is not needed to apply a certain class you can simply use css only with the focus selector. See here https://www.w3schools.com/cssref/sel_focus.asp

For example

#overlay:focus {
 some-property: true;
}

Then import the css file in your react setup. (For example with create-react-app)


问:
getting error in chrome extension : A cookie associated with a cross-site resource at http://*******.com/ was set without the `SameSite` attribute
i am new here in chrome extension, this is my first chrome extension ever, i have create one crome extension,  when i click on icon of my extesion i am getting error, A cookie associated with a cross-site resource at http://*****.com/ was set without theSameSiteattribute., can anyone please help me how to resolve this issue ? here i have mention all the extension files, can anyone please look in to that and help me to resolve this issue ?

manifest.json

```<code>{
    "manifest_version": 2,
    "name": "Next",
    "version": "0.1",
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "browser_action": {
        "default_icon": "logo.png",
        "default_popup": "popup.html",
        "default_title": "Hi"
    }
}
</code>```

background.js

```<code>var i = 1;

function updateIcon() {
    i = 1;
    chrome.browserAction.setBadgeText({
        text: ''
    });
    chrome.browserAction.setPopup({
        popup: "popup.html"
    });
}

chrome.browserAction.setBadgeBackgroundColor({
    color: [200, 0, 0, 100]
});
</code>```

popup.html

```<code><html>
<head>

</head>

<body>
    <p><iframe width="500" height="500" src="https://****.com" ></iframe></p></p>
</body>
</html>
</code>```

答: It's not an extension specific problem. The script you load in the popup is responsible for a request that gives you the warning. If it's not under your control then there is not much you can do, the server has to be reconfigured that the script is accessing. Read this for more: SameSite warning Chrome 77</p>

Body:
i am new here in chrome extension, this is my first chrome extension ever, i have create one crome extension,  when i click on icon of my extesion i am getting error, A cookie associated with a cross-site resource at http://*****.com/ was set without theSameSiteattribute., can anyone please help me how to resolve this issue ? here i have mention all the extension files, can anyone please look in to that and help me to resolve this issue ?

manifest.json

{
    "manifest_version": 2,
    "name": "Next",
    "version": "0.1",
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "browser_action": {
        "default_icon": "logo.png",
        "default_popup": "popup.html",
        "default_title": "Hi"
    }
}

background.js

var i = 1;

function updateIcon() {
    i = 1;
    chrome.browserAction.setBadgeText({
        text: ''
    });
    chrome.browserAction.setPopup({
        popup: "popup.html"
    });
}

chrome.browserAction.setBadgeBackgroundColor({
    color: [200, 0, 0, 100]
});

popup.html


问:
sshd.exe is not presen in script path
I have the problem that a script executed correctly on one server (2016 / PS5.1) but fails on another (2008 / PS2). The Path should be alright because it already worked. I'm quite sure it is a PS Version Problem, however I'm do not have enough experience nor knowledge to figure this one out...

The Error:

```<code>sshd.exe is not present in script path
Bei C:\Admin\LANAgentTransfer\OpenSSH-Win64\install-sshd.ps1:14 Zeichen:10
+     throw <<<<  "sshd.exe is not present in script path"
    + CategoryInfo          : OperationStopped: (sshd.exe is not present in script path:String) [], RuntimeException
    + FullyQualifiedErrorId : sshd.exe is not present in script path
</code>```

Relevant install-sshd.ps1:

```<code>    # @manojampalam - authored initial script
    # @friism - Fixed issue with invalid SDDL on Set-Acl
    # @manojampalam - removed ntrights.exe dependency
    # @bingbing8 - removed secedit.exe dependency

    $scriptpath = $MyInvocation.MyCommand.Path
    $scriptdir = Split-Path $scriptpath

    $sshdpath = Join-Path $scriptdir "sshd.exe"
    $sshagentpath = Join-Path $scriptdir "ssh-agent.exe"
    $etwman = Join-Path $scriptdir "openssh-events.man"

    if (-not (Test-Path $sshdpath)) {
        throw "sshd.exe is not present in script path"
    }
</code>```

SCRIPT:

```<code>
Set-ExecutionPolicy RemoteSigned -Force

Set Variables
$credentials = New-Object System.Net.NetworkCredential("XY", "XY")
$url = "ftp://XY/OpenSSH-Win64/OpenSSH-Win64/"
$localPath = "C:\XY\XY\OpenSSH-Win64"

function DownloadFtpDirectory($url, $credentials, $localPath)
{
        $listRequest = [Net.WebRequest]::Create($url)
        $listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
        $listRequest.Credentials = $credentials

        $lines = New-Object System.Collections.ArrayList

        $listResponse = $listRequest.GetResponse()
        $listStream = $listResponse.GetResponseStream()
        $listReader = New-Object System.IO.StreamReader($listStream)
        while (!$listReader.EndOfStream)
        {
            $line = $listReader.ReadLine()
            $lines.Add($line) | Out-Null
        }
        $listReader.Dispose()
        $listStream.Dispose()
        $listResponse.Dispose()

        foreach ($line in $lines)
        {
            $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
            $name = $tokens[8]
            $permissions = $tokens[0]

            $localFilePath = Join-Path $localPath $name
            $fileUrl = ($url + $name)

            if ($permissions[0] -eq 'd')
            {
                if (!(Test-Path $localFilePath -PathType container))
                {
                    Write-Host "Creating directory $localFilePath"
                    New-Item $localFilePath -Type directory | Out-Null
                }

                DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
            }
            else
            {
                Write-Host "Downloading $fileUrl to $localFilePath"

                $downloadRequest = [Net.WebRequest]::Create($fileUrl)
                $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
                $downloadRequest.Credentials = $credentials

                $downloadResponse = $downloadRequest.GetResponse()
                $sourceStream = $downloadResponse.GetResponseStream()
                $targetStream = [System.IO.File]::Create($localFilePath)
                $buffer = New-Object byte[] 10240
                while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
                {
                    $targetStream.Write($buffer, 0, $read);
                }
                $targetStream.Dispose()
                $sourceStream.Dispose()
                $downloadResponse.Dispose()
            }
        }
    }

IF (Test-Path C:\XY\XY\OpenSSH-Win64) {
    ECHO "FOLDER ALREADY EXISTS"
}

    else{
    #Function to Download all Files from a Directory
    md "C:\XY\XY\OpenSSH-Win64"
}

IF (Test-Path C:\XY\XY\OpenSSH-Win64\scp.exe) {
    ECHO "FILES ALREADY EXIST"
}

else {
  DownloadFtpDirectory $url $credentials "C:\XY\XY\OpenSSH-Win64"
}

#Install SSH via integrated ps1
C:\XY\XY\OpenSSH-Win64\install-sshd.ps1

#Set Service to start automatic and start service
Set-Service -Name sshd -StartupType Automatic
Start-Service -Name sshd

ECHO "SCRIPT SUCCESFUL"

Set-ExecutionPolicy Default -Force

</code>```

FOLDER CONTENT:

I'm open for critique!

答:
The FTP transfer was incomplete so files were missing, after redoing the transfer everything went fine.

Thanks @LievenKeersmaek for pointing it out!

Title: sshd.exe is not presen in script path

Body:
I have the problem that a script executed correctly on one server (2016 / PS5.1) but fails on another (2008 / PS2). The Path should be alright because it already worked. I'm quite sure it is a PS Version Problem, however I'm do not have enough experience nor knowledge to figure this one out...

The Error:

sshd.exe is not present in script path
Bei C:\Admin\LANAgentTransfer\OpenSSH-Win64\install-sshd.ps1:14 Zeichen:10
+     throw <<<<  "sshd.exe is not present in script path"
    + CategoryInfo          : OperationStopped: (sshd.exe is not present in script path:String) [], RuntimeException
    + FullyQualifiedErrorId : sshd.exe is not present in script path

Relevant install-sshd.ps1:

    # @manojampalam - authored initial script
    # @friism - Fixed issue with invalid SDDL on Set-Acl
    # @manojampalam - removed ntrights.exe dependency
    # @bingbing8 - removed secedit.exe dependency

    $scriptpath = $MyInvocation.MyCommand.Path
    $scriptdir = Split-Path $scriptpath

    $sshdpath = Join-Path $scriptdir "sshd.exe"
    $sshagentpath = Join-Path $scriptdir "ssh-agent.exe"
    $etwman = Join-Path $scriptdir "openssh-events.man"

    if (-not (Test-Path $sshdpath)) {
        throw "sshd.exe is not present in script path"
    }

SCRIPT:

Set-ExecutionPolicy RemoteSigned -Force

Set Variables
$credentials = New-Object System.Net.NetworkCredential("XY", "XY")
$url = "ftp://XY/OpenSSH-Win64/OpenSSH-Win64/"
$localPath = "C:\XY\XY\OpenSSH-Win64"

function DownloadFtpDirectory($url, $credentials, $localPath)
{
        $listRequest = [Net.WebRequest]::Create($url)
        $listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
        $listRequest.Credentials = $credentials

        $lines = New-Object System.Collections.ArrayList

        $listResponse = $listRequest.GetResponse()
        $listStream = $listResponse.GetResponseStream()
        $listReader = New-Object System.IO.StreamReader($listStream)
        while (!$listReader.EndOfStream)
        {
            $line = $listReader.ReadLine()
            $lines.Add($line) | Out-Null
        }
        $listReader.Dispose()
        $listStream.Dispose()
        $listResponse.Dispose()

        foreach ($line in $lines)
        {
            $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
            $name = $tokens[8]
            $permissions = $tokens[0]

            $localFilePath = Join-Path $localPath $name
            $fileUrl = ($url + $name)

            if ($permissions[0] -eq 'd')
            {
                if (!(Test-Path $localFilePath -PathType container))
                {
                    Write-Host "Creating directory $localFilePath"
                    New-Item $localFilePath -Type directory | Out-Null
                }

                DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
            }
            else
            {
                Write-Host "Downloading $fileUrl to $localFilePath"

                $downloadRequest = [Net.WebRequest]::Create($fileUrl)
                $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
                $downloadRequest.Credentials = $credentials

                $downloadResponse = $downloadRequest.GetResponse()
                $sourceStream = $downloadResponse.GetResponseStream()
                $targetStream = [System.IO.File]::Create($localFilePath)
                $buffer = New-Object byte[] 10240
                while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
                {
                    $targetStream.Write($buffer, 0, $read);
                }
                $targetStream.Dispose()
                $sourceStream.Dispose()
                $downloadResponse.Dispose()
            }
        }
    }

IF (Test-Path C:\XY\XY\OpenSSH-Win64) {
    ECHO "FOLDER ALREADY EXISTS"
}

    else{
    #Function to Download all Files from a Directory
    md "C:\XY\XY\OpenSSH-Win64"
}

IF (Test-Path C:\XY\XY\OpenSSH-Win64\scp.exe) {
    ECHO "FILES ALREADY EXIST"
}

else {
  DownloadFtpDirectory $url $credentials "C:\XY\XY\OpenSSH-Win64"
}

#Install SSH via integrated ps1
C:\XY\XY\OpenSSH-Win64\install-sshd.ps1

#Set Service to start automatic and start service
Set-Service -Name sshd -StartupType Automatic
Start-Service -Name sshd

ECHO "SCRIPT SUCCESFUL"

Set-ExecutionPolicy Default -Force

FOLDER CONTENT:

I'm open for critique!


问:
CSS: Make image fit the proper area with the absolutely positioned label on the picture
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
  <span class="label">Label</span>
</div></code>```

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!

答:
You can wrap the image with a div that has a display: inline-block rule, that will force the div to fit the image scale, then, in this div add another div for the label and position it with absolute.

.cont {
  width: 300px;
  height: 250px;
  background-size: contain;
  background-repeat: no-repeat;
  margin: 20px;
  border: 3px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
}

div .image-cont {
  display: inline-block;
  position: relative;
}

img {
  max-width: 300px;
  max-height: 250px;
  width: auto;
  height: auto;
}

.label {
  background-color: yellow;
  padding: 5px;
  position: absolute;
  top: 0;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cont">
  <div class="image-cont">
    <img src="https://image.shutterstock.com/image-photo/beautiful-abstract-grunge-decorative-navy-260nw-539880832.jpg" />
    <div class="label">Label</div>
  </div>
</div>

<div class="cont">
  <div class="image-cont">
    <img src="https://i.pinimg.com/originals/1b/30/80/1b30806bed30a7d071752948d00e75f8.jpg" />
    <div class="label">Label</div>
  </div>
</div></code>```

Body:
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}

  Label

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!

Body:
You can wrap the image with a div that has a display: inline-block rule, that will force the div to fit the image scale, then, in this div add another div for the label and position it with absolute.

.cont {
  width: 300px;
  height: 250px;
  background-size: contain;
  background-repeat: no-repeat;
  margin: 20px;
  border: 3px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
}

div .image-cont {
  display: inline-block;
  position: relative;
}

img {
  max-width: 300px;
  max-height: 250px;
  width: auto;
  height: auto;
}

.label {
  background-color: yellow;
  padding: 5px;
  position: absolute;
  top: 0;
  right: 0;
}

<div class="cont">
  <div class="image-cont">
    <img src="https://image.shutterstock.com/image-photo/beautiful-abstract-grunge-decorative-navy-260nw-539880832.jpg" />
    <div class="label">Label</div>
  </div>
</div>

<div class="cont">
  <div class="image-cont">
    <img src="https://i.pinimg.com/originals/1b/30/80/1b30806bed30a7d071752948d00e75f8.jpg" />
    <div class="label">Label</div>
  </div>
</div>


问:
get checkbox state and value from Request.Form collection
I try to access the posted value from a checkbox and if it is checked or not. I currently have this..

```<code><input type="checkbox" value="2" class="form-check-input" id="chk1">

            for (i = 1; i <= Convert.ToInt32(HiddenNumberOfControls.Value); i++)
        {
            chkName = ("chk" + i);
            var ctrl = Request.Form[chkName];

            if (ctrl == "on")
            {

            }

        }
</code>```

I can see if the checkbox is checked or not using this but is it possible to get its value?

答: Got it working by setting the checkbox value like this .InputAttributes.Add("value", "myVal");

Body:
I try to access the posted value from a checkbox and if it is checked or not. I currently have this..

<input type="checkbox" value="2" class="form-check-input" id="chk1">

            for (i = 1; i <= Convert.ToInt32(HiddenNumberOfControls.Value); i++)
        {
            chkName = ("chk" + i);
            var ctrl = Request.Form[chkName];

            if (ctrl == "on")
            {

            }

        }

I can see if the checkbox is checked or not using this but is it possible to get its value?


问:
php file_get_contents ('....datafile.xml') - get the datafile from my local desktop?
I have a database that exports xmls only locally (to my computer).  It will not export to a remote server.

I have a php file (located on remote server) that sends the xml to a webserivce.
Can I have the remote php file use "file_get_contents" function to extract xml data from my local computer?

If so, what is the proper syntax?
Thanks in advance.

答:
You have to make your file available from your linux machine:

install a webserver on your desktop machine and allow it to expose the file, so the file will be available to an URI like http://ip_of_your_desktop/path_to_files/filename.xml (this was mentioned above also)

if your desktop and server are on the same network, share the folder on your desktop, mount the folder on your linux machine and use file_get_contens to read the file from the mounted location


问:
v-model for dynamically generated checkboxes
Here is my fiddle : DEMO

```<code> modules: [{
      moduleName: "Module ABC",
      id: 1,
      actions: [{
        actionName: "addbrand",
        id: 1,
        permissions: [{
          permissionName: "read",
          "id": 1,
          "value": true
        }, {
          permissionName: "write",
          "id": 2,
          "value": true
        }, {
          permissionName: "execute",
          "id": 1,
          "value": false
        }]
}]
</code>```

Checkboxes are dynamically generated iterating over "modules" array in data object. But I am finding it difficult to assign v-model and capture the checked values for the corresponding "action" for its respective "module"'

How do I do this?

```<code><div v-for="module in modules"><b>{{ module.moduleName }}</b>
    <div v-for="action in module.actions">{{ action.actionName }}
      <div v-for="permission in action.permissions">
        <input type="checkbox"> {{ permission.permissionName }}
      </div>
    </div>
    <hr>
  </div>
</code>```

Any help would be much appreciated. Thank you..

答:
https://jsfiddle.net/srinivassunkari/t2fjzLpn/29/

1 Because of mutation no need to use the index to update the values of permission 'value'

2 When you use v-model it updates the value of the permission in the module.action.

{{ module.moduleName }}

{{ action.actionName }}

                <input type="checkbox" v-model="permission.value">
                {{ permission.permissionName }}

```

Body:
Here is my fiddle : DEMO

 modules: [{
      moduleName: "Module ABC",
      id: 1,
      actions: [{
        actionName: "addbrand",
        id: 1,
        permissions: [{
          permissionName: "read",
          "id": 1,
          "value": true
        }, {
          permissionName: "write",
          "id": 2,
          "value": true
        }, {
          permissionName: "execute",
          "id": 1,
          "value": false
        }]
}]

Checkboxes are dynamically generated iterating over "modules" array in data object. But I am finding it difficult to assign v-model and capture the checked values for the corresponding "action" for its respective "module"'

How do I do this?

{{ module.moduleName }}

{{ action.actionName }}

        <input type="checkbox"> {{ permission.permissionName }}

Any help would be much appreciated. Thank you..

Body:
https://jsfiddle.net/srinivassunkari/t2fjzLpn/29/

1 Because of mutation no need to use the index to update the values of permission 'value'

2 When you use v-model it updates the value of the permission in the module.action.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="module in modules"><b>{{ module.moduleName }}</b>
        <div v-for="action in module.actions">{{ action.actionName }}
            <div v-for="permission in action.permissions">
                <input type="checkbox" v-model="permission.value">
                {{ permission.permissionName }}
            </div>
        </div>
        <hr>
    </div>
</div>
<script>

new Vue({
    el: '#app',
    data() {
        return {
            modules: [{
                moduleName: "Module ABC",
                id: 1,
                actions: [{
                    actionName: "addbrand",
                    id: 1,
                    permissions: [{
                        permissionName: "read",
                        "id": 1,
                        "value": true
                    }, {
                        permissionName: "write",
                        "id": 2,
                        "value": true
                    }, {
                        permissionName: "execute",
                        "id": 1,
                        "value": false
                    }]
                }]
            }]
        }
    },
    // for understanding purpose added no need to consider this...
    watch: {
        modules: {
            deep: true,
            handler(modules) {
                console.log('modules', modules)
            }
        }
    }
})
</script>


问:
How to create multiple rows from a single row in Redshift SQL
I want to expand a single row to multiple rows in my table based on a column in the table in AWS Redshift.

Here is my example table schema and rows:

```<code>CREATE TABLE test (
  start timestamp, -- start time of the first slot
  slot_length int, -- the length of the slots in minutes
  repeat int       -- how many slots will be there
);

INSERT INTO test (start, slot_length, repeat) VALUES
('2019-09-22T00:00:00', 90, 2),
('2019-09-21T15:30:00', 60, 3);
</code>```

I want to expand these two rows into 5 based on the value of the "repeat" column. So any row will be expanded "repeat" times. The first expansion won't change anything. The subsequent expansions need to add "slot_length" to the "start" column. Here is the final list of rows I want to have in the end:

```<code>'2019-09-22 00:00:00', 90, 2  -- expanded from the first row
'2019-09-22 01:30:00', 90, 2  -- expanded from the first row
'2019-09-21 15:30:00', 60, 3  -- expanded from the second row
'2019-09-21 16:30:00', 60, 3  -- expanded from the second row
'2019-09-21 17:30:00', 60, 3  -- expanded from the second row
</code>```

Can this be done via pure SQL in Redshift?

答:
This SQL should solves your purpose. Kindly Up-vote if it does.

```<code>    select t.start
    , case when rpt.repeat>1
           then dateadd(min,t.slot_length*(rpt.repeat-1),t.start)
           else t.start
           end as new_start
    , t.slot_length
    , t.repeat
    from schema.test t
    join (select row_number() over() as repeat from schema.random_table) rpt
    on t.repeat>=rpt.repeat
    order by t.slot_length desc,rpt.repeat;
</code>```

Please note that the "random_table" in your schema should have at least as many rows as the maximum value in your "repeat" column.

Body:
I want to expand a single row to multiple rows in my table based on a column in the table in AWS Redshift.

Here is my example table schema and rows:

CREATE TABLE test (
  start timestamp, -- start time of the first slot
  slot_length int, -- the length of the slots in minutes
  repeat int       -- how many slots will be there
);

INSERT INTO test (start, slot_length, repeat) VALUES
('2019-09-22T00:00:00', 90, 2),
('2019-09-21T15:30:00', 60, 3);

I want to expand these two rows into 5 based on the value of the "repeat" column. So any row will be expanded "repeat" times. The first expansion won't change anything. The subsequent expansions need to add "slot_length" to the "start" column. Here is the final list of rows I want to have in the end:

'2019-09-22 00:00:00', 90, 2  -- expanded from the first row
'2019-09-22 01:30:00', 90, 2  -- expanded from the first row
'2019-09-21 15:30:00', 60, 3  -- expanded from the second row
'2019-09-21 16:30:00', 60, 3  -- expanded from the second row
'2019-09-21 17:30:00', 60, 3  -- expanded from the second row

Can this be done via pure SQL in Redshift?

Body:
This SQL should solves your purpose. Kindly Up-vote if it does.

    select t.start
    , case when rpt.repeat>1
           then dateadd(min,t.slot_length*(rpt.repeat-1),t.start)
           else t.start
           end as new_start
    , t.slot_length
    , t.repeat
    from schema.test t
    join (select row_number() over() as repeat from schema.random_table) rpt
    on t.repeat>=rpt.repeat
    order by t.slot_length desc,rpt.repeat;

Please note that the "random_table" in your schema should have at least as many rows as the maximum value in your "repeat" column.


问:
Kafka streams application failing to start
I have a Kafka streams application that is reading off a topic data that is produced with a console producer. I have a number of steps in the application, that produces two KTables which I then wish to join.

Each KTable is produed sucessfully, and I can even call toStream and then peek the values to console individually. As soon as I try to join the KTables together, then the application fails to even launch i.e. introducing the line bar.join(qux).toStream() causes the below panic. It looks like KTables bar and qux are produced.

Here is the output that I receive as error message:

```<code>2020-02-14 15:56:28.599  INFO  AssignorConfiguration - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer] Cooperative rebalancing enabled now
2020-02-14 15:56:28.630  WARN  ConsumerConfig - The configuration 'admin.retries' was supplied but isn't a known config.
2020-02-14 15:56:28.630  WARN  ConsumerConfig - The configuration 'admin.retry.backoff.ms' was supplied but isn't a known config.
2020-02-14 15:56:28.630  INFO  AppInfoParser - Kafka version: 2.4.0
2020-02-14 15:56:28.630  INFO  AppInfoParser - Kafka commitId: 77a89fcf8d7fa018
2020-02-14 15:56:28.630  INFO  AppInfoParser - Kafka startTimeMs: 1581695788630
2020-02-14 15:56:28.636  INFO  KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] State transition from CREATED to REBALANCING
2020-02-14 15:56:28.636  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Starting
2020-02-14 15:56:28.636  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] State transition from CREATED to STARTING
2020-02-14 15:56:28.637  INFO  KafkaConsumer - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] Subscribed to pattern: 'foo-KSTREAM-AGGREGATE-STATE-STORE-0000000009-repartition|foo-KSTREAM-AGGREGATE-STATE-STORE-0000000016-repartition|foo-KSTREAM-AGGREGATE-STATE-STORE-0000000022-repartition|foo-KSTREAM-AGGREGATE-STATE-STORE-0000000029-repartition|data'
2020-02-14 15:56:28.906  INFO  Metadata - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] Cluster ID: ghhNsZUZRSGD984ra7fXRg
2020-02-14 15:56:28.907  INFO  AbstractCoordinator - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] Discovered group coordinator 10.1.36.24:9092 (id: 2147483647 rack: null)
2020-02-14 15:56:28.915  INFO  AbstractCoordinator - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] (Re-)joining group
2020-02-14 15:56:28.920  INFO  AbstractCoordinator - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] (Re-)joining group
2020-02-14 15:56:28.925  ERROR StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Encountered the following error during processing:
java.lang.IllegalArgumentException: Number of partitions must be at least 1.
    at org.apache.kafka.streams.processor.internals.InternalTopicConfig.setNumberOfPartitions(InternalTopicConfig.java:62) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor.assign(StreamsPartitionAssignor.java:473) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.performAssignment(ConsumerCoordinator.java:548) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.onJoinLeader(AbstractCoordinator.java:650) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.access$1300(AbstractCoordinator.java:111) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:572) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:555) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:1026) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:1006) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.RequestFuture$1.onSuccess(RequestFuture.java:204) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.RequestFuture.fireSuccess(RequestFuture.java:167) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.RequestFuture.complete(RequestFuture.java:127) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient$RequestFutureCompletionHandler.fireCompletion(ConsumerNetworkClient.java:599) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.firePendingCompletedRequests(ConsumerNetworkClient.java:409) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:294) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:233) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:212) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:400) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:340) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:471) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.KafkaConsumer.updateAssignmentMetadataIfNeeded(KafkaConsumer.java:1267) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1231) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1211) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.pollRequests(StreamThread.java:843) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:743) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:698) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:671) ~[kafka-streams-2.4.0.jar:?]
2020-02-14 15:56:28.925  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] State transition from STARTING to PENDING_SHUTDOWN
2020-02-14 15:56:28.925  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Shutting down
2020-02-14 15:56:28.925  INFO  KafkaConsumer - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
2020-02-14 15:56:28.932  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] State transition from PENDING_SHUTDOWN to DEAD
2020-02-14 15:56:28.932  INFO  KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] State transition from REBALANCING to ERROR
2020-02-14 15:56:28.932  ERROR KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] All stream threads have died. The instance will be in error state and should be closed.
2020-02-14 15:56:28.932  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Shutdown complete
2020-02-14 15:56:28.934  INFO  KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] State transition from ERROR to PENDING_SHUTDOWN
2020-02-14 15:56:28,935 kafka-streams-close-thread WARN [AsyncContext@18b4aac2] Ignoring log event after log4j was shut down.
2020-02-14 15:56:28,936 kafka-streams-close-thread WARN Ignoring log event after log4j was shut down
2020-02-14 15:56:28,938 kafka-streams-close-thread WARN [AsyncContext@18b4aac2] Ignoring log event after log4j was shut down.
2020-02-14 15:56:28,939 kafka-streams-close-thread WARN Ignoring log event after log4j was shut down
2020-02-14 15:56:28,939 Thread-1 WARN [AsyncContext@18b4aac2] Ignoring log event after log4j was shut down.
2020-02-14 15:56:28,939 Thread-1 WARN Ignoring log event after log4j was shut down
</code>```

What's the cause of this? Is there some magic config I need to include to deal with the extra state store of the join I am trying to introduce?

答:
Downgrade to v2.3.1 has fixed the issue as found here: issues.apache.org/jira/browse/KAFKA-9335

Thank you to Spasoje Petronijević.

Body:
I have a Kafka streams application that is reading off a topic data that is produced with a console producer. I have a number of steps in the application, that produces two KTables which I then wish to join.

Each KTable is produed sucessfully, and I can even call toStream and then peek the values to console individually. As soon as I try to join the KTables together, then the application fails to even launch i.e. introducing the line bar.join(qux).toStream() causes the below panic. It looks like KTables bar and qux are produced.

Here is the output that I receive as error message:

2020-02-14 15:56:28.599  INFO  AssignorConfiguration - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer] Cooperative rebalancing enabled now
2020-02-14 15:56:28.630  WARN  ConsumerConfig - The configuration 'admin.retries' was supplied but isn't a known config.
2020-02-14 15:56:28.630  WARN  ConsumerConfig - The configuration 'admin.retry.backoff.ms' was supplied but isn't a known config.
2020-02-14 15:56:28.630  INFO  AppInfoParser - Kafka version: 2.4.0
2020-02-14 15:56:28.630  INFO  AppInfoParser - Kafka commitId: 77a89fcf8d7fa018
2020-02-14 15:56:28.630  INFO  AppInfoParser - Kafka startTimeMs: 1581695788630
2020-02-14 15:56:28.636  INFO  KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] State transition from CREATED to REBALANCING
2020-02-14 15:56:28.636  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Starting
2020-02-14 15:56:28.636  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] State transition from CREATED to STARTING
2020-02-14 15:56:28.637  INFO  KafkaConsumer - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] Subscribed to pattern: 'foo-KSTREAM-AGGREGATE-STATE-STORE-0000000009-repartition|foo-KSTREAM-AGGREGATE-STATE-STORE-0000000016-repartition|foo-KSTREAM-AGGREGATE-STATE-STORE-0000000022-repartition|foo-KSTREAM-AGGREGATE-STATE-STORE-0000000029-repartition|data'
2020-02-14 15:56:28.906  INFO  Metadata - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] Cluster ID: ghhNsZUZRSGD984ra7fXRg
2020-02-14 15:56:28.907  INFO  AbstractCoordinator - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] Discovered group coordinator 10.1.36.24:9092 (id: 2147483647 rack: null)
2020-02-14 15:56:28.915  INFO  AbstractCoordinator - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] (Re-)joining group
2020-02-14 15:56:28.920  INFO  AbstractCoordinator - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-consumer, groupId=foo] (Re-)joining group
2020-02-14 15:56:28.925  ERROR StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Encountered the following error during processing:
java.lang.IllegalArgumentException: Number of partitions must be at least 1.
    at org.apache.kafka.streams.processor.internals.InternalTopicConfig.setNumberOfPartitions(InternalTopicConfig.java:62) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor.assign(StreamsPartitionAssignor.java:473) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.performAssignment(ConsumerCoordinator.java:548) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.onJoinLeader(AbstractCoordinator.java:650) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.access$1300(AbstractCoordinator.java:111) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:572) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:555) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:1026) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:1006) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.RequestFuture$1.onSuccess(RequestFuture.java:204) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.RequestFuture.fireSuccess(RequestFuture.java:167) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.RequestFuture.complete(RequestFuture.java:127) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient$RequestFutureCompletionHandler.fireCompletion(ConsumerNetworkClient.java:599) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.firePendingCompletedRequests(ConsumerNetworkClient.java:409) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:294) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:233) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:212) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:400) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:340) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:471) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.KafkaConsumer.updateAssignmentMetadataIfNeeded(KafkaConsumer.java:1267) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1231) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1211) ~[kafka-clients-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.pollRequests(StreamThread.java:843) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:743) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:698) ~[kafka-streams-2.4.0.jar:?]
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:671) ~[kafka-streams-2.4.0.jar:?]
2020-02-14 15:56:28.925  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] State transition from STARTING to PENDING_SHUTDOWN
2020-02-14 15:56:28.925  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Shutting down
2020-02-14 15:56:28.925  INFO  KafkaConsumer - [Consumer clientId=foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
2020-02-14 15:56:28.932  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] State transition from PENDING_SHUTDOWN to DEAD
2020-02-14 15:56:28.932  INFO  KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] State transition from REBALANCING to ERROR
2020-02-14 15:56:28.932  ERROR KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] All stream threads have died. The instance will be in error state and should be closed.
2020-02-14 15:56:28.932  INFO  StreamThread - stream-thread [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4-StreamThread-1] Shutdown complete
2020-02-14 15:56:28.934  INFO  KafkaStreams - stream-client [foo-d2f546ef-f7eb-4088-ae04-1943ed71f7a4] State transition from ERROR to PENDING_SHUTDOWN
2020-02-14 15:56:28,935 kafka-streams-close-thread WARN [AsyncContext@18b4aac2] Ignoring log event after log4j was shut down.
2020-02-14 15:56:28,936 kafka-streams-close-thread WARN Ignoring log event after log4j was shut down
2020-02-14 15:56:28,938 kafka-streams-close-thread WARN [AsyncContext@18b4aac2] Ignoring log event after log4j was shut down.
2020-02-14 15:56:28,939 kafka-streams-close-thread WARN Ignoring log event after log4j was shut down
2020-02-14 15:56:28,939 Thread-1 WARN [AsyncContext@18b4aac2] Ignoring log event after log4j was shut down.
2020-02-14 15:56:28,939 Thread-1 WARN Ignoring log event after log4j was shut down

What's the cause of this? Is there some magic config I need to include to deal with the extra state store of the join I am trying to introduce?


问:
How to troubleshoot a url error with "Port number ended with 'y'"?
While trying to clone an already existing repository from gitlab into my local drive. I used the format

```<code>$ git clone https://github.com/libgit2/libgit2  mylibgit
</code>```

The resulting folder e.g mylibgit was found somewhere outside the XAMPP web folder (i.e htdocs), I moved it there but it's not working as supposed.

I moved it out to my desktop and got the error :

```<code>fatal: unable to access 'https://git@gitlab.com:xxxxx/yyyyyy/':Port number ended with 'y'
</code>```

答:
I had similar problem. Just corrected(removed git@ and port number) URL in .git/config file and it worked.

[remote "origin"]
    url = https://git@gitlab.com:xxxxx/yyyyyy/

To

[remote "origin"]
    url = https://gitlab.com/yyyyyy/

Body:
While trying to clone an already existing repository from gitlab into my local drive. I used the format

$ git clone https://github.com/libgit2/libgit2  mylibgit

The resulting folder e.g mylibgit was found somewhere outside the XAMPP web folder (i.e htdocs), I moved it there but it's not working as supposed.

I moved it out to my desktop and got the error :

fatal: unable to access 'https://git@gitlab.com:xxxxx/yyyyyy/':Port number ended with 'y'


问:
Call GraphQL API with String variable
I want to execute a simple GraphQL query in which I pass a variable.

```<code>import requests
import json

var = "whatever"

query = """
    query ($var: String!){
        styles(locale: "en", styleNumbers: [ $var] ) {
            styleOptions {
    parms {
        parm1
        parm2
            }
        }
        }
    }
"""

url = 'https://sth_random.io/graphql?'
response = requests.get(url, json={'query': query, '$var': var})
response = response.json()

print(response)
</code>```

but I am getting the following error:

```<code>{'errors': [{'message': 'Variable "$var" of required type "String!" was not provided.', 'locations': [{'line': 2, 'column': 12}]}]}
</code>```

What am I missing?

Thank you in advance.

答:
The request body should include a variables key that is itself a dictionary of the variable values:

```<code>variables = {'var': var}
response = requests.post(url, json={'query': query, 'variables': variables})
</code>```

Title: Call GraphQL API with String variable

Body:
I want to execute a simple GraphQL query in which I pass a variable.

import requests
import json

var = "whatever"

query = """
    query ($var: String!){
        styles(locale: "en", styleNumbers: [ $var] ) {
            styleOptions {
    parms {
        parm1
        parm2
            }
        }
        }
    }
"""

url = 'https://sth_random.io/graphql?'
response = requests.get(url, json={'query': query, '$var': var})
response = response.json()

print(response)

but I am getting the following error:

{'errors': [{'message': 'Variable "$var" of required type "String!" was not provided.', 'locations': [{'line': 2, 'column': 12}]}]}

What am I missing?

Thank you in advance.

Body:
The request body should include a variables key that is itself a dictionary of the variable values:

variables = {'var': var}
response = requests.post(url, json={'query': query, 'variables': variables})


问:
git ignore directory except for specified
I want to ignore entire public_html/ directory except one file inside

I give .gitignore as below:

```<code>public_html/*
!public_html/config/config.php
</code>```

However, when I run git status , I can not find config.php has been included.

答: First commit / add public_html/config/config.php and then add public_html to the gitignore.

Body:
I want to ignore entire public_html/ directory except one file inside

I give .gitignore as below:

public_html/*
!public_html/config/config.php

However, when I run git status , I can not find config.php has been included.


问:
Eclipse RCP product configuration not adding all required plugins
I am in the process of trying to migrate an old Kepler RCP app to an up-to-date platform. The old configuration was based on plugins but I now want to use features and have now grouped the pluging into feature groups. I have also created a Target Platform based on Eclipse 2019-03, BIRT 4.7 and a few other items which are required.

The project configuration is defined to use features and I added the following features (followed by Add Required):

When I try to test the product (from the Product Editor) I get a long list of missing constraints:

When I open the generated Launch Configuration, I can see on the Plug-ins tab that 95 out of 547 plugins are selected. Without changing any settings, if I simply click Add Required Plug-ins the total jumps to 226.

My question is: what am I doing wrong so that the Product Configuration cannot resolve the required plug-ins but the Launch Configuration can?

答:
The org.eclipse.e4.rcp feature only contains the plug-ins for an e4 based RCP. This type of RCP is very minimal and does not contain any of the plug-ins for the 3.x compatability mode RCP - which are the plug-ins being listed as missing.

You will need to use one of the features which contain the 3.x compatability mode code (maybe org.eclipse.platform or org.eclipse.sdk).


问:
How to read binary data from dicom file?
How to read raw image data from uncompressed DICOM file and dump it to a file. I just use the following code for compressed files. using dcmtk library

```<code>dataSet->findAndGetElement(DCM_PixelData, element);
pixDataElem = OFstatic_cast(DcmPixelData*, element);

DcmPixelSequence *pixelSequence = NULL;
E_TransferSyntax tran_Syntax = EXS_Unknown;
const DcmRepresentationParameter *representation = NULL;

// Find the key that is needed to access the right representation of the data within DCMTK
pixDataElem->getOriginalRepresentationKey(tran_Syntax, representation);
//pixDataElem->getCurrentRepresentationKey(tran_Syntax, representation);

// Access original data representation and get result within pixel sequence
pixDataElem->getEncapsulatedRepresentation(tran_Syntax, representation, pixelSequence);

    DcmPixelItem *pixelItem = NULL;
    //Access the First frame by skipping the offset table...
    pixelSequence->getItem(pixelItem, 1);

    Uint8 *pixels = NULL;
    pixDataElem = (DcmPixelData*)pixelItem;
    pixDataElem->getUint8Array(pixels);
    Uint8 *pixels = NULL;
    pixDataElem->getUint8Array(pixels);
    //Writing the Raw data to a file...
    FILE *file;
    file = fopen("D:\\DicomImage.jpeg", "wb");
    fwrite(pixels, sizeof(char), imageSize, file);
    cout << "File write Completed and the File is closed Successfully" << endl;
</code>```

How can I raw image data from the uncompressed files with many frames in c++ using dcmtk library.....?

答:
Basically, you can use the same code, but without compression (this is actually the easier case...)

```<code>dataSet->findAndGetElement(DCM_PixelData, element);
pixDataElem = OFstatic_cast(DcmPixelData*, element);

Uint8 *pixels = NULL;
pixDataElem->getUint8Array(pixels);

//Writing the Raw data to a file...
FILE *file;
file = fopen("D:\\DicomImage.raw", "wb");
// frameSize is the size of a single frame
fwrite(pixels + frameSize * frameIndex, sizeof(char), frameSize, file);
cout << "File write Completed and the File is closed Successfully" << endl;
</code>```

(this is out of my head, so no guarantee for completeness)

What you get, is the raw binary data. If you want to create an image file like JPG from that, you need the respective image functionality, though that has nothing to do with dcmtk.

Body:
How to read raw image data from uncompressed DICOM file and dump it to a file. I just use the following code for compressed files. using dcmtk library

dataSet->findAndGetElement(DCM_PixelData, element);
pixDataElem = OFstatic_cast(DcmPixelData*, element);

DcmPixelSequence *pixelSequence = NULL;
E_TransferSyntax tran_Syntax = EXS_Unknown;
const DcmRepresentationParameter *representation = NULL;

// Find the key that is needed to access the right representation of the data within DCMTK
pixDataElem->getOriginalRepresentationKey(tran_Syntax, representation);
//pixDataElem->getCurrentRepresentationKey(tran_Syntax, representation);

// Access original data representation and get result within pixel sequence
pixDataElem->getEncapsulatedRepresentation(tran_Syntax, representation, pixelSequence);

    DcmPixelItem *pixelItem = NULL;
    //Access the First frame by skipping the offset table...
    pixelSequence->getItem(pixelItem, 1);

    Uint8 *pixels = NULL;
    pixDataElem = (DcmPixelData*)pixelItem;
    pixDataElem->getUint8Array(pixels);
    Uint8 *pixels = NULL;
    pixDataElem->getUint8Array(pixels);
    //Writing the Raw data to a file...
    FILE *file;
    file = fopen("D:\\DicomImage.jpeg", "wb");
    fwrite(pixels, sizeof(char), imageSize, file);
    cout << "File write Completed and the File is closed Successfully" << endl;

How can I raw image data from the uncompressed files with many frames in c++ using dcmtk library.....?

Body:
Basically, you can use the same code, but without compression (this is actually the easier case...)

dataSet->findAndGetElement(DCM_PixelData, element);
pixDataElem = OFstatic_cast(DcmPixelData*, element);

Uint8 *pixels = NULL;
pixDataElem->getUint8Array(pixels);

//Writing the Raw data to a file...
FILE *file;
file = fopen("D:\\DicomImage.raw", "wb");
// frameSize is the size of a single frame
fwrite(pixels + frameSize * frameIndex, sizeof(char), frameSize, file);
cout << "File write Completed and the File is closed Successfully" << endl;

(this is out of my head, so no guarantee for completeness)

What you get, is the raw binary data. If you want to create an image file like JPG from that, you need the respective image functionality, though that has nothing to do with dcmtk.


问:
How do you add a character string for every second row in R?
I would like to concatenate one string to every second row for only one column:

From this:

```<code>+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B    |   22 |
| A    |   22 |
| A    |   33 |
| A    |   44 |

+------+------+
</code>```

To this (adding _a to the first col):

```<code>+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B_a  |   22 |
| A    |   22 |
| A_a  |   33 |
| A    |   44 |
+------+------+
</code>```

Thank you for your help! Preferably I would like to use paste0() or anything in the tidyverse!

答:
You can try:</p>

```<code>df %>%
 mutate(col1 = if_else(row_number() %% 2 == 0, paste0(col1, "_A"), col1))

  col1 col2
1    A   11
2  B_A   22
3    A   22
4  A_A   33
5    A   44
</code>```

Body:
I would like to concatenate one string to every second row for only one column:

From this:

+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B    |   22 |
| A    |   22 |
| A    |   33 |
| A    |   44 |

+------+------+

To this (adding _a to the first col):

+------+------+
| col1 | col2 |
+------+------+
| A    |   11 |
| B_a  |   22 |
| A    |   22 |
| A_a  |   33 |
| A    |   44 |
+------+------+

Thank you for your help! Preferably I would like to use paste0() or anything in the tidyverse!

Body:
You can try:

df %>%
 mutate(col1 = if_else(row_number() %% 2 == 0, paste0(col1, "_A"), col1))

  col1 col2
1    A   11
2  B_A   22
3    A   22
4  A_A   33
5    A   44


问:
Excel VBA Cell Format
I am making a simple tracking spreadsheet for myself with a userform interface, learning from lots of different online tutorials as I've never coded before.
Using the excel ribbon, I have set certain cells with a certain format, one for dates (Day Month Year) & one for currency ([$$-en-AU]-#,##0.00;[Red]-[$$-en-AU]-#,##0.00).

My issue is: whenever I enter data into textbox6, textbox20 textbox21 & textbox22, then close the userform, transferring all the entered data into the worksheet.
The data entered into the above textboxes overrides how the cell is formatted.
Is there any way to lock the cell format or make it use a certain format regardless of what the user enters into the text box?

This is the code that is used when adding the data into the sheet & unloading the userform:
    Private Sub cmdAdd_Click()
    'Copy input values to sheet.
    Dim rw As Integer
    Dim ws As Worksheet
    Dim lrow As Long
    Dim LO As ListObject
    Dim LEO As Range
    Set ws = Worksheets("2020_Data")
    Set LO = ws.ListObjects("Table1")
    'lrow = ws.Cells(Rows.Count, "B") .End(xlUp). .Offset(1, 0) .Row
    With LO.Range.Columns(2)
        Set LEO = .Find(what:="", after:=.Cells(1), LookIn:=xlValues, _
            searchorder:=xlByRows, searchdirection:=xlNext)
        If Not LEO Is Nothing Then
            lrow = LEO.Row
    '        MsgBox LEO.Row 'First empty row at column B
        End If
    End With
    'rw = ws.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookInValues) .Row + 1
    With ws
        .Cells(lrow, "B") = Me.TextBox6
        .Cells(lrow, "C") = Me.TextBox21
        .Cells(lrow, "F") = Me.ComboBox2
        .Cells(lrow, "G") = Me.ComboBox3
        .Cells(lrow, "I") = Me.TextBox16
        .Cells(lrow, "H") = Me.TextBox17
        .Cells(lrow, "J") = Me.TextBox18

答:
Like I said in my previous comment, the problem is:
.Cells(lrow, "B") = Me.TextBox6

As a rule of thumb, when you want to modify only the value of a cell with VBA, you should use .Cells(...).Value Otherwise, you'll likely override some properties (in this case, formatting)

Using Me.TextBox.6 is not ideal, and I prefer being explicit as well in this case (even if this will work just fine). So, all in all:

.Cells(lrow, "B").Value = Me.Textbox6.Value

Title: Excel VBA Cell Format


问:
How do I get Pylint message IDs to show up after pylint-1.0.0?
Starting with pylint-1.0.0 the --include-ids argument is no longer allowed.

How do I get:

```<code>************* Module foo.bar
E:199,11: Module 'yaml' has no 'scanner' member (no-member)
************* Module foo.baz
W:153,27: Unused variable '_filenames' (unused-variable)
</code>```

to show the IDs (e.g. W0142), for each warning?

答:
The proper command which can be used is</p>

```<code>python3 -m pylint --msg-template="{path}||{msg_id}||{symbol}||{category}||{line}||{column}||{msg}" sscript.py
</code>```

Body:
Starting with pylint-1.0.0 the --include-ids argument is no longer allowed.

How do I get:

************* Module foo.bar
E:199,11: Module 'yaml' has no 'scanner' member (no-member)
************* Module foo.baz
W:153,27: Unused variable '_filenames' (unused-variable)

to show the IDs (e.g. W0142), for each warning?

Body:
The proper command which can be used is

python3 -m pylint --msg-template="{path}||{msg_id}||{symbol}||{category}||{line}||{column}||{msg}" sscript.py


问:
React/Redux: focus is lost in the input field
When you enter text in the field, focus is lost. Why?

If remove the label prop, then the problem is solved. But a label is needed

```<code><SimpleItem
  label={{ text: "Your Address" }}
  dataField="surname"
  editorOptions={{
    value: formEdit.surname,
    onValueChanged: ({ value }) => {
      addChange("surname", value);
    },
    valueChangeEvent: "keyup"
  }}
/>;
</code>```

online demo:
https://codesandbox.io/s/de-form-ezmmg

答:
I noticed that when using Label as child of SimpleItem (instead of prop), the input doesn't lose focus on keyup event (I tried digging in the docs, but I couldn't find a reason why this would happen):

```<code><SimpleItem
  dataField="surname"
  editorOptions={{
    value: formEdit.surname,
    onValueChanged: ({ value }) => {
      addChange("surname", value);
    },
    valueChangeEvent: "keyup"
  }}
>
     <Label text="Your Address" />
</SimpleItem>
</code>```

Code Sandbox

Body:
When you enter text in the field, focus is lost. Why?

If remove the label prop, then the problem is solved. But a label is needed

<SimpleItem
  label={{ text: "Your Address" }}
  dataField="surname"
  editorOptions={{
    value: formEdit.surname,
    onValueChanged: ({ value }) => {
      addChange("surname", value);
    },
    valueChangeEvent: "keyup"
  }}
/>;

online demo:
https://codesandbox.io/s/de-form-ezmmg

Body:
I noticed that when using Label as child of SimpleItem (instead of prop), the input doesn't lose focus on keyup event (I tried digging in the docs, but I couldn't find a reason why this would happen):

<SimpleItem
  dataField="surname"
  editorOptions={{
    value: formEdit.surname,
    onValueChanged: ({ value }) => {
      addChange("surname", value);
    },
    valueChangeEvent: "keyup"
  }}
>
     <Label text="Your Address" />
</SimpleItem>

Code Sandbox


问:
Interacting with Metamask web3.js
I am facing a problem when I am creating a contract on my local ethereum blockchain. I have a basic contract to register a doc on blockchain.

So, when a run my contract in truffle console I can call all my functions perfectly, but, when I create a webpage with a front end interface, I can't open metamask to pay a fee.
My contract has basicly 2 functions: addDoc and FindDoc. I did a test creating a transaction using remix website and it worked normal. At my page, I still can call a findDoc and get answer with the correct informations, but when I try creating a transaction and pay a fee, the metamask doesn't show me.

My project is just 4 files:

index.html

app.js

notaryWebApp.js

sha256

The codes can be found here: https://github.com/ffelipesimoes/solidity/tree/master/webapp

The main interact with blockchain is notaryWebApp.js file:

```<code>var contract = undefined;
var customProvider = undefined;
var address = "0x6A4494ed32ce0Ab8004fbEAdac534916f88C8d3E";
var abi = undefined;

function notary_init() {
    // Check if Web3 has been injected by the browser (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
        // Use existing gateway
        window.web3 = new Web3(web3.currentProvider);
    } else {
        alert("No Ethereum interface injected into browser. Read-only access");
    }
    //contract abi
    abi = [...]
    contract = new web3.eth.Contract(abi, address);
};

//sends a hash to the blockchain
function notary_send(hash, callback) {
    web3.eth.getAccounts(function (error, accounts) {
        contract.methods.addDocHash(hash).send({
            from: accounts[0]
        }, function (error, tx) {
            if (error) callback(error, null);
            else callback(null, tx);
        });
    });
};

//looks up a hash on the blockchain
function notary_find(hash, callback) {
    contract.methods.findDocHash(hash).call(function (error, result) {
        if (error) callback(error, null);
        else {
            let resultObj = {
                mineTime: new Date(result[0] * 1000),
                blockNumber: result[1]
            }
            callback(null, resultObj);
        }
    });
};
</code>```

since now, thank you all!

答:
You need to use window.ethereum and ethereum.enable() as described here, this is due to the privacy mode introduced in MetaMask recently.

In your case, call await window.ethereum.enable() before notary_init(), and init the web3 instance with window.ethereum instead of currentProvider.

Title: Interacting with Metamask web3.js

Body:
I am facing a problem when I am creating a contract on my local ethereum blockchain. I have a basic contract to register a doc on blockchain.

So, when a run my contract in truffle console I can call all my functions perfectly, but, when I create a webpage with a front end interface, I can't open metamask to pay a fee.
My contract has basicly 2 functions: addDoc and FindDoc. I did a test creating a transaction using remix website and it worked normal. At my page, I still can call a findDoc and get answer with the correct informations, but when I try creating a transaction and pay a fee, the metamask doesn't show me.

My project is just 4 files:

index.html

app.js

notaryWebApp.js

sha256

The codes can be found here: https://github.com/ffelipesimoes/solidity/tree/master/webapp

The main interact with blockchain is notaryWebApp.js file:

var contract = undefined;
var customProvider = undefined;
var address = "0x6A4494ed32ce0Ab8004fbEAdac534916f88C8d3E";
var abi = undefined;

function notary_init() {
    // Check if Web3 has been injected by the browser (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
        // Use existing gateway
        window.web3 = new Web3(web3.currentProvider);
    } else {
        alert("No Ethereum interface injected into browser. Read-only access");
    }
    //contract abi
    abi = [...]
    contract = new web3.eth.Contract(abi, address);
};

//sends a hash to the blockchain
function notary_send(hash, callback) {
    web3.eth.getAccounts(function (error, accounts) {
        contract.methods.addDocHash(hash).send({
            from: accounts[0]
        }, function (error, tx) {
            if (error) callback(error, null);
            else callback(null, tx);
        });
    });
};

//looks up a hash on the blockchain
function notary_find(hash, callback) {
    contract.methods.findDocHash(hash).call(function (error, result) {
        if (error) callback(error, null);
        else {
            let resultObj = {
                mineTime: new Date(result[0] * 1000),
                blockNumber: result[1]
            }
            callback(null, resultObj);
        }
    });
};

since now, thank you all!


问:
Aqueduct framework fetch Query where by document
```<code>@Operation.get()
  Future<Response> getAllCoworking({@Bind.query('l') String location}) async {
    final query = Query<Coworking>(context);
    /*if (location != null) {
      query.where((x) => x.title).contains(
            location,
            caseSensitive: false,
          );
    }*/
    query
      ..sortBy((w) => w.title, QuerySortOrder.ascending)
      ..fetchLimit = 5;
    final coworkingList = await query.fetch();
    return Response.ok(coworkingList);
  }
</code>```

JSON Object

```<code>[
    {
        "id": 1,
        "title": "House of Words",
        "content": {
            "location": "Jaipur"
        }
    },
    {
        "id": 2,
        "title": "T-START UDAIPUR",
        "content": {
            "location": "Udaipur"
        }
    },
    {
        "id": 3,
        "title": "Thalagiri Co-Working Space",
        "content": {
            "location": "Udaipur"
        }
    }
]

</code>```

i want to do http request http://localhost:8888?l=jaipur

how can i create a aqueduct query to fetch row where jsonb column has value for example

i just want to fetch where location is jaipur

答: query.predicate = QueryPredicate("content ->> 'location' = @loc", {"loc" : location});</p>

Body:
@Operation.get()
  Future<Response> getAllCoworking({@Bind.query('l') String location}) async {
    final query = Query<Coworking>(context);
    /*if (location != null) {
      query.where((x) => x.title).contains(
            location,
            caseSensitive: false,
          );
    }*/
    query
      ..sortBy((w) => w.title, QuerySortOrder.ascending)
      ..fetchLimit = 5;
    final coworkingList = await query.fetch();
    return Response.ok(coworkingList);
  }

JSON Object

[
    {
        "id": 1,
        "title": "House of Words",
        "content": {
            "location": "Jaipur"
        }
    },
    {
        "id": 2,
        "title": "T-START UDAIPUR",
        "content": {
            "location": "Udaipur"
        }
    },
    {
        "id": 3,
        "title": "Thalagiri Co-Working Space",
        "content": {
            "location": "Udaipur"
        }
    }
]

i want to do http request http://localhost:8888?l=jaipur

how can i create a aqueduct query to fetch row where jsonb column has value for example

i just want to fetch where location is jaipur


问:
decode numbers in an array and compare to different array
I have 2 arrays, one containing numbers and another one containing encoded numbers.

I need to match the encoded numbers to the normal numbers to find a match.  The trick is that I need to decode the numbers to find a match.

```<code>let encoded = ['310254@3543129', '03254@03715P5'];
let numbers = ['3102540003543129', '0325400003715445', ...]
</code>```

I have tried using a for loop with recursion for when there are multiple special characters in the string, but I am not getting the results correctly.

```<code>for (let i = 0; i < encrypted.length; i++) {
for (let j = 0; j < numbers.length; j++) {

function removeSpecialChars(referenceNumber) {
    if(!/^\d*$/.test(referenceNumber)){
        for (let x = 0, invalidChar = ''; invalidChar = referenceNumber.charAt(x); x++) {
            let newString = '';
            // which char is invalid
            if (!/^\d*$/.test(invalidChar)) {
                for(let y = 0; i < numbers[j].split('').length; y++){
                    if(numbers[j].split('')[x] === numbers[j].split('')[x + y]){
                        newString += numbers[j].split('')[x];
                    } else break;
                 }
            return removeSpecialChars(referenceNumber.replace(invalidChar, newString));
            }
        }
    }

    return referenceNumber;
} // end function

if (removeSpecialChars(encrypted[i]) === numbers[j]) {
    count++;
}

}
}
</code>```

I am not sure if I am approaching this in the wrong way entirely or if I am just missing something.

Here is a fiddle to reproduce my results.
https://jsfiddle.net/6ezuwhdb/1/

答:
it seems that there are at least 2 rules at play here (I haven't looked at the fiddle in any detail but what there is here can be easily extended):

000 is encoded with a @, and

44 is encoded with a P

I would first get a complete list of these rules together and then use regular expressions to replace all instances of the special characters with their numeric equivalents.

The regular expressions use the g modifier so that all instances of the encoded value get replaced within the string.

const encoded = ['310254@3543129', '03254@03715P5'];

const decoded = encoded.map(en => {
  // replace the special characters using multiple regular expressions
  let result = en;
  // swap all @'s for
  result = result.replace(/@/g, '000');
  // swap all P's for 44
  result = result.replace(/P/g, '44');
  // add more rules here ...

  return result;
});

console.log('Decoded numbers: ', decoded);```
</div>
</div>
</p>

<p>To then check whether the normal numbers can be found within the decoded set of numbers is fairly straight forward.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// From previous step ;o)
const decoded = [
  "3102540003543129",
  "0325400003715445"
];

const numbers = ['3102540003543129', '0325400003715445'];
const matchedNumbers = numbers.filter(number => {
  return decoded.indexOf(number) >= 0;
});

console.log(matchedNumbers);</code>```

Body:
I have 2 arrays, one containing numbers and another one containing encoded numbers.

I need to match the encoded numbers to the normal numbers to find a match.  The trick is that I need to decode the numbers to find a match.

let encoded = ['310254@3543129', '03254@03715P5'];
let numbers = ['3102540003543129', '0325400003715445', ...]

I have tried using a for loop with recursion for when there are multiple special characters in the string, but I am not getting the results correctly.

for (let i = 0; i < encrypted.length; i++) {
for (let j = 0; j < numbers.length; j++) {

function removeSpecialChars(referenceNumber) {
    if(!/^\d*$/.test(referenceNumber)){
        for (let x = 0, invalidChar = ''; invalidChar = referenceNumber.charAt(x); x++) {
            let newString = '';
            // which char is invalid
            if (!/^\d*$/.test(invalidChar)) {
                for(let y = 0; i < numbers[j].split('').length; y++){
                    if(numbers[j].split('')[x] === numbers[j].split('')[x + y]){
                        newString += numbers[j].split('')[x];
                    } else break;
                 }
            return removeSpecialChars(referenceNumber.replace(invalidChar, newString));
            }
        }
    }

    return referenceNumber;
} // end function

if (removeSpecialChars(encrypted[i]) === numbers[j]) {
    count++;
}

}
}

I am not sure if I am approaching this in the wrong way entirely or if I am just missing something.

Here is a fiddle to reproduce my results.
https://jsfiddle.net/6ezuwhdb/1/

Body:
it seems that there are at least 2 rules at play here (I haven't looked at the fiddle in any detail but what there is here can be easily extended):

000 is encoded with a @, and

44 is encoded with a P

I would first get a complete list of these rules together and then use regular expressions to replace all instances of the special characters with their numeric equivalents.

The regular expressions use the g modifier so that all instances of the encoded value get replaced within the string.

const encoded = ['310254@3543129', '03254@03715P5'];

const decoded = encoded.map(en => {
  // replace the special characters using multiple regular expressions
  let result = en;
  // swap all @'s for
  result = result.replace(/@/g, '000');
  // swap all P's for 44
  result = result.replace(/P/g, '44');
  // add more rules here ...

  return result;
});

console.log('Decoded numbers: ', decoded);

To then check whether the normal numbers can be found within the decoded set of numbers is fairly straight forward.

// From previous step ;o)
const decoded = [
  "3102540003543129",
  "0325400003715445"
];

const numbers = ['3102540003543129', '0325400003715445'];
const matchedNumbers = numbers.filter(number => {
  return decoded.indexOf(number) >= 0;
});

console.log(matchedNumbers);


问:
Sending POST data via AJAX to NodeJS server
I have made basic web apps whereby data is sent via HTTP parameters. However, I am trying to send data from client-side that contains an array (a list of ingredients for a recipe) and eventually, hopefully user uploaded image (but not worried about that for now). For this I know I need to use AJAX. I have spent hours trying to get it to work but for some reason, no POST request is being sent. The user inputs are fairly basic but here's a snippet:

```<code> <label for="method"> Method </label>
    <textarea id="method" name="method">method here</textarea>
    </br>
    <p> add ingredients </p>
    <input name="ingredient" id="ingredient" placeholder="add ingredient">
    <input name="quantity" id="quantity" placeholder="#"><button id="addIngBtn" type="button">Add</button><br>
    <button type="submit">submit</button>
    <p> Ingredients:</p>
    <ul id="ingredientListUL">

</code>```

I use JQUERY to allow users to append as many ingredients as they want to the list:

```<code>  $(document).ready(() => {
        $("#addIngBtn").click(() => {
            let ingredient = $("#ingredient").val();
            let quantity = $("#quantity").val();
            $("#ingredient").val(""); //reset ingredient input
            $("#quantity").val("");
            $("ul").append(
                "<li>" + ingredient + " - " + quantity + "</li>"
            );
        });
    })

</code>```

Ingredients are built into an array and then added to a new recipe object which is the data I want to send to my server:

```<code>var ingredients = [];
          $("#ingredientListUL li").each((index, element) =>
              ingredients.push($(element).text())
          )
          var recipe = {
              name: $("#name").val(),
              image: $("#image").val(),
              oneLiner: $("#oneLiner").val(),
              method: $("#method").val(),
              ingredients: ingredients
          }

</code>```

So far so good. I presume I am doing something wrong with these next parts. Here's the AJAX post request:

```<code>$.ajax({
            url: "http://localhost:5000/recipes",
            type: "POST",
            dataType: "json",
            data: recipe,
            contentType: "application/json",
            complete: function () {
                console.log("process complete");
            },
            success: function (data) {
                console.log(data);
                console.log("process success");
            },
            error: function () {
                console.log(err);
            }
        })

</code>```

And here's my server info:

```<code>// express setup
const express = require("express");
const app = express();
const port = 5000;

// set templating engine to EJS
app.set('view engine', 'ejs');

// import route files
const recipeRoutes = require("./routes/recipes")
app.use("/recipes", recipeRoutes);

// body parser
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

//--
// BASIC ROUTES
//--

app.get("/", (req, res) => res.render("landing"));

// Port
app.listen(port, () => console.log(`Server starting on port ${port}!`));

</code>```

All routes, are stored in a recipe routes file, which contains the post route for this request:

```<code>// default "/" route is really "/recipes" as defined in main server file.
router.post("/", (req, res) => {

    console.log(req.body.recipe);

})

</code>```

The problem is that nothing appears to be sent to, or received by my server according to network tab. Even when I try to send something like:

```<code>        $.post("http://localhost:5000/recipes", { test: "test" })

</code>```

What am I doing wrong? Thanks.

答:
The contentType property does not work that way. It indicates if it is URL encoded, as a multipart message, etc. Try removing it.

According to: https://api.jquery.com/jquery.ajax/ :

"If you explicitly pass in a content-type to $.ajax(), then it is
  always sent to the server (even if no data is sent)"

Body:
I have made basic web apps whereby data is sent via HTTP parameters. However, I am trying to send data from client-side that contains an array (a list of ingredients for a recipe) and eventually, hopefully user uploaded image (but not worried about that for now). For this I know I need to use AJAX. I have spent hours trying to get it to work but for some reason, no POST request is being sent. The user inputs are fairly basic but here's a snippet:

  Method
    <textarea id="method" name="method">method here</textarea>

 add ingredients

    <input name="ingredient" id="ingredient" placeholder="add ingredient">
    <input name="quantity" id="quantity" placeholder="#"><button id="addIngBtn" type="button">Add</button>

    <button type="submit">submit</button>

 Ingredients:

I use JQUERY to allow users to append as many ingredients as they want to the list:

  $(document).ready(() => {
        $("#addIngBtn").click(() => {
            let ingredient = $("#ingredient").val();
            let quantity = $("#quantity").val();
            $("#ingredient").val(""); //reset ingredient input
            $("#quantity").val("");
            $("ul").append(
                "
" + ingredient + " - " + quantity + "
"
            );
        });
    })

Ingredients are built into an array and then added to a new recipe object which is the data I want to send to my server:

var ingredients = [];
          $("#ingredientListUL li").each((index, element) =>
              ingredients.push($(element).text())
          )
          var recipe = {
              name: $("#name").val(),
              image: $("#image").val(),
              oneLiner: $("#oneLiner").val(),
              method: $("#method").val(),
              ingredients: ingredients
          }

So far so good. I presume I am doing something wrong with these next parts. Here's the AJAX post request:

$.ajax({
            url: "http://localhost:5000/recipes",
            type: "POST",
            dataType: "json",
            data: recipe,
            contentType: "application/json",
            complete: function () {
                console.log("process complete");
            },
            success: function (data) {
                console.log(data);
                console.log("process success");
            },
            error: function () {
                console.log(err);
            }
        })

And here's my server info:

// express setup
const express = require("express");
const app = express();
const port = 5000;

// set templating engine to EJS
app.set('view engine', 'ejs');

// import route files
const recipeRoutes = require("./routes/recipes")
app.use("/recipes", recipeRoutes);

// body parser
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

//--
// BASIC ROUTES
//--

app.get("/", (req, res) => res.render("landing"));

// Port
app.listen(port, () => console.log(`Server starting on port ${port}!`));

All routes, are stored in a recipe routes file, which contains the post route for this request:

// default "/" route is really "/recipes" as defined in main server file.
router.post("/", (req, res) => {

    console.log(req.body.recipe);

})

The problem is that nothing appears to be sent to, or received by my server according to network tab. Even when I try to send something like:

        $.post("http://localhost:5000/recipes", { test: "test" })

What am I doing wrong? Thanks.


问:
Obtain form input fields using jQuery?
I have a form with many input fields.

When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?

答:
Try the following code:</p>

```<code>jQuery("#form").serializeArray().filter(obje =>
obje.value!='').map(aobj=>aobj.name+"="+aobj.value).join("&")
</code>```

OwnerDisplayName: Vasil

ContentLicense: CC BY-SA 2.5

Title: Obtain form input fields using jQuery?

Body:
Try the following code:

jQuery("#form").serializeArray().filter(obje =>
obje.value!='').map(aobj=>aobj.name+"="+aobj.value).join("&")


问:
es6 Map and Set complexity, v8 implementation
Is it a fair assumption that in v8 implementation retrieval / lookup is O(1)?

(I know that the standard doesn't guarantee that)

答:
```<code>let map = new Map();
let obj = {};

const benchMarkMapSet = size => {
console.time("benchMarkMapSet");
for (let i = 0; i < size; i++) {
    map.set(i, i);
}
console.timeEnd("benchMarkMapSet");
};

const benchMarkMapGet = size => {
console.time("benchMarkMapGet");
for (let i = 0; i < size; i++) {
    let x = map.get(i);
}
console.timeEnd("benchMarkMapGet");
};

const benchMarkObjSet = size => {
console.time("benchMarkObjSet");
for (let i = 0; i < size; i++) {
    obj[i] = i;
}
console.timeEnd("benchMarkObjSet");
};

const benchMarkObjGet = size => {
console.time("benchMarkObjGet");
for (let i = 0; i < size; i++) {
    let x = obj[i];
}
console.timeEnd("benchMarkObjGet");
};

let size = 2e6;

benchMarkMapSet(size);
benchMarkObjSet(size);
benchMarkMapGet(size);
benchMarkObjGet(size);
</code>```

benchMarkMapSet: 382.935ms
benchMarkObjSet: 76.077ms
benchMarkMapGet: 125.478ms
benchMarkObjGet: 2.764ms

benchMarkMapSet: 373.172ms
benchMarkObjSet: 77.192ms
benchMarkMapGet: 123.035ms
benchMarkObjGet: 2.638ms

Body:
let map = new Map();
let obj = {};

const benchMarkMapSet = size => {
console.time("benchMarkMapSet");
for (let i = 0; i < size; i++) {
    map.set(i, i);
}
console.timeEnd("benchMarkMapSet");
};

const benchMarkMapGet = size => {
console.time("benchMarkMapGet");
for (let i = 0; i < size; i++) {
    let x = map.get(i);
}
console.timeEnd("benchMarkMapGet");
};

const benchMarkObjSet = size => {
console.time("benchMarkObjSet");
for (let i = 0; i < size; i++) {
    obj[i] = i;
}
console.timeEnd("benchMarkObjSet");
};

const benchMarkObjGet = size => {
console.time("benchMarkObjGet");
for (let i = 0; i < size; i++) {
    let x = obj[i];
}
console.timeEnd("benchMarkObjGet");
};

let size = 2e6;

benchMarkMapSet(size);
benchMarkObjSet(size);
benchMarkMapGet(size);
benchMarkObjGet(size);

benchMarkMapSet: 382.935ms
benchMarkObjSet: 76.077ms
benchMarkMapGet: 125.478ms
benchMarkObjGet: 2.764ms

benchMarkMapSet: 373.172ms
benchMarkObjSet: 77.192ms
benchMarkMapGet: 123.035ms
benchMarkObjGet: 2.638ms