问:
Did SWIFT DateFormatter.dateFormat formatting change?
I recently noticed my DateFormatter is no longer working with am/pm format. Did Swift recently change "h" and "a" dateFormat symbols? Could it be another setting I may have recently changed and am not seeing?

```<code>let formatt = DateFormatter()
formatt.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateDater = formatt.date(from:"2019-03-16 14:00:00")
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yy hh:mm a"
let string = formatter.string(from:dateDater!)
print("DateString",string)
</code>```

Result: DateString 03/16/19 14:00

答:
Unless you prevent it, formatting depends on the user Locale. So it all depends on your regional and date time settings, such as this one:

And this one:

For more info, read https://developer.apple.com/library/archive/qa/qa1480/_index.html

Body:
I recently noticed my DateFormatter is no longer working with am/pm format. Did Swift recently change "h" and "a" dateFormat symbols? Could it be another setting I may have recently changed and am not seeing?

let formatt = DateFormatter()
formatt.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateDater = formatt.date(from:"2019-03-16 14:00:00")
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yy hh:mm a"
let string = formatter.string(from:dateDater!)
print("DateString",string)

Result: DateString 03/16/19 14:00


来源: stackexchange

问:
Custom meta tag name color in VS Code
I'm new in developement. I'm using VSCode with One Dark+ theme. I would like to change a meta tag name color from "#E06C75" to "#1b1ff0". I tried modified the settings.json but it didn't work. Please help me to resolve this issue.

To make it clear what is "meta tag name" (maybe I use wrong words), it means something like <xs:complexType> </xs:complexType> in XML file or html tag like
,
 etc...

Here is my settings.json file.
Hope it helps.

Thank you.

```<code>    {
    "php.validate.executablePath": "C:/xampp/php/php.exe",
    "workbench.sideBar.location": "right",
    "workbench.iconTheme": "vscode-icons",
    "workbench.colorTheme": "One Dark Pro",
    "workbench.colorCustomizations":{
        "tokenColors": [
           {
            "scope": "entity.name.tag",
            "settings": {
                "foreground": "#1b1ff0"
            }
           },
           {
            "scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
            "settings": {
                "foreground": "#1b1ff0"
            }
        }
        ]
    }
}
</code>```

答:
Your syntax is just a little off:</p>

```<code>"editor.tokenColorCustomizations": {            // this is different
    "textMateRules": [                          // this is different
       {
        "scope": "entity.name.tag",
        "settings": {
            "foreground": "#1b1ff0"
        }
       },
       {
        "scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
        "settings": {
            "foreground": "#1b1ff0"
        }
      }
   ]
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Custom meta tag name color in VS Code

Body:
I'm new in developement. I'm using VSCode with One Dark+ theme. I would like to change a meta tag name color from "#E06C75" to "#1b1ff0". I tried modified the settings.json but it didn't work. Please help me to resolve this issue.

To make it clear what is "meta tag name" (maybe I use wrong words), it means something like <xs:complexType> </xs:complexType> in XML file or html tag like
,
 etc...

Here is my settings.json file.
Hope it helps.

Thank you.

    {
    "php.validate.executablePath": "C:/xampp/php/php.exe",
    "workbench.sideBar.location": "right",
    "workbench.iconTheme": "vscode-icons",
    "workbench.colorTheme": "One Dark Pro",
    "workbench.colorCustomizations":{
        "tokenColors": [
           {
            "scope": "entity.name.tag",
            "settings": {
                "foreground": "#1b1ff0"
            }
           },
           {
            "scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
            "settings": {
                "foreground": "#1b1ff0"
            }
        }
        ]
    }
}

Body:
Your syntax is just a little off:

"editor.tokenColorCustomizations": {            // this is different
    "textMateRules": [                          // this is different
       {
        "scope": "entity.name.tag",
        "settings": {
            "foreground": "#1b1ff0"
        }
       },
       {
        "scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
        "settings": {
            "foreground": "#1b1ff0"
        }
      }
   ]
}


问:
C# conversion failed when converting nvarchar to int
I am trying to insert values to my database but I keep getting the error

"conversion failed when converting the nvarchar 'Year' value to
  datatype int"

in c#. I don't know how to fix this.

Here is my code:

```<code>private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        if (MessageBox.Show("Are you sure you want to save this book?", "Saving Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            //open connection to the database
            cn.Open();
            //command to be executed on the database
            cm = new SqlCommand("INSERT INTO Books(BookTitle, Edition, Genre, Author, Publisher, Year, ISBN) VALUES (@BookTitle, @Edition, @Genre, @Author, @Publisher, @Year, @ISBN )", cn);
            //set paramaters value
            cm.Parameters.AddWithValue("@booktitle", txtBook.Text);
            cm.Parameters.AddWithValue("@edition", txtEdition.Text);
            cm.Parameters.AddWithValue("@genre", txtGenre.Text);
            cm.Parameters.AddWithValue("@author", txtAuthor.Text);
            cm.Parameters.AddWithValue("@publisher", txtPublisher.Text);
            cm.Parameters.AddWithValue("@year", txtYear.Text);
            cm.Parameters.AddWithValue("@isbn", txtISBN.Text);
            //ask db to execute query
            cm.ExecuteNonQuery();
            //close connection
            cn.Close();
            MessageBox.Show("Record has been sucessfully saved!");
            Clear();
            frmlist.LoadRecords();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

答:
Convert the value first</p>

```<code>String yr = txtYear.Text;
int yr = Convert.ToInt32(yr);

cm.Parameters.AddWithValue("@year",""+yr );
</code>```

Body:
I am trying to insert values to my database but I keep getting the error

"conversion failed when converting the nvarchar 'Year' value to
  datatype int"

in c#. I don't know how to fix this.

Here is my code:

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        if (MessageBox.Show("Are you sure you want to save this book?", "Saving Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            //open connection to the database
            cn.Open();
            //command to be executed on the database
            cm = new SqlCommand("INSERT INTO Books(BookTitle, Edition, Genre, Author, Publisher, Year, ISBN) VALUES (@BookTitle, @Edition, @Genre, @Author, @Publisher, @Year, @ISBN )", cn);
            //set paramaters value
            cm.Parameters.AddWithValue("@booktitle", txtBook.Text);
            cm.Parameters.AddWithValue("@edition", txtEdition.Text);
            cm.Parameters.AddWithValue("@genre", txtGenre.Text);
            cm.Parameters.AddWithValue("@author", txtAuthor.Text);
            cm.Parameters.AddWithValue("@publisher", txtPublisher.Text);
            cm.Parameters.AddWithValue("@year", txtYear.Text);
            cm.Parameters.AddWithValue("@isbn", txtISBN.Text);
            //ask db to execute query
            cm.ExecuteNonQuery();
            //close connection
            cn.Close();
            MessageBox.Show("Record has been sucessfully saved!");
            Clear();
            frmlist.LoadRecords();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Body:
Convert the value first

String yr = txtYear.Text;
int yr = Convert.ToInt32(yr);

cm.Parameters.AddWithValue("@year",""+yr );


问:
Vector capacity and reserve
Consider the following code snippet:

```<code>std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;
</code>```

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?

答:
Yes, the vector still holds 100 locations. reserve is only used to increase the size and isn't able to shrink it. A reserve(0); call would have no effect at all. In C++1x I believe there will be a shrink_to_fit call that you're interested in.

In the current standard, you have to use the swap trick to release storage allocated by a vector, but before you do, carefully consider if you really want to do that. If you add elements back to the vector later again you'll just reallocate. Unless you're on an embedded system just let vector manage its own memory.

Swap trick: Use vector<T>().swap(myvector); to release the storage of a vector.

ContentLicense: CC BY-SA 3.0

Title: Vector capacity and reserve

Body:
Consider the following code snippet:

std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?


问:
How to split string surrounded by separators
How can I indicate that everything between { and } is a list of its own and everything inside of quotes but between a comma is a row in the list?

I'm using python 3 and pulling data from a website with 'request'. The website URL feeds me data in a format where it's separated by being enclosed in various characters.

```<code>URL = 'https://url.tld/thing?stuff&more_stuff'
request = requests.get(URL, auth=(USER,PASS))
request = request.content.decode('utf-8')
print(request)
print(type(request))
</code>```

Result:

```<code>[{"domain":"aaa.local","os":"2","hostname":"srv1.nyc","location":"Townsville, New York"},{"domain":"bbb.local","os":"3","hostname":"srv2.lax","location":"Compton, California"}]
<class 'str'>
</code>```

which can be thought of like this:

```<code>[{+-----------+----+----------+----------------------+
  | domain    | OS | hostname | location             |
  +-----------+----+----------+----------------------+
  | aaa.local | 2  | srv1.nyc | Townsville, New York |
  +-----------+----+----------+----------------------+},
 {+-----------+----+----------+----------------------+
  | domain    | OS | hostname | location             |
  +-----------+----+----------+----------------------+
  | bbb.local | 3  | srv2.lax | Compton, Californa   |
  +-----------+----+----------+----------------------+}]
</code>```

If I define it as a list without a separator, it comically puts every single character as an element inside of 1 list. If I define it as a list and the split is },{ then it all just one list.

ideally it would look like this if i manually typed it in a python list:

```<code>[['domain:aaa.local','os:2','location:Townsville, New York'],['domain:bbb.local','os:3','location:Compton, California']]
</code>```

With '},{' as the split, i get something close.

```<code>['[{"domain":aaa.local","os":"2","location":"townsville, new york"','"domain":bbb.local","os":"3","location":"compton, california"}]']
</code>```

答:
Looks like the request() is giving you back a list of two dicts in string form. So, you can just eval() it to make it into an actual list of two dicts. So,

```<code>my_list = eval(str(request))
</code>```

type(my_list) --> list

Actually, what's in between the { and } is not a list but rather a dict...

Body:
How can I indicate that everything between { and } is a list of its own and everything inside of quotes but between a comma is a row in the list?

I'm using python 3 and pulling data from a website with 'request'. The website URL feeds me data in a format where it's separated by being enclosed in various characters.

URL = 'https://url.tld/thing?stuff&more_stuff'
request = requests.get(URL, auth=(USER,PASS))
request = request.content.decode('utf-8')
print(request)
print(type(request))

Result:

[{"domain":"aaa.local","os":"2","hostname":"srv1.nyc","location":"Townsville, New York"},{"domain":"bbb.local","os":"3","hostname":"srv2.lax","location":"Compton, California"}]
<class 'str'>

which can be thought of like this:

[{+-----------+----+----------+----------------------+
  | domain    | OS | hostname | location             |
  +-----------+----+----------+----------------------+
  | aaa.local | 2  | srv1.nyc | Townsville, New York |
  +-----------+----+----------+----------------------+},
 {+-----------+----+----------+----------------------+
  | domain    | OS | hostname | location             |
  +-----------+----+----------+----------------------+
  | bbb.local | 3  | srv2.lax | Compton, Californa   |
  +-----------+----+----------+----------------------+}]

If I define it as a list without a separator, it comically puts every single character as an element inside of 1 list. If I define it as a list and the split is },{ then it all just one list.

ideally it would look like this if i manually typed it in a python list:

[['domain:aaa.local','os:2','location:Townsville, New York'],['domain:bbb.local','os:3','location:Compton, California']]

With '},{' as the split, i get something close.

['[{"domain":aaa.local","os":"2","location":"townsville, new york"','"domain":bbb.local","os":"3","location":"compton, california"}]']

Body:
Looks like the request() is giving you back a list of two dicts in string form. So, you can just eval() it to make it into an actual list of two dicts. So,

my_list = eval(str(request))

type(my_list) --> list

Actually, what's in between the { and } is not a list but rather a dict...


问:
How can I match the two dataframe and get the following result?
I have the following dataframe:
payment is the line of payment name with value

```<code>payment = pd.DataFrame({'Payment':["payment1","payment2","payment3"],'Value':[100,200,300]})

Payment     Value
payment1    100
payment2    200
payment3    300
</code>```

and project_cost is the line of project name with their cost

```<code>project_cost = pd.DataFrame({'Project':["Project1","Project2","Project3"],'Cost':[200,300,400]})

Project        Cost
Project1       200
Project2       300
Project3       400
</code>```

I basically want to match the payment with the project.

How can I get the following dataframe?

```<code>Project     Cost      Payment
Project1     100      payment1
Project1     100      payment2
Project2     100      payment2
Project2     200      payment3
Project3     100      payment3
Project3     300
</code>```

The last row of payment left empty because there is a deficit of payment to pay the project.

Is there anything I can do in the pandas to get this result?
Thanks a lot

The following is the logic of my dataframe:

The payment is broken down to match with the project.

答:
I am not sure that I understand the question properly, but if you want to merge both the data frames then you would need to have atleast one column to match i.e., "Value" or "Cost". So if you have the below input

```<code>payment = pd.DataFrame({'Payment':["payment1","payment2","payment3"],'Cost':[100,200,300]})
project_cost = pd.DataFrame({'Project':["Project1","Project2","Project3"],'Cost':[200,300,400]})
</code>```

Then you can merge the two data frames by using merge in pandas

```<code>result = pd.merge(payment, project_cost, on= 'Cost')
</code>```

Let me know if I understood the problem correctly.

Edit:

```<code>    Payment Cost    Project
0   payment1    200 Project1
1   payment2    200 Project1
2   payment3    200 Project1
</code>```

Is this what you are looking for?

Body:
I have the following dataframe:
payment is the line of payment name with value

payment = pd.DataFrame({'Payment':["payment1","payment2","payment3"],'Value':[100,200,300]})

Payment     Value
payment1    100
payment2    200
payment3    300

and project_cost is the line of project name with their cost

project_cost = pd.DataFrame({'Project':["Project1","Project2","Project3"],'Cost':[200,300,400]})

Project        Cost
Project1       200
Project2       300
Project3       400

I basically want to match the payment with the project.

How can I get the following dataframe?

Project     Cost      Payment
Project1     100      payment1
Project1     100      payment2
Project2     100      payment2
Project2     200      payment3
Project3     100      payment3
Project3     300

The last row of payment left empty because there is a deficit of payment to pay the project.

Is there anything I can do in the pandas to get this result?
Thanks a lot

The following is the logic of my dataframe:

The payment is broken down to match with the project.

Body:
I am not sure that I understand the question properly, but if you want to merge both the data frames then you would need to have atleast one column to match i.e., "Value" or "Cost". So if you have the below input

payment = pd.DataFrame({'Payment':["payment1","payment2","payment3"],'Cost':[100,200,300]})
project_cost = pd.DataFrame({'Project':["Project1","Project2","Project3"],'Cost':[200,300,400]})

Then you can merge the two data frames by using merge in pandas

result = pd.merge(payment, project_cost, on= 'Cost')

Let me know if I understood the problem correctly.

Edit:

    Payment Cost    Project
0   payment1    200 Project1
1   payment2    200 Project1
2   payment3    200 Project1

Is this what you are looking for?


问:
Expanding variable scope
Within a for loop (i.e. .each()), I need to set the variable of openvalue to 1 if a condition is met. I then need to access the value of this variable at the end of the loop. Regardless of the situation, when I print the variable to the console, the result is always 0. I know why (variable scope), but I'm wondering how I can modify my code so that if openvalue is set to 1 within the forloop, that value will have permanence outside of the forloop.

```<code>var openvalue = 0; //sets default value
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        var openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);
</code>```

Thanks for your help!

答:
The problem exists only because you redeclare your openvalue variable with a var statement, which creates a second openvalue variable in the new function scope.  Here is your code in a snippet below:

var openvalue = 0; //sets default value
var textinputs = $('input');
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        var openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<input disabled />
<input /></code>```

Here in our solution we omit the second declaration and simply refer to the original openvalue in the parent scope, and we get the expected behavior:

var openvalue = 0; //sets default value
var textinputs = $('input');
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<input disabled />
<input /></code>```

Title: Expanding variable scope

Body:
Within a for loop (i.e. .each()), I need to set the variable of openvalue to 1 if a condition is met. I then need to access the value of this variable at the end of the loop. Regardless of the situation, when I print the variable to the console, the result is always 0. I know why (variable scope), but I'm wondering how I can modify my code so that if openvalue is set to 1 within the forloop, that value will have permanence outside of the forloop.

var openvalue = 0; //sets default value
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        var openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);

Thanks for your help!

Body:
The problem exists only because you redeclare your openvalue variable with a var statement, which creates a second openvalue variable in the new function scope.  Here is your code in a snippet below:

var openvalue = 0; //sets default value
var textinputs = $('input');
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        var openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<input disabled />
<input />

Here in our solution we omit the second declaration and simply refer to the original openvalue in the parent scope, and we get the expected behavior:

var openvalue = 0; //sets default value
var textinputs = $('input');
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<input disabled />
<input />


问:
Powershell: ConvertFrom-Json doesn't get the variable assigned due to forward and backward compatibility
I am trying to load a variables into powershell from variables.json having the following

```<code>{
    "psfp":  "C:/San\/SV65\/ps",
    "vmfp": "'C:/San\/SV65\/hyper-packer\/hyper-packer\/output-centos8-9\/Virtual Machines'",
    "psmp": "C:/San\/SV65\/ps",
    "vmname": ""
}
</code>```

Trying to import with

```<code>$jvariables=Get-Content -Raw -Path '.\variables-ps.json' | ConvertFrom-Json
</code>```

Output on powershell

```<code>PS C:\San\SV65\ps> Write-host $jvariables.psfp
C:/San/SV65/ps

PS C:\San\SV65\ps> Write-host $jvariables.vmfp
'C:/San/SV65/hyper-packer/hyper-packer/output-centos8-9/Virtual Machines'

PS C:\San\SV65\ps> Write-host $jvariables.psmp
C:/San/SV65/ps
</code>```

These forward slash not incompatible on powershell for a windows path! ConvertFrom-Json doesn't accept backslash on the variables tried with '' as well

Hence could not load my modules on these path

any other way to achieve the above case?
Want to use json as it easy for the end user to update rather a txt files

Please share

答:
you can loop through the object properties and change the path separator like this:

```<code>$jvariables.psobject.properties | where {$_.membertype -eq "NoteProperty"} |
foreach {$data.($_.name) = $_.value.replace("/","\")}
</code>```

or a simpler approach would be to escape backslash in config file, like this :

```<code>{
"psfp":  "C:\\San\\SV65\\ps",
"vmfp": "'C:\\San\\SV65\\hyper-packer\\hyper-packer\\output-centos8-9\\Virtual Machines'",
"psmp": "C:\\San\\SV65\\ps",
"vmname": ""

}
</code>```

Body:
I am trying to load a variables into powershell from variables.json having the following

{
    "psfp":  "C:/San\/SV65\/ps",
    "vmfp": "'C:/San\/SV65\/hyper-packer\/hyper-packer\/output-centos8-9\/Virtual Machines'",
    "psmp": "C:/San\/SV65\/ps",
    "vmname": ""
}

Trying to import with

$jvariables=Get-Content -Raw -Path '.\variables-ps.json' | ConvertFrom-Json

Output on powershell

PS C:\San\SV65\ps> Write-host $jvariables.psfp
C:/San/SV65/ps

PS C:\San\SV65\ps> Write-host $jvariables.vmfp
'C:/San/SV65/hyper-packer/hyper-packer/output-centos8-9/Virtual Machines'

PS C:\San\SV65\ps> Write-host $jvariables.psmp
C:/San/SV65/ps

These forward slash not incompatible on powershell for a windows path! ConvertFrom-Json doesn't accept backslash on the variables tried with '' as well

Hence could not load my modules on these path

any other way to achieve the above case?
Want to use json as it easy for the end user to update rather a txt files

Please share

Body:
you can loop through the object properties and change the path separator like this:

$jvariables.psobject.properties | where {$_.membertype -eq "NoteProperty"} |
foreach {$data.($_.name) = $_.value.replace("/","\")}

or a simpler approach would be to escape backslash in config file, like this :

{
"psfp":  "C:\\San\\SV65\\ps",
"vmfp": "'C:\\San\\SV65\\hyper-packer\\hyper-packer\\output-centos8-9\\Virtual Machines'",
"psmp": "C:\\San\\SV65\\ps",
"vmname": ""

}


问:
Can man pass an option to the roff formatter?

SYNOPSIS

From man(1):

-l

Format and display local manual files instead of
searching through the system's manual collection.

-t

Use groff -mandoc to format the manual page to stdout.

From groff_tmac(5):

papersize

This macro file is already loaded at start-up by troff so it
isn't necessary to call it explicitly.  It provides an interface
to set the paper size  on  the  command  line  with  the  option
-dpaper=size.  Possible values for size are the same as
the predefined papersize values in the DESC file (only
lowercase; see groff_font(5) for more) except a7–d7.
An appended l (ell) character denotes landscape orientation.
Examples:  a4,  c3l,  letterl.

Most output drivers need additional command-line switches -p
and -l to override the default paper length and orientation
as  set in  the driver-specific DESC file.  For example, use the
following for PS output on A4 paper in landscape orientation:

```<code>sh# groff -Tps -dpaper=a4l -P-pa4 -P-l -ms foo.ms > foo.ps
</code>```

THE PROBLEM

I would like to use these to format local and system man pages to print out, but want to switch the paper size from letter to A4. Unfortunately I couldn't find anything in man(1) about  passing options to the underlying roff formatter.

Right now I can use

zcat `man -w man` | groff -tman -dpaper=a4 -P-pa4
```

to format man(1) on stdout, but that's kind of long and I'd rather have man build the pipeline for me if I can. In addition the above pipeline might need changing for more complicated man pages, and while I could use grog, even it doesn't detect things like accented characters (for groff's -k option), while man does (perhaps using locale settings).

答:
The man command is typically intended only for searching for and displaying manual pages on a TTY device, not for producing typeset and paper printed output.

Depending on the host system, and/or the programs of interest, the a fully typeset printable form of a manual page can sometimes be generated when a program (or the whole system) is compiled.  This is more common for system documents and less common for manual pages though.

Note that depending on which manual pages you are trying to print there may be additional steps required.  Traditionally the following pipeline would be used to cover all the bases:

```<code>grap $MANFILE | pic | tbl | eqn /usr/pub/eqnchar | troff -tman -Tps | lpr -Pps
</code>```

Your best solution for simplifying your command line would probably be to write a little tiny script which encapsulates what you're doing.  Note that man -w might find several different filenames, so you would probably want to print each separately (or maybe only print the first one).

Body:
SYNOPSIS

From man(1):

-l

Format and display local manual files instead of
searching through the system's manual collection.

-t

Use groff -mandoc to format the manual page to stdout.

From groff_tmac(5):

papersize

This macro file is already loaded at start-up by troff so it
isn't necessary to call it explicitly.  It provides an interface
to set the paper size  on  the  command  line  with  the  option
-dpaper=size.  Possible values for size are the same as
the predefined papersize values in the DESC file (only
lowercase; see groff_font(5) for more) except a7–d7.
An appended l (ell) character denotes landscape orientation.
Examples:  a4,  c3l,  letterl.

Most output drivers need additional command-line switches -p
and -l to override the default paper length and orientation
as  set in  the driver-specific DESC file.  For example, use the
following for PS output on A4 paper in landscape orientation:

sh# groff -Tps -dpaper=a4l -P-pa4 -P-l -ms foo.ms > foo.ps

THE PROBLEM

I would like to use these to format local and system man pages to print out, but want to switch the paper size from letter to A4. Unfortunately I couldn't find anything in man(1) about  passing options to the underlying roff formatter.

Right now I can use

zcat `man -w man` | groff -tman -dpaper=a4 -P-pa4

to format man(1) on stdout, but that's kind of long and I'd rather have man build the pipeline for me if I can. In addition the above pipeline might need changing for more complicated man pages, and while I could use grog, even it doesn't detect things like accented characters (for groff's -k option), while man does (perhaps using locale settings).

Body:
The man command is typically intended only for searching for and displaying manual pages on a TTY device, not for producing typeset and paper printed output.

Depending on the host system, and/or the programs of interest, the a fully typeset printable form of a manual page can sometimes be generated when a program (or the whole system) is compiled.  This is more common for system documents and less common for manual pages though.

Note that depending on which manual pages you are trying to print there may be additional steps required.  Traditionally the following pipeline would be used to cover all the bases:

grap $MANFILE | pic | tbl | eqn /usr/pub/eqnchar | troff -tman -Tps | lpr -Pps

Your best solution for simplifying your command line would probably be to write a little tiny script which encapsulates what you're doing.  Note that man -w might find several different filenames, so you would probably want to print each separately (or maybe only print the first one).


问:
Git - How to use .netrc file on Windows to save user and password
Is it possible to use a .netrc file on Windows when I'm using Git to clone a remote repository with HTTP and user - password?</p>

答:
Is it possible to use a .netrc file on Windows?

Yes: You must:

define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)

put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

```<code>setx HOME %USERPROFILE%
</code>```

and the %HOME% will be set to 'C:\Users\"username"'.

Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

```<code>machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>
</code>```

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":

git-cmd.bat included in msysgit does set the %HOME% environment variable:

```<code>@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%
</code>```

爱国者 believes in the comments that  "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page):  . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".

A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

```
[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://bob@code.google.com/p/my-project/
```

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

```
[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/
```

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.

With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).

On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.

  Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

```<code>git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'
</code>```

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

```<code># and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'
</code>```

See a full example at "Is there a way to skip password typing when using https:// github"

With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).

(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of
  the gpg.program option.

  This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

Body:
Is it possible to use a .netrc file on Windows?

Yes: You must:

define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)

put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.

Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":

git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

爱国者 believes in the comments that  "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page):  . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".

A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://bob@code.google.com/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.

With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).

On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.

  Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"

With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).

(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of
  the gpg.program option.

  This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'


问:
Is there a way to run raw sql with Kotlin's Exposed library
I'm trying to run some sql specific to postgres and would like to reuse the transaction management within Exposed.</p>

答:
You can create a simple helper function like:

fun <T : Any> String.execAndMap(transform: (ResultSet) -> T): List<T> {
    val result = arrayListOf<T>()
    TransactionManager.current().exec(this) { rs ->
        while (rs.next()) {
            result += transform(rs)
        }
    }
    return result
}
"select u.name, c.name from user u inner join city c where blah blah".execAndMap { rs ->
    rs.getString("u.name") to rs.getString("c.name")
}

```

Taken from: https://github.com/JetBrains/Exposed/wiki/FAQ#q-is-it-possible-to-use-native-sql--sql-as-a-string

Body:
You can create a simple helper function like:

fun <T : Any> String.execAndMap(transform: (ResultSet) -> T): List<T> {
    val result = arrayListOf<T>()
    TransactionManager.current().exec(this) { rs ->
        while (rs.next()) {
            result += transform(rs)
        }
    }
    return result
}
"select u.name, c.name from user u inner join city c where blah blah".execAndMap { rs ->
    rs.getString("u.name") to rs.getString("c.name")
}

Taken from: https://github.com/JetBrains/Exposed/wiki/FAQ#q-is-it-possible-to-use-native-sql--sql-as-a-string


问:
How to initialize a LiveData<> object to avoid a NullPointerException when trying to return a single record
I want to pull a single record from my Room database and can do so with a query in my Dao:

```<code>@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
LiveData<Scenario> getScenario(long scenarioId);
</code>```

I only want to be update it in my ViewModel when there is a change:

```<code>final Observer<Scenario> scenarioObserver = new Observer<Scenario>() {
    @Override
    public void onChanged(Scenario scenario) {
        Log.d(TAG, "onChanged: " + scenario.getId());
    }
};
</code>```

When running I get an error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference
</code>```

but I can't initialize it the variable:

```<code>scenario = new LiveData<Scenario>();
</code>```

because I get an error: LiveData is abstract; cannot be abstract.

How do I deal with this situation? How do I initialize the LiveData object?

UPDATE

I get this error from the compiler:

```<code>error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.MutableLiveData<com.behaviorotg.tokensystem1.model.ScenarioBehaviorTokenLog>).
</code>```

On this line:

```<code>@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
MutableLiveData<Scenario> getScenario (long scenarioId);
</code>```

答:
Try </p>

```<code>LiveData scenario = new MutableLiveData<Scenario>();
</code>```

Body:
I want to pull a single record from my Room database and can do so with a query in my Dao:

@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
LiveData<Scenario> getScenario(long scenarioId);

I only want to be update it in my ViewModel when there is a change:

final Observer<Scenario> scenarioObserver = new Observer<Scenario>() {
    @Override
    public void onChanged(Scenario scenario) {
        Log.d(TAG, "onChanged: " + scenario.getId());
    }
};

When running I get an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observe(androidx.lifecycle.LifecycleOwner, androidx.lifecycle.Observer)' on a null object reference

but I can't initialize it the variable:

scenario = new LiveData<Scenario>();

because I get an error: LiveData is abstract; cannot be abstract.

How do I deal with this situation? How do I initialize the LiveData object?

UPDATE

I get this error from the compiler:

error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.MutableLiveData<com.behaviorotg.tokensystem1.model.ScenarioBehaviorTokenLog>).

On this line:

@Query("SELECT * FROM Scenario WHERE id=:scenarioId")
MutableLiveData<Scenario> getScenario (long scenarioId);

Body:
Try

LiveData scenario = new MutableLiveData<Scenario>();


问:
Accessing value from key with JavaScript
I'm new to JavaScript. This is giving me undefined.

What am I doing wrong? How do I log the values inside the objects?

let spaceship = {
  passengers: null
};

(spaceship.passengers = [{ name: "Mike" }, { ability: "teleportation" }]),
  [{ name: "David" }, { ability: "cook" }];

let firstPassenger = spaceship.passengers[0];
console.log(firstPassenger.ability);```

答:
For clarity, this statement:

```<code>(spaceship.passengers = [{ name: "Mike" }, { ability: "teleportation" }]),
  [{ name: "David" }, { ability: "cook" }];
</code>```

is syntactically like

```<code>(foo = 1), 2;
</code>```

This assigns 1 to foo, not [1, 2] as you expect. In your example, you assign to spaceship.passengers the value [{ name: "Mike" }, { ability: "teleportation" }]. Your firstPassenger is thus { name: "Mike" }, and has no ability. The one with the ability is your second, nameless passenger.

What you likely wanted to write instead is:

```<code>spaceship.passengers = [{ name: "Mike", ability: "teleportation" },
  { name: "David", ability: "cook" }];
</code>```

or formatted a bit more nicely:

```<code>spaceship.passengers = [
  { name: "Mike", ability: "teleportation" },
  { name: "David", ability: "cook" },
];
</code>```

It might sound preachy, but good formatting is key to good programming, as it allows you to see the structure of your code at a glance. It is clear in my last example what is the first passenger; in yours, not so much.

Body:
For clarity, this statement:

(spaceship.passengers = [{ name: "Mike" }, { ability: "teleportation" }]),
  [{ name: "David" }, { ability: "cook" }];

is syntactically like

(foo = 1), 2;

This assigns 1 to foo, not [1, 2] as you expect. In your example, you assign to spaceship.passengers the value [{ name: "Mike" }, { ability: "teleportation" }]. Your firstPassenger is thus { name: "Mike" }, and has no ability. The one with the ability is your second, nameless passenger.

What you likely wanted to write instead is:

spaceship.passengers = [{ name: "Mike", ability: "teleportation" },
  { name: "David", ability: "cook" }];

or formatted a bit more nicely:

spaceship.passengers = [
  { name: "Mike", ability: "teleportation" },
  { name: "David", ability: "cook" },
];

It might sound preachy, but good formatting is key to good programming, as it allows you to see the structure of your code at a glance. It is clear in my last example what is the first passenger; in yours, not so much.


问:
Printing Javascript Template Strings with Line Breaks
Is there a way to print (using console.log) javascript template strings, applying the substitutions when it's the case, but considering the linebreaks '\n' when printing?

For instance, when I have the following:

let someVar = 'a';

let tsString = `here goes ${someVar}
some other line
some other line`;

console.log(tsString);```

I'd like it to print WITH the linebreaks, not printing the \n's instead.

I think there could be some transformation between template strings and regular strings, but I could not find it.

*** EDIT: It happens on Terminal, not browser. Running a NodeJS app. Sorry for not specifying that, I assumed that what I wanted would be JS-specific, not node's (at least the solution).

答:
You should try replacing the EOL based on where you are taking the content, forms as a standard should support the CRLF \r\n as per the spec (https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4)

Use the following regex to replace all occurences. \n would match EOL and /gm would match all

let someVar = 'a';

let tsString = `here goes ${someVar}
some other line
some other line`;

//For terminal (detects EOL on it's own)
console.log(tsString);
let txtString = tsString.replace(/\n/gm, `\r\n`);
// Works in terminal and in textarea
console.log(txtString);
//For html content, redundant but if it's just html you want!
let htmlString = tsString.replace(/\n/gm, `<br>`);
console.log(htmlString);```

Body:
Is there a way to print (using console.log) javascript template strings, applying the substitutions when it's the case, but considering the linebreaks '\n' when printing?

For instance, when I have the following:

let someVar = 'a';

let tsString = `here goes ${someVar}
some other line
some other line`;

console.log(tsString);

I'd like it to print WITH the linebreaks, not printing the \n's instead.

I think there could be some transformation between template strings and regular strings, but I could not find it.

*** EDIT: It happens on Terminal, not browser. Running a NodeJS app. Sorry for not specifying that, I assumed that what I wanted would be JS-specific, not node's (at least the solution).


问:
Python Opencv: Filter Image for Text Detection

I have these set of images I want to de-noise in order to run OCR on :

I am trying to read the 1973 from the image.

I have tried

```<code>import cv2,numpy as np

img=cv2.imread('uxWbP.png',0)
img = cv2.resize(img, (0, 0), fx=2, fy=2)
copy_img=np.copy(img)
#adaptive threshold as the image has different lighting conditions in different areas
thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 2)

contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#kill small contours
for i_cnt, cnt in enumerate(sorted(contours, key=lambda x: cv2.boundingRect(x)[0])):
    _area = cv2.contourArea(cnt)
    x, y, w, h = cv2.boundingRect(cnt)
    x_y_area = w * h
    if 10000 < x_y_area and x_y_area < 400000:
        pass
        # cv2.rectangle(copy_img, (x, y), (x + w, y + h), (255, 0, 255), 2)
        # cv2.putText(copy_img, str(int(x_y_area)) + ' , ' + str(w) + ' , ' + str(h), (x, y + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
        # cv2.drawContours(copy_img, [cnt], 0, (0, 255, 0), 1)
    elif 10000 > x_y_area:
        #write over small contours
        cv2.drawContours(thresh, [cnt], -1, 255, -1)

cv2.imshow('img',copy_img)
cv2.imshow('thresh',thresh)
cv2.waitKey(0)
</code>```

Which significantly improves the image to:

Any recommendations on how to filter this image sufficiently either on improvements to the filtered image or complete change from the start, that I could run OCR or some ML detection scripts on this? I'd like to split out the numbers for detection, but open to other methods as well.

答:
My first thought is to put on a Gaussian blur for a sort of "unsharp filter". (I think my second idea is better; it combines this blur-and-add with the erosion/dilation game. I posted it as a separate answer, because I think it is a different-enough strategy to merit that.) @eldesgraciado noted frequency stuff, which is basically what we're doing here. I'll put on some code and explanation. (Here is one answer to an SO post that has a lot about sharpening - the answer linked is a more variable unsharp mask written in Python. Do take the time to look at other answers - including this one, one of many simple implementations that look just like mine - though some are written in different programming languages.) You'll need to mess with parameters. It's possible this won't work, but it's the first thing I thought of.

>>> import cv2
>>> im_0 = cv2.imread("FWM8b.png")
>>> cv2.imshow("FWM8b.png", im_0)
>>> cv2.waitKey(0)
## Press any key.
>>> ## Here's where we get to frequency. We'll use a Gaussian Blur.
    ## We want to take out the "frequency" of changes from white to black
    ## and back to white that are less than the thickness of the "1973"
>>> k_size = 0 ## This is the kernal size - the "width frequency",
               ## if you will. Using zero gives a width based on sigmas in
               ## the Gaussian function.
               ## You'll want to experiment with this and the other
               ## parameters, perhaps trying to run OCR over the image
               ## after each combination of parameters.
               ## Hint, avoid even numbers, and think of it as a radius
>>> gs_border = 3
>>> im_blurred = cv2.GaussianBlur(im_0, (k_size, k_size), gs_border)
>>> cv2.imshow("gauss", im_blurred)
>>> cv2.waitKey(0)
```

<p><img src="https://i.stack.imgur.com/Q7yry.png" alt="Gaussian blur with kernel size determined by sigmas"></p>

<p>Okay, my parameters probably didn't blur this enough. The parts of the words that you want to get rid of aren't really blurry. I doubt you'll even see much of a difference from the original, but hopefully you'll get the idea.</p>

<p>We're going to multiply the original image by a value, multiply the blurry image by a value, and subtract <code>value*blurry</code> from <code>value*orig</code>. Code will be clearer, I hope.</p>

<pre class="lang-py prettyprint-override"><code>>>> orig_img_multiplier = 1.5
>>> blur_subtraction_factor = -0.5
>>> gamma = 0
>>> im_better = cv2.addWeighted(im_0, orig_img_multiplier, im_blurred, blur_subtraction_factor, gamma)
>>> cv2.imshow("First shot at fixing", im_better)

</code>```

Yeah, not too much different. Mess around with the parameters, try to do the blur before you do your adaptive threshold, and try some other methods. I can't guarantee it will work, but hopefully it will get you started going somewhere.

Edit
This is a great question. Responding to the tongue-in-cheek criticism of @eldesgraciado

Ah, naughty, naughty. Trying to break them CAPTCHA codes, huh? They are difficult to break for a reason. The text segmentation, as you see, is non-trivial. In your particular image, there’s a lot of high-frequency noise, you could try some frequency filtering first and see what result you get.

I submit the following from the Wikipedia article on reCAPTCHA (archived).

reCAPTCHA has completely digitized the archives of The New York Times and books from Google Books, as of 2011.three The archive can be searched from the New York Times Article Archive.four Through mass collaboration, reCAPTCHA was helping to digitize books that are too illegible to be scanned by computers, as well as translate books to different languages, as of 2015.five

Also look at this article (archived).

I don't think this CAPTCHA is part of Massive-scale Online Collaboration, though.

Edit: Some other type of sharpening will be needed. I just realized that I'm applying 1.5 and -0.5 multipliers to pixels which usually have values very close to 0 or 255, meaning I'm probably just recovering the original image after the sharpening. I welcome any feedback on this.

Also, from comments with @eldesgracio:

Someone probably knows a better sharpening algorithm than the one I used. Blur it enough, and maybe threshold on average values over an n-by-n grid (pixel density). I don't know to much about the whole adaptive-thresholding-then-contours thing. Maybe that could be re-done after the blurring...

Just to give you some ideas ...

Here's a blur with k_size = 5

Here's a blur with k_size = 25

Note those are the BLURS, not the fixes. You'll likely need to mess with the orig_img_multiplier and blur_subtraction_factor based on the frequency (I can't remember exactly how, so I can't really tell you how it's done.) Don't hesitate to fiddle with gs_border, gamma, and anything else you might find in the documentation for the methods I've shown.

Good luck with it.

By the way, the frequency is more something based on the 2-D Fast Fourier Transform, and possibly based on kernel details. I've just messed around with this stuff myself - definitely not an expert AND definitely happy if someone wants to give more details - but I hope I've given a basic idea. Adding some jitter noise (up and down or side to side blurring, rather than radius-based), might be helpful as well.

Body:
I have these set of images I want to de-noise in order to run OCR on :

I am trying to read the 1973 from the image.

I have tried

import cv2,numpy as np

img=cv2.imread('uxWbP.png',0)
img = cv2.resize(img, (0, 0), fx=2, fy=2)
copy_img=np.copy(img)
#adaptive threshold as the image has different lighting conditions in different areas
thresh = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 2)

contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#kill small contours
for i_cnt, cnt in enumerate(sorted(contours, key=lambda x: cv2.boundingRect(x)[0])):
    _area = cv2.contourArea(cnt)
    x, y, w, h = cv2.boundingRect(cnt)
    x_y_area = w * h
    if 10000 < x_y_area and x_y_area < 400000:
        pass
        # cv2.rectangle(copy_img, (x, y), (x + w, y + h), (255, 0, 255), 2)
        # cv2.putText(copy_img, str(int(x_y_area)) + ' , ' + str(w) + ' , ' + str(h), (x, y + 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
        # cv2.drawContours(copy_img, [cnt], 0, (0, 255, 0), 1)
    elif 10000 > x_y_area:
        #write over small contours
        cv2.drawContours(thresh, [cnt], -1, 255, -1)

cv2.imshow('img',copy_img)
cv2.imshow('thresh',thresh)
cv2.waitKey(0)

Which significantly improves the image to:

Any recommendations on how to filter this image sufficiently either on improvements to the filtered image or complete change from the start, that I could run OCR or some ML detection scripts on this? I'd like to split out the numbers for detection, but open to other methods as well.

Body:
My first thought is to put on a Gaussian blur for a sort of "unsharp filter". (I think my second idea is better; it combines this blur-and-add with the erosion/dilation game. I posted it as a separate answer, because I think it is a different-enough strategy to merit that.) @eldesgraciado noted frequency stuff, which is basically what we're doing here. I'll put on some code and explanation. (Here is one answer to an SO post that has a lot about sharpening - the answer linked is a more variable unsharp mask written in Python. Do take the time to look at other answers - including this one, one of many simple implementations that look just like mine - though some are written in different programming languages.) You'll need to mess with parameters. It's possible this won't work, but it's the first thing I thought of.

>>> import cv2
>>> im_0 = cv2.imread("FWM8b.png")
>>> cv2.imshow("FWM8b.png", im_0)
>>> cv2.waitKey(0)
## Press any key.
>>> ## Here's where we get to frequency. We'll use a Gaussian Blur.
    ## We want to take out the "frequency" of changes from white to black
    ## and back to white that are less than the thickness of the "1973"
>>> k_size = 0 ## This is the kernal size - the "width frequency",
               ## if you will. Using zero gives a width based on sigmas in
               ## the Gaussian function.
               ## You'll want to experiment with this and the other
               ## parameters, perhaps trying to run OCR over the image
               ## after each combination of parameters.
               ## Hint, avoid even numbers, and think of it as a radius
>>> gs_border = 3
>>> im_blurred = cv2.GaussianBlur(im_0, (k_size, k_size), gs_border)
>>> cv2.imshow("gauss", im_blurred)
>>> cv2.waitKey(0)

Okay, my parameters probably didn't blur this enough. The parts of the words that you want to get rid of aren't really blurry. I doubt you'll even see much of a difference from the original, but hopefully you'll get the idea.

We're going to multiply the original image by a value, multiply the blurry image by a value, and subtract value*blurry from value*orig. Code will be clearer, I hope.

>>> orig_img_multiplier = 1.5
>>> blur_subtraction_factor = -0.5
>>> gamma = 0
>>> im_better = cv2.addWeighted(im_0, orig_img_multiplier, im_blurred, blur_subtraction_factor, gamma)
>>> cv2.imshow("First shot at fixing", im_better)

Yeah, not too much different. Mess around with the parameters, try to do the blur before you do your adaptive threshold, and try some other methods. I can't guarantee it will work, but hopefully it will get you started going somewhere.

Edit
This is a great question. Responding to the tongue-in-cheek criticism of @eldesgraciado

Ah, naughty, naughty. Trying to break them CAPTCHA codes, huh? They are difficult to break for a reason. The text segmentation, as you see, is non-trivial. In your particular image, there’s a lot of high-frequency noise, you could try some frequency filtering first and see what result you get.

I submit the following from the Wikipedia article on reCAPTCHA (archived).

reCAPTCHA has completely digitized the archives of The New York Times and books from Google Books, as of 2011.three The archive can be searched from the New York Times Article Archive.four Through mass collaboration, reCAPTCHA was helping to digitize books that are too illegible to be scanned by computers, as well as translate books to different languages, as of 2015.five

Also look at this article (archived).

I don't think this CAPTCHA is part of Massive-scale Online Collaboration, though.

Edit: Some other type of sharpening will be needed. I just realized that I'm applying 1.5 and -0.5 multipliers to pixels which usually have values very close to 0 or 255, meaning I'm probably just recovering the original image after the sharpening. I welcome any feedback on this.

Also, from comments with @eldesgracio:

Someone probably knows a better sharpening algorithm than the one I used. Blur it enough, and maybe threshold on average values over an n-by-n grid (pixel density). I don't know to much about the whole adaptive-thresholding-then-contours thing. Maybe that could be re-done after the blurring...

Just to give you some ideas ...

Here's a blur with k_size = 5

Here's a blur with k_size = 25

Note those are the BLURS, not the fixes. You'll likely need to mess with the orig_img_multiplier and blur_subtraction_factor based on the frequency (I can't remember exactly how, so I can't really tell you how it's done.) Don't hesitate to fiddle with gs_border, gamma, and anything else you might find in the documentation for the methods I've shown.

Good luck with it.

By the way, the frequency is more something based on the 2-D Fast Fourier Transform, and possibly based on kernel details. I've just messed around with this stuff myself - definitely not an expert AND definitely happy if someone wants to give more details - but I hope I've given a basic idea. Adding some jitter noise (up and down or side to side blurring, rather than radius-based), might be helpful as well.


问:
How to use input to refrence a specific object
This is my symptom class:

```<code>class Symptom:
    def __init__(self, name, cost, infectivity, lethality, pain):
        print(self)
        self.name = name
        self.cost = cost
        self.infectivity = infectivity
        self.lethality = lethality
        self.pain = pain
        self.bought = False

coughing = Symptom("coughing", 5, 50, 10, 5)
weight_loss = Symptom("weight_loss", 10, 5, 50, 15)
</code>```

I want to be able to use input to ask which symptom the player chooses(trying to make Plague Inc)

```<code>symptom = input("which symptom do you choose? ")#player must choose between coughing and weight loss

symptom.bought = True
</code>```

答:
Here is a way: </p>

```<code>while not symptom:
       symptom = input("which symptom do you choose")
</code>```

Body:
This is my symptom class:

class Symptom:
    def __init__(self, name, cost, infectivity, lethality, pain):
        print(self)
        self.name = name
        self.cost = cost
        self.infectivity = infectivity
        self.lethality = lethality
        self.pain = pain
        self.bought = False

coughing = Symptom("coughing", 5, 50, 10, 5)
weight_loss = Symptom("weight_loss", 10, 5, 50, 15)

I want to be able to use input to ask which symptom the player chooses(trying to make Plague Inc)

symptom = input("which symptom do you choose? ")#player must choose between coughing and weight loss

symptom.bought = True

Body:
Here is a way:

while not symptom:
       symptom = input("which symptom do you choose")


答:
I think you are defining the array of objects the wrong way, I think you want the ability and name into one object:

let spaceship = {
  passengers: null
};

spaceship.passengers = [{ name: "Mike" , ability: "teleportation" }, { name: "David" , ability: "cook" }];

let firstPassenger = spaceship.passengers[0];
console.log(firstPassenger.ability);```

Title: Accessing value from key with JavaScript

Body:
I'm new to JavaScript. This is giving me undefined.

What am I doing wrong? How do I log the values inside the objects?

let spaceship = {
  passengers: null
};

(spaceship.passengers = [{ name: "Mike" }, { ability: "teleportation" }]),
  [{ name: "David" }, { ability: "cook" }];

let firstPassenger = spaceship.passengers[0];
console.log(firstPassenger.ability);


问:
Change foreign key using SQL
I have a table like this:

```<code>ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     john@foo.com
3     Sally     sally@foo.com   sam@foo.com
..... more rows .....
</code>```

And I would like to change it to:

```<code>ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     1
3     Sally     sally@foo.com   2
..... more rows .....
</code>```

Can I make this change using SQL?

答:
Many DBMS' will allow this by the use of DDL (definition) statements rather than DML (manipulation). Assuming that id is an integral type and referred_by is (currently) a textual column, you can do something like:

alter the table to add a new column ref2 (nullable) of the same type as id.

set up a foreign key constraint between that ref2 and id.

populate the ref2 column for all the rows.

drop the original constraint.

alter the table to remove column referred_by.

alter the table to rename column ref2 to referred_by.

Title: Change foreign key using SQL

Body:
I have a table like this:

ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     john@foo.com
3     Sally     sally@foo.com   sam@foo.com
..... more rows .....

And I would like to change it to:

ID    Name      Email           Referred_by
-------------------------------------------
1     John      john@foo.com    NULL
2     Sam       sam@foo.com     1
3     Sally     sally@foo.com   2
..... more rows .....

Can I make this change using SQL?


问:
Dockerizing Drupal 8 on AWS ECS Error: Task failed ELB health checks in Target group for Drupal
I am trying to Dockerize my Drupal 8. Below DockerFile I have.

```<code>FROM drupal:8.8

RUN apt-get update && apt-get install -y \
    curl \
    git \
    mysql-client \
    vim \
    wget

RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \
    php composer-setup.php && \
    mv composer.phar /usr/local/bin/composer && \
    php -r "unlink('composer-setup.php');"

RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \
    chmod +x drush.phar && \
    mv drush.phar /usr/local/bin/drush

RUN rm -rf /var/www/html/*

WORKDIR /drupal
</code>```

Questions

Am I missing anything in above file?

Stopped reason : Task failed ELB health checks in (target-group arn:aws:elasticloadbalancing:ap-southeast-1:1111111:targetgroup/ecs-drupal/eff768afe54dda4a)

I am not sure what I am missing in ECS Cluster configuration or Task definition?

答:
It means you failed the health check so that maybe your container is working properly on your local environment, but you should check your Target Group -> health check.

You can set a health check path, interval, timeout, success code...etc on the Target Group health check setting. Then I think it should be the issue you are looking for.

So you can following the steps below:

1) Build and run your container locally, can check the health page on your local machine.

2) Check the Target Group -> Health Check settings

Body:
I am trying to Dockerize my Drupal 8. Below DockerFile I have.

FROM drupal:8.8

RUN apt-get update && apt-get install -y \
    curl \
    git \
    mysql-client \
    vim \
    wget

RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \
    php composer-setup.php && \
    mv composer.phar /usr/local/bin/composer && \
    php -r "unlink('composer-setup.php');"

RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \
    chmod +x drush.phar && \
    mv drush.phar /usr/local/bin/drush

RUN rm -rf /var/www/html/*

WORKDIR /drupal

Questions

Am I missing anything in above file?

Stopped reason : Task failed ELB health checks in (target-group arn:aws:elasticloadbalancing:ap-southeast-1:1111111:targetgroup/ecs-drupal/eff768afe54dda4a)

I am not sure what I am missing in ECS Cluster configuration or Task definition?


问:
500 error in Laravel but log folder is empty
I am working in a Client's Laravel project which version is 5.7.28. But I am not getting anything in storage/logs/ folder. I copied the .env.example to .env. I run composer install and php artisan key:generate. Some of my .env files configuration is like below

```<code>APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:8ovbzfpWGsGTDyDIRWDO8VKObeXGyWqnMVw5KjTVJTc=
APP_DEBUG=true
APP_URL=http://127.0.0.1:8000
BASE_URL=http://127.0.0.1:8000
</code>```

I set permission 777 for all folders.

But I am getting 500 error. How can I solve the error.

答:
try change to prod mode: APP_ENV=production then back to dev mode

don't forget to run: php artisan config:clear -> php artisan env

Body:
I am working in a Client's Laravel project which version is 5.7.28. But I am not getting anything in storage/logs/ folder. I copied the .env.example to .env. I run composer install and php artisan key:generate. Some of my .env files configuration is like below

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:8ovbzfpWGsGTDyDIRWDO8VKObeXGyWqnMVw5KjTVJTc=
APP_DEBUG=true
APP_URL=http://127.0.0.1:8000
BASE_URL=http://127.0.0.1:8000

I set permission 777 for all folders.

But I am getting 500 error. How can I solve the error.


问:
how to replace email domain name
Im trying to write a procedure that updates the domain of an email (example: converting Email123@gmail.com into Email123@hotmail.com when i pass 2 strings gmail.com and hotmail.com) while having a cursor in my procedure

```<code>create of replace procedure pr_update_email
(Old_Email Varchar2, New_Email Varchar2)
    As
    V_OldDomain Varchar2(50);
      Cursor C_Domains IS Select Email_Address
                From Customer
                where Email_Address Like '%@'||Old_Email;
          Begin
          Open C_Domains;
          Fetch C_Domains INTO V_OldDomain;
          While C_Domains %Found loop
                    Update Customer
                    Set Email_Address = regexp_replace(Email_Address, '^(.*@.*)'||Old_Email||'\1'||New_Email)
                    WHERE Email_Address LIKE V_OldDomain;
          Fetch C_Domains into New_Email;
          End Loop;
  Close C_Domains;
End pr_update_email;
/
Show Errors;
</code>```

getting errors:
 19/11    PL/SQL: SQL Statement ignored

19/32    PLS-00403: expression'NEW_EMAIL' cannot be used as an INTO-target of a
   SELECT/FETCH statement

答:
Why you are using the cursor? It can be handled using simple update statement.

Your procedure should look like this:

```<code>create procedure pr_update_email (p_oldemail in varchar2,
                       p_newemail in varchar2)
As
Begin

UPDATE BROKER
SET
    EMAIL_ADDRESS = REPLACE(EMAIL_ADDRESS, p_oldemail, p_newemail)
WHERE
    REGEXP_LIKE ( EMAIL_ADDRESS,'.*@'|| p_oldemail|| '$' );

Commit;

End;
/
</code>```

Or if you really want to use the loop then

```<code>create of replace procedure pr_update_email
(Old_Email Varchar2, New_Email Varchar2)
    As
    Begin
          For i in (Select Email_Address
                From Customer
                where Email_Address Like '%@'||Old_Email) loop

             Update Customer
                Set Email_Address = Replace(Email_Address, old_email, new_email)
              WHERE Email_Address = i.Email_Address;
          End Loop;
  Commit;
End pr_update_email;
/
</code>```

To call this procedure, you need to pass both the domain as following:

```<code>Begin
pr_update_email('gmail.com', 'hotmail.com');
End;
/
</code>```

And Yes, Issue in your code is following line:

```<code>Fetch C_Domains into New_Email;
</code>```

New_Email is an input parameter and you can not assign any value to the input parameter.

Cheers!!

Title: how to replace email domain name

Body:
Im trying to write a procedure that updates the domain of an email (example: converting Email123@gmail.com into Email123@hotmail.com when i pass 2 strings gmail.com and hotmail.com) while having a cursor in my procedure

create of replace procedure pr_update_email
(Old_Email Varchar2, New_Email Varchar2)
    As
    V_OldDomain Varchar2(50);
      Cursor C_Domains IS Select Email_Address
                From Customer
                where Email_Address Like '%@'||Old_Email;
          Begin
          Open C_Domains;
          Fetch C_Domains INTO V_OldDomain;
          While C_Domains %Found loop
                    Update Customer
                    Set Email_Address = regexp_replace(Email_Address, '^(.*@.*)'||Old_Email||'\1'||New_Email)
                    WHERE Email_Address LIKE V_OldDomain;
          Fetch C_Domains into New_Email;
          End Loop;
  Close C_Domains;
End pr_update_email;
/
Show Errors;

getting errors:
 19/11    PL/SQL: SQL Statement ignored

19/32    PLS-00403: expression'NEW_EMAIL' cannot be used as an INTO-target of a
   SELECT/FETCH statement

Body:
Why you are using the cursor? It can be handled using simple update statement.

Your procedure should look like this:

create procedure pr_update_email (p_oldemail in varchar2,
                       p_newemail in varchar2)
As
Begin

UPDATE BROKER
SET
    EMAIL_ADDRESS = REPLACE(EMAIL_ADDRESS, p_oldemail, p_newemail)
WHERE
    REGEXP_LIKE ( EMAIL_ADDRESS,'.*@'|| p_oldemail|| '$' );

Commit;

End;
/

Or if you really want to use the loop then

create of replace procedure pr_update_email
(Old_Email Varchar2, New_Email Varchar2)
    As
    Begin
          For i in (Select Email_Address
                From Customer
                where Email_Address Like '%@'||Old_Email) loop

             Update Customer
                Set Email_Address = Replace(Email_Address, old_email, new_email)
              WHERE Email_Address = i.Email_Address;
          End Loop;
  Commit;
End pr_update_email;
/

To call this procedure, you need to pass both the domain as following:

Begin
pr_update_email('gmail.com', 'hotmail.com');
End;
/

And Yes, Issue in your code is following line:

Fetch C_Domains into New_Email;

New_Email is an input parameter and you can not assign any value to the input parameter.

Cheers!!


问:
Is there a way to intercept setters and getters in C#?
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

答: Are you in a position to rewrite your class to implement an interface? If so, Unity's interface interceptor might give you what you need. If an interface is not an option then that link also documents Unity's type and instance interceptors.</p>

Body:
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.


问:
Using WebWorkers in Typescript with Webpack and worker-loader without custom loader strings
I'm trying to get web workers playing nice with Typescript and Webpack's worker-loader. There's an example in their documentation of achieving this through a custom module declaration, however this relies on using the webpack worker-loader!./myWorker syntax.

I want to be able to load workers through a custom *.worker.js webpack use rule rather than explicitly listing the loader in the import string. Something about typescript doesn't seem to like defining or modifying a modules declaration if it's a plain relative import, and gets stuck on the fact that the worker file is not a module, even with a module declaration for it.

I have a worker that looks like

```<code>// test.worker.ts
/// <reference lib="webworker" />

const worker: DedicatedWorkerGlobalScope = self as any;

worker.onmessage = ({ data }) => {
  if (data instanceof Array) {
    worker.postMessage(data.join(' ') + '!');
  }
};

</code>```

A declaration that looks like

```<code>// custom.d.ts
declare module '*.worker' {
  class TestWorker extends Worker {
    constructor();
  }

  export default TestWorker
}
</code>```

And is used in my main app as

```<code>import TestWorker from './test.worker';

const testWorker = new TestWorker();
testWorker.onmessage = ({ data }: { data: string }) => {
  console.log(data);
};

testWorker.postMessage([
  'hello',
  'I',
  'am',
  'a',
  'web',
  'worker',
]);
</code>```

The error output is

```<code>TypeScript error in /worker-test/src/index.tsx(9,24):File '/worker-test/src/test.worker.ts' is not a module.  TS2306
</code>```

Changing the import to worker-loader!./test.worker seems to work and gets typescript to understand the custom declaration, however I'm really trying to avoid using custom loader strings as the intention is to integrate this into create-react-app which doesn't allow these.

Is there a way to get regular relative imports to recognise a custom module declaration?

答:
You were almost there!

Change the module declaration to include the file extension:

```<code>// custom.d.ts
declare module '*.worker.ts' {
  class TestWorker extends Worker {
    constructor();
  }

  export default TestWorker
}
</code>```

And your import to also include the file extension:

```<code>import TestWorker from './test.worker.ts';
</code>```

This did it for me - specifying the extension in the import stops TS from importing it as a module, and specifying the extension in the declaration stops TS from complaining since you're importing a .ts file by also specifying the extension.

Body:
I'm trying to get web workers playing nice with Typescript and Webpack's worker-loader. There's an example in their documentation of achieving this through a custom module declaration, however this relies on using the webpack worker-loader!./myWorker syntax.

I want to be able to load workers through a custom *.worker.js webpack use rule rather than explicitly listing the loader in the import string. Something about typescript doesn't seem to like defining or modifying a modules declaration if it's a plain relative import, and gets stuck on the fact that the worker file is not a module, even with a module declaration for it.

I have a worker that looks like

// test.worker.ts
/// <reference lib="webworker" />

const worker: DedicatedWorkerGlobalScope = self as any;

worker.onmessage = ({ data }) => {
  if (data instanceof Array) {
    worker.postMessage(data.join(' ') + '!');
  }
};

A declaration that looks like

// custom.d.ts
declare module '*.worker' {
  class TestWorker extends Worker {
    constructor();
  }

  export default TestWorker
}

And is used in my main app as

import TestWorker from './test.worker';

const testWorker = new TestWorker();
testWorker.onmessage = ({ data }: { data: string }) => {
  console.log(data);
};

testWorker.postMessage([
  'hello',
  'I',
  'am',
  'a',
  'web',
  'worker',
]);

The error output is

TypeScript error in /worker-test/src/index.tsx(9,24):File '/worker-test/src/test.worker.ts' is not a module.  TS2306

Changing the import to worker-loader!./test.worker seems to work and gets typescript to understand the custom declaration, however I'm really trying to avoid using custom loader strings as the intention is to integrate this into create-react-app which doesn't allow these.

Is there a way to get regular relative imports to recognise a custom module declaration?

Body:
You were almost there!

Change the module declaration to include the file extension:

// custom.d.ts
declare module '*.worker.ts' {
  class TestWorker extends Worker {
    constructor();
  }

  export default TestWorker
}

And your import to also include the file extension:

import TestWorker from './test.worker.ts';

This did it for me - specifying the extension in the import stops TS from importing it as a module, and specifying the extension in the declaration stops TS from complaining since you're importing a .ts file by also specifying the extension.


问:
Bigcommerce Pagination in php
i hope all are doing well, I am working on Bigcommerce API integration with PHP, as API fetches 50 records per page, but what i want is it starts fetching all records 50 and then from next page store it in an array and then that data should be dropped to the database, i am confused with how to pass current page id to the api </p>

```<code>self::set_config($channel);
        $page  = 1;
        $url=self::$current_channel->api_url."v3/catalog/products?page=$page";
        $headers = self::getHeader($channel);
        $body = '';
        $response=self::make_api_request($url,$body,"GET",$headers);
//        echo "```";
//        print_r($response->meta->pagination->total);
//        echo "```";
//        exit;
        if(isset($response->data)) {
            foreach ($response->data as $item) {
                $record = self::get_product_detail($channel,$item->id); // get detail from api
                $record = isset($record->data[0]) ? $record->data[0] : NULL;
                if ($record)
                {
                    $mappedItems = [
                        'parent_sku_id' => null,
                        'sku' => $record->id,
                        'channel_sku' => $record->sku,
                        'variation_id' => $record->option_set_id,
                        'name' => $record->name,
                        'ean' => $record->upc, //$data->mpn, $data->gtin
                        'price' => $record->price,
                        'stock_qty' => isset($record->inventory_level) ? $record->inventory_level : null,
                        'channel_id' => self::$current_channel->id,
                        'is_live' => isset($record->is_visible) ? $record->is_visible : "1",
                        'type1' => 'main_product',
                    ];
                    $parent_sku_id = self::save_channel_products((object)$mappedItems); // will return product id from products table
                    $headers = self::getHeader($channel);

                    $url=self::$current_channel->api_url."v3/catalog/products/$item->id/variants";
                    $server_output = self::make_api_request($url,$body,"GET",$headers);

                    if ($parent_sku_id && isset($record->option_set_id)) {
                        foreach ($server_output->data as $variation) {
                            $mappedItems = [
                                'parent_sku_id' => $parent_sku_id,
                                'sku' => $variation->sku_id,
                                //'sku' => $variation->product_id,
                                'channel_sku' => $variation->sku,
                                // 'variation_id' => $variation->sku_id,
                                'variation_id' => $variation->id,
                                'name' => $record->name,
                                'ean' => $variation->upc, //$variation->mpn, $variation->gtin
                                'price' => $variation->calculated_price,
                                'stock_qty' => isset($variation->inventory_level) ? $variation->inventory_level : null,
                                'channel_id' => self::$current_channel->id,
                                'is_live' => isset($record->is_visible) ? $record->is_visible : "1",
                                'type1' => 'variation',
                            ];
                            //echo '```';print_r($new_item);die;

                           // self::save_channel_products((object)$mappedItems);
                            if(isset($response->meta->pagination->total))
                            {
                                self:: $products_fetched = self:: $products_fetched + 50; // for offset

                                if($response->meta->pagination->total > self:: $products_fetched)
                                {
                                    $lim=($response->meta->pagination->total - self:: $products_fetched);
                                    $lim= $lim > 50 ? 50:$lim;
                                    //self:: channelProducts(null,self:: $products_fetched ,$lim);
                                }
                                    echo $page = $response->meta->pagination->current_page;
                            }
                        }

                    }
                }
            }

I am looking forward for help with php? i am little confused how to set per page request in api, every time it fetches same records in api i want to make it as per pagination changes
</code>```

答:
you can send a key from url with get method ex: p=1
and replace this code : <code>$page  = 1;</code> with : </p>

```<code>$page = isset($_GET['p']) ? $_GET['p'] : 1;
</code>```

Title: Bigcommerce Pagination in php

Body:
i hope all are doing well, I am working on Bigcommerce API integration with PHP, as API fetches 50 records per page, but what i want is it starts fetching all records 50 and then from next page store it in an array and then that data should be dropped to the database, i am confused with how to pass current page id to the api

self::set_config($channel);
        $page  = 1;
        $url=self::$current_channel->api_url."v3/catalog/products?page=$page";
        $headers = self::getHeader($channel);
        $body = '';
        $response=self::make_api_request($url,$body,"GET",$headers);
//        echo "
";
//        print_r($response->meta->pagination->total);
//        echo "
";
//        exit;
        if(isset($response->data)) {
            foreach ($response->data as $item) {
                $record = self::get_product_detail($channel,$item->id); // get detail from api
                $record = isset($record->data[0]) ? $record->data[0] : NULL;
                if ($record)
                {
                    $mappedItems = [
                        'parent_sku_id' => null,
                        'sku' => $record->id,
                        'channel_sku' => $record->sku,
                        'variation_id' => $record->option_set_id,
                        'name' => $record->name,
                        'ean' => $record->upc, //$data->mpn, $data->gtin
                        'price' => $record->price,
                        'stock_qty' => isset($record->inventory_level) ? $record->inventory_level : null,
                        'channel_id' => self::$current_channel->id,
                        'is_live' => isset($record->is_visible) ? $record->is_visible : "1",
                        'type1' => 'main_product',
                    ];
                    $parent_sku_id = self::save_channel_products((object)$mappedItems); // will return product id from products table
                    $headers = self::getHeader($channel);

                    $url=self::$current_channel->api_url."v3/catalog/products/$item->id/variants";
                    $server_output = self::make_api_request($url,$body,"GET",$headers);

                    if ($parent_sku_id && isset($record->option_set_id)) {
                        foreach ($server_output->data as $variation) {
                            $mappedItems = [
                                'parent_sku_id' => $parent_sku_id,
                                'sku' => $variation->sku_id,
                                //'sku' => $variation->product_id,
                                'channel_sku' => $variation->sku,
                                // 'variation_id' => $variation->sku_id,
                                'variation_id' => $variation->id,
                                'name' => $record->name,
                                'ean' => $variation->upc, //$variation->mpn, $variation->gtin
                                'price' => $variation->calculated_price,
                                'stock_qty' => isset($variation->inventory_level) ? $variation->inventory_level : null,
                                'channel_id' => self::$current_channel->id,
                                'is_live' => isset($record->is_visible) ? $record->is_visible : "1",
                                'type1' => 'variation',
                            ];
                            //echo '
';print_r($new_item);die;

                           // self::save_channel_products((object)$mappedItems);
                            if(isset($response->meta->pagination->total))
                            {
                                self:: $products_fetched = self:: $products_fetched + 50; // for offset

                                if($response->meta->pagination->total > self:: $products_fetched)
                                {
                                    $lim=($response->meta->pagination->total - self:: $products_fetched);
                                    $lim= $lim > 50 ? 50:$lim;
                                    //self:: channelProducts(null,self:: $products_fetched ,$lim);
                                }
                                    echo $page = $response->meta->pagination->current_page;
                            }
                        }

                    }
                }
            }

I am looking forward for help with php? i am little confused how to set per page request in api, every time it fetches same records in api i want to make it as per pagination changes

Body:
you can send a key from url with get method ex: p=1
and replace this code : $page  = 1; with :

$page = isset($_GET['p']) ? $_GET['p'] : 1;


问:
How can I get data from a Select query as a String data type from a SQLite database?
I'm using this query:

```<code>string query = "SELECT CAST(FullName AS STRING) FROM Register WHERE ID = 1;

DataTable result = SQLiteDataAccess.MakeQuery(query);
</code>```

from this SQLite Table. I'm using System.Data and Dapper to access the SQLite database. The following code is used to access the database:

```<code>public static DataTable MakeQuery(string query)
{
            SQLiteDataReader result;
            DataTable datatable = new DataTable();

        using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            cnn.Open();

            SQLiteCommand command = new SQLiteCommand(query, cnn);
            result = command.ExecuteReader();
            datatable.Load(result);

            cnn.Close();
        }

        return datatable;
    }
</code>```

When I try to use the result, for example with this code:

```<code>        foreach (DataRow record in result.Rows)
        {
            names.Add((string)record["FullName"]);
        }
</code>```

I get the error "System.ArgumentException: 'Column 'FullName' does not belong to table .'" The following locals window screenshot shows that the name of the column is "CAST(FullName AS STRING)" and not "FullName", and the data type is int64, not string.

It seems that I'm using the wrong syntax for casting data types. It must be different in SQLite because it works in SQL Server. What's the correct query in SQLite? Thanks

Edit: Tried a suggestion in a comment and got this error showing the data type is still Int64.

答:
If you don't define the name of a requested column, your database has to go with some kind of default. Normally, this is the name of your column. If you start throwing functions around though, things get much more complicated for such an idea. After all, you could include two columns in the function.

Luckily this is very easily fixed using the AS keyword. Change your query to:

```<code>string query = "SELECT CAST(FullName AS TEXT) as FullName FROM Register WHERE ID = 1;
</code>```

Note: I chose to use FullName here, as you seem to want to. This is fine as long as you don't duplicate column names in the call.

I've also changed the STRING type to TEXT since that's sqlite3's actual type.

Body:
I'm using this query:

string query = "SELECT CAST(FullName AS STRING) FROM Register WHERE ID = 1;

DataTable result = SQLiteDataAccess.MakeQuery(query);

from this SQLite Table. I'm using System.Data and Dapper to access the SQLite database. The following code is used to access the database:

public static DataTable MakeQuery(string query)
{
            SQLiteDataReader result;
            DataTable datatable = new DataTable();

        using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            cnn.Open();

            SQLiteCommand command = new SQLiteCommand(query, cnn);
            result = command.ExecuteReader();
            datatable.Load(result);

            cnn.Close();
        }

        return datatable;
    }

When I try to use the result, for example with this code:

        foreach (DataRow record in result.Rows)
        {
            names.Add((string)record["FullName"]);
        }

I get the error "System.ArgumentException: 'Column 'FullName' does not belong to table .'" The following locals window screenshot shows that the name of the column is "CAST(FullName AS STRING)" and not "FullName", and the data type is int64, not string.

It seems that I'm using the wrong syntax for casting data types. It must be different in SQLite because it works in SQL Server. What's the correct query in SQLite? Thanks

Edit: Tried a suggestion in a comment and got this error showing the data type is still Int64.

Body:
If you don't define the name of a requested column, your database has to go with some kind of default. Normally, this is the name of your column. If you start throwing functions around though, things get much more complicated for such an idea. After all, you could include two columns in the function.

Luckily this is very easily fixed using the AS keyword. Change your query to:

string query = "SELECT CAST(FullName AS TEXT) as FullName FROM Register WHERE ID = 1;

Note: I chose to use FullName here, as you seem to want to. This is fine as long as you don't duplicate column names in the call.

I've also changed the STRING type to TEXT since that's sqlite3's actual type.


问:
What are some faster alternatives to Java2d?
I'm looking to do some physics simulations and I need fast rendering in Java.

I've run into performance issues with Java2d in the past, so what are the fast alternatives? Is JOGL significantly faster than Java2d?

答: I don't know - in the past I'd have said yes - especially if you use display lists rather than making lots of calls through the API each time the screen is displayed. But update 10 of the 1.6 JVM added accelerated Java2D graphics, so may have the advantage now.  Really the only way to know for sure is to try to render typical scenes in both and measure it.</p>

OwnerDisplayName: KingNestor

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

OwnerDisplayName: Pete Kirkham


答:
You can't really control user, but can prompt user again for wrong inputs. You can't also ask user to read real class objects, instead use a string to choose between them:</p>

```<code>coughing = Symptom("coughing", 5, 50, 10, 5)
weight_loss = Symptom("weight_loss", 10, 5, 50, 15)

symptom = ''
while symptom != 'coughing' and symptom != 'weight loss':
    symptom = input("which symptom do you choose? ") # player must choose between coughing and weight loss

symptom = coughing if symptom == 'coughing' else weight_loss
symptom.bought = True
</code>```

Title: How to use input to refrence a specific object

Body:
You can't really control user, but can prompt user again for wrong inputs. You can't also ask user to read real class objects, instead use a string to choose between them:

coughing = Symptom("coughing", 5, 50, 10, 5)
weight_loss = Symptom("weight_loss", 10, 5, 50, 15)

symptom = ''
while symptom != 'coughing' and symptom != 'weight loss':
    symptom = input("which symptom do you choose? ") # player must choose between coughing and weight loss

symptom = coughing if symptom == 'coughing' else weight_loss
symptom.bought = True