问:
Create (pandas / matplotlib) Chart For Each Change In First Column Value - Export All in One PDF
I have data that looks like this:

ID_Num
Date
Data_1
Data_2
Data_3

1
1/1/2021
75
49
98

1
1/3/2021
76
99
18

1
1/4/2021
64
54
71

1
1/5/2021
88
60
96

1
1/11/2021
8
40
33

1
1/12/2021
66
71
34

1
1/13/2021
15
49
100

2
1/1/2021
50
55
35

2
1/3/2021
14
10
26

2
1/4/2021
71
37
30

2
1/5/2021
41
36
92

3
1/1/2021
78
59
57

3
1/3/2021
28
58
51

I want to create a pdf report that has a generated line chart for each "ID_Num" with "Date" on the x axis and "Data_1,Data_2,Data_3" plotted on the y axis. I'd like the report to contain all the graphs in one document.

I'd also like the title of each chart to contain the "ID_Num" that's being plotted

This is where I'm at:

import os
import sqlalchemy
import pandas as pd
import matplotlib.pyplot as plt
#needed to see charts in dark theme
from matplotlib import style
style.use('dark_background')

#%% Get data
df = pd.read_excel('/home/james/git/JamesWork/Example_Data.xlsx')
print(df)
#%% Plots

#charttitle = df.ID_Num + ' - Chart'
plt.figure(figsize=(19,13))
#plt.title(charttitle, fontdict={'fontweight':'bold', 'fontsize':25})

plt.plot(df.Date, df.Data_1, 'g.-', label='Data1')
plt.plot(df.Date, df.Data_2, 'r.-', label='Data2')
plt.plot(df.Date, df.Data_3, 'b.-', label='Data3')

plt.xlabel('Year', fontdict={'fontsize':20})
plt.ylabel('Values', fontdict={'fontsize':20})
plt.ylim([0, None])
plt.legend(prop={'size':20})
plt.savefig('/home/james/git/JamesWork/Code_Exports/test.pdf', dpi = 300)
plt.show()
```
<hr />
<p>EDIT: I'm thinking 1.) delete every pdf in the folder 2.) loop though my data creating a pdf for every "ID_Num" 3.) Merge the PDFs together</p>
<p>I have 1 and 3 figured out:</p>
<p>#1:</p>
<pre class="lang-py prettyprint-override"><code>#%% Deletes Just PDFs
for parent, dirnames, filenames in os.walk('/home/james/git/JamesWork/Code_Modules/Example'):
    for fn in filenames:
        if fn.lower().endswith('.pdf'):
            os.remove(os.path.join(parent, fn))
</code>```

And #3:

#%% Combines PDFS
from PyPDF2 import PdfFileMerger
x = [a for a in os.listdir() if a.endswith(".pdf")]
merger = PdfFileMerger()
for pdf in x:
    merger.append(open(pdf, 'rb'))
with open("result.pdf", "wb") as fout:
    merger.write(fout)
```

答:
This does it all. Cheers:

import os
import sqlalchemy
import pandas as pd
import matplotlib.pyplot as plt
#needed to see charts in dark theme
from matplotlib import style
style.use('dark_background')
#%% Gets data
df = pd.read_excel('/home/james/git/JamesWork/Example_Data.xlsx')
print(df)

#%% Deletes Just PDFs
for parent, dirnames, filenames in os.walk('/home/james/git/JamesWork/Code_Modules/Example_ChartPuller_PDFMerge'):
    for fn in filenames:
        if fn.lower().endswith('.pdf'):
            os.remove(os.path.join(parent, fn))

#%% Find Unique Values
IDNumbers = df.ID_Num.unique()
print(IDNumbers)
#cycle though ID_Numbs and chart
for x in range(len(IDNumbers)):
    #filter df
    IDnumber = x+1
    print(IDnumber)
    rslt_df = df.loc[df['ID_Num'] == IDnumber]
    print(rslt_df)
    #plot new df
    #charttitle = rslt_df.ID_Num + ' - Chart'
    plt.figure(figsize=(19,13))
    #plt.title(charttitle, fontdict={'fontweight':'bold', 'fontsize':25})
    plt.plot(rslt_df.Date, rslt_df.Data_1, 'g.-', label='Data1')
    plt.plot(rslt_df.Date, rslt_df.Data_2, 'r.-', label='Data2')
    plt.plot(rslt_df.Date, rslt_df.Data_3, 'b.-', label='Data3')
    plt.xlabel('Year', fontdict={'fontsize':20})
    plt.ylabel('Values', fontdict={'fontsize':20})
    plt.ylim([0, None])
    plt.legend(prop={'size':20})
    path1 = '/home/james/git/JamesWork/Code_Modules/Example_ChartPuller_PDFMerge'
    filename1 = str(x)+'test.pdf'
    plt.savefig(os.path.join(path1,filename1), dpi = 300)
    #plt.show()

#%% Combines PDFS
from PyPDF2 import PdfFileMerger
x = [a for a in os.listdir() if a.endswith(".pdf")]
merger = PdfFileMerger()
for pdf in x:
    merger.append(open(pdf, 'rb'))
with open("newresult.pdf", "wb") as fout:
    merger.write(fout)
```

Body:
I have data that looks like this:

ID_Num
Date
Data_1
Data_2
Data_3

1
1/1/2021
75
49
98

1
1/3/2021
76
99
18

1
1/4/2021
64
54
71

1
1/5/2021
88
60
96

1
1/11/2021
8
40
33

1
1/12/2021
66
71
34

1
1/13/2021
15
49
100

2
1/1/2021
50
55
35

2
1/3/2021
14
10
26

2
1/4/2021
71
37
30

2
1/5/2021
41
36
92

3
1/1/2021
78
59
57

3
1/3/2021
28
58
51

I want to create a pdf report that has a generated line chart for each "ID_Num" with "Date" on the x axis and "Data_1,Data_2,Data_3" plotted on the y axis. I'd like the report to contain all the graphs in one document.

I'd also like the title of each chart to contain the "ID_Num" that's being plotted

This is where I'm at:

import os
import sqlalchemy
import pandas as pd
import matplotlib.pyplot as plt
#needed to see charts in dark theme
from matplotlib import style
style.use('dark_background')

#%% Get data
df = pd.read_excel('/home/james/git/JamesWork/Example_Data.xlsx')
print(df)
#%% Plots

#charttitle = df.ID_Num + ' - Chart'
plt.figure(figsize=(19,13))
#plt.title(charttitle, fontdict={'fontweight':'bold', 'fontsize':25})

plt.plot(df.Date, df.Data_1, 'g.-', label='Data1')
plt.plot(df.Date, df.Data_2, 'r.-', label='Data2')
plt.plot(df.Date, df.Data_3, 'b.-', label='Data3')

plt.xlabel('Year', fontdict={'fontsize':20})
plt.ylabel('Values', fontdict={'fontsize':20})
plt.ylim([0, None])
plt.legend(prop={'size':20})
plt.savefig('/home/james/git/JamesWork/Code_Exports/test.pdf', dpi = 300)
plt.show()

EDIT: I'm thinking 1.) delete every pdf in the folder 2.) loop though my data creating a pdf for every "ID_Num" 3.) Merge the PDFs together

I have 1 and 3 figured out:

#1:

#%% Deletes Just PDFs
for parent, dirnames, filenames in os.walk('/home/james/git/JamesWork/Code_Modules/Example'):
    for fn in filenames:
        if fn.lower().endswith('.pdf'):
            os.remove(os.path.join(parent, fn))

And #3:

#%% Combines PDFS
from PyPDF2 import PdfFileMerger
x = [a for a in os.listdir() if a.endswith(".pdf")]
merger = PdfFileMerger()
for pdf in x:
    merger.append(open(pdf, 'rb'))
with open("result.pdf", "wb") as fout:
    merger.write(fout)


来源: stackexchange

问:
jq: convert milliseconds to date
I need to convert seconds to date:

My input documents are:

```<code>{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":{"value":{"$date":{"$numberLong":"-469929600000"}}}}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":{"value":{"$date":{"$numberLong":"-854755200000"}}}}
</code>```

I need to get:

```<code>{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}
</code>```

Any ideas?

答:
Grab the source value, chop off the last three digits to turn the number into seconds and call todate to convert it into a date string (GMT).

jq -c '.birthDate |= (.value."$date"."$numberLong"[:-3] | tonumber | todate[:10])'
```
<pre class="lang-json prettyprint-override"><code>{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}
</code>```

Demo

ContentLicense: CC BY-SA 4.0

Title: jq: convert milliseconds to date

Body:
I need to convert seconds to date:

My input documents are:

{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":{"value":{"$date":{"$numberLong":"-469929600000"}}}}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":{"value":{"$date":{"$numberLong":"-854755200000"}}}}

I need to get:

{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}

Any ideas?

Body:
Grab the source value, chop off the last three digits to turn the number into seconds and call todate to convert it into a date string (GMT).

jq -c '.birthDate |= (.value."$date"."$numberLong"[:-3] | tonumber | todate[:10])'

{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}

Demo


问:
Doubt about validation in WinForm application
I'm creating my first application in WindowsForms and wondered how I would do to validate the User input logic layer and return to the textbox control such that he filled out incorrectly by ErrorProvider. That is, each would have to return the validation error for each specific control indicating whether the user typed an invalid value.

This is a good practice?

Today, this validation is done on the presentation layer and would like to use my more logical layer so that she is not only acting as an intermediary between the presentation and data access.

答:
If you would like to maintain separation of concerns you should look into implementing the model-view-controller design pattern.  This will allow you to keep you UI code cleaner

Overview of MVC

Model

Contains state and implementation

Notifies listeners (views) of changes

View

Displays model state (and responds to model state notifications)

Send all user input to the controller

Controller

Processes all input from the view

Changes model state and calls model methods

Load a different view as needed

Further Reading

http://www.martinfowler.com/eaaDev/uiArchs.html

http://en.wikipedia.org/wiki/Model-view-controller

ContentLicense: CC BY-SA 3.0


问:
"Cannot read property 'flags' of undefined" with custom-webpack and istanbul-instrumenter-loader
My goal is to get dynamic code coverage of Protractor (v 7) E2E tests within Angular 12.

I'm following this thread:
Code coverage for Protractor tests in Angular 5 Application

It is said, that https://www.npmjs.com/package/protractor-istanbul-plugin would not work with Angular 12, so I'm trying customWebpackConfig & istanbul-instrumenter-loader, but am stuck with the following error, when trying to build the project.
I realy struggle with setting up things like this, so any help would be greatly appreciated!!

Errormessage

ng build

```<code>Generating browser application bundles (phase: setup)...
An error occurred during the build:
TypeError: Cannot read property 'flags' of undefined
    at checkUnreachable (myprojectpath\node_modules\typescript\lib\typescript.js:43458:31)
    at bindChildren (myprojectpath\node_modules\typescript\lib\typescript.js:40978:17)
    at bind (myprojectpath\node_modules\typescript\lib\typescript.js:42548:21)
    at bindSourceFile (myprojectpath\node_modules\typescript\lib\typescript.js:40523:17)
    at Object.bindSourceFile (myprojectpath\node_modules\typescript\lib\typescript.js:40460:9)
    at initializeTypeChecker (myprojectpath\node_modules\typescript\lib\typescript.js:79672:20)
    at Object.createTypeChecker (myprojectpath\node_modules\typescript\lib\typescript.js:44614:9)
    at Object.getTypeChecker (myprojectpath\node_modules\typescript\lib\typescript.js:107350:79)
    at new NgCompiler (myprojectpath\node_modules\@angular\compiler-cli\src\ngtsc\core\src\compiler.js:199:99)
    at Function.NgCompiler.fromTicket (myprojectpath\node_modules\@angular\compiler-cli\src\ngtsc\core\src\compiler.js:238:28)
    at new NgtscProgram (myprojectpath\node_modules\@angular\compiler-cli\src\ngtsc\program.js:95:47)
    at AngularWebpackPlugin.updateAotProgram (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\@ngtools\webpack\src\ivy\plugin.js:310:32)
    at myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\@ngtools\webpack\src\ivy\plugin.js:187:24
    at Hook.eval [as call] (eval at create (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:24:1)
    at Hook.CALL_DELEGATE [as _call] (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\webpack\lib\Compiler.js:1043:30)
An unhandled exception occurred: Cannot read property 'flags' of undefined
</code>```

My configuration

myprojectpath\package.json

```<code>"devDependencies": {
    "@angular-builders/custom-webpack": "^12.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular/cli": "~12.0.5",
    "@angular/compiler-cli": "~12.0.5",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^12.11.1",
    "browserify-istanbul": "^3.0.1",
    "istanbul-instrumenter-loader": "^3.0.1",
    "jasmine-core": "~3.7.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.6.0",
    "typescript": "~4.2.3"
  }
</code>```

myprojectpath\angular.json

```<code>     "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            ...
            "customWebpackConfig": {"path": "./custom-webpack.config.js"}
          },
</code>```

myprojectpath\custom-webpack.config.js

```<code>const path = require("path");

module.exports = {
  module: {
    rules: [
      {
          test: /\.js$/, //TODO: should this point to the test subdir? Problem: unexpected token when trying to add the slash for the dir
          use: {
            loader: 'istanbul-instrumenter-loader',
            options: {
                //
            }
          }
      }
    ]
  }
};
</code>```

myprojectpath\test\conf.js

```<code>exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['todo-spec.js']
};
</code>```

myprojectpath\test\todo-spec.js

```<code>describe('demo test', function() {
  it('describtion', function() {
    browser.get('http://localhost:4200/');

    expect(...);
  });
});
</code>```

Next steps according to the original thread would be

Run your e2e/IT test suit on the instrumented bundle

```<code>webdriver-manager start
test\protractor conf.js
</code>```

Collect your istanbul coverage(window.__ coverage__) json from browser context & save it as coverage.json file. Genarate viewable
report using istanbul comments istanbul report(istanbul should be
installed globally),It will generate coverage/lcov-report folder with
html files to view the code coverage report for each files.

答:
I now are able to build the solution. My packages.json now looks like this:

```<code>  "devDependencies": {
    "@angular-builders/custom-webpack": "^12.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular-devkit/build-angular": "~12.2.16",
    "@angular/cli": "~12.2.16",
    "@angular/compiler-cli": "~12.2.0",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^12.11.1",
    "istanbul-instrumenter-loader": "^3.0.1",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "protractor": "~7.0.0",
    "typescript": "~4.3.5"
  }
</code>```

I also had to increase the budget size within the angular.json and had to dig into the source code of the istanbul-instrumenter-loader to allow for import and exports being defined anywhere:

\node_modules\istanbul-instrumenter-loader\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121

```<code>   var ast = babylon.parse(code, {
        allowReturnOutsideFunction: opts.autoWrap, allowImportExportEverywhere: true, //CUSTOM EDIT: added allowImportExportEverywhere here
        sourceType: opts.esModules ? "module" : "script",
        plugins: ['asyncGenerators', 'dynamicImport', 'objectRestSpread', 'flow', 'jsx']
    });
</code>```

Body:
My goal is to get dynamic code coverage of Protractor (v 7) E2E tests within Angular 12.

I'm following this thread:
Code coverage for Protractor tests in Angular 5 Application

It is said, that https://www.npmjs.com/package/protractor-istanbul-plugin would not work with Angular 12, so I'm trying customWebpackConfig & istanbul-instrumenter-loader, but am stuck with the following error, when trying to build the project.
I realy struggle with setting up things like this, so any help would be greatly appreciated!!

Errormessage

ng build

Generating browser application bundles (phase: setup)...
An error occurred during the build:
TypeError: Cannot read property 'flags' of undefined
    at checkUnreachable (myprojectpath\node_modules\typescript\lib\typescript.js:43458:31)
    at bindChildren (myprojectpath\node_modules\typescript\lib\typescript.js:40978:17)
    at bind (myprojectpath\node_modules\typescript\lib\typescript.js:42548:21)
    at bindSourceFile (myprojectpath\node_modules\typescript\lib\typescript.js:40523:17)
    at Object.bindSourceFile (myprojectpath\node_modules\typescript\lib\typescript.js:40460:9)
    at initializeTypeChecker (myprojectpath\node_modules\typescript\lib\typescript.js:79672:20)
    at Object.createTypeChecker (myprojectpath\node_modules\typescript\lib\typescript.js:44614:9)
    at Object.getTypeChecker (myprojectpath\node_modules\typescript\lib\typescript.js:107350:79)
    at new NgCompiler (myprojectpath\node_modules\@angular\compiler-cli\src\ngtsc\core\src\compiler.js:199:99)
    at Function.NgCompiler.fromTicket (myprojectpath\node_modules\@angular\compiler-cli\src\ngtsc\core\src\compiler.js:238:28)
    at new NgtscProgram (myprojectpath\node_modules\@angular\compiler-cli\src\ngtsc\program.js:95:47)
    at AngularWebpackPlugin.updateAotProgram (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\@ngtools\webpack\src\ivy\plugin.js:310:32)
    at myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\@ngtools\webpack\src\ivy\plugin.js:187:24
    at Hook.eval [as call] (eval at create (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:24:1)
    at Hook.CALL_DELEGATE [as _call] (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation (myprojectpath\node_modules\@angular-builders\custom-webpack\node_modules\webpack\lib\Compiler.js:1043:30)
An unhandled exception occurred: Cannot read property 'flags' of undefined

My configuration

myprojectpath\package.json

"devDependencies": {
    "@angular-builders/custom-webpack": "^12.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular/cli": "~12.0.5",
    "@angular/compiler-cli": "~12.0.5",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^12.11.1",
    "browserify-istanbul": "^3.0.1",
    "istanbul-instrumenter-loader": "^3.0.1",
    "jasmine-core": "~3.7.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.6.0",
    "typescript": "~4.2.3"
  }

myprojectpath\angular.json

     "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            ...
            "customWebpackConfig": {"path": "./custom-webpack.config.js"}
          },

myprojectpath\custom-webpack.config.js

const path = require("path");

module.exports = {
  module: {
    rules: [
      {
          test: /\.js$/, //TODO: should this point to the test subdir? Problem: unexpected token when trying to add the slash for the dir
          use: {
            loader: 'istanbul-instrumenter-loader',
            options: {
                //
            }
          }
      }
    ]
  }
};

myprojectpath\test\conf.js

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['todo-spec.js']
};

myprojectpath\test\todo-spec.js

describe('demo test', function() {
  it('describtion', function() {
    browser.get('http://localhost:4200/');

    expect(...);
  });
});

Next steps according to the original thread would be

Run your e2e/IT test suit on the instrumented bundle

webdriver-manager start
test\protractor conf.js

Collect your istanbul coverage(window.__ coverage__) json from browser context & save it as coverage.json file. Genarate viewable
report using istanbul comments istanbul report(istanbul should be
installed globally),It will generate coverage/lcov-report folder with
html files to view the code coverage report for each files.

Body:
I now are able to build the solution. My packages.json now looks like this:

  "devDependencies": {
    "@angular-builders/custom-webpack": "^12.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular-devkit/build-angular": "~12.2.16",
    "@angular/cli": "~12.2.16",
    "@angular/compiler-cli": "~12.2.0",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^12.11.1",
    "istanbul-instrumenter-loader": "^3.0.1",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "protractor": "~7.0.0",
    "typescript": "~4.3.5"
  }

I also had to increase the budget size within the angular.json and had to dig into the source code of the istanbul-instrumenter-loader to allow for import and exports being defined anywhere:

\node_modules\istanbul-instrumenter-loader\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121

   var ast = babylon.parse(code, {
        allowReturnOutsideFunction: opts.autoWrap, allowImportExportEverywhere: true, //CUSTOM EDIT: added allowImportExportEverywhere here
        sourceType: opts.esModules ? "module" : "script",
        plugins: ['asyncGenerators', 'dynamicImport', 'objectRestSpread', 'flow', 'jsx']
    });


问:
Get parent directory of path in Elisp
I'm trying to find the parent directory of a user-given string str to check if it exists. I can find this easily with (file-name-directory str). My issue is I also want to get the parent directory if they pass something with a trailing slash, like "~/Projects/newdir/" would hopefully get "~/Projects/" spit out instead of "~/Projects/newdir/". I can't seem to find anything like this inside the Emacs documentation.

答:
I believe you are looking for directory-file-name:

```<code>(file-name-directory "/usr/bin/cc")
==> "/usr/bin/"
(directory-file-name (file-name-directory "/usr/bin/cc"))
==> "/usr/bin"
(file-name-directory (directory-file-name (file-name-directory "/usr/bin/cc")))
==> "/usr/"
(directory-file-name (file-name-directory (directory-file-name (file-name-directory "/usr/bin/cc"))))
==> "/usr"
</code>```

and file-exists-p:

```<code>(file-exists-p "/usr/bin/cc")
==> t
(file-exists-p "/usr/bin/")
==> t
(file-exists-p "/usr/bin")
==> t
(file-exists-p "/usr/bin/no such file")
==> nil
</code>```

See also

Walk up the directory tree

Function that returns parent directory absolute path

Distinguishing Kinds of Files

Title: Get parent directory of path in Elisp

Body:
I believe you are looking for directory-file-name:

(file-name-directory "/usr/bin/cc")
==> "/usr/bin/"
(directory-file-name (file-name-directory "/usr/bin/cc"))
==> "/usr/bin"
(file-name-directory (directory-file-name (file-name-directory "/usr/bin/cc")))
==> "/usr/"
(directory-file-name (file-name-directory (directory-file-name (file-name-directory "/usr/bin/cc"))))
==> "/usr"

and file-exists-p:

(file-exists-p "/usr/bin/cc")
==> t
(file-exists-p "/usr/bin/")
==> t
(file-exists-p "/usr/bin")
==> t
(file-exists-p "/usr/bin/no such file")
==> nil

See also

Walk up the directory tree

Function that returns parent directory absolute path

Distinguishing Kinds of Files


问:
How to show raspberrypi sensor data in react using nodejs and socketio
I want to display some sensors data from raspberry pi (using python socketio) in react as frontend and I am using nodejs as backend. Data is currently displaying in the console (nodejs) but I can't seem to figure out how it will displayed in react. Sorry for this basic question but I can't seem to find a reasonable way to implement this. Here are my codes for raspberry pi, node and react.

```<code>#raspberrypi code
import asyncio
import socketio

sio = socketio.AsyncClient()

@sio.event
async def connect():
    print('connection established')

@sio.event
async def message(data):
    print('message received with ', data)
    await sio.emit('fromAPI', {'msgFromPy': 'my response'})

@sio.event
async def disconnect():
    print('disconnected from server')

async def main():
    await sio.connect('http://localhost:5000')
    await sio.wait()

if __name__ == '__main__':
    asyncio.run(main())
</code>```

Nodejs code

```<code>const io = require("socket.io")(5000);

io.on("connection", socket => {
  // either with send()
  console.log('Connected');
  socket.send("Hello!");

  // handle the event sent with socket.send()
  socket.on("fromAPI", (data) => {
    console.log(data);
    socket.emit("fromAPI", data);

  });

     });
});
</code>```

Following is react code

```<code>import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:5000";

function App() {

  const [response, setResponse] = useState("");

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("fromAPI", data => {
      setResponse(data);
    });
  }, []);

  return (
    <p>
      It's {response.msgFromPy}
    </p>
  );

}

export default App;
</code>```

What should I do so that data from the node can be displayed in react. I am not getting any error in react as well. Thanks for helping

答:
I solve this whole thing using websockets. Made two nodejs websocket servers. One is connected with raspberry pi via port 5000 and other is connected to react via port 4001. Code for raspberrypi python, nodejs server and react client is given below.
rpi code:

```<code>import asyncio
import socketio
import random
import time

sio = socketio.AsyncClient()

@sio.event
async def connect():
    print('connection established')

@sio.event
async def message(data):
    print('message received with ', data)
    while True:
        await sio.emit('fromAPI', {"id": 1, "Temprature" : random.randint(0,9), "Humidity": random.randint(0,9)})
        await sio.sleep(3)

@sio.on('my_message')
async def on_message(data):
    #while True:
    print('I received a message!', data)
    await sio.sleep(1)

@sio.event
async def disconnect():
    print('disconnected from server')

async def main():
    await sio.connect('http://localhost:5000')
    await sio.wait()
    loop = asyncio.get_event_loop()
    try:
        asyncio.ensure_future(message(data))
        asyncio.ensure_future(on_message(data))
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        print("closing thread")
        loop.close()

if __name__ == '__main__':
    asyncio.run(main())
</code>```

nodejs code:

```<code>const io = require("socket.io")(5000);
const io1 = require("socket.io")(4001);

let interval;
let dataFromReact;

io.on("connection", (socket) => {
  io1.on("connection", (socket1) => {
    socket1.on("rcvdFromReact", data1 => {
      dataFromReact = data1;
      socket.emit("my_message", data1);
    });
  });
});

io.on("connection", socket => {
  socket.send("hello");
  io1.on("connection", socket1 => {
  // either with send()
  console.log('Connected');
  socket.on("fromAPI", (data) => {
    console.log(data);
   socket1.emit("fromNodejs", data);

  });
 });
});
</code>```

react code (App.js):

```<code>import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:4001";

function App() {

  const [response, setResponse] = useState("");
  const [title, setTitle] = useState('')

  const handleSubmit = (e) => {
    e.preventDefault();
    var temps = e.target.temp.value;
    var humids = e.target.humid.value;
    console.log(temps + humids);
    setTitle(temps);
    const socket = socketIOClient(ENDPOINT);
    socket.emit("rcvdFromReact", temps);
    console.log("Temprature is " + temps);
  }

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("fromNodejs", data => {
      setResponse(data);
      console.log(data);
      //console.log("Temprature is " + temps);
    });
  }, []);

  return (
    <div>
    <p>
      It's {response.Temprature} and {response.Humidity}
    </p>
    <form onSubmit={handleSubmit}>
    <input placeholder = "Temprature" name = "temp"  />
    <input placeholder = "Humidity" name = "humid"  />
    <button>Click Me</button>
    </form>
    </div>
  );

}

export default App;
</code>```

Body:
I want to display some sensors data from raspberry pi (using python socketio) in react as frontend and I am using nodejs as backend. Data is currently displaying in the console (nodejs) but I can't seem to figure out how it will displayed in react. Sorry for this basic question but I can't seem to find a reasonable way to implement this. Here are my codes for raspberry pi, node and react.

#raspberrypi code
import asyncio
import socketio

sio = socketio.AsyncClient()

@sio.event
async def connect():
    print('connection established')

@sio.event
async def message(data):
    print('message received with ', data)
    await sio.emit('fromAPI', {'msgFromPy': 'my response'})

@sio.event
async def disconnect():
    print('disconnected from server')

async def main():
    await sio.connect('http://localhost:5000')
    await sio.wait()

if __name__ == '__main__':
    asyncio.run(main())

Nodejs code

const io = require("socket.io")(5000);

io.on("connection", socket => {
  // either with send()
  console.log('Connected');
  socket.send("Hello!");

  // handle the event sent with socket.send()
  socket.on("fromAPI", (data) => {
    console.log(data);
    socket.emit("fromAPI", data);

  });

     });
});

Following is react code

import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:5000";

function App() {

  const [response, setResponse] = useState("");

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("fromAPI", data => {
      setResponse(data);
    });
  }, []);

  return (

      It's {response.msgFromPy}

  );

}

export default App;

What should I do so that data from the node can be displayed in react. I am not getting any error in react as well. Thanks for helping

Body:
I solve this whole thing using websockets. Made two nodejs websocket servers. One is connected with raspberry pi via port 5000 and other is connected to react via port 4001. Code for raspberrypi python, nodejs server and react client is given below.
rpi code:

import asyncio
import socketio
import random
import time

sio = socketio.AsyncClient()

@sio.event
async def connect():
    print('connection established')

@sio.event
async def message(data):
    print('message received with ', data)
    while True:
        await sio.emit('fromAPI', {"id": 1, "Temprature" : random.randint(0,9), "Humidity": random.randint(0,9)})
        await sio.sleep(3)

@sio.on('my_message')
async def on_message(data):
    #while True:
    print('I received a message!', data)
    await sio.sleep(1)

@sio.event
async def disconnect():
    print('disconnected from server')

async def main():
    await sio.connect('http://localhost:5000')
    await sio.wait()
    loop = asyncio.get_event_loop()
    try:
        asyncio.ensure_future(message(data))
        asyncio.ensure_future(on_message(data))
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        print("closing thread")
        loop.close()

if __name__ == '__main__':
    asyncio.run(main())

nodejs code:

const io = require("socket.io")(5000);
const io1 = require("socket.io")(4001);

let interval;
let dataFromReact;

io.on("connection", (socket) => {
  io1.on("connection", (socket1) => {
    socket1.on("rcvdFromReact", data1 => {
      dataFromReact = data1;
      socket.emit("my_message", data1);
    });
  });
});

io.on("connection", socket => {
  socket.send("hello");
  io1.on("connection", socket1 => {
  // either with send()
  console.log('Connected');
  socket.on("fromAPI", (data) => {
    console.log(data);
   socket1.emit("fromNodejs", data);

  });
 });
});

react code (App.js):

import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:4001";

function App() {

  const [response, setResponse] = useState("");
  const [title, setTitle] = useState('')

  const handleSubmit = (e) => {
    e.preventDefault();
    var temps = e.target.temp.value;
    var humids = e.target.humid.value;
    console.log(temps + humids);
    setTitle(temps);
    const socket = socketIOClient(ENDPOINT);
    socket.emit("rcvdFromReact", temps);
    console.log("Temprature is " + temps);
  }

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.on("fromNodejs", data => {
      setResponse(data);
      console.log(data);
      //console.log("Temprature is " + temps);
    });
  }, []);

  return (
    <div>
    <p>
      It's {response.Temprature} and {response.Humidity}
    </p>
    <form onSubmit={handleSubmit}>
    <input placeholder = "Temprature" name = "temp"  />
    <input placeholder = "Humidity" name = "humid"  />
    <button>Click Me</button>
    </form>
    </div>
  );

}

export default App;


问:
AppleTalk framework not found
I have a library which was Building perfectly fine in MacOSX10.10 XCode5.0.2 I was using Base SDK 10.8 and deployment target 10.6. now I have to ported that solution to MacOSX10.11 and Deployment target 10.9 in Xcode 7.2. one of my target has dependency on AppleTalk framework, when I tried to Build it It started giving error AppleTalk Framework not found I looked in SDKs folder APPleTalk Framework was not there in case of SDK10.11, but it was there in case of SDK10.8.

Is there any way i can get AppleTalk framework on MacOSX10.11 as I have read somewhere that AppleTalk is no longer Part of Framework.

答:
From: https://en.wikipedia.org/wiki/AppleTalk

With the purchase of NeXT and subsequent development of Mac OS X,
AppleTalk was strictly a legacy system. Support was added to OS X in
order to provide support for the large number of existing AppleTalk
devices, notably laser printers and file shares, but alternate
connection solutions common in this era, notably USB for printers,
limited their demand. As Apple abandoned many of these product
categories, and all new systems were based on IP, AppleTalk became
less and less common. AppleTalk support was finally removed from the
MacOS in Mac OS X v10.6 in 2009.[32]

Title: AppleTalk framework not found


问:
Left and right padding (not leading and trailing) in SwiftUI
A padding modifier in SwiftUI takes an EdgeInsets, eg

.padding(.leading, 8)

However, there are only leading and trailing EdgeInsets, and not left and right. This presents a problem because not everything in RTL languages should necessarily be reversed from the way it's displayed in LTR languages.

Is there a way to achieve the same or similar effect as the padding modifier, which forces the padding to be on left or right side, regardless of directionality of the language?

答:
For me it was</p>
```<code>VStack(alignment: .center) {
                    Text("Car")
                        .font(.body)
                        .foregroundColor(.black)
                }
                .padding(.trailing, 5)
</code>```

Body:
For me it was

VStack(alignment: .center) {
                    Text("Car")
                        .font(.body)
                        .foregroundColor(.black)
                }
                .padding(.trailing, 5)


问:
Julia Markdown - Chunk Output as Markdown
I would like to print a table in Julia Markdown. To the best of my knowledge there is no cool package, yet, that is doing this. Hence, I would like to create a nice looking table through code, but I can't figure out how.

This is my table code...

```<code>---
title: Just a test
author: Me
date: 2022-01-03
output: pdf_document
---

```julia
"""
| Column One | Column Two | Column Three |
|:---------- | ---------- |:------------:|
| Row `1`    | Column `2` |              |
| *Row* 2    | **Row** 2  | Column ``3`` |
"""
```
</code>```

...and I want it to produce this...

...instead of this:

答:
The Markdown standard library can parse tables too:

```<code>julia> tbl = """
       | Column One | Column Two | Column Three |
       |:---------- | ---------- |:------------:|
       | Row `1`    | Column `2` |              |
       | *Row* 2    | **Row** 2  | Column ``3`` |
       """
julia> md = Markdown.parse(tbl);

julia> # text formatting like emphasis and bold are lost in pasting
       # to StackOverflow, but shown in the original output
       md

  Column One Column Two Column Three
  –––––––––– –––––––––– ––––––––––––
  Row 1        Column 2
  Row 2           Row 2   Column 3

</code>```

The parse output is a Markdown.MD object that is rendered appropriately depending on your output display (i.e. terminal, Jupyter, etc).

If you want to produce a markdown table directly from data (without parsing it from a string), you can also construct a Markdown.Table directly; check the varinfo() function from the InteractiveUtils standard library for an example of that.

Body:
I would like to print a table in Julia Markdown. To the best of my knowledge there is no cool package, yet, that is doing this. Hence, I would like to create a nice looking table through code, but I can't figure out how.

This is my table code...

---
title: Just a test
author: Me
date: 2022-01-03
output: pdf_document
---

```julia
"""
| Column One | Column Two | Column Three |
|:---------- | ---------- |:------------:|
| Row `1`    | Column `2` |              |
| *Row* 2    | **Row** 2  | Column ``3`` |
"""
```

...and I want it to produce this...

...instead of this:

Body:
The Markdown standard library can parse tables too:

julia> tbl = """
       | Column One | Column Two | Column Three |
       |:---------- | ---------- |:------------:|
       | Row `1`    | Column `2` |              |
       | *Row* 2    | **Row** 2  | Column ``3`` |
       """
julia> md = Markdown.parse(tbl);

julia> # text formatting like emphasis and bold are lost in pasting
       # to StackOverflow, but shown in the original output
       md

  Column One Column Two Column Three
  –––––––––– –––––––––– ––––––––––––
  Row 1        Column 2
  Row 2           Row 2   Column 3

The parse output is a Markdown.MD object that is rendered appropriately depending on your output display (i.e. terminal, Jupyter, etc).

If you want to produce a markdown table directly from data (without parsing it from a string), you can also construct a Markdown.Table directly; check the varinfo() function from the InteractiveUtils standard library for an example of that.


问:
Yappi ModuleNotFoundError even after installation
I have installed yappi successfully but still I'm getting ModuleNotFoundError while importing yappi in the same shell:

```<code>((python) ) soumeng78@linux-16 $ pipenv install  git+https://github.com/sumerc/yappi#egg=yappi
Installing git+https://github.com/sumerc/yappi#egg=yappi...
Adding yappi to Pipfile's [packages]...
âœ” Installation Succeeded
Pipfile.lock (db4242) out of date, updating to (b482eb)...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
âœ” Success!
Updated Pipfile.lock (b482eb)!
Installing dependencies from Pipfile.lock (b482eb)...
  ðŸ   â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰ 0/0 â€” 00:00:00

((python) ) soumeng78@linux-16 $ python
Python 3.9.6 (default, Jan  4 2022, 00:31:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yappi

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
<stdin> 1 <module>
1

ModuleNotFoundError:
No module named 'yappi'
</code>```

Any idea how to make it work? I want to use yappi for profiling a function.

答:
Removing the old environment and recreating the environment solved the problem. It seems like some issue with pipenv.

When I tried same pip install in conda virtual environment on Windows, I get below issue - seems some issue with the package:

```<code>Collecting yappi
  Using cached yappi-1.3.3.tar.gz (58 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: yappi
  Building wheel for yappi (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [9 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-3.8
      copying yappi\yappi.py -> build\lib.win-amd64-3.8
      running build_ext
      building '_yappi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for yappi
  Running setup.py clean for yappi
Failed to build yappi
Installing collected packages: yappi
  Running setup.py install for yappi ... error
  error: subprocess-exited-with-error

  × Running setup.py install for yappi did not run successfully.
  │ exit code: 1
  ╰─> [11 lines of output]
      running install
      C:\Users\soumen\Miniconda3\envs\kubeflow-pipeline\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-3.8
      copying yappi\yappi.py -> build\lib.win-amd64-3.8
      running build_ext
      building '_yappi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> yappi
</code>```

Body:
I have installed yappi successfully but still I'm getting ModuleNotFoundError while importing yappi in the same shell:

((python) ) soumeng78@linux-16 $ pipenv install  git+https://github.com/sumerc/yappi#egg=yappi
Installing git+https://github.com/sumerc/yappi#egg=yappi...
Adding yappi to Pipfile's [packages]...
âœ” Installation Succeeded
Pipfile.lock (db4242) out of date, updating to (b482eb)...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
âœ” Success!
Updated Pipfile.lock (b482eb)!
Installing dependencies from Pipfile.lock (b482eb)...
  ðŸ   â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰â–‰ 0/0 â€” 00:00:00

((python) ) soumeng78@linux-16 $ python
Python 3.9.6 (default, Jan  4 2022, 00:31:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yappi

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
<stdin> 1 <module>
1

ModuleNotFoundError:
No module named 'yappi'

Any idea how to make it work? I want to use yappi for profiling a function.

Body:
Removing the old environment and recreating the environment solved the problem. It seems like some issue with pipenv.

When I tried same pip install in conda virtual environment on Windows, I get below issue - seems some issue with the package:

Collecting yappi
  Using cached yappi-1.3.3.tar.gz (58 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: yappi
  Building wheel for yappi (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [9 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-3.8
      copying yappi\yappi.py -> build\lib.win-amd64-3.8
      running build_ext
      building '_yappi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for yappi
  Running setup.py clean for yappi
Failed to build yappi
Installing collected packages: yappi
  Running setup.py install for yappi ... error
  error: subprocess-exited-with-error

  × Running setup.py install for yappi did not run successfully.
  │ exit code: 1
  ╰─> [11 lines of output]
      running install
      C:\Users\soumen\Miniconda3\envs\kubeflow-pipeline\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-3.8
      copying yappi\yappi.py -> build\lib.win-amd64-3.8
      running build_ext
      building '_yappi' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> yappi


问:
SSL with no-ip and XAMPP Apache server
I am working on a web page, and so that the clients could test it I mounted it on an apache server with xampp (windows). Also, I changed the ip to a domain at www.no-ip.com and now it looks something like "example.ddns.net". The problem I have now is that I want to install an SSL certificate so that the non-secure page message won't appear, but I can't do it. I tried using https://zerossl.com/ which creates 3 files: "private.key", "certificate.crt" and "ca_bundle.crt". I have tried all the tutorials on the internet, seen all the videos on youtube but I can't find the solution. Can someone help me? Thanks!</p>

答:
They have actually added earlier this year free SSL certificate for their dynamic domains.

SSL Certificates

Check the following links for details on how to generate them.

First generate the CSR file
https://www.noip.com/support/knowledgebase/apache-openssl/

Then, follow the "second part" of the guide where you will add the CSR content to you domain in order for the SSL certificate to be generated.
https://www.noip.com/support/knowledgebase/get-trustcor-premium-dv-ssl/

The last part is to install the certificate to Apache. The installation is pretty much the same with all other SSL certificates (https://www.namecheap.com/support/knowledgebase/article.aspx/10026/33/installing-an-ssl-certificate-on-xampp/).

Title: SSL with no-ip and XAMPP Apache server


问:
Regex matches on exclusion/inclusion of a word with various possessiveness then a key word

I want to look for various types of matches on the word "car" but not if its preceded by "Jane, Jane's, Janes, and Jane(s).

the following 2 regex partially work for exclusion and inclusion, but I can't get the other variants to work

(?<!\bJane) car

Jane car

for example

the car is red  - Match

here is Jane car is red  -> None

here is Janes car is red  -> None

here is Jane's car is red  -> None

I also want to find the cases Jane is in the phrase

the car is red  - None

here is Jane car is red  - Match

here is Janes car is red  - Match

here is Jane's car is red  - Match

and where car is not preceding by Jane(s)

here Jane(s) car is red  - None

and of course the opposite

here is Jane(s) car is red  - Match

Edit

If I have a document with "red car\n and Janes car"  this should be a Match as there is a reference to "car" without the word Jane/Janes/Jane's/etc. in front of it.

In fact, for additional clarity.  I will be doing a re.Findall for all the occurrences of "car" without the word Jane in front of them.

答:
If you want to match it where the different forms of Jane should not occur, you can exclude the match with a negative lookahead, and then still match car

```<code>^(?!.*\bJane(?:'?s|\(s\))? car\b).*\bcar\b.*
</code>```

^ Start of string

(?! Negative lookahead

.*\bJane(?:'?s|\(s\))? Match Jane Janes Jane's Jane(s)

 car\b Match a space and the word car

) Close the lookahead

.*\bcar\b.* Match the whole line with the word car between word boundaries

Regex demo

If the different forms of Jane followed by car should be there, you can match it:

```<code>^.*\bJane(?:'?s|\(s\))? car\b.*
</code>```

Regex demo

To matching all occurrences of car without the ones that have Jane in front of it, you can match what you don't want to keep and capture what you do want to keep.

Then in Python you can use re.findall which will return the capture group values and remove the empty entries from the result.

```<code>\bJane(?:'?s|\(s\))? car\b|\b(car)\b
</code>```

Regex demo | Python demo

Body:
If you want to match it where the different forms of Jane should not occur, you can exclude the match with a negative lookahead, and then still match car

^(?!.*\bJane(?:'?s|\(s\))? car\b).*\bcar\b.*

^ Start of string

(?! Negative lookahead

.*\bJane(?:'?s|\(s\))? Match Jane Janes Jane's Jane(s)

 car\b Match a space and the word car

) Close the lookahead

.*\bcar\b.* Match the whole line with the word car between word boundaries

Regex demo

If the different forms of Jane followed by car should be there, you can match it:

^.*\bJane(?:'?s|\(s\))? car\b.*

Regex demo

To matching all occurrences of car without the ones that have Jane in front of it, you can match what you don't want to keep and capture what you do want to keep.

Then in Python you can use re.findall which will return the capture group values and remove the empty entries from the result.

\bJane(?:'?s|\(s\))? car\b|\b(car)\b

Regex demo | Python demo


问:
django: migration x in app x has no Migration class
here is the exact error

```<code>django.db.migrations.loader.BadMigrationError: Migration 0001_initial in app django_comments has no Migration class
</code>```

I have no idea what this means and I don't know where to go. I did some work with my venv, making a new one and then I was trying to get everything back to normal. Installing this and that...I lost track of everything I was doing because my laptop died which really pissed me off.

Any idea where to go from here?

EDIT:

If I try to upgrade django_comments I get the following error:

```<code> Could not find a version that satisfies the requirement django-comments (from versions: 0.2a, 0.3.1a, 0.3.2a, 0.3.3a, 0.3a, 1.0.0.b, 1.0.0.b, 1.0.0.b)
</code>```

Cleaning up...
No distributions matching the version for django-comments
Storing debug log for failure in /home/jeff/.pip/pip.log

答: I've shared my Django ORM DB model between my custom APP and a Django App via symbolic links: ln -s

Body:
here is the exact error

django.db.migrations.loader.BadMigrationError: Migration 0001_initial in app django_comments has no Migration class

I have no idea what this means and I don't know where to go. I did some work with my venv, making a new one and then I was trying to get everything back to normal. Installing this and that...I lost track of everything I was doing because my laptop died which really pissed me off.

Any idea where to go from here?

EDIT:

If I try to upgrade django_comments I get the following error:

 Could not find a version that satisfies the requirement django-comments (from versions: 0.2a, 0.3.1a, 0.3.2a, 0.3.3a, 0.3a, 1.0.0.b, 1.0.0.b, 1.0.0.b)

Cleaning up...
No distributions matching the version for django-comments
Storing debug log for failure in /home/jeff/.pip/pip.log


问:
Writing an R function, using "for-loop", to compute the arithmetic mean from vectors with numeric data?
I need to write a function that does the above, basically. I would like it to be able to apply it to any numeric vector. I am very new to R so I'm struggling to get this off the ground. I appreciate any help!</p>

答:
Rather than write your own function use mean(), which comes with base R:

```<code>numbers <- c(11, 3, 4.2, 0, -12)
numbers
result <- mean(numbers)

</code>```

Body:
Rather than write your own function use mean(), which comes with base R:

numbers <- c(11, 3, 4.2, 0, -12)
numbers
result <- mean(numbers)


问:
Dialog: how make dialog content scroll-able?
Anyway to have Dialog's content scroll-able?
We have sometimes Dialog content with a lot of content and we just would like to have it scrollable. Here sample with Boostrap and only modal content scrollable: http://www.bootply.com/WaTI0dBpa3</p>

答:
In current v5.0 of Kendo React (so probably the same in Angular) you can make sure all the dialogs/windows don't extend off screen using CSS:

.k-window {
  max-height: 90vh;
}
```

In this case I set the max height for a window to 90% of the screen height so that there is still a little bit of the translucent backdrop showing to indicate that you are in a modal dialog still.

Body:
In current v5.0 of Kendo React (so probably the same in Angular) you can make sure all the dialogs/windows don't extend off screen using CSS:

.k-window {
  max-height: 90vh;
}

In this case I set the max height for a window to 90% of the screen height so that there is still a little bit of the translucent backdrop showing to indicate that you are in a modal dialog still.


问:
Spring/Spring bean configuration file option is missing in STS
I am just following a tutorial , where in I need to add a spring configuration file
but I don't see spring / Spring bean configuration file option in Spring Tool Suite 4 (Version: 4.0.1.RELEASE), could somebody help me where to find that option

As shown in this screenshot

答:
I solved the problem doing an addicional step, not expliained on previous answers:

Help > Eclipse Marketplace

Search for "spring"

Install Spring Tools 3 Add-On for Spring Tools 4. After the installation the ide will restart

When the ide has restarted, on Package explorer, right click on the project > Maven > Update Project

Finally, right click on your project > New > Other > search for "spring bean". The option "Spring Bean Configuration File" should appear


问:
Can't apply conditions and select colums in pandas dataframe

Problem Context:

I connected to a database using mysql.connector and tried printing the dataframe. It worked perfectly fine.
Now when I try to apply conditions on that very dataframe (which is now stored inside a variable) it generates an empty table.

What I want to do:

Just like in a sql query where we can define both things(**columns** to display and **conditions** to follow) in one query. I want to do it using pandas, but without using the pd.read_sql().
I want to do it using pandas functions only.

Code:

```<code># importing dataframe from database
#this is just to show that a table is stored inside "df" variable
df = DatabaseTable

new_df = df.loc[(df["month"] == "JAN") &
    (df["topic_number"] >= 5) ,
    ["name","topic_number","month"]]
print(new_df)
</code>```

OUTPUT>>

```<code>--------------------------------------
name   |   topic_number   |   month
--------------------------------------
empty  |   empty          |   empty
       |                  |
</code>```

What am I doing wrong here? I followed Pandas Docs but didn't get anywhere. There are no exceptions thrown. It just shows me this empty table, whereas if I print df it shows me completely populated table.

答:
Your code works for me when I create an artificial example.

I would suggest looking at your data in more detail to ensure that they are what you think they are, posting a sample might be helpful.

```<code>import pandas as pd
df = pd.DataFrame()
df["month"] = pd.Series(["JAN", "JAN", "FEB"])
df["name"] = pd.Series(["max", "muhammad", "jane"])
df["topic_number"] = pd.Series([10, 1, 10])

new_df = df.loc[(df["month"] == "JAN") &
     (df["topic_number"] >= 5) ,
     ["name","topic_number","month"]]

print(new_df)
</code>```

This script prints:

```<code>  name  topic_number month
0  max            10   JAN
</code>```

Body:
Problem Context:

I connected to a database using mysql.connector and tried printing the dataframe. It worked perfectly fine.
Now when I try to apply conditions on that very dataframe (which is now stored inside a variable) it generates an empty table.

What I want to do:

Just like in a sql query where we can define both things(**columns** to display and **conditions** to follow) in one query. I want to do it using pandas, but without using the pd.read_sql().
I want to do it using pandas functions only.

Code:

# importing dataframe from database
#this is just to show that a table is stored inside "df" variable
df = DatabaseTable

new_df = df.loc[(df["month"] == "JAN") &
    (df["topic_number"] >= 5) ,
    ["name","topic_number","month"]]
print(new_df)

OUTPUT>>

--------------------------------------
name   |   topic_number   |   month
--------------------------------------
empty  |   empty          |   empty
       |                  |

What am I doing wrong here? I followed Pandas Docs but didn't get anywhere. There are no exceptions thrown. It just shows me this empty table, whereas if I print df it shows me completely populated table.

Body:
Your code works for me when I create an artificial example.

I would suggest looking at your data in more detail to ensure that they are what you think they are, posting a sample might be helpful.

import pandas as pd
df = pd.DataFrame()
df["month"] = pd.Series(["JAN", "JAN", "FEB"])
df["name"] = pd.Series(["max", "muhammad", "jane"])
df["topic_number"] = pd.Series([10, 1, 10])

new_df = df.loc[(df["month"] == "JAN") &
     (df["topic_number"] >= 5) ,
     ["name","topic_number","month"]]

print(new_df)

This script prints:

  name  topic_number month
0  max            10   JAN


问:
Portable way to split an external variable containing newlines in awk?
Consider these awk commands:

#!/bin/bash
awk 'BEGIN { print split("X\nX",a,"\n") }'
awk -v s=$'X\nX' 'BEGIN { print split(s,a,"\n") }'
```
<p><strong>Results:</strong></p>
<ul>
<li>Linux:</li>
</ul>
```2
2
```
<ul>
<li>macOS, FreeBSD:</li>
</ul>
```2
/usr/bin/awk: newline in string X
X... at source line 1
```
<ul>
<li>Solaris:</li>
</ul>
```2
/usr/xpg4/bin/awk: file "(null)": line 1: Newline in string
  Context is:
>>>     X
>>>             <<<
```
<p>Is there a way to work around that?</p>
<hr />
<p><strong>Edit:</strong></p>
<p>There's not even the need to use an external variable, the following will also fail in all <code>awk</code> implementations but the GNU one:</p>
<pre class="lang-sh prettyprint-override"><code>awk 'BEGIN { s = "X\nX"; print split(s,a,"\n") }'
</code>```

答:
POSIX awk does not allow physical newlines in string values.

When you use C/BASH string notation like $'a\nb' then any POSIX compliant awk implementation will fail.

Even with gnu-awk, when you enable posix option following error will be returned:

awk --posix -v s=$'X\nX' 'BEGIN { print split(s,a,"\n") }'
awk: fatal: POSIX does not allow physical newlines in string values
```
<p>However if you remove <code>$'...'</code> notation then error will not be there:</p>
<pre class="lang-sh prettyprint-override"><code>awk --posix -v s="X\nX" 'BEGIN { print split(s,a,"\n") }'
2
</code>```

Body:
Consider these awk commands:

#!/bin/bash
awk 'BEGIN { print split("X\nX",a,"\n") }'
awk -v s=$'X\nX' 'BEGIN { print split(s,a,"\n") }'

Results:

Linux:

2
2

macOS, FreeBSD:

2
/usr/bin/awk: newline in string X
X... at source line 1

Solaris:

2
/usr/xpg4/bin/awk: file "(null)": line 1: Newline in string
  Context is:
>>>     X
>>>             <<<

Is there a way to work around that?

Edit:

There's not even the need to use an external variable, the following will also fail in all awk implementations but the GNU one:

awk 'BEGIN { s = "X\nX"; print split(s,a,"\n") }'

Body:
POSIX awk does not allow physical newlines in string values.

When you use C/BASH string notation like $'a\nb' then any POSIX compliant awk implementation will fail.

Even with gnu-awk, when you enable posix option following error will be returned:

awk --posix -v s=$'X\nX' 'BEGIN { print split(s,a,"\n") }'
awk: fatal: POSIX does not allow physical newlines in string values

However if you remove $'...' notation then error will not be there:

awk --posix -v s="X\nX" 'BEGIN { print split(s,a,"\n") }'
2


问:
Nested ternary operators
I have this code:

```<code>_viewModel.PhoneDefault = user == null ? "" :
    (string.IsNullOrEmpty(user.PhoneDay) ?
        (string.IsNullOrEmpty(user.PhoneEvening) ?
            (string.IsNullOrEmpty(user.Mobile) ? "" :
                user.Mobile) :
            user.PhoneEvening) :
         user.PhoneDay);
</code>```

Is there a better way to write this to make it more readable?

答:
Write a seperate method to get the phone number, something like this:

```<code>public string GetDefaultPhone(User user)
        {
            if(user == null)
            {
                return string.Empty;
            }

            if(!string.IsNullOrEmpty(user.PhoneDay))
            {
                return user.PhoneDay;
            }

            if(!string.IsNullOrEmpty(user.PhoneEvening))
            {
                return user.PhoneEvening;
            }

            if(!string.IsNullOrEmpty(user.Mobile))
            {
                return user.Mobile;
            }

            return string.Empty;
        }
</code>```

And then in your code:

```<code>_viewModel.PhoneDefault = GetDefaultPhone(user);
</code>```

Title: Nested ternary operators

Body:
I have this code:

_viewModel.PhoneDefault = user == null ? "" :
    (string.IsNullOrEmpty(user.PhoneDay) ?
        (string.IsNullOrEmpty(user.PhoneEvening) ?
            (string.IsNullOrEmpty(user.Mobile) ? "" :
                user.Mobile) :
            user.PhoneEvening) :
         user.PhoneDay);

Is there a better way to write this to make it more readable?

Body:
Write a seperate method to get the phone number, something like this:

public string GetDefaultPhone(User user)
        {
            if(user == null)
            {
                return string.Empty;
            }

            if(!string.IsNullOrEmpty(user.PhoneDay))
            {
                return user.PhoneDay;
            }

            if(!string.IsNullOrEmpty(user.PhoneEvening))
            {
                return user.PhoneEvening;
            }

            if(!string.IsNullOrEmpty(user.Mobile))
            {
                return user.Mobile;
            }

            return string.Empty;
        }

And then in your code:

_viewModel.PhoneDefault = GetDefaultPhone(user);


问:
Randomize selection from snowflake SQL
I am trying to select 1,000 random rows from a database of 97 million rows. I am using the following code:

```<code>SELECT *
FROM "DB"."SCHEMA"."TABLE"
ORDER BY
   RAND()                                      LIMIT 1000
</code>```

I tried this code and got an error stating "SQL compilation error: Unknown function RAND." Is there a better way to do this in Snowflake? I am worried that this code only works in MySQL.

答:
Using  SAMPLE clause:

Returns a subset of rows sampled randomly from the specified table. The following sampling methods are supported:

Sample a fraction of a table, with a specified probability for including a given row. The number of rows returned depends on the size of the table and the requested probability. A seed can be specified to make the sampling deterministic.

Sample a fixed, specified number of rows. The exact number of specified rows is returned unless the table contains fewer rows.

```<code>SELECT *
FROM "DB"."SCHEMA"."TABLE"
SAMPLE (1000 ROWS);
</code>```

Title: Randomize selection from snowflake SQL

Body:
I am trying to select 1,000 random rows from a database of 97 million rows. I am using the following code:

SELECT *
FROM "DB"."SCHEMA"."TABLE"
ORDER BY
   RAND()                                      LIMIT 1000

I tried this code and got an error stating "SQL compilation error: Unknown function RAND." Is there a better way to do this in Snowflake? I am worried that this code only works in MySQL.

Body:
Using  SAMPLE clause:

Returns a subset of rows sampled randomly from the specified table. The following sampling methods are supported:

Sample a fraction of a table, with a specified probability for including a given row. The number of rows returned depends on the size of the table and the requested probability. A seed can be specified to make the sampling deterministic.

Sample a fixed, specified number of rows. The exact number of specified rows is returned unless the table contains fewer rows.

SELECT *
FROM "DB"."SCHEMA"."TABLE"
SAMPLE (1000 ROWS);


问:
HTML Input autocomplete not working in WKWebview
Inputs with autocomplete enabled are working properly when opening in mobile Safari but not when loaded in a WKWebview (iOS 11.3). Is this a known limitation?

答:
I know I'm late to the party, but I had a surprisingly hard time finding a solution to such an old problem, so I wanted to share since this is still high on the Google results.

The autofill that I wanted was for the WKWebView to autocomplete a saved username and password for easy login.  However, this could present a security risk to the user, so you have to add the "Associated Domains" entitlement to the iOS app that tells it which domains/subdomains it can trust, and you have to add a JSON file to the web site server's wwwroot/.well-known directory to prove that you control the site you are displaying in the WKWebView.  Once that is done, then the username/password is autosuggested the same way that it is in Safari.

Here is the Apple documentation: https://developer.apple.com/documentation/xcode/supporting-associated-domains

To summarize the steps I took, in XCode, I went to the "Signing and Capabilities" tab in my app target, clicked the "+ Capability" button, added Associated Domains, and put entries in the newly created list for all of my subdomains:

```<code>webcredentials:example.com
webcredentials:www.example.com
webcredentials:othersubdomain.example.com
</code>```

And then on my web server, I added a file to the .well-known directory called "apple-app-site-association" (no extension) with the following contents:

```<code>{
  "webcredentials": {
    "apps": [ "ABCDE12345.com.example.myapp" ]
  }
}
</code>```

(where the format for the identifier is <Application Identifier Prefix>.<Bundle Identifier>).  Then I browsed to https://www.example.com/.well-known/apple-app-site-association to make sure that the json was displayed in the browser.

Note: I use ASP.Net Core MVC, and the file WASN'T displayed in the browser since it doesn't use a recognized file extension.  I found several methods for getting around that - I chose to add a file extension to the file and then use a rewrite rule in startup.cs so that Apple can find the file without supplying the extension in the request.  You can find more on that at asp.net core - How to serve static file with no extension

Body:
I know I'm late to the party, but I had a surprisingly hard time finding a solution to such an old problem, so I wanted to share since this is still high on the Google results.

The autofill that I wanted was for the WKWebView to autocomplete a saved username and password for easy login.  However, this could present a security risk to the user, so you have to add the "Associated Domains" entitlement to the iOS app that tells it which domains/subdomains it can trust, and you have to add a JSON file to the web site server's wwwroot/.well-known directory to prove that you control the site you are displaying in the WKWebView.  Once that is done, then the username/password is autosuggested the same way that it is in Safari.

Here is the Apple documentation: https://developer.apple.com/documentation/xcode/supporting-associated-domains

To summarize the steps I took, in XCode, I went to the "Signing and Capabilities" tab in my app target, clicked the "+ Capability" button, added Associated Domains, and put entries in the newly created list for all of my subdomains:

webcredentials:example.com
webcredentials:www.example.com
webcredentials:othersubdomain.example.com

And then on my web server, I added a file to the .well-known directory called "apple-app-site-association" (no extension) with the following contents:

{
  "webcredentials": {
    "apps": [ "ABCDE12345.com.example.myapp" ]
  }
}

(where the format for the identifier is <Application Identifier Prefix>.<Bundle Identifier>).  Then I browsed to https://www.example.com/.well-known/apple-app-site-association to make sure that the json was displayed in the browser.

Note: I use ASP.Net Core MVC, and the file WASN'T displayed in the browser since it doesn't use a recognized file extension.  I found several methods for getting around that - I chose to add a file extension to the file and then use a rewrite rule in startup.cs so that Apple can find the file without supplying the extension in the request.  You can find more on that at asp.net core - How to serve static file with no extension


问:
How can I have cleaner code and do less copying/pasting of code (VBA. Python)
I find myself constantly copying code from previous sections of my project into other sections in VBA.

My entire code seems unnecessarily long because this.

Over half my code is copied from one section and pasted in other sections. This is an issue when I realize there's a small error, causing me to go back to correct it in every instance I copied and pasted.

Is there any way to make my code shorter and to reference copied code only once in VBA, and also python?

答: I uaually have a module for my functions. they work like a tool box for me. i need to call them always in other subs.they save my time and make my codes more readable. Also debugging is much easier. I recommend the same to you.</p>


问:
Trying to run each_index on an array but getting `each': can't iterate from NilClass (TypeError)
I am currently attempting the codewars 6th kyu kata "Equal Sides Of An Array" where it asks:

'Input:
An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative.

Output:
The lowest index N where the side to the left of N is equal to the side to the right of N. If you do not find an index that fits these rules, then you will return -1.

Note:
If you are given an array with multiple answers, return the lowest correct index.'

I know my code doesn't work completely but trying to run the code to see where it is going wrong to try and get a further understanding of how to use error codes to guide my thought process.

My code is as follows

```<code>def find_even_index(arr)
  even_index = -1
  arr.with_each_index do |n, index|
    even_index = index if (arr[0]..arr[index - 1]).sum == (arr[index + 1]..arr[-1]).sum
  end
  even_index
end
</code>```

When I input this into the kata to test, I get the following error:

'./lib/solution.rb:4:in `each': can't iterate from NilClass (TypeError)'

This error leads me to believe that there is an issue with the use of each_with_index on arr but the parameter is an array. What is going wrong here?

答:
Here's a solution that does not repeatedly sum each side of a partitioned array.

Note that the Kata defines the sum of the elements before the first and after the last to equal zero.

```<code>def doit(arr)
  left = 0
  right = arr.sum - arr[0]
  (0..arr.size-1).each do |i|
    return i if left == right
    return -1 if i == arr.size - 1
    left += arr[i]
    right -= arr[i+1]
  end
end
</code>```

```<code>doit [1, 2, 3, 4, 3, 2, 1]
  #=> 3
doit [1, 2, 3, -5]
  #=> 0
doit [1, -3, 2, 18]
  #=> 3
doit [99]
  #=> 0
doit [0,0,0,0,0]
  #=> 0
doit [1, 2, 2, 4, 3, 2, 1]
  #=> -1
</code>```

I can best explain the calculations by executing the method after having salted it with puts statements.

```<code>def doit(arr)
  puts "arr.size == #{arr.size}, arr.sum = #{arr.sum}"
  left = 0
  right = arr.sum - arr[0]
  puts "initially left = 0, right = #{right}"
  (0..arr.size-1).each do |i|
    puts "i = #{i}"
    puts left == right ?
      "returning #{i} because left == right" : "left != right"
    return i if left == right
    puts  i == arr.size - 1 ? "  i == arr.size - 1 so returning #{-1}" :
       "  i < arr.size - 1, so continuing"
    return -1 if i == arr.size - 1
    left += arr[i]
    puts "  left = left + arr[#{i}] = #{left} for i = #{i+1}"
    right -= arr[i+1]
    puts "  right = right - arr[#{i+1}] = #{right} for i = #{i+1}"
  end
end
</code>```

```<code>doit [1, 2, 3, 4, 3, 2, 1]
  #=> 3
</code>```

```<code>arr.size == 7, arr.sum = 16
initially left = 0, right = 15
i = 0
left != right
  i < arr.size - 1, so continuing
  left = left + arr[0] = 1 for i = 1
  right = right - arr[1] = 13 for i = 1
i = 1
left != right
  i < arr.size - 1, so continuing
  left = left + arr[1] = 3 for i = 2
  right = right - arr[2] = 10 for i = 2
i = 2
left != right
  i < arr.size - 1, so continuing
  left = left + arr[2] = 6 for i = 3
  right = right - arr[3] = 6 for i = 3
i = 3
returning 3 because left == right
</code>```

Body:
I am currently attempting the codewars 6th kyu kata "Equal Sides Of An Array" where it asks:

'Input:
An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative.

Output:
The lowest index N where the side to the left of N is equal to the side to the right of N. If you do not find an index that fits these rules, then you will return -1.

Note:
If you are given an array with multiple answers, return the lowest correct index.'

I know my code doesn't work completely but trying to run the code to see where it is going wrong to try and get a further understanding of how to use error codes to guide my thought process.

My code is as follows

def find_even_index(arr)
  even_index = -1
  arr.with_each_index do |n, index|
    even_index = index if (arr[0]..arr[index - 1]).sum == (arr[index + 1]..arr[-1]).sum
  end
  even_index
end

When I input this into the kata to test, I get the following error:

'./lib/solution.rb:4:in `each': can't iterate from NilClass (TypeError)'

This error leads me to believe that there is an issue with the use of each_with_index on arr but the parameter is an array. What is going wrong here?

Body:
Here's a solution that does not repeatedly sum each side of a partitioned array.

Note that the Kata defines the sum of the elements before the first and after the last to equal zero.

def doit(arr)
  left = 0
  right = arr.sum - arr[0]
  (0..arr.size-1).each do |i|
    return i if left == right
    return -1 if i == arr.size - 1
    left += arr[i]
    right -= arr[i+1]
  end
end

doit [1, 2, 3, 4, 3, 2, 1]
  #=> 3
doit [1, 2, 3, -5]
  #=> 0
doit [1, -3, 2, 18]
  #=> 3
doit [99]
  #=> 0
doit [0,0,0,0,0]
  #=> 0
doit [1, 2, 2, 4, 3, 2, 1]
  #=> -1

I can best explain the calculations by executing the method after having salted it with puts statements.

def doit(arr)
  puts "arr.size == #{arr.size}, arr.sum = #{arr.sum}"
  left = 0
  right = arr.sum - arr[0]
  puts "initially left = 0, right = #{right}"
  (0..arr.size-1).each do |i|
    puts "i = #{i}"
    puts left == right ?
      "returning #{i} because left == right" : "left != right"
    return i if left == right
    puts  i == arr.size - 1 ? "  i == arr.size - 1 so returning #{-1}" :
       "  i < arr.size - 1, so continuing"
    return -1 if i == arr.size - 1
    left += arr[i]
    puts "  left = left + arr[#{i}] = #{left} for i = #{i+1}"
    right -= arr[i+1]
    puts "  right = right - arr[#{i+1}] = #{right} for i = #{i+1}"
  end
end

doit [1, 2, 3, 4, 3, 2, 1]
  #=> 3

arr.size == 7, arr.sum = 16
initially left = 0, right = 15
i = 0
left != right
  i < arr.size - 1, so continuing
  left = left + arr[0] = 1 for i = 1
  right = right - arr[1] = 13 for i = 1
i = 1
left != right
  i < arr.size - 1, so continuing
  left = left + arr[1] = 3 for i = 2
  right = right - arr[2] = 10 for i = 2
i = 2
left != right
  i < arr.size - 1, so continuing
  left = left + arr[2] = 6 for i = 3
  right = right - arr[3] = 6 for i = 3
i = 3
returning 3 because left == right


问:
Why is my website's grid collapsing the first time it's loaded?
I'm sorry for dropping so much code here, but I've been playing with this for over a week and I just can't figure it out.

So I am working on my personal website, and the problem is that the images in the the body's grid system overlap sometimes on the first load of the site. If you refresh it, it seems to work ok (most of the time). You can try yourself: tylerteacher.com . The strange thing is that the site works in the compatibility viewers in chrome and firefox.

I have tried adding margins and using the 'space-between' function in the css. I have double checked the html to make sure everything is properly linked to the css page, and I have also played with Javascript page and the slides per view functions.

I really appreciate the help!

let toggle = document.querySelector("#header .toggle-button");
let collapse = document.querySelectorAll("#header .collapse");

toggle.addEventListener('click' , function(){
    collapse.forEach(col => col.classList.toggle("collapse-toggle"));
})

// with masonry
new Masonry("#posts .grid", {
    itemSelector : '.grid-item',
    gutter : 20
});

// swiper libray initialization
new Swiper('.swiper-container', {
    direction : 'horizontal',
    loop : true,
    slidesPerView : 6,
    autoplay : {
        delay : 0
    },
    // responsive breakpoints
    breakpoints : {
        '@0' : {
            slidesPerView : 2

        },
        // 888px
        '@1.00' : {
            slidesPerView : 3
        },
        // 1110px
        '@1.25' : {
            slidesPerView : 4
        },
        // 1330px
        '@1.50' : {
            slidesPerView: 5
        }
    }
})

// Sticky Navigation
window.onscroll = function(){ myFunction()};

// get the current value
let navbar = document.getElementById("header");

// get the navbar position
let sticky = navbar.offsetTop;

// sticky function
function myFunction(){
    if(window.pageYOffset >= sticky){
        navbar.classList.add("sticky");
    }else{
        navbar.classList.remove("sticky");
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=DM+Sans&family=Poppins&family=Roboto&display=swap');

/* root styling */

:root{
    --light : #f8f9fa;
    --secondary: #adb5bd;
    --dark: #343a40;
    --primary-color: #f15bb5;
    --secondary-color: #2ec4b6;
    --border : #e9ecef;
}

body{
    font-family: 'Roboto', sans-serif;
    padding: 0;
    margin: 0;
}

a{
    text-decoration: none;

}

* > *{
    box-sizing: border-box;
}

/* global styling */
.text-light{
    color: var(--light);
}

.text-secondary{
    color: var(--secondary);
}

.text-dark{
    color: var(--dark);
}

.text-primary{
    color: var(--primary-color);
}

.bg-light{
    background-color: var(--light);
}

.container{
    max-width: 1200px;
    padding: 0 15px;
    margin: auto;
}

.img-fluid{
    width: 100%;
}

.text-title{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
}

.secondary-title{
    font-family: 'Poppins' , sans-serif;
}

.display-1{
    font-size: 22px;
}

.display-2{
    font-size: 16px;
}

.display-3{
    font-size: 14px;
}

.text-center{
    text-align: center;
}

.text-right{
    text-align: right;
}

.btn{
    padding: 15px 20px;
    border: none;
}

.btn-primary{
    border-radius: 4px;
    background-color: var(--secondary-color);
}

.object-fit{
    max-height: 120px;
    height: 80px;
    width: 80px;
    object-fit: fill;
    justify-content: space-between;
}

.d-flex{
    display: flex;
}

.flex-wrap{
    flex-wrap: wrap;
}

.justify-content-center{
    justify-content: center;
}

.justify-content-between{
    justify-content: space-between;
}

.mt-2{
    margin-top: 10px;
}

.mt-3{
    margin-top: 50px;
}

.mb-3{
    margin-bottom: 30px;
}

.m-0{
    margin: 0;
}

.px-1{
    padding-left: 5px;
    padding-right: 5px;
}

.px-2{
    padding-left: 20px;
    padding-right: 20px;
}

.py-1{
    padding-top: 10px;
    padding-bottom: 10px;
}

.py-2{
    padding-top: 20px;
    padding-bottom: 20px;
}

.py-3{
    padding-top: 30px;
    padding-bottom: 30px;
}

.thumbnail{
    width: 100%;
    height: 500px;
    object-fit: cover;
}

.rounded{
    height: 120px;
    width: 120px;
    object-fit: fill;
    border-radius: 99px;
}

.shadow{
    box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
}

/* section styling */

/* ------- Navigation Menu ---------- */
.navbar{
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
}

.nav-brand{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
    align-self: center;
    font-size: 32px;
}

.collapse{
    align-self: center;
}

.nav-link{
    font-size: 18px;
    margin: 12px;
    color: var(--dark);
    font-family: 'Poppins', sans-serif;
}

.nav-link:hover{
    color: var(--primary-color);
}

.search-box{
    display: inline;
    border-right: 1px solid var(--secondary);
    padding-right: 12px;
    margin-right: 10px;
}

.toggle-button{
    font-size: 21px;
    background-color: transparent;
    border: none;
    position: absolute;
    right: 0;
    margin: 8px 10px;
    display: none;
}

.toggle-button:focus{
    outline: none;
}

/* ------- .Navigation Menu ---------- */

/* ----------- Main Section ---------- */

#site-main{
    margin-top: 4em;
}

#posts{
    margin-bottom: 5em;

}

.grid{
    margin: 1 auto;
    row-gap: 20px;
}

.grid .grid-item{
    width: calc(33.3333% - 20px);
    margin-bottom: 3em;

}

/* ----------- .Main Section ---------- */

/* ----------- sticky ------- */

.sticky{
    position: fixed;
    top: 0;
    z-index: 99;
    width: 100%;
}

.sticky + .content{
    padding-top: 60px;
}

/* ----------- .sticky ------- */

/* Media Query */

.row{
    display: flex;

}

.col-3{
    flex: 0 0 33.3333%;
    max-width: 33.3333%;
    padding-right: 35px;
}

.col-8{
    flex: 0 0 70%;
    max-width: 70%;
}

.col-4{
    flex: 0 0 30%;
    max-width: 30%;
}

@media (max-width : 1024px){
    .row{
       flex-wrap: wrap;
    }

    .col-3{
        flex: 0 0 50%;
        max-width: 50%;
    }

    .col-8{
        flex: 0 0 100%;
        max-width: 100%;
    }

    .col-4{
        flex: 0 0 100%;
        max-width: 100%;
    }

}

@media (max-width : 992px){
    .navbar{
        flex-direction: column;
    }

    #site-main{
        margin-top: 14em;
    }

}

@media (max-width : 768px){
    .grid .grid-item{
        width: calc(50% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    .col-3{
        flex: 0 0 100%;
        max-width: calc(100% - 50px);
        padding-top: 40px;
    }
}

@media (max-width : 574px){
    .toggle-button{
        display: initial;
    }

    .collapse{
        max-height: 0;
        overflow: hidden;
        transition: all 0.8s cubic-bezier(0.51,-0.15, 0, 0.98);
    }

    .collapse .nav-link{
        display: block;
        text-align: center;
    }

    .search-box{
        border-right: none;
    }

    .collapse-toggle{
        max-height: 500px;
    }

    .grid .grid-item{
        width: calc(100% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    #site-main{
        margin-top: 6em;
        justify-content: space-around;
    }

}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TylerTeacher</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
        integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/6.4.5/swiper-bundle.min.css"
        integrity="sha512-m3pAvNriL711NMlhkZHK6K4Tu2/RjtrzyjxZU8mlAbxxoDoURy27KajN1LGTLeEEPvaN12mKAgSCrYEwF9y0jA=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="style.css">

                TylerTeacher

            <button class="toggle-button">

            </button>

                    Home
                    Resources
                    Classes
                    Testimonials
                    Contact

                                        Welcome to TylerTeacher.com

                                         Clock Wed 02, 2021
                                         12

                                        Why online education is the future

                                         Clock Wed 02, 2021
                                         12

                                        How to overcome language anxiety

                                         Clock Wed 02, 2021
                                         12

                                        Podcasts are a great tool for language learners

                                         Clock Wed 02, 2021
                                         12

                                        What makes some people better at learning languages?

                                         Clock Wed 02, 2021
                                         12

                                        Tips for becoming a more confident communicator in English

                                         Clock Wed 02, 2021
                                         12

                                        How listening can make you better at speaking English

                                         Clock Wed 02, 2021
                                         12

                                        How to use online classes effectively

                                         Clock Wed 02, 2021
                                         12

                                        Coming soon

                                         Clock Wed 02, 2021
                                         12

                    <button class="btn btn-primary secondary-title text-light">Load More Posts...</button>

```

答:
What you're experiencing is due to the Masonry script calculating the dimensions of the grid based on its content. While loading the page your images don't have a width and height because the browser doesn't know what they look like. Masonry doesn't wait and will render your grid anyway.

A fix for this is to let the browser know in advance what the dimensions of the image will be. You can do this by adding a width and height attribute to your img tag containing the width and height in pixels.

```
<p>Alternatively you could wait for all images in your grid to load <em>before</em> initializing the Masonry script.</p>
```// Loads a single image.
const loadImage = src => new Promise(resolve => {
  const image = new Image();
  image.onload = () => resolve();
  image.src = src;
});

// Get the container with all images.
// Loop over each image and wait for all of them to load.
async function allImagesLoaded(selector) {
  const container = document.querySelector(selector);
  if (container === null) {
    return;
  }

  const images = container.querySelectorAll('img');
  return Promise.all([...images].map(
    src => loadImage(src)
  ));
}

// Load all images inside #posts .grid.
allImagesLoaded('#posts .grid').then(() => {
  new Masonry("#posts .grid", {
    itemSelector : '.grid-item',
    gutter : 20
  });
});
```

Body:
I'm sorry for dropping so much code here, but I've been playing with this for over a week and I just can't figure it out.

So I am working on my personal website, and the problem is that the images in the the body's grid system overlap sometimes on the first load of the site. If you refresh it, it seems to work ok (most of the time). You can try yourself: tylerteacher.com . The strange thing is that the site works in the compatibility viewers in chrome and firefox.

I have tried adding margins and using the 'space-between' function in the css. I have double checked the html to make sure everything is properly linked to the css page, and I have also played with Javascript page and the slides per view functions.

I really appreciate the help!

let toggle = document.querySelector("#header .toggle-button");
let collapse = document.querySelectorAll("#header .collapse");

toggle.addEventListener('click' , function(){
    collapse.forEach(col => col.classList.toggle("collapse-toggle"));
})

// with masonry
new Masonry("#posts .grid", {
    itemSelector : '.grid-item',
    gutter : 20
});

// swiper libray initialization
new Swiper('.swiper-container', {
    direction : 'horizontal',
    loop : true,
    slidesPerView : 6,
    autoplay : {
        delay : 0
    },
    // responsive breakpoints
    breakpoints : {
        '@0' : {
            slidesPerView : 2

        },
        // 888px
        '@1.00' : {
            slidesPerView : 3
        },
        // 1110px
        '@1.25' : {
            slidesPerView : 4
        },
        // 1330px
        '@1.50' : {
            slidesPerView: 5
        }
    }
})

// Sticky Navigation
window.onscroll = function(){ myFunction()};

// get the current value
let navbar = document.getElementById("header");

// get the navbar position
let sticky = navbar.offsetTop;

// sticky function
function myFunction(){
    if(window.pageYOffset >= sticky){
        navbar.classList.add("sticky");
    }else{
        navbar.classList.remove("sticky");
    }
}

@import url('https://fonts.googleapis.com/css2?family=DM+Sans&family=Poppins&family=Roboto&display=swap');

/* root styling */

:root{
    --light : #f8f9fa;
    --secondary: #adb5bd;
    --dark: #343a40;
    --primary-color: #f15bb5;
    --secondary-color: #2ec4b6;
    --border : #e9ecef;
}

body{
    font-family: 'Roboto', sans-serif;
    padding: 0;
    margin: 0;
}

a{
    text-decoration: none;

}

* > *{
    box-sizing: border-box;
}

/* global styling */
.text-light{
    color: var(--light);
}

.text-secondary{
    color: var(--secondary);
}

.text-dark{
    color: var(--dark);
}

.text-primary{
    color: var(--primary-color);
}

.bg-light{
    background-color: var(--light);
}

.container{
    max-width: 1200px;
    padding: 0 15px;
    margin: auto;
}

.img-fluid{
    width: 100%;
}

.text-title{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
}

.secondary-title{
    font-family: 'Poppins' , sans-serif;
}

.display-1{
    font-size: 22px;
}

.display-2{
    font-size: 16px;
}

.display-3{
    font-size: 14px;
}

.text-center{
    text-align: center;
}

.text-right{
    text-align: right;
}

.btn{
    padding: 15px 20px;
    border: none;
}

.btn-primary{
    border-radius: 4px;
    background-color: var(--secondary-color);
}

.object-fit{
    max-height: 120px;
    height: 80px;
    width: 80px;
    object-fit: fill;
    justify-content: space-between;
}

.d-flex{
    display: flex;
}

.flex-wrap{
    flex-wrap: wrap;
}

.justify-content-center{
    justify-content: center;
}

.justify-content-between{
    justify-content: space-between;
}

.mt-2{
    margin-top: 10px;
}

.mt-3{
    margin-top: 50px;
}

.mb-3{
    margin-bottom: 30px;
}

.m-0{
    margin: 0;
}

.px-1{
    padding-left: 5px;
    padding-right: 5px;
}

.px-2{
    padding-left: 20px;
    padding-right: 20px;
}

.py-1{
    padding-top: 10px;
    padding-bottom: 10px;
}

.py-2{
    padding-top: 20px;
    padding-bottom: 20px;
}

.py-3{
    padding-top: 30px;
    padding-bottom: 30px;
}

.thumbnail{
    width: 100%;
    height: 500px;
    object-fit: cover;
}

.rounded{
    height: 120px;
    width: 120px;
    object-fit: fill;
    border-radius: 99px;
}

.shadow{
    box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
}

/* section styling */

/* ------- Navigation Menu ---------- */
.navbar{
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
}

.nav-brand{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
    align-self: center;
    font-size: 32px;
}

.collapse{
    align-self: center;
}

.nav-link{
    font-size: 18px;
    margin: 12px;
    color: var(--dark);
    font-family: 'Poppins', sans-serif;
}

.nav-link:hover{
    color: var(--primary-color);
}

.search-box{
    display: inline;
    border-right: 1px solid var(--secondary);
    padding-right: 12px;
    margin-right: 10px;
}

.toggle-button{
    font-size: 21px;
    background-color: transparent;
    border: none;
    position: absolute;
    right: 0;
    margin: 8px 10px;
    display: none;
}

.toggle-button:focus{
    outline: none;
}

/* ------- .Navigation Menu ---------- */

/* ----------- Main Section ---------- */

#site-main{
    margin-top: 4em;
}

#posts{
    margin-bottom: 5em;

}

.grid{
    margin: 1 auto;
    row-gap: 20px;
}

.grid .grid-item{
    width: calc(33.3333% - 20px);
    margin-bottom: 3em;

}

/* ----------- .Main Section ---------- */

/* ----------- sticky ------- */

.sticky{
    position: fixed;
    top: 0;
    z-index: 99;
    width: 100%;
}

.sticky + .content{
    padding-top: 60px;
}

/* ----------- .sticky ------- */

/* Media Query */

.row{
    display: flex;

}

.col-3{
    flex: 0 0 33.3333%;
    max-width: 33.3333%;
    padding-right: 35px;
}

.col-8{
    flex: 0 0 70%;
    max-width: 70%;
}

.col-4{
    flex: 0 0 30%;
    max-width: 30%;
}

@media (max-width : 1024px){
    .row{
       flex-wrap: wrap;
    }

    .col-3{
        flex: 0 0 50%;
        max-width: 50%;
    }

    .col-8{
        flex: 0 0 100%;
        max-width: 100%;
    }

    .col-4{
        flex: 0 0 100%;
        max-width: 100%;
    }

}

@media (max-width : 992px){
    .navbar{
        flex-direction: column;
    }

    #site-main{
        margin-top: 14em;
    }

}

@media (max-width : 768px){
    .grid .grid-item{
        width: calc(50% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    .col-3{
        flex: 0 0 100%;
        max-width: calc(100% - 50px);
        padding-top: 40px;
    }
}

@media (max-width : 574px){
    .toggle-button{
        display: initial;
    }

    .collapse{
        max-height: 0;
        overflow: hidden;
        transition: all 0.8s cubic-bezier(0.51,-0.15, 0, 0.98);
    }

    .collapse .nav-link{
        display: block;
        text-align: center;
    }

    .search-box{
        border-right: none;
    }

    .collapse-toggle{
        max-height: 500px;
    }

    .grid .grid-item{
        width: calc(100% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    #site-main{
        margin-top: 6em;
        justify-content: space-around;
    }

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TylerTeacher</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
        integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/6.4.5/swiper-bundle.min.css"
        integrity="sha512-m3pAvNriL711NMlhkZHK6K4Tu2/RjtrzyjxZU8mlAbxxoDoURy27KajN1LGTLeEEPvaN12mKAgSCrYEwF9y0jA=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="style.css">

                TylerTeacher

            <button class="toggle-button">

            </button>

                    Home
                    Resources
                    Classes
                    Testimonials
                    Contact

                                        Welcome to TylerTeacher.com

                                         Clock Wed 02, 2021
                                         12

                                        Why online education is the future

                                         Clock Wed 02, 2021
                                         12

                                        How to overcome language anxiety

                                         Clock Wed 02, 2021
                                         12

                                        Podcasts are a great tool for language learners

                                         Clock Wed 02, 2021
                                         12

                                        What makes some people better at learning languages?

                                         Clock Wed 02, 2021
                                         12

                                        Tips for becoming a more confident communicator in English

                                         Clock Wed 02, 2021
                                         12

                                        How listening can make you better at speaking English

                                         Clock Wed 02, 2021
                                         12

                                        How to use online classes effectively

                                         Clock Wed 02, 2021
                                         12

                                        Coming soon

                                         Clock Wed 02, 2021
                                         12

                    <button class="btn btn-primary secondary-title text-light">Load More Posts...</button>

Body:
What you're experiencing is due to the Masonry script calculating the dimensions of the grid based on its content. While loading the page your images don't have a width and height because the browser doesn't know what they look like. Masonry doesn't wait and will render your grid anyway.

A fix for this is to let the browser know in advance what the dimensions of the image will be. You can do this by adding a width and height attribute to your img tag containing the width and height in pixels.

<img src="your-image.jpg" class="img-fluid" width="480" height="720" alt="" />

Alternatively you could wait for all images in your grid to load before initializing the Masonry script.

// Loads a single image.
const loadImage = src => new Promise(resolve => {
  const image = new Image();
  image.onload = () => resolve();
  image.src = src;
});

// Get the container with all images.
// Loop over each image and wait for all of them to load.
async function allImagesLoaded(selector) {
  const container = document.querySelector(selector);
  if (container === null) {
    return;
  }

  const images = container.querySelectorAll('img');
  return Promise.all([...images].map(
    src => loadImage(src)
  ));
}

// Load all images inside #posts .grid.
allImagesLoaded('#posts .grid').then(() => {
  new Masonry("#posts .grid", {
    itemSelector : '.grid-item',
    gutter : 20
  });
});