问:
Android studio, open a file , continuously write and then close
I have code that is generating data every second and displaying onscreen.
This all works fine but I want to create a log file of all the data to analyze later.

I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file

```<code>  String data= reading1","+reading2+","+time +"/n";
        try {
            FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
            out.write(data.getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
</code>```

I would prefer to have the file open when the start button is clicked.

```<code>if ( v.getId() == R.id.start ){
                // checks which button is clicked
                Log.d("dennis", "Scan working"); //logs the text
                // open a file
                try {
                    FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
</code>```

but when it comes to closing the file, no options for .close() appear when out is typed

```<code>if ( v.getId() == R.id.stop ){
                // checks which button is clicked

                out. // no valid options appear
                messageValue.setText(R.string.stopButtonText);// changes the hallo world text
                readNoRead=false;

            }
</code>```

Does all the open/write/close need to be together or is it possible to

```<code>***open file***
-----
Cycle through all the data
-----
***Close file***
</code>```

答:
It is definitely possible to open, process and close a file all in one block without closing the file.

Your out variable is not showing any method suggestions because it has not been defined in that block. Change the line

```<code>FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
</code>```

to

```<code>out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
</code>```

and then add FileOutputStream out; to a line above the first if statement (outside of the block).

You may want to also look into 'try-catch-finally', or 'try with resources' as options for closing files in a try-catch block.

Body:
I have code that is generating data every second and displaying onscreen.
This all works fine but I want to create a log file of all the data to analyze later.

I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file

  String data= reading1","+reading2+","+time +"/n";
        try {
            FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
            out.write(data.getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();

I would prefer to have the file open when the start button is clicked.

if ( v.getId() == R.id.start ){
                // checks which button is clicked
                Log.d("dennis", "Scan working"); //logs the text
                // open a file
                try {
                    FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

but when it comes to closing the file, no options for .close() appear when out is typed

if ( v.getId() == R.id.stop ){
                // checks which button is clicked

                out. // no valid options appear
                messageValue.setText(R.string.stopButtonText);// changes the hallo world text
                readNoRead=false;

            }

Does all the open/write/close need to be together or is it possible to

***open file***
-----
Cycle through all the data
-----
***Close file***

Body:
It is definitely possible to open, process and close a file all in one block without closing the file.

Your out variable is not showing any method suggestions because it has not been defined in that block. Change the line

FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);

to

out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);

and then add FileOutputStream out; to a line above the first if statement (outside of the block).

You may want to also look into 'try-catch-finally', or 'try with resources' as options for closing files in a try-catch block.


来源: stackexchange

答:
You should store a link to your FileOutputStream on top level in your class.

Example to your code:

```<code>FileOutputStream out;

void clickStart() {
    if (v.getId() == R.id.start){
        // checks which button is clicked
        Log.d("dennis", "Scan working"); //logs the text
        // open a file
        try {
            out = openFileOutput("data.csv", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
}

void writeData() {
    String data= reading1+","+reading2+","+time +"/n";
    try {
        out.write(data.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

void clickStop() {
    if (v.getId() == R.id.stop) {
        try {
            out.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
        messageValue.setText(R.string.stopButtonText);// changes the hello world text
            readNoRead=false;
        }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Android studio, open a file , continuously write and then close

Body:
You should store a link to your FileOutputStream on top level in your class.

Example to your code:

FileOutputStream out;

void clickStart() {
    if (v.getId() == R.id.start){
        // checks which button is clicked
        Log.d("dennis", "Scan working"); //logs the text
        // open a file
        try {
            out = openFileOutput("data.csv", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
}

void writeData() {
    String data= reading1+","+reading2+","+time +"/n";
    try {
        out.write(data.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

void clickStop() {
    if (v.getId() == R.id.stop) {
        try {
            out.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
        messageValue.setText(R.string.stopButtonText);// changes the hello world text
            readNoRead=false;
        }
}


问:
Character segmentation of an image with overlapping parts
I try to segment captcha with overlapping characters, but nothing works at all.

I have read some articles concerning character segmentation and tried to implement an algorithm of summing over pixels by columns and finding local minima which should constitute to start of different character. However, the algorithm doesn't work as characters are very skewed.

Also I tried to erode away overlaps, but it ends up completely eroding significant part of text.

Here are some examples:

```<code>img = cv.imread('captcha.png')
cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
gray = FindDividingCols(gray)
### algo for summing over pixels and finding local minima:
col_pix = np.apply_along_axis(lambda row: np.sum(row)//255, 0, img)
loc_min = np.r_[True, lst[1:] < lst[:-1]] & np.r_[lst[:-1] < lst[1:],True]
</code>```

I would like to know what did I miss, or what other ways there exist to segment?

答: These captchas are deliberately distorted to make it extremely hard for OCR algorithms to read them. If it would be reasonably easy to do, the captcha would be pointless.  Thus, you probably have a problem that requires a lot of research and work to solve; I don't think Stack Overflow will readily provide an answer (and if it does, the captchas will get harder) ;)</p>

Body:
I try to segment captcha with overlapping characters, but nothing works at all.

I have read some articles concerning character segmentation and tried to implement an algorithm of summing over pixels by columns and finding local minima which should constitute to start of different character. However, the algorithm doesn't work as characters are very skewed.

Also I tried to erode away overlaps, but it ends up completely eroding significant part of text.

Here are some examples:

img = cv.imread('captcha.png')
cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
gray = FindDividingCols(gray)
### algo for summing over pixels and finding local minima:
col_pix = np.apply_along_axis(lambda row: np.sum(row)//255, 0, img)
loc_min = np.r_[True, lst[1:] < lst[:-1]] & np.r_[lst[:-1] < lst[1:],True]

I would like to know what did I miss, or what other ways there exist to segment?


问:
Delayed scroll to Div ID when select option is chosen
I'd like to be able to scroll to a particular ID when a select option has been chosen from a drop down list. It seems like it should be extremely simple, however I can't find an example on here that performs how I want it to.

Basically, I have a div near the top of the page

CONTENT

Then lower down the page, a select box:

```<code><select id="variant">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</code>```

What I would like to do, is - once a selection has been made - for the page to scroll back up to the id "mainimage".

If possible, ideally this would happen after a delay of around half a second, and scroll smoothly.

It seems like it should be fairly straightforward, as the page just needs to scroll to the same ID regardless of the selection.

Is this possible with javascript?

Thanks in advance.

答:
Try like this. I have used a jquery inside a javascript function. Hope it helps

function myFunction() {
  var x = document.getElementById("test").value;
  document.getElementById("mainimage").innerHTML = "You selected: " + x;
   setTimeout(function(){
    $('html, body').animate({
    scrollTop: $("#mainimage").offset().top
  }, 2000);
 },500);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="mainimage">welcm to mainimage </p>

<p>Select a new car from the list.</p>
<!-- M using br tags since i dont have content to be placed here .. since to see scrolling we need some content to be here to fill up the page -->
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<select id="test" onchange="myFunction()">
  <option value="Audi">Audi</option>
  <option value="BMW">BMW</option>
  <option value="Mercedes">Mercedes</option>
  <option value="Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p></code>```

Body:
I'd like to be able to scroll to a particular ID when a select option has been chosen from a drop down list. It seems like it should be extremely simple, however I can't find an example on here that performs how I want it to.

Basically, I have a div near the top of the page

CONTENT

Then lower down the page, a select box:

<select id="variant">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

What I would like to do, is - once a selection has been made - for the page to scroll back up to the id "mainimage".

If possible, ideally this would happen after a delay of around half a second, and scroll smoothly.

It seems like it should be fairly straightforward, as the page just needs to scroll to the same ID regardless of the selection.

Is this possible with javascript?

Thanks in advance.

Body:
Try like this. I have used a jquery inside a javascript function. Hope it helps

function myFunction() {
  var x = document.getElementById("test").value;
  document.getElementById("mainimage").innerHTML = "You selected: " + x;
   setTimeout(function(){
    $('html, body').animate({
    scrollTop: $("#mainimage").offset().top
  }, 2000);
 },500);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="mainimage">welcm to mainimage </p>

<p>Select a new car from the list.</p>
<!-- M using br tags since i dont have content to be placed here .. since to see scrolling we need some content to be here to fill up the page -->
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<select id="test" onchange="myFunction()">
  <option value="Audi">Audi</option>
  <option value="BMW">BMW</option>
  <option value="Mercedes">Mercedes</option>
  <option value="Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>


问:
Add user data to Firestore on sign up with Firebase Authentication with Google Sign-In with Swift
I need to store some data in a "users" collection in the Firestore when the user signs in with Google for the first time on my iOS app. I am using Firebase Authentication. The data to be stored is:

id: the user's UID

display name: the user's full name

photoURL: the url of the user's google account

points: this will be 0 when the user first signs in

knownLanguageCodes: this will be an empty array when the user first signs in

At the moment, nothing is saved to the Firestore.
This the section on my app delegate where signing in is handled.

```<code>class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self

        return true
    }

    //Only available on iOS 9 and later
    @available(iOS 9.0, *)
    func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url)
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let authentication = user.authentication else { return }
        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                 accessToken: authentication.accessToken)

        Auth.auth().signIn(with: credential) { (res, err) in

            if let err = err {
                print(err.localizedDescription)
                return
            }

            //I'm not sure if this block of code is in the right place
            let db = Firestore.firestore()
            db.collection("user").document(String((res?.user.uid)!)).setData([
                "id" : String((res?.user.uid)!),
                "displayName" : (res?.user.displayName)!,
                "photoURL" : (res?.user.photoURL)!
                "points" : 0
                "knownLanguageCodes" : []
            ], merge: true)
        }
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {

    }
    //...
</code>```

I'm using SwiftUI for the UI.

答:
Instead of AppDelegate, it is better to do this process in UIViewController on the action of UIButton. I think you are missing GIDSignIn.sharedInstance()?.signIn() and this method should not be called when the app is starting up,
/// (e.g in application:didFinishLaunchingWithOptions:). So you can try the following code for UIButton action

```<code>//rest of your code

if GIDSignIn.sharedInstance()?.hasPreviousSignIn() == true {

   //perform Your action if a user already sign in

} else {

  GIDSignIn.sharedInstance()?.signIn()

}

//rest of your code
</code>```

Body:
I need to store some data in a "users" collection in the Firestore when the user signs in with Google for the first time on my iOS app. I am using Firebase Authentication. The data to be stored is:

id: the user's UID

display name: the user's full name

photoURL: the url of the user's google account

points: this will be 0 when the user first signs in

knownLanguageCodes: this will be an empty array when the user first signs in

At the moment, nothing is saved to the Firestore.
This the section on my app delegate where signing in is handled.

class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self

        return true
    }

    //Only available on iOS 9 and later
    @available(iOS 9.0, *)
    func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url)
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let authentication = user.authentication else { return }
        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                 accessToken: authentication.accessToken)

        Auth.auth().signIn(with: credential) { (res, err) in

            if let err = err {
                print(err.localizedDescription)
                return
            }

            //I'm not sure if this block of code is in the right place
            let db = Firestore.firestore()
            db.collection("user").document(String((res?.user.uid)!)).setData([
                "id" : String((res?.user.uid)!),
                "displayName" : (res?.user.displayName)!,
                "photoURL" : (res?.user.photoURL)!
                "points" : 0
                "knownLanguageCodes" : []
            ], merge: true)
        }
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {

    }
    //...

I'm using SwiftUI for the UI.

Body:
Instead of AppDelegate, it is better to do this process in UIViewController on the action of UIButton. I think you are missing GIDSignIn.sharedInstance()?.signIn() and this method should not be called when the app is starting up,
/// (e.g in application:didFinishLaunchingWithOptions:). So you can try the following code for UIButton action

//rest of your code

if GIDSignIn.sharedInstance()?.hasPreviousSignIn() == true {

   //perform Your action if a user already sign in

} else {

  GIDSignIn.sharedInstance()?.signIn()

}

//rest of your code


问:
how to focus on the tab when alert was active?
for example
I use chrome, I create a new tabs we call it "tabA" in tabA we run the javascript
setTimeout("alert('test')",10000)

in addition create a new tab quickly and browsing some web page, after 10 sec tabA javascript active pop-out the alert message, but i need to click on tabA then I can see the alert message.

Is it possible to auto switch to tabA when it was active? or it was case by security problem, chrome/ Firefox was block this function?

I have try hard to explain my problem
hope you guys will understand

答:
You can switch to a tab you opened from your website, in that way:

```<code>const newTabs = [];
newTabs.push(window.open(<OTHER_TAB_URL>));
newTabs[0].focus();
</code>```

You can put a timeout on the focus or put a condition.

As for changing the active tab from the new tab when the alert pops, sadly, you can't. You can only switch focus to tabs you opened yourself.

Body:
You can switch to a tab you opened from your website, in that way:

const newTabs = [];
newTabs.push(window.open(<OTHER_TAB_URL>));
newTabs[0].focus();

You can put a timeout on the focus or put a condition.

As for changing the active tab from the new tab when the alert pops, sadly, you can't. You can only switch focus to tabs you opened yourself.


问:
Merging two images
I need to merge two images (BufferedImage) in Java. It wouldn't be a problem if there was no transparency. The base image already has some transparency. I want to keep this as it is and apply a "mask" to it, the second image. This second image has no opaque pixels, in fact it's almost completely transparent, just has some less transparent pixels to give some sort of "light effect", like a reflex. Important detail: I don't want to do this on screen, with graphics, I need to obtain a BufferedImage with the resultant merge.

Can anyone help me?
Thanks!

DETAILS: Merge two images maintaining transparency. This is what I need to do.

Note: this Set BufferedImage alpha mask in Java does not do what I need because it does not handle well with the two images having transparency - it modifies first picture transparency.

答:
merge any type of file vertically. </p>

```<code>void mergeFiles(List<String> files, String fileName) {
        int heightTotal = 0;
        int maxWidth = 100;

        List<BufferedImage> images = new ArrayList<>();
        try {
            for (String file : files) {
                BufferedImage image = ImageIO.read(new File(file));
                images.add(image);
            }

        for (BufferedImage bufferedImage : images) {
            heightTotal += bufferedImage.getHeight();
            if (bufferedImage.getWidth() > maxWidth) {
                maxWidth = bufferedImage.getWidth();
            }
        }

        int heightCurr = 0;
        BufferedImage concatImage = new BufferedImage(maxWidth, heightTotal, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = concatImage.createGraphics();
        for (BufferedImage bufferedImage : images) {
            g2d.drawImage(bufferedImage, 0, heightCurr, null);
            heightCurr += bufferedImage.getHeight();
        }

        File compressedImageFile = new File(fileName);
        OutputStream outputStream = new FileOutputStream(compressedImageFile);

        float imageQuality = 0.7f;
        Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("jpeg");

        if (!imageWriters.hasNext())
            throw new IllegalStateException("Writers Not Found!!");

        ImageWriter imageWriter = imageWriters.next();
        ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
        imageWriter.setOutput(imageOutputStream);

        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();

        //Set the compress quality metrics
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality(imageQuality);

        //Created image
        imageWriter.write(null, new IIOImage(concatImage, null, null), imageWriteParam);

        // close all streams
        outputStream.close();
        imageOutputStream.close();
        imageWriter.dispose();
        log.info(" Files Merged");
        } catch (IOException e) {
            log.error("Error while merging files :::"+e);
            throw new RuntimeException(e);
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Merging two images

Body:
merge any type of file vertically.

void mergeFiles(List<String> files, String fileName) {
        int heightTotal = 0;
        int maxWidth = 100;

        List<BufferedImage> images = new ArrayList<>();
        try {
            for (String file : files) {
                BufferedImage image = ImageIO.read(new File(file));
                images.add(image);
            }

        for (BufferedImage bufferedImage : images) {
            heightTotal += bufferedImage.getHeight();
            if (bufferedImage.getWidth() > maxWidth) {
                maxWidth = bufferedImage.getWidth();
            }
        }

        int heightCurr = 0;
        BufferedImage concatImage = new BufferedImage(maxWidth, heightTotal, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = concatImage.createGraphics();
        for (BufferedImage bufferedImage : images) {
            g2d.drawImage(bufferedImage, 0, heightCurr, null);
            heightCurr += bufferedImage.getHeight();
        }

        File compressedImageFile = new File(fileName);
        OutputStream outputStream = new FileOutputStream(compressedImageFile);

        float imageQuality = 0.7f;
        Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("jpeg");

        if (!imageWriters.hasNext())
            throw new IllegalStateException("Writers Not Found!!");

        ImageWriter imageWriter = imageWriters.next();
        ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
        imageWriter.setOutput(imageOutputStream);

        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();

        //Set the compress quality metrics
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality(imageQuality);

        //Created image
        imageWriter.write(null, new IIOImage(concatImage, null, null), imageWriteParam);

        // close all streams
        outputStream.close();
        imageOutputStream.close();
        imageWriter.dispose();
        log.info(" Files Merged");
        } catch (IOException e) {
            log.error("Error while merging files :::"+e);
            throw new RuntimeException(e);
        }
    }


问:
Cell should not highlight automatically when view loads
I am working on TVOS. I have used UICollectionView. When view loads, the first cell is automatically highlighted. As per the requirement, cell should not highlight automatically.</p>

```<code>// MARK: UIFocusEnvironment
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    coordinator.addCoordinatedAnimations({
        if self.isFocused {
            if !self.isList {
                self.titleLabel.isHidden = true
            } else {
                self.titleLabel.isHidden = false
            }
            self.focusImageView.alpha = 0
            self.favoriteView.alpha = 0
            self.topLabelConstraint.constant = 55
            self.bottomLabelConstraint.constant = -20
            self.titleLabel.font = UIFont(name: "Roboto-Bold", size: 30)
            self.loadFocusImage()
        } else {
            if !self.isList {
                self.titleLabel.isHidden = true
            } else {
                self.titleLabel.isHidden = false
            }
            self.focusImageView.image = nil
            //self.titleLabel.text =
            self.focusImageView.alpha = 0
            self.imgView.alpha = 1.0
            self.favoriteView.alpha = 1.0
            self.topLabelConstraint.constant = 20
            self.bottomLabelConstraint.constant = 15
            self.titleLabel.font = UIFont(name: "Roboto-Regular", size: 22.0)
        }

    }, completion: {})
}

</code>```

答:
```<code>Here I got my answer.

    override func viewDidLoad() {
    super.viewDidLoad()
    TVManager.shared.isSelected = false
    }

    // MARK: UIFocusEnvironment
        override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
            coordinator.addCoordinatedAnimations({
                if self.isFocused {
                    if !self.isList {
                        self.titleLabel.isHidden = true
                    } else {
                        self.titleLabel.isHidden = false
                    }
                    if TVManager.shared.isSelected {
                        self.focusImageView.alpha = 0
                                       self.favoriteView.alpha = 0
                                       self.topLabelConstraint.constant = 55
                                       self.bottomLabelConstraint.constant = -20
                                       self.titleLabel.font = UIFont(name: "Roboto-Bold", size: 30)
                                       self.loadFocusImage()
                    } else {
                        self.focusImageView.image = nil
                        //self.titleLabel.text =
                        self.focusImageView.alpha = 0
                        self.imgView.alpha = 1.0
                        self.favoriteView.alpha = 1.0
                        self.topLabelConstraint.constant = 20
                        self.bottomLabelConstraint.constant = 15
                        self.titleLabel.font = UIFont(name: "Roboto-Regular", size: 22.0)
                        TVManager.shared.isSelected = true
                    }

                } else {
                    if !self.isList {
                        self.titleLabel.isHidden = true
                    } else {
                        self.titleLabel.isHidden = false
                    }
                    self.focusImageView.image = nil
                    //self.titleLabel.text =
                    self.focusImageView.alpha = 0
                    self.imgView.alpha = 1.0
                    self.favoriteView.alpha = 1.0
                    self.topLabelConstraint.constant = 20
                    self.bottomLabelConstraint.constant = 15
                    self.titleLabel.font = UIFont(name: "Roboto-Regular", size: 22.0)
                }

            }, completion: {})
        }
</code>```

Body:
I am working on TVOS. I have used UICollectionView. When view loads, the first cell is automatically highlighted. As per the requirement, cell should not highlight automatically.

// MARK: UIFocusEnvironment
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    coordinator.addCoordinatedAnimations({
        if self.isFocused {
            if !self.isList {
                self.titleLabel.isHidden = true
            } else {
                self.titleLabel.isHidden = false
            }
            self.focusImageView.alpha = 0
            self.favoriteView.alpha = 0
            self.topLabelConstraint.constant = 55
            self.bottomLabelConstraint.constant = -20
            self.titleLabel.font = UIFont(name: "Roboto-Bold", size: 30)
            self.loadFocusImage()
        } else {
            if !self.isList {
                self.titleLabel.isHidden = true
            } else {
                self.titleLabel.isHidden = false
            }
            self.focusImageView.image = nil
            //self.titleLabel.text =
            self.focusImageView.alpha = 0
            self.imgView.alpha = 1.0
            self.favoriteView.alpha = 1.0
            self.topLabelConstraint.constant = 20
            self.bottomLabelConstraint.constant = 15
            self.titleLabel.font = UIFont(name: "Roboto-Regular", size: 22.0)
        }

    }, completion: {})
}


问:
Rails custom ActiveRecord::Type fails when using `class_name` in has_many :through association
I'm using KSUIDs as a replacement for UUIDs in my Rails app. michaelherold/ksuid-ruby ported KSUIDs to Ruby and implemented them as ::ActiveRecord::Type::String. Everything is working great except one little bug when using has_many :through associations combined with class_name.

I was able to create two rspec tests to demonstrate the bug.

Working test

https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast1_spec.rb#L50-L58

```<code># code excerpt from link above
class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :appointments
  has_many :physicians, through: :appointments
end

bundle exec rspec ./spec/cast1_spec.rb # works as expected, tests pass
</code>```

Failing test

When I update Patient's appointment association to use class_name it will cause a TypeError: can't cast KSUID::Type.

https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast2_spec.rb#L46

```<code># code excerpt from link above
class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :foobar, class_name: "Appointment" # <---- using class_name here
  has_many :physicians, through: :foobar
end

bundle exec rspec ./spec/cast2_spec.rb # test fails

TypeError:
  can't cast KSUID::Type
# ./spec/cast2_spec.rb:59:in `block (2 levels) in <top (required)>'
</code>```

Can you help me find the problem and fix the test? To reproduce yourself run:

```<code>git clone https://github.com/mattes/ksuid-ruby.git
cd ksuid-ruby
git checkout cast_error
bundle install
bundle exec rspec ./spec/cast1_spec.rb # works
bundle exec rspec ./spec/cast2_spec.rb # fails
</code>```

答:
This looks like a rails bug.

When resolving a through-association (patient.physicians) rails looks for a relation named the same as join table, and since there's none - falls back to typecasting as a string (=no typecasting needed, thus the error).

A hack to make the example work is to add the relation:

class Physician < ActiveRecord::Base
  act_as_ksuid :id

  has_many :foobar, class_name: "Appointment"
  has_many :patients, through: :foobar

  has_many :appointments # <= this is not used in app, but rails now can correctly resolve types
end
```

<p>Rails master (6.1-alpha) has pull request 36847 merged, that fixes some cases and also outputs a more comprehensible error:</p>

<blockquote>
  <p>NotImplementedError: In order to correctly type cast Patient.id, Physician needs to define a :appointments association.</p>
</blockquote>

<p>But it appears to break some other cases, so it's uncertain what will come in 6.1 release. So for now the above hack or monkey-patch with a rails version guard look like a viable solution.</p>

<p>PS. your <code>ksuid/activerecord/schema_statements</code> adds type to <code>PostgreSQLAdapter</code> no matter what actual adapter is.</p>

<p>PPS. you can use <code>bundler/inline</code> and <code>minitest/autorun</code> to create a self-contained example (runnable with just <code>ruby filename.rb</code>):</p>

<pre class="lang-rb prettyprint-override"><code>require 'bundler/inline'

gemfile(ENV['INSTALL']=='1') do
  source 'https://rubygems.org'
  gem 'activerecord', '~>6.0.2' # also tested '~>5.2', '5.0' with same result, master with different error
  gem 'sqlite3' # use , '~> 1.3.6' # for rails 5
  gem 'ksuid', github: 'mattes/ksuid-ruby', ref:'e545b1b251bd6430c454509475963a7845b1da0f'

  gem 'minitest'
end

require "active_record"
require "logger"

require "ksuid/activerecord"
require "ksuid/activerecord/table_definition"

# require "rails"
# require "ksuid/activerecord/schema_statements" # commented out to not load rails only to check Rails.env, instead:
require "active_record/connection_adapters/sqlite3_adapter"
::ActiveRecord::ConnectionAdapters::SQLite3Adapter::NATIVE_DATABASE_TYPES[:ksuid] = { name: "varchar", limit: 27 }

# require "ksuid/activerecord/quoting" # monkey-patch that fixes the error

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(IO::NULL)
ActiveRecord::Schema.verbose = false

ActiveRecord::Schema.define do
  create_table(:physicians,   force: true, id: :ksuid)
  create_table(:patients,     force: true, id: :ksuid)
  create_table(:appointments, force: true, id: :ksuid) {|t| t.ksuid :physician_id, :patient_id }
end

class Physician < ActiveRecord::Base
  act_as_ksuid :id
  has_many :foobar, class_name: "Appointment"
  has_many :patients, through: :foobar

  has_many :appointments # the hack
end

class Appointment < ActiveRecord::Base
  act_as_ksuids :id, :physician_id, :patient_id
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :appointments
  has_many :physicians, through: :appointments
end

ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)

require "minitest/autorun"

describe "ActiveRecord integration" do
  it "loads all associations correctly" do
    patient = Patient.create!
    physician = Physician.create!
    appointment = Appointment.create!(patient_id: patient.id, physician_id: physician.id)
    expect(patient.id.class).must_equal KSUID::Type

    expect(patient.physicians.first).must_equal physician
    expect(physician.patients.first).must_equal patient
  end
end

</code>```

Body:
I'm using KSUIDs as a replacement for UUIDs in my Rails app. michaelherold/ksuid-ruby ported KSUIDs to Ruby and implemented them as ::ActiveRecord::Type::String. Everything is working great except one little bug when using has_many :through associations combined with class_name.

I was able to create two rspec tests to demonstrate the bug.

Working test

https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast1_spec.rb#L50-L58

# code excerpt from link above
class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :appointments
  has_many :physicians, through: :appointments
end

bundle exec rspec ./spec/cast1_spec.rb # works as expected, tests pass

Failing test

When I update Patient's appointment association to use class_name it will cause a TypeError: can't cast KSUID::Type.

https://github.com/mattes/ksuid-ruby/blob/e545b1b251bd6430c454509475963a7845b1da0f/spec/cast2_spec.rb#L46

# code excerpt from link above
class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :foobar, class_name: "Appointment" # <---- using class_name here
  has_many :physicians, through: :foobar
end

bundle exec rspec ./spec/cast2_spec.rb # test fails

TypeError:
  can't cast KSUID::Type
# ./spec/cast2_spec.rb:59:in `block (2 levels) in <top (required)>'

Can you help me find the problem and fix the test? To reproduce yourself run:

git clone https://github.com/mattes/ksuid-ruby.git
cd ksuid-ruby
git checkout cast_error
bundle install
bundle exec rspec ./spec/cast1_spec.rb # works
bundle exec rspec ./spec/cast2_spec.rb # fails

Body:
This looks like a rails bug.

When resolving a through-association (patient.physicians) rails looks for a relation named the same as join table, and since there's none - falls back to typecasting as a string (=no typecasting needed, thus the error).

A hack to make the example work is to add the relation:

class Physician < ActiveRecord::Base
  act_as_ksuid :id

  has_many :foobar, class_name: "Appointment"
  has_many :patients, through: :foobar

  has_many :appointments # <= this is not used in app, but rails now can correctly resolve types
end

Rails master (6.1-alpha) has pull request 36847 merged, that fixes some cases and also outputs a more comprehensible error:

NotImplementedError: In order to correctly type cast Patient.id, Physician needs to define a :appointments association.

But it appears to break some other cases, so it's uncertain what will come in 6.1 release. So for now the above hack or monkey-patch with a rails version guard look like a viable solution.

PS. your ksuid/activerecord/schema_statements adds type to PostgreSQLAdapter no matter what actual adapter is.

PPS. you can use bundler/inline and minitest/autorun to create a self-contained example (runnable with just ruby filename.rb):

require 'bundler/inline'

gemfile(ENV['INSTALL']=='1') do
  source 'https://rubygems.org'
  gem 'activerecord', '~>6.0.2' # also tested '~>5.2', '5.0' with same result, master with different error
  gem 'sqlite3' # use , '~> 1.3.6' # for rails 5
  gem 'ksuid', github: 'mattes/ksuid-ruby', ref:'e545b1b251bd6430c454509475963a7845b1da0f'

  gem 'minitest'
end

require "active_record"
require "logger"

require "ksuid/activerecord"
require "ksuid/activerecord/table_definition"

# require "rails"
# require "ksuid/activerecord/schema_statements" # commented out to not load rails only to check Rails.env, instead:
require "active_record/connection_adapters/sqlite3_adapter"
::ActiveRecord::ConnectionAdapters::SQLite3Adapter::NATIVE_DATABASE_TYPES[:ksuid] = { name: "varchar", limit: 27 }

# require "ksuid/activerecord/quoting" # monkey-patch that fixes the error

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(IO::NULL)
ActiveRecord::Schema.verbose = false

ActiveRecord::Schema.define do
  create_table(:physicians,   force: true, id: :ksuid)
  create_table(:patients,     force: true, id: :ksuid)
  create_table(:appointments, force: true, id: :ksuid) {|t| t.ksuid :physician_id, :patient_id }
end

class Physician < ActiveRecord::Base
  act_as_ksuid :id
  has_many :foobar, class_name: "Appointment"
  has_many :patients, through: :foobar

  has_many :appointments # the hack
end

class Appointment < ActiveRecord::Base
  act_as_ksuids :id, :physician_id, :patient_id
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  act_as_ksuid :id
  has_many :appointments
  has_many :physicians, through: :appointments
end

ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)

require "minitest/autorun"

describe "ActiveRecord integration" do
  it "loads all associations correctly" do
    patient = Patient.create!
    physician = Physician.create!
    appointment = Appointment.create!(patient_id: patient.id, physician_id: physician.id)
    expect(patient.id.class).must_equal KSUID::Type

    expect(patient.physicians.first).must_equal physician
    expect(physician.patients.first).must_equal patient
  end
end


问:
Tweeter bot with Ruby bot.rb:4:in `<main>': undefined local variable or method `twitter' for main:Object (NameError)
I'm trying to build a small twitter bot following a tutorial
but I got this error "bot.rb:4:in ': undefined local variable or methodtwitter' for main:Object (NameError)"

My code is

```<code> require 'rubygems'
 require 'twitter'

 client = twitter::REST::Client.new do |config|
 config.consumer_key = ""
 config.consumer_secret = ""
 config.access_token_secret = ""
end
</code>```

source 'https://rubygems.org'
   ruby "~> 2.6.0"

```<code>gem 'twitter'
gem 'activesupport'
gem 'actionview'
gem 'httparty'
gem 'rake'
</code>```

答:
As you can see from the documentation that you mentioned, name of classes should starts from the capital letter, so in your case: Twitter::REST::Client.new, not twitter::REST::Client.new.

I suggest you to learn basics of Ruby, it will help you further. ;)

Body:
I'm trying to build a small twitter bot following a tutorial
but I got this error "bot.rb:4:in ': undefined local variable or methodtwitter' for main:Object (NameError)"

My code is

 require 'rubygems'
 require 'twitter'

 client = twitter::REST::Client.new do |config|
 config.consumer_key = ""
 config.consumer_secret = ""
 config.access_token_secret = ""
end

source 'https://rubygems.org'
   ruby "~> 2.6.0"

gem 'twitter'
gem 'activesupport'
gem 'actionview'
gem 'httparty'
gem 'rake'


问:
ItemsSource Binding in UserControl doens't work
i am currently testing UserControls and therefore created this little App.

Main.xaml

```<code><Grid>
<control:CustomInterfaceGrid Color="Green" Height="400" CustomItemsSource="{Binding Packages}"></control:CustomInterfaceGrid>
</Grid>
</code>```

UserControl.xaml

```<code><UserControl x:Class="App.Custom.CustomInterfaceGrid"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="App.Custom"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800"
             x:Name="SourceElement"
             >
        <Grid>
        <ListBox x:Name="listView" Background="{Binding Color, ElementName=SourceElement}" ItemsSource="{Binding CustomItemsSource, ElementName=SourceElement}"></ListBox>
    </Grid>
</UserControl>
</code>```

CodeBehind from UserControl

```<code>public partial class CustomInterfaceGrid : UserControl, INotifyPropertyChanged
  {

     public CustomInterfaceGrid()
    {
      InitializeComponent();
      DataContext = this;
     }

    public static readonly DependencyProperty ColorProperty =

    DependencyProperty.Register("Color", typeof(SolidColorBrush), typeof(CustomInterfaceGrid));

    public SolidColorBrush Color
    {
      get; set;
    }

    public static readonly DependencyProperty CustomItemsSourceProperty =

    DependencyProperty.Register("CustomItemsSource", typeof(IEnumerable<Object>), typeof(CustomInterfaceGrid));

    public IEnumerable<Object> CustomItemsSource
    {
      get
      {
        return GetValue(CustomItemsSourceProperty) as IEnumerable<Object>;
      }
      set {
        SetValue(CustomItemsSourceProperty, value);
        OnPropertyChanged();
      }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }

  }
</code>```

The problem is that my the color changes when I set it in Main, but it wont show the Packages from the List.
When i bind the Packages directly to a list in Main.xaml its alright. So the fault has to be somewhere else.
Hope you can help!

答:
the main mistakes which leads to binding erros is unnecessary set DataContext. remove this line from constructor:

```<code> DataContext = this;
</code>```

there is no need to implement INotifyPropertyChanged for UserControl which is also DependencyObject. DependencyProperties have internal mechanism to notify about changes. Remove OnPropertyChanged - declaration and all usages.

Speaking of DependencyProperties: public SolidColorBrush Color { get; set; } doesn't follow required pattern and has to be implemented with GetValue / SetValue method

Body:
i am currently testing UserControls and therefore created this little App.

Main.xaml

<Grid>
<control:CustomInterfaceGrid Color="Green" Height="400" CustomItemsSource="{Binding Packages}"></control:CustomInterfaceGrid>
</Grid>

UserControl.xaml

<UserControl x:Class="App.Custom.CustomInterfaceGrid"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="App.Custom"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800"
             x:Name="SourceElement"
             >
        <Grid>
        <ListBox x:Name="listView" Background="{Binding Color, ElementName=SourceElement}" ItemsSource="{Binding CustomItemsSource, ElementName=SourceElement}"></ListBox>
    </Grid>
</UserControl>

CodeBehind from UserControl

public partial class CustomInterfaceGrid : UserControl, INotifyPropertyChanged
  {

     public CustomInterfaceGrid()
    {
      InitializeComponent();
      DataContext = this;
     }

    public static readonly DependencyProperty ColorProperty =

    DependencyProperty.Register("Color", typeof(SolidColorBrush), typeof(CustomInterfaceGrid));

    public SolidColorBrush Color
    {
      get; set;
    }

    public static readonly DependencyProperty CustomItemsSourceProperty =

    DependencyProperty.Register("CustomItemsSource", typeof(IEnumerable<Object>), typeof(CustomInterfaceGrid));

    public IEnumerable<Object> CustomItemsSource
    {
      get
      {
        return GetValue(CustomItemsSourceProperty) as IEnumerable<Object>;
      }
      set {
        SetValue(CustomItemsSourceProperty, value);
        OnPropertyChanged();
      }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }

  }

The problem is that my the color changes when I set it in Main, but it wont show the Packages from the List.
When i bind the Packages directly to a list in Main.xaml its alright. So the fault has to be somewhere else.
Hope you can help!

Body:
the main mistakes which leads to binding erros is unnecessary set DataContext. remove this line from constructor:

 DataContext = this;

there is no need to implement INotifyPropertyChanged for UserControl which is also DependencyObject. DependencyProperties have internal mechanism to notify about changes. Remove OnPropertyChanged - declaration and all usages.

Speaking of DependencyProperties: public SolidColorBrush Color { get; set; } doesn't follow required pattern and has to be implemented with GetValue / SetValue method


问:
Can anyone help me out with block.io API for withdrawal of bitcoin from wallet?
I am trying to use block.io API, before few months I tried and implemented, it was working perfect, and now they have changed signed signature method, All APIs working correct, only withdrawal API not working, Response of curl is showing success, but says required more_signatures_needed , I don't know how to do this, Can anyone help me? I will be thankful.

protected void Page_Load(object sender, EventArgs e)
    {
         myPage.Text = readHtmlPage("https://block.io/api/v2/withdraw_from_addresses/");

```<code>   //fecth response
    String myUri = Session["myPagecc"].ToString();
</code>```

//display response
        Label1.Text = myUri.ToString();

```<code>}
private String readHtmlPage(string url)
{

    String api_key = "myapikey";

    double amounts = "btcamount";

    String to_addresses = "receiveraddress";

    string FROM_ADDRESS = "myaddress";

    string NEWCODE = Guid.NewGuid().ToString().Substring(0, 5);
    string priority="medium";
    String result = "";
    String strPost = "api_key=" + api_key + "&from_addresses=" + FROM_ADDRESS + "&to_addresses="+to_addresses +"&amounts="+amounts+"&priority="+priority+"&nonce="+NEWCODE;

    StreamWriter myWriter = null;

    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
    objRequest.Method = "POST";
    objRequest.ContentLength = strPost.Length;
    objRequest.ContentType = "application/x-www-form-urlencoded";

    try
    {
        myWriter = new StreamWriter(objRequest.GetRequestStream());
        myWriter.Write(strPost);

    }
    catch (Exception e)
    {
        return e.Message;
    }
    finally
    {
        myWriter.Close();

    }

    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
    using (StreamReader sr =
       new StreamReader(objResponse.GetResponseStream()))
    {
        result = sr.ReadToEnd();

        // Close and clean up the StreamReader
        sr.Close();
    }
    return result;
}
</code>```

"status" : "success", "data" : { "reference_id" : "70ab0922cf036481533e7f345068c0bed36f9681d644d8", "more_signatures_needed" : true, "inputs" : [ { "input_no" : 0, "signatures_needed" : 1, "data_to_sign" : "3916022666e29882298d54c2c8f2ab3306cc4e774594f5db9", "signers" : [ { "signer_address" : "jhE397dsNaNLByJ8WV43emD1mhSpPtwDV", "signer_public_key" : "a34b48a3a18373020d8d96fb53b733d373cd3ba9b5bbfd2c9f8105c8939058130d", "signed_data" : null } ] } ], "encrypted_passphrase" : { "signer_address" : "NaNLmhSByJ8WV43emD1jhE397dspPtwDV", "signer_public_key" : "373cd3ba9b5bbfd2c9f8020d8d96fb53b733d373a34b48a3a18105c8939058130d", "passphrase" : "r20/Wyy5iTVFmpcmn1Y8JOMR8mP7jAqaBrMf2UOW2aEBQSQ1XfxpgonIyFLDOKkmuqH84sETSjXTFsl3dpo5niABB2rL69vnsLbS4DaXMw1o33NH0zgHyzdkAYmIoeGe85YVPMkrQsNhLrGQ6JUaubT+W3rIBxP7rCqYznnMnt8QxG4wu5LSh2EY8fja6AI1" }, "unsigned_tx_hex" : "010000000127d8d4654bc8cf69c9b1980c1afa67e51b5b28241ac080100000023220020200d0c2118ad382e8dab4f3c2ddf5ab8ca1d8ac3ffa3d910a0a2aa86cb69cb77bb62e2a7f12fbc8a699ffffffff076a914103ee4139219756a503842b0ad01000000000019caf5a381440b66bd81188ac64a401000000000017a9145af1577250a83928e306b35f8463047d72d9e3408700000000" } }

答:
Any solution for this please.

With Block.IO token withdrawal it seems we need to send some extra secure pins
as per their doc:  https://block.io/api/simple/signing

Like to know how to send cURL to execute ?

Their sample cURL is not working: /api/v2/withdraw_from_addresses/?api_key=API KEY&from_addresses=ADDRESS1,ADDRESS2,...&to_addresses=ADDRESS1,ADDRESS2,...&amounts=AMOUNT1,AMOUNT2,...

response is:

```<code>{[status, success]}
{[data, {
  "reference_id": "24fe5a.....",
  "more_signatures_needed": true,
  "inputs": [
    {
      "input_no": 0,
      "signatures_needed": 1,
      "data_to_sign": "2498d....",
      "signers": [
        {
          "signer_address": "1H4.....",
          "signer_public_key": "037710.....",
          "signed_data": null
        }
      ]
    }
  ],
  "encrypted_passphrase": {
    "signer_address": "1H4...",
    "signer_public_key": "0377....",
    "passphrase": "fDCM0...."
  },
  "unsigned_tx_hex": "01000...."
}]}
</code>```

if possible: expecting some sample in asp.net vb please

Body:
I am trying to use block.io API, before few months I tried and implemented, it was working perfect, and now they have changed signed signature method, All APIs working correct, only withdrawal API not working, Response of curl is showing success, but says required more_signatures_needed , I don't know how to do this, Can anyone help me? I will be thankful.

protected void Page_Load(object sender, EventArgs e)
    {
         myPage.Text = readHtmlPage("https://block.io/api/v2/withdraw_from_addresses/");

   //fecth response
    String myUri = Session["myPagecc"].ToString();

//display response
        Label1.Text = myUri.ToString();

}
private String readHtmlPage(string url)
{

    String api_key = "myapikey";

    double amounts = "btcamount";

    String to_addresses = "receiveraddress";

    string FROM_ADDRESS = "myaddress";

    string NEWCODE = Guid.NewGuid().ToString().Substring(0, 5);
    string priority="medium";
    String result = "";
    String strPost = "api_key=" + api_key + "&from_addresses=" + FROM_ADDRESS + "&to_addresses="+to_addresses +"&amounts="+amounts+"&priority="+priority+"&nonce="+NEWCODE;

    StreamWriter myWriter = null;

    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
    objRequest.Method = "POST";
    objRequest.ContentLength = strPost.Length;
    objRequest.ContentType = "application/x-www-form-urlencoded";

    try
    {
        myWriter = new StreamWriter(objRequest.GetRequestStream());
        myWriter.Write(strPost);

    }
    catch (Exception e)
    {
        return e.Message;
    }
    finally
    {
        myWriter.Close();

    }

    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
    using (StreamReader sr =
       new StreamReader(objResponse.GetResponseStream()))
    {
        result = sr.ReadToEnd();

        // Close and clean up the StreamReader
        sr.Close();
    }
    return result;
}

"status" : "success", "data" : { "reference_id" : "70ab0922cf036481533e7f345068c0bed36f9681d644d8", "more_signatures_needed" : true, "inputs" : [ { "input_no" : 0, "signatures_needed" : 1, "data_to_sign" : "3916022666e29882298d54c2c8f2ab3306cc4e774594f5db9", "signers" : [ { "signer_address" : "jhE397dsNaNLByJ8WV43emD1mhSpPtwDV", "signer_public_key" : "a34b48a3a18373020d8d96fb53b733d373cd3ba9b5bbfd2c9f8105c8939058130d", "signed_data" : null } ] } ], "encrypted_passphrase" : { "signer_address" : "NaNLmhSByJ8WV43emD1jhE397dspPtwDV", "signer_public_key" : "373cd3ba9b5bbfd2c9f8020d8d96fb53b733d373a34b48a3a18105c8939058130d", "passphrase" : "r20/Wyy5iTVFmpcmn1Y8JOMR8mP7jAqaBrMf2UOW2aEBQSQ1XfxpgonIyFLDOKkmuqH84sETSjXTFsl3dpo5niABB2rL69vnsLbS4DaXMw1o33NH0zgHyzdkAYmIoeGe85YVPMkrQsNhLrGQ6JUaubT+W3rIBxP7rCqYznnMnt8QxG4wu5LSh2EY8fja6AI1" }, "unsigned_tx_hex" : "010000000127d8d4654bc8cf69c9b1980c1afa67e51b5b28241ac080100000023220020200d0c2118ad382e8dab4f3c2ddf5ab8ca1d8ac3ffa3d910a0a2aa86cb69cb77bb62e2a7f12fbc8a699ffffffff076a914103ee4139219756a503842b0ad01000000000019caf5a381440b66bd81188ac64a401000000000017a9145af1577250a83928e306b35f8463047d72d9e3408700000000" } }

Body:
Any solution for this please.

With Block.IO token withdrawal it seems we need to send some extra secure pins
as per their doc:  https://block.io/api/simple/signing

Like to know how to send cURL to execute ?

Their sample cURL is not working: /api/v2/withdraw_from_addresses/?api_key=API KEY&from_addresses=ADDRESS1,ADDRESS2,...&to_addresses=ADDRESS1,ADDRESS2,...&amounts=AMOUNT1,AMOUNT2,...

response is:

{[status, success]}
{[data, {
  "reference_id": "24fe5a.....",
  "more_signatures_needed": true,
  "inputs": [
    {
      "input_no": 0,
      "signatures_needed": 1,
      "data_to_sign": "2498d....",
      "signers": [
        {
          "signer_address": "1H4.....",
          "signer_public_key": "037710.....",
          "signed_data": null
        }
      ]
    }
  ],
  "encrypted_passphrase": {
    "signer_address": "1H4...",
    "signer_public_key": "0377....",
    "passphrase": "fDCM0...."
  },
  "unsigned_tx_hex": "01000...."
}]}

if possible: expecting some sample in asp.net vb please


问:
Get Screen size irrespective of orientation
I have  TableViewController with multiple cells. I am setting the height of these cells in the heightForRowAt method:

```<code>    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UIScreen.main.bounds.maxY / 15
}
</code>```

When the device orientation is portrait, everything is working fine, but when its landscape, maxY is very small, so the cells are too small as well. I want them to have the same height whatever the orientation is.
So how do I get the portrait device height even if the current orientation is landscape?

答:
Ok, if found a pretty simple solution for this problem. I just use both width and height when calculating the row height, so the orientation doesn't matter.

When you do that, you just have to find the right constant to divide the addition by, so that it looks good.

That is my code now:

```<code>    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return (UIScreen.main.bounds.maxY+UIScreen.main.bounds.maxX) / 28
}
</code>```

Body:
I have  TableViewController with multiple cells. I am setting the height of these cells in the heightForRowAt method:

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UIScreen.main.bounds.maxY / 15
}

When the device orientation is portrait, everything is working fine, but when its landscape, maxY is very small, so the cells are too small as well. I want them to have the same height whatever the orientation is.
So how do I get the portrait device height even if the current orientation is landscape?

Body:
Ok, if found a pretty simple solution for this problem. I just use both width and height when calculating the row height, so the orientation doesn't matter.

When you do that, you just have to find the right constant to divide the addition by, so that it looks good.

That is my code now:

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return (UIScreen.main.bounds.maxY+UIScreen.main.bounds.maxX) / 28
}


问:
How to use recursion or some other technique for following problem
I have some n-d matrix in which data is filled using indexes. following is a sample code which will give you the idea of what I am trying to implement.

```<code># sf = some_function or it can also be considered as array where
# sf(i) = sf[i]

def sample_function(matrix, matrix2, obj1, obj2):
    for i in range(len(obj1):
        for j in range(len(obj2)):
            for k in range(len(obj3):
                matrix[sf(i)][sf(j)][sf(k)] = matrix2[i][j][k]
</code>```

This is easy to do if I have only 2-3 parameters for function but if parameteres are many how can I do this?
You can assume matrix is already there filled with some value(0).

答:
This is not recursive, just makes use of inbuilt itertools, which might still be useful for you... if I understood your question correctly, that is :) Otherwise correct me</p>

```<code>import numpy  as np
import itertools as it

def other_fun(*args):
    return sum(args)

def sample_fun(mtx, *args):
    for ids in it.product(*[range(len(obj)) for obj in args]):
        mtx[ids] = other_fun(*[obj[idx] for obj,idx in zip(args,ids)])
    return mtx

obj1 = [1,2,3]
obj2 = [4,5,6,7]
obj3 = [8,9]
objects = [obj1, obj2, obj3]

mtx = np.zeros([len(obj) for obj in objects])
mtx = sample_fun(mtx, *objects)
print(mtx)
</code>```

Body:
I have some n-d matrix in which data is filled using indexes. following is a sample code which will give you the idea of what I am trying to implement.

# sf = some_function or it can also be considered as array where
# sf(i) = sf[i]

def sample_function(matrix, matrix2, obj1, obj2):
    for i in range(len(obj1):
        for j in range(len(obj2)):
            for k in range(len(obj3):
                matrix[sf(i)][sf(j)][sf(k)] = matrix2[i][j][k]

This is easy to do if I have only 2-3 parameters for function but if parameteres are many how can I do this?
You can assume matrix is already there filled with some value(0).

Body:
This is not recursive, just makes use of inbuilt itertools, which might still be useful for you... if I understood your question correctly, that is :) Otherwise correct me

import numpy  as np
import itertools as it

def other_fun(*args):
    return sum(args)

def sample_fun(mtx, *args):
    for ids in it.product(*[range(len(obj)) for obj in args]):
        mtx[ids] = other_fun(*[obj[idx] for obj,idx in zip(args,ids)])
    return mtx

obj1 = [1,2,3]
obj2 = [4,5,6,7]
obj3 = [8,9]
objects = [obj1, obj2, obj3]

mtx = np.zeros([len(obj) for obj in objects])
mtx = sample_fun(mtx, *objects)
print(mtx)


问:
How to have fixed div height irrespective of image height within it
I have a row with three coloumns. I want to have a image on each coloumn's divs with same height irrespective of image size in each div.

I want the images to get resized with in a div. But i get different size of divs as the image size of myImage1.png, myImage2.png and myImage3.png is different.

This is happening because i have fixed padding in my 'bg' class. Can somebody help me to fix this? Below is my HTML and CSS code.

```<code><div class="row IDE_container">
    <div class="col-lg-3 col-md-3 col-sm-3">
        <div class="bg">
            <img src="myImage1.png" class="IDE_div" />
        </div>
    </div>

    <div class="col-lg-2 col-md-2 col-sm-2">
        <div class="circle_bg circle_bg_sm">
            <img src="myImage2.png" class="IDE_div" />
        </div>
    </div>

    <div class="col-lg-3 col-md-3 col-sm-3">
        <div class="circle_bg">
            <img src="myImage3.png" class="IDE_div" />
        </div>
    </div>
</div>

.bg{
    background-color: #ededed;
    border-radius: 100%;
    text-align: center;
    padding: 35% 5%;
    width: max-content;
    max-width: 100%;
    box-shadow: 0 0 3px 1px #DDD;
}

.IDE_div {
display: inline-block;
position: relative;
width: 100%;
height: 100%;
}

.IDE_container {
    display: flex;
    align-items: baseline;
  }
</code>```

答:
For various kind of images, so can use object-fit property.

Add the CSS like this:

```<code>.IDE_div{
width: 100%;
object-fit: cover;
height: 300px; /* only if you want fixed height */
}

<div class="col-3">
    <div class="circle_bg">
        <img src="myImage3.png" class="IDE_div" />
    </div>
</div>
</code>```

You will find the details about object-fit and object-position here : https://css-tricks.com/on-object-fit-and-object-position/

Body:
I have a row with three coloumns. I want to have a image on each coloumn's divs with same height irrespective of image size in each div.

I want the images to get resized with in a div. But i get different size of divs as the image size of myImage1.png, myImage2.png and myImage3.png is different.

This is happening because i have fixed padding in my 'bg' class. Can somebody help me to fix this? Below is my HTML and CSS code.

.bg{
    background-color: #ededed;
    border-radius: 100%;
    text-align: center;
    padding: 35% 5%;
    width: max-content;
    max-width: 100%;
    box-shadow: 0 0 3px 1px #DDD;
}

.IDE_div {
display: inline-block;
position: relative;
width: 100%;
height: 100%;
}

.IDE_container {
    display: flex;
    align-items: baseline;
  }

Body:
For various kind of images, so can use object-fit property.

Add the CSS like this:

.IDE_div{
width: 100%;
object-fit: cover;
height: 300px; /* only if you want fixed height */
}

<div class="col-3">
    <div class="circle_bg">
        <img src="myImage3.png" class="IDE_div" />
    </div>
</div>

You will find the details about object-fit and object-position here : https://css-tricks.com/on-object-fit-and-object-position/


问:
AbstractNCSARequestLog not working for log4j
I am using Java Spark(web framework) and I am following this tutorial: http://sparkjava.com/tutorials/jetty-request-log in order to enable logging.

The following class however, gives me an error:

```<code>constructor AbstractNCSARequestLog in class AbstractNCSARequestLog cannot be applied to given types;
                return new AbstractNCSARequestLog() {
                       ^
  required: Writer
  found: no arguments
</code>```

The class in question:

```<code>    public class RequestLogFactory {

    private Logger logger;

    public RequestLogFactory(Logger logger) {
        this.logger = logger;
    }

    AbstractNCSARequestLog create() {
        return new AbstractNCSARequestLog() {
            @Override
            protected boolean isEnabled() {
                return true;
            }

            @Override
            public void write(String s) throws IOException {
                logger.info(s);
            }
        };
    }
}
</code>```

答:
If you want to use the old-school NCSA Request Log format, then use the
Slf4jRequestLog instead of the AbstractNCSARequestLog (both are now deprecated).

If you want to use the modern RequestLog techniques use the CustomRequestLog with a Slf4jRequestLogWriter. (added bonus is the ability to customize the requestlog format)

With either of those approaches you'll need to route your slf4j to log4j (by including the slf4j-log4j12-<ver>.jar in your classpath)

Then you can now capture your request logs on a named logger (logger name is configurable in the Slf4jRequestLogWriter)

Example:

Slf4jRequestLogWriter slf4jWriter = new Slf4jRequestLogWriter();
// The name of the logger to write request logs to
slf4jWriter.setLoggerName("my.requestlog");
CustomRequestLog requestLog = new CustomRequestLog(slf4jWriter, CustomRequestLog.NCSA_FORMAT);
server.setRequestLog(requestLog);
```

Body:
I am using Java Spark(web framework) and I am following this tutorial: http://sparkjava.com/tutorials/jetty-request-log in order to enable logging.

The following class however, gives me an error:

constructor AbstractNCSARequestLog in class AbstractNCSARequestLog cannot be applied to given types;
                return new AbstractNCSARequestLog() {
                       ^
  required: Writer
  found: no arguments

The class in question:

    public class RequestLogFactory {

    private Logger logger;

    public RequestLogFactory(Logger logger) {
        this.logger = logger;
    }

    AbstractNCSARequestLog create() {
        return new AbstractNCSARequestLog() {
            @Override
            protected boolean isEnabled() {
                return true;
            }

            @Override
            public void write(String s) throws IOException {
                logger.info(s);
            }
        };
    }
}


问:
Would it be better to do a PUT request to update a whole item or DELETE + POST?
I was trying to update some customer records on an API when this question struck.

First I request the customer object from the API and transform it into an array, the update I have to perform consists on appending a quite big second array to the one I first got, so I decided to do so and then, use UPDATE to upload the whole new array as substitute for the old one.

Since this is the actual API and every change I made would go directly into production, I am not sure if this is going to work, and I thought that I could always delete the old object and make a simple POST request to upload the new one.

This is the method tasked to upload the new array ($response).

function updateReceipt($response, $receiptId, $uri4, $token){
    $ch = curl_init();

    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $uri4.$receiptId,
        CURLOPT_CUSTOMREQUEST => 'PUT',
        CURLOPT_POSTFIELDS => http_build_query($response),
        CURLOPT_HTTPHEADER => array("Content-Type: application/json", "key: ".$token)
    );
    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);
    $response = json_decode($response, true);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    echo "Status code: $http_code ";

    curl_close($ch);

    return $updated;
}
```

So, will the PUT method accept the whole array and update the customer record? Does PUT require more accurate changes to be done for it to wrok?

What do you think about the DELETE first, POST next solution? Is it going to be more efficient?

Thank you all for your help!

答: If you are sure about that the old object is not referenced to other data , then you can do delete_post, but if it is related to some other data then it is not the right solution.</p>

Body:
I was trying to update some customer records on an API when this question struck.

First I request the customer object from the API and transform it into an array, the update I have to perform consists on appending a quite big second array to the one I first got, so I decided to do so and then, use UPDATE to upload the whole new array as substitute for the old one.

Since this is the actual API and every change I made would go directly into production, I am not sure if this is going to work, and I thought that I could always delete the old object and make a simple POST request to upload the new one.

This is the method tasked to upload the new array ($response).

function updateReceipt($response, $receiptId, $uri4, $token){
    $ch = curl_init();

    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $uri4.$receiptId,
        CURLOPT_CUSTOMREQUEST => 'PUT',
        CURLOPT_POSTFIELDS => http_build_query($response),
        CURLOPT_HTTPHEADER => array("Content-Type: application/json", "key: ".$token)
    );
    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);
    $response = json_decode($response, true);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    echo "Status code: $http_code ";

    curl_close($ch);

    return $updated;
}

So, will the PUT method accept the whole array and update the customer record? Does PUT require more accurate changes to be done for it to wrok?

What do you think about the DELETE first, POST next solution? Is it going to be more efficient?

Thank you all for your help!


问:
After parsing xml files in perl, getting special characters
I'm parsing a xml file & storing it in Database [using perl]. At the time of parsing am getting special characters like - &[quot;amp;lt;gt;].
What is the meaning of these special characters ? </p>

答: See here on wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references</p>

ContentLicense: CC BY-SA 3.0


问:
Modifying a String (char array)
I am trying to modify a string in C language

```<code>    char signal_cat[8];

        if (k == 1) {
            strcpy_s(signal_cat, "HPHA",6);             //why cant I change char array (string) values???
        }
        else if (k == 2) {
            strcpy_s(signal_cat, "Normal",6);
        }

        printf("Original signal category: %s \n", signal_cat);

</code>```

When I run this it shows an exception "Unhandled exception at 0x7BEBF71D (ucrtbased.dll) in Lab3Parti.exe: 0xC0000005: Access violation reading location 0x00000006"

I have tried

```<code>signal_cat = "HPHA";
</code>```

too, but an error shows "expression must be a modifiable lvalue"

Does anyone know how I can go about doing this?

答:
Are you using Visual Studio to compile your C code?

If you are and the compiler is forcing you to use strcpy_s() instead of strcpy(), you can still use the standard library function strcpy() by defining the following macro at the top of your source file:

```<code>#define _CRT_SECURE_NO_WARNINGS
</code>```

The actual problem in your code is that you are giving the arguments to strcpy_s() in the wrong order. Check the function's prototype to provide the arguments in the correct order.

Title: Modifying a String (char array)

Body:
I am trying to modify a string in C language

    char signal_cat[8];

        if (k == 1) {
            strcpy_s(signal_cat, "HPHA",6);             //why cant I change char array (string) values???
        }
        else if (k == 2) {
            strcpy_s(signal_cat, "Normal",6);
        }

        printf("Original signal category: %s \n", signal_cat);

When I run this it shows an exception "Unhandled exception at 0x7BEBF71D (ucrtbased.dll) in Lab3Parti.exe: 0xC0000005: Access violation reading location 0x00000006"

I have tried

signal_cat = "HPHA";

too, but an error shows "expression must be a modifiable lvalue"

Does anyone know how I can go about doing this?

Body:
Are you using Visual Studio to compile your C code?

If you are and the compiler is forcing you to use strcpy_s() instead of strcpy(), you can still use the standard library function strcpy() by defining the following macro at the top of your source file:

#define _CRT_SECURE_NO_WARNINGS

The actual problem in your code is that you are giving the arguments to strcpy_s() in the wrong order. Check the function's prototype to provide the arguments in the correct order.


问:
Breaking down array of objects into separate variables for database storage (React,express,sql server)
I have a stored array of objects within my reactjs application which when console logged looks like this.

```<code>0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}
</code>```

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

```<code>insert into table where answer = answer and question = question and state = state
</code>```

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

```<code>create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

</code>```

EDIT

Stored procedure

```<code>create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;
</code>```

How it is passed through to the sql query from express npm

```<code>app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

</code>```

This is the console.info(results)

```<code>[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]
</code>```

error

```<code>RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.
</code>```

答:
This solution converts the source lines into json strings (your log lines already are very similar to a json, so only minor changes are needed). This way you can use standard SQL Server functions to read their values, making the code cleaner, easier to maintain, and hopefully more robust than my other proposal.

The lines are still separated using the string_split function with the line feed character.

```<code>create procedure StoreAnswers(@text varchar(max))
as begin
  insert into QuestionResponses(question, answer, state)
  select json_value(json, '$.question') as question,
         json_value(json, '$.answer') as answer,
         json_value(json, '$.state') as state
  from (select replace(replace(replace(substring(value, charindex('{', value), len(value)), 'answer: ', '"answer": '), 'question: ', '"question": '), 'state: ', '"state": ') as json
        from string_split(@source, char(10))
        where value like '%{%}%') as jsons
end;
</code>```

json_value is the SQL function that extracts a value from a json string.

Example of the conversion from a source line to a json. From :

0: {answer: "yes", question: "Is the keyboard separate from the
  screen?", state: "Declined with soloution defined"}

... we convert it to :

{"answer": "yes", "question": "Is the keyboard separate from the
  screen?", "state": "Declined with soloution defined"}

We just remove the initial line number, and we add quotes to the identifiers. This expression does those changes :

```<code>replace(replace(replace(substring(value, charindex('{', value), len(value)), 'answer: ', '"answer": '), 'question: ', '"question": '), 'state: ', '"state": ')
</code>```

Here you can see live the extraction of each value from the source text : http://sqlfiddle.com/#!18/9eecb/74419

Body:
I have a stored array of objects within my reactjs application which when console logged looks like this.

0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

insert into table where answer = answer and question = question and state = state

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

EDIT

Stored procedure

create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;

How it is passed through to the sql query from express npm

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

This is the console.info(results)

[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]

error

RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.

Body:
This solution converts the source lines into json strings (your log lines already are very similar to a json, so only minor changes are needed). This way you can use standard SQL Server functions to read their values, making the code cleaner, easier to maintain, and hopefully more robust than my other proposal.

The lines are still separated using the string_split function with the line feed character.

create procedure StoreAnswers(@text varchar(max))
as begin
  insert into QuestionResponses(question, answer, state)
  select json_value(json, '$.question') as question,
         json_value(json, '$.answer') as answer,
         json_value(json, '$.state') as state
  from (select replace(replace(replace(substring(value, charindex('{', value), len(value)), 'answer: ', '"answer": '), 'question: ', '"question": '), 'state: ', '"state": ') as json
        from string_split(@source, char(10))
        where value like '%{%}%') as jsons
end;

json_value is the SQL function that extracts a value from a json string.

Example of the conversion from a source line to a json. From :

0: {answer: "yes", question: "Is the keyboard separate from the
  screen?", state: "Declined with soloution defined"}

... we convert it to :

{"answer": "yes", "question": "Is the keyboard separate from the
  screen?", "state": "Declined with soloution defined"}

We just remove the initial line number, and we add quotes to the identifiers. This expression does those changes :

replace(replace(replace(substring(value, charindex('{', value), len(value)), 'answer: ', '"answer": '), 'question: ', '"question": '), 'state: ', '"state": ')

Here you can see live the extraction of each value from the source text : http://sqlfiddle.com/#!18/9eecb/74419


问:
Find blank cells, insert formula that includes cell range above
I am trying to find a vba code that will find blank cells in a certain column, and replace these cells with a formula that includes the range of cells above (up until the next blank cell)

for instance, cells A2:A15 are filled in,
A16 is blank,
I want a code that can find the blank C16, and insert the following code:

```<code>=COUNTIF(A2:A13,A2)=COUNTA(A2:A13)
</code>```

I have about 72,000 rows, and there is not a uniform spacing between the blank cell ranges.

Thank you so much in advance!

This the what the code in have found

```<code>Sub Testing()
Dim Rng As Range, r As Range

Set Rng = Range("a2:a" & Range("a" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeConstants)
Top = Selection.End(xlUp).Value

For Each r In Rng.Areas
    With r
         .Cells(1, 1).Offset(.Rows.Count).Formula = "=countif(" & .Address & ", " & .Top & ") = CountA(" & .Address & ")" 'i got stucked with the code here. where i want to pick the first cell for every range.
    End With
Next
End Sub

</code>```

答:
Think you just need a coupel of changes to your formula. I replaced Top which I didn't understand and you had an errant "=" instead of a "-".

```<code>Sub Testing()

Dim Rng As Range, r As Range

Set Rng = Range("a2:a" & Range("a" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeConstants)
'Top = Selection.End(xlUp).Value

For Each r In Rng.Areas
    With r
         .Cells(1, 1).Offset(.Rows.Count).Formula = "=countif(" & .Address & ", " & .Cells(1).Address & ") - CountA(" & .Address & ")" 'i got stucked with the code here. where i want to pick the first cell for every range.
    End With
Next

End Sub
</code>```

Body:
I am trying to find a vba code that will find blank cells in a certain column, and replace these cells with a formula that includes the range of cells above (up until the next blank cell)

for instance, cells A2:A15 are filled in,
A16 is blank,
I want a code that can find the blank C16, and insert the following code:

=COUNTIF(A2:A13,A2)=COUNTA(A2:A13)

I have about 72,000 rows, and there is not a uniform spacing between the blank cell ranges.

Thank you so much in advance!

This the what the code in have found

Sub Testing()
Dim Rng As Range, r As Range

Set Rng = Range("a2:a" & Range("a" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeConstants)
Top = Selection.End(xlUp).Value

For Each r In Rng.Areas
    With r
         .Cells(1, 1).Offset(.Rows.Count).Formula = "=countif(" & .Address & ", " & .Top & ") = CountA(" & .Address & ")" 'i got stucked with the code here. where i want to pick the first cell for every range.
    End With
Next
End Sub

Body:
Think you just need a coupel of changes to your formula. I replaced Top which I didn't understand and you had an errant "=" instead of a "-".

Sub Testing()

Dim Rng As Range, r As Range

Set Rng = Range("a2:a" & Range("a" & Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeConstants)
'Top = Selection.End(xlUp).Value

For Each r In Rng.Areas
    With r
         .Cells(1, 1).Offset(.Rows.Count).Formula = "=countif(" & .Address & ", " & .Cells(1).Address & ") - CountA(" & .Address & ")" 'i got stucked with the code here. where i want to pick the first cell for every range.
    End With
Next

End Sub


问:
replace value in datafrme if another value is empty
I have a dataframe:

```<code>x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, 4.2),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)
</code>```

I want to replace subgroup value to "A" if type is empty.so exceted output is:

```<code>x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, "A"),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)
</code>```

I tried this:

```<code>if (x$type = '') {
  x$subgroup = "A"
}
</code>```

But it didnt work. How could i do it?

答:
You can try the code below:

using ifelse

```<code>x <- within(x,subgroup <- ifelse(type=="","A",subgroup))
</code>```

using replace

```<code>x <- within(x,subgroup <- replace(subgroup,type=="","A"))
</code>```

or

```<code>x <- within(x,subgroup <- replace(subgroup,nchar(as.character(type))==0,"A"))
</code>```

such that

```<code>> x
   group subgroup type
1      1      1.1 good
2      1      1.2 good
3      1      1.3  bad
4      2      2.1  bad
5      2      2.2 good
6      3      3.1  bad
7      3      3.2  bad
8      3      3.3 good
9      4      4.1 good
10     4        A
</code>```

Body:
I have a dataframe:

x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, 4.2),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)

I want to replace subgroup value to "A" if type is empty.so exceted output is:

x = data.frame(group = c(1,1,1,2,2,3,3,3,4,4),
               subgroup = c(1.1, 1.2, 1.3, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, "A"),
               type = c("good", 'good', 'bad', 'bad', 'good', 'bad', 'bad', 'good', 'good', '')
)

I tried this:

if (x$type = '') {
  x$subgroup = "A"
}

But it didnt work. How could i do it?

Body:
You can try the code below:

using ifelse

x <- within(x,subgroup <- ifelse(type=="","A",subgroup))

using replace

x <- within(x,subgroup <- replace(subgroup,type=="","A"))

or

x <- within(x,subgroup <- replace(subgroup,nchar(as.character(type))==0,"A"))

such that

> x
   group subgroup type
1      1      1.1 good
2      1      1.2 good
3      1      1.3  bad
4      2      2.1  bad
5      2      2.2 good
6      3      3.1  bad
7      3      3.2  bad
8      3      3.3 good
9      4      4.1 good
10     4        A