问:
Using inheritance to provide one class by another in Python
I'm trying to become a self taught developer, so I have nobody to ask when I do not understand the task in a course. The question is about inheritance.
Given structure

I have to implement some classes as a piece of program to monitor news.
I was given the base abstract class Trigger

```<code>class Trigger(object):
    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """
        # DO NOT CHANGE THIS!
        raise NotImplementedError
</code>```

And then I have to implement other classes accordingly the scheme. I did it like that:

```<code>class PhraseTrigger(Trigger):

    def __init__(self, trigger, story):
        self._trigger = trigger
        self._story = story

    def is_phrase_in(self):

        phrase_to_match = r"((\W)+|^)"
        for i in self._trigger.split():
            phrase_to_match += i
            if (i != self._trigger.split()[-1]):
                phrase_to_match += r"(\W)+"
            else:
                phrase_to_match += r"((\W)+|$)"

        # print(phrase_to_match) # delete after debugging
        scheme_to_match = re.compile(phrase_to_match, re.IGNORECASE)
        mo = scheme_to_match.search(self._story)

        if (mo != None):
            return True
        else:
            return False

    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """

        if is_phrase_in(self):
            return True
        else:
            return False
</code>```

I've done all of them except Not-, And- and OrTrigger.
Next I was said "The NotTrigger should produce its output by inverting the output of another trigger. The NOT trigger should take this other trigger as an argument to its constructor". How can I add another class to init method of NotTrigger? Or I did not catch the idea completely. Any advice will be appreciated.
P.S. Sorry for long text and my poor English(it's my second language).

答:
It means NotTrigger.__init__ takes an instance of Trigger as its argument. Once you have that, you can implement NotTrigger.evaluate in terms of the other trigger's evaluate method. Something like

```<code>class NotTrigger:
    def __init__(self, trigger):
        self.trigger = trigger

    def evaluate(self, story):
        if self.trigger.evaluate(story):
            ...
        else:
            ...
</code>```

Note that it's not __init__ that should take a story argument, only evaluate. If a Trigger wraps another Trigger (or more than one), it's evaluate's job to ensure that the wrapped Trigger's evaluate method is called on story when appropriate.

Body:
I'm trying to become a self taught developer, so I have nobody to ask when I do not understand the task in a course. The question is about inheritance.
Given structure

I have to implement some classes as a piece of program to monitor news.
I was given the base abstract class Trigger

class Trigger(object):
    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """
        # DO NOT CHANGE THIS!
        raise NotImplementedError

And then I have to implement other classes accordingly the scheme. I did it like that:

class PhraseTrigger(Trigger):

    def __init__(self, trigger, story):
        self._trigger = trigger
        self._story = story

    def is_phrase_in(self):

        phrase_to_match = r"((\W)+|^)"
        for i in self._trigger.split():
            phrase_to_match += i
            if (i != self._trigger.split()[-1]):
                phrase_to_match += r"(\W)+"
            else:
                phrase_to_match += r"((\W)+|$)"

        # print(phrase_to_match) # delete after debugging
        scheme_to_match = re.compile(phrase_to_match, re.IGNORECASE)
        mo = scheme_to_match.search(self._story)

        if (mo != None):
            return True
        else:
            return False

    def evaluate(self, story):
        """
        Returns True if an alert should be generated
        for the given news item, or False otherwise.
        """

        if is_phrase_in(self):
            return True
        else:
            return False

I've done all of them except Not-, And- and OrTrigger.
Next I was said "The NotTrigger should produce its output by inverting the output of another trigger. The NOT trigger should take this other trigger as an argument to its constructor". How can I add another class to init method of NotTrigger? Or I did not catch the idea completely. Any advice will be appreciated.
P.S. Sorry for long text and my poor English(it's my second language).

Body:
It means NotTrigger.__init__ takes an instance of Trigger as its argument. Once you have that, you can implement NotTrigger.evaluate in terms of the other trigger's evaluate method. Something like

class NotTrigger:
    def __init__(self, trigger):
        self.trigger = trigger

    def evaluate(self, story):
        if self.trigger.evaluate(story):
            ...
        else:
            ...

Note that it's not __init__ that should take a story argument, only evaluate. If a Trigger wraps another Trigger (or more than one), it's evaluate's job to ensure that the wrapped Trigger's evaluate method is called on story when appropriate.


来源: stackexchange

问:
How to create rounded border with dividers and gradient for all divided parts in Android?
I am trying to create a rounded border with 5 dividers/segments that contain gradients for each divider.
Attaching reference image(sorry for bad editing images)

I am able to fill the rounded border around the image with a gradient but I am unable to proceed further with it.

Any help or reference to it will be appreciated.

Thanks in advance

答:
You can create a custom view and draw circle with gradient colors in it.

See this answer： https://stackoverflow.com/a/37743507/2173056

ContentLicense: CC BY-SA 4.0


问:
Determine time of event in R
Wondering what the most effective way to determine event time in R is. Other answers seemed to not have grouping by ID, and that's a big chunk of what I need.

My data looks something like this:

```<code>time = rep(c(1:5),2)
id = c(rep(1,5),rep(2,5))
event = c(0,0,0,1,1,0,1,1,1,1)

df = data.frame(cbind(time,id,event))
df
   time id event
1     1  1     0
2     2  1     0
3     3  1     0
4     4  1     1
5     5  1     1
6     1  2     0
7     2  2     1
8     3  2     1
9     4  2     1
10    5  2     1
>
</code>```

Where "event" is binary observation (death of individual in experiment), and (should) remain 1 once it is first observed.

I need to determine the first time of event == 1, for each id number, and generate a vector of the id number and time first observed where event =1.

I originally was going to sloppily subset the data where event =1, and then just pick the minimum value of the week for each id, but that gets even sloppier when grouping by ID. Then I tried some aggregating but also struggled to do it across the ID grouping. I know tidyverse has some options but I'm a n00b.

I'm sure there's a very straightforward way to do this. Thanks!

答:
The tidyverse is indeed super helpful for this kind of stuff.

```<code>df %>%
  filter(event == 1) %>%
  group_by(id) %>%
  arrange(id, time) %>%
  summarise(time = first(time)) %>%
  ungroup()
</code>```

```<code># A tibble: 2 x 2
     id  time
  <dbl> <dbl>
1     1     4
2     2     2
</code>```

Title: Determine time of event in R

Body:
Wondering what the most effective way to determine event time in R is. Other answers seemed to not have grouping by ID, and that's a big chunk of what I need.

My data looks something like this:

time = rep(c(1:5),2)
id = c(rep(1,5),rep(2,5))
event = c(0,0,0,1,1,0,1,1,1,1)

df = data.frame(cbind(time,id,event))
df
   time id event
1     1  1     0
2     2  1     0
3     3  1     0
4     4  1     1
5     5  1     1
6     1  2     0
7     2  2     1
8     3  2     1
9     4  2     1
10    5  2     1
>

Where "event" is binary observation (death of individual in experiment), and (should) remain 1 once it is first observed.

I need to determine the first time of event == 1, for each id number, and generate a vector of the id number and time first observed where event =1.

I originally was going to sloppily subset the data where event =1, and then just pick the minimum value of the week for each id, but that gets even sloppier when grouping by ID. Then I tried some aggregating but also struggled to do it across the ID grouping. I know tidyverse has some options but I'm a n00b.

I'm sure there's a very straightforward way to do this. Thanks!

Body:
The tidyverse is indeed super helpful for this kind of stuff.

df %>%
  filter(event == 1) %>%
  group_by(id) %>%
  arrange(id, time) %>%
  summarise(time = first(time)) %>%
  ungroup()

# A tibble: 2 x 2
     id  time
  <dbl> <dbl>
1     1     4
2     2     2


问:
Xcode: Keep order of plist
I have a question depending plists in Xcode.
I'm loading images from a plist into a NSDictionary (the paths of the images) and then display the images from that dictionary but they are not shown in the same order like in the plist.

How can I manage that the images are shown in the same order?

答: By definition NSDictionary is not ordered... you should consider using an NSArray of NSDictionaries that contains path to image, and some ordering number, then sort that array after reading it from file with NSSortDescriptor</p>

ContentLicense: CC BY-SA 3.0

Title: Xcode: Keep order of plist


问:
Make lower case to a specific latter in javascript
please help me to make this string "SeLamAT PAGi semua halOo"

become this "Selamat Pagi Semua Haloo"

i lil bit confuse make a function

答:
I've recently solved this problem,
what I ended up using for this purpose is a regex.

Single line solution

```<code>const result = "SeLamAT PAGi semua halOo".replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase())
</code>```

Alternative solution

```<code>function titleCase(input) {
   const splittedInput = input.toLowerCase().split(' ');
   for (const i = 0; i < splittedInput.length; i++) {
       splittedInput[i] = splittedInput[i].charAt(0).toUpperCase() + splittedInput[i].substring(1);
   }
   return splittedInput.join(' ');
}

const result = titleCase("SeLamAT PAGi semua halOo");
console.log(result);
</code>```

Body:
I've recently solved this problem,
what I ended up using for this purpose is a regex.

Single line solution

const result = "SeLamAT PAGi semua halOo".replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase())

Alternative solution

function titleCase(input) {
   const splittedInput = input.toLowerCase().split(' ');
   for (const i = 0; i < splittedInput.length; i++) {
       splittedInput[i] = splittedInput[i].charAt(0).toUpperCase() + splittedInput[i].substring(1);
   }
   return splittedInput.join(' ');
}

const result = titleCase("SeLamAT PAGi semua halOo");
console.log(result);


问:
CAShapeLayer path animation shrinking before completing animation
I am trying to animate a rotation of a layer's CGpath.

The rotation works perfectly, but for some reason, the path seems to shrink, then get bigger again. I just want it to show a rotating animation. I don't want it to shrink

here is a video.

here is the code

```<code>class ViewController: UIViewController {

@IBOutlet weak var overlayView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    let maskLayer = CAShapeLayer()
    let path = UIBezierPath(rect: view.bounds)
    let mask = UIBezierPath.drawSquare(width: 100, center: view.center)

    // Makes it so we can see through the center of the view
    maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
    path.append(mask)
    maskLayer.path = path.cgPath
    overlayView.layer.mask = maskLayer
}

@IBAction func rotateView(_ sender: Any) {

    let maskPath = UIBezierPath.drawSquare(width: 100, center: overlayView.center)
    let path = UIBezierPath(rect: overlayView.frame)

    let bounds: CGRect = maskPath.cgPath.boundingBox
    let center = CGPoint(x: bounds.midX, y: bounds.midY)

    let radians = 90 / 180.0 * .pi
    var transform: CGAffineTransform = .identity
    transform = transform.translatedBy(x: center.x, y: center.y)
    transform = transform.rotated(by: radians)
    transform = transform.translatedBy(x: -center.x, y: -center.y)
    maskPath.apply(transform)

    path.append(maskPath)

    // create new animation
    let anim = CABasicAnimation(keyPath: "path")
    anim.toValue = path.cgPath

    (overlayView.layer.mask as? CAShapeLayer)?.add(anim, forKey: "path")

}

}

extension UIBezierPath{

static func drawSquare(width: CGFloat, center: CGPoint) -> UIBezierPath {
    let rect = CGRect(x: center.x - width/2, y: center.y - width/2, width: width, height: width)

    let path = UIBezierPath()
    path.move(to: rect.origin)

    path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
    path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
    path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
    path.close()
    return path
}
}
</code>```

答:
Your "cutout box" is shrinking and growing because you're using path animation.

When you animate a path from one set of points to another, each point will take a straight line from its starting point to its ending point.

Couple ways to visualize this...

First, we'll add an "outline" frame to the cutout mask box:

as you see, each corner is taking a direct route to its next position.

If we highlight one side, it's maybe a bit more obvious:

and, we can number the corners for even more clarity:

So, if we want to rotate the square without changing its size, we could use keyframe animation and run the corners along a circle:

or, much easier, rotate the mask layer instead of its path:

```<code>let radians = 90 / 180.0 * .pi
let anim = CABasicAnimation(keyPath: "transform.rotation.z")
anim.toValue = radians
anim.duration = 1.0
(overlayView.layer.mask as? CAShapeLayer)?.add(anim, forKey: "layerRotate")
</code>```

No doubt we notice that the mask layer frame does not completely cover the overlayView frame.

So, we can fix that by making the mask layer frame larger.

We could calculate exactly how big it needs to be, but because shape layers are very efficient, we'll just make it a square, 1.5 times bigger than the longer axis:

so when it rotates, it covers the view:

and we finish with this:

Body:
I am trying to animate a rotation of a layer's CGpath.

The rotation works perfectly, but for some reason, the path seems to shrink, then get bigger again. I just want it to show a rotating animation. I don't want it to shrink

here is a video.

here is the code

class ViewController: UIViewController {

@IBOutlet weak var overlayView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    let maskLayer = CAShapeLayer()
    let path = UIBezierPath(rect: view.bounds)
    let mask = UIBezierPath.drawSquare(width: 100, center: view.center)

    // Makes it so we can see through the center of the view
    maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
    path.append(mask)
    maskLayer.path = path.cgPath
    overlayView.layer.mask = maskLayer
}

@IBAction func rotateView(_ sender: Any) {

    let maskPath = UIBezierPath.drawSquare(width: 100, center: overlayView.center)
    let path = UIBezierPath(rect: overlayView.frame)

    let bounds: CGRect = maskPath.cgPath.boundingBox
    let center = CGPoint(x: bounds.midX, y: bounds.midY)

    let radians = 90 / 180.0 * .pi
    var transform: CGAffineTransform = .identity
    transform = transform.translatedBy(x: center.x, y: center.y)
    transform = transform.rotated(by: radians)
    transform = transform.translatedBy(x: -center.x, y: -center.y)
    maskPath.apply(transform)

    path.append(maskPath)

    // create new animation
    let anim = CABasicAnimation(keyPath: "path")
    anim.toValue = path.cgPath

    (overlayView.layer.mask as? CAShapeLayer)?.add(anim, forKey: "path")

}

}

extension UIBezierPath{

static func drawSquare(width: CGFloat, center: CGPoint) -> UIBezierPath {
    let rect = CGRect(x: center.x - width/2, y: center.y - width/2, width: width, height: width)

    let path = UIBezierPath()
    path.move(to: rect.origin)

    path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
    path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
    path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
    path.close()
    return path
}
}

Body:
Your "cutout box" is shrinking and growing because you're using path animation.

When you animate a path from one set of points to another, each point will take a straight line from its starting point to its ending point.

Couple ways to visualize this...

First, we'll add an "outline" frame to the cutout mask box:

as you see, each corner is taking a direct route to its next position.

If we highlight one side, it's maybe a bit more obvious:

and, we can number the corners for even more clarity:

So, if we want to rotate the square without changing its size, we could use keyframe animation and run the corners along a circle:

or, much easier, rotate the mask layer instead of its path:

let radians = 90 / 180.0 * .pi
let anim = CABasicAnimation(keyPath: "transform.rotation.z")
anim.toValue = radians
anim.duration = 1.0
(overlayView.layer.mask as? CAShapeLayer)?.add(anim, forKey: "layerRotate")

No doubt we notice that the mask layer frame does not completely cover the overlayView frame.

So, we can fix that by making the mask layer frame larger.

We could calculate exactly how big it needs to be, but because shape layers are very efficient, we'll just make it a square, 1.5 times bigger than the longer axis:

so when it rotates, it covers the view:

and we finish with this:


问:
LAST_NUMBER on oracle sequence
I have a sequence SEQ_PAGE_ID

```<code>SEQUENCE_NAME   INCREMENT_BY  CACHE_SIZE   LAST_NUMBER
-------------------------------------------------------
SEQ_PAGE_ID      1              20          2222292456
</code>```

To change the CACHE_SIZE, I used below script,

alter sequence SEQ_PAGE_ID CACHE 5000;

When I checked the query,

```<code>select ... from user_sequences where sequence_name  = 'SEQ_PAGE_ID';

SEQUENCE_NAME   INCREMENT_BY  CACHE_SIZE    LAST_NUMBER
-------------------------------------------------------
SEQ_PAGE_ID      1              5000          2222292447
</code>```

The LAST_NUMBER changed from 2222292456 to 2222292447.
Is this happened due to the alter script?

答:
This post is for changing Last Number :)

Let us assume LAST_NUMBER in seq xyz is 3953 and you want to change it to 205233, then you need to increment the sequence by (205233 - 3953 = 201,280) and then increment it by 1. that can be achieved by below statements:

to change the LAST_NUMBER to

```<code>ALTER SEQUENCE xyz INCREMENT BY 201280;
SELECT xyz.nextval from dual;
ALTER SEQUENCE xyz INCREMENT BY 1;
</code>```

Now the LAST_NUMBER would be updated as 205233

Title: LAST_NUMBER on oracle sequence

Body:
I have a sequence SEQ_PAGE_ID

SEQUENCE_NAME   INCREMENT_BY  CACHE_SIZE   LAST_NUMBER
-------------------------------------------------------
SEQ_PAGE_ID      1              20          2222292456

To change the CACHE_SIZE, I used below script,

alter sequence SEQ_PAGE_ID CACHE 5000;

When I checked the query,

select ... from user_sequences where sequence_name  = 'SEQ_PAGE_ID';

SEQUENCE_NAME   INCREMENT_BY  CACHE_SIZE    LAST_NUMBER
-------------------------------------------------------
SEQ_PAGE_ID      1              5000          2222292447

The LAST_NUMBER changed from 2222292456 to 2222292447.
Is this happened due to the alter script?

Body:
This post is for changing Last Number :)

Let us assume LAST_NUMBER in seq xyz is 3953 and you want to change it to 205233, then you need to increment the sequence by (205233 - 3953 = 201,280) and then increment it by 1. that can be achieved by below statements:

to change the LAST_NUMBER to

ALTER SEQUENCE xyz INCREMENT BY 201280;
SELECT xyz.nextval from dual;
ALTER SEQUENCE xyz INCREMENT BY 1;

Now the LAST_NUMBER would be updated as 205233


问:
How to use Regex to select multiple line
I have the following string in form of HTML Text -

```<code>=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=
</code>```

dth: 300px"

The following string(dynamic token) needs to be extracted-

```<code>3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk
</code>```

How can this be done using Regex?

Actively looking forward to some suggestions.

Thank you

答:
Can use MULTILINE flag with the regexp 'token=([^&]+)'.

Try this:

import re

html = '''
=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=
dth: 300px"
'''

m = re.search(r'token=([^&]+)', html, re.MULTILINE)
if m:
    print(m.group(1))
```
<p><strong>Output:</strong></p>
```3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk
```

Body:
I have the following string in form of HTML Text -

=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=

dth: 300px"

The following string(dynamic token) needs to be extracted-

3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk

How can this be done using Regex?

Actively looking forward to some suggestions.

Thank you

Body:
Can use MULTILINE flag with the regexp 'token=([^&]+)'.

Try this:

import re

html = '''
=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=
dth: 300px"
'''

m = re.search(r'token=([^&]+)', html, re.MULTILINE)
if m:
    print(m.group(1))

Output:

3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk


问:
ng2-ckeditor - how to customise the css loaded inside the editor itself?
I need to customise the ENTER key behaviour of ng2-ckeditor. I understand there is a config option as explained here.

However as that link explains, I should use custom css:

If you want to change it to control paragraph spacing, you should use
  stylesheets instead. Edit the contents.css file and set up a suitable
  margin value for
 elements, for example:

p { margin: 0; }

According to this SO question I can load a custom CSS file using a config option, like this:

```<code>config.contentsCss = 'mystyles.css'
</code>```

I tried adding a single file to my project and setting the config in angular 2 component, but the file does not appear to load.

```<code>  private setConfig(): void {
    this.ckConfig = {
      height: '250',
      extraPlugins: 'divarea',
      contentsCss: '/theme/styles/ckeditor.css',
      toolbar: [... toolbar configurations ...]
    };
  }
</code>```

So how can I get ng2-ckeditor to load this file?

答:
This breaks if you have the DIVAREA plugin activated

Edit (from comment):

This is because contentsCss does not load when using DIVAREA. Makes sense since the CSS would need to be scoped to inside the DIV (easy with iFrame).

Maybe new CSS layers could help here?
github.com/ckeditor/ckeditor4/issues/4640 github.com/ckeditor/ckeditor4/issues/4642

Body:
I need to customise the ENTER key behaviour of ng2-ckeditor. I understand there is a config option as explained here.

However as that link explains, I should use custom css:

If you want to change it to control paragraph spacing, you should use
  stylesheets instead. Edit the contents.css file and set up a suitable
  margin value for
 elements, for example:

p { margin: 0; }

According to this SO question I can load a custom CSS file using a config option, like this:

config.contentsCss = 'mystyles.css'

I tried adding a single file to my project and setting the config in angular 2 component, but the file does not appear to load.

  private setConfig(): void {
    this.ckConfig = {
      height: '250',
      extraPlugins: 'divarea',
      contentsCss: '/theme/styles/ckeditor.css',
      toolbar: [... toolbar configurations ...]
    };
  }

So how can I get ng2-ckeditor to load this file?


问:
Data provided to import into Oracle only has day and month. Year is missing. What DATE type to use?
Data provided to import into Oracle only has day and month. Year is missing. I need to run some queries to calculate number of days between dates. Eg. Checkin date: 03-April and Check out: 07-May.
What DATE type to use?</p>

答:
I need to run some queries to calculate number of days between dates. Eg. Check in date: 03-April and Check out: 07-May.

In general, you need a year to unambiguously calculate the number of days between two dates as you need to account for leap years (and, if you are being particularly precise, leap seconds).

You can use several methods:

Assume that your dates are always going to be in a non-leap year. Then you can pick any non-leap year and use it in your query as a default year.

Assume that your dates are always going to be in a leap year. Then you can pick any leap year and use it in your query as a default year.

Assume that your dates are always going to be of the current year.

They all have flaws:

If the assumption is wrong then you will get the wrong value if the dates are either side of Feb-29.

If you get the value Feb-29 then 1 & 3 can raise exceptions.

What DATE type to use?

If you are talking about how to store the value in a table then either store the value in a VARCHAR2 if you want to store the raw values or chose one of the three assumptions above and use a DATE data type and apply the default year.

For example, you could store the raw data and calculate the DATE values for the default year:

CREATE TABLE table_name (
  check_in            VARCHAR2(20),
  check_out           VARCHAR2(20),
  check_in_1970       DATE GENERATED ALWAYS AS (TO_DATE(check_in || 1970 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
  check_out_1970      DATE GENERATED ALWAYS AS (TO_DATE(check_in || 1970 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
  check_in_2020       DATE GENERATED ALWAYS AS (TO_DATE(check_in || 2020 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
  check_out_2020      DATE GENERATED ALWAYS AS (TO_DATE(check_in || 2020 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
);

INSERT INTO table_name (check_in, check_out) VALUES ('03-April', '07-May');
INSERT INTO table_name (check_in, check_out) VALUES ('01-January', '31-December');
INSERT INTO table_name (check_in, check_out) VALUES ('29-February', '29-February');
```
<p>Then:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT check_in,
       check_out,
       check_out_1970 - check_in_1970 AS diff_1970,
       check_out_2020 - check_in_2020 AS diff_2020
FROM   table_name;
</code>```

Outputs:

CHECK_IN
CHECK_OUT
DIFF_1970
DIFF_2020

03-April
07-May
34
34

01-January
31-December
364
365

29-February
29-February
null
0

db<>fiddle here

Body:
I need to run some queries to calculate number of days between dates. Eg. Check in date: 03-April and Check out: 07-May.

In general, you need a year to unambiguously calculate the number of days between two dates as you need to account for leap years (and, if you are being particularly precise, leap seconds).

You can use several methods:

Assume that your dates are always going to be in a non-leap year. Then you can pick any non-leap year and use it in your query as a default year.

Assume that your dates are always going to be in a leap year. Then you can pick any leap year and use it in your query as a default year.

Assume that your dates are always going to be of the current year.

They all have flaws:

If the assumption is wrong then you will get the wrong value if the dates are either side of Feb-29.

If you get the value Feb-29 then 1 & 3 can raise exceptions.

What DATE type to use?

If you are talking about how to store the value in a table then either store the value in a VARCHAR2 if you want to store the raw values or chose one of the three assumptions above and use a DATE data type and apply the default year.

For example, you could store the raw data and calculate the DATE values for the default year:

CREATE TABLE table_name (
  check_in            VARCHAR2(20),
  check_out           VARCHAR2(20),
  check_in_1970       DATE GENERATED ALWAYS AS (TO_DATE(check_in || 1970 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
  check_out_1970      DATE GENERATED ALWAYS AS (TO_DATE(check_in || 1970 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
  check_in_2020       DATE GENERATED ALWAYS AS (TO_DATE(check_in || 2020 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
  check_out_2020      DATE GENERATED ALWAYS AS (TO_DATE(check_in || 2020 DEFAULT NULL ON CONVERSION ERROR, 'DD-MonthYYYY')),
);

INSERT INTO table_name (check_in, check_out) VALUES ('03-April', '07-May');
INSERT INTO table_name (check_in, check_out) VALUES ('01-January', '31-December');
INSERT INTO table_name (check_in, check_out) VALUES ('29-February', '29-February');

Then:

SELECT check_in,
       check_out,
       check_out_1970 - check_in_1970 AS diff_1970,
       check_out_2020 - check_in_2020 AS diff_2020
FROM   table_name;

Outputs:

CHECK_IN
CHECK_OUT
DIFF_1970
DIFF_2020

03-April
07-May
34
34

01-January
31-December
364
365

29-February
29-February
null
0

db<>fiddle here


问:
jQuery if visible
```<code> <div id="chatCenterMembers">
   <div class="chatmember">
       <a title="Blah Blah Blah">
          <div class="newchatmessage" style="display: block;"></div>
</code>```

How can I capture the visible div in an if statement?

I have $(this) set to
 - second line from the top.

I've been working with below but had now luck so far.

```<code>if($(this+' a div.newchatmessage').filter(":visible")) {
</code>```

Above just drops out...

I've also tried below and it doesn't work either

```<code>if ($(this + 'a div.newchatmessage').is(':visible')) {
</code>```

答:
Use .is() to check if an element fills a certain requirement, like such:

```<code>if ($(this).find('a div.newchatmessage').is(':visible'))
</code>```

Or, if you want it more readable:

```<code>var element = $(this).find('a div.newchatmessage');

if (element.is(':visible')) {
    // Do your thing
}
</code>```

Title: jQuery if visible

Body:
How can I capture the visible div in an if statement?

I have $(this) set to
 - second line from the top.

I've been working with below but had now luck so far.

if($(this+' a div.newchatmessage').filter(":visible")) {

Above just drops out...

I've also tried below and it doesn't work either

if ($(this + 'a div.newchatmessage').is(':visible')) {

Body:
Use .is() to check if an element fills a certain requirement, like such:

if ($(this).find('a div.newchatmessage').is(':visible'))

Or, if you want it more readable:

var element = $(this).find('a div.newchatmessage');

if (element.is(':visible')) {
    // Do your thing
}


问:
Disjoint Set Union with directed graph
I understand the DSU strictly works with undirected graphs from this stack overflow question - Can we detect cycles in directed graph using Union-Find data structure?

Nevertheless, I am currently working on a problem that involves 400000 queries and a graph with at most 400000 nodes, in which there are two possible queries:

Connect nodes a and b (directed, of course)

Output "true" if node "x" is reachable from node 1. Otherwise, print "false."

However, my original instinct was to use DSU; that obviously would not work. Any suggestions? Thank you.

答:
As long as you don't have to delete connections, and you're only interested in reachability from a single source, then you can do this in amortized constant time per operation pretty easily.

Maintain a set of nodes that are known to be reachable from node 1.  Initially this would just contain node 1.  We'll call these nodes 'marked'.

When you connect a->b, if a is marked but b is not, then mark all the newly reachable nodes.  This is a transitive closure operation:

put b in a queue.

while the queue is not empty, remove a vertex, mark it reachable, and put all of its unmarked neighbors in the queue.

Title: Disjoint Set Union with directed graph


问:
Codeigniter : Delete directory after deleting all files
I want to delete a folder after deleting all the files inside it, in my codeigniter project. Lets say my folder name is upload, which is located near the application folder in my ci project.

The upload folder contains Peniyal as a sub-folder and it contains 4 images inside it. I need that 4 images to be deleted, next the sub-folder has to be deleted.upload folder should not be deleted.  I am hanging my mind to do it.
So far I have tried the following:-

```<code>$files = glob('./upload/Peniyal');//to get all file names
//am not sure whether the path is correctly given..
foreach($files as $file){ // iterate files one by one
    if(is_file($file))
        unlink($file); // delete file
}
$path   = './upload/Peniyal';
rmdir($path);
</code>```

Any help will be appreciated. Thx!

答:
With CodeIgnitor 4:</p>
```<code>delete_files('./path/to/directory/', true);
rmdir('./path/to/directory/');
</code>```

Body:
I want to delete a folder after deleting all the files inside it, in my codeigniter project. Lets say my folder name is upload, which is located near the application folder in my ci project.

The upload folder contains Peniyal as a sub-folder and it contains 4 images inside it. I need that 4 images to be deleted, next the sub-folder has to be deleted.upload folder should not be deleted.  I am hanging my mind to do it.
So far I have tried the following:-

$files = glob('./upload/Peniyal');//to get all file names
//am not sure whether the path is correctly given..
foreach($files as $file){ // iterate files one by one
    if(is_file($file))
        unlink($file); // delete file
}
$path   = './upload/Peniyal';
rmdir($path);

Any help will be appreciated. Thx!

Body:
With CodeIgnitor 4:

delete_files('./path/to/directory/', true);
rmdir('./path/to/directory/');


问:
Only execute the insert function after passing the validate
I have the following code to validate if the form is filled out:

$("#validate").on("click",function(){
    if(!$(".alerta").valid());
  });
  $.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })
  $(".alerta").validate({
      messages: {
        Tipo: "Tipo de alerta obrigatório",
        Prioridade: {
              required: "Prioridade obrigatório"
          }
      }
  });
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

<form method="POST" class="row g-3 alerta">
  <div class="col-md-4">
    <label for="Tipo" class="form-label">TIPO DE ALERTA <span style="color: red;">*</span></label>
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option></option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>
  </div>

  <div class="col-md-4">
    <label for="Tipo" class="form-label">Prioridade <span style="color: red;">*</span></label>
    <select class="form-select" name="Prioridade" id="Prioridade" required>
    <option></option>
    <option value="1">Prioridade</option>
    <option value="2">Prioridade1</option>
    </select>
  </div>
  <div class="col-12">
    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" id="validate"> Enviar <i class="metismenu-icon pe-7s-paper-plane"></i></button>
  </div>
</form></code>```

After validation I created the code to insert into the database as follows:
To the form button I added this code onclick="inserir_registo();"

Then I created the function:

```<code>function inserir_registo(){
    var dadosajax = {
        'Tipo' : $("#Tipo").val(),
        'Prioridade' : $("#Prioridade").val()
    };
    $.ajax({
        url: 'registo.php',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(data)
        {
            $('.alerta')[0].reset();
            Swal.fire('Boa!', 'Alerta enviado com sucesso!', 'success');
        }
    });
}
</code>```

The problem I have is that when I click on the button to insert into the database, if it does not pass the validation, it inserts it into the database, only with the fields filled in.
You should only insert it when the form correctly passed the validate.

答:
You need to make sure that the insertIntoDB() function is only called when the validation succeeds:

```<code> $("#validate").on("click", function() {
  if ($(".alerta").valid()) insertIntoDB($("form.alerta"));
 });
</code>```

Here is a working snippet:

$("#validate").on("click", function() {
  if ($(".alerta").valid()) insertIntoDB($("form.alerta"));
});
$.validator.setDefaults({
  ignore: ":hidden:not(.chosen-select)"
})
$(".alerta").validate({
  messages: {
    Tipo: "Tipo de alerta obrigatório",
    Prioridade: "Prioridade obrigatório"
  }
});

function insertIntoDB($o){
 console.log($o.serializeArray())
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

<form method="POST" class="row g-3 alerta">
  <div class="col-md-4">
    <label for="Tipo" class="form-label">TIPO DE ALERTA <span style="color: red;">*</span></label>
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
      <option></option>
      <option value="1">Teste</option>
      <option value="2">Teste1</option>
    </select>
  </div>

  <div class="col-md-4">
    <label for="Tipo" class="form-label">Prioridade <span style="color: red;">*</span></label>
    <select class="form-select" name="Prioridade" id="Prioridade" required>
      <option></option>
      <option value="1">Prioridade</option>
      <option value="2">Prioridade1</option>
    </select>
  </div>
  <div class="col-12">
    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" id="validate"> Enviar <i class="metismenu-icon pe-7s-paper-plane"></i></button>
  </div>
</form></code>```

Body:
I have the following code to validate if the form is filled out:

$("#validate").on("click",function(){
    if(!$(".alerta").valid());
  });
  $.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })
  $(".alerta").validate({
      messages: {
        Tipo: "Tipo de alerta obrigatório",
        Prioridade: {
              required: "Prioridade obrigatório"
          }
      }
  });

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">

<form method="POST" class="row g-3 alerta">

    TIPO DE ALERTA *
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option></option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>

    Prioridade *
    <select class="form-select" name="Prioridade" id="Prioridade" required>
    <option></option>
    <option value="1">Prioridade</option>
    <option value="2">Prioridade1</option>
    </select>

    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" id="validate"> Enviar </button>

</form>

After validation I created the code to insert into the database as follows:
To the form button I added this code onclick="inserir_registo();"

Then I created the function:

function inserir_registo(){
    var dadosajax = {
        'Tipo' : $("#Tipo").val(),
        'Prioridade' : $("#Prioridade").val()
    };
    $.ajax({
        url: 'registo.php',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){

        },
        success: function(data)
        {
            $('.alerta')[0].reset();
            Swal.fire('Boa!', 'Alerta enviado com sucesso!', 'success');
        }
    });
}

The problem I have is that when I click on the button to insert into the database, if it does not pass the validation, it inserts it into the database, only with the fields filled in.
You should only insert it when the form correctly passed the validate.

Body:
You need to make sure that the insertIntoDB() function is only called when the validation succeeds:

 $("#validate").on("click", function() {
  if ($(".alerta").valid()) insertIntoDB($("form.alerta"));
 });

Here is a working snippet:

$("#validate").on("click", function() {
  if ($(".alerta").valid()) insertIntoDB($("form.alerta"));
});
$.validator.setDefaults({
  ignore: ":hidden:not(.chosen-select)"
})
$(".alerta").validate({
  messages: {
    Tipo: "Tipo de alerta obrigatório",
    Prioridade: "Prioridade obrigatório"
  }
});

function insertIntoDB($o){
 console.log($o.serializeArray())
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

<form method="POST" class="row g-3 alerta">
  <div class="col-md-4">
    <label for="Tipo" class="form-label">TIPO DE ALERTA <span style="color: red;">*</span></label>
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
      <option></option>
      <option value="1">Teste</option>
      <option value="2">Teste1</option>
    </select>
  </div>

  <div class="col-md-4">
    <label for="Tipo" class="form-label">Prioridade <span style="color: red;">*</span></label>
    <select class="form-select" name="Prioridade" id="Prioridade" required>
      <option></option>
      <option value="1">Prioridade</option>
      <option value="2">Prioridade1</option>
    </select>
  </div>
  <div class="col-12">
    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" id="validate"> Enviar <i class="metismenu-icon pe-7s-paper-plane"></i></button>
  </div>
</form>


问:
Adding condition when counting NA value by a group
I am counting row-based Na values according to col1 variable in the data set. I want to add a condition to this query:

When calculating the number of NA,
For col2 = a and b, also look at col4 column, for col2 = c, do not look at col4 column

```<code># creating a dataframe
data_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE),
                        col2 = letters[1:3],
                        col3 = c(1,NA,NA,1,NA,NA,2,NA,2),
                        col4 = c(1,4,NA,1,NA,NA,NA,1,2))

data_frame = data_frame %>%
   rowwise() %>%
   mutate(Count_NA = sum(is.na(cur_data()))) %>%
   ungroup

#print (data_frame)

data_frame %>% group_by(col1) %>%
   summarize(Sum_Count_NA=sum(Count_NA))
</code>```

The output I want is;

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
2

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
2

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

After adding the condition, the output I want is;
Counting Na in col4 for col2 = c

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
1

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
1

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

答:
An option is also to replace the NA elements in the 'col4' with non-NA when 'col2' is 'c' and then do the rowSums on the logical matrix

```<code>library(dplyr)
data_frame %>%
   mutate(Count_Na = rowSums(is.na(cbind(col3, replace(col4, col2 == 'c', 999)))))
</code>```

-output

```<code> col1 col2 col3 col4 Count_Na
1    7    a    1    1        0
2    9    b   NA    4        1
3    9    c   NA   NA        1
4    7    a    1    1        0
5    7    b   NA   NA        2
6    7    c   NA   NA        1
7    7    a    2   NA        1
8    9    b   NA    1        1
9    7    c    2    2        0
</code>```

Body:
I am counting row-based Na values according to col1 variable in the data set. I want to add a condition to this query:

When calculating the number of NA,
For col2 = a and b, also look at col4 column, for col2 = c, do not look at col4 column

# creating a dataframe
data_frame <- data.frame(col1 = sample(6:9, 9 , replace = TRUE),
                        col2 = letters[1:3],
                        col3 = c(1,NA,NA,1,NA,NA,2,NA,2),
                        col4 = c(1,4,NA,1,NA,NA,NA,1,2))

data_frame = data_frame %>%
   rowwise() %>%
   mutate(Count_NA = sum(is.na(cur_data()))) %>%
   ungroup

#print (data_frame)

data_frame %>% group_by(col1) %>%
   summarize(Sum_Count_NA=sum(Count_NA))

The output I want is;

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
2

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
2

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

After adding the condition, the output I want is;
Counting Na in col4 for col2 = c

col1
col2
col3
col4
Count_NA

8
a
1
1
0

6
b
NA
4
1

8
c
NA
NA
1

7
a
1
1
0

8
b
NA
NA
2

8
c
NA
NA
1

8
a
2
NA
1

8
b
NA
1
1

9
c
2
2
0

Body:
An option is also to replace the NA elements in the 'col4' with non-NA when 'col2' is 'c' and then do the rowSums on the logical matrix

library(dplyr)
data_frame %>%
   mutate(Count_Na = rowSums(is.na(cbind(col3, replace(col4, col2 == 'c', 999)))))

-output

 col1 col2 col3 col4 Count_Na
1    7    a    1    1        0
2    9    b   NA    4        1
3    9    c   NA   NA        1
4    7    a    1    1        0
5    7    b   NA   NA        2
6    7    c   NA   NA        1
7    7    a    2   NA        1
8    9    b   NA    1        1
9    7    c    2    2        0


问:
How to wrap external paths (include, lib) and definitions into a target in cmake
Rather than providing a target, some libraries like LibRaw generate variables that contain information about include paths, library paths and compile definitions. In the case of LibRaw, vcpkg recommends the following usage:

```<code>target_compile_definitions(main PRIVATE ${LibRaw_DEFINITIONS})
target_include_directories(main PRIVATE ${LibRaw_INCLUDE_DIR})
target_link_libraries(main PRIVATE ${LibRaw_LIBRARIES})
</code>```

However, I would much rather stay consistent on linking libraries using

```<code>target_link_libraries(main PRIVATE LibRaw)
</code>```

Is there a way to wrap all of the provided variables into a target.

答:
You can create your own target:</p>
```<code>add_library( MyLibRaw INTERFACE IMPORTED )

set_target_properties(MyLibRaw
    PROPERTIES
        INTERFACE_INCLUDE_DIRECTORIES ${LibRaw_INCLUDE_DIR}
        IMPORTED_IMPLIB_DEBUG ${LibRaw_LIBRARIES_debug}
        IMPORTED_IMPLIB_RELEASE ${LibRaw_LIBRARIES_release}
        IMPORTED_LOCATION_DEBUG ${LibRaw_LIBRARIES_shared_debug}
        IMPORTED_LOCATION_RELEASE ${LibRaw_LIBRARIES_shared_release}
)

target_link_libraries(MyLibRaw
    INTERFACE
        optimized $<TARGET_PROPERTY:MyLibRaw ,IMPORTED_IMPLIB_RELEASE>
        debug $<TARGET_PROPERTY:MyLibRaw ,IMPORTED_IMPLIB_DEBUG>
)
</code>```

Body:
Rather than providing a target, some libraries like LibRaw generate variables that contain information about include paths, library paths and compile definitions. In the case of LibRaw, vcpkg recommends the following usage:

target_compile_definitions(main PRIVATE ${LibRaw_DEFINITIONS})
target_include_directories(main PRIVATE ${LibRaw_INCLUDE_DIR})
target_link_libraries(main PRIVATE ${LibRaw_LIBRARIES})

However, I would much rather stay consistent on linking libraries using

target_link_libraries(main PRIVATE LibRaw)

Is there a way to wrap all of the provided variables into a target.

Body:
You can create your own target:

add_library( MyLibRaw INTERFACE IMPORTED )

set_target_properties(MyLibRaw
    PROPERTIES
        INTERFACE_INCLUDE_DIRECTORIES ${LibRaw_INCLUDE_DIR}
        IMPORTED_IMPLIB_DEBUG ${LibRaw_LIBRARIES_debug}
        IMPORTED_IMPLIB_RELEASE ${LibRaw_LIBRARIES_release}
        IMPORTED_LOCATION_DEBUG ${LibRaw_LIBRARIES_shared_debug}
        IMPORTED_LOCATION_RELEASE ${LibRaw_LIBRARIES_shared_release}
)

target_link_libraries(MyLibRaw
    INTERFACE
        optimized $<TARGET_PROPERTY:MyLibRaw ,IMPORTED_IMPLIB_RELEASE>
        debug $<TARGET_PROPERTY:MyLibRaw ,IMPORTED_IMPLIB_DEBUG>
)


问:
the files generated by docker
My question is the files generated by running docker are not within the user's permission while within the root's. This is absolutely not a feature that I want.

So, there are two possible solutions:
(1) Change the permission after the files are generated. Like, use the command line chmod 777. But it is very time-consuming and error-prune.
(2) During the running of the docker directly change the permission of the docker running for which I do not know how to realize but there must be a way to fix it.

Which solution is better? And why?

An example is the following. I create a Dockerfile:

```<code>FROM pytorch/pytorch:1.9.0-cuda11.1-cudnn8-devel
</code>```

Then I build it with the command docker build -t test .
After that, I run it with the command docker run -d -t test:latest.
Then I run docker exec -it test bash.
Then I am in the container. Then I run touch test.txt and made some editing on the test.txt.

Then I exit the container. I would like to edit the test.txt on my local machine. Then I find I can not do that.

What should I do? chmod 777 test.txt is a solution. But what if I generate multiple files in different locations?

Best regards,

George Yang

答:
By default, docker uses the root account when you start the container. But there is nothing stopping you from running as a different user.

https://docs.docker.com/engine/reference/run/#user

USER root (id = 0) is the default user within a container. The image
developer can create additional users. Those users are accessible by
name. When passing a numeric ID, the user does not have to exist in
the container.

The developer can set a default user to run the first process with the
Dockerfile USER instruction. When starting a container, the operator
can override the USER instruction by passing the -u option.

-u="", --user="": Sets the username or UID used and optionally the groupname or GID for the specified command.

The followings examples are all valid:
--user=[ user | user:group | uid | uid:gid | user:gid | uid:group ] Note: if you pass a numeric uid, it must be in the range of
0-2147483647.

So, since your user doesn't exist in the image, you can't use your username and must use the uid instead.

Title: the files generated by docker

Body:
My question is the files generated by running docker are not within the user's permission while within the root's. This is absolutely not a feature that I want.

So, there are two possible solutions:
(1) Change the permission after the files are generated. Like, use the command line chmod 777. But it is very time-consuming and error-prune.
(2) During the running of the docker directly change the permission of the docker running for which I do not know how to realize but there must be a way to fix it.

Which solution is better? And why?

An example is the following. I create a Dockerfile:

FROM pytorch/pytorch:1.9.0-cuda11.1-cudnn8-devel

Then I build it with the command docker build -t test .
After that, I run it with the command docker run -d -t test:latest.
Then I run docker exec -it test bash.
Then I am in the container. Then I run touch test.txt and made some editing on the test.txt.

Then I exit the container. I would like to edit the test.txt on my local machine. Then I find I can not do that.

What should I do? chmod 777 test.txt is a solution. But what if I generate multiple files in different locations?

Best regards,

George Yang


问:
Joining a List with a Table in C#
I have the following Model and populated Data as follows.

```<code>public class School
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Class {get;set;}
 public bool IsActive {get;set;}
}

//After making a service I get the following data with IsActive as false initially.
List<School> schoolList = //make service call
[{1,'A','First',0} , {2,'B','Second',0}].
</code>```

Next I have a MasterTable table with columns as ID,Name,Area .
Eg:

```<code>1 A ABC
2 B DEF
3 H GHJ
</code>```

If the data stored in Name property in schoolList matches with Name in MasterTable , then once again I need to update the IsActive property of schoolList as true .

I tried the following approach.

Get all the data from MasterTable using EF Core and extract Name column and store it in a List NameFromMasterTable ;

Loop schoolList.ForEach() and in the loop, check if Name is present in NameFromMasterTable and if found update , IsActive as true.

Since this approach fetches all the data from table and also looping on each and every row and updating is a expensive operation. Whats the best way to update the IsActive of schoolList to true if Name is found in MasterTable's Name column?

答:
I think you will need at least two loops for this, but the inclusion of a HashSet<T> will prevent the O(N^2) time complexity.  If you create a HashSet<string> and populate it with the Name values from MasterTable you can then use this collection as a reference when iterating schoolList to set IsActive.

The HashSet<T>.Contains() method is O(1).  This is all assuming you do not care about the ID column in either of the tables, which seems to be the case.

HashSet<T> has a constructor that takes IEqualityComparer<string> if you need to be concerned with case sensitivity.

Title: Joining a List with a Table in C#

Body:
I have the following Model and populated Data as follows.

public class School
{
 public int Id {get;set;}
 public string Name {get;set;}
 public string Class {get;set;}
 public bool IsActive {get;set;}
}

//After making a service I get the following data with IsActive as false initially.
List<School> schoolList = //make service call
[{1,'A','First',0} , {2,'B','Second',0}].

Next I have a MasterTable table with columns as ID,Name,Area .
Eg:

1 A ABC
2 B DEF
3 H GHJ

If the data stored in Name property in schoolList matches with Name in MasterTable , then once again I need to update the IsActive property of schoolList as true .

I tried the following approach.

Get all the data from MasterTable using EF Core and extract Name column and store it in a List NameFromMasterTable ;

Loop schoolList.ForEach() and in the loop, check if Name is present in NameFromMasterTable and if found update , IsActive as true.

Since this approach fetches all the data from table and also looping on each and every row and updating is a expensive operation. Whats the best way to update the IsActive of schoolList to true if Name is found in MasterTable's Name column?


问:
When to use aws direct connect and aws storage gateway

When to use aws direct connect and aws storage gateway. My question is these services seems to be similer, so what are use cases to use these two services.

答:
Storage Gateway - As the name suggests, this service is used to connect on-premises infra with STORAGE services (specifically S3, FSx, EBS)

Direct Connect - This service is used to connect on-premises infra with any AWS resources (in any region)


问:
Search multiple column values with one search string
I have this query where I want to return results if the search string provided yields data from the 'FirstName' and 'LastName' column of my database. They each work individually as I can get results for Firstname = 'john' and LastName = 'doe'. I also want to be able to pass in a search string of 'John doe' and get results. How would I implement this using .net/linq

snippet:
var query = _context.Players.Where(p => p.Firstname.Contains(searchString.ToLower().Trim()) || p.Lastname.Contains(searchString.ToLower().Trim()));

答:
Created an extension method class to isolate the functional parts of search algo. This is based on pattern matching algo. You can try this one once.</p>
```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

static class Extensions
{
    public static void Sanitize(this string item)
    {
        Regex rgx = new Regex("[^a-AA-Z0-9 -]");
        item = rgx.Replace(item, " ");
    }

    public static string GetPipedString(this string item)
    {
        StringBuilder builder = new StringBuilder();
        item.Split(' ').ToList().ForEach(x => builder.Append('|').Append(x));
        builder.Remove(0, 1);
        return builder.ToString();
    }

    public static IEnumerable<Person> FindPlayers(this IEnumerable<Person> persons, string searchKey)
    {
        searchKey.Sanitize();
        string pattern = string.Format(@"^?:{0}\w*$", searchKey.GetPipedString());
        return persons.Where(x => Regex.IsMatch(
                              string.Join(string.Empty,
                              new List<string>() { x.FirstName, x.LastName }),
                              pattern,
                              RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace));
    }
}

class Program
{
    static void Main(string[] args)
    {
        /* Assuming peoples is the IEnumerable<Person>.
           Anyways there is an explicit sanitization of the string to remove the non alphanum characters*/
        var items = peoples.FindPlayers("ANY DATA SPACE SEPARATED").ToList();
    }
}
</code>```

Body:
Created an extension method class to isolate the functional parts of search algo. This is based on pattern matching algo. You can try this one once.

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

static class Extensions
{
    public static void Sanitize(this string item)
    {
        Regex rgx = new Regex("[^a-AA-Z0-9 -]");
        item = rgx.Replace(item, " ");
    }

    public static string GetPipedString(this string item)
    {
        StringBuilder builder = new StringBuilder();
        item.Split(' ').ToList().ForEach(x => builder.Append('|').Append(x));
        builder.Remove(0, 1);
        return builder.ToString();
    }

    public static IEnumerable<Person> FindPlayers(this IEnumerable<Person> persons, string searchKey)
    {
        searchKey.Sanitize();
        string pattern = string.Format(@"^?:{0}\w*$", searchKey.GetPipedString());
        return persons.Where(x => Regex.IsMatch(
                              string.Join(string.Empty,
                              new List<string>() { x.FirstName, x.LastName }),
                              pattern,
                              RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace));
    }
}

class Program
{
    static void Main(string[] args)
    {
        /* Assuming peoples is the IEnumerable<Person>.
           Anyways there is an explicit sanitization of the string to remove the non alphanum characters*/
        var items = peoples.FindPlayers("ANY DATA SPACE SEPARATED").ToList();
    }
}


问:
Docker pull fails with "failed to register layer: sync ... input/output error"
Attempting to pull a docker image and got the following result:</p>
```<code>2f94e549220a: Pull complete
72007112f52f: Pull complete
e1886834052f: Pull complete
934c6c525c1d: Pull complete
6bc1674f1e8f: Pull complete
07e666cf45ea: Pull complete
609b62e99828: Extracting   5.23GB/5.23GB
bbd38441b44b: Download complete
4e6cf32e909d: Download complete
3ed8401905bf: Download complete
failed to register layer: sync /var/lib/docker/image/overlay2/layerdb/tmp/write-set-315662188/diff: input/output error
</code>```

答: Judging by the input/output error, and knowing that I had less than ~10GB left on my drive, I cleaned up some more space and reran the pull command. Error was resolved.

Body:
Attempting to pull a docker image and got the following result:

2f94e549220a: Pull complete
72007112f52f: Pull complete
e1886834052f: Pull complete
934c6c525c1d: Pull complete
6bc1674f1e8f: Pull complete
07e666cf45ea: Pull complete
609b62e99828: Extracting   5.23GB/5.23GB
bbd38441b44b: Download complete
4e6cf32e909d: Download complete
3ed8401905bf: Download complete
failed to register layer: sync /var/lib/docker/image/overlay2/layerdb/tmp/write-set-315662188/diff: input/output error


问:
Snowflake: Configure Microsoft Azure AD for External OAuth - admin consent
I am using this guide to configure Microsoft Azure AD for external OAuth in Snowflake.
I'm pretty sure that I followed all the steps because tried that meticulously on three Azure subscriptions and got the same result.

Every time I got stuck at the testing procedure section where I'm supposed to send a request to Azure AD to get an access token:

```<code>curl -X POST -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
  --data-urlencode "client_id=<OAUTH_CLIENT_ID>" \
  --data-urlencode "client_secret=<OAUTH_CLIENT_SECRET>" \
  --data-urlencode "username=<AZURE_AD_USER>" \
  --data-urlencode "password=<AZURE_AD_USER_PASSWORD>" \
  --data-urlencode "grant_type=password" \
  --data-urlencode "scope=session:role:analyst" \
  '<AZURE_AD_OAUTH_TOKEN_ENDPOINT>'
</code>```

I am a subscription owner and definitely granted admin access to the session:role:analyst scope:

However, instead of the access token, I get the following response:

```<code>{
    "error": "invalid_grant",
    "error_description": "AADSTS65001: The user or administrator has not consented to use the application with ID '...' named 'Snowflake OAuth Client'. Send an interactive authorization request for this user and resource.\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        65001
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "...",
    "suberror": "consent_required"
}
</code>```

Tried to grant the consent by reaching https://login.microsoftonline.com/{{tenant_id}}/adminconsent?client_id={{client_id}} and after granting the consent, got an error: AADSTS500113: No reply address is registered for the application.

Found this and added the return URL http://localhost/ (without a clear understanding of why). Granted the consent again and was redirected to http://localhost/?admin_consent=True&tenant={{tenant_id}}# which, I suppose, is fine.

But I still get AADSTS65001: The user or administrator has not consented to use the application.

Reached to Microsoft documentation and figured out that using grant_type=password is not recommended - makes sense.

Tried grant_type=client credentials:

```<code>curl --location --request GET 'https://login.microsoftonline.com/{{tenant_id}}/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id={{client_id}}' \
--data-urlencode 'scope=https://graph.microsoft.com/.default' \
--data-urlencode 'client_secret={{client_secret}}'
</code>```

Got the access token, but attempts to connect to Snowflake with a connection string like:

```<code>connection.ConnectionString = $"account={account};host={host};authenticator=oauth;user={oauthUser};token={token};";
</code>```

Throw Snowflake.Data.Client.SnowflakeDbException: 'Invalid OAuth access token..

I suspect this is because scope=https://graph.microsoft.com/.default, but replacing it with session:scope:analyst brings this:

```<code>{
    "error": "invalid_scope",
    "error_description": "AADSTS1002012: The provided value for scope session:scope:analyst is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        1002012
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "..."
}
</code>```

Since I already deviated from the official Snowflake guide, I'm asking the community for help with this issue. Thank you in in advance!

答:
When obtaining an access token with the Resource Owner Password Credentials Grant flow (which is not recommended and you really shouldn't do), the resulting access token is for accessing a resource (API) on behalf of the signed-in user. In the Microsoft identity platform, access on behalf of a user requires the client application be granted at least one delegated permissions to the requested resource.

In your screenshot, we see that the permission you granted for "Snowflake OAuth Resource" is an application permission (aka "app role").

You need to do two things:

On the resource app's app registration, make sure you followed sub-step 10 under Step 1: Configure the OAuth Resource in Azure AD, and defined "session:scope:analyst" as a delegated permission (scope).

In the client's app registration, under API permissions, choose the corresponding delegated permission for the resource, and grant it.

Then, when you go to test obtaining the token, make sure the "scope" parameter is the full scope value, including the resource's identifier URI (which you defined in sub-step 9). For example, if your identifier URI is https://my.snowflake.example.com, then the "scope" value would be https://my.snowflake.example.com/session:role:analyst and your cURL request would be:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
  --data-urlencode "client_id=<OAUTH_CLIENT_ID>" \
  --data-urlencode "client_secret=<OAUTH_CLIENT_SECRET>" \
  --data-urlencode "username=<AZURE_AD_USER>" \
  --data-urlencode "password=<AZURE_AD_USER_PASSWORD>" \
  --data-urlencode "grant_type=password" \
  --data-urlencode "scope=https://my.snowflake.example.com/session:role:analyst" \
  '<AZURE_AD_OAUTH_TOKEN_ENDPOINT>'
```

WARNING: The Resource Owner Password Credentials Grant flow is not recommended. I suggest reaching out to app publishers who are suggesting you use this flow. Here is Microsoft's warning on the subject:

Microsoft recommends you do not use the ROPC flow. In most scenarios, more secure alternatives are available and recommended. This flow requires a very high degree of trust in the application, and carries risks which are not present in other flows. You should only use this flow when other more secure flows can't be used.

Body:
I am using this guide to configure Microsoft Azure AD for external OAuth in Snowflake.
I'm pretty sure that I followed all the steps because tried that meticulously on three Azure subscriptions and got the same result.

Every time I got stuck at the testing procedure section where I'm supposed to send a request to Azure AD to get an access token:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
  --data-urlencode "client_id=<OAUTH_CLIENT_ID>" \
  --data-urlencode "client_secret=<OAUTH_CLIENT_SECRET>" \
  --data-urlencode "username=<AZURE_AD_USER>" \
  --data-urlencode "password=<AZURE_AD_USER_PASSWORD>" \
  --data-urlencode "grant_type=password" \
  --data-urlencode "scope=session:role:analyst" \
  '<AZURE_AD_OAUTH_TOKEN_ENDPOINT>'

I am a subscription owner and definitely granted admin access to the session:role:analyst scope:

However, instead of the access token, I get the following response:

{
    "error": "invalid_grant",
    "error_description": "AADSTS65001: The user or administrator has not consented to use the application with ID '...' named 'Snowflake OAuth Client'. Send an interactive authorization request for this user and resource.\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        65001
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "...",
    "suberror": "consent_required"
}

Tried to grant the consent by reaching https://login.microsoftonline.com/{{tenant_id}}/adminconsent?client_id={{client_id}} and after granting the consent, got an error: AADSTS500113: No reply address is registered for the application.

Found this and added the return URL http://localhost/ (without a clear understanding of why). Granted the consent again and was redirected to http://localhost/?admin_consent=True&tenant={{tenant_id}}# which, I suppose, is fine.

But I still get AADSTS65001: The user or administrator has not consented to use the application.

Reached to Microsoft documentation and figured out that using grant_type=password is not recommended - makes sense.

Tried grant_type=client credentials:

curl --location --request GET 'https://login.microsoftonline.com/{{tenant_id}}/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id={{client_id}}' \
--data-urlencode 'scope=https://graph.microsoft.com/.default' \
--data-urlencode 'client_secret={{client_secret}}'

Got the access token, but attempts to connect to Snowflake with a connection string like:

connection.ConnectionString = $"account={account};host={host};authenticator=oauth;user={oauthUser};token={token};";

Throw Snowflake.Data.Client.SnowflakeDbException: 'Invalid OAuth access token..

I suspect this is because scope=https://graph.microsoft.com/.default, but replacing it with session:scope:analyst brings this:

{
    "error": "invalid_scope",
    "error_description": "AADSTS1002012: The provided value for scope session:scope:analyst is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: ...",
    "error_codes": [
        1002012
    ],
    "timestamp": "...",
    "trace_id": "...",
    "correlation_id": "..."
}

Since I already deviated from the official Snowflake guide, I'm asking the community for help with this issue. Thank you in in advance!

Body:
When obtaining an access token with the Resource Owner Password Credentials Grant flow (which is not recommended and you really shouldn't do), the resulting access token is for accessing a resource (API) on behalf of the signed-in user. In the Microsoft identity platform, access on behalf of a user requires the client application be granted at least one delegated permissions to the requested resource.

In your screenshot, we see that the permission you granted for "Snowflake OAuth Resource" is an application permission (aka "app role").

You need to do two things:

On the resource app's app registration, make sure you followed sub-step 10 under Step 1: Configure the OAuth Resource in Azure AD, and defined "session:scope:analyst" as a delegated permission (scope).

In the client's app registration, under API permissions, choose the corresponding delegated permission for the resource, and grant it.

Then, when you go to test obtaining the token, make sure the "scope" parameter is the full scope value, including the resource's identifier URI (which you defined in sub-step 9). For example, if your identifier URI is https://my.snowflake.example.com, then the "scope" value would be https://my.snowflake.example.com/session:role:analyst and your cURL request would be:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" \
  --data-urlencode "client_id=<OAUTH_CLIENT_ID>" \
  --data-urlencode "client_secret=<OAUTH_CLIENT_SECRET>" \
  --data-urlencode "username=<AZURE_AD_USER>" \
  --data-urlencode "password=<AZURE_AD_USER_PASSWORD>" \
  --data-urlencode "grant_type=password" \
  --data-urlencode "scope=https://my.snowflake.example.com/session:role:analyst" \
  '<AZURE_AD_OAUTH_TOKEN_ENDPOINT>'

WARNING: The Resource Owner Password Credentials Grant flow is not recommended. I suggest reaching out to app publishers who are suggesting you use this flow. Here is Microsoft's warning on the subject:

Microsoft recommends you do not use the ROPC flow. In most scenarios, more secure alternatives are available and recommended. This flow requires a very high degree of trust in the application, and carries risks which are not present in other flows. You should only use this flow when other more secure flows can't be used.


问:
gVim: How to load multiple files in buffer?
Im in windows and is new in using gvim. I am using the Nerdtree plugin for project navigations. Right now I open files from the nerd tree, vim will then load this opened files in the buffer. I find it easier to switch throug multiple files using the :b command, it gets more convenient after opening more files as more is loaded in the buffer.

But I think it will be more convenient if there is a way to load all files in a directory in the buffer at the same time instead of loading one by one when opening them.

答:
You can specify multiple files on the command line (or right-click 'Open with Single Vim' in windows).

Equivalently, you can add or change the argument list after starting:

```<code>:args *.cs
</code>```

Replaces the argument list, opening all files as buffers, showing just one

```<code>:argadd **/.java
</code>```

Appends all java files in the tree below the current directory to the argument lst, opening them as buffers, keeping the active buffer in the current window unchanged

There are several other nice commands in relation to this:

```<code>:argdo %s/version_1-6-0/version_1-6-1/g
:bufdo g/SECRET/d
</code>```

(apply commands to all files in argument list vs. all open buffers)

```<code>:sall
:tab sall
</code>```

(open all loaded buffers in separate windows, optionally in tabs)

OT hint: to clear out the buffer list

```<code>:bufdo bclose
:bufdo bwipeout
:bufdo bwipeout!
</code>```

Set the current directory:

```<code>:cd $HOME/myproject/subdir
</code>```

Set it to the dir of the currently open file:

```<code>:cd %:h
</code>```

This is very handy with tools like :argadd *.cpp or :!ctags -R . etc.

Body:
You can specify multiple files on the command line (or right-click 'Open with Single Vim' in windows).

Equivalently, you can add or change the argument list after starting:

:args *.cs

Replaces the argument list, opening all files as buffers, showing just one

:argadd **/.java

Appends all java files in the tree below the current directory to the argument lst, opening them as buffers, keeping the active buffer in the current window unchanged

There are several other nice commands in relation to this:

:argdo %s/version_1-6-0/version_1-6-1/g
:bufdo g/SECRET/d

(apply commands to all files in argument list vs. all open buffers)

:sall
:tab sall

(open all loaded buffers in separate windows, optionally in tabs)

OT hint: to clear out the buffer list

:bufdo bclose
:bufdo bwipeout
:bufdo bwipeout!

Set the current directory:

:cd $HOME/myproject/subdir

Set it to the dir of the currently open file:

:cd %:h

This is very handy with tools like :argadd *.cpp or :!ctags -R . etc.


问:
django-import-export, importing ManyToMany from XLSX
For my current project I need to import data from excelsheets format .xlsx to the django-admin. I'm struggling with the many2many relations that I have in my models. The importing feature just doesn't recognize the many2many fields and imports only the remaining fields (normal and foreignkey).
Same goes for exporting, all fields except the many2many get exported into a excelsheet, although I dont need this feature, just tested it.

For better understanding the code snippets from my models.py, admin.py, resources.py and widgets.py.

I tried the default many2many widget -> in the TeacherResource in resources.py
and I also tired overriding the default m2m widget -> StudyfieldWidget in widgets.py

```<code>models.py

class Translation(models.Model):
    de = models.TextField(unique=True)
    en = models.TextField(unique=True)

    def __str__(self):
        return self.de

class Studyfield(models.Model):
    degree = models.CharField(max_length=50)
    title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+")

    def __str__(self):
        return self.title

class Course(models.Model):
    number = models.CharField(max_length=50)
    title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+")

    studyfields = models.ManyToManyField("Studyfield", related_name="course", blank=True)

    def __str__(self):
        return self.title

class Teacher(models.Model):
    name = models.CharField(max_length=50, blank=True)

    studyfields = models.ManyToManyField("Studyfield", related_name="teacher", blank=True)
    courses = models.ManyToManyField("Course", related_name="teacher", blank=True)

    def __str__(self):
        return self.name

admin.py

@admin.register(Translation)
class TranslationAdmin(ImportExportModelAdmin):
    resource_class = TranslationResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

@admin.register(Studyfield)
class StudyfieldAdmin(ImportExportModelAdmin):
    resource_class = StudyfieldResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

@admin.register(Course)
class CourseAdmin(ImportExportModelAdmin):
    resource_class = CourseResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

@admin.register(Teacher)
class TeacherAdmin(ImportExportModelAdmin):
    resource_class = TeacherResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

resources.py

class TranslationResource(resources.ModelResource):
    class Meta:
        model = Translation
        fields = ('id', 'de', 'en')

class StudyfieldResource(resources.ModelResource):
    title = fields.Field(
        column_name = 'title',
        attribute = 'title',
        widget = TranslationWidget(Translation, 'de'),
    )

    class Meta:
        model = Studyfield
        fields = ('id', 'degree', 'title')

class CourseResource(resources.ModelResource):
    title = fields.Field(
        column_name = 'title',
        attribute = 'title',
        widget = TranslationWidget(Translation, 'de')
    )

    studyfields = fields.Field(
        widget = StudyfieldWidget(Studyfield)
    )

    class Meta:
        model = Course
        fields = ('id', 'number', 'title', 'studyfields')

class TeacherResource(resources.ModelResource):
    studyfields = fields.Field(
        widget = ManyToManyWidget(Studyfield)
    )

    courses = fields.Field(
        widget = ManyToManyWidget(Course)
    )

    class Meta:
        model = Teacher
        fields = ('id', 'name', 'studyfields', 'courses')

widgets.py

class TranslationWidget(widgets.ForeignKeyWidget):
    def clean(self, value, row=None, *args, **kwargs):
        return self.model.objects.get_or_create(de=value)[0] if value else None

class StudyfieldWidget(widgets.ManyToManyWidget):
    def clean(self, value, row=None, *args, **kwargs):
        if not value:
            return self.model.objects.none()
        if isinstance(value, (float, int)):
            ids = [int(value)]
        else:
            ids = value.split(self.separator)
            ids = filter(None, [i.strip() for i in ids])
        return self.model.objects.filter(**{
            '%s__in' % self.field: ids
        })
</code>```

答:
It seems you didn't set the separator?

This is how I make it work.

```<code>studyfields = fields.Field(
    attribute='provider',
    widget=widgets.ManyToManyWidget(Studyfield, field='title', separator=',')
)
</code>```

Attribute = the name of the column as in your model.
field = the name of the related name that you are going to send, in your case, title or degree.

separator = how its going to be separated in the excel (boo,baa,bii)

Body:
For my current project I need to import data from excelsheets format .xlsx to the django-admin. I'm struggling with the many2many relations that I have in my models. The importing feature just doesn't recognize the many2many fields and imports only the remaining fields (normal and foreignkey).
Same goes for exporting, all fields except the many2many get exported into a excelsheet, although I dont need this feature, just tested it.

For better understanding the code snippets from my models.py, admin.py, resources.py and widgets.py.

I tried the default many2many widget -> in the TeacherResource in resources.py
and I also tired overriding the default m2m widget -> StudyfieldWidget in widgets.py

models.py

class Translation(models.Model):
    de = models.TextField(unique=True)
    en = models.TextField(unique=True)

    def __str__(self):
        return self.de

class Studyfield(models.Model):
    degree = models.CharField(max_length=50)
    title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+")

    def __str__(self):
        return self.title

class Course(models.Model):
    number = models.CharField(max_length=50)
    title = models.ForeignKey("Translation", on_delete=models.CASCADE, related_name="+")

    studyfields = models.ManyToManyField("Studyfield", related_name="course", blank=True)

    def __str__(self):
        return self.title

class Teacher(models.Model):
    name = models.CharField(max_length=50, blank=True)

    studyfields = models.ManyToManyField("Studyfield", related_name="teacher", blank=True)
    courses = models.ManyToManyField("Course", related_name="teacher", blank=True)

    def __str__(self):
        return self.name

admin.py

@admin.register(Translation)
class TranslationAdmin(ImportExportModelAdmin):
    resource_class = TranslationResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

@admin.register(Studyfield)
class StudyfieldAdmin(ImportExportModelAdmin):
    resource_class = StudyfieldResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

@admin.register(Course)
class CourseAdmin(ImportExportModelAdmin):
    resource_class = CourseResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

@admin.register(Teacher)
class TeacherAdmin(ImportExportModelAdmin):
    resource_class = TeacherResource
    ordering = ('id',)
    formats = [base_formats.XLSX]

resources.py

class TranslationResource(resources.ModelResource):
    class Meta:
        model = Translation
        fields = ('id', 'de', 'en')

class StudyfieldResource(resources.ModelResource):
    title = fields.Field(
        column_name = 'title',
        attribute = 'title',
        widget = TranslationWidget(Translation, 'de'),
    )

    class Meta:
        model = Studyfield
        fields = ('id', 'degree', 'title')

class CourseResource(resources.ModelResource):
    title = fields.Field(
        column_name = 'title',
        attribute = 'title',
        widget = TranslationWidget(Translation, 'de')
    )

    studyfields = fields.Field(
        widget = StudyfieldWidget(Studyfield)
    )

    class Meta:
        model = Course
        fields = ('id', 'number', 'title', 'studyfields')

class TeacherResource(resources.ModelResource):
    studyfields = fields.Field(
        widget = ManyToManyWidget(Studyfield)
    )

    courses = fields.Field(
        widget = ManyToManyWidget(Course)
    )

    class Meta:
        model = Teacher
        fields = ('id', 'name', 'studyfields', 'courses')

widgets.py

class TranslationWidget(widgets.ForeignKeyWidget):
    def clean(self, value, row=None, *args, **kwargs):
        return self.model.objects.get_or_create(de=value)[0] if value else None

class StudyfieldWidget(widgets.ManyToManyWidget):
    def clean(self, value, row=None, *args, **kwargs):
        if not value:
            return self.model.objects.none()
        if isinstance(value, (float, int)):
            ids = [int(value)]
        else:
            ids = value.split(self.separator)
            ids = filter(None, [i.strip() for i in ids])
        return self.model.objects.filter(**{
            '%s__in' % self.field: ids
        })

Body:
It seems you didn't set the separator?

This is how I make it work.

studyfields = fields.Field(
    attribute='provider',
    widget=widgets.ManyToManyWidget(Studyfield, field='title', separator=',')
)

Attribute = the name of the column as in your model.
field = the name of the related name that you are going to send, in your case, title or degree.

separator = how its going to be separated in the excel (boo,baa,bii)


问:
Eclipse, CDT, (N)Curses and debugin/profiling
Hi!

Is it possible to debug/profile a ncurses based application written in Eclipse\CDT? By using eclipse IDE of course.

Main problem is that eclipse to run this application should use a external console but it wont do that.
Even redirecting output into a file (terminal) didnt change anything...

For now Im using valgrind to looking for leaks and other things and its hard to read output file wich a single editor. Eclipse had a plugin for valgrind but it can not import resoult data for analise.

Here is my configuration:

System Linux(Debian based)

Eclipse IDE

Valgrind as a profiler

答:
Yes, as long as the executable was compiled with debug symbols you can simply launch it in an external shell then attach the debugger after the process is up:

http://wiki.eclipse.org/CDT/User/FAQ#Can_I_debug_a_process_that_I_didn.27t_develop_in_Eclipse.3F

On the screenshot by that FAQ item, you'll be interested in the "C/C++ Attach to Application" Launch Configuration.


问:
Pandas to_excel from SQL query outputs a memory address
I am attempting to output the results of a SQL query to a database as an Excel file.

What appear to be UUID values are not outputting as strings properly, and I'm not sure how to get Pandas to output these as a hexadecimal string representation.

df = pd.read_sql(query,conn)
writer = pd.ExcelWriter(output_filename, engine='xlsxwriter')
df.to_excel(writer,"data")
```

Output of example value:
<memory at 0x00000204FC8C7AC0>

I attempted this:

df["GUID_LCXX"] = df["GUID_LCXX"].astype(str)

But the output was the same.

How can I get pandas to output the string hex value representation of the UUID and not a memory reference?

答:
Solved this myself, posting here for future searchers and in case someone wants to propose a more efficient/elegant solution.

guid_columns = ["GUID_LX1", "GUID_LX2"]
for col in guid_columns:
    df[col] = df[col].apply(lambda x: (x.tobytes().hex()).upper())
```

Body:
I am attempting to output the results of a SQL query to a database as an Excel file.

What appear to be UUID values are not outputting as strings properly, and I'm not sure how to get Pandas to output these as a hexadecimal string representation.

df = pd.read_sql(query,conn)
writer = pd.ExcelWriter(output_filename, engine='xlsxwriter')
df.to_excel(writer,"data")

Output of example value:
<memory at 0x00000204FC8C7AC0>

I attempted this:

df["GUID_LCXX"] = df["GUID_LCXX"].astype(str)

But the output was the same.

How can I get pandas to output the string hex value representation of the UUID and not a memory reference?


问:
when i try to run my project i get the error that says no module named flask
when I try to run my project I get the following error and it says no module named flask
I am using python 3.10 and it is the first time to get this error i used pywhatkit before and it worked

the error

```<code>File "D:\pythonProject\pypot\venv\lib\site-packages\pywhatkit\remotekit.py", line 6, in <module>
    from flask import Flask, request
ModuleNotFoundError: No module named 'flask'
</code>```

答:
You need to install flask from https://pypi.org/

You can do so with the command:  pip install flask

Or better, you create an virtual environnement and install flask in it

```<code>python -m venv myFlaskProject
.\myFlaskProject\Scripts\activate # windows
source ./myFlaskProject/bin/activate # MacOS, Linux
pip install flask
</code>```

Body:
when I try to run my project I get the following error and it says no module named flask
I am using python 3.10 and it is the first time to get this error i used pywhatkit before and it worked

the error

File "D:\pythonProject\pypot\venv\lib\site-packages\pywhatkit\remotekit.py", line 6, in <module>
    from flask import Flask, request
ModuleNotFoundError: No module named 'flask'

Body:
You need to install flask from https://pypi.org/

You can do so with the command:  pip install flask

Or better, you create an virtual environnement and install flask in it

python -m venv myFlaskProject
.\myFlaskProject\Scripts\activate # windows
source ./myFlaskProject/bin/activate # MacOS, Linux
pip install flask


问:
Hide portion of component in home component Angular
this is the ts file of an accordion component that I have called in the Home Page. However I want to use the parameter showOnHome to only display the ones with boolean true. How can I do that?</p>
```<code> @Component({
  selector: "app-faq",
  templateUrl: "./faq.component.html",
  styleUrls: ["./faq.component.css"],
})
export class FaqComponent implements OnInit {

  data = [
    {
      id: 1,
      question: "question1",
      answer: [
        "answer here",
      ],
      bullet: false,
      showOnHome: true,
    },
    {
      id: 2,
      question: "question2",
      answer: [
        "answer2",
      ],
      bullet: false,
      showOnHome: false,
    },]```

Called On Home Page as:
``` <app-faq></app-faq> ```
</code>```

答:
You can create a parameter for you component called showHome and filter internally for him.

```<code>export class FaqComponent {
  @Input() showHome: boolean = false;
  filteredData;

  data = [
    {
      id: 1,
      question: "question1",
      answer: ["answer here"],
      bullet: false,
      showOnHome: true
    },
    {
      id: 2,
      question: "question2",
      answer: ["answer2"],
      bullet: false,
      showOnHome: false
    }
  ];

  ngOnInit() {
    console.log(this.showHome);
    if (this.showHome) {
      this.filteredData = this.data.filter((question) => question.showOnHome);
    } else {
      this.filteredData = this.data;
    }
  }
}

</code>```

Called On Home Page as:

```<code><app-faq [showHome]="true"></app-faq>
</code>```

EDIT: Create a simple example how this works.
https://codesandbox.io/s/focused-nash-dlgsl?file=/src/app/app.component.html

Body:
this is the ts file of an accordion component that I have called in the Home Page. However I want to use the parameter showOnHome to only display the ones with boolean true. How can I do that?

 @Component({
  selector: "app-faq",
  templateUrl: "./faq.component.html",
  styleUrls: ["./faq.component.css"],
})
export class FaqComponent implements OnInit {

  data = [
    {
      id: 1,
      question: "question1",
      answer: [
        "answer here",
      ],
      bullet: false,
      showOnHome: true,
    },
    {
      id: 2,
      question: "question2",
      answer: [
        "answer2",
      ],
      bullet: false,
      showOnHome: false,
    },]```

Called On Home Page as:
``` <app-faq></app-faq> ```

Body:
You can create a parameter for you component called showHome and filter internally for him.

export class FaqComponent {
  @Input() showHome: boolean = false;
  filteredData;

  data = [
    {
      id: 1,
      question: "question1",
      answer: ["answer here"],
      bullet: false,
      showOnHome: true
    },
    {
      id: 2,
      question: "question2",
      answer: ["answer2"],
      bullet: false,
      showOnHome: false
    }
  ];

  ngOnInit() {
    console.log(this.showHome);
    if (this.showHome) {
      this.filteredData = this.data.filter((question) => question.showOnHome);
    } else {
      this.filteredData = this.data;
    }
  }
}

Called On Home Page as:

<app-faq [showHome]="true"></app-faq>

EDIT: Create a simple example how this works.
https://codesandbox.io/s/focused-nash-dlgsl?file=/src/app/app.component.html


问:
How to add copy code snippet button in React
I have code snippet. I need to add space between different lines so I have   and ```</code> for the code block. I want users to click on a button and copy this entire code as such.</p>
```
import {CopyToClipboard} from 'react-copy-to-clipboard';

let snippet =  ```<code>  {`
 z <!-- Start of test client code snippet -->

           <script>
               fjs.parentNode.insertBefore(js, fjs);
           })(window, document, "script", "_hw", "./widget.js");
           _hw("init", { debug: true, clientID: ${} });

           </script>
 <!-- End of test client code snippet -->
       `}
       </code>```

<CopyToClipboard text={snippet}>
          <button>Copy Snippet</button>
          </CopyToClipboard>

```

But it's not working. Does it work only for input field?

答:
Just wrap all snippet code in literals template.

```<code>const id = 1;
let snippet = ````
 z

       ````;

<CopyToClipboard text={snippet}>
   <button>Copy Snippet</button>
 </CopyToClipboard>
</code>```

Demo

Body:
I have code snippet. I need to add space between different lines so I have   and
 for the code block. I want users to click on a button and copy this entire code as such.

import {CopyToClipboard} from 'react-copy-to-clipboard';

let snippet =
  {`
 z

       `}

<CopyToClipboard text={snippet}>
          <button>Copy Snippet</button>
          </CopyToClipboard>

But it's not working. Does it work only for input field?

Body:
Just wrap all snippet code in literals template.

const id = 1;
let snippet = `<pre><code>
 z <!-- Start of test client code snippet -->

           <script>
               fjs.parentNode.insertBefore(js, fjs);
           })(window, document, "script", "_hw", "./widget.js");
           _hw("init", { debug: true, clientID: ${id}});

           </script>
 <!-- End of test client code snippet -->

       </code></pre>`;

<CopyToClipboard text={snippet}>
   <button>Copy Snippet</button>
 </CopyToClipboard>

Demo


问:
Oracle CLOB data type to Redshift data type
we are in the process of migrating Oracle tables to redshift tables. We found that few tables are having CLOB data type. In redshift we converted CLOB to Varchar(65535) type. While doing copy command , we are getting

The length of the data column investigation_process is longer than the length defined in the table. Table: 65000, Data: 90123.

Which data type we need to use? Please share your suggestion.

答:
Redshift isn't designed to store CLOB (or BLOB) data.  Most databases that do store the CLOB separately from the table contents to not burden all queries with the excess data.  A CLOB reference is stored in the table contents and a replacement of CLOB for reference is performed at result generation.

CLOBs should be stored in S3 and references to the appropriate CLOB (S3 key) stored in the Redshift table.  The issue is that there isn't a prepackaged tool for doing the CLOB for reference replacement with Redshift AFAIK.  Your solution will need some retooling to perform this replacement actions for all data users.  It's doable, it's just going to take a data layer that performs the needed replacement.


问:
Why needn't the query function in Room add suspend keyword in Kotlin?
I'm learning Coroutines of Kotlin.

The Code A is from the arctical https://github.com/googlecodelabs/android-room-with-a-view

I find that the keyword suspend are added for the Insert and Delete function.

Why needn't the query function getAlphabetizedWords() in Room add suspend keyword in Kotlin? I think that some query function need to spend long time to operate, so it need to run in Coroutines.

Code A

```<code>@Dao
interface WordDao {

    // LiveData is a data holder class that can be observed within a given lifecycle.
    // Always holds/caches latest version of data. Notifies its active observers when the
    // data has changed. Since we are getting all the contents of the database,
    // we are notified whenever any of the database contents have changed.
    @Query("SELECT * from word_table ORDER BY word ASC")
    fun getAlphabetizedWords(): LiveData<List<Word>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(word: Word)

    @Query("DELETE FROM word_table")
    suspend fun deleteAll()
}
</code>```

答:
In a more precise way !!

Especially from version room 2.1 , queries support suspend keyword,
This means, these queries marked with suspend will automatically get called in another thread by the room library itself, so these room queries are main safe.

And also additionally, if the return type is LiveData or flow, then suspend keyword is not necessary, because under the hood room will take heavy lifting and whenever data is changed it will provide the data at the observer end.

Body:
I'm learning Coroutines of Kotlin.

The Code A is from the arctical https://github.com/googlecodelabs/android-room-with-a-view

I find that the keyword suspend are added for the Insert and Delete function.

Why needn't the query function getAlphabetizedWords() in Room add suspend keyword in Kotlin? I think that some query function need to spend long time to operate, so it need to run in Coroutines.

Code A

@Dao
interface WordDao {

    // LiveData is a data holder class that can be observed within a given lifecycle.
    // Always holds/caches latest version of data. Notifies its active observers when the
    // data has changed. Since we are getting all the contents of the database,
    // we are notified whenever any of the database contents have changed.
    @Query("SELECT * from word_table ORDER BY word ASC")
    fun getAlphabetizedWords(): LiveData<List<Word>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(word: Word)

    @Query("DELETE FROM word_table")
    suspend fun deleteAll()
}