问:
Pytorch: how to convert data into tensor
I am a beginner for Pytorch.
I was trying to write CNN code referring Pytorch tutorial.
Below is a part of the code, but it shows error "RuntimeError: Variable data has to be a tensor, but got list". I tried to cast input data to tensor but didn't work well. If anybody know the solution, please help me out...

```<code>    def read_labels(file):
      dic = {}
      with open(file) as f:
        reader = f
        for row in reader:
            dic[row.split(",")[0]]  = row.split(",")[1].rstrip() #rstrip(): eliminate "\n"
      return dic

    image_names= os.listdir("./train_mini")
    label_dic = read_labels("labels.csv")

    names =[]
    labels = []
    images =[]

    for name in image_names[1:]:
        images.append(cv2.imread("./train_mini/"+name))
        labels.append(label_dic[os.path.splitext(name)[0]])

    """
    Data distribution
    """
    N = len(images)
    N_train = int(N * 0.7)
    N_test = int(N*0.2)

    X_train, X_tmp, Y_train, Y_tmp = train_test_split(images, labels, train_size=N_train)
    X_validation, X_test, Y_validation, Y_test = train_test_split(X_tmp, Y_tmp, test_size=N_test)

    """
    Model Definition
    """

    class CNN(nn.Module):
        def __init__(self):
            super(CNN, self).__init__()
            self.head = nn.Sequential(
                nn.Conv2d(in_channels=1, out_channels=10,
                          kernel_size=5, stride=1),
                nn.MaxPool2d(kernel_size=2),
                nn.ReLU(),
                nn.Conv2d(10, 20, kernel_size=5),
                nn.MaxPool2d(kernel_size=2),
                nn.ReLU())
            self.tail = nn.Sequential(
                nn.Linear(320, 50),
                nn.ReLU(),
                nn.Linear(50, 10))

        def forward(self, x):
            x = self.head(x)
            x = x.view(-1, 320)
            x = self.tail(x)
            return F.log_softmax(x)

    CNN = CNN()
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(CNN.parameters(), lr=0.001, momentum=0.9)

    """
    Training
    """
    batch_size = 50
    for epoch in range(2):  # loop over the dataset multiple times
        running_loss = 0.0
        for i in range(N / batch_size):
        #for i, data in enumerate(trainloader, 0):
            batch = batch_size * i

            # get the inputs
            images_batch = X_train[batch:batch + batch_size]
            labels_batch = Y_train[batch:batch + batch_size]

            # wrap them in Variable
            images_batch, labels_batch = Variable(images_batch), Variable(labels_batch)

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            outputs = CNN(images_batch)
            loss = criterion(outputs, labels_batch)
            loss.backward()
            optimizer.step()

            # print statistics
            running_loss += loss.data[0]
            if i % 2000 == 1999:    # print every 2000 mini-batches
                print('[%d, %5d] loss: %.3f' %
                      (epoch + 1, i + 1, running_loss / 2000))
                running_loss = 0.0

    print('Finished Training')
</code>```

And error is happening here

```<code># wrap them in Variable
images_batch, labels_batch = Variable(images_batch), Variable(labels_batch)
</code>```

答:
If my guess is correct, you are probably getting error in the following line.

```<code># wrap them in Variable
images_batch, labels_batch = Variable(images_batch), Variable(labels_batch)
</code>```

It means, images_batch and/or labels_batch are lists. You can simple convert them to numpy array and then convert to tensor as follows.

```<code># wrap them in Variable
images_batch = torch.from_numpy(numpy.array(images_batch))
labels_batch = torch.from_numpy(numpy.array(labels_batch))
</code>```

It should solve your problem.

Edit: If you get the following error while running the above snippet of code:

"RuntimeError: can't convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8."

You can create the numpy array by giving a data type. For example,

```<code>images_batch = torch.from_numpy(numpy.array(images_batch, dtype='int32'))
</code>```

I am assuming images_batch contains pixel information of images, so I used int32. For more information, see official documentation.

Body:
I am a beginner for Pytorch.
I was trying to write CNN code referring Pytorch tutorial.
Below is a part of the code, but it shows error "RuntimeError: Variable data has to be a tensor, but got list". I tried to cast input data to tensor but didn't work well. If anybody know the solution, please help me out...

    def read_labels(file):
      dic = {}
      with open(file) as f:
        reader = f
        for row in reader:
            dic[row.split(",")[0]]  = row.split(",")[1].rstrip() #rstrip(): eliminate "\n"
      return dic

    image_names= os.listdir("./train_mini")
    label_dic = read_labels("labels.csv")

    names =[]
    labels = []
    images =[]

    for name in image_names[1:]:
        images.append(cv2.imread("./train_mini/"+name))
        labels.append(label_dic[os.path.splitext(name)[0]])

    """
    Data distribution
    """
    N = len(images)
    N_train = int(N * 0.7)
    N_test = int(N*0.2)

    X_train, X_tmp, Y_train, Y_tmp = train_test_split(images, labels, train_size=N_train)
    X_validation, X_test, Y_validation, Y_test = train_test_split(X_tmp, Y_tmp, test_size=N_test)

    """
    Model Definition
    """

    class CNN(nn.Module):
        def __init__(self):
            super(CNN, self).__init__()
            self.head = nn.Sequential(
                nn.Conv2d(in_channels=1, out_channels=10,
                          kernel_size=5, stride=1),
                nn.MaxPool2d(kernel_size=2),
                nn.ReLU(),
                nn.Conv2d(10, 20, kernel_size=5),
                nn.MaxPool2d(kernel_size=2),
                nn.ReLU())
            self.tail = nn.Sequential(
                nn.Linear(320, 50),
                nn.ReLU(),
                nn.Linear(50, 10))

        def forward(self, x):
            x = self.head(x)
            x = x.view(-1, 320)
            x = self.tail(x)
            return F.log_softmax(x)

    CNN = CNN()
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(CNN.parameters(), lr=0.001, momentum=0.9)

    """
    Training
    """
    batch_size = 50
    for epoch in range(2):  # loop over the dataset multiple times
        running_loss = 0.0
        for i in range(N / batch_size):
        #for i, data in enumerate(trainloader, 0):
            batch = batch_size * i

            # get the inputs
            images_batch = X_train[batch:batch + batch_size]
            labels_batch = Y_train[batch:batch + batch_size]

            # wrap them in Variable
            images_batch, labels_batch = Variable(images_batch), Variable(labels_batch)

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            outputs = CNN(images_batch)
            loss = criterion(outputs, labels_batch)
            loss.backward()
            optimizer.step()

            # print statistics
            running_loss += loss.data[0]
            if i % 2000 == 1999:    # print every 2000 mini-batches
                print('[%d, %5d] loss: %.3f' %
                      (epoch + 1, i + 1, running_loss / 2000))
                running_loss = 0.0

    print('Finished Training')

And error is happening here

# wrap them in Variable
images_batch, labels_batch = Variable(images_batch), Variable(labels_batch)

Body:
If my guess is correct, you are probably getting error in the following line.

# wrap them in Variable
images_batch, labels_batch = Variable(images_batch), Variable(labels_batch)

It means, images_batch and/or labels_batch are lists. You can simple convert them to numpy array and then convert to tensor as follows.

# wrap them in Variable
images_batch = torch.from_numpy(numpy.array(images_batch))
labels_batch = torch.from_numpy(numpy.array(labels_batch))

It should solve your problem.

Edit: If you get the following error while running the above snippet of code:

"RuntimeError: can't convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8."

You can create the numpy array by giving a data type. For example,

images_batch = torch.from_numpy(numpy.array(images_batch, dtype='int32'))

I am assuming images_batch contains pixel information of images, so I used int32. For more information, see official documentation.


来源: stackexchange

问:
unicode characters not showing correctly on one server (Azure)
this problem is driving me nuts. I have a test server and a live server. The test server is showing unicode characters retrieved from an Azure sql database correctly. While the live server running identical code accessing the same data is not showing them correctly.

The data in the database is:
Hallo ich heiße Pokémon! Ich würde gerne mal mit einem anderen Kämpfe!

The test servers shows
    Hallo ich heiße Pokémon! Ich würde etc...

The live server, which is an Azure web  service shows
    Hallo ich hei�e Pok�mon! Ich w�rde gerne mal mit einem anderen K�mpfe

Same PHP code, Same database, Same browser, same db connection string,
different web servers, different results.

I do know Azure is running PHP 5.6 and the test server is running PHP 5.3
They are using sqlsrv_connect
The data field is type  varchar.

I tried using "CharacterSet" => "UTF-8"  in the connection but this made no difference to the Azure server and screwed up the result on the test server.

I am out of ideas and leads.

答:
I swear I tried this before, but this turns out to be the answer

```<code>"CharacterSet" => "UTF-8"
</code>```

added to the connection string, and

```<code><meta charset="UTF-8">
</code>```

in the web page.

ContentLicense: CC BY-SA 3.0

Body:
I swear I tried this before, but this turns out to be the answer

"CharacterSet" => "UTF-8"

added to the connection string, and

<meta charset="UTF-8">

in the web page.


问:
Testing for a deadlock with nUnit
I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this?

Thank you

答:
Well its certainly possible to test for a deadlock by running your code on another thread and seeing if it returns in a timely fashion. Here's some (very basic) example code:

```<code>[TestFixture]
public class DeadlockTests
{
    [Test]
    public void TestForDeadlock()
    {
        Thread thread = new Thread(ThreadFunction);
        thread.Start();
        if (!thread.Join(5000))
        {
            Assert.Fail("Deadlock detected");
        }
    }

    private void ThreadFunction()
    {
        // do something that causes a deadlock here
        Thread.Sleep(10000);
    }
}
</code>```

I wouldn't like to say that this is the "best way", but it is one I have found useful on occasions.

OwnerDisplayName: frou

ContentLicense: CC BY-SA 2.5

Title: Testing for a deadlock with nUnit

Body:
Well its certainly possible to test for a deadlock by running your code on another thread and seeing if it returns in a timely fashion. Here's some (very basic) example code:

[TestFixture]
public class DeadlockTests
{
    [Test]
    public void TestForDeadlock()
    {
        Thread thread = new Thread(ThreadFunction);
        thread.Start();
        if (!thread.Join(5000))
        {
            Assert.Fail("Deadlock detected");
        }
    }

    private void ThreadFunction()
    {
        // do something that causes a deadlock here
        Thread.Sleep(10000);
    }
}

I wouldn't like to say that this is the "best way", but it is one I have found useful on occasions.

OwnerDisplayName: Mark Heath


问:
How do you Tar an svn directory and filter out all the .svn files?
I'm trying to create a tar file for deployment of some code but I dont want all the .svn files being deployed.

How can I filter these out? They're in multiple directories...

答:
use svn export command to make a clean copy of the local sandbox.

http://svnbook.red-bean.com/en/1.0/re10.html

```<code>svn export [-r REV] URL [PATH]

svn export PATH1 PATH2
</code>```

Body:
use svn export command to make a clean copy of the local sandbox.

http://svnbook.red-bean.com/en/1.0/re10.html

svn export [-r REV] URL [PATH]

svn export PATH1 PATH2


问:
How to convert an already open file to string?
Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type)</p>

```<code>def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''
</code>```

答:
```<code>content = myfile.read()
</code>```

Or to read it line by line and put it in a list:

```<code>content_list = myfile.readlines()
</code>```

You can then use:

```<code>content_list = [x.strip() for x in content_list]
</code>```

to remove \n characters.

Body:
Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type)

def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''

Body:
content = myfile.read()

Or to read it line by line and put it in a list:

content_list = myfile.readlines()

You can then use:

content_list = [x.strip() for x in content_list]

to remove \n characters.


问:
MASM Array not looping
Update (2017-11-13):

I added another variable "index" and set it to zero.  Then, after every .IF loop, I added 4 (DWORD) to the index, which is then passed to the esi register and points to the correct array variable.  I also moved the includedCounter variable outside of the .IF loop.  The answer is now correct!!

I'm trying to loop through an array and sum only the values that are >= 3 && <= 8.  The pointer [ESI] to the array is only "looping" to the first value in the array (3).

Why is ESI not incrementing to the next array?

Values should return "64" for the sum and "13" for the includedCounter.  Current values return as "60" for sum and "20" for includedCounter, which tells me that the first integer in the array is constantly being pointed to, instead of each integer in the array being pointed to.

```<code>; Calculates the sum of all array elements
; >= "lower" value (3) and <= "higher" value (8).

INCLUDE Irvine32.inc

.data
sum DWORD ?              ; EAX - holds sum of included integers

lower DWORD 3            ; holds lower value
upper DWORD 8            ; holds higher value

;Update (2017-11-13)
index DWORD 0            ; holds index for array
;==============
loopCounter DWORD ?      ; ESI - holds loop array pointer
includedCounter DWORD ?  ; EDX - holds 'included' counter

array DWORD 3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4    ; values checked
arraySize = ($ - array) / TYPE array                   ; [current location lounter ($) - array / DWORD] = 20

.code
main PROC
 mov eax, sum
 mov ebx, lower
 mov ecx, upper
 mov edx, includedCounter

.WHILE loopCounter < arraySize     ; While loopCounter is less than 20
      ;Update (2017-11-13)
      mov esi, index
      ;===============
      .IF (array[esi] >= ebx) && (array[esi] <= ecx)
      add eax, array[esi]
      inc includedCounter
     .ENDIF
  ;Update (2017-11-13)
  add index, 4
  inc loopCounter
  ;================
.ENDW

; Display values
mov sum, eax
mov eax, sum
call WriteInt
call CrLF

mov eax, includedCounter
call WriteInt
Call CrLF

; Exit program
call WaitMsg

    exit
main ENDP
END main
</code>```

答: Your comments (in and out of the code) suggest that you think that incrementing loopCounter will somehow automatically increment ESI as well.  These are, in fact, distinct entities (one is a register, the other a location in memory), so this "automatic increment" does not happen.  (In fact, more often than not, nothing happens "automatically" in assembly code.)

Title: MASM Array not looping

Body:
Update (2017-11-13):

I added another variable "index" and set it to zero.  Then, after every .IF loop, I added 4 (DWORD) to the index, which is then passed to the esi register and points to the correct array variable.  I also moved the includedCounter variable outside of the .IF loop.  The answer is now correct!!

I'm trying to loop through an array and sum only the values that are >= 3 && <= 8.  The pointer [ESI] to the array is only "looping" to the first value in the array (3).

Why is ESI not incrementing to the next array?

Values should return "64" for the sum and "13" for the includedCounter.  Current values return as "60" for sum and "20" for includedCounter, which tells me that the first integer in the array is constantly being pointed to, instead of each integer in the array being pointed to.

; Calculates the sum of all array elements
; >= "lower" value (3) and <= "higher" value (8).

INCLUDE Irvine32.inc

.data
sum DWORD ?              ; EAX - holds sum of included integers

lower DWORD 3            ; holds lower value
upper DWORD 8            ; holds higher value

;Update (2017-11-13)
index DWORD 0            ; holds index for array
;==============
loopCounter DWORD ?      ; ESI - holds loop array pointer
includedCounter DWORD ?  ; EDX - holds 'included' counter

array DWORD 3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4    ; values checked
arraySize = ($ - array) / TYPE array                   ; [current location lounter ($) - array / DWORD] = 20

.code
main PROC
 mov eax, sum
 mov ebx, lower
 mov ecx, upper
 mov edx, includedCounter

.WHILE loopCounter < arraySize     ; While loopCounter is less than 20
      ;Update (2017-11-13)
      mov esi, index
      ;===============
      .IF (array[esi] >= ebx) && (array[esi] <= ecx)
      add eax, array[esi]
      inc includedCounter
     .ENDIF
  ;Update (2017-11-13)
  add index, 4
  inc loopCounter
  ;================
.ENDW

; Display values
mov sum, eax
mov eax, sum
call WriteInt
call CrLF

mov eax, includedCounter
call WriteInt
Call CrLF

; Exit program
call WaitMsg

    exit
main ENDP
END main


答:
you can use the svn Export function to get a clean version of the files without the .svn folders.

Do this in a different location than your working copy.

Title: How do you Tar an svn directory and filter out all the .svn files?

Body:
I'm trying to create a tar file for deployment of some code but I dont want all the .svn files being deployed.

How can I filter these out? They're in multiple directories...


问:
CSS: Left, Center, & Right Align Text on Same Line
I need to left, center, & right align text on the same line. I have the following text:

Left Align: 1/10

Center: 02:27

Right Align: 100%

I wrote the following code which works for left and right aligning text but does not work correctly for the center text.

HTML

```<code><div id="textbox">
<p class="alignleft">1/10</p>
<p class="aligncenter">02:27</p>
<p class="alignright">100%</p>
</div>
<div style="clear: both;"></div>
</code>```

CSS

```<code>.alignleft {
    float: left;
}
.aligncenter {
    float: left;
}
.alignright {
    float: right;
}
</code>```

答:
And now a fresh, quite different approach.

.same-line {
    height: 10px; /*childrens it's all absolute position, so must set height*/
    position: relative;
}
.same-line div{
    display: inline-block;
    position: absolute;
}
.on-the-left{
 left:0px;
}
.on-the-center{
    left: 0%;
    right: 0%;
    text-align: center;
}
.on-the-right{
   right: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="same-line">
    <div class="on-the-left" >it's Left</div>
    <div class="on-the-center" >this Centrer bla bla bla</div>
    <div class="on-the-right" >it's Right</div>
  </div></code>```

Body:
I need to left, center, & right align text on the same line. I have the following text:

Left Align: 1/10

Center: 02:27

Right Align: 100%

I wrote the following code which works for left and right aligning text but does not work correctly for the center text.

HTML

1/10

02:27

100%

CSS

.alignleft {
    float: left;
}
.aligncenter {
    float: left;
}
.alignright {
    float: right;
}

Body:
And now a fresh, quite different approach.

.same-line {
    height: 10px; /*childrens it's all absolute position, so must set height*/
    position: relative;
}
.same-line div{
    display: inline-block;
    position: absolute;
}
.on-the-left{
 left:0px;
}
.on-the-center{
    left: 0%;
    right: 0%;
    text-align: center;
}
.on-the-right{
   right: 0px;
}

<div class="same-line">
    <div class="on-the-left" >it's Left</div>
    <div class="on-the-center" >this Centrer bla bla bla</div>
    <div class="on-the-right" >it's Right</div>
  </div>


问:
insert data to column based on query
I have two tables. The table I am trying to update is table A which doesn't have some IDs ProfileIDs. At the other hand table B has all the IDs. I am trying to update the column in Table A based on a query. When I join the tables I get all the results in my query and as i try to update/insert the results in my column I get a cannot insert into my table. I am intending to insert my results with the following query  </p>

```<code> insert into TableA a
(profileID)

select b.profileID
from tableA
join TableB B on B.userID = A.userID

where a.profileID = '' or a.profileID is null

    Table A                                                            Table B

UserID | profileID | lastname | Firstname               UserID | profileID | lastname | Firstname
0012356               Wung      Clara                   0012356   15963         Wung      Clara
0512356    14753      Williams  Michael                 0512356   14753      Williams     Michael
0956356               Walters   Jeff                    0956356   94356      Walters      Jeff
0486312    68956      Wwagner   George                  0486312   68956      Wwagner   George

select A.*, B.profileID
from TableA A
join TableB B on B.userID = A.userID

Results

UserID | profileID | lastname | Firstname
0012356   15963         Wung      Clara
0512356   14753      Williams     Michael
0956356   94356      Walters      Jeff
0486312   68956      Wwagner   George
</code>```

答:
You should not use 'INSERT' statement for updating a table. Instead use 'UPDATE'.</p>

```<code>UPDATE tableA SET tableA.profileID = tableB.profileID FROM tableB b
INNER JOIN TableA a ON a.userID = b.userID WHERE
a.profileID = '' OR a.profileID IS NULL;
</code>```

Title: insert data to column based on query

Body:
I have two tables. The table I am trying to update is table A which doesn't have some IDs ProfileIDs. At the other hand table B has all the IDs. I am trying to update the column in Table A based on a query. When I join the tables I get all the results in my query and as i try to update/insert the results in my column I get a cannot insert into my table. I am intending to insert my results with the following query

 insert into TableA a
(profileID)

select b.profileID
from tableA
join TableB B on B.userID = A.userID

where a.profileID = '' or a.profileID is null

    Table A                                                            Table B

UserID | profileID | lastname | Firstname               UserID | profileID | lastname | Firstname
0012356               Wung      Clara                   0012356   15963         Wung      Clara
0512356    14753      Williams  Michael                 0512356   14753      Williams     Michael
0956356               Walters   Jeff                    0956356   94356      Walters      Jeff
0486312    68956      Wwagner   George                  0486312   68956      Wwagner   George

select A.*, B.profileID
from TableA A
join TableB B on B.userID = A.userID

Results

UserID | profileID | lastname | Firstname
0012356   15963         Wung      Clara
0512356   14753      Williams     Michael
0956356   94356      Walters      Jeff
0486312   68956      Wwagner   George

Body:
You should not use 'INSERT' statement for updating a table. Instead use 'UPDATE'.

UPDATE tableA SET tableA.profileID = tableB.profileID FROM tableB b
INNER JOIN TableA a ON a.userID = b.userID WHERE
a.profileID = '' OR a.profileID IS NULL;


问:
Issues with ng serve Angular 2
I have a problem with the installation of an existing angular application.

I'm trying to launch the application with the ng serve command, and this error is occurring:
The "@angular/compiler-cli" package was not properly installed. Error: reflect-metadata shim is required when using class decorators.

I've installed all the packages provided in the package.json file with the npm install command, I know they are a bit outdated, but they are still supposed to work.

These are all the dev dependencies:

```<code>"card"                             : "^1.2",
"del"                              : "latest",
"gulp"                             : "latest",
"gulp-autoprefixer"                : "latest",
"gulp-concat"                      : "latest",
"gulp-cssnano"                     : "2.x",
"gulp-eslint"                      : "latest",
"gulp-html5-lint"                  : "latest",
"gulp-htmlmin"                     : "2.x",
"gulp-imagemin"                    : "latest",
"gulp-inline-source"               : "latest",
"gulp-notify"                      : "latest",
"gulp-plumber"                     : "latest",
"gulp-rev-all"                     : "latest",
"gulp-sass"                        : "latest",
"gulp-scss-lint"                   : "latest",
"gulp-sourcemaps"                  : "2.0.0-alpha",
"gulp-svg-sprite"                  : "latest",
"gulp-tslint"                      : "4.x",
"gulp-typescript"                  : "2.x",
"gulp-uglify"                      : "latest",
"gulp-util"                        : "latest",
"merge-stream"                     : "latest",
"tslint"                           : "3.x",
"browser-sync"                     : "2.x",
"connect-history-api-fallback"     : "latest",
"typescript"                       : "1.x",
"typings"                          : "^0.8.1",
"svg4everybody"                    : "2.x",
"jquery"                           : "2.x",
"jasmine"                          : "2.x",
"semantic-ui"                      : "2.x",
"@angular/common"                  : "2.0.0-rc.1",
"@angular/compiler"                : "2.0.0-rc.1",
"@angular/compiler-cli"            : "^2.0.x",
"@angular/core"                    : "2.0.0-rc.1",
"@angular/http"                    : "2.0.0-rc.1",
"@angular/platform-browser"        : "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router"                  : "2.0.0-rc.1",
"@angular/router-deprecated"       : "2.0.0-rc.1",
"@angular/upgrade"                 : "2.0.0-rc.1",
"@angular/cli"                     : "1.4.8",
"systemjs"                         : "0.19.27",
"es6-shim"                         : "^0.35.0",
"reflect-metadata"                 : "^0.1.3",
"rxjs"                             : "5.0.0-beta.6",
"zone.js"                          : "^0.6.12",
"angular2-in-memory-web-api"       : "0.0.7"
</code>```

Anyone has an idea on how to resolve this? I'm struggling on this because I'm pretty new to Angular, any suggestion is accepted.

Thanks in advance.

答:
for enable angular cli commands, you must install it in global area of node by this command</p>

```<code>npm install -g angular-cli
</code>```

Title: Issues with ng serve Angular 2

Body:
I have a problem with the installation of an existing angular application.

I'm trying to launch the application with the ng serve command, and this error is occurring:
The "@angular/compiler-cli" package was not properly installed. Error: reflect-metadata shim is required when using class decorators.

I've installed all the packages provided in the package.json file with the npm install command, I know they are a bit outdated, but they are still supposed to work.

These are all the dev dependencies:

"card"                             : "^1.2",
"del"                              : "latest",
"gulp"                             : "latest",
"gulp-autoprefixer"                : "latest",
"gulp-concat"                      : "latest",
"gulp-cssnano"                     : "2.x",
"gulp-eslint"                      : "latest",
"gulp-html5-lint"                  : "latest",
"gulp-htmlmin"                     : "2.x",
"gulp-imagemin"                    : "latest",
"gulp-inline-source"               : "latest",
"gulp-notify"                      : "latest",
"gulp-plumber"                     : "latest",
"gulp-rev-all"                     : "latest",
"gulp-sass"                        : "latest",
"gulp-scss-lint"                   : "latest",
"gulp-sourcemaps"                  : "2.0.0-alpha",
"gulp-svg-sprite"                  : "latest",
"gulp-tslint"                      : "4.x",
"gulp-typescript"                  : "2.x",
"gulp-uglify"                      : "latest",
"gulp-util"                        : "latest",
"merge-stream"                     : "latest",
"tslint"                           : "3.x",
"browser-sync"                     : "2.x",
"connect-history-api-fallback"     : "latest",
"typescript"                       : "1.x",
"typings"                          : "^0.8.1",
"svg4everybody"                    : "2.x",
"jquery"                           : "2.x",
"jasmine"                          : "2.x",
"semantic-ui"                      : "2.x",
"@angular/common"                  : "2.0.0-rc.1",
"@angular/compiler"                : "2.0.0-rc.1",
"@angular/compiler-cli"            : "^2.0.x",
"@angular/core"                    : "2.0.0-rc.1",
"@angular/http"                    : "2.0.0-rc.1",
"@angular/platform-browser"        : "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router"                  : "2.0.0-rc.1",
"@angular/router-deprecated"       : "2.0.0-rc.1",
"@angular/upgrade"                 : "2.0.0-rc.1",
"@angular/cli"                     : "1.4.8",
"systemjs"                         : "0.19.27",
"es6-shim"                         : "^0.35.0",
"reflect-metadata"                 : "^0.1.3",
"rxjs"                             : "5.0.0-beta.6",
"zone.js"                          : "^0.6.12",
"angular2-in-memory-web-api"       : "0.0.7"

Anyone has an idea on how to resolve this? I'm struggling on this because I'm pretty new to Angular, any suggestion is accepted.

Thanks in advance.

Body:
for enable angular cli commands, you must install it in global area of node by this command

npm install -g angular-cli


问:
How to use filterM with an infinite list
I was trying to find a directory name by appending a number until I found a name that doesn't yet exist:

```<code>head <$> filterM (fmap not . fexists_) [ getDatedDir t d n | n <- [0..] ]
</code>```

The problem with this is that it never returns.  I think the problem is that although IO is a Functor, filterM has to do all the IO before the head effects; that is, it has to evaluate fexists for every n - and that's of course infinite.

Now, I can solve this:

```<code>go t d 0
where go t d n = do
    let dir = getDatedDir t d n
    fexists_ dir >>= \case
        False -> return dir
        True  -> go t d (n+1)
</code>```

But I feel that there ought to be a more elegant approach, using filterM or something similar.

This feels like a common enough pattern that there is probably an extisting function in Control.Monad, I'm just not seeing it.

答:
An equivalent without monads, would be find :: Foldable t => (a -> Bool) -> t a -> Maybe a. But I can not find a version to let it work with monads.

An idea might be to implement findM ourselves:

```<code>import Data.Bool(bool)

findM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)
findM f [] = return Nothing
findM f (x:xs) = f x >>= bool (findM f xs) (return (Just x))
</code>```

You can then use it like:

```<code>import System.Directory(doesFileExist)

main = do
    Just fln <- findM (not . doesDirectoryExist) (map (getDatedDir t d) [0..])
    putStrLn fln
</code>```

to print the first filename such that the file does not exists. Of course you can also process fln in a different way.

Body:
I was trying to find a directory name by appending a number until I found a name that doesn't yet exist:

head <$> filterM (fmap not . fexists_) [ getDatedDir t d n | n <- [0..] ]

The problem with this is that it never returns.  I think the problem is that although IO is a Functor, filterM has to do all the IO before the head effects; that is, it has to evaluate fexists for every n - and that's of course infinite.

Now, I can solve this:

go t d 0
where go t d n = do
    let dir = getDatedDir t d n
    fexists_ dir >>= \case
        False -> return dir
        True  -> go t d (n+1)

But I feel that there ought to be a more elegant approach, using filterM or something similar.

This feels like a common enough pattern that there is probably an extisting function in Control.Monad, I'm just not seeing it.

Body:
An equivalent without monads, would be find :: Foldable t => (a -> Bool) -> t a -> Maybe a. But I can not find a version to let it work with monads.

An idea might be to implement findM ourselves:

import Data.Bool(bool)

findM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)
findM f [] = return Nothing
findM f (x:xs) = f x >>= bool (findM f xs) (return (Just x))

You can then use it like:

import System.Directory(doesFileExist)

main = do
    Just fln <- findM (not . doesDirectoryExist) (map (getDatedDir t d) [0..])
    putStrLn fln

to print the first filename such that the file does not exists. Of course you can also process fln in a different way.


问:
What is the quickest way to extract 100 K images from an Oracle DB?
The options I am thinking of are:

1) C# Console Based App to extract images to the windows file system.

2) java app to extract images on the unix based file system.

Any other method that you can think of, please let me know. There are approximately 101,234 records and each BLOB column may have a file between 1 MB to 6 MB.

答:
If you want speed, I would recomend you to use a PL/SQL stored procedure to save the images to files directly. It should be quicker than an external program

```<code>DECLARE
t_blob BLOB;
t_len NUMBER;
t_file_name VARCHAR2(100);
t_output UTL_FILE.file_type;
t_TotalSize number;
t_position number := 1;
t_chucklen NUMBER := 4096;
t_chuck raw(4096);
t_remain number;
BEGIN
-- Get length of blob
SELECT DBMS_LOB.getlength (PHOTO), ename || '_1.jpg'
INTO t_TotalSize, t_file_name FROM DEMO WHERE ENAME ='moon';
t_remain := t_TotalSize;
-- The directory TEMPDIR should exist before executing
t_output := UTL_FILE.fopen ('TEMPDIR', t_file_name, 'wb', 32760);
-- Get BLOB
SELECT PHOTO INTO t_blob FROM DEMO WHERE ENAME ='moon';
-- Retrieving BLOB
WHILE t_position < t_TotalSize
LOOP
DBMS_LOB.READ (t_blob, t_chucklen, t_position, t_chuck);
UTL_FILE.put_raw (t_output, t_chuck);
UTL_FILE.fflush (t_output);
t_position := t_position + t_chucklen;
t_remain := t_remain - t_chucklen;
IF t_remain < 4096
THEN
t_chucklen := t_remain;
END IF;
END LOOP;
END;
</code>```

Check this Link

Body:
If you want speed, I would recomend you to use a PL/SQL stored procedure to save the images to files directly. It should be quicker than an external program

DECLARE
t_blob BLOB;
t_len NUMBER;
t_file_name VARCHAR2(100);
t_output UTL_FILE.file_type;
t_TotalSize number;
t_position number := 1;
t_chucklen NUMBER := 4096;
t_chuck raw(4096);
t_remain number;
BEGIN
-- Get length of blob
SELECT DBMS_LOB.getlength (PHOTO), ename || '_1.jpg'
INTO t_TotalSize, t_file_name FROM DEMO WHERE ENAME ='moon';
t_remain := t_TotalSize;
-- The directory TEMPDIR should exist before executing
t_output := UTL_FILE.fopen ('TEMPDIR', t_file_name, 'wb', 32760);
-- Get BLOB
SELECT PHOTO INTO t_blob FROM DEMO WHERE ENAME ='moon';
-- Retrieving BLOB
WHILE t_position < t_TotalSize
LOOP
DBMS_LOB.READ (t_blob, t_chucklen, t_position, t_chuck);
UTL_FILE.put_raw (t_output, t_chuck);
UTL_FILE.fflush (t_output);
t_position := t_position + t_chucklen;
t_remain := t_remain - t_chucklen;
IF t_remain < 4096
THEN
t_chucklen := t_remain;
END IF;
END LOOP;
END;

Check this Link


问:
Batch-renaming "complicated" files names
I am having a hard time with this issue.

I've got several files in a folder with the general name format:

[ file type ] file name ( date ) file specs . file extension

File type can be anything such as: Webinar, Presentation, Symposium, Oral Talk etc... Please notice that it is surrounded by [] and might include spaces.

File name can be anything, please notice it might include spaces.

Date is in the general format dd_mm_yyyy. Please notice that it is surrounded by ().

File specs gives general information about the file attributes (and is not important.

I want to write a script so I could rename all files inside the folder to the following format:

date [ file type ] file name . file extension

() around date should be discarded, the date should change for format ddmmyyyy, [] around file type should be maintained, and file specs should be ignored.

Example:

```<code>[Oral Talk] Prospects for future research (13_11_2017) 1080p 320kpbs.mp4
</code>```

should change to:

```<code>13112017 [Oral Talk] Prospects for future research.mp4
</code>```

But then, this should be iterated for all files in the folder.

答:
```<code>#!/usr/bin/env bash

# use a regular expression with match groups to pick out pieces of the name
re='\[(.+)\] (.+) [(]([[:digit:]_]+)[)](.*)[.]([[:alnum:]]+)'
#     1      2        3                4       5

# if we were passed a directory name, change to it before running
if [[ $1 ]]; then cd -- "$1" || exit; fi

for name in *.*; do
  if [[ $name =~ $re ]]; then
    date=${BASH_REMATCH[3]}
    ext=${BASH_REMATCH[5]}
    type=${BASH_REMATCH[1]}
    topic=${BASH_REMATCH[2]}
    new_name="${date//_/} [$type] $topic.$ext"
    printf 'Renaming %q to %q\n' "$name" "$new_name" >&2
    [[ $dry_run ]] || mv -- "$name" "$new_name"
  else
    printf 'Filename %q does not match pattern; ignoring\n' "$name" >&2
  fi
done
</code>```

If saved under the name renaming-script and run as:

```<code>dry_run=1 ./renaming-script directory-to-rename
</code>```

...this will merely print a report of which contents it would rename. With the dry_run=1 removed, it actually performs those rename operations.

Body:
I am having a hard time with this issue.

I've got several files in a folder with the general name format:

[ file type ] file name ( date ) file specs . file extension

File type can be anything such as: Webinar, Presentation, Symposium, Oral Talk etc... Please notice that it is surrounded by [] and might include spaces.

File name can be anything, please notice it might include spaces.

Date is in the general format dd_mm_yyyy. Please notice that it is surrounded by ().

File specs gives general information about the file attributes (and is not important.

I want to write a script so I could rename all files inside the folder to the following format:

date [ file type ] file name . file extension

() around date should be discarded, the date should change for format ddmmyyyy, [] around file type should be maintained, and file specs should be ignored.

Example:

[Oral Talk] Prospects for future research (13_11_2017) 1080p 320kpbs.mp4

should change to:

13112017 [Oral Talk] Prospects for future research.mp4

But then, this should be iterated for all files in the folder.

Body:
#!/usr/bin/env bash

# use a regular expression with match groups to pick out pieces of the name
re='\[(.+)\] (.+) [(]([[:digit:]_]+)[)](.*)[.]([[:alnum:]]+)'
#     1      2        3                4       5

# if we were passed a directory name, change to it before running
if [[ $1 ]]; then cd -- "$1" || exit; fi

for name in *.*; do
  if [[ $name =~ $re ]]; then
    date=${BASH_REMATCH[3]}
    ext=${BASH_REMATCH[5]}
    type=${BASH_REMATCH[1]}
    topic=${BASH_REMATCH[2]}
    new_name="${date//_/} [$type] $topic.$ext"
    printf 'Renaming %q to %q\n' "$name" "$new_name" >&2
    [[ $dry_run ]] || mv -- "$name" "$new_name"
  else
    printf 'Filename %q does not match pattern; ignoring\n' "$name" >&2
  fi
done

If saved under the name renaming-script and run as:

dry_run=1 ./renaming-script directory-to-rename

...this will merely print a report of which contents it would rename. With the dry_run=1 removed, it actually performs those rename operations.


问:
How can I align a specific flex item to the horizontal center of its parent?
I have a flex container with two items. I'd like the first item to be aligned to flex-start, and the second item to be aligned to the center of the flex container. My main concern is preserving align-items: center so that all the flex items are vertically centered regardless of their height, their width, or the height of their container.

.container {
  display: flex;
  height: 100px;
  background-color: tomato;
  align-items: center;
}

.box {
  height: 50px;
  width: 50px;
}

.a {
  width: 100px;
  background-color: green;
}

.b {
  background-color: purple;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box a"></div>
  <div class="box b"></div>
</div></code>```

How can I get the second box (the purple one in this example) to be perfectly centered?

答:
Whit this code, purple box is centered.

.container {
  display: flex;
  height: 100px;
  background-color: tomato;
  align-items: center;
}

.box {
  height: 50px;
  width: 50px;
}

.a {
  background-color: green;
}

.b {
  background-color: purple;
  /*add this*/
  position: relative;
  margin: 0 auto;
  left: -25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box a"></div>
  <div class="box b"></div>
</div></code>```

Body:
I have a flex container with two items. I'd like the first item to be aligned to flex-start, and the second item to be aligned to the center of the flex container. My main concern is preserving align-items: center so that all the flex items are vertically centered regardless of their height, their width, or the height of their container.

.container {
  display: flex;
  height: 100px;
  background-color: tomato;
  align-items: center;
}

.box {
  height: 50px;
  width: 50px;
}

.a {
  width: 100px;
  background-color: green;
}

.b {
  background-color: purple;
}

How can I get the second box (the purple one in this example) to be perfectly centered?

Body:
Whit this code, purple box is centered.

.container {
  display: flex;
  height: 100px;
  background-color: tomato;
  align-items: center;
}

.box {
  height: 50px;
  width: 50px;
}

.a {
  background-color: green;
}

.b {
  background-color: purple;
  /*add this*/
  position: relative;
  margin: 0 auto;
  left: -25px;
}

<div class="container">
  <div class="box a"></div>
  <div class="box b"></div>
</div>


问:
How do I create a layout that can contain buttons in PyQt5?
I am trying to create a window that has a banner with two buttons underneath. I would like the layout to be like this:

Where I could put buttons in the green and blue boxes and an image in the red box. How would you go about doing something like this?

答:
```<code>    self.verticalLayoutWidget = QtWidgets.QWidget(borreme)
    self.verticalLayoutWidget.setGeometry(QtCore.QRect(19, 30, 351, 111))
    self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
    self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
    self.verticalLayout.setObjectName("verticalLayout")
    self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
    self.label.setObjectName("label")
    self.verticalLayout.addWidget(self.label)
    self.horizontalLayout = QtWidgets.QHBoxLayout()
    self.horizontalLayout.setObjectName("horizontalLayout")
    self.pushButton_2 = QtWidgets.QPushButton(self.verticalLayoutWidget)
    self.pushButton_2.setObjectName("pushButton_2")
    self.horizontalLayout.addWidget(self.pushButton_2)
    self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
    self.pushButton.setObjectName("pushButton")
    self.horizontalLayout.addWidget(self.pushButton)
    self.verticalLayout.addLayout(self.horizontalLayout)
</code>```

<p>done by using qtdesigner and this </p>

```<code>     pyuic5 borreme.ui -o borrreme.py
</code>```

Body:
    self.verticalLayoutWidget = QtWidgets.QWidget(borreme)
    self.verticalLayoutWidget.setGeometry(QtCore.QRect(19, 30, 351, 111))
    self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
    self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
    self.verticalLayout.setObjectName("verticalLayout")
    self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
    self.label.setObjectName("label")
    self.verticalLayout.addWidget(self.label)
    self.horizontalLayout = QtWidgets.QHBoxLayout()
    self.horizontalLayout.setObjectName("horizontalLayout")
    self.pushButton_2 = QtWidgets.QPushButton(self.verticalLayoutWidget)
    self.pushButton_2.setObjectName("pushButton_2")
    self.horizontalLayout.addWidget(self.pushButton_2)
    self.pushButton = QtWidgets.QPushButton(self.verticalLayoutWidget)
    self.pushButton.setObjectName("pushButton")
    self.horizontalLayout.addWidget(self.pushButton)
    self.verticalLayout.addLayout(self.horizontalLayout)

done by using qtdesigner and this

     pyuic5 borreme.ui -o borrreme.py


问:
Show another div when image is hovered over
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>

  <div class="castcontainer">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div class="castcontainer">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article></code>```

答:
Let me offer a more radical departure from your current code:

.cast * {
 box-sizing: border-box;
}

.cast {
 border-radius: 10px;
 background: #8b2323;
 font-family: Verdana, sans-serif;
 text-align: center;
 padding: 12px;
}

.cast img {
 border-radius: 50%;
 max-height: 300px;
}

.cast strong {
 background: white;
 display: block;
 border-radius: 10px;
 margin-top: 5px;
}

.cast .actor,
.cast .role {
 width: 100%;
}

.cast .actor {
 display: block;
 z-index: 2;
}

.cast .role {
 display: none;
 z-index: 1;
}

.cast:hover .actor {
 display: none;
}

.cast:hover .role {
 display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article class="cast">
 <div class="actor">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg">
      <strong>Ryan Reynalds</strong>
 </div>

 <div class="role">
  <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg">
  <strong>Wade Wilson</strong>
 </div>
</article></code>```

This reduces the number of child elements and (in my opinion) makes selecting which element to show/hide that much easier.  You're targeting the :hover event of the parent wrapper and instead of trying to use an ID (which cannot be reused) you're targeting .actor and .role.

One concern would be to make sure that the images for each were the same dimension, otherwise on change you could get some transition that was unappealing if the box had to resize.

Body:
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}

Ryan Reynalds

Wade Wilson

Body:
Let me offer a more radical departure from your current code:

.cast * {
 box-sizing: border-box;
}

.cast {
 border-radius: 10px;
 background: #8b2323;
 font-family: Verdana, sans-serif;
 text-align: center;
 padding: 12px;
}

.cast img {
 border-radius: 50%;
 max-height: 300px;
}

.cast strong {
 background: white;
 display: block;
 border-radius: 10px;
 margin-top: 5px;
}

.cast .actor,
.cast .role {
 width: 100%;
}

.cast .actor {
 display: block;
 z-index: 2;
}

.cast .role {
 display: none;
 z-index: 1;
}

.cast:hover .actor {
 display: none;
}

.cast:hover .role {
 display: block;
}

<article class="cast">
 <div class="actor">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg">
      <strong>Ryan Reynalds</strong>
 </div>

 <div class="role">
  <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg">
  <strong>Wade Wilson</strong>
 </div>
</article>

This reduces the number of child elements and (in my opinion) makes selecting which element to show/hide that much easier.  You're targeting the :hover event of the parent wrapper and instead of trying to use an ID (which cannot be reused) you're targeting .actor and .role.

One concern would be to make sure that the images for each were the same dimension, otherwise on change you could get some transition that was unappealing if the box had to resize.


问:
How do I get the size of objects in a bucket based on storage class
I have a bucket with objects in standard,IA and Glacier. Is there a way I can get the size of total objects in each storage type? Right now I generate a report every day with total size of the bucket and amount of data added the previous data. I would like to further split it based on the storage class.</p>

答:
You can use the Inventory option under Management tab to generate detailed inventory of current/all version of objects with details such as Size, Storage Class, replication and expiration status etc.
Snapshot


问:
Use RegExp in Awk
I have CSV file:

```<code><iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

```<code>44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

I have worked RegExp in Grep

```<code>$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda
</code>```

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

```<code>$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5
</code>```

Just Awk work fine:

```<code>$ awk -F "|" '{print $1"|"$2}' example.txt
<iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

Title: Use RegExp in Awk

Body:
I have CSV file:

|name_1
|name_2
|name_3
|name_4
|name_5

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5

I have worked RegExp in Grep

$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5

Just Awk work fine:

$ awk -F "|" '{print $1"|"$2}' example.txt
|name_1
|name_2
|name_3
|name_4
|name_5

Body:
awk '{gsub(/<.*get\//,"")gsub(/".*e>/,"")}1'  file

44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5


问:
How to add objects to a pointer
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

```<code>int *ptr;
ptr = new int;
</code>```

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

答:
A vector keeps track of two bits of information.

It's size, which is the number of elements it's currently holding.

It's capacity, or how many elements it can actually contain before running out of memory.

If adding an element does not cause it to exceed its capacity, then there is no problem. It simply adds the new element.

If the capacity will be exceeded, then it will calculate a new capacity (usually between 1.5 and 2 times the current capacity) and copy all elements to the new array. This is why iterators are invalidated after adding an item to a vector. They may be referring to the old (now freed) array.

ContentLicense: CC BY-SA 4.0

Title: How to add objects to a pointer

Body:
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

int *ptr;
ptr = new int;

How after using that, can you add more objects to that pointer? (make it an array). Thanks!


问:
Azure AD App Registration - Exchange API - Read Calendar
I have the following permissions granted in my Azure AD App:

App:

```<code>Read calendars in all mailboxes
Read and write calendars in all mailboxes
Read calendars in all mailboxes
</code>```

Delegated:

```<code>Read user and shared calendars
Read and write user and shared calendars
Read and write user calendars
Read user calendars
Read and write user and shared calendars
Read user and shared calendars
</code>```

Registration Screen Shot

I am successfully generating an Access Token like the following:

const string clientId = "my-client-id";
const string clientSecret = "my-secret"; // C
var tenant = "mytenant.onmicrosoft.com";

var authContext = new AuthenticationContext($"https://login.windows.net/{tenant}/oauth2/token");
var credentials = new ClientCredential(clientId, clientSecret);

AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
```

<p>With that Access Token, I am trying to make  a basic request to <code>/CalendarView</code> passing the Bearer token header:</p>

```https://outlook.office.com/api/v2.0/users/my@email.com/calendarview?startDateTime=2017-11-12&endDateTime=2017-11-13
```

However, I keep receiving Access Denied. Are there additional permissions I need to set? Am I calling into the correct endpoint?

答: You don't include the body of the error response, but my guess is that you're hitting this because Exchange won't accept a token generated with a shared secret. Instead, you need to use a certificate-based assertion to request the token. Azure documents this a "Second case: Access token request with a certificate" here.</p>

Body:
I have the following permissions granted in my Azure AD App:

App:

Read calendars in all mailboxes
Read and write calendars in all mailboxes
Read calendars in all mailboxes

Delegated:

Read user and shared calendars
Read and write user and shared calendars
Read and write user calendars
Read user calendars
Read and write user and shared calendars
Read user and shared calendars

Registration Screen Shot

I am successfully generating an Access Token like the following:

const string clientId = "my-client-id";
const string clientSecret = "my-secret"; // C
var tenant = "mytenant.onmicrosoft.com";

var authContext = new AuthenticationContext($"https://login.windows.net/{tenant}/oauth2/token");
var credentials = new ClientCredential(clientId, clientSecret);

AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);

With that Access Token, I am trying to make  a basic request to /CalendarView passing the Bearer token header:

https://outlook.office.com/api/v2.0/users/my@email.com/calendarview?startDateTime=2017-11-12&endDateTime=2017-11-13

However, I keep receiving Access Denied. Are there additional permissions I need to set? Am I calling into the correct endpoint?


问:
SpeechToTextV1 - Missing required modules SSCZLib, SSCommonCrypto
I am working on XCode 9.1 project that uses IBM Watson swift-sdk SpeechToTextV1 package. After upgrading swift-sdk to the version 0.19.0 and building XCode project the compiler error has occured: Missing required modules: 'SSCZLib', 'SSCommonCrypto' pointing to the import SpeechToTextV1 statement. swift-sdk updated via Carthage.
Cartfile content: github "watson-developer-cloud/swift-sdk".
command line update: carthage update --platform ios --no-use-binaries.

How can I include SSCZLib and SSCommonCrypto modules into XCode project?

Please help. Thanks a lot.

答:
I'm afraid that I haven't been able to replicate the problem on my machine. I started with a new, empty Xcode project and was able to transcribe audio with the Speech to Text service.

I uploaded my app here. Can you try downloading it, adding your Speech to Text credentials, and running the app?


问:
Add concatenated column to temp table when I don't have ADD permission
I do not have ADD or DELETE or ALTER permission in my instance of SQL Server.  I have a temp table in which I want to add a column to.

This new column is a concatenation of other columns and I want to write it to another temp table.

Right now, when I employ the CONCAT code below, the output is just that one column.  I want to have the CONCAT column along with all the other columns in my original temp table (#df_ERA4_b).

```<code>SELECT CONCAT(A, OP, F, SUB, AIR, D, REQ, P) as CONCAT_COL
INTO #df_ERA4_c
FROM #df_ERA4_b
</code>```

How can I achieve this?

答:
Add a * to include all other rows, or list them explicitly.</p>

```<code>SELECT
    *,
    CONCAT(A, OP, F, SUB, AIR, D, REQ, P) as CONCAT_COL
INTO #df_ERA4_c
FROM #df_ERA4_b
</code>```

Body:
I do not have ADD or DELETE or ALTER permission in my instance of SQL Server.  I have a temp table in which I want to add a column to.

This new column is a concatenation of other columns and I want to write it to another temp table.

Right now, when I employ the CONCAT code below, the output is just that one column.  I want to have the CONCAT column along with all the other columns in my original temp table (#df_ERA4_b).

SELECT CONCAT(A, OP, F, SUB, AIR, D, REQ, P) as CONCAT_COL
INTO #df_ERA4_c
FROM #df_ERA4_b

How can I achieve this?

Body:
Add a * to include all other rows, or list them explicitly.

SELECT
    *,
    CONCAT(A, OP, F, SUB, AIR, D, REQ, P) as CONCAT_COL
INTO #df_ERA4_c
FROM #df_ERA4_b


问:
Issues using regex to match either (forward slash[/]) or (hyphen[-]) characters in data validation for data-processing program
I have researched fairly extensively (I've looked at 5 or 6 stackoverflow posts that have often lead me to stare at the official Java regex resource for 30 minutes at a time) but I'm still struggling with this issue. Here is my code for the String matching method:

```<code>        public String checkDateFormat(String date)
        {
            if (date.matches("[0-3][0-9](?:-|/)[0-1][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-1][0-9](?:-|/)[0-3][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-1][0-9](?:-|/)[0-3][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-3][0-9](?:-|/)[0-1][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else
            {
                throw new InvalidParameterException("(The passed argument is invalid date format: [yyyy/dd/MM, yyyy/MM/dd, MM/dd/yyyy, or dd/MM/yyyy])");
            }
        }
</code>```

The current setup for checking the - and / conditions is one of many I've tried; I've also attempted these: [-/] [-\\\\/] [-&&[/]] [-[/]] and probably a few more I don't remember.

The program simply needs to be able to accept - and / as different separators in the dd/MM/yyyy format as I'm reading this info from multiple csv files that contain the format both as dd/MM/yyyy and dd-MM-yyyy.

EDIT: I've updated my code to this for the time being, but I still fail to pass the data through this validation method. To be more specific about the problem, the specific string I'm checking is 2016-01-01. I've also tried using the code Ole V.V. provided using the DateTimeFormatter class, but to no success.

Body:
I have researched fairly extensively (I've looked at 5 or 6 stackoverflow posts that have often lead me to stare at the official Java regex resource for 30 minutes at a time) but I'm still struggling with this issue. Here is my code for the String matching method:

        public String checkDateFormat(String date)
        {
            if (date.matches("[0-3][0-9](?:-|/)[0-1][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-1][0-9](?:-|/)[0-3][0-9](?:-|/)[0-2][0-9][0-9][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-1][0-9](?:-|/)[0-3][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else if (date.matches("[0-2][0-9][0-9][0-9](?:-|/)[0-3][0-9](?:-|/)[0-1][0-9] [0-2][0-9]:[0-6][0-9]:[0-6][0-9]"))
            {
                return date;
            }
            else
            {
                throw new InvalidParameterException("(The passed argument is invalid date format: [yyyy/dd/MM, yyyy/MM/dd, MM/dd/yyyy, or dd/MM/yyyy])");
            }
        }

The current setup for checking the - and / conditions is one of many I've tried; I've also attempted these: [-/] [-\\\\/] [-&&[/]] [-[/]] and probably a few more I don't remember.

The program simply needs to be able to accept - and / as different separators in the dd/MM/yyyy format as I'm reading this info from multiple csv files that contain the format both as dd/MM/yyyy and dd-MM-yyyy.

EDIT: I've updated my code to this for the time being, but I still fail to pass the data through this validation method. To be more specific about the problem, the specific string I'm checking is 2016-01-01. I've also tried using the code Ole V.V. provided using the DateTimeFormatter class, but to no success.

Body:
Brief

As per my comment, I would recommend you do not use regex for this as this will be extremely long, convoluted and will not be easy to debug. See how to get the given date string format pattern in Java or Ole V.V.'s answer on this post to do this without regex.

On the other hand, and just to show you how massive and unmanageable this regex would actually be if it included all necessary components, I've adapted my own regex to create a regex that works in Java and does what you want.

This regex not only matches the given date formats, but also ensures the correct days are given for each month and year. That means this regex ensures February only has 28 days unless it's a leap year (in which case it will have 29). This also means it ensures proper days/month (i.e. January has 31, March has 31, April has 30, etc.).

Code

The code below is a working regex that should work in most regex languages. This will not work in languages where backreferencing is not possible.

See regex in use here

^(?:
(?:0[1-9]|1\d|2[0-8])([\/-])(?:02)\1(?:\d+)|
(?:0[1-9]|1\d|2\d)([\/-])(?:02)\2(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))|
(?:0[1-9]|1\d|2\d|30)([\/-])(?:0[469]|11)\3(?:\d+)|
(?:0[1-9]|1\d|2\d|3[01])([\/-])(?:0[13578]|1[02])\4(?:\d+)|
(?:02)([\/-])(?:0[1-9]|1\d|2[0-8])\5(?:\d+)|
(?:02)([\/-])(?:0[1-9]|1\d|2\d)\6(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))|
(?:0[469]|11)([\/-])(?:0[1-9]|1\d|2\d|30)\7(?:\d+)|
(?:0[13578]|1[02])([\/-])(?:0[1-9]|1\d|2\d|3[01])\8(?:\d+)|
(?:\d+)([\/-])(?:0[1-9]|1\d|2[0-8])\9(?:02)|
(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))([\/-])(?:0[1-9]|1\d|2\d)\10(?:02)|
(?:\d+)([\/-])(?:0[1-9]|1\d|2\d|30)\11(?:0[469]|11)|
(?:\d+)([\/-])(?:0[1-9]|1\d|2\d|3[01])\12(?:0[13578]|1[02])|
(?:\d+)([\/-])(?:02)\13(?:0[1-9]|1\d|2[0-8])|
(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))([\/-])(?:02)\14(?:0[1-9]|1\d|2\d)|
(?:\d+)([\/-])\15(?:0[469]|11)(?:0[1-9]|1\d|2\d|30)|
(?:\d+)([\/-])(?:0[13578]|1[02])\16(?:0[1-9]|1\d|2\d|3[01])
)$

Note: The regex above uses the x (ignore whitespace) flag. This is used to keep the regex somewhat legible. If you really want a one-liner, you can use the following:

See regex in use here

^(?:(?:0[1-9]|1\d|2[0-8])([\/-])(?:02)\1(?:\d+)|(?:0[1-9]|1\d|2\d)([\/-])(?:02)\2(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))|(?:0[1-9]|1\d|2\d|30)([\/-])(?:0[469]|11)\3(?:\d+)|(?:0[1-9]|1\d|2\d|3[01])([\/-])(?:0[13578]|1[02])\4(?:\d+)|(?:02)([\/-])(?:0[1-9]|1\d|2[0-8])\5(?:\d+)|(?:02)([\/-])(?:0[1-9]|1\d|2\d)\6(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))|(?:0[469]|11)([\/-])(?:0[1-9]|1\d|2\d|30)\7(?:\d+)|(?:0[13578]|1[02])([\/-])(?:0[1-9]|1\d|2\d|3[01])\8(?:\d+)|(?:\d+)([\/-])(?:0[1-9]|1\d|2[0-8])\9(?:02)|(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))([\/-])(?:0[1-9]|1\d|2\d)\10(?:02)|(?:\d+)([\/-])(?:0[1-9]|1\d|2\d|30)\11(?:0[469]|11)|(?:\d+)([\/-])(?:0[1-9]|1\d|2\d|3[01])\12(?:0[13578]|1[02])|(?:\d+)([\/-])(?:02)\13(?:0[1-9]|1\d|2[0-8])|(?:(?:\d*?(?:(?:0[48]|[13579][26]|[2468][048])|(?:(?:[02468][048]|[13579][26])00))|[48]00|[48])(?=\D|\b))([\/-])(?:02)\14(?:0[1-9]|1\d|2\d)|(?:\d+)([\/-])\15(?:0[469]|11)(?:0[1-9]|1\d|2\d|30)|(?:\d+)([\/-])(?:0[13578]|1[02])\16(?:0[1-9]|1\d|2\d|3[01]))$

Results

** VALID **
30/11/2017
30-11-2017
2017-05-31

** INVALID **
30-/11-/2017
30-11/2017

Explanation

I will not provide a full explanation of the entire regex here as that would literally be absurd. Instead, I'll provide you with a link to the original regex so that you can look at it and decode it using the original.

Each option's non-capturing group represents either a day, month or year. Each capture group represents a delimiter. Assuming a delimiter match; the backreference ensures the second delimiter is the same as the first.


问:
Errors concerning return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object
I am a beginner at Python, and when I try to execute this command on CMD, I was faced with this error. Please advise:

Code:

```<code>import re
handle=open('regex_sum_41718.txt')
for line in handle:
    word=line.split()
    print(type(word))
    y=re.findall('[0-9]+',word)
print(y)
</code>```

Error:

```<code>Traceback (most recent call last):
    File "Assi_1.py", line 5, in <module>
        y=re.findall('[0-9]+', word)
    File "D:\Python\lib\re.py", line 222, in findall
        return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
</code>```

Thanks a lot.

答:
You need to put another loop around line.split():

```<code>for line in handle:
    for word in line.split():
        print(type(word))
        y=re.findall('[0-9]+',word)
</code>```

Otherwise word is a list and only strings can be searched.

Body:
I am a beginner at Python, and when I try to execute this command on CMD, I was faced with this error. Please advise:

Code:

import re
handle=open('regex_sum_41718.txt')
for line in handle:
    word=line.split()
    print(type(word))
    y=re.findall('[0-9]+',word)
print(y)

Error:

Traceback (most recent call last):
    File "Assi_1.py", line 5, in <module>
        y=re.findall('[0-9]+', word)
    File "D:\Python\lib\re.py", line 222, in findall
        return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

Thanks a lot.

Body:
You need to put another loop around line.split():

for line in handle:
    for word in line.split():
        print(type(word))
        y=re.findall('[0-9]+',word)

Otherwise word is a list and only strings can be searched.


问:
Bad FPS in a simple Three.js scene in Safari MacOS
I have a simple demo that works fine in Chrome and Firefox. But Safari is lag like hell. If I disable antialising, it increases the FPS but not that much. How can i optimize my code ? Maybe use some caching? I'm new to three.js

It will be nice if it will work in iOs safari too.

Here's the demo:

var $container = $('#torus');
var mouseX = 0,
  mouseY = 0;

var camera, scene, renderer;
var geometry, material, mesh, config;
var numTorus = 65;
var tabTorus = [];
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

config = {
  speed: 1.3,
  rotation: 1,
  opacity: 1
}

function init() {

  camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 10, 1000);
  camera.position.z = 1;
  scene = new THREE.Scene();
  material = new THREE.MeshNormalMaterial();
  material.transparent = true;
  material.opacity = config.opacity;
  geometry = new THREE.TorusGeometry(130, .5, 120, 100);
  geometry.computeFaceNormals();
  geometry.computeVertexNormals();
  geometry.normalsNeedUpdate = true;
  geometry.verticesNeedUpdate = true;
  geometry.dynamic = true;

  for (var i = 0; i < numTorus; i++) {
    tabTorus.push(new Torus(-i * 6));
    scene.add(tabTorus[i].b);
  }

  renderer = new THREE.WebGLRenderer({
    antialias: true,
    autoClear: true,
    alpha: true,
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  $container.append(renderer.domElement);

}

function Torus(f) {

  this.b = new THREE.Mesh(geometry, material);
  this.b.position.y = 55 * Math.sin(f);
  this.b.position.x = 55 * Math.cos(f);
  this.b.position.z = f * 2.72;
}

function onWindowResize() {

  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}

function onDocumentMouseMove(event) {
  mouseX = (event.clientX - windowHalfX) / 10;
  mouseY = (event.clientY - windowHalfY) / 10;
}

function update() {
  for (var i = 0; i < numTorus; i++) {
    tabTorus[i].b.position.z += config.speed * 1.5;
    tabTorus[i].b.material.opacity = config.opacity;
    tabTorus[i].b.geometry.parameters.arc = 0.5 + config.opacity * 10;
    if (tabTorus[i].b.position.z > 0) {
      tabTorus[i].b.position.z = -1000;
    }
  }
}

function animate() {
  requestAnimationFrame(animate);
  camera.position.x += (mouseX - camera.position.x) * .02;
  camera.position.y += (-mouseY - camera.position.y) * .02;
  renderer.render(scene, camera);
  update();
}

window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);

init();
animate();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: black;
}

#torus {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}</code>```

```

答: It seems to be a problem in Safari itself: enormous amounts of time spent compositing the page (40-50ms on my machine vs 2-4 ms for JavaScript). Also, it depends on size of the window. You should report it to https://bugs.webkit.org.</p>

Body:
I have a simple demo that works fine in Chrome and Firefox. But Safari is lag like hell. If I disable antialising, it increases the FPS but not that much. How can i optimize my code ? Maybe use some caching? I'm new to three.js

It will be nice if it will work in iOs safari too.

Here's the demo:

var $container = $('#torus');
var mouseX = 0,
  mouseY = 0;

var camera, scene, renderer;
var geometry, material, mesh, config;
var numTorus = 65;
var tabTorus = [];
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

config = {
  speed: 1.3,
  rotation: 1,
  opacity: 1
}

function init() {

  camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 10, 1000);
  camera.position.z = 1;
  scene = new THREE.Scene();
  material = new THREE.MeshNormalMaterial();
  material.transparent = true;
  material.opacity = config.opacity;
  geometry = new THREE.TorusGeometry(130, .5, 120, 100);
  geometry.computeFaceNormals();
  geometry.computeVertexNormals();
  geometry.normalsNeedUpdate = true;
  geometry.verticesNeedUpdate = true;
  geometry.dynamic = true;

  for (var i = 0; i < numTorus; i++) {
    tabTorus.push(new Torus(-i * 6));
    scene.add(tabTorus[i].b);
  }

  renderer = new THREE.WebGLRenderer({
    antialias: true,
    autoClear: true,
    alpha: true,
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  $container.append(renderer.domElement);

}

function Torus(f) {

  this.b = new THREE.Mesh(geometry, material);
  this.b.position.y = 55 * Math.sin(f);
  this.b.position.x = 55 * Math.cos(f);
  this.b.position.z = f * 2.72;
}

function onWindowResize() {

  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}

function onDocumentMouseMove(event) {
  mouseX = (event.clientX - windowHalfX) / 10;
  mouseY = (event.clientY - windowHalfY) / 10;
}

function update() {
  for (var i = 0; i < numTorus; i++) {
    tabTorus[i].b.position.z += config.speed * 1.5;
    tabTorus[i].b.material.opacity = config.opacity;
    tabTorus[i].b.geometry.parameters.arc = 0.5 + config.opacity * 10;
    if (tabTorus[i].b.position.z > 0) {
      tabTorus[i].b.position.z = -1000;
    }
  }
}

function animate() {
  requestAnimationFrame(animate);
  camera.position.x += (mouseX - camera.position.x) * .02;
  camera.position.y += (-mouseY - camera.position.y) * .02;
  renderer.render(scene, camera);
  update();
}

window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);

init();
animate();

body {
  background: black;
}

#torus {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}


问:
Unity and C# click/touch over specific UI element check
I have a code where if I start click or touch the screen and drag for specific distance does something. I would like to check whenever it is over a specific area (lets say over UI like canvas). The main goal is to have the upper half of the screen to react on click and touch.

I tried to do so by creating new Rect. This works, but I can`t make the rect on upper part of the screen (right now it is on the lower part of the screen). I might be missing something, but the following code should create rect in the upper part of the screen, not ?

```<code>if (Input.GetMouseButtonDown(0))
    {
        Rect bounds = new Rect(0, 0, Screen.height / 2, Screen.width);
        if (Input.GetMouseButtonDown(0) && bounds.Contains(Input.mousePosition))
        {
            Debug.Log("Touchableee!");
            TouchableArea = true;
        }

        if (TouchableArea == true)
        {
            tap = true;
            isDraging = true;
            startTouch = Input.mousePosition;
            TouchableArea = false;
        }

    }
    else if (Input.GetMouseButtonUp(0))
    {
        isDraging = false;
        Reset();
    }
</code>```

Any ideas are welcome, thank you...

答:
You're starting the Rect at the bottom of the screen, thus why it's on the bottom half.

Parameters

x The X value the rect is measured from.

y The Y value the rect is measured from.

width The width of the rectangle.

height    The height of the rectangle.

The following should work for you:

```<code>Rect bounds = new Rect(0, Screen.height, Screen.height / 2, Screen.width);
</code>```

Body:
I have a code where if I start click or touch the screen and drag for specific distance does something. I would like to check whenever it is over a specific area (lets say over UI like canvas). The main goal is to have the upper half of the screen to react on click and touch.

I tried to do so by creating new Rect. This works, but I can`t make the rect on upper part of the screen (right now it is on the lower part of the screen). I might be missing something, but the following code should create rect in the upper part of the screen, not ?

if (Input.GetMouseButtonDown(0))
    {
        Rect bounds = new Rect(0, 0, Screen.height / 2, Screen.width);
        if (Input.GetMouseButtonDown(0) && bounds.Contains(Input.mousePosition))
        {
            Debug.Log("Touchableee!");
            TouchableArea = true;
        }

        if (TouchableArea == true)
        {
            tap = true;
            isDraging = true;
            startTouch = Input.mousePosition;
            TouchableArea = false;
        }

    }
    else if (Input.GetMouseButtonUp(0))
    {
        isDraging = false;
        Reset();
    }

Any ideas are welcome, thank you...

Body:
You're starting the Rect at the bottom of the screen, thus why it's on the bottom half.

Parameters

x The X value the rect is measured from.

y The Y value the rect is measured from.

width The width of the rectangle.

height    The height of the rectangle.

The following should work for you:

Rect bounds = new Rect(0, Screen.height, Screen.height / 2, Screen.width);


问:
Android - How to properly get a variable from a parent activity from a fragment
I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.

if have an interface like this in my fragment

public interface InteractWithFragmentA {
    String getStringText();
}

In my calling activity I tested it out with a dummy text

```<code>@Override
public String getStringText(){ return "Some dummy text";}
</code>```

I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using

_hostActivity.getStringText()

the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.

答:
Try this from fragment</p>

```<code>((YourActivity) getActivity()).getStringText();
</code>```

Body:
I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.

if have an interface like this in my fragment

public interface InteractWithFragmentA {
    String getStringText();
}

In my calling activity I tested it out with a dummy text

@Override
public String getStringText(){ return "Some dummy text";}

I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using

_hostActivity.getStringText()

the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.

Body:
Try this from fragment

((YourActivity) getActivity()).getStringText();


问:
glsl arithmetic operator
Why does this line:

```<code>float x = 1 - gl_Color.x;
</code>```

give:

```<code>(26): error: Could not implicitly convert operands to arithmetic operator
</code>```

答:
GLSL (prior to #version 120) does not allow implicit conversions between integer and floating point.  1 is an integer and gl_Color.x is a float, so you get an error.  You need

```<code>float x = 1.0 - gl_Color.x;
</code>```

instead

Title: glsl arithmetic operator

Body:
Why does this line:

float x = 1 - gl_Color.x;

give:

(26): error: Could not implicitly convert operands to arithmetic operator

Body:
GLSL (prior to #version 120) does not allow implicit conversions between integer and floating point.  1 is an integer and gl_Color.x is a float, so you get an error.  You need

float x = 1.0 - gl_Color.x;

instead


问:
Referenced AudioKit framework is not recognized by XCode
When I create a new XCode project that references (as opposed to CocoaPods, etc) one of the AudioKit frameworks, XCode does not autocomplete AudioKit declarations and explicitly declaring an AudioKit object (such as AKMIDISampler) results in a build error:  'AKMIDISampler' is unavailable: cannot find Swift declaration for this class.

Typically the problem lies in correctly inputting the framework search paths in XCode.  However, even though I put in a relative path to the framework for both my target and my project, I still get the same results.

It's likely that this is an issue with all 3rd party frameworks, but I am asking it here in reference to AudioKit as I have seen this question come up before in the AudioKit Support group on Google.

What is the best practice in setting up a new project to use AudioKit so that AudioKit is recognized and autocomplete work?

答:
I've worked out the solution and am posting it here for future reference.

Here is a step by step to get setup with AudioKit.

Two things to note:

This solution was posted using XCode 9.1.

The AudioKit frameworks used in this solution are the pre-built binaries downloaded from http://audiokit.io/downloads/.  I have placed these in a Libraries folder 2 folders up from where I keep my projects.

Steps:

Create a new project in XCode

Select the appropriate target and under Embedded Binaries, select the '+'.  Choose 'Add Other...' and navigate to the correct AudioKit framework.  I leave 'Copy Items' unchecked so that I can update the framework in one location on my hard drive when it changes.  I also select 'Create groups' instead of folder references, but I'm not sure that plays into the solution.

Select Build Settings and go to the Framework Search Paths.  For the target, put $(inherited) for your search path.  For the project, put $(SRCROOT)/.  For me this looks like $(SRCROOT)/../../_Libraries/AudioKit-iOS

Now you can import AudioKit and declarations should resolve.

Step 3 above is typically the point most get incorrect.  Many expect SRCROOT to be implied and expect that just putting in a relative path is sufficient, but it is not.  SRCROOT must be specified.


问:
How to filter by an optional relationship parameter in cypher?
There are organizations and applications within the software system. User actions generate log records. Log records (green) do belong to organizations (red) and may belong to applications (pink).

There is a need to filter log records by a various set of parameters (creation time, author, organization etc). Let's filter log records by the application they belong to and enlist all log records in the system if this parameter is not specified. To do this I created the following query:

```<code>MATCH
(log0:Log)-[:GENERATED_IN]->(org:Organization),
(a1:Application)<-[:GENERATED_IN]-(log1:Log)
WHERE ID(a)=coalesce({applicationID}, ID(a))
RETURN DISTINCT
CASE {applicationID}
    WHEN null THEN log0
    ELSE log1
END
as result
</code>```

Because the parameter is optional, I need to handle the situation when it is not specified. I decided to use  ID(a)=coalesce({applicationID}, ID(a)) for this case, what will be equal to ID(a)=ID(a) in case the applicationID param is not specified (so we just don't filter by this parameter, what I was going to actually achieve).

I wonder if there is more elegant way to do this filtering by optional relationship. I tried

```<code>MATCH
(a:Application)<-[:GENERATED_IN*0..1]-(log:Log)-[:GENERATED_IN]->(org:Organization)
WHERE ID(a)=coalesce({applicationID}, ID(a))
RETURN
log
</code>```

And also tried queries with OPTIONAL MATCH, but without success. I would appreciate suggestions for improvement.

And BTW, is there a way to specify parameters like {applicationID} from the neo4j browser console? Like <query>, {applicationID}=202175. I substitute values manually every time.

答:
Instead of coalesce, you could use IS NULL and check if the parameter was provided:

```<code>MATCH
  (log0:Log)-[:GENERATED_IN]->(org:Organization),
  (a1:Application)<-[:GENERATED_IN]-(log1:Log)
WHERE {applicationID} IS NULL
   OR ID(a1)={applicationID}
RETURN DISTINCT
  CASE {applicationID}
    WHEN null THEN log0
    ELSE log1
  END
  AS result
</code>```

If using Neo4j 3.2+, I'd also consider switching to the new parameter syntax, $param instead of {param}, which makes the queries slightly easier to read.

Body:
There are organizations and applications within the software system. User actions generate log records. Log records (green) do belong to organizations (red) and may belong to applications (pink).

There is a need to filter log records by a various set of parameters (creation time, author, organization etc). Let's filter log records by the application they belong to and enlist all log records in the system if this parameter is not specified. To do this I created the following query:

MATCH
(log0:Log)-[:GENERATED_IN]->(org:Organization),
(a1:Application)<-[:GENERATED_IN]-(log1:Log)
WHERE ID(a)=coalesce({applicationID}, ID(a))
RETURN DISTINCT
CASE {applicationID}
    WHEN null THEN log0
    ELSE log1
END
as result

Because the parameter is optional, I need to handle the situation when it is not specified. I decided to use  ID(a)=coalesce({applicationID}, ID(a)) for this case, what will be equal to ID(a)=ID(a) in case the applicationID param is not specified (so we just don't filter by this parameter, what I was going to actually achieve).

I wonder if there is more elegant way to do this filtering by optional relationship. I tried

MATCH
(a:Application)<-[:GENERATED_IN*0..1]-(log:Log)-[:GENERATED_IN]->(org:Organization)
WHERE ID(a)=coalesce({applicationID}, ID(a))
RETURN
log

And also tried queries with OPTIONAL MATCH, but without success. I would appreciate suggestions for improvement.

And BTW, is there a way to specify parameters like {applicationID} from the neo4j browser console? Like <query>, {applicationID}=202175. I substitute values manually every time.

Body:
Instead of coalesce, you could use IS NULL and check if the parameter was provided:

MATCH
  (log0:Log)-[:GENERATED_IN]->(org:Organization),
  (a1:Application)<-[:GENERATED_IN]-(log1:Log)
WHERE {applicationID} IS NULL
   OR ID(a1)={applicationID}
RETURN DISTINCT
  CASE {applicationID}
    WHEN null THEN log0
    ELSE log1
  END
  AS result

If using Neo4j 3.2+, I'd also consider switching to the new parameter syntax, $param instead of {param}, which makes the queries slightly easier to read.


问:
Two between separated with an AND
is it possible to have 2 between in 1 SQL query separated with an "AND"?

```<code>SELECT *
  FROM t
 WHERE (x BETWEEN '48.3' and '49.3')
   AND (y BETWEEN '1.8' and '3.8');
</code>```

This will work with an OR but won't with an AND.

```<code>***************************************
|   id   |  x    |   y   |    name     |
|    1   | 48.5  |  2.8  |   patrick   |
|    2   | 48.9  |  1.9  |    Sam      |
|    3   | 49.0  |  5.0  |    Jon      |
</code>```

答:
If the value are number you could  use </p>

```<code>  SELECT * FROM t
  WHERE  x BETWEEN 48.3 and 49.3
  AND y BETWEEN 1.8 and 3.8
</code>```

Title: Two between separated with an AND

Body:
is it possible to have 2 between in 1 SQL query separated with an "AND"?

SELECT *
  FROM t
 WHERE (x BETWEEN '48.3' and '49.3')
   AND (y BETWEEN '1.8' and '3.8');

This will work with an OR but won't with an AND.

***************************************
|   id   |  x    |   y   |    name     |
|    1   | 48.5  |  2.8  |   patrick   |
|    2   | 48.9  |  1.9  |    Sam      |
|    3   | 49.0  |  5.0  |    Jon      |

Body:
If the value are number you could  use

  SELECT * FROM t
  WHERE  x BETWEEN 48.3 and 49.3
  AND y BETWEEN 1.8 and 3.8


问:
How can i combine a case insensitive search with a case sensitive replace in regex?
For example, suppose I have the following text:

```<code>"Constants cons are CONTAGIOUS"
</code>```

I want all the "cons" replaced irrespective of case, but preserving case on the replace.

For example, suppose I want to put bold tags around them, I would want the output to be:

```<code>"<b>Con</b>stants <b>cons</b> are <b>CON</b>TAGIOUS"
</code>```

In JavaScript, I have tried:

```<code>var re = new RegExp("con", 'ig');
var newText = text.replace(re,"<b>" + "con" + "</b>");
</code>```

This does a case insensitive search but I lose the case on the replace. Is there a way to preserve case on the replace?

答:
As @JordanRunning has pointed out in a comment,
a simple solution is to refer to the matched string in the replacement string using $&:

```<code>"Constants cons are CONTAGIOUS".replace(/con/ig, "<b>$&</b>")
</code>```

Produces:

```<code>"<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"
</code>```

Another alternative (my original suggestion) it using capturing group (con), and reference it in the replacement string with $1:

```<code>"Constants cons are CONTAGIOUS".replace(/(con)/ig, "<b>$1</b>")
</code>```

Body:
For example, suppose I have the following text:

"Constants cons are CONTAGIOUS"

I want all the "cons" replaced irrespective of case, but preserving case on the replace.

For example, suppose I want to put bold tags around them, I would want the output to be:

"Constants cons are CONTAGIOUS"

In JavaScript, I have tried:

var re = new RegExp("con", 'ig');
var newText = text.replace(re,"" + "con" + "");

This does a case insensitive search but I lose the case on the replace. Is there a way to preserve case on the replace?

Body:
As @JordanRunning has pointed out in a comment,
a simple solution is to refer to the matched string in the replacement string using $&:

"Constants cons are CONTAGIOUS".replace(/con/ig, "<b>$&</b>")

Produces:

"<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"

Another alternative (my original suggestion) it using capturing group (con), and reference it in the replacement string with $1:

"Constants cons are CONTAGIOUS".replace(/(con)/ig, "<b>$1</b>")


问:
Using React props vs import , What is the best choice?
I'm trying to understand what is the best way to use props in React

Let's say I have a container that use import {FormattedMessage} from 'react-intl'

And let say I have a component used in the JSX of the container.

Now, If I wanted to use FormattedMessage in the component also, Should I use import again in the component?
or should I send FormattedMessage as a prop to the component via the container?

Example:

```<code>import {FormattedMessage} from 'react-intl';

class Container {
   render() {
        return (
                <Component formattedMessage={FormattedMessage} />
        );
   }
}
</code>```

答: You should try to not using props to transfer Components to other Components. Better import them where you need them or use Higher Order Components instead. Props are usually used to transfer data or container functions.</p>

Body:
I'm trying to understand what is the best way to use props in React

Let's say I have a container that use import {FormattedMessage} from 'react-intl'

And let say I have a component used in the JSX of the container.

Now, If I wanted to use FormattedMessage in the component also, Should I use import again in the component?
or should I send FormattedMessage as a prop to the component via the container?

Example:

import {FormattedMessage} from 'react-intl';

class Container {
   render() {
        return (
                <Component formattedMessage={FormattedMessage} />
        );
   }
}


问:
Drupal - dynamic options for text_list field
I have a custom node type for which I want to have a field that uses a special combobox based on list_text. When one chooses the type list_text it is normally possible to enter a static list of selectable texts, however, I want this list to be dynamic, i.e. based on the results of a db_query. What is the best way to do this using Drupal 7?

A simple example for clarification: A node of this custom type X contains a field that points to another node, so whenever a node of type X is created I want a combobox that contains all other nodes.

(Best solution would be to only display the combobox during node creation, and no longer during edit. But I could also live with it if the combobox was shown during the edit as well.)

I have tried to customize options_select by defining my own data type and implementing hook_options_list accordingly. The combobox was displayed during creation with the correct values, however,  I could not save it.. I have no idea what went wrong there, but on the first submit it would change to a different theme, and when I tried again I got an internal server error. Am I on the right track at all with defining a completely new data type for the field? there surely must be a simpler way?

答:
The tutorial linked by allegroconmolto sent me on the right way. Thanks for that.

Here's the simpler way of doing it: tutorial

Basically, it is, as I assumed, a common problem and hence a simple solution for it was included in the webform module by now. It provides a hook_webform_select_options_info which can be used to register a callback method. The callback method is then called each time a corresponding option select of a webform is shown, so that you can easily fill it with the results of a dbquery or anything else. Works like a charm and takes next to no time to implement.


问:
Not able to fire angular function (John Papa style)
Here's the form in html:

```<code><form ng-submit="vm.setTest(test)">
    <input type="text" ng-model="test" required />in USD
    <input type="submit" value="Submit">
</form>
</code>```

Here's the JavaScript:

```<code>var vm = this;
vm.setTest = setTest;
function setTest(test) {
    alert(test);
}
</code>```

Please note, that no $scope involved and should not be.

答:
Figure out. This is how now html looks:

```<code><form ng-submit="testController.setTest(test)">
    <input type="text" ng-model="test" required />in USD
    <input type="submit" value="Submit">
</form>
</code>```

Body:
Here's the form in html:

<form ng-submit="vm.setTest(test)">
    <input type="text" ng-model="test" required />in USD
    <input type="submit" value="Submit">
</form>

Here's the JavaScript:

var vm = this;
vm.setTest = setTest;
function setTest(test) {
    alert(test);
}

Please note, that no $scope involved and should not be.

Body:
Figure out. This is how now html looks:

<form ng-submit="testController.setTest(test)">
    <input type="text" ng-model="test" required />in USD
    <input type="submit" value="Submit">
</form>