问:
How to select first N elements in hierarchical query (Oracle SQL)
I have the following problem. There is an hirarchy with millions of elements in oracle12 db. How can I select first N objects of hierarchy. It doesn't matter which objects should be selected, the only requirement is that objects should be in heirarcy.  Rownum filter doesn't work at all:

```<code>SELECT object_id
FROM objects
WHERE rownum < 10
START WITH object_id = 9072243521013844211
CONNECT BY PRIOR object_id = parent_id
</code>```

I get the following execution plan: filtering is done after objects select.

```<code>/*
LEVEL   PLAN    ROWS    COST    PREDICATES
*/
1   SELECT STATEMENT (OPTIMIZER=ALL_ROWS)   8   1

2     COUNT

3       FILTER          filter(ROWNUM<10)

4         CONNECT BY (WITH FILTERING)           access("PARENT_ID"=PRIOR "OBJECT_ID")

5           TABLE ACCESS (BY INDEX ROWID) "OBJECTS"

6             INDEX (UNIQUE SCAN) "XPKOBJECTS"  1   1   access("OBJECT_ID"=9072243521013844211)

5           NESTED LOOPS

6             CONNECT BY PUMP

6             TABLE ACCESS (BY INDEX ROWID BATCHED) "OBJECTS"   8   1

7               INDEX (RANGE SCAN) "XIF25OBJECTS"   8   1   access("PARENT_ID"=PRIOR "OBJECT_ID")
</code>```

答:
The following example solution should provide some guidance:</p>

```<code>with objects as
(select level object_id, decode(level+1, :len+1, null, level+1) parent_id
from dual connect by level<=:len )
SELECT object_id
FROM objects
where level <= :n_objects
START WITH object_id = 1
CONNECT BY PRIOR parent_id = object_id
;
</code>```

Body:
I have the following problem. There is an hirarchy with millions of elements in oracle12 db. How can I select first N objects of hierarchy. It doesn't matter which objects should be selected, the only requirement is that objects should be in heirarcy.  Rownum filter doesn't work at all:

SELECT object_id
FROM objects
WHERE rownum < 10
START WITH object_id = 9072243521013844211
CONNECT BY PRIOR object_id = parent_id

I get the following execution plan: filtering is done after objects select.

/*
LEVEL   PLAN    ROWS    COST    PREDICATES
*/
1   SELECT STATEMENT (OPTIMIZER=ALL_ROWS)   8   1

2     COUNT

3       FILTER          filter(ROWNUM<10)

4         CONNECT BY (WITH FILTERING)           access("PARENT_ID"=PRIOR "OBJECT_ID")

5           TABLE ACCESS (BY INDEX ROWID) "OBJECTS"

6             INDEX (UNIQUE SCAN) "XPKOBJECTS"  1   1   access("OBJECT_ID"=9072243521013844211)

5           NESTED LOOPS

6             CONNECT BY PUMP

6             TABLE ACCESS (BY INDEX ROWID BATCHED) "OBJECTS"   8   1

7               INDEX (RANGE SCAN) "XIF25OBJECTS"   8   1   access("PARENT_ID"=PRIOR "OBJECT_ID")

Body:
The following example solution should provide some guidance:

with objects as
(select level object_id, decode(level+1, :len+1, null, level+1) parent_id
from dual connect by level<=:len )
SELECT object_id
FROM objects
where level <= :n_objects
START WITH object_id = 1
CONNECT BY PRIOR parent_id = object_id
;


来源: stackexchange

问:
Simple solution for 3 circles (images) sitting horizontally equidistant apart and aligned
So for 3 days all I've been trying to do is have:

3 images shaped into circles

sitting aligned horizontally, equal distance apart

taking up central 70% of the screen

where all heights and widths are based on % (so they adjust with resizing of the browsers)

It seems like such a simple task, but after 3 days and asking multiple questions, I'm getting nowhere. Please, can someone write me a code to achieve this?

If it helps, I have this circle code so far:

Thanks if you can help me

(I am new to coding)

<!DOCTYPE html>

  <link rel="stylesheet" href="styles.css">
   <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Welcome to RyanTeaches

Activities

Helllllloooooooooo

```

答:
This should come close to a satisfactory solution. I optimized some code and used shorthand notation where possible and introduced class .band as a generic container with default values. The .band content will give it it's final height.

Also, to get a nice circle I introduced a responsive width and height constraint for the images. This is necessary to force images of any arbitrary size to fit nicely in a circle (check the sizes of the dummy images!)

height: calc(0.2 * 100vmin) will result in an circle of 64px at a minimum viewport size of 320px smoothly resizing to 256px at a minimum viewport size of 1280px, called responsive sizing.

I commented the code for as far I deemed relevant, let me know if you need more explanation or just want to pick my brain (caution: it is a bit of a mess up there).

body {
  max-width: 100%;
  height: 100%;
  margin: 0; /* remove nasty space around our page */
}

#navigation {
  color: #357eca;
  font-size: 1.5rem;
}

#parallax {
  background-image: url("bg.jpg");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

#parallax>div {
  z-index: 1;
  width: 50px;
  height: 2px;
  background: black;
  margin: 0 -60px;
}

#header {
  width: 50%;
  padding: 15px 5% 20px 5%;
  background-color: #357eca;
  opacity: 0.9;

  font-size: 4vw;
  text-align: center;
  font-weight: 900;
  word-wrap: break-word;
}

h5 {
  color:white;
  text-align: center;
  font-family: 'Montserrat';
  text-transform: uppercase;
  font-weight: 900;
}

.band { /* Nice grey'ish band as container */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eee;

  max-width: 100vw; /* stay in horizontal view */

  /* padding moves all content to center 70% of  */
  padding: 2rem 15%; /* 100% - 2 * 15% = 70% width */

  /* extra top/bottom spacing for clarity */
  margin: 1rem 0;
}

#container1 {
  justify-content: space-around; /* evenly space the images on the line */
}
[class^="img-circular"] {
  height: calc(0.2 * 100vmin); /* 64px at 320 and 256px at 1280 */
  width : calc(0.2 * 100vmin); /* nice responsive sizing */

  background-position: center;  /* center image in parent */
  background-repeat: no-repeat; /* prevents repeat of image! */
  background-size: cover;       /* stretch/shrink to fill */

  border-radius: 50%;
}
.img-circular1 { background-image: url("http://placehold.it/237x334") }
.img-circular2 { background-image: url("http://placehold.it/317x123") }
.img-circular3 { background-image: url("http://placehold.it/141x301") }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navigation" class="band">
        <p>navigation</p>
    </div>

    <div id="parallax" class="band">
        <div></div>
        <h5 id="header">
            <b>Welcome to RyanTeaches</b>
        </h5>
        <div></div>
    </div>

    <div class="band content">
        <h2>Activities</h2>
    </div>

    <div id="container1" class="band">
        <div class="img-circular1"></div>
        <div class="img-circular2"></div>
        <div class="img-circular3"></div>
    </div>

    <div class="band content">
        <p>Helllllloooooooooo</p>
    </div></code>```

ContentLicense: CC BY-SA 3.0

Body:
This should come close to a satisfactory solution. I optimized some code and used shorthand notation where possible and introduced class .band as a generic container with default values. The .band content will give it it's final height.

Also, to get a nice circle I introduced a responsive width and height constraint for the images. This is necessary to force images of any arbitrary size to fit nicely in a circle (check the sizes of the dummy images!)

height: calc(0.2 * 100vmin) will result in an circle of 64px at a minimum viewport size of 320px smoothly resizing to 256px at a minimum viewport size of 1280px, called responsive sizing.

I commented the code for as far I deemed relevant, let me know if you need more explanation or just want to pick my brain (caution: it is a bit of a mess up there).

body {
  max-width: 100%;
  height: 100%;
  margin: 0; /* remove nasty space around our page */
}

#navigation {
  color: #357eca;
  font-size: 1.5rem;
}

#parallax {
  background-image: url("bg.jpg");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

#parallax>div {
  z-index: 1;
  width: 50px;
  height: 2px;
  background: black;
  margin: 0 -60px;
}

#header {
  width: 50%;
  padding: 15px 5% 20px 5%;
  background-color: #357eca;
  opacity: 0.9;

  font-size: 4vw;
  text-align: center;
  font-weight: 900;
  word-wrap: break-word;
}

h5 {
  color:white;
  text-align: center;
  font-family: 'Montserrat';
  text-transform: uppercase;
  font-weight: 900;
}

.band { /* Nice grey'ish band as container */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eee;

  max-width: 100vw; /* stay in horizontal view */

  /* padding moves all content to center 70% of <body> */
  padding: 2rem 15%; /* 100% - 2 * 15% = 70% width */

  /* extra top/bottom spacing for clarity */
  margin: 1rem 0;
}

#container1 {
  justify-content: space-around; /* evenly space the images on the line */
}
[class^="img-circular"] {
  height: calc(0.2 * 100vmin); /* 64px at 320 and 256px at 1280 */
  width : calc(0.2 * 100vmin); /* nice responsive sizing */

  background-position: center;  /* center image in parent */
  background-repeat: no-repeat; /* prevents repeat of image! */
  background-size: cover;       /* stretch/shrink to fill */

  border-radius: 50%;
}
.img-circular1 { background-image: url("http://placehold.it/237x334") }
.img-circular2 { background-image: url("http://placehold.it/317x123") }
.img-circular3 { background-image: url("http://placehold.it/141x301") }

<div id="navigation" class="band">
        <p>navigation</p>
    </div>

    <div id="parallax" class="band">
        <div></div>
        <h5 id="header">
            <b>Welcome to RyanTeaches</b>
        </h5>
        <div></div>
    </div>

    <div class="band content">
        <h2>Activities</h2>
    </div>

    <div id="container1" class="band">
        <div class="img-circular1"></div>
        <div class="img-circular2"></div>
        <div class="img-circular3"></div>
    </div>

    <div class="band content">
        <p>Helllllloooooooooo</p>
    </div>


问:
Beautiful soup Python extracing data
I am very new to python. Long time user of stackoverflow but first time posting a question.
I am trying to extract data from website using beautifulsoup.
Sample Code where I want to extract is (listed in and tagged in data)

The was able to extract in to list but I am unable to extract the acutal data.
the goal here is to extract
Listed in: Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women
Tagged in: Makeup, Beauty, Nail polish

Can you please tell me how to achive it.

```<code>import requests
from bs4 import BeautifulSoup

l1=[]
url='http://boxes.mysubscriptionaddiction.com/box/julep-maven'
source_code=requests.get(url)
plain_text=source_code.text
soup= BeautifulSoup(plain_text,"lxml")
for item in soup.find_all('p'):
       l1.append(item.contents)
search='\nListed in:\n'
for a in l1:
    if a[0] in ('\nTagged in:\n','\nListed in:\n'):
        print(a)
</code>```

答:
```<code>soup = BeautifulSoup(plain_text, 'html.parser')

import re
context = soup(text=re.compile(r'Listed in:'))

for item in context:
    listed_in = item.parent
    tagged_in = listed_in.find_next_siblings()[0]

print(listed_in.text.strip('\n').replace('\n', ''))
print(tagged_in.text.strip('\n').replace('\n', ''))
</code>```

will display all in one line:

```<code>Listed in:Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women, Tagged in: Makeup, Beauty, Nail polish
</code>```

Hope that helps.

Title: Beautiful soup Python extracing data

Body:
I am very new to python. Long time user of stackoverflow but first time posting a question.
I am trying to extract data from website using beautifulsoup.
Sample Code where I want to extract is (listed in and tagged in data)

The was able to extract in to list but I am unable to extract the acutal data.
the goal here is to extract
Listed in: Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women
Tagged in: Makeup, Beauty, Nail polish

Can you please tell me how to achive it.

import requests
from bs4 import BeautifulSoup

l1=[]
url='http://boxes.mysubscriptionaddiction.com/box/julep-maven'
source_code=requests.get(url)
plain_text=source_code.text
soup= BeautifulSoup(plain_text,"lxml")
for item in soup.find_all('p'):
       l1.append(item.contents)
search='\nListed in:\n'
for a in l1:
    if a[0] in ('\nTagged in:\n','\nListed in:\n'):
        print(a)

Body:
soup = BeautifulSoup(plain_text, 'html.parser')

import re
context = soup(text=re.compile(r'Listed in:'))

for item in context:
    listed_in = item.parent
    tagged_in = listed_in.find_next_siblings()[0]

print(listed_in.text.strip('\n').replace('\n', ''))
print(tagged_in.text.strip('\n').replace('\n', ''))

will display all in one line:

Listed in:Nail Polish Subscription Boxes, Subscription Boxes for Beauty Products, Subscription Boxes for Women, Tagged in: Makeup, Beauty, Nail polish

Hope that helps.


问:
Can an @Input binding be an observable in Angular?
I'm creating a component that displays validation errors under input fields. If there is an error message shown, and the user submits the form I want to flash the message to draw their attention.

I was wondering if it's possible to use an observable as an input binding?

That way I can subscribe to the input and flash when any data is observed.

Here's an example of my idea:

```<code>@Component({..})
export class MessageComponent implement OnChanges {
   @Input()
   public flash: Observable<any>;

    public ngOnChanges(changes: SimpleChanges): void {
        if ('flash' in changes) {
            (<Observable<any>> changes['flash'].currentValue).subscribe(() => {
                // trigger the flash animation here
            });
        }
    }
}
</code>```

What I can't figure out is if this will leak memory, and how/when should I unsubscribe (or is it even necessary).

Is this kind of practice allowed in Angular?

答:
Yes, you can use an observable as an input.

Whether or not you need to unsubscribe depends upon the observable in question. When an observable completes or errors, any subscribers are unsubscribed automatically. So, in general, if you know an observable completes, explicit unsubscription is not necessary.

However, looking at your snippet, this seems to be a secondary issue, as you've written code suggesting that you expect the input to change.

In that case, you should unsubscribe whenever a change occurs. Otherwise, you will have two subscribers - with the first still listening to the original flash observable.

import { Subscription } from 'rxjs/Subscription';

@Component({..})
export class MessageComponent implement OnChanges, OnDestroy {

    @Input()
    public flash: Observable<any>;
    private flashSubscription: Subscription;

    public ngOnChanges(changes: SimpleChanges): void {
        if ('flash' in changes) {
            if (this.flashSubscription) {
                this.flashSubscription.unsubscribe();
            }
            this.flashSubscription = (<Observable<any>> changes['flash'].currentValue).subscribe(() => {
                // trigger the flash animation here
            });
        }
    }

    public ngOnDestroy(): void {
        if (this.flashSubscription) {
            this.flashSubscription.unsubscribe();
        }
    }
```

I'd also call unsubscribe in ngOnDestroy - so that unsubscription will occur for flash observables that don't complete or error.

Note that is is safe to call a subscription's unsubscribe method multiple times.

Body:
I'm creating a component that displays validation errors under input fields. If there is an error message shown, and the user submits the form I want to flash the message to draw their attention.

I was wondering if it's possible to use an observable as an input binding?

That way I can subscribe to the input and flash when any data is observed.

Here's an example of my idea:

@Component({..})
export class MessageComponent implement OnChanges {
   @Input()
   public flash: Observable<any>;

    public ngOnChanges(changes: SimpleChanges): void {
        if ('flash' in changes) {
            (<Observable<any>> changes['flash'].currentValue).subscribe(() => {
                // trigger the flash animation here
            });
        }
    }
}

What I can't figure out is if this will leak memory, and how/when should I unsubscribe (or is it even necessary).

Is this kind of practice allowed in Angular?

Body:
Yes, you can use an observable as an input.

Whether or not you need to unsubscribe depends upon the observable in question. When an observable completes or errors, any subscribers are unsubscribed automatically. So, in general, if you know an observable completes, explicit unsubscription is not necessary.

However, looking at your snippet, this seems to be a secondary issue, as you've written code suggesting that you expect the input to change.

In that case, you should unsubscribe whenever a change occurs. Otherwise, you will have two subscribers - with the first still listening to the original flash observable.

import { Subscription } from 'rxjs/Subscription';

@Component({..})
export class MessageComponent implement OnChanges, OnDestroy {

    @Input()
    public flash: Observable<any>;
    private flashSubscription: Subscription;

    public ngOnChanges(changes: SimpleChanges): void {
        if ('flash' in changes) {
            if (this.flashSubscription) {
                this.flashSubscription.unsubscribe();
            }
            this.flashSubscription = (<Observable<any>> changes['flash'].currentValue).subscribe(() => {
                // trigger the flash animation here
            });
        }
    }

    public ngOnDestroy(): void {
        if (this.flashSubscription) {
            this.flashSubscription.unsubscribe();
        }
    }

I'd also call unsubscribe in ngOnDestroy - so that unsubscription will occur for flash observables that don't complete or error.

Note that is is safe to call a subscription's unsubscribe method multiple times.


问:
Why can I extend a class at runtime by initializing another class by ClassName.__init__(self)
I was wondering why can I extend a class at runtime using the following code:

```<code>class ClassA:
    def __init__(self):
        self.value = "1"
        ClassB.__init__(self)

class ClassB:
    def __init__(self):
        self.punk = "Punk"

test = ClassA()
print(dir(test))
</code>```

This gives me access to test.value and test.punk. But I don't understand why. Thanks.

答:
The reason this works is because you are modifying ClassA's self parmeter using ClassB.__init__().

When you passed self to ClassB inside of ClassA.__init__(), ClassB.__init__() accepted the object passed in an assigned the attribute punk to it. Normally self would have been an instance of ClassB because Python implicitly passes the value of self. But because you explicitly passed in a different argument - an instance of ClassA - Python used that value instead.

This can be seen with a simple example:

```<code>>>> class A:
    def __init__(self):
        B.__init__(self)

>>> class B:
    def __init__(self):
        print('The type of self is: ', self)

>>> a = A()
The type of self is:  <__main__.A object at 0x03E9A050>
>>>
</code>```

As @chepner mentioned, its the same as if you used a normal method and called that inside of ClassA's constructor:

```<code>>>> class A:
    def __init__(self):
        B.method(self)

>>> class B:
    def method(self):
        print('The type of self is: ', self)

>>> a = A()
The type of self is:  <__main__.A object at 0x03E9A670>
>>>
</code>```

Body:
I was wondering why can I extend a class at runtime using the following code:

class ClassA:
    def __init__(self):
        self.value = "1"
        ClassB.__init__(self)

class ClassB:
    def __init__(self):
        self.punk = "Punk"

test = ClassA()
print(dir(test))

This gives me access to test.value and test.punk. But I don't understand why. Thanks.

Body:
The reason this works is because you are modifying ClassA's self parmeter using ClassB.__init__().

When you passed self to ClassB inside of ClassA.__init__(), ClassB.__init__() accepted the object passed in an assigned the attribute punk to it. Normally self would have been an instance of ClassB because Python implicitly passes the value of self. But because you explicitly passed in a different argument - an instance of ClassA - Python used that value instead.

This can be seen with a simple example:

>>> class A:
    def __init__(self):
        B.__init__(self)

>>> class B:
    def __init__(self):
        print('The type of self is: ', self)

>>> a = A()
The type of self is:  <__main__.A object at 0x03E9A050>
>>>

As @chepner mentioned, its the same as if you used a normal method and called that inside of ClassA's constructor:

>>> class A:
    def __init__(self):
        B.method(self)

>>> class B:
    def method(self):
        print('The type of self is: ', self)

>>> a = A()
The type of self is:  <__main__.A object at 0x03E9A670>
>>>


问:
angular2- Observable getting data from list out of order
```<code>    for (let i = 0; i < this.data.VirtualHosts.length; i++) {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
            }
</code>```

Here, I loop through a list of ID's of VirtualHosts and do a get call (findVH) on every single one of them. However, the get call seems to be calling each index out of order. How would I make it so that the get call returns a list of data in the order that it was given in the this.data.VirtualHosts list?

答:
I think you will need to do 2 things.  One convert your this.data.VirtualHosts into an observable using the from operator as described here:

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/from.md

Then use concatMap which will force the api results to return in the order that you are firing off the requests.  This is explained here:

https://www.learnrxjs.io/operators/transformation/concatmap.html

Body:
    for (let i = 0; i < this.data.VirtualHosts.length; i++) {
                // get the vh
                this.apiService.findVH(this.data.VirtualHosts[i])
                    // then add each vhost to data by concat and then convert to json
                    .subscribe((data) => {
                        this.data = data.docs[0]
                        this.jsonData = this.jsonData.concat(this.data)
                        //console.log("AFTER: " + this.jsonData[i]._id)
                        //console.log("Response for getVH: " + JSON.stringify(this.jsonData))

                    })
            }

Here, I loop through a list of ID's of VirtualHosts and do a get call (findVH) on every single one of them. However, the get call seems to be calling each index out of order. How would I make it so that the get call returns a list of data in the order that it was given in the this.data.VirtualHosts list?


问:
Run multiple tasks with the same command?
I want to chain up some commands / tasks I defined in tasks.json.

I have many different sub-projects (C# csproj files) that should be built, then tested (shell commands) in a big single task.

I have this tasks.json working, but I can only invoke the different commands one by one.

答:
Wow, there is a dependsOn property since 1.10.

See More work on Terminal Runner in release notes.

```<code>{
    "version": "2.0.0",
    "tasks":
    [
        {
            "taskName": "Build",
            "isBuildCommand": true,
            "command": "/Applications/Unity/Unity.app/Contents/MonoBleedingEdge/bin/xbuild",
            "args":
            [
                "Project.sln",
                "/property:GenerateFullPaths=true"
            ],
            "showOutput": "silent",
            "problemMatcher": "$msCompile"
        },
        {
            "taskName": "Build EPPZ.Extensions.Test",
            "command": "/Applications/Unity/Unity.app/Contents/MonoBleedingEdge/bin/xbuild",
            "args":
            [
                "Assets/Plugins/eppz!/Extensions/Test.csproj",
                "/property:Configuration=Local",
                "/property:GenerateFullPaths=true"
            ],
            "showOutput": "always",
            "problemMatcher": "$msCompile"
        },
        {
            "taskName": "Test EPPZ.Extensions.Test",
            "isShellCommand": true,
            "command": "mono",
            "dependsOn": [ "Build EPPZ.Extensions.Test" ],
            "args":
            [
                "/Users/eppz/Projects/Unity/Packages/NUnit/NUnit.ConsoleRunner.3.6.1/tools/nunit3-console.exe",
                "bin/EPPZ.Extensions.Test.dll",
                "--labels=All",
                "--result=EPPZ.Extensions.Test.Result.xml"
            ],
            "showOutput": "always"
        },
        {
            "taskName": "Test",
            "isShellCommand": true,
            "isTestCommand": true,
            "command": "echo",
            "args": ["All done."],
            "dependsOn": [ "Test (EPPZ.Extensions.Test)" ],
            "showOutput": "always"
        }
    ]
}
</code>```

Body:
Wow, there is a dependsOn property since 1.10.

See More work on Terminal Runner in release notes.

{
    "version": "2.0.0",
    "tasks":
    [
        {
            "taskName": "Build",
            "isBuildCommand": true,
            "command": "/Applications/Unity/Unity.app/Contents/MonoBleedingEdge/bin/xbuild",
            "args":
            [
                "Project.sln",
                "/property:GenerateFullPaths=true"
            ],
            "showOutput": "silent",
            "problemMatcher": "$msCompile"
        },
        {
            "taskName": "Build EPPZ.Extensions.Test",
            "command": "/Applications/Unity/Unity.app/Contents/MonoBleedingEdge/bin/xbuild",
            "args":
            [
                "Assets/Plugins/eppz!/Extensions/Test.csproj",
                "/property:Configuration=Local",
                "/property:GenerateFullPaths=true"
            ],
            "showOutput": "always",
            "problemMatcher": "$msCompile"
        },
        {
            "taskName": "Test EPPZ.Extensions.Test",
            "isShellCommand": true,
            "command": "mono",
            "dependsOn": [ "Build EPPZ.Extensions.Test" ],
            "args":
            [
                "/Users/eppz/Projects/Unity/Packages/NUnit/NUnit.ConsoleRunner.3.6.1/tools/nunit3-console.exe",
                "bin/EPPZ.Extensions.Test.dll",
                "--labels=All",
                "--result=EPPZ.Extensions.Test.Result.xml"
            ],
            "showOutput": "always"
        },
        {
            "taskName": "Test",
            "isShellCommand": true,
            "isTestCommand": true,
            "command": "echo",
            "args": ["All done."],
            "dependsOn": [ "Test (EPPZ.Extensions.Test)" ],
            "showOutput": "always"
        }
    ]
}


问:
Enter key is "clicking" the wrong button. asp.net
I have two asp buttons and a asp textbox. One button is to logout and the other to add the content of the textbox (username) to a database table.

All works great except when I type in a username and hit the enter key, it logs me off i.e. clicks logout button.

```<code><asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
<asp:TextBox ID="adduser" runat="server" placeholder="Enter username here"></asp:TextBox>
<asp:Button ID="adduserbtn" runat="server" Text="Add" />
</code>```

I got it to work by wrapping the textbox and adduserbtn button in a panel and setting the adduserbtn button as the default button.

```<code><asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Panel DefaultButton="adduserbtn" runat="server" ID="addUserPanel">
    <asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
    <asp:TextBox ID="adduser" runat="server" placeholder="Enter username here" ></asp:TextBox>
    <asp:Button ID="adduserbtn" runat="server" Text="Add" />
</asp:Panel>
</code>```

But this feels more like a "hack" than a fix.  Does anybody know of a better / cleaner way to do this? Thanks in advance.

答:
What ever your are done is correct. This not a hack this the feature ASP.Net.
Just change the code as folllowing</p>

```<code><asp:Panel DefaultButton="adduserbtn" runat="server" ID="addUserPanel">
    <asp:Button Style="float: right;" ID="logout" runat="server" Text="LogOut" />
    <asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
    <asp:TextBox ID="adduser" runat="server" placeholder="Enter username here"></asp:TextBox>
    <asp:Button ID="adduserbtn" runat="server" Text="Add" />
</asp:Panel>
</code>```

Body:
I have two asp buttons and a asp textbox. One button is to logout and the other to add the content of the textbox (username) to a database table.

All works great except when I type in a username and hit the enter key, it logs me off i.e. clicks logout button.

<asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
<asp:TextBox ID="adduser" runat="server" placeholder="Enter username here"></asp:TextBox>
<asp:Button ID="adduserbtn" runat="server" Text="Add" />

I got it to work by wrapping the textbox and adduserbtn button in a panel and setting the adduserbtn button as the default button.

<asp:Button style="float: right;" ID="logout" runat="server" Text="LogOut" />
<asp:Panel DefaultButton="adduserbtn" runat="server" ID="addUserPanel">
    <asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
    <asp:TextBox ID="adduser" runat="server" placeholder="Enter username here" ></asp:TextBox>
    <asp:Button ID="adduserbtn" runat="server" Text="Add" />
</asp:Panel>

But this feels more like a "hack" than a fix.  Does anybody know of a better / cleaner way to do this? Thanks in advance.

Body:
What ever your are done is correct. This not a hack this the feature ASP.Net.
Just change the code as folllowing

<asp:Panel DefaultButton="adduserbtn" runat="server" ID="addUserPanel">
    <asp:Button Style="float: right;" ID="logout" runat="server" Text="LogOut" />
    <asp:Label AssociatedControlID="adduser" Text="Add new admin user." runat="server" />
    <asp:TextBox ID="adduser" runat="server" placeholder="Enter username here"></asp:TextBox>
    <asp:Button ID="adduserbtn" runat="server" Text="Add" />
</asp:Panel>


问:
Xpage - Copy document to another document
I have two documents; document1 allows read/write, but document2 is readonly.

```<code>var document1:NotesView = database.getView("viewDoc1");
var document2:NotesView = database.getView("viewDoc2");
//var copiedDoc:NotesDocument=document2.CopyToDatabase(document1);
docEv:NotesDocument = document1.getDocumentByKey("userName");
if(docEv!=""){...}else{...};
</code>```

beforePageLoad

Before page is rendered, I want to be able copy all data in the readonly document and save it into the read/write document and also check if documents already exist in the read/write, in which case don't copy.
Your help will be appreciated.

答:
This line of your code makes no sense:

```<code>var copiedDoc:NotesDocument=document2.CopyToDatabase(document1)
</code>```

First of all, you said that you want to copy document2 into document1, but you appear to be trying to copy it into a new, third NotesDocument called copiedDoc.

But more importantly, you're passing document1 as the argument into the CopyToDatabase method, but that method takes a NotesDatbase argument, not a NotesDocument argument!

You may want to look at the CopyAllItems method instead.

Body:
I have two documents; document1 allows read/write, but document2 is readonly.

var document1:NotesView = database.getView("viewDoc1");
var document2:NotesView = database.getView("viewDoc2");
//var copiedDoc:NotesDocument=document2.CopyToDatabase(document1);
docEv:NotesDocument = document1.getDocumentByKey("userName");
if(docEv!=""){...}else{...};

beforePageLoad

Before page is rendered, I want to be able copy all data in the readonly document and save it into the read/write document and also check if documents already exist in the read/write, in which case don't copy.
Your help will be appreciated.

Body:
This line of your code makes no sense:

var copiedDoc:NotesDocument=document2.CopyToDatabase(document1)

First of all, you said that you want to copy document2 into document1, but you appear to be trying to copy it into a new, third NotesDocument called copiedDoc.

But more importantly, you're passing document1 as the argument into the CopyToDatabase method, but that method takes a NotesDatbase argument, not a NotesDocument argument!

You may want to look at the CopyAllItems method instead.


问:
How can I customize a nested serialized list of django model objects to be key/value pairs instead?
lets say I have models like so:

```<code>class Device(models.Model):
    name = models.CharField(max_length=100,null=True)
    model = models.CharField(max_length=100,null=True)
    lab = models.ForeignKey(Lab,null=True, related_name='devices')

class Lab(models.Model):
    name = models.CharField(max_length=100)
</code>```

Where a lab can have multiple devices.
When I create serializers I am able to get something back like this:

```<code>{'name':'My Lab','devices':[{'name':'Device 1','model':'iPhone'},{'name':'Device 2','model':'iPad'}]}
</code>```

However, what I would like to get back is key/value pairs instead of a list of devices, like so:

```<code>{'name':'My Lab','devices':{'Device 1':{'model':'iPhone'},'Device 2':{'model':'iPad'}}}
</code>```

I'm imagining I have to use the SerializerMethodField to make this work, but I am having trouble figuring it out.

答:
ok, sometimes just writing the question out helps my brain figure out the answer.

this is what I came up with:

```<code>class LabSerializer(serializers.ModelSerializer):
    devices = serializers.SerializerMethodField()

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Lab
        fields = ('name','devices')

    def get_devices(self, obj):
        devices = {}
        for d in Device.objects.filter(lab = obj):
            serializer = DeviceSerializer(d)
            devices[d.name] = serializer.data
        return devices
</code>```

Body:
lets say I have models like so:

class Device(models.Model):
    name = models.CharField(max_length=100,null=True)
    model = models.CharField(max_length=100,null=True)
    lab = models.ForeignKey(Lab,null=True, related_name='devices')

class Lab(models.Model):
    name = models.CharField(max_length=100)

Where a lab can have multiple devices.
When I create serializers I am able to get something back like this:

{'name':'My Lab','devices':[{'name':'Device 1','model':'iPhone'},{'name':'Device 2','model':'iPad'}]}

However, what I would like to get back is key/value pairs instead of a list of devices, like so:

{'name':'My Lab','devices':{'Device 1':{'model':'iPhone'},'Device 2':{'model':'iPad'}}}

I'm imagining I have to use the SerializerMethodField to make this work, but I am having trouble figuring it out.

Body:
ok, sometimes just writing the question out helps my brain figure out the answer.

this is what I came up with:

class LabSerializer(serializers.ModelSerializer):
    devices = serializers.SerializerMethodField()

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Lab
        fields = ('name','devices')

    def get_devices(self, obj):
        devices = {}
        for d in Device.objects.filter(lab = obj):
            serializer = DeviceSerializer(d)
            devices[d.name] = serializer.data
        return devices


问:
.c files instead of .m in Objective-C projects?
I noticed it some Objective-C projects some of the files that use a significant amount of C functions, store the code in .c files instead of .m. I know .m is for Objective-C and .c is for C but is there any benefit to using .c over .m when you can? Is there a performance increase or complication benefit? Would GCC or clang compile equivalent code differently in each?

答: Besides everything else, .c is good for cross platform development. The overhead of porting it from one platform to another is very low or almost negligible.  . And mostly the backend or the model of an application is developed using "C" where performance is required and you need a direct interaction with the machine. Such as interaction with hardware and stuff. </p>

ContentLicense: CC BY-SA 2.5


问:
Express.js & Mongoose Query Issue
I am trying to query my MongoDB for a single document using _id. I am using Mongoose (version: 4.11.1). When I try to run the query, I pass in the _id as a URL param on the route localhost:3000/poi/one/595ef9c8c4891179f8b4bbfb.

When I hit enter, the browser will just continue loading and never complete. I am able to see the "getting one POI" in the console. But never see anything else.

I am using mLab to host my DB. And there is only 1 document inside.

mLab Document:

Here is my code for the query:

```<code>let express = require('express');
let router = express.Router();

let {Poi} = require('../models/db-model');

router.get('/one/:id', (req, res, next) => {
    console.log('getting one POI');
    Poi.findOne({_id: req.params.id}).exec(function (err, poi) {
        if (err) {
            res.send('error occurred')
        }
        else {
            console.log(poi);
            res.send(poi)
        }
    });
});
</code>```

My database model:

```<code>const mongoose = require('mongoose');

// point of interest schema
let poiSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 1,
        trim: true,
    },
    url: {
        type: String,
        required: true
    },
    address: {
        type: String,
        required: true
    },
    cost: {
        type: Number,
        required: false
    }
});

// instantiate models
let Poi = mongoose.model('Poi', poiSchema);

// export models
module.exports = {Poi};
</code>```

I have been stuck with this problem for hours now and can just not figure out what the issue is.

EDIT:

Mongoose Configuration:

```<code>const mongoose = require('mongoose');
const config = require('../app-config.json');

mongoose.Promise = global.Promise;

// connect to mLab Collection
mongoose.connect(config.dbUri);

module.exports = {mongoose};
</code>```

答:
In their official documentation for findOne, Mongoose recommends using Model.findById() method when querying by the _id field. You may read the documentation specifically for findById here: http://mongoosejs.com/docs/api.html#model_Model.findById

Essentially it would look something like:

```<code>Poi.findById(req.params.id).exec(function (err, poi) {
  // ...
</code>```

Title: Express.js & Mongoose Query Issue

Body:
I am trying to query my MongoDB for a single document using _id. I am using Mongoose (version: 4.11.1). When I try to run the query, I pass in the _id as a URL param on the route localhost:3000/poi/one/595ef9c8c4891179f8b4bbfb.

When I hit enter, the browser will just continue loading and never complete. I am able to see the "getting one POI" in the console. But never see anything else.

I am using mLab to host my DB. And there is only 1 document inside.

mLab Document:

Here is my code for the query:

let express = require('express');
let router = express.Router();

let {Poi} = require('../models/db-model');

router.get('/one/:id', (req, res, next) => {
    console.log('getting one POI');
    Poi.findOne({_id: req.params.id}).exec(function (err, poi) {
        if (err) {
            res.send('error occurred')
        }
        else {
            console.log(poi);
            res.send(poi)
        }
    });
});

My database model:

const mongoose = require('mongoose');

// point of interest schema
let poiSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 1,
        trim: true,
    },
    url: {
        type: String,
        required: true
    },
    address: {
        type: String,
        required: true
    },
    cost: {
        type: Number,
        required: false
    }
});

// instantiate models
let Poi = mongoose.model('Poi', poiSchema);

// export models
module.exports = {Poi};

I have been stuck with this problem for hours now and can just not figure out what the issue is.

EDIT:

Mongoose Configuration:

const mongoose = require('mongoose');
const config = require('../app-config.json');

mongoose.Promise = global.Promise;

// connect to mLab Collection
mongoose.connect(config.dbUri);

module.exports = {mongoose};

Body:
In their official documentation for findOne, Mongoose recommends using Model.findById() method when querying by the _id field. You may read the documentation specifically for findById here: http://mongoosejs.com/docs/api.html#model_Model.findById

Essentially it would look something like:

Poi.findById(req.params.id).exec(function (err, poi) {
  // ...


问:
Bootstrap Nav Tab Click Event Works EXCEPT on Tab Label Click
Hello I've been poking at this for about 1/2 hour - it seems trivial perhaps but I want to deliver well for the client on this one.

We've got a form set up with sections inside of a sequence of tabs. For now I'm just trying to make the 'Save and Continue' button change to 'Submit' when the last tab is made active - either by the user hitting the 'Save and Continue' button or by clicking the tabs at top - later we'll be adding submission validation, etc. But I figure that having the button text-change working will get me familiar enough with what was built (by sommeone else) to get the more complex stuff working later.

What's working:

The button changes name perfectly when the user arrives at the final tab by clicking the button.

The button changes name perfectly when the user clicks on the last tab... EXCEPT when they click on the actual text inside the tab. The click event is still generated, but the console call for the e.target.id throws an empty string.

Code for the Nav-tabs:

Personal InformationPersonal Info

Professional InformationProf. Info

Employment ExpectationsExpectations

Profile SettingsSettings

```
</div>
</div>
</p>

<p>Code for the Button:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="submit" name="profile-continue" class="btn btn-danger" id="continueBtn" value="Save & Continue"></code>```

And the Jquery:

 // Check which tab is active and set the Continue Button text
 function initButtons() {

  console.log($('#settingsTab'));

 if ($('#settingsTab').hasClass('active')) {
  $('#continueBtn').prop( 'value' , 'Submit');
 }
 else {
  $('#continueBtn').prop( 'value' , 'Save and Continue');
 }
 };

 initButtons();

 /* The 'Continue' button behavior */
 $('#continueBtn').click(function(){
  // Activate the next tab
  $('.nav-tabs > .active').next('li').find('a').trigger('click');
  // Change the submit Button text accordingly
  initButtons();
  // Possible to-do: wrap in an 'if' statement that checks if there's any missing 'required' fields.
  // Possible to-do: determine 'if' the tab selected is the last in the sequence.
  // Possible to-do: grey/non-grey tabs (make accessible in sequnce).
  }
  );

 $( 'a[data-toggle="tab"]' ).click(function(e){
  console.log(e);
  console.log('Target: ' , e.target.id);
  // Check what tab was picked and submit Button text accordingly

   if ( e.target.id === 'settingsLink' ) {
    $('#continueBtn').prop( 'value' , 'Submit');
   }
   else {
    $('#continueBtn').prop( 'value' , 'Save and Continue');
   }

  }
  );```

答:
Ok, so I figured this out just as I was typing up the question but figured I'd still post here to help somebody else who might need it. The tab-text is inside of a 'strong' HTML element, which is a child of the tab that I'm trying to target.

So I got it working by changing the line:

if (e.target.id === 'settingsLink' ) {...```
</div>
</div>
</p>

<p>to:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>if (e.target.id === 'settingsLink' || e.target.parentElement.id === 'settingsLink' ) {...</code>```

Hope it saves somebody some time.

Body:
Hello I've been poking at this for about 1/2 hour - it seems trivial perhaps but I want to deliver well for the client on this one.

We've got a form set up with sections inside of a sequence of tabs. For now I'm just trying to make the 'Save and Continue' button change to 'Submit' when the last tab is made active - either by the user hitting the 'Save and Continue' button or by clicking the tabs at top - later we'll be adding submission validation, etc. But I figure that having the button text-change working will get me familiar enough with what was built (by sommeone else) to get the more complex stuff working later.

What's working:

The button changes name perfectly when the user arrives at the final tab by clicking the button.

The button changes name perfectly when the user clicks on the last tab... EXCEPT when they click on the actual text inside the tab. The click event is still generated, but the console call for the e.target.id throws an empty string.

Code for the Nav-tabs:

Personal InformationPersonal Info

Professional InformationProf. Info

Employment ExpectationsExpectations

Profile SettingsSettings

Code for the Button:

<input type="submit" name="profile-continue" class="btn btn-danger" id="continueBtn" value="Save & Continue">

And the Jquery:

 // Check which tab is active and set the Continue Button text
 function initButtons() {

  console.log($('#settingsTab'));

 if ($('#settingsTab').hasClass('active')) {
  $('#continueBtn').prop( 'value' , 'Submit');
 }
 else {
  $('#continueBtn').prop( 'value' , 'Save and Continue');
 }
 };

 initButtons();

 /* The 'Continue' button behavior */
 $('#continueBtn').click(function(){
  // Activate the next tab
  $('.nav-tabs > .active').next('li').find('a').trigger('click');
  // Change the submit Button text accordingly
  initButtons();
  // Possible to-do: wrap in an 'if' statement that checks if there's any missing 'required' fields.
  // Possible to-do: determine 'if' the tab selected is the last in the sequence.
  // Possible to-do: grey/non-grey tabs (make accessible in sequnce).
  }
  );

 $( 'a[data-toggle="tab"]' ).click(function(e){
  console.log(e);
  console.log('Target: ' , e.target.id);
  // Check what tab was picked and submit Button text accordingly

   if ( e.target.id === 'settingsLink' ) {
    $('#continueBtn').prop( 'value' , 'Submit');
   }
   else {
    $('#continueBtn').prop( 'value' , 'Save and Continue');
   }

  }
  );

Body:
Ok, so I figured this out just as I was typing up the question but figured I'd still post here to help somebody else who might need it. The tab-text is inside of a 'strong' HTML element, which is a child of the tab that I'm trying to target.

So I got it working by changing the line:

if (e.target.id === 'settingsLink' ) {...

to:

if (e.target.id === 'settingsLink' || e.target.parentElement.id === 'settingsLink' ) {...

Hope it saves somebody some time.


问:
Build a Queue with a limitation of Array of size 5 - but queue can grow
Question: Build a queue class with the enqueue and dequeue methods. However, the language you are using has a bug which does not allow arrays to store more than 5 elements, how would you build that?

I wrote the below code and I was rejected, curious to understand what is the issue and why I was rejected, fyi - this is in technical phone screen.

```<code>static LinkedList<Queue<Integer>> list = new LinkedList<Queue<Integer>>();

public static void enQueue(Integer element){

    //iterating the linkedlist....
    while(true){ //todo
        Queue<Integer> curr;
        if(list.size() > 0)
            curr = list.getLast();
        else{
            curr = new LinkedList<Integer>();
            list.add(curr);
        }
        if(curr.size() < 5){
            curr.add(element);
            System.out.println("enqueued:" + element);
            break;
        } else{
            Queue<Integer> newQueue = new LinkedList<Integer>();
            newQueue.add(element);
            list.add(newQueue); //adding the new Queue of size(5) to the list
            break;
        }
    }
}

public static Integer deQueue(){
    LinkedList<Queue<Integer>> node = list;
    if(!isEmpty()){
        Integer retValue = 0;
        while(list.size() > 0){
            Queue<Integer> q = node.getFirst();
            if(!q.isEmpty()){
                retValue =  q.poll();
                break;
            }else{
                node.removeFirst();
            }
        }
        return retValue;
    }else{
        System.out.println("No such element found");
        return -1; //throw new NoSuchElementException("no element found");
    }
}

public static boolean isEmpty(){
    return list.size() == 0;
}
</code>```

答:
You were rejected, because:

you assumed a pre-existing Queue class, which is what you were supposed to implement.

you used a LinkedList, which already implements a queue-like interface, instead of actually implementing a queue.

You used the LinkedList badly -- there is no reason for any kind of loop at all.  You could have just had your enQueue and deQueue call LinkedList.add()  LinkedList.pollFirst()

The interviewer really wanted you to actually implement a queue.  The array limitation is to force you to use a linked implementation, and the interviewer wanted to see you maintain the links properly.

Body:
Question: Build a queue class with the enqueue and dequeue methods. However, the language you are using has a bug which does not allow arrays to store more than 5 elements, how would you build that?

I wrote the below code and I was rejected, curious to understand what is the issue and why I was rejected, fyi - this is in technical phone screen.

static LinkedList<Queue<Integer>> list = new LinkedList<Queue<Integer>>();

public static void enQueue(Integer element){

    //iterating the linkedlist....
    while(true){ //todo
        Queue<Integer> curr;
        if(list.size() > 0)
            curr = list.getLast();
        else{
            curr = new LinkedList<Integer>();
            list.add(curr);
        }
        if(curr.size() < 5){
            curr.add(element);
            System.out.println("enqueued:" + element);
            break;
        } else{
            Queue<Integer> newQueue = new LinkedList<Integer>();
            newQueue.add(element);
            list.add(newQueue); //adding the new Queue of size(5) to the list
            break;
        }
    }
}

public static Integer deQueue(){
    LinkedList<Queue<Integer>> node = list;
    if(!isEmpty()){
        Integer retValue = 0;
        while(list.size() > 0){
            Queue<Integer> q = node.getFirst();
            if(!q.isEmpty()){
                retValue =  q.poll();
                break;
            }else{
                node.removeFirst();
            }
        }
        return retValue;
    }else{
        System.out.println("No such element found");
        return -1; //throw new NoSuchElementException("no element found");
    }
}

public static boolean isEmpty(){
    return list.size() == 0;
}


问:
MS Excel - Unable to import data as text/csv file
I am trying to import data from yahoo finance. However, when I go to

Data >> From text/CSV and enter the link, the following screen pops up:

The link I enter is just a copied link from yahoo finance (i.e. yahoo finacne >> google >> historical price >> download data >> copy link address).

Thank you very much!

答:
The video you linked to in your comment has been shot with Excel 2007, so it is about software that is 10 years behind what you are using. It was published three years ago. Things have changed since then.

Yahoo Finance API is no longer a free service. They shut down the service earlier this year and you can no longer pull data from it with Excel.

Apart from that, if you run the most recent versions of Excel 2016, the icon to import text or CSV will now start the Get & Transform functionality, also known as Power Query, not the old text import wizard. The dialogs that you see are from Get & Transform, asking you to authenticate for the URL you entered. If you have a user name and password, enter it and the connection will be made.

If you want to use the old text import wizard, you need to go File > Options > Data and tick the box for "From Text (Legacy)".

Then you can use the drop-down option for Legacy Wizards in the Get Data dialog of Get & Transform.

But I doubt that this will work, since Yahoo Finance has shut down the service.


问:
Get each file size inside a Folder using SQL
We are keeping images in Folder which can have images & sub folder & these sub folders can also have images & sub folders for example

```<code>c:\myImageFolder\image1.png    //'myImageFolder' have image
c:\myImageFolder\Folder1\imagex.png // 'myImageFolder' have another folder inside which is 'Folder1'.
c:\myImageFolder\Folder1\ChildFolder1\imagen.png // 'myImageFolder' have 'Folder1' which have 'ChildFolder1' which have imagen.png
</code>```

We need to know that how many images are in there over 1 MB, over 750KB and 500KB?

Some facts:

We need to do it through SQL

We are using SQL Server 2008

myImageFolder contains more than thousands sub folders

myImageFolder size is nearly 5 GB

Thanks in advance for your valuable time & help.
Note: I found the solution, you can find it here

答:
Version 2.0 of perfect solution!!

```<code>-- =============================================
-- Author:      Carlos Dominguez (krlosnando@gmail.com)
-- Create date: July 07th 2017
-- Description: Scan folders and files Size
-- Example: EXEC [dbo].[spScanFolder] 'C:\Users\Public'
-- =============================================
CREATE PROCEDURE [dbo].[spScanFolder]
(
    @FolderToScan VARCHAR(1000)
)
AS
BEGIN
    ---------------------------------------------------------------------------------------------
    -- Variable declaration
    ---------------------------------------------------------------------------------------------
    DECLARE @CurrentDir VARCHAR(400)
    DECLARE @Line VARCHAR(400)
    DECLARE @Command VARCHAR(400)
    DECLARE @Counter int

    DECLARE @1MB DECIMAL
    SET @1MB = 1024 * 1024

    DECLARE @1KB DECIMAL
    SET @1KB = 1024

    ---------------------------------------------------------------------------------------------
    -- DROP temp tables
    ---------------------------------------------------------------------------------------------
    IF OBJECT_ID(N'tempdb..#tableTempDirs') IS NOT NULL BEGIN  DROP TABLE #tableTempDirs END
    IF OBJECT_ID(N'tempdb..#tableTempOutput') IS NOT NULL BEGIN  DROP TABLE #tableTempOutput END
    IF OBJECT_ID(N'tempdb..#tableTempResult') IS NOT NULL BEGIN  DROP TABLE #tableTempResult END
    IF OBJECT_ID(N'tempdb..#tableTempFilePaths') IS NOT NULL BEGIN  DROP TABLE #tableTempFilePaths END
    IF OBJECT_ID(N'tempdb..#tableTempFileInfo') IS NOT NULL BEGIN  DROP TABLE #tableTempFileInfo END

    ---------------------------------------------------------------------------------------------
    -- Temp tables creation
    ---------------------------------------------------------------------------------------------
    CREATE TABLE #tableTempDirs (DIRID int identity(1,1), directory varchar(400))
    CREATE TABLE #tableTempOutput (line varchar(400))
    CREATE TABLE #tableTempResult (Directory varchar(400), FilePath VARCHAR(400), SizeInMB DECIMAL(13,2), SizeInKB DECIMAL(13,2))
    CREATE TABLE #tableTempFilePaths (Files VARCHAR(500))
    CREATE TABLE #tableTempFileInfo (FilePath VARCHAR(500), FileSize VARCHAR(100))

    ---------------------------------------------------------------------------------------------
    -- Call xp_cmdshell
    ---------------------------------------------------------------------------------------------
    SET @Command = 'dir "'+ @FolderToScan +'" /S/O/B/A:D'
    INSERT INTO #tableTempDirs EXEC xp_cmdshell @Command
    INSERT INTO #tableTempDirs SELECT @FolderToScan
    DELETE FROM #tableTempDirs WHERE Directory is null

    ---------------------------------------------------------------------------------------------
    -- Remove text to extract file information from command result "05/27/2017  12:26 PM 5,208 rulog.txt"
    ---------------------------------------------------------------------------------------------
    SET @Counter = (select count(*) from #tableTempDirs)
    WHILE @Counter <> 0
    BEGIN
        DECLARE @filesize INT
        SET @CurrentDir = (SELECT directory FROM #tableTempDirs WHERE DIRID = @Counter)
        SET @Command = 'dir "' + @CurrentDir +'"'

        -- Clear the table
        TRUNCATE TABLE #tableTempFilePaths

        -- Get files from current directory
        INSERT INTO #tableTempFilePaths
        EXEC MASTER..XP_CMDSHELL @Command

        --delete all directories
        DELETE #tableTempFilePaths WHERE Files LIKE '%<dir>%'

        --delete all informational messages
        DELETE #tableTempFilePaths WHERE Files LIKE ' %'

        --delete the null values
        DELETE #tableTempFilePaths WHERE Files IS NULL

        --delete files without date "05/27/2017  12:26 PM 5,208 rulog.txt"
        --Fix error: Invalid length parameter passed to the right function.
        DELETE #tableTempFilePaths WHERE LEN(files) < 20

        --get rid of dateinfo
        UPDATE #tableTempFilePaths SET files = RIGHT(files,(LEN(files)-20))

        --get rid of leading spaces
        UPDATE #tableTempFilePaths SET files =LTRIM(files)

        --split data into size and filename and clear the table
        TRUNCATE TABLE #tableTempFileInfo;

        -- Store the FileName & Size
        INSERT INTO #tableTempFileInfo
        SELECT
            RIGHT(files,LEN(files) -PATINDEX('% %',files)) AS FilePath,
            LEFT(files,PATINDEX('% %',files)) AS FileSize
        FROM
            #tableTempFilePaths

        --Remove the commas
        UPDATE #tableTempFileInfo
        SET FileSize = REPLACE(FileSize, ',','')

        --------------------------------------------------------------
        -- Store the results in the output table
        -- Fix Error: conveting varchar to decimal
        --------------------------------------------------------------
        INSERT INTO #tableTempResult--(FilePath, SizeInMB, SizeInKB)
        SELECT
            @CurrentDir,
            FilePath,
            CASE FileSize
                WHEN 'File ' THEN 0
                ELSE CAST(CAST(FileSize AS DECIMAL(13,2))/ @1MB AS DECIMAL(13,2))
            END,
            CASE FileSize
                WHEN 'File ' THEN 0
                ELSE CAST(CAST(FileSize AS DECIMAL(13,2))/ @1KB AS DECIMAL(13,2))
            END
        FROM
            #tableTempFileInfo

        Set @Counter = @Counter -1
    END

    -- Remove null directories
    DELETE FROM #tableTempResult WHERE Directory is null

    ----------------------------------------------
    -- Show result
    ----------------------------------------------
    SELECT * FROM  #tableTempResult

    ----------------------------------------------
    -- DROP temp tables
    ----------------------------------------------
    IF OBJECT_ID(N'tempdb..#tableTempDirs') IS NOT NULL BEGIN  DROP TABLE #tableTempDirs END
    IF OBJECT_ID(N'tempdb..#tableTempOutput') IS NOT NULL BEGIN  DROP TABLE #tableTempOutput END
    IF OBJECT_ID(N'tempdb..#tableTempResult') IS NOT NULL BEGIN  DROP TABLE #tableTempResult END
    IF OBJECT_ID(N'tempdb..#tableTempFilePaths') IS NOT NULL BEGIN  DROP TABLE #tableTempFilePaths END
    IF OBJECT_ID(N'tempdb..#tableTempFileInfo') IS NOT NULL BEGIN  DROP TABLE #tableTempFileInfo END
END
</code>```

Body:
We are keeping images in Folder which can have images & sub folder & these sub folders can also have images & sub folders for example

c:\myImageFolder\image1.png    //'myImageFolder' have image
c:\myImageFolder\Folder1\imagex.png // 'myImageFolder' have another folder inside which is 'Folder1'.
c:\myImageFolder\Folder1\ChildFolder1\imagen.png // 'myImageFolder' have 'Folder1' which have 'ChildFolder1' which have imagen.png

We need to know that how many images are in there over 1 MB, over 750KB and 500KB?

Some facts:

We need to do it through SQL

We are using SQL Server 2008

myImageFolder contains more than thousands sub folders

myImageFolder size is nearly 5 GB

Thanks in advance for your valuable time & help.
Note: I found the solution, you can find it here

Body:
Version 2.0 of perfect solution!!

-- =============================================
-- Author:      Carlos Dominguez (krlosnando@gmail.com)
-- Create date: July 07th 2017
-- Description: Scan folders and files Size
-- Example: EXEC [dbo].[spScanFolder] 'C:\Users\Public'
-- =============================================
CREATE PROCEDURE [dbo].[spScanFolder]
(
    @FolderToScan VARCHAR(1000)
)
AS
BEGIN
    ---------------------------------------------------------------------------------------------
    -- Variable declaration
    ---------------------------------------------------------------------------------------------
    DECLARE @CurrentDir VARCHAR(400)
    DECLARE @Line VARCHAR(400)
    DECLARE @Command VARCHAR(400)
    DECLARE @Counter int

    DECLARE @1MB DECIMAL
    SET @1MB = 1024 * 1024

    DECLARE @1KB DECIMAL
    SET @1KB = 1024

    ---------------------------------------------------------------------------------------------
    -- DROP temp tables
    ---------------------------------------------------------------------------------------------
    IF OBJECT_ID(N'tempdb..#tableTempDirs') IS NOT NULL BEGIN  DROP TABLE #tableTempDirs END
    IF OBJECT_ID(N'tempdb..#tableTempOutput') IS NOT NULL BEGIN  DROP TABLE #tableTempOutput END
    IF OBJECT_ID(N'tempdb..#tableTempResult') IS NOT NULL BEGIN  DROP TABLE #tableTempResult END
    IF OBJECT_ID(N'tempdb..#tableTempFilePaths') IS NOT NULL BEGIN  DROP TABLE #tableTempFilePaths END
    IF OBJECT_ID(N'tempdb..#tableTempFileInfo') IS NOT NULL BEGIN  DROP TABLE #tableTempFileInfo END

    ---------------------------------------------------------------------------------------------
    -- Temp tables creation
    ---------------------------------------------------------------------------------------------
    CREATE TABLE #tableTempDirs (DIRID int identity(1,1), directory varchar(400))
    CREATE TABLE #tableTempOutput (line varchar(400))
    CREATE TABLE #tableTempResult (Directory varchar(400), FilePath VARCHAR(400), SizeInMB DECIMAL(13,2), SizeInKB DECIMAL(13,2))
    CREATE TABLE #tableTempFilePaths (Files VARCHAR(500))
    CREATE TABLE #tableTempFileInfo (FilePath VARCHAR(500), FileSize VARCHAR(100))

    ---------------------------------------------------------------------------------------------
    -- Call xp_cmdshell
    ---------------------------------------------------------------------------------------------
    SET @Command = 'dir "'+ @FolderToScan +'" /S/O/B/A:D'
    INSERT INTO #tableTempDirs EXEC xp_cmdshell @Command
    INSERT INTO #tableTempDirs SELECT @FolderToScan
    DELETE FROM #tableTempDirs WHERE Directory is null

    ---------------------------------------------------------------------------------------------
    -- Remove text to extract file information from command result "05/27/2017  12:26 PM 5,208 rulog.txt"
    ---------------------------------------------------------------------------------------------
    SET @Counter = (select count(*) from #tableTempDirs)
    WHILE @Counter <> 0
    BEGIN
        DECLARE @filesize INT
        SET @CurrentDir = (SELECT directory FROM #tableTempDirs WHERE DIRID = @Counter)
        SET @Command = 'dir "' + @CurrentDir +'"'

        -- Clear the table
        TRUNCATE TABLE #tableTempFilePaths

        -- Get files from current directory
        INSERT INTO #tableTempFilePaths
        EXEC MASTER..XP_CMDSHELL @Command

        --delete all directories
        DELETE #tableTempFilePaths WHERE Files LIKE '%<dir>%'

        --delete all informational messages
        DELETE #tableTempFilePaths WHERE Files LIKE ' %'

        --delete the null values
        DELETE #tableTempFilePaths WHERE Files IS NULL

        --delete files without date "05/27/2017  12:26 PM 5,208 rulog.txt"
        --Fix error: Invalid length parameter passed to the right function.
        DELETE #tableTempFilePaths WHERE LEN(files) < 20

        --get rid of dateinfo
        UPDATE #tableTempFilePaths SET files = RIGHT(files,(LEN(files)-20))

        --get rid of leading spaces
        UPDATE #tableTempFilePaths SET files =LTRIM(files)

        --split data into size and filename and clear the table
        TRUNCATE TABLE #tableTempFileInfo;

        -- Store the FileName & Size
        INSERT INTO #tableTempFileInfo
        SELECT
            RIGHT(files,LEN(files) -PATINDEX('% %',files)) AS FilePath,
            LEFT(files,PATINDEX('% %',files)) AS FileSize
        FROM
            #tableTempFilePaths

        --Remove the commas
        UPDATE #tableTempFileInfo
        SET FileSize = REPLACE(FileSize, ',','')

        --------------------------------------------------------------
        -- Store the results in the output table
        -- Fix Error: conveting varchar to decimal
        --------------------------------------------------------------
        INSERT INTO #tableTempResult--(FilePath, SizeInMB, SizeInKB)
        SELECT
            @CurrentDir,
            FilePath,
            CASE FileSize
                WHEN 'File ' THEN 0
                ELSE CAST(CAST(FileSize AS DECIMAL(13,2))/ @1MB AS DECIMAL(13,2))
            END,
            CASE FileSize
                WHEN 'File ' THEN 0
                ELSE CAST(CAST(FileSize AS DECIMAL(13,2))/ @1KB AS DECIMAL(13,2))
            END
        FROM
            #tableTempFileInfo

        Set @Counter = @Counter -1
    END

    -- Remove null directories
    DELETE FROM #tableTempResult WHERE Directory is null

    ----------------------------------------------
    -- Show result
    ----------------------------------------------
    SELECT * FROM  #tableTempResult

    ----------------------------------------------
    -- DROP temp tables
    ----------------------------------------------
    IF OBJECT_ID(N'tempdb..#tableTempDirs') IS NOT NULL BEGIN  DROP TABLE #tableTempDirs END
    IF OBJECT_ID(N'tempdb..#tableTempOutput') IS NOT NULL BEGIN  DROP TABLE #tableTempOutput END
    IF OBJECT_ID(N'tempdb..#tableTempResult') IS NOT NULL BEGIN  DROP TABLE #tableTempResult END
    IF OBJECT_ID(N'tempdb..#tableTempFilePaths') IS NOT NULL BEGIN  DROP TABLE #tableTempFilePaths END
    IF OBJECT_ID(N'tempdb..#tableTempFileInfo') IS NOT NULL BEGIN  DROP TABLE #tableTempFileInfo END
END


问:
Using the Django ORM, How can you create a unique hash for all possible combinations
I want to maintain a Django model with a unique id for every combination of choices within the model. I would then like to be able to update the model with a new field and not have the previous unique id's change.
The id's can be a hash or integer or anything.
What's the best way to achieve this?

```<code>class MyModel(models.Model):
    WINDOW_MIN = 5
    WINDOW_MAX = 7
    WINDOW_CHOICES = [(i,i) for i in range(WINDOW_MIN - 1, WINDOW_MAX - 1)]
    window = models.PositiveIntegerField('Window', editable=True, default=WINDOW_MIN, choices=WINDOW_CHOICES)
    is_live = models.BooleanField('Live', editable=True, default=False)
    unique_id = ....
</code>```

Given the above example there will be 3 * 2 == 6 unique id's. If I add another editable boolean field, I don't want to change the previous unique id's but I want the new unique id's to be generated for the new boolean field.

The thought process behind this is the parameters in MyModel define the inputs to a function who's results are stored in another Django model MyResultModel by unique_id and the name of the model. The reasoning behind this is there are multiple variants of MyModel each with it's own set unique combination's that get updated regularly but the result set in MyResultModel is the same across MyModel1 to MyModelN. Ideally I would like the unique_id's to be autogenerated. In other words the key for the result set stored in MyResultModel is the model_name (MyModel) and a unique_id. I want to sanely manage this many (MyModel1,...MyModelN) to one (MyResultModel) relationship.

```<code>class MyResultModel(models.Model):
    unique_id = ...
    model_name = models.CharField(max_length=200, default='', blank=False) # Points to a Django Model ex MyModel
    result1 = ...
    result2 = ...
</code>```

答:
Another possible solution is to store the parameters JsonField

https://bitbucket.org/schinckel/django-jsonfield

Body:
I want to maintain a Django model with a unique id for every combination of choices within the model. I would then like to be able to update the model with a new field and not have the previous unique id's change.
The id's can be a hash or integer or anything.
What's the best way to achieve this?

class MyModel(models.Model):
    WINDOW_MIN = 5
    WINDOW_MAX = 7
    WINDOW_CHOICES = [(i,i) for i in range(WINDOW_MIN - 1, WINDOW_MAX - 1)]
    window = models.PositiveIntegerField('Window', editable=True, default=WINDOW_MIN, choices=WINDOW_CHOICES)
    is_live = models.BooleanField('Live', editable=True, default=False)
    unique_id = ....

Given the above example there will be 3 * 2 == 6 unique id's. If I add another editable boolean field, I don't want to change the previous unique id's but I want the new unique id's to be generated for the new boolean field.

The thought process behind this is the parameters in MyModel define the inputs to a function who's results are stored in another Django model MyResultModel by unique_id and the name of the model. The reasoning behind this is there are multiple variants of MyModel each with it's own set unique combination's that get updated regularly but the result set in MyResultModel is the same across MyModel1 to MyModelN. Ideally I would like the unique_id's to be autogenerated. In other words the key for the result set stored in MyResultModel is the model_name (MyModel) and a unique_id. I want to sanely manage this many (MyModel1,...MyModelN) to one (MyResultModel) relationship.

class MyResultModel(models.Model):
    unique_id = ...
    model_name = models.CharField(max_length=200, default='', blank=False) # Points to a Django Model ex MyModel
    result1 = ...
    result2 = ...


问:
How to map number in a range to another in the same range with no collisions?
Effectively what I'm looking for is a function f(x) that outputs into a range that is pre-defined. Calling f(f(x)) should be valid as well. The function should be cyclical, so calling f(f(...(x))) where the number of calls is equal to the size of the range should give you the original number, and f(x) should not be time dependent and will always give the same output.

While I can see that taking a list of all possible values and shuffling it would give me something close to what I want, I'd much prefer it if I could simply plug values into the function one at a time so that I do not have to compute the entire range all at once.

I've looked into Minimal Perfect Hash Functions but haven't been able to find one that doesn't use external libraries. I'm okay with using them, but would prefer to not do so.

If an actual range is necessary to help answer my question, I don't think it would need to be bigger than [0, 2^24-1], but the starting and ending values don't matter too much.

答:
Minimal perfect hash functions are overkill, all you've asked for is a function f that is,

bijective, and

"cyclical" (ie fN=f)

For a permutation to be cyclical in that way, its order must divide N (or be N but in a way that's just a special case of dividing N). Which in turn means the LCM of the orders of the sub-cycles must divide N. One way to do that is to just have one "sub"-cycle of order N. For power of two N, it's also really easy to have lots of small cycles of some other power-of-two order. General permutations do not necessarily satisfy the cycle-requirement, of course they are bijective but the LCM of the orders of the sub-cycles may exceed N.

In the following I will leave all reduction modulo N implicit. Without loss of generality I will assume the range starts at 0 and goes up to N-1, where N is the size of the range.

The only thing I can immediately think of for general N is f(x) = x + c where gcd(c, N) == 1. The GCD condition ensures there is only one cycle, which necessarily has order N.

For power-of-two N I have more inspiration:

f(x) = cx where c is odd. Bijective because gcd(c, N) == 1 so c has a modular multiplicative inverse. Also cN=1, because φ(N)=N/2 (since N is a power of two) so cφ(N)=1 (Euler's theorem).

f(x) = x XOR c where c < N. Trivially bijective and trivially cycles with a period of 2, which divides N.

f(x) = clmul(x, c) where c is odd and clmul is carry-less multiplication. Bijective because any odd c has a carry-less multiplicative inverse. Has some power-of-two cycle length (less than N) so it divides N. I don't know why though. This is a weird one, but it has decent special cases such as x ^ (x << k). By symmetry, the "mirrored" version also works.

Eg x ^ (x >> k).

f(x) = x >>> k where >>> is bit-rotation. Obviously bijective, and fN(x) = x >>> Nk, where Nk mod N = 0 so it rotates all the way back to the unrotated position regardless of what k is.


问:
Vertical spacing in Matplotlib latex fractions
I have created fractional values for my x tick labels, but the fractions look a little cramped to me. Is there a way to increase the vertical spacing?

```<code>import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_xticklabels(
    ['$\\frac{{{0}}}{{{1}}}$'.format('M', x) for x in ax.get_xticks()],
    fontsize=12)

plt.show()
</code>```

答:
The vertical spacing can be improved by forcing Matplotlib to use LaTeX rather than mathtext:

```<code>plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] = [r'\usepackage{sansmath}', r'\sansmath']
</code>```

The sansmath package retains the sans-serif type:

before:  after:

Body:
I have created fractional values for my x tick labels, but the fractions look a little cramped to me. Is there a way to increase the vertical spacing?

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_xlim(0, 10)
ax.set_xticklabels(
    ['$\\frac{{{0}}}{{{1}}}$'.format('M', x) for x in ax.get_xticks()],
    fontsize=12)

plt.show()

Body:
The vertical spacing can be improved by forcing Matplotlib to use LaTeX rather than mathtext:

plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] = [r'\usepackage{sansmath}', r'\sansmath']

The sansmath package retains the sans-serif type:

before:  after:


问:
Trying to set 2 animations on the same elements
I am trying to set 2 different animations, one first and then the other one.

As you may see on this Codepen and in the snippet below, the first animation fires when page load, which is the one re-arranging the icons to its original positions.
The other animation is a pulse animation which must be reflected on the border of the icons.

Look at the code:

.eight-box {
  position: relative;
  display: block;
  margin: 1em auto;
  width: 16em;
  height: 16em;
  font-family: sans-serif;
  font-size: 20px;
  border: 1px solid;
  border-radius: 50%;
}
.fig-8 {
  display: block;
  position: absolute;
  color: #fff;
  width: 2em;
  height: 2em;
  line-height: 2;
  text-align: center;
  font-weight: bold;
  font-smoothing: antialiased;
 transition: all .5s linear;
  overflow: hidden;
  z-index: 5;
}

.col-1 {
 background: #1abc9c;
}
.col-2 {
 background: #9b59b6;
}
.col-3 {
 background: #27ae60;
}
.col-4 {
 background: #2c3e50;
}

.pos-1 {
 top: 30%;
 left: 93.75%;
}
.pos-2 {
 top: 66.25%;
 left: 88.75%;
}
.pos-3 {
 top: 72.92%;
 right: 83.125%;
}
.pos-4 {
 top: 19.58%;
 right: 88.75%;
}

.fig-8 {
    animation: pulse-special 1s 1s 1 alternate backwards, upDown 1s;
    border-radius: 50%;
}
@keyframes pulse-special {
    0% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -webkit-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}
@keyframes pulse-special {
    0% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -moz-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}

@keyframes upDown {
    from { margin-top: -30px; }
    to { margin-top: 0; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="eight-box">
  <div class="fig-8 col-1 pos-1">1</div>
  <div class="fig-8 col-2 pos-2">2</div>
  <div class="fig-8 col-3 pos-3">3</div>
  <div class="fig-8 col-4 pos-4">4</div>
</div></code>```

Any suggestions?

答:
Try this CSS
Seperate the two animations using comma(,)

CSS

```<code>.fig-8 {
       animation: upDown 1s 1s 1 alternate backwards,
         pulse-special 1s 1s 1 alternate backwards;
}
</code>```

Hope this helps..

Body:
I am trying to set 2 different animations, one first and then the other one.

As you may see on this Codepen and in the snippet below, the first animation fires when page load, which is the one re-arranging the icons to its original positions.
The other animation is a pulse animation which must be reflected on the border of the icons.

Look at the code:

.eight-box {
  position: relative;
  display: block;
  margin: 1em auto;
  width: 16em;
  height: 16em;
  font-family: sans-serif;
  font-size: 20px;
  border: 1px solid;
  border-radius: 50%;
}
.fig-8 {
  display: block;
  position: absolute;
  color: #fff;
  width: 2em;
  height: 2em;
  line-height: 2;
  text-align: center;
  font-weight: bold;
  font-smoothing: antialiased;
 transition: all .5s linear;
  overflow: hidden;
  z-index: 5;
}

.col-1 {
 background: #1abc9c;
}
.col-2 {
 background: #9b59b6;
}
.col-3 {
 background: #27ae60;
}
.col-4 {
 background: #2c3e50;
}

.pos-1 {
 top: 30%;
 left: 93.75%;
}
.pos-2 {
 top: 66.25%;
 left: 88.75%;
}
.pos-3 {
 top: 72.92%;
 right: 83.125%;
}
.pos-4 {
 top: 19.58%;
 right: 88.75%;
}

.fig-8 {
    animation: pulse-special 1s 1s 1 alternate backwards, upDown 1s;
    border-radius: 50%;
}
@keyframes pulse-special {
    0% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -webkit-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}
@keyframes pulse-special {
    0% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -moz-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}

@keyframes upDown {
    from { margin-top: -30px; }
    to { margin-top: 0; }
}

1

2

3

4

Any suggestions?

Body:
Try this CSS
Seperate the two animations using comma(,)

CSS

.fig-8 {
       animation: upDown 1s 1s 1 alternate backwards,
         pulse-special 1s 1s 1 alternate backwards;
}

Hope this helps..


问:
Save data to csv from different variables
I'm new to python and I'm looking for some help to create a loop that store data from two different variables. This method saves only the first tweet.

```<code># Twitter Loop

for tweet in tweepy.Cursor(api.search,q=search+
        " -filter:retweets",
        result_type='recent',
        lang="en").items(num_tweets):

    raw = tweet.text

    # Text processing

    clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw)

    result = cool.api(clean)

# CSV File

import csv
f = open("file.csv", "a")
c = csv.writer(f)
c.writerow([clean, result])
f.close()
</code>```

I made a lot of attempts and I'm not sure what's the correct way to do it.n Should I create a loop for every variable?

答:
Simple. You need to move your calls to csv.writerow() inside of your for loop. That way, each tweet you iterate over will be written to the csv file(or to be more precise, the data grepped from the tweet):

```<code>import csv

f = open("file.csv", "a", newline="")
c = csv.writer(f)

for tweet in tweepy.Cursor(api.search,q=search+
        " -filter:retweets",
        result_type='recent',
        lang="en").items(num_tweets):

    raw = tweet.text
    clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw)
    result = cool.api(clean)
    c.writerow([clean, result]) # Write each tweet to the csv file.
f.close()
</code>```

Your code can be improved by using the context manager statement with. This means your file will always be closed regardless of what happens:

```<code>import csv

with open('file.csv', 'a') as file:
    c = csv.writer(file)
    for tweet in tweepy.Cursor(api.search,q=search+
        " -filter:retweets",
        result_type='recent',
        lang="en").items(num_tweets):

        raw = tweet.text
        clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw)
        result = cool.api(clean)
        c.writerow([clean, result])
</code>```

Body:
I'm new to python and I'm looking for some help to create a loop that store data from two different variables. This method saves only the first tweet.

# Twitter Loop

for tweet in tweepy.Cursor(api.search,q=search+
        " -filter:retweets",
        result_type='recent',
        lang="en").items(num_tweets):

    raw = tweet.text

    # Text processing

    clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw)

    result = cool.api(clean)

# CSV File

import csv
f = open("file.csv", "a")
c = csv.writer(f)
c.writerow([clean, result])
f.close()

I made a lot of attempts and I'm not sure what's the correct way to do it.n Should I create a loop for every variable?

Body:
Simple. You need to move your calls to csv.writerow() inside of your for loop. That way, each tweet you iterate over will be written to the csv file(or to be more precise, the data grepped from the tweet):

import csv

f = open("file.csv", "a", newline="")
c = csv.writer(f)

for tweet in tweepy.Cursor(api.search,q=search+
        " -filter:retweets",
        result_type='recent',
        lang="en").items(num_tweets):

    raw = tweet.text
    clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw)
    result = cool.api(clean)
    c.writerow([clean, result]) # Write each tweet to the csv file.
f.close()

Your code can be improved by using the context manager statement with. This means your file will always be closed regardless of what happens:

import csv

with open('file.csv', 'a') as file:
    c = csv.writer(file)
    for tweet in tweepy.Cursor(api.search,q=search+
        " -filter:retweets",
        result_type='recent',
        lang="en").items(num_tweets):

        raw = tweet.text
        clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw)
        result = cool.api(clean)
        c.writerow([clean, result])


问:
Writing a dictionary with multiple items and values into a cvs file
I Have a dictionary with multiple keys and values as follows:

```<code> My_data = {'key1': [item1 value1, item2 value2],
            'key2': [item1 value1, item2 value2],
            'key3': [item1 value1, item2 value2]}
</code>```

Now, I need to write them into a csv file as follows:

```<code>      Item1    Item2   Item3

Key1  value1   value2 value3
Key2  value1   value2 value3
Key3  value1   value2 value3
</code>```

Does Anyone know how to do that? I tried this code but does not work:

```<code>with open("dict2csv.csv", 'wb') as csv_file:
    for key, value in My_data.items():
        csv_file.write('%s:%s\n' % (key, value))
</code>```

答:
If you format your My_data correctly to be dictionary with valid key value pair and the value being a valid tuple or list here is one of the way you can get desired output. (assuming the value will be a tuple of (item, value)).

If your item and value are two words then you can go for approach 2.

This is basic coding, you would have to add error handling and other cosmetics to make it perfect for your input validation.

```<code>import platform

## Approach 1
My_data = {'key1': [('item1','value1'),('item2','value2')], 'key2': [('item1','value1'), ('item2','value2')], 'key3': [('item1','value1'), ('item2','value2'), ('item3','value3')]}

print("Python version : " + platform.python_version())

print()

print("Approach 1 with formatted My_data")
with open("dict2csv1.csv", 'w') as output:
    ## print data
    for key, values in My_data.items():
        data = ""
        for value in values:
            data = data + value[1] + ","
        data = key + "," + data[:-1] + "\n"
        ## display on console for debugging
        print(data, end='')
        output.write(data)

print()

## Approach 2
print("Approach 2 with given My_data")
My_data = {'key1': ['item1 value1', 'item2 value2'], 'key2': ['item1 value1', 'item2 value2'], 'key3': ['item1 value1', 'item2 value2', 'item3 value3']}
with open("dict2csv2.csv", 'w') as output:
    ## print data
    for key, values in My_data.items():
        data = ""
        for value in values:
            valueItems = value.split()
            data = data + valueItems[1] + ","
        data = key + "," + data[:-1] + "\n"
        ## display on console for debugging
        print(data, end='')
        output.write(data)
</code>```

Sample Run (key3 has more than 2 items i.e. each key having different number of items)

```<code>Python version : 3.6.1

Approach 1 with formatted My_data
key1,value1,value2
key2,value1,value2
key3,value1,value2,value3

Approach 2 with given My_data
key1,value1,value2
key2,value1,value2
key3,value1,value2,value3
</code>```

Body:
I Have a dictionary with multiple keys and values as follows:

 My_data = {'key1': [item1 value1, item2 value2],
            'key2': [item1 value1, item2 value2],
            'key3': [item1 value1, item2 value2]}

Now, I need to write them into a csv file as follows:

      Item1    Item2   Item3

Key1  value1   value2 value3
Key2  value1   value2 value3
Key3  value1   value2 value3

Does Anyone know how to do that? I tried this code but does not work:

with open("dict2csv.csv", 'wb') as csv_file:
    for key, value in My_data.items():
        csv_file.write('%s:%s\n' % (key, value))

Body:
If you format your My_data correctly to be dictionary with valid key value pair and the value being a valid tuple or list here is one of the way you can get desired output. (assuming the value will be a tuple of (item, value)).

If your item and value are two words then you can go for approach 2.

This is basic coding, you would have to add error handling and other cosmetics to make it perfect for your input validation.

import platform

## Approach 1
My_data = {'key1': [('item1','value1'),('item2','value2')], 'key2': [('item1','value1'), ('item2','value2')], 'key3': [('item1','value1'), ('item2','value2'), ('item3','value3')]}

print("Python version : " + platform.python_version())

print()

print("Approach 1 with formatted My_data")
with open("dict2csv1.csv", 'w') as output:
    ## print data
    for key, values in My_data.items():
        data = ""
        for value in values:
            data = data + value[1] + ","
        data = key + "," + data[:-1] + "\n"
        ## display on console for debugging
        print(data, end='')
        output.write(data)

print()

## Approach 2
print("Approach 2 with given My_data")
My_data = {'key1': ['item1 value1', 'item2 value2'], 'key2': ['item1 value1', 'item2 value2'], 'key3': ['item1 value1', 'item2 value2', 'item3 value3']}
with open("dict2csv2.csv", 'w') as output:
    ## print data
    for key, values in My_data.items():
        data = ""
        for value in values:
            valueItems = value.split()
            data = data + valueItems[1] + ","
        data = key + "," + data[:-1] + "\n"
        ## display on console for debugging
        print(data, end='')
        output.write(data)

Sample Run (key3 has more than 2 items i.e. each key having different number of items)

Python version : 3.6.1

Approach 1 with formatted My_data
key1,value1,value2
key2,value1,value2
key3,value1,value2,value3

Approach 2 with given My_data
key1,value1,value2
key2,value1,value2
key3,value1,value2,value3


问:
Regular Expression matches in online testing but not in javascript execution?
My regular expression should find and remove all words beginning with foo-. The regular expression works in an online regex http://regexr.com/3gafi but fails in my javascript.

Whats going wrong?

$('[class*="foo-"]').each(function(index, ele) {

 ele.className = ele.className.replace(/(foo-.*( |\0))/g, '');
  console.log(ele.className);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo-abc img-responsive"></div>

<div class="foo-abc"></div>

<div class=" foo-abc"></div>

<div class=" foo-abc "></div></code>```

答:
$('[class*="foo-"]').each(function(index, ele) {

 ele.className = ele.className.replace(/(foo-.*( |\0)?)/g, '');
  console.log(ele.className);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo-abc img-responsive"></div>

<div class="foo-abc"></div>

<div class=" foo-abc"></div>

<div class=" foo-abc "></div></code>```

Hope it helps.

Body:
$('[class*="foo-"]').each(function(index, ele) {

 ele.className = ele.className.replace(/(foo-.*( |\0)?)/g, '');
  console.log(ele.className);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo-abc img-responsive"></div>

<div class="foo-abc"></div>

<div class=" foo-abc"></div>

<div class=" foo-abc "></div>

Hope it helps.