问:
toHaveBeenCalled() failing when mocked output shows correct data
I am getting tired of trying to figure out the following out. Basically I have a method in my component that calls a service which is mocked. Once that service completes, another service does some logging activities, which is also mocked. But my test fails saying the logging service wasn't called:

```<code>       process(){
       const that : any = this;
      this.mainService.process().then(result=>{

       return result;

    }).then(result=>{
      //log the operation now after doing some checkups
      let checkups = ""
      that.logService.log('process',result, checkups).then(logged=>{
        console.log(logged)

      }).catch(err=>console.log(err)
    }).catch(err=>console.log(err);

    }
</code>```

Before we go ahead, doing Promise.all() isn't match of an option due to the logic in place to do checkups. Now to the testing bit:

```<code>fit("should log processed request", done => {
  const mainSerivce = TestBed.get(MainService)
  const logService = TestBed.get(LogService)
  spyOn(mainService, "process").and.returnValue(Promise.resolve({id:34,value:64, rank:310));
  const logSpy = spyOn(logSerivce, "log").and.returnValue(Promise.resolve({'done':true}))

  fixture.whenStable().then(finished=>{

    component.process();

    expect(logSpy).toHaveBeenCalled();
    done();

  })

});

expect(logSpy).toHaveBeenCalled();
</code>```

fails now but I can see in my console the result of the mock {'done':true} or whatever value I pass is shown, meaning it was mocked and called (?). What am I missing exactly since the methods appear to have been mocked and logged correctly in the console.

答:
It seems to me you have to wait for the promises to resolve before asserting for it, try:

```<code>fit("should log processed request", done => {
  const mainSerivce = TestBed.get(MainService)
  const logService = TestBed.get(LogService)
  spyOn(mainService, "process").and.returnValue(Promise.resolve({id:34,value:64, rank:310));
  const logSpy = spyOn(logSerivce, "log").and.returnValue(Promise.resolve({'done':true}));
  // call the function that will resolve promises
  component.process();
  // whenStable waits for the promises to resolve.
  fixture.whenStable().then(finished=>{
    console.log('Making the assertion !!');
    expect(logSpy).toHaveBeenCalled();
    done();
  });
});
</code>```

Make sure you see the log of { 'done': true } before the log of Making the assertion !!. But since you have a promise resolving within a promise, the following might fix it.

```<code>fit("should log processed request", async done => { // check out the async keyword here
  const mainSerivce = TestBed.get(MainService)
  const logService = TestBed.get(LogService)
  spyOn(mainService, "process").and.returnValue(Promise.resolve({id:34,value:64, rank:310));
  const logSpy = spyOn(logSerivce, "log").and.returnValue(Promise.resolve({'done':true}));
  // call the function that will resolve promises
  component.process();
  // when stable waits for the promises to resolve.
  await fixture.whenStable();
  await fixture.whenStable();
  expect(logSpy).toHaveBeenCalled();
  done();
});
</code>```

Body:
I am getting tired of trying to figure out the following out. Basically I have a method in my component that calls a service which is mocked. Once that service completes, another service does some logging activities, which is also mocked. But my test fails saying the logging service wasn't called:

       process(){
       const that : any = this;
      this.mainService.process().then(result=>{

       return result;

    }).then(result=>{
      //log the operation now after doing some checkups
      let checkups = ""
      that.logService.log('process',result, checkups).then(logged=>{
        console.log(logged)

      }).catch(err=>console.log(err)
    }).catch(err=>console.log(err);

    }

Before we go ahead, doing Promise.all() isn't match of an option due to the logic in place to do checkups. Now to the testing bit:

fit("should log processed request", done => {
  const mainSerivce = TestBed.get(MainService)
  const logService = TestBed.get(LogService)
  spyOn(mainService, "process").and.returnValue(Promise.resolve({id:34,value:64, rank:310));
  const logSpy = spyOn(logSerivce, "log").and.returnValue(Promise.resolve({'done':true}))

  fixture.whenStable().then(finished=>{

    component.process();

    expect(logSpy).toHaveBeenCalled();
    done();

  })

});

expect(logSpy).toHaveBeenCalled();

fails now but I can see in my console the result of the mock {'done':true} or whatever value I pass is shown, meaning it was mocked and called (?). What am I missing exactly since the methods appear to have been mocked and logged correctly in the console.

Body:
It seems to me you have to wait for the promises to resolve before asserting for it, try:

fit("should log processed request", done => {
  const mainSerivce = TestBed.get(MainService)
  const logService = TestBed.get(LogService)
  spyOn(mainService, "process").and.returnValue(Promise.resolve({id:34,value:64, rank:310));
  const logSpy = spyOn(logSerivce, "log").and.returnValue(Promise.resolve({'done':true}));
  // call the function that will resolve promises
  component.process();
  // whenStable waits for the promises to resolve.
  fixture.whenStable().then(finished=>{
    console.log('Making the assertion !!');
    expect(logSpy).toHaveBeenCalled();
    done();
  });
});

Make sure you see the log of { 'done': true } before the log of Making the assertion !!. But since you have a promise resolving within a promise, the following might fix it.

fit("should log processed request", async done => { // check out the async keyword here
  const mainSerivce = TestBed.get(MainService)
  const logService = TestBed.get(LogService)
  spyOn(mainService, "process").and.returnValue(Promise.resolve({id:34,value:64, rank:310));
  const logSpy = spyOn(logSerivce, "log").and.returnValue(Promise.resolve({'done':true}));
  // call the function that will resolve promises
  component.process();
  // when stable waits for the promises to resolve.
  await fixture.whenStable();
  await fixture.whenStable();
  expect(logSpy).toHaveBeenCalled();
  done();
});


来源: stackexchange

问:
Swift: How to get substring from start to last index of character
I want to learn the best/simplest way to turn a string into another string but with only a subset, starting at the beginning and going to the last index of a character.

For example, convert "www.stackoverflow.com" to "www.stackoverflow".  What code snippet would do that, and being the most swift-like? (I hope this doesn't bring a debate, but I can't find good lesson on how to handle substrings in Swift.

答:
Try this Int-based workaround:

```<code>extension String {
    // start and end is included
    func intBasedSubstring(_ start: Int, _ end: Int) -> String {
        let endOffset: Int = -(count - end - 1)
        let startIdx = self.index(startIndex, offsetBy: start)
        let endIdx = self.index(endIndex, offsetBy: endOffset)
        return String(self[startIdx..<endIdx])
    }
}
</code>```

Note: It's just a practice. It doesn't check the boundary. Modify to suit your needs.

ContentLicense: CC BY-SA 3.0

Body:
Try this Int-based workaround:

extension String {
    // start and end is included
    func intBasedSubstring(_ start: Int, _ end: Int) -> String {
        let endOffset: Int = -(count - end - 1)
        let startIdx = self.index(startIndex, offsetBy: start)
        let endIdx = self.index(endIndex, offsetBy: endOffset)
        return String(self[startIdx..<endIdx])
    }
}

Note: It's just a practice. It doesn't check the boundary. Modify to suit your needs.

ContentLicense: CC BY-SA 4.0


问:
Create row of most frequent value in each dataframe column
CONTEXT

I want to create a top row with the most frequent values of each column.

CURRENT CODE

```<code>df = df.loc[df['Gender'] == 'M']
df = df('Gender').count()
</code>```

DATA SAMPLE

```<code>Gender      Eyes      Hair    Height
  M         Brown     Brown    >6ft
  M         Blue      Blonde   <6ft
  M         Brown     Blonde   <6ft
</code>```

EXPECTED OUTCOME

```<code>Gender      Eyes      Hair    Height
  M         Brown     Blonde    <6ft
</code>```

答:
Check with mode

```<code>df.mode()
  Gender   Eyes    Hair Height
0      M  Brown  Blonde   <6ft
</code>```

Body:
CONTEXT

I want to create a top row with the most frequent values of each column.

CURRENT CODE

df = df.loc[df['Gender'] == 'M']
df = df('Gender').count()

DATA SAMPLE

Gender      Eyes      Hair    Height
  M         Brown     Brown    >6ft
  M         Blue      Blonde   <6ft
  M         Brown     Blonde   <6ft

EXPECTED OUTCOME

Gender      Eyes      Hair    Height
  M         Brown     Blonde    <6ft

Body:
Check with mode

df.mode()
  Gender   Eyes    Hair Height
0      M  Brown  Blonde   <6ft


问:
How to read images from a specific folder?
I have created a group folder in my Xcode project named USER_PHOTO

Then I store some images into that folder.

In my application, I open the camera mode.

How can I save the captured images into the "USER_PHOTO" folder? Also, how can I read all images from the folder?

Please give me ideas to solve these issues. Thanks in advance.

答:
It can be done in the following way,</p>

```<code>NSString *animationFolderName = UIDeviceOrientationIsPortrait(mDeviceOrientation)? @"Portrait_animation":@"Landscape_animation";
    int index = 0;
    NSMutableArray *imagesArray = [[NSMutableArray alloc] init];
    for (index = 1; index <= kMaxAnimationImages; index++)
    {
        NSString *cname = [animationFolderName stringByAppendingFormat:@"/%d.png", index];
        UIImage *img = [UIImage imageNamed:cname];
        if (img)
            [imagesArray addObject:img];
    }
</code>```

Body:
It can be done in the following way,

NSString *animationFolderName = UIDeviceOrientationIsPortrait(mDeviceOrientation)? @"Portrait_animation":@"Landscape_animation";
    int index = 0;
    NSMutableArray *imagesArray = [[NSMutableArray alloc] init];
    for (index = 1; index <= kMaxAnimationImages; index++)
    {
        NSString *cname = [animationFolderName stringByAppendingFormat:@"/%d.png", index];
        UIImage *img = [UIImage imageNamed:cname];
        if (img)
            [imagesArray addObject:img];
    }


答:
It's exactly what the mode function in Pandas does. Assuming your data sample is df, you can obtain your expected output using the following line of code

```<code>df.mode()
</code>```

Title: Create row of most frequent value in each dataframe column

Body:
It's exactly what the mode function in Pandas does. Assuming your data sample is df, you can obtain your expected output using the following line of code

df.mode()


问:
Firebase: Custom claims require my users to log out and log in before taking effect?
When assigned a custom claim, my users in the client have to log out and log in before the claims show on their account. I spent all today trying to figure out why my claims were not setting and it turns out the user has to relog in order for the claim to show LOL rip 5 hours of my day for no reason. Is there anything I can add to make it refresh the users info without them having to relog?</p>

答:
Custom claims may be force refreshed by calling currentUser.getIdToken(true).

From the docs...

Propagate custom claims to the client

After new claims are modified on a user via the Admin SDK, they are propagated to an authenticated user on the client side via the ID token in the following ways:

A user signs in or re-authenticates after the custom claims are modified. The ID token issued as a result will contain the latest claims.

An existing user session gets its ID token refreshed after an older token expires.

An ID token is force refreshed by calling currentUser.getIdToken(true).


问:
What is the correct moment to create dynamodb table on .netcore project
I'm starting a new API in .Net core. This project is using AWS DynamoDB. I would like this project to take care of the creation of the tables.

What is the best moment to create the table?

I don't need to verify every time I receive a request if I have the table created or not.

Is the startup class the moment I must create the table?

I'm open to doing it out of the project if it is the best approach.

答: The DynamoDB table creation should be part of the deployment of the API. Doing it in code is not a good idea because the table creation can take several minutes. </p>


问:
Codename One Aligning components vertically over multiple rows
I have a container that has within it some unknown number of components (which are actually also containers in which I have overridden calcPreferredSize to make them a consistent size).  Since the number of components may be > the number that can fit on a single line, there may be an overflow to line 2, etc.

I am using FlowLayout on the outer container, which works fine for one row.  But the second row is offset.

So where I want:

|.X.X.X.|

|.X.X.X.|

I actually get:

|.X.X.X.|

|X.X.X..|

where X is the component, dots are spacing, and |  are the sides of the container.

What is the best way to do this?  I assume FlowLayout does this because the left margin for the first element on row 2 is actually applied on the top row, so there is no margin remaining to push it away from the container border.

I have tried GridLayout, but I find the rightmost X component on each row is expanded beyond the preferred size I have set.

答:
Row spanning is the problem here. If you override calcPreferredSize you're effectively blocking the spanning from working properly as we need to allocate space for each component horizontally and vertically.

The problem is that layout is determined and then line breaks might need more space (vertically) but layout was already set. The only solution for this is reflow (or multiple-passes) which we don't "really" support as it includes a serious performance overhead.

Grid layout will set everything to the same size. A table layout might be a better choice. I suggest not overriding calcPreferredSize() and instead just using 50% as the width of the table columns.


问:
Python regular expressions ignoring commas in a long number
I am trying to figure out how to ignore commas in a long number, some the numbers are in the 0's to 10 million so I need something that can capture numbers from 0 to 10,000,000 and ignore commas.  I am not sure how to go about this.   Thanks </p>

```<code>#Here is the pattern that contains the information I am looking for
Median Sales Price\n$1,417,000

# here is my pattern
median_sales_price = re.findall(r'\bMedian Sales Price\n\$(\d*\,\d*\,\d*)',data)
</code>```

答:
You can't. One capture captures one continuous substring. Capture with commas, then filter the commas out later.

```<code>median_sales_price = [re.sub(',', '', price) for price in
    re.findall(r'\bMedian Sales Price\n\$([\d,]+)', data)]
</code>```

Body:
I am trying to figure out how to ignore commas in a long number, some the numbers are in the 0's to 10 million so I need something that can capture numbers from 0 to 10,000,000 and ignore commas.  I am not sure how to go about this.   Thanks

#Here is the pattern that contains the information I am looking for
Median Sales Price\n$1,417,000

# here is my pattern
median_sales_price = re.findall(r'\bMedian Sales Price\n\$(\d*\,\d*\,\d*)',data)

Body:
You can't. One capture captures one continuous substring. Capture with commas, then filter the commas out later.

median_sales_price = [re.sub(',', '', price) for price in
    re.findall(r'\bMedian Sales Price\n\$([\d,]+)', data)]


问:
Typescript Class - Should a private field be in the constructor?
I've written a singleton class in Typescript to avoid having the keep declaring/creating the same OktaAuth object namely: new OktaAuth({ issuer: appConfig.OKTA_ORG_URL }).

(By the way I did this as I assume this the best way to write such things)

So at the moment my code looks like

```<code>export class OktaAuthorisation {
    private static instance: OktaAuthorisation;

    private constructor() {
    }

    static getInstance(): OktaAuthorisation {
        if (!OktaAuthorisation.instance) {
            OktaAuthorisation.instance = new OktaAuthorisation();
        }

        return OktaAuthorisation.instance;
    }

    private authClient = new OktaAuth({ issuer: appConfig.OKTA_ORG_URL });

    async accessToken(): Promise<OktaAccessToken> {
        return await this.authClient.tokenManager.get("accessToken");
    }

    async getOktaUserEmail() {
        let oktaUser: OktaUser = await this.authClient.token.getUserInfo(await this.accessToken());

        return oktaUser.email
    }
}
</code>```

My question is where should the line private authClient = new OktaAuth({ issuer: appConfig.OKTA_ORG_URL }); live? Where it is in the above or should I be setting that in the constructor?

I'm not sure whether it would be recreated each time I use it - which I do like:

```<code>const oktaAuth = OktaAuthorisation.getInstance();

const myUser = await oktaAuth.getOktaUserEmail()
</code>```

Also, in general is the tidiest way to go about this? And if I don't use the constructor for anything I guess I can remove it?

Thanks.

答:
Where possible, set class state in the field declarations not in the constructor. This helps because:

it avoids accidental null/undefined errors,

it helps human readers quickly determine default values,

it decreases the number of lines of code.

Whether you set class state in the field declaration or in the constructor, that state will only be recreated each time you create a new instance of the class not each time you access the field.

All that being said... whether you set class state in the field declarations or in the constructor, the TypeScript compiler output sets it in the constructor (by default). That is because mainstream JavaScript/ECMAScript does not support field declarations (though plans to soon). Here is an example from the playground with the TypeScript on the left and the compiler output on the right.

Body:
I've written a singleton class in Typescript to avoid having the keep declaring/creating the same OktaAuth object namely: new OktaAuth({ issuer: appConfig.OKTA_ORG_URL }).

(By the way I did this as I assume this the best way to write such things)

So at the moment my code looks like

export class OktaAuthorisation {
    private static instance: OktaAuthorisation;

    private constructor() {
    }

    static getInstance(): OktaAuthorisation {
        if (!OktaAuthorisation.instance) {
            OktaAuthorisation.instance = new OktaAuthorisation();
        }

        return OktaAuthorisation.instance;
    }

    private authClient = new OktaAuth({ issuer: appConfig.OKTA_ORG_URL });

    async accessToken(): Promise<OktaAccessToken> {
        return await this.authClient.tokenManager.get("accessToken");
    }

    async getOktaUserEmail() {
        let oktaUser: OktaUser = await this.authClient.token.getUserInfo(await this.accessToken());

        return oktaUser.email
    }
}

My question is where should the line private authClient = new OktaAuth({ issuer: appConfig.OKTA_ORG_URL }); live? Where it is in the above or should I be setting that in the constructor?

I'm not sure whether it would be recreated each time I use it - which I do like:

const oktaAuth = OktaAuthorisation.getInstance();

const myUser = await oktaAuth.getOktaUserEmail()

Also, in general is the tidiest way to go about this? And if I don't use the constructor for anything I guess I can remove it?

Thanks.


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

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

My project is just 4 files:

index.html

app.js

notaryWebApp.js

sha256

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

The main interact with blockchain is notaryWebApp.js file:

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

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

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

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

since now, thank you all!

答:
thnks so much. Worked that way:</p>

```<code>function notary_init() {

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

    ethereum.enable()
.then(function (accounts) {
  // You now have an array of accounts!
  // Currently only ever one:
  // ['0xFDEa65C8e26263F6d9A1B5de9555D2931A33b825']
})
.catch(function (error) {
  // Handle error. Likely the user rejected the login
  console.error(error)
})

    //contract abi
     abi =[...]
    contract = new web3.eth.Contract(abi, address);
};
</code>```

Title: Interacting with Metamask web3.js

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

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

My project is just 4 files:

index.html

app.js

notaryWebApp.js

sha256

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

The main interact with blockchain is notaryWebApp.js file:

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

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

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

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

since now, thank you all!

Body:
thnks so much. Worked that way:

function notary_init() {

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

    ethereum.enable()
.then(function (accounts) {
  // You now have an array of accounts!
  // Currently only ever one:
  // ['0xFDEa65C8e26263F6d9A1B5de9555D2931A33b825']
})
.catch(function (error) {
  // Handle error. Likely the user rejected the login
  console.error(error)
})

    //contract abi
     abi =[...]
    contract = new web3.eth.Contract(abi, address);
};


问:
Email validation using javascript with a custom message below the input field
I have a simple form with email input field. I would like to get an error below the field when the email input is left empty which my code already does.
However, I would like a message to appear below the input field if the email is not validated. Currently, I can only get the error message (email is invalid) at all times.
So basically a user either leaves the input empty and get an error message (you must type in an email), or does not provide a valid email then gets a another error message.

const email = document.querySelector('.email');
const form = document.querySelector('.form');
const emailMessage = document.querySelector('.empty-email-message');
const errorEmail = document.querySelector('.invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    // setTimeout(() => {
    //   emailMessage.style.display = 'none';
    // }, 1000);
    emailMessage.innerHTML = 'You must type in an email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});

if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value)) {
  errorEmail.value = '';
} else {
  errorEmail.value = 'email is invalid';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form class="form" id="form" action="submit">
    <input class="email" type="email" />
    <button class="submit-email" type="submit">Go</button>
    <!-- dont use id -->
    <p class="empty-email-message"></p>
    <p class="invalid-email-message"></p>
</form></code>```

答:
You have mentioned the condition outside of the function scope, so make it inside
and check first whether the email has value,

If it has value then check for regex match.

If regex match doesn't match with input provided, then display the error message,
errorEmail.textContent = 'email is invalid'; and makue sure that you are making the empty error message to '' empty string..

If you want to make the validation on user input, then you can follow this approach https://codepen.io/Maniraj_Murugan/pen/WNvxQPq

Note:

Unless you are replacing HTML element, don't use innerHTML, instead use textContent if you are going to replace only text.

const email = document.querySelector('.email');
const form = document.querySelector('.form');
const emailMessage = document.querySelector('.empty-email-message');
const errorEmail = document.querySelector('.invalid-email-message');

form.addEventListener('submit', e => {
    if(email.value){
    const regexMatch = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value);
    if (regexMatch) {
          errorEmail.textContent = '';
        } else {
          e.preventDefault();
          errorEmail.textContent = 'email is invalid';
          emailMessage.textContent = "";
        }
    } else {
      e.preventDefault();
      emailMessage.textContent = 'You must type in an email';
      errorEmail.textContent = "";
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form" id="form" action="submit">
    <input class="email" type="email" />
    <button class="submit-email" type="submit">Go</button>
    <!-- dont use id -->
    <p class="empty-email-message"></p>
    <p class="invalid-email-message"></p>
 </form></code>```

Body:
I have a simple form with email input field. I would like to get an error below the field when the email input is left empty which my code already does.
However, I would like a message to appear below the input field if the email is not validated. Currently, I can only get the error message (email is invalid) at all times.
So basically a user either leaves the input empty and get an error message (you must type in an email), or does not provide a valid email then gets a another error message.

const email = document.querySelector('.email');
const form = document.querySelector('.form');
const emailMessage = document.querySelector('.empty-email-message');
const errorEmail = document.querySelector('.invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    // setTimeout(() => {
    //   emailMessage.style.display = 'none';
    // }, 1000);
    emailMessage.innerHTML = 'You must type in an email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});

if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value)) {
  errorEmail.value = '';
} else {
  errorEmail.value = 'email is invalid';
}

 <form class="form" id="form" action="submit">
    <input class="email" type="email" />
    <button class="submit-email" type="submit">Go</button>

</form>

Body:
You have mentioned the condition outside of the function scope, so make it inside
and check first whether the email has value,

If it has value then check for regex match.

If regex match doesn't match with input provided, then display the error message,
errorEmail.textContent = 'email is invalid'; and makue sure that you are making the empty error message to '' empty string..

If you want to make the validation on user input, then you can follow this approach https://codepen.io/Maniraj_Murugan/pen/WNvxQPq

Note:

Unless you are replacing HTML element, don't use innerHTML, instead use textContent if you are going to replace only text.

const email = document.querySelector('.email');
const form = document.querySelector('.form');
const emailMessage = document.querySelector('.empty-email-message');
const errorEmail = document.querySelector('.invalid-email-message');

form.addEventListener('submit', e => {
    if(email.value){
    const regexMatch = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value);
    if (regexMatch) {
          errorEmail.textContent = '';
        } else {
          e.preventDefault();
          errorEmail.textContent = 'email is invalid';
          emailMessage.textContent = "";
        }
    } else {
      e.preventDefault();
      emailMessage.textContent = 'You must type in an email';
      errorEmail.textContent = "";
    }
});

<form class="form" id="form" action="submit">
    <input class="email" type="email" />
    <button class="submit-email" type="submit">Go</button>
    <!-- dont use id -->
    <p class="empty-email-message"></p>
    <p class="invalid-email-message"></p>
 </form>


问:
Recreating Pinterest UI Flutter
How do I implement the long press peek and select an item with animation do with flutter I tried using onLongPressStart to track the long press and now how do I animate the icons popping up and hiding them when finger is released select them when hovering above them.

And also how do make the Pinterest bottom navigation

答:
The same animation already implemented with other naive solutions. The code logic is very similar. I suggest that you can take a look at it first and then implement it on Flutter.

eg.
https://github.com/brucetoo/PinterestView

Title: Recreating Pinterest UI Flutter


问:
Rectangle is not moving
I am trying to code a rectangle moving but it is not working and I do not understand why. I created a class for the rectangle and gave the parameters value. Then I drew the rectangle. I am trying to add the value of 5 to the rectangle's x but nothing is happening. </p>

```<code>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var width = 50;

class Rectangle{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  draw(){
    ctx.beginPath();
    ctx.rect(this.x, this.y, width, height);
    ctx.fillStyle = "0095DD";
    ctx.fill();
    ctx.closePath();
  }
}

function movingRectangle(){
  var rect = new Rectangle(canvas.width/2 - width/2, 300);
  rect.draw();
  rect.x += 5;
}

function draw(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  movingRectangle();
}

var interval = setInterval(draw, 10);
</code>```

答:
You're recreating rect on each movingRectangle() call, effectively resetting its position to the initial value.

Move this:

```<code>var rect = new Rectangle(canvas.width/2 - width/2, 300);
</code>```

Out of the movingRectangle() function - you only need to create the Rectangle instance once.

Title: Rectangle is not moving

Body:
I am trying to code a rectangle moving but it is not working and I do not understand why. I created a class for the rectangle and gave the parameters value. Then I drew the rectangle. I am trying to add the value of 5 to the rectangle's x but nothing is happening.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var width = 50;

class Rectangle{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  draw(){
    ctx.beginPath();
    ctx.rect(this.x, this.y, width, height);
    ctx.fillStyle = "0095DD";
    ctx.fill();
    ctx.closePath();
  }
}

function movingRectangle(){
  var rect = new Rectangle(canvas.width/2 - width/2, 300);
  rect.draw();
  rect.x += 5;
}

function draw(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  movingRectangle();
}

var interval = setInterval(draw, 10);

Body:
You're recreating rect on each movingRectangle() call, effectively resetting its position to the initial value.

Move this:

var rect = new Rectangle(canvas.width/2 - width/2, 300);

Out of the movingRectangle() function - you only need to create the Rectangle instance once.


问:
SQL query to check if a select operation returns rows
I need to check if the select operation I am performing is returning any rows or not.

Can someone please help me with this.

I am working on a shell script so I cannot save it in a variable and check. I need to check on the fly. I know I can use the count switch. But can someone help me with the syntax?

For example, I need to check:

```<code>--Now this query should return some data
select * from error_repository_BKP partition(part_maxval);
</code>```

答:
```<code>select count(*) from error_repository_BKP partition(part_maxval);
</code>```

<p>??</p>

Body:
I need to check if the select operation I am performing is returning any rows or not.

Can someone please help me with this.

I am working on a shell script so I cannot save it in a variable and check. I need to check on the fly. I know I can use the count switch. But can someone help me with the syntax?

For example, I need to check:

--Now this query should return some data
select * from error_repository_BKP partition(part_maxval);

Body:
select count(*) from error_repository_BKP partition(part_maxval);

??


问:
How to make the blend mode MULTIPLY not make all the image black in p5js
I have this codepen: https://codepen.io/giorgiomartini/pen/OjQpKd?editors=0010

Where I paint some shapes and some text, now I want to add a radial overlay between the shapes and the text.

So I created a drawgradient function and call it between the shapes and the text:

function drawGradient() {
  blendMode(MULTIPLY)
  for (let r = canvasX; r > 0; --r) {
    let lightnes = map(r,0,canvasX,255,0)
    fill(0, 0, lightnes)
    ellipse(0, 0, r*1.8, r*2)
  }
}
```

<p>I want this gradient to have a multiply blend mode, so that it makes the whole thing a bit darker where the pixels are darker in the gradient.</p>

<p>But all i get is a full black overlay...</p>

<p>In photoshop or gimp, if you add a black and white radial gradient with a multiply blend mode it makes the background darker where there are darker pixles in the gradient.. but here in p5js it just makes everything black.</p>

<p>any ideas what am I doing wrong?</p>

<p>This is the mouseClicked function, and at the bottom, you can see the gradient function being called:</p>

<pre class="lang-javascript prettyprint-override"><code>function mouseClicked(){

    blendMode(BLEND)
    const colsArray = randomColor({luminosity: 'light', format: 'hsl',count: 4})
    background(colsArray[0])
    translate(width/2, height/2)

    //////////////////////////////////////////////////////////////////          amt              initial       range
    const arrayOfRandomNumsOfFirstProbStepX  = createArrayOfRandomNums(amtOfSpotsInFirstProb,startProbStep,firstProbStepX)
    const arrayOfRandomNumsOfFirstProbStepY  = createArrayOfRandomNums(amtOfSpotsInFirstProb,startProbStep,firstProbStepY)

    const arrayOfRandomNumsOfSecondProbStepX = createArrayOfRandomNums(amtOfSpotsInSecondProb,startProbStep,secondProbStepX)
    const arrayOfRandomNumsOfSecondProbStepY = createArrayOfRandomNums(amtOfSpotsInSecondProb,startProbStep,secondProbStepY)

    drawLinesAtRandomspots(6,random(50),colsArray)

    //args => element, arrayOfRandomNumsOfProbStepX, arrayOfRandomNumsOfProbStepY, elmntSizeMin, elmntSizeMax,rot, colors
    drawElmntsOnSomeProbabilityStep('ellipse',arrayOfRandomNumsOfFirstProbStepX, arrayOfRandomNumsOfFirstProbStepY , 10, 80, true, colsArray )
    drawElmntsOnSomeProbabilityStep('rect',arrayOfRandomNumsOfSecondProbStepX, arrayOfRandomNumsOfSecondProbStepY, 5, 30, true, colsArray)
   drawGradient()
     addText()

}
</code>```

答: Placing clear() at the beginning of the draw() function will clear the pixels within a buffer. This lets you use blendMode(MULTIPLY) without your overlapping shapes turning black after the first few frames.

Body:
I have this codepen: https://codepen.io/giorgiomartini/pen/OjQpKd?editors=0010

Where I paint some shapes and some text, now I want to add a radial overlay between the shapes and the text.

So I created a drawgradient function and call it between the shapes and the text:

function drawGradient() {
  blendMode(MULTIPLY)
  for (let r = canvasX; r > 0; --r) {
    let lightnes = map(r,0,canvasX,255,0)
    fill(0, 0, lightnes)
    ellipse(0, 0, r*1.8, r*2)
  }
}

I want this gradient to have a multiply blend mode, so that it makes the whole thing a bit darker where the pixels are darker in the gradient.

But all i get is a full black overlay...

In photoshop or gimp, if you add a black and white radial gradient with a multiply blend mode it makes the background darker where there are darker pixles in the gradient.. but here in p5js it just makes everything black.

any ideas what am I doing wrong?

This is the mouseClicked function, and at the bottom, you can see the gradient function being called:

function mouseClicked(){

    blendMode(BLEND)
    const colsArray = randomColor({luminosity: 'light', format: 'hsl',count: 4})
    background(colsArray[0])
    translate(width/2, height/2)

    //////////////////////////////////////////////////////////////////          amt              initial       range
    const arrayOfRandomNumsOfFirstProbStepX  = createArrayOfRandomNums(amtOfSpotsInFirstProb,startProbStep,firstProbStepX)
    const arrayOfRandomNumsOfFirstProbStepY  = createArrayOfRandomNums(amtOfSpotsInFirstProb,startProbStep,firstProbStepY)

    const arrayOfRandomNumsOfSecondProbStepX = createArrayOfRandomNums(amtOfSpotsInSecondProb,startProbStep,secondProbStepX)
    const arrayOfRandomNumsOfSecondProbStepY = createArrayOfRandomNums(amtOfSpotsInSecondProb,startProbStep,secondProbStepY)

    drawLinesAtRandomspots(6,random(50),colsArray)

    //args => element, arrayOfRandomNumsOfProbStepX, arrayOfRandomNumsOfProbStepY, elmntSizeMin, elmntSizeMax,rot, colors
    drawElmntsOnSomeProbabilityStep('ellipse',arrayOfRandomNumsOfFirstProbStepX, arrayOfRandomNumsOfFirstProbStepY , 10, 80, true, colsArray )
    drawElmntsOnSomeProbabilityStep('rect',arrayOfRandomNumsOfSecondProbStepX, arrayOfRandomNumsOfSecondProbStepY, 5, 30, true, colsArray)
   drawGradient()
     addText()

}


问:
Cant find a button in react testing library with getByDisplayValueText
I have a simple component that has 3 buttons. i want to find the buttons and simulate click by using react testing library. problem is that I cant find the first button in my test by below code.
considering I have a button with
value="All"
and the other button has "completed" as a text. I can find the second button (i can't change my code for the first button)

```<code>document.body.innerHTML = `
<button value="All" />
<button>Completed<button/>
<button>in progress<button/>
<span>multi-test</span>
<div>multi-test</div>`;

screen.debug();
screen.debug(screen.getByDisplayValueText('All'));  ---> doesn't work
screen.debug(screen.getByText('Completed'));  ----> works
</code>```

答:
screen.debug(screen.getByDisplayValueText('All'));  ---> doesnt work

You have .getByDisplayValueText and should have .getByDisplayValue (without "Text").

https://testing-library.com/docs/dom-testing-library/api-queries

```<code>getByDisplayValue(
  container: HTMLElement,
  value: TextMatch,
  options?: {
    exact?: boolean = true,
    normalizer?: NormalizerFn,
  }): HTMLElement
</code>```

Body:
I have a simple component that has 3 buttons. i want to find the buttons and simulate click by using react testing library. problem is that I cant find the first button in my test by below code.
considering I have a button with
value="All"
and the other button has "completed" as a text. I can find the second button (i can't change my code for the first button)

document.body.innerHTML = `
<button value="All" />
<button>Completed<button/>
<button>in progress<button/>
multi-test

multi-test
`;

screen.debug();
screen.debug(screen.getByDisplayValueText('All'));  ---> doesn't work
screen.debug(screen.getByText('Completed'));  ----> works

Body:
screen.debug(screen.getByDisplayValueText('All'));  ---> doesnt work

You have .getByDisplayValueText and should have .getByDisplayValue (without "Text").

https://testing-library.com/docs/dom-testing-library/api-queries

getByDisplayValue(
  container: HTMLElement,
  value: TextMatch,
  options?: {
    exact?: boolean = true,
    normalizer?: NormalizerFn,
  }): HTMLElement


问:
Loading local html with WKWebView
I need to load html/CSS/Javascript files that have been previously downloaded from a server. I can do this on Android and iOS using UIWebView, but fails when enabling WKWebView.

I did some research and seems that there is a workaround to get this working. From this post, the solution could be this:

```<code> if Url.scheme == "file" as String {
     wkWebView.loadFileURL(Url, allowingReadAccessTo: Url)
}
else {
     let request = URLRequest.init(url: Url, cachePolicy:.reloadIgnoringLocalCacheData, timeoutInterval:60)
     wkWebView.load(request)
}
</code>```

Is this implemented on Codename One? Or there is a better way to get WKWebView working with downloaded html files?

答:
This is implemented in Codename One if you enable WKWebView and use a file system storage URL it should work seamlessly see:
https://github.com/codenameone/CodenameOne/blob/master/Ports/iOSPort/nativeSources/IOSNative.m#L2490

Title: Loading local html with WKWebView

Body:
I need to load html/CSS/Javascript files that have been previously downloaded from a server. I can do this on Android and iOS using UIWebView, but fails when enabling WKWebView.

I did some research and seems that there is a workaround to get this working. From this post, the solution could be this:

 if Url.scheme == "file" as String {
     wkWebView.loadFileURL(Url, allowingReadAccessTo: Url)
}
else {
     let request = URLRequest.init(url: Url, cachePolicy:.reloadIgnoringLocalCacheData, timeoutInterval:60)
     wkWebView.load(request)
}

Is this implemented on Codename One? Or there is a better way to get WKWebView working with downloaded html files?


问:
Azure Function APP [Expose functions key]
I'm trying to create an Authentication function for user login, but my idea is to expose the "function keys" of the rest of the functions. So the mobile app can grave the keys to star calling the rest of the functions.

Is a way to do this?

答:
If you want to manage Azure function key, you can use the Key management API to implement it. For more details, please refer to document

Get function key

```<code>GET https://<functionappname>.azurewebsites.net/admin/functions/{functionname}/keys

</code>```

Create Function key

```<code>PUT https://<functionappname>.azurewebsites.net/admin/functions/{functionname}/keys/{keyname}

{
  "name": "keyname",
  "value" : "keyvalue"
}
</code>```

The code

```<code>tring clientId = "client id";
     string secret = "secret key";
     string tenant = "tenant id";
     var functionName ="functionName";
     var webFunctionAppName = "functionApp name";
     string resourceGroup = "resource group name";
     var credentials = new AzureCredentials(new ServicePrincipalLoginInformation { ClientId = clientId, ClientSecret = secret}, tenant, AzureEnvironment.AzureGlobalCloud);
     var azure = Azure
              .Configure()
              .Authenticate(credentials)
              .WithDefaultSubscription();

     var webFunctionApp = azure.AppServices.FunctionApps.GetByResourceGroup(resourceGroup, webFunctionAppName);
     var ftpUsername = webFunctionApp.GetPublishingProfile().FtpUsername;
     var username = ftpUsername.Split('\\').ToList()[1];
     var password = webFunctionApp.GetPublishingProfile().FtpPassword;
     var base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{password}"));
     var apiUrl = new Uri($"https://{webFunctionAppName}.scm.azurewebsites.net/api");
     var siteUrl = new Uri($"https://{webFunctionAppName}.azurewebsites.net");
     string JWT;
     using (var client = new HttpClient())
      {
         client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Auth}");

         var result = client.GetAsync($"{apiUrl}/functions/admin/token").Result;
         JWT = result.Content.ReadAsStringAsync().Result.Trim('"'); //get  JWT for call funtion key
       }
// get key
     using (var client = new HttpClient())
     {
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + JWT);
        var key = await client.GetAsync($"{siteUrl}/admin/functions/{functionName}/keys").Result.Content.ReadAsStringAsync();
      }

// create key
var map = new Dictionary<string, string>();
            map.Add("name", "keyName");
            map.Add("value", "keyVaule");

            using (var client = new HttpClient()) {

                var content = new StringContent(JsonConvert.SerializeObject(map), System.Text.Encoding.UTF8, "application/json");
                await client.PutAsync($"{siteUrl}/admin/functions/{functionname}/keys/{keyname}", content);

            }

</code>```

Besides, according to my research, we also can use Azure REST API to manage Azure function key. For more details, please refer to

a. Create Azure function key

b. List Azure function key

Body:
If you want to manage Azure function key, you can use the Key management API to implement it. For more details, please refer to document

Get function key

GET https://<functionappname>.azurewebsites.net/admin/functions/{functionname}/keys

Create Function key

PUT https://<functionappname>.azurewebsites.net/admin/functions/{functionname}/keys/{keyname}

{
  "name": "keyname",
  "value" : "keyvalue"
}

The code

tring clientId = "client id";
     string secret = "secret key";
     string tenant = "tenant id";
     var functionName ="functionName";
     var webFunctionAppName = "functionApp name";
     string resourceGroup = "resource group name";
     var credentials = new AzureCredentials(new ServicePrincipalLoginInformation { ClientId = clientId, ClientSecret = secret}, tenant, AzureEnvironment.AzureGlobalCloud);
     var azure = Azure
              .Configure()
              .Authenticate(credentials)
              .WithDefaultSubscription();

     var webFunctionApp = azure.AppServices.FunctionApps.GetByResourceGroup(resourceGroup, webFunctionAppName);
     var ftpUsername = webFunctionApp.GetPublishingProfile().FtpUsername;
     var username = ftpUsername.Split('\\').ToList()[1];
     var password = webFunctionApp.GetPublishingProfile().FtpPassword;
     var base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{password}"));
     var apiUrl = new Uri($"https://{webFunctionAppName}.scm.azurewebsites.net/api");
     var siteUrl = new Uri($"https://{webFunctionAppName}.azurewebsites.net");
     string JWT;
     using (var client = new HttpClient())
      {
         client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Auth}");

         var result = client.GetAsync($"{apiUrl}/functions/admin/token").Result;
         JWT = result.Content.ReadAsStringAsync().Result.Trim('"'); //get  JWT for call funtion key
       }
// get key
     using (var client = new HttpClient())
     {
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + JWT);
        var key = await client.GetAsync($"{siteUrl}/admin/functions/{functionName}/keys").Result.Content.ReadAsStringAsync();
      }

// create key
var map = new Dictionary<string, string>();
            map.Add("name", "keyName");
            map.Add("value", "keyVaule");

            using (var client = new HttpClient()) {

                var content = new StringContent(JsonConvert.SerializeObject(map), System.Text.Encoding.UTF8, "application/json");
                await client.PutAsync($"{siteUrl}/admin/functions/{functionname}/keys/{keyname}", content);

            }

Besides, according to my research, we also can use Azure REST API to manage Azure function key. For more details, please refer to

a. Create Azure function key

b. List Azure function key


问:
Running artisan commands along with npm commands
I am trying to find a simple way to run npm dev and php artisan serve using a single command. I have created a new script within package.json and run the command via npm run start. This may come as obvious to most, but I thought it was an interesting idea that obviously can be expanded upon.

答:
Here is the command below in case anyone has this idea down the road and doesn't want to spend an hour looking into it like I did.</p>

```<code>"scripts": {
    "start": "(php artisan serve) & npm run dev"
}
</code>```

Body:
Here is the command below in case anyone has this idea down the road and doesn't want to spend an hour looking into it like I did.

"scripts": {
    "start": "(php artisan serve) & npm run dev"
}


问:
Concatenate two numpy arrays so that index order keeps the same?
Assume I have two numpy arrays as follows:

```<code>{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}
</code>```

Now I want to replace each array with the ID at the front, i.e. the values in array 0 become 0 and in array 1 become 1, then both arrays should be merged, whereby the index order must be correct.
I.e. desired output:

```<code>array([1, 0, 1, 0, 1, 0, 0 ,0])
</code>```

But that's what I get:

```<code>np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])
</code>```

(Each array contains only unique values, if this helps.)

How can this be done?

答:
Something like this?</p>

```<code>d = {0: array([ 2, 4, 8, 9, 12], dtype=int64),
     1: array([ 1, 3, 5], dtype=int64)}

(np.concatenate([d[0],d[1]]).argsort(kind="stable")>=len(d[0])).view(np.uint8)
# array([1, 0, 1, 0, 1, 0, 0, 0], dtype=uint8)
</code>```

Body:
Assume I have two numpy arrays as follows:

{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}

Now I want to replace each array with the ID at the front, i.e. the values in array 0 become 0 and in array 1 become 1, then both arrays should be merged, whereby the index order must be correct.
I.e. desired output:

array([1, 0, 1, 0, 1, 0, 0 ,0])

But that's what I get:

np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])

(Each array contains only unique values, if this helps.)

How can this be done?

Body:
Something like this?

d = {0: array([ 2, 4, 8, 9, 12], dtype=int64),
     1: array([ 1, 3, 5], dtype=int64)}

(np.concatenate([d[0],d[1]]).argsort(kind="stable")>=len(d[0])).view(np.uint8)
# array([1, 0, 1, 0, 1, 0, 0, 0], dtype=uint8)


问:
Getting the maximum value of vertical scroll using jQuery
This is my view code I used jQuery it works and I didn't have any problem until I have changed the screen resolution it stops working. I know where is the problem but I can't solve it look at the code :

```<code>@model PNUBOOKIR.Models.ProductModels
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>

<title>Index</title>
<script src="@Url.Content("~/Scripts/jquery.js")" type="text/javascript"></script>
<script type="text/javascript">
    var endRun = false;
    var PageNO = 1;
    $(window).scroll(function () {
        if ((($("#container").outerHeight() - 796) == ($(this).scrollTop())) && (!endRun)) {
            endRun = true;
            Load();
        }
    });

    $(document).ready(function () {
        Load();
        return false;
    });

    function Load() {
        var BtnShowMore = document.getElementById("BtnShowMore");
        BtnShowMore.innerHTML = "Loading...";
        $.ajax({ type: "Post",
            url: "Product" + "/" + "GetHomeEventAjax",
            data: "{" + "PageNO" + ":" + PageNO + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function succ(data, states) {
                if (states == "success") {
                    if (data.Content != null) {
                        var EventListArea = document.getElementById("result");
                        $('#result > tbody:last').append(data.Content);
                        PageNO = PageNO + 50;
                        BtnShowMore.innerHTML = "More";
                        endRun = false;
                    }
                    else BtnShowMore.innerHTML = "Loading is complete";
                }
            },
            error: function err(result) { alert(result.responseText); }
        });
    }
</script>
</head>
<body>
    <div id="container">
        <table cellpadding="4" cellspacing="2" border="1" style="width: 450px; direction: rtl;"
            id="result">
            <tbody>
                <tr>
                    <th>کد کالا</th>
                    <th>نام کتاب</th>
                    <th>ناشر</th>
                </tr>
            </tbody>
        </table>
        <a style="width: 200px" id="BtnShowMore">
            Load</a>
    </div>
</body>
</html>
</code>```

In the scroll event script I need to found out what is the maximum value of vertical scroll so I get the container outer-Height but is wasn't exactly the maximum value it is 796px greater than it in the 1280x1024 screen resolution it can be different in different screen resolution setting. I need some help what should be instead of "796" number.

答:
Try:

```<code>$("#container").attr({ scrollTop: $("#container").attr("scrollHeight") });
</code>```

Starting from JQuery 1.9.1, you'll need:

```<code>$("#container").scrollTop($("#container").prop("scrollHeight"));
</code>```

Body:
This is my view code I used jQuery it works and I didn't have any problem until I have changed the screen resolution it stops working. I know where is the problem but I can't solve it look at the code :

@model PNUBOOKIR.Models.ProductModels
@{
    Layout = null;
}

<!DOCTYPE html>

<title>Index</title>

                    کد کالا
                    نام کتاب
                    ناشر

            Load

In the scroll event script I need to found out what is the maximum value of vertical scroll so I get the container outer-Height but is wasn't exactly the maximum value it is 796px greater than it in the 1280x1024 screen resolution it can be different in different screen resolution setting. I need some help what should be instead of "796" number.

Body:
Try:

$("#container").attr({ scrollTop: $("#container").attr("scrollHeight") });

Starting from JQuery 1.9.1, you'll need:

$("#container").scrollTop($("#container").prop("scrollHeight"));


问:
How to load an instance in class based views using form_valid
I'm trying to build a form that automatically fills some fields in a class based create view that lets logged in users create a Job. However, I can't seem to find the correct way of doing this for fields that aren't the user (eg. request.user).

So the create view is trying to get a company_name from the logged in user, company_name field belongs to a model called Company. Each Company has an owner with a foreign key to the User model. All the reuest I've tried so far have led to a 'WSGIRequest' error.

So far I've tried to request:
company_name
user.company_name
company.company_name
company
user

I don't understand how these requests work, I have seen examples for getting the logged in users name and I'm not familiar how to do this otherwise.

Please can someone help me understand how this works and how I should be doing this?

I'm using Django 2.2 with python 3.6

Auth Models:

```<code>class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    phone_number = models.CharField(max_length=15)
    email = models.EmailField(max_length=250, unique=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    objects = UserManager()

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'

    def __str__(self):
        return self.first_name

    def get_absolute_url(self):
        return "/users/%i/" % self.pk

class Company(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=100, unique=True)
    company_address = models.CharField(max_length=100, unique=True)
    company_website = models.URLField(blank=True, null=True)
    company_verified = models.BooleanField(default=False)

    def __str__(self):
        return self.company_name
</code>```

View

```<code>class JobCreateView(LoginRequiredMixin, CreateView):
    model = Job
    form_class = JobForm
    template_name = 'jobs/job_create.html'

def form_valid(self, form):
    form.instance.company_name = self.request.user
    form.instance.job_reference = self.request.job.pk
    return super(JobCreateView, self).form_valid(form)

def get_success_url(self):
    return reverse('jobs:job_details', kwargs={'pk': self.object.pk})
</code>```

Other Model:

```<code>class Job(models.Model):
JOB_TYPE = (
    ('1', 'Service'),
    ('2', 'Repair'),
    ('3', 'Quotation'),
    ('4', 'Consultation'),
    ('5', 'Report'),
    ('6', 'Design'),
)

ACCOUNT_TYPE = (
    ('1', 'Existing Customer'),
    ('2', 'Charge to Account'),
    ('3', 'New Customer'),
    ('4', 'Pre-Paid/C.O.D'),
    ('5', 'Issued and Acc App'),
)

company_name = models.ForeignKey(Company, related_name='jobs', verbose_name="Company Name", on_delete=models.CASCADE)
job_reference = models.CharField(max_length=50, blank=False)
contact_person = models.CharField(max_length=50)
contact_number = models.IntegerField()
contact_person_email = models.EmailField(max_length=100, blank=True, null=True)
site_address = models.CharField(max_length=100)
job_type = models.CharField(choices=JOB_TYPE, max_length=50, default='1')
account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=50, default='1')
job_details = models.CharField(max_length=1000)
created = models.DateTimeField(default=now, blank=True)

def __str__(self):
    return str(self.company_name)

def get_absolute_url(self):
    return reverse('jobs:detail', kwargs={'pk': self.pk})
</code>```

答:
For anyone trying to solve a problem like this, the answer is;

Views:

```<code>class JobDocketCreate(CreateView):
    model = JobDocket
    form_class = JobDocketForm
    template_name = 'jobs/job_docket_create.html'

def form_valid(self, form):
    form.instance.technician = self.request.user
    form.instance.job = Job.objects.get(pk=self.kwargs['job_pk'])
    print(form.instance.job)
    print(form.instance.technician)
    context = {'job_pk':self.kwargs['job_pk']}
    return super(JobDocketCreate, self).form_valid(form)

def get_context_data(self, **kwargs):
    context = super(JobDocketCreate, self).get_context_data(**kwargs)
    context['job_pk'] = self.kwargs['job_pk']
    return context

def get_success_url(self):
    return reverse('jobs:my_job_dockets')
</code>```

Form action in View:

```<code>action="{% url 'jobs:create_job_docket' job_pk %}"
</code>```

Body:
I'm trying to build a form that automatically fills some fields in a class based create view that lets logged in users create a Job. However, I can't seem to find the correct way of doing this for fields that aren't the user (eg. request.user).

So the create view is trying to get a company_name from the logged in user, company_name field belongs to a model called Company. Each Company has an owner with a foreign key to the User model. All the reuest I've tried so far have led to a 'WSGIRequest' error.

So far I've tried to request:
company_name
user.company_name
company.company_name
company
user

I don't understand how these requests work, I have seen examples for getting the logged in users name and I'm not familiar how to do this otherwise.

Please can someone help me understand how this works and how I should be doing this?

I'm using Django 2.2 with python 3.6

Auth Models:

class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    phone_number = models.CharField(max_length=15)
    email = models.EmailField(max_length=250, unique=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    objects = UserManager()

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'

    def __str__(self):
        return self.first_name

    def get_absolute_url(self):
        return "/users/%i/" % self.pk

class Company(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=100, unique=True)
    company_address = models.CharField(max_length=100, unique=True)
    company_website = models.URLField(blank=True, null=True)
    company_verified = models.BooleanField(default=False)

    def __str__(self):
        return self.company_name

View

class JobCreateView(LoginRequiredMixin, CreateView):
    model = Job
    form_class = JobForm
    template_name = 'jobs/job_create.html'

def form_valid(self, form):
    form.instance.company_name = self.request.user
    form.instance.job_reference = self.request.job.pk
    return super(JobCreateView, self).form_valid(form)

def get_success_url(self):
    return reverse('jobs:job_details', kwargs={'pk': self.object.pk})

Other Model:

class Job(models.Model):
JOB_TYPE = (
    ('1', 'Service'),
    ('2', 'Repair'),
    ('3', 'Quotation'),
    ('4', 'Consultation'),
    ('5', 'Report'),
    ('6', 'Design'),
)

ACCOUNT_TYPE = (
    ('1', 'Existing Customer'),
    ('2', 'Charge to Account'),
    ('3', 'New Customer'),
    ('4', 'Pre-Paid/C.O.D'),
    ('5', 'Issued and Acc App'),
)

company_name = models.ForeignKey(Company, related_name='jobs', verbose_name="Company Name", on_delete=models.CASCADE)
job_reference = models.CharField(max_length=50, blank=False)
contact_person = models.CharField(max_length=50)
contact_number = models.IntegerField()
contact_person_email = models.EmailField(max_length=100, blank=True, null=True)
site_address = models.CharField(max_length=100)
job_type = models.CharField(choices=JOB_TYPE, max_length=50, default='1')
account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=50, default='1')
job_details = models.CharField(max_length=1000)
created = models.DateTimeField(default=now, blank=True)

def __str__(self):
    return str(self.company_name)

def get_absolute_url(self):
    return reverse('jobs:detail', kwargs={'pk': self.pk})

Body:
For anyone trying to solve a problem like this, the answer is;

Views:

class JobDocketCreate(CreateView):
    model = JobDocket
    form_class = JobDocketForm
    template_name = 'jobs/job_docket_create.html'

def form_valid(self, form):
    form.instance.technician = self.request.user
    form.instance.job = Job.objects.get(pk=self.kwargs['job_pk'])
    print(form.instance.job)
    print(form.instance.technician)
    context = {'job_pk':self.kwargs['job_pk']}
    return super(JobDocketCreate, self).form_valid(form)

def get_context_data(self, **kwargs):
    context = super(JobDocketCreate, self).get_context_data(**kwargs)
    context['job_pk'] = self.kwargs['job_pk']
    return context

def get_success_url(self):
    return reverse('jobs:my_job_dockets')

Form action in View:

action="{% url 'jobs:create_job_docket' job_pk %}"


问:
windows explorer cant see files written by c# app File.WriteAllLines
I am having a strange problem that I am unable to access files written by my c# application. My app basically does :

```<code>var file = "C:\\Users\\Public\\Documents\\something.txt";
List<string> content = new List<string> { "one thing", "two things" };
Console.WriteLine(System.IO.File.Exists(file));
System.IO.File.WriteAllLines(file, content);
Console.WriteLine(System.IO.File.Exists(file));
</code>```

The first time I run the app, the output is

```<code>False
True
</code>```

Yet I cannot see the written file in Windows Explorer (Windows 10). I get no exceptions attempting to write the file. The second time I run the app, the output is :

```<code>True
True
</code>```

According to my application the file is being written however Windows thinks differently. As a sanity check I spun up a second app that opens a dialog using OpenFileDialog. When I run that, I am able to see my written files! Windows explorer still cannot. Attached is a screenshot of windows explorer and my openfiledialog side by side.

If I go to notepad and browse for the file I cannot see it or manually type in the name.

Its been a long week of work, there must be some dumb explanation...? Help! :-)

Screenshot - windows explorer on left, c# app open dialog on right :
https://imgur.com/a/8ZTDIe6

答:
per @BACON 's suggestion in the comments above I discovered that after disabling the Comodo anti-virus I am able to write and see my files.

I believe the software is running my app or either only allowing IO from my app in some kind of container. I need to figure out how to grant my apps proper permissions through the anti-virus software, but that was the culprit.

Body:
I am having a strange problem that I am unable to access files written by my c# application. My app basically does :

var file = "C:\\Users\\Public\\Documents\\something.txt";
List<string> content = new List<string> { "one thing", "two things" };
Console.WriteLine(System.IO.File.Exists(file));
System.IO.File.WriteAllLines(file, content);
Console.WriteLine(System.IO.File.Exists(file));

The first time I run the app, the output is

False
True

Yet I cannot see the written file in Windows Explorer (Windows 10). I get no exceptions attempting to write the file. The second time I run the app, the output is :

True
True

According to my application the file is being written however Windows thinks differently. As a sanity check I spun up a second app that opens a dialog using OpenFileDialog. When I run that, I am able to see my written files! Windows explorer still cannot. Attached is a screenshot of windows explorer and my openfiledialog side by side.

If I go to notepad and browse for the file I cannot see it or manually type in the name.

Its been a long week of work, there must be some dumb explanation...? Help! :-)

Screenshot - windows explorer on left, c# app open dialog on right :
https://imgur.com/a/8ZTDIe6


答:
I managed to do a short example, based in your code, and leaving the Rectangle constructor outside:

```<code>function movingRectangle(){
    let x = rect ? rect.x + 5 : canvas.width/2 - width/2;
  if (!rect)
    rect = new Rectangle(x, 300);
  rect.x = x;
  rect.draw();
}
</code>```

https://jsfiddle.net/nicoavn/vc254q0a/4/

Title: Rectangle is not moving

Body:
I am trying to code a rectangle moving but it is not working and I do not understand why. I created a class for the rectangle and gave the parameters value. Then I drew the rectangle. I am trying to add the value of 5 to the rectangle's x but nothing is happening.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var width = 50;

class Rectangle{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  draw(){
    ctx.beginPath();
    ctx.rect(this.x, this.y, width, height);
    ctx.fillStyle = "0095DD";
    ctx.fill();
    ctx.closePath();
  }
}

function movingRectangle(){
  var rect = new Rectangle(canvas.width/2 - width/2, 300);
  rect.draw();
  rect.x += 5;
}

function draw(){
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  movingRectangle();
}

var interval = setInterval(draw, 10);

Body:
I managed to do a short example, based in your code, and leaving the Rectangle constructor outside:

function movingRectangle(){
    let x = rect ? rect.x + 5 : canvas.width/2 - width/2;
  if (!rect)
    rect = new Rectangle(x, 300);
  rect.x = x;
  rect.draw();
}

https://jsfiddle.net/nicoavn/vc254q0a/4/


问:
Applying a function n times
I am trying to apply a function to a value n times.

Currently, I have

```<code>let rec n_times (f, n, v) =
 if n > 0 then
  n_times f n-1 (f v)
 else
  v
</code>```

For some reason I keep getting an error that says

```<code>This expression has type 'a but an expression was expected of type 'a * int * 'b
The type variable 'a occurs inside 'a * int * 'b
</code>```

I saw a few posts that address the same problem I am working on but none of them gets the same error.

答:
In the first line of your code: you say "I declare a function called n_times that take a triplet (f, n, v) so one argument" then at the call site (third line) you give 3 arguments.

To fix this: write let rec n_times f n v = on line 1 or n_times (f, n-1, (f v)) on line 3.

Title: Applying a function n times

Body:
I am trying to apply a function to a value n times.

Currently, I have

let rec n_times (f, n, v) =
 if n > 0 then
  n_times f n-1 (f v)
 else
  v

For some reason I keep getting an error that says

This expression has type 'a but an expression was expected of type 'a * int * 'b
The type variable 'a occurs inside 'a * int * 'b

I saw a few posts that address the same problem I am working on but none of them gets the same error.


答:
You have defined the function to take a 3-tuple of values. So when you call it recursively you need to supply a 3-tuple:</p>

```<code>n_times (f, n - 1, f v)
</code>```

Title: Applying a function n times

Body:
You have defined the function to take a 3-tuple of values. So when you call it recursively you need to supply a 3-tuple:

n_times (f, n - 1, f v)


问:
java out of memory then exit
I have a piece of software that has to analyze big files. Constraining the input or giving infinite memory is not an option, so I have to live with flying OOMEs. Because the OOME only kills the Thread, my software runs in some crappy state.

From outside everything looks okay because the process is running but on the inside it's braindead.

I would like to pull the plug on it. But how can I do this?

Catching a OOME does not guranteee that the next line of code will be executed. e.g System.exit(9). So the JVM has to notice OOME and destory itself.

Is their some vm option for this?

答:
When you get an OOME you can be very low on memory and logging doesn't always work.  One way around this is to have a shutdown method which holds some memory it doesn't release until its shutting down.

e.g.

```<code> private static byte[] lastResort = new byte[256*1024];
 public static void handleOOME(OutOfMemoryError oome) {
     lastResort = null;
     try {
        LOG.fatal("Dying after ", oome);
     } finally {
        System.exit(-1);
     }
  }
</code>```

Title: java out of memory then exit

Body:
When you get an OOME you can be very low on memory and logging doesn't always work.  One way around this is to have a shutdown method which holds some memory it doesn't release until its shutting down.

e.g.

 private static byte[] lastResort = new byte[256*1024];
 public static void handleOOME(OutOfMemoryError oome) {
     lastResort = null;
     try {
        LOG.fatal("Dying after ", oome);
     } finally {
        System.exit(-1);
     }
  }


问:
Json object array
```<code>.ajax({
  cache: false,
    url: '/Dashboard/ListofNames',
    data: {
        charSearch: txtboxvalue
    },
    success: function (res){
        var obj = JSON.parse(res); //this object contains 1 index which is 0.
        var parseObj = JSON.parse(obj[0].JsonResult) // This line is working i successfully gets the data from index 0
        var parseObj2 = JSON.parse(obj[1].JsonResult) //This is not working because index 1 is not existing, what i want is instead of getting an undefined exception, i want to set the index 1 into an empty string or whatever solution that i wont get any undefined exception.

    }
});
</code>```

Any suggestion would really help me thanks.

答:
```<code>Considering your JSON.parse of object given the response as this object.
let res = [
    { name: "john", id: 1, JsonResult: "json-stringified-object-or-string" }
]
JSON.parse(res[0] ? res[0].JsonResult : '""');
JSON.parse(res[1] ? res[1].JsonResult : '""');
</code>```

Title: Json object array

Body:
.ajax({
  cache: false,
    url: '/Dashboard/ListofNames',
    data: {
        charSearch: txtboxvalue
    },
    success: function (res){
        var obj = JSON.parse(res); //this object contains 1 index which is 0.
        var parseObj = JSON.parse(obj[0].JsonResult) // This line is working i successfully gets the data from index 0
        var parseObj2 = JSON.parse(obj[1].JsonResult) //This is not working because index 1 is not existing, what i want is instead of getting an undefined exception, i want to set the index 1 into an empty string or whatever solution that i wont get any undefined exception.

    }
});

Any suggestion would really help me thanks.


问:
Swift -What is a SCNCamera's Definition and Purpose
I can't find a good explanation of what a SCNCamera is and it's purpose. This is Apple's definition:

A set of camera attributes that can be attached to a node to provide a
  point of view for displaying the scene.

This definition isn't clear because I set up the scene and added a SCNNode without attaching a SCNCamera to it. The point of view from the device's camera shows the SCNNode at the location I positioned it at with no problem and the scene is displayed fine.

What is the difference between the device's camera and a SCNCamera?

What is the benefit of attaching a SCNCamera to a SCNNode vs not using one?

If I have multiple SCNNodes (all detached no hierarchy amongst each other) does each node need it's own SCNCamera?

If I have multiple SCNNodes in a hierarchy (parent node with child nodes) does each node need it's own SCNCamera or does just the parent node?

```<code>lazy var sceneView: ARSCNView = {
    let sceneView = ARSCNView()
    sceneView.translatesAutoresizingMaskIntoConstraints = false
    sceneView.delegate = self
    return sceneView
}()

let configuration = ARWorldTrackingConfiguration()

override func viewDidLoad() {
    super.viewDidLoad()

    // pin sceneView to the view

    let material = SCNMaterial()
    material.diffuse.contents = UIImage(named: "earth")

    let plane = SCNPlane(width: 0.33, height: 0.33)
    plane.materials = [material]
    plane.firstMaterial?.isDoubleSided = true

    let myNode = SCNNode(geometry: plane)
    myNode.name = "earth"
    myNode.position = SCNVector3(0.0, 0.6, -0.9)

    sceneView.scene.rootNode.addChildNode(myNode)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    sceneView.session.run(configuration, options: [])
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillAppear(animated)

    sceneView.session.pause()
    sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
}
</code>```

答:
In SceneKit, the SCNCamera represents the point of view from which the user sees a scene. Ray Wenderlich provides a good explanation:

Think back to the analogy of the movie set from Chapter 1: to shoot a
  scene, you’d position a camera looking at the scene and the resulting
  image of that scene would be from the camera’s perspective.

Scene Kit
  works in a similar fashion; the position of the node that contains the
  camera determines the point of view from which you view the scene.

You do not need to have a SCNCamera for each node. You should only need to have one camera for each angle that you want to show, or even just one. You can move one camera throughout the scene using its parent's position property.

It looks like you're working with ARKit, which behaves a little differently. When using an ARSCNView, as opposed to a non-AR SCNView, you get the following behvior:

The view automatically renders the live video feed from the device camera as the scene background.

The world coordinate system of the view's SceneKit scene directly responds to the AR world coordinate system established by the session
  configuration.

The view automatically moves its SceneKit camera to match the real-world movement of the device.

You do not need to worry as much about the scene's camera in this case, as it is automatically being controlled by the system so that it matches the device's movement for AR.

For more detail, see Apple's documentation on SCNCamera: SCNCamera - SceneKit

Body:
I can't find a good explanation of what a SCNCamera is and it's purpose. This is Apple's definition:

A set of camera attributes that can be attached to a node to provide a
  point of view for displaying the scene.

This definition isn't clear because I set up the scene and added a SCNNode without attaching a SCNCamera to it. The point of view from the device's camera shows the SCNNode at the location I positioned it at with no problem and the scene is displayed fine.

What is the difference between the device's camera and a SCNCamera?

What is the benefit of attaching a SCNCamera to a SCNNode vs not using one?

If I have multiple SCNNodes (all detached no hierarchy amongst each other) does each node need it's own SCNCamera?

If I have multiple SCNNodes in a hierarchy (parent node with child nodes) does each node need it's own SCNCamera or does just the parent node?

lazy var sceneView: ARSCNView = {
    let sceneView = ARSCNView()
    sceneView.translatesAutoresizingMaskIntoConstraints = false
    sceneView.delegate = self
    return sceneView
}()

let configuration = ARWorldTrackingConfiguration()

override func viewDidLoad() {
    super.viewDidLoad()

    // pin sceneView to the view

    let material = SCNMaterial()
    material.diffuse.contents = UIImage(named: "earth")

    let plane = SCNPlane(width: 0.33, height: 0.33)
    plane.materials = [material]
    plane.firstMaterial?.isDoubleSided = true

    let myNode = SCNNode(geometry: plane)
    myNode.name = "earth"
    myNode.position = SCNVector3(0.0, 0.6, -0.9)

    sceneView.scene.rootNode.addChildNode(myNode)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    sceneView.session.run(configuration, options: [])
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillAppear(animated)

    sceneView.session.pause()
    sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
}


问:
no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
Log Cat:

```<code>no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
</code>```

code:

```<code>    102) public String getID(String note){
    103)      SQLiteDatabase db = this.getWritableDatabase();
    104)      String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
    105)      db.rawQuery(query,null);
    106)      return query;
    107) }
</code>```

I do have a column name hey in my Database
Database Picture

答:
Your query should look like this

```<code>SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = 'hey'
</code>```

Let me know if it helps

Body:
Log Cat:

no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey

code:

    102) public String getID(String note){
    103)      SQLiteDatabase db = this.getWritableDatabase();
    104)      String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
    105)      db.rawQuery(query,null);
    106)      return query;
    107) }

I do have a column name hey in my Database
Database Picture

Body:
Your query should look like this

SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = 'hey'

Let me know if it helps


问:
iOS Certificate Pinning and Amazon Certificate Manager
I can't find good information regarding certificate pinning in iOS and Amazon Certificate Manager.

They recommend you don't pin against an ACM certificate.

https://docs.aws.amazon.com/acm/latest/userguide/acm-bestpractices.html#best-practices-pinning

We recommend that your application not pin an ACM Certificate

The reason they don't recommend it is that:

To renew a certificate, ACM generates a new public-private key pair.

Instead, they recommend:

If you're using a public certificate, pin your application to all available Amazon root certificates.

I understand why not to pin to an ACM Certificate - because you will have to release updates with new certificates risking possible bricking of clients. You also can't pin against the public key because it will change.

What I don't understand is how pinning against only the root certificates is ok? Will it still prevent man in the middle attacks? How is this more secure?

Can someone explain it better?

答:
It would not be more secured to pin against the root certificate. I think what the Amazon documentation trying to recommend is a way that would not break your network connection in the case that when the certificate expires and renews.

Here's the quote from this website explaining the different kinds of certificate pinning:
https://carvesystems.com/news/cert_pin/

Leaf Cert: A leaf cert is the top level cert in a certificate chain.
  Pinning a leaf certs brings us to almost complete certainty that the
  certificate matches. However, if you cycle your leaf certs often,
  updates need to roll out fairly frequently to make sure your
  customer’s app continues to work.

Intermediate Cert: The intermediate cert lives between the leaf and
  root cert. In this case, pinning against the intermediate cert, you’re
  putting your trust in the intermediate certificate authority.
  Therefore, you can update your server’s leaf cert more often, as the
  validation of certs occurs on the intermediate cert.

Root Cert: Finally, the root cert comes from the trusted certificate
  authority. Pinning the root cert alone puts trust in the root cert
  authority, as well as all intermediaries that the root cert authority
  trusts.

Hope this helps


答:
I got the answer to my question from within this answer. Basically in ARKit using ARSCNView the camera comes from sceneView.pointOfView but in SceneKit you need to create a camera to get the camera pov (code below).

Getting the camera node

To get the camera node, it depends if you're using SCNKit, ARKit, or other framework. Below are examples for ARKit and SceneKit.

With ARKit, you have ARSCNView to render the 3D objects of an SCNScene overlapping the camera content. You can get the camera node from ARSCNView's pointOfView property:

```<code>let cameraNode = sceneView.pointOfView
</code>```

For SceneKit, you have an SCNView that renders the 3D objects of an SCNScene. You can create camera nodes and position them wherever you want, so you'd do something like:

```<code>let scnScene = SCNScene()
// (Configure scnScene here if necessary)
scnView.scene = scnScene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(0, 5, 10)  // For example
scnScene.rootNode.addChildNode(cameraNode)
</code>```

Once a camera node has been setup, you can access the current camera in the same way as ARKit:

```<code>let cameraNode = scnView.pointOfView
</code>```

Title: Swift -What is a SCNCamera's Definition and Purpose

Body:
I got the answer to my question from within this answer. Basically in ARKit using ARSCNView the camera comes from sceneView.pointOfView but in SceneKit you need to create a camera to get the camera pov (code below).

Getting the camera node

To get the camera node, it depends if you're using SCNKit, ARKit, or other framework. Below are examples for ARKit and SceneKit.

With ARKit, you have ARSCNView to render the 3D objects of an SCNScene overlapping the camera content. You can get the camera node from ARSCNView's pointOfView property:

let cameraNode = sceneView.pointOfView

For SceneKit, you have an SCNView that renders the 3D objects of an SCNScene. You can create camera nodes and position them wherever you want, so you'd do something like:

let scnScene = SCNScene()
// (Configure scnScene here if necessary)
scnView.scene = scnScene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(0, 5, 10)  // For example
scnScene.rootNode.addChildNode(cameraNode)

Once a camera node has been setup, you can access the current camera in the same way as ARKit:

let cameraNode = scnView.pointOfView


问:
Is it possible to add Android Thread Annotations to existing library methods?
I have not found any source which indicates that Android Annotations, like @UiThread, @WorkerThread, can be applied to library codes, for example, ActiveAndroid.

I want to enforce that all ActiveAndroid related code to be called in worker thread, but ActiveAndroid is library code, is there a way to add annotations to existing libraries?

答: You could create a function that use the library you want to use and put the AndroidAnnotation on the function you will have created.</p>


问:
Browser animations using multiple Javascript source files
I have two Javascript files, both setup to generate an image from base64. The first script, called static.js looks like this.

var element = new Image();
  element.src = "data:image/png;base64,..."
  document.body.appendChild(element);
```

<p>I can embed the script into my website using the following code and the image appears with no issues. (To see the full code, including the base64, go here)</p>

<pre class="lang-html prettyprint-override"><code><body>
  <script src="./static.js"></script>
</body>
</code>```

Similarly, I have a second script that I found on CodePen by takashi that converts a base64 image into an animated glitch. I was able to take that code and modify it using the same base64 image as the static code but with the glitch (apologies, but the code is really long even without my base64 image so I just included the link). The code for my image can be seen here. Note that while CodePen shows the HTML and Javascript on the same page, I broke mine out into separate files.

Again, if I embed the script into the webpage, it works with no issues.

```

<p>The issue I have is that neither code has a dedicated javascript <code>function()</code> attribute, so the only way they work is if I embed the code as indicated above. Using the static image for brevity, if I add a dedicated function:</p>

<pre class="lang-js prettyprint-override"><code>function isStatic() {
var element = new Image();
  element.src = "data:image/png;base64,..."
  document.body.appendChild(element);
}
</code>```

and then try a callback,

```

<p>the image does not appear on the webpage any longer. The same happens on the glitched image when I try to wrap the whole script into a function and then try a callback.</p>

<p>The main reason I was trying to turn each JS file into functions is so that I could combine the two into one file (which I did), and then using an embedded script like</p>

<pre class="lang-html prettyprint-override"><code><script>
  setInterval(function(isStatic) {
    // This will be executed every 9 seconds
  }, 9000);

  setInterval(function(isGlitch) {
    // This will be executed every 2 seconds
  }, 2000);
</script>
</code>```

to create an image that switches from static to glitched, and then back again.

Since I was not able to successfully turn each JS file/script into it's own function, what I am trying to figure out is if there is a better way to combine my Static and Glitch JS scripts into one, or if there is a way that I can set the webpage to call each script file individually in such a way that creates a loop of the static and glitched images switching back and forth.

I have scoured the Google-webs looking for anything that describes what I am trying to do visually, but have absolutely nothing to show for it but a whole heap of scripts on various ways to make text and/or images glitch (just not how to make them start out static and then glitch randomly). Essentially what I would like to do with my two scripts is

 - run static image (script or call) for *x* seconds (120-180 seconds)
 - run glitched image (script or call) for *x* seconds (3-5 seconds)
 - reset (loop) the sequence
```

in order to create the appearance of a single image that seems to randomly glitch for unknown reasons.

答:
Edited answer after your clarifying comment:

Your code uses a library called p5, which is controlling your animation timing, so my previous answer is irrelevant. If you just want to change how often the glitch occurs, you already have almost everything you need. The glitch.js file already has a flag to turn the glitch on and off (this.throughFlag). And, it already has a slight random delay between glitches on line 226:

```<code>setTimeout(() => {
                this.throughFlag = true;
            }, floor(random(40, 400)));
</code>```

The second parameter to setTimeout controls how long to wait beofre setting this.throughFlag to true (and thus starting to glitch again).
You just need to make this number longer. To do so, you want to make the time on the timeout longer, ie by multiplying it by some constant, which I'll call delayFactor.

```<code>const delayFactor = 10;
setTimeout(() => {
                this.throughFlag = true;
            }, delayFactor * floor(random(40, 400)));
</code>```

See it in action here.

Body:
I have two Javascript files, both setup to generate an image from base64. The first script, called static.js looks like this.

var element = new Image();
  element.src = "data:image/png;base64,..."
  document.body.appendChild(element);

I can embed the script into my website using the following code and the image appears with no issues. (To see the full code, including the base64, go here)

Similarly, I have a second script that I found on CodePen by takashi that converts a base64 image into an animated glitch. I was able to take that code and modify it using the same base64 image as the static code but with the glitch (apologies, but the code is really long even without my base64 image so I just included the link). The code for my image can be seen here. Note that while CodePen shows the HTML and Javascript on the same page, I broke mine out into separate files.

Again, if I embed the script into the webpage, it works with no issues.

The issue I have is that neither code has a dedicated javascript function() attribute, so the only way they work is if I embed the code as indicated above. Using the static image for brevity, if I add a dedicated function:

function isStatic() {
var element = new Image();
  element.src = "data:image/png;base64,..."
  document.body.appendChild(element);
}

and then try a callback,

the image does not appear on the webpage any longer. The same happens on the glitched image when I try to wrap the whole script into a function and then try a callback.

The main reason I was trying to turn each JS file into functions is so that I could combine the two into one file (which I did), and then using an embedded script like

to create an image that switches from static to glitched, and then back again.

Since I was not able to successfully turn each JS file/script into it's own function, what I am trying to figure out is if there is a better way to combine my Static and Glitch JS scripts into one, or if there is a way that I can set the webpage to call each script file individually in such a way that creates a loop of the static and glitched images switching back and forth.

I have scoured the Google-webs looking for anything that describes what I am trying to do visually, but have absolutely nothing to show for it but a whole heap of scripts on various ways to make text and/or images glitch (just not how to make them start out static and then glitch randomly). Essentially what I would like to do with my two scripts is

 - run static image (script or call) for *x* seconds (120-180 seconds)
 - run glitched image (script or call) for *x* seconds (3-5 seconds)
 - reset (loop) the sequence

in order to create the appearance of a single image that seems to randomly glitch for unknown reasons.

Body:
Edited answer after your clarifying comment:

Your code uses a library called p5, which is controlling your animation timing, so my previous answer is irrelevant. If you just want to change how often the glitch occurs, you already have almost everything you need. The glitch.js file already has a flag to turn the glitch on and off (this.throughFlag). And, it already has a slight random delay between glitches on line 226:

setTimeout(() => {
                this.throughFlag = true;
            }, floor(random(40, 400)));

The second parameter to setTimeout controls how long to wait beofre setting this.throughFlag to true (and thus starting to glitch again).
You just need to make this number longer. To do so, you want to make the time on the timeout longer, ie by multiplying it by some constant, which I'll call delayFactor.

const delayFactor = 10;
setTimeout(() => {
                this.throughFlag = true;
            }, delayFactor * floor(random(40, 400)));

See it in action here.