问:
How do I set django generic foreign key from my views?
I have 4 forms that the user submits by clicking one Submit button. The forms are:

Person Form - Will Save to Person Model

Address Form - Will Save to Address Model

Email Form - Will save to Email Model

Phone Form - Will save to Phone Model.

So, a Person can have multiple Addresses, Emails and Phone Numbers. So, I did this in the Person Model:

```<code>class Person(models.Model):
    first_name = models.CharField(max_length=99)
    middle_name = models.CharField(max_length=99, blank=True, null=True)
    last_name = models.CharField(max_length=99, blank=True, null=True)
    address = GenericRelation('Address')
    phone = GenericRelation('Phone')
    email = GenericRelation('Email')
</code>```

I have these 3 lines along with their respective model fields for Address, Phone and Email

```<code>content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
</code>```

Now, how do I save data to these models properly in my views when I receive the form from the user? This what I have so far.

```<code> if request.method == 'POST':
        if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \
                and phone_form.is_valid():

            address = address_form.save()
            email = email_form.save()
            phone = phone_form.save()

            person = person_form.save(commit=False) #This person model has a generic foreign key relation with Address, Email and Phone
            person.address = (address)  #This is where I need help. Am I thinking right? Is this the right way to save?
</code>```

答:
You need to set the content object in model where GFK is defined,  I have modified the code,

```<code> if request.method == 'POST':
                if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \
                        and phone_form.is_valid():

                person = person_form.save()

                address = address_form.save(commit=False)
                address.content_object = person
                address.save()
                email = email_form.save(commit=False)
                email.content_object = person
                email.save()
                phone = phone_form.save(commit=False)
                phone.content_object = person
                phone.save()
</code>```

But i have one serious doubt ? why are your using Generic Foreign Key in your models ? Can these models refer to any other model other than Person.

Body:
I have 4 forms that the user submits by clicking one Submit button. The forms are:

Person Form - Will Save to Person Model

Address Form - Will Save to Address Model

Email Form - Will save to Email Model

Phone Form - Will save to Phone Model.

So, a Person can have multiple Addresses, Emails and Phone Numbers. So, I did this in the Person Model:

class Person(models.Model):
    first_name = models.CharField(max_length=99)
    middle_name = models.CharField(max_length=99, blank=True, null=True)
    last_name = models.CharField(max_length=99, blank=True, null=True)
    address = GenericRelation('Address')
    phone = GenericRelation('Phone')
    email = GenericRelation('Email')

I have these 3 lines along with their respective model fields for Address, Phone and Email

content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')

Now, how do I save data to these models properly in my views when I receive the form from the user? This what I have so far.

 if request.method == 'POST':
        if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \
                and phone_form.is_valid():

            address = address_form.save()
            email = email_form.save()
            phone = phone_form.save()

            person = person_form.save(commit=False) #This person model has a generic foreign key relation with Address, Email and Phone
            person.address = (address)  #This is where I need help. Am I thinking right? Is this the right way to save?

Body:
You need to set the content object in model where GFK is defined,  I have modified the code,

 if request.method == 'POST':
                if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \
                        and phone_form.is_valid():

                person = person_form.save()

                address = address_form.save(commit=False)
                address.content_object = person
                address.save()
                email = email_form.save(commit=False)
                email.content_object = person
                email.save()
                phone = phone_form.save(commit=False)
                phone.content_object = person
                phone.save()

But i have one serious doubt ? why are your using Generic Foreign Key in your models ? Can these models refer to any other model other than Person.


来源: stackexchange

问:
Qt and UI Skinning
I wanted to consult with the sages here regarding Qt and skinning, get your opinion and chart a path for my development. My requirements are as follows:

My Qt/C++ application (cross platform with Mac, Windows and Linux versions) needs to have modular skins.

A skin is defined as a set of one or more elements: - Window background texture - Look/feel of UI controls such as edit boxes, drop down, radio buttons, buttons etc. - Look/feel of window "caption", resize grips etc.

Skins will be installed with the application installer, allowing the user to choose which one he/she wants to use. Users should be able to change skins on the fly.

Can I go the QML route? should this be custom and based on simple resources which are built into the application? Any design advice will be appreciated.

Thanks.

答:
I haven't played with QML yet, but you could also create a custom QStyle implementation that supports your resource format. Note that you'd lose style sheet support if you went this route.

Changing window captions is a little trickier if you want portability.

ContentLicense: CC BY-SA 2.5

Title: Qt and UI Skinning


问:
WebDriverException: Message: unknown error: Chrome failed to start: crashed
I am trying to use headless chrome with selenium, I created a symlink for path to chromedriver into /usr/local/bin, but when I run

```<code>from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')

browser = webdriver.Chrome()
browser.get('http://www.google.com')
</code>```

I got the error as

```<code>     Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
    desired_capabilities=desired_capabilities)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 92, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 179, in start_session
    response = self.execute(Command.NEW_SESSION, capabilities)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 3.10.0-327.22.2.el7.x86_64 x86_64)
</code>```

Also it generates a core.*****, a core file dot with five random numbers, which is more than 200MB large.

Versions:

```<code>Selenium 3.0.0b3
Google Chrome 60.0.3112.113
chromedriver 2.30
</code>```

Could anyone help me figure out what is wrong please?

答:
I was having a problem getting headless Chrome to work on Ubuntu 14.04, it was dying with the same unknown error: Chrome failed to start: crashed error, I traced it back to a dependency problem that the Selenium driver was oblivious to.

To diagnose I tried running headless Chrome directly and got:

```<code>$ google-chrome --headless "http://example.com"
NSS_VersionCheck("3.26") failed. NSS >= 3.26 is required.
</code>```

This is what libnss3 had installed:

```<code>$ dpkg -s libnss3
Package: libnss3
Version: 2:3.23-0ubuntu0.14.04.1
</code>```

So I switched over to libnss3-dev:

```<code>$ apt-get install libnss3-dev
$ dpkg -s libnss3
Package: libnss3
Version: 2:3.28.4-0ubuntu0.14.04.3
</code>```

And retried on the command line:

```<code>$ google-chrome --headless "http://example.com"
$ echo $?
0
</code>```

And sure enough, once headless Chrome was working on the command line it started working in Selenium also.

These are the versions I am currently using:

```<code>$ google-chrome --version
Google Chrome 62.0.3202.94
$ chromedriver --version
ChromeDriver 2.33.506092
$ $ pip freeze |grep selenium
selenium==3.7.0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use headless chrome with selenium, I created a symlink for path to chromedriver into /usr/local/bin, but when I run

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless')

browser = webdriver.Chrome()
browser.get('http://www.google.com')

I got the error as

     Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
    desired_capabilities=desired_capabilities)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 92, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 179, in start_session
    response = self.execute(Command.NEW_SESSION, capabilities)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/opt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
  (Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 3.10.0-327.22.2.el7.x86_64 x86_64)

Also it generates a core.*****, a core file dot with five random numbers, which is more than 200MB large.

Versions:

Selenium 3.0.0b3
Google Chrome 60.0.3112.113
chromedriver 2.30

Could anyone help me figure out what is wrong please?

Body:
I was having a problem getting headless Chrome to work on Ubuntu 14.04, it was dying with the same unknown error: Chrome failed to start: crashed error, I traced it back to a dependency problem that the Selenium driver was oblivious to.

To diagnose I tried running headless Chrome directly and got:

$ google-chrome --headless "http://example.com"
NSS_VersionCheck("3.26") failed. NSS >= 3.26 is required.

This is what libnss3 had installed:

$ dpkg -s libnss3
Package: libnss3
Version: 2:3.23-0ubuntu0.14.04.1

So I switched over to libnss3-dev:

$ apt-get install libnss3-dev
$ dpkg -s libnss3
Package: libnss3
Version: 2:3.28.4-0ubuntu0.14.04.3

And retried on the command line:

$ google-chrome --headless "http://example.com"
$ echo $?
0

And sure enough, once headless Chrome was working on the command line it started working in Selenium also.

These are the versions I am currently using:

$ google-chrome --version
Google Chrome 62.0.3202.94
$ chromedriver --version
ChromeDriver 2.33.506092
$ $ pip freeze |grep selenium
selenium==3.7.0


问:
Problems with Sprites Appearing and Collision with Rotated Objects; Pygame object is not iterable
I'm currently trying to make pixel perfect collisions between my pong ball and my player's paddle using the mask and collide_rect functions. I made my own checkCollision function in the pong class which would check for pixel perfect collision. However, right now, I can't even get the Sprites to work or appear on the screen because my "Pong object is not iterable.

Here is my pong class with the important features: (I will post additional code if needed)

```<code>class Pong(pygame.sprite.Sprite):

    def __init__(self, screensize):

        pygame.sprite.Sprite.__init__(self)

        self.screensize = screensize

        self.centerx = screensize[0] // 2
        self.centery = screensize[1] // 2
        self.radius = 25
        self.rect = pygame.Rect(self.centerx-self.radius,
                                self.centery-self.radius,
                                self.radius*2, self.radius*2)

        self.pokeimage = pygame.image.load("pokeball.png")
        self.pokeimage = pygame.transform.scale(self.pokeimage, (self.radius, self.radius))

        #Create the mask
        self.mask = pygame.mask.from_surface(self.pokeimage)

    def checkCollision(self, player_paddle, ai_paddle):

        col = pygame.sprite.collide_rect(self, player_paddle)

        return col

    def collisionFormula(self, player_paddle, ai_paddle):

        if self.checkCollision(self, player_paddle):

    def collision_checks(self, player_paddle, ai_paddle):

        #if the ball hits the top or bottom of the screen, change the y direction
        if self.rect.top <= 0 or self.rect.bottom >= self.screensize[1] - 1:
            self.direction[1] *= -1

        #if the pong hits the paddles, change how the pong ball moves
        if self.rect.colliderect(player_paddle.rect) or self.rect.colliderect(ai_paddle.rect):
            self.collisionFormula(player_paddle, ai_paddle)

    def update(self, player_paddle, ai_paddle):

        self.update_ball_position()
        self.reset_ball()
        self.collision_checks(player_paddle, ai_paddle)
</code>```

In my PlayerPaddle class, I do the same mask initialization.

```<code>class PlayerPaddle(pygame.sprite.Sprite):
    def __init__(self, screensize):

        pygame.sprite.Sprite.__init__(self)
        self.screensize = screensize

        self.centerx = 50
        self.centery = screensize[1]//2

        self.height = 100
        self.width = 20
        self.imageMaster = pygame.image.load("naruto.png").convert_alpha()
        self.imageMaster = pygame.transform.scale(self.imageMaster, (self.width, self.height))
        self.image = self.imageMaster

        #mask
        self.mask = pygame.mask.from_surface(self.image)

    def turnLeft(self):
        self.dir += 45
        if self.dir > 360:
            self.dir = 45

    def turnRight(self):
        self.dir -= 45
        if self.dir < 0:
            self.dir = 315
    def update(self):
        #Rotate functions
        oldCenter = self.rect.center
        self.image = pygame.transform.rotate(self.imageMaster, self.dir)
        self.rect = self.image.get_rect()
        self.rect.center = oldCenter
</code>```

And here is my main function:

def main():
    pygame.init()

```<code>screensize = (640,700)
screen = pygame.display.set_mode(screensize)

background = pygame.Surface(screen.get_size())
background.fill((0, 255, 0))

clock = pygame.time.Clock()

pong = Pong(screensize)
player_paddle = PlayerPaddle(screensize)
ai_paddle = AIPaddle(screensize)

paddleSprite = pygame.sprite.Group(player_paddle)
pongSprite = pygame.sprite.Group(pong)

while running:
    running = True

        #object updating phase
        ai_paddle.update(pong, player_paddle)
        player_paddle.update()
        pong.update(player_paddle, ai_paddle)

        if pygame.sprite.spritecollide(player_paddle, pong, False, pygame.sprite.collide_mask):
            print("Collided")

    #rendering phase
        ai_paddle.render(screen)
        player_paddle.render(screen)
        pong.render(screen)

        paddleSprite.clear(screen, background)
        paddleSprite.update()
        paddleSprite.draw(screen)

        pongSprite.clear(screen,background)
        pongSprite.update()
        pongSprite.draw(screen)

        pygame.display.flip()

    pygame.quit()

main()
</code>```

I made two "group" objects (the pong and the player_paddle) but I'm not sure why I'm even failing to run the program. Additionally, I know the collision will not work because the pong ball will hit the rectangle of the original image, but not the rotated image, but I'm not sure why that will happen if I use the built in sprite function. Thanks.

答:
Read documentation for spritecollide

Find sprites in a group that intersect another sprite.

  spritecollide(sprite, group, dokill, collided = None) -> Sprite_list

Second argument has to be group (pygame.sprite.Group), not single Sprite.

It can be group event with one sprite. But you use pong which is single sprite, not group.

See documentation for collide_mask

Collision detection between two sprites, using masks.

  collide_mask(SpriteLeft, SpriteRight) -> point

It checks collision between two sprites using mask.

EDIT: in your code you have problem with

```<code>spritecollide(player_paddle, pong,...)
</code>```

because pong is single Sprite, not Group.

With pong you should use collide_mask

```<code>collide_mask(player_paddle, pong)
</code>```

You can use spritecollidewith pongSprite which is Group

```<code>spritecollide(player_paddle, pongSprite,...)`
</code>```

BTW: you could use better names ie. pong_group instead of pongSprite.

And eventually pong_sprite instead of pong (but pong is OK, too).

Body:
I'm currently trying to make pixel perfect collisions between my pong ball and my player's paddle using the mask and collide_rect functions. I made my own checkCollision function in the pong class which would check for pixel perfect collision. However, right now, I can't even get the Sprites to work or appear on the screen because my "Pong object is not iterable.

Here is my pong class with the important features: (I will post additional code if needed)

class Pong(pygame.sprite.Sprite):

    def __init__(self, screensize):

        pygame.sprite.Sprite.__init__(self)

        self.screensize = screensize

        self.centerx = screensize[0] // 2
        self.centery = screensize[1] // 2
        self.radius = 25
        self.rect = pygame.Rect(self.centerx-self.radius,
                                self.centery-self.radius,
                                self.radius*2, self.radius*2)

        self.pokeimage = pygame.image.load("pokeball.png")
        self.pokeimage = pygame.transform.scale(self.pokeimage, (self.radius, self.radius))

        #Create the mask
        self.mask = pygame.mask.from_surface(self.pokeimage)

    def checkCollision(self, player_paddle, ai_paddle):

        col = pygame.sprite.collide_rect(self, player_paddle)

        return col

    def collisionFormula(self, player_paddle, ai_paddle):

        if self.checkCollision(self, player_paddle):

    def collision_checks(self, player_paddle, ai_paddle):

        #if the ball hits the top or bottom of the screen, change the y direction
        if self.rect.top <= 0 or self.rect.bottom >= self.screensize[1] - 1:
            self.direction[1] *= -1

        #if the pong hits the paddles, change how the pong ball moves
        if self.rect.colliderect(player_paddle.rect) or self.rect.colliderect(ai_paddle.rect):
            self.collisionFormula(player_paddle, ai_paddle)

    def update(self, player_paddle, ai_paddle):

        self.update_ball_position()
        self.reset_ball()
        self.collision_checks(player_paddle, ai_paddle)

In my PlayerPaddle class, I do the same mask initialization.

class PlayerPaddle(pygame.sprite.Sprite):
    def __init__(self, screensize):

        pygame.sprite.Sprite.__init__(self)
        self.screensize = screensize

        self.centerx = 50
        self.centery = screensize[1]//2

        self.height = 100
        self.width = 20
        self.imageMaster = pygame.image.load("naruto.png").convert_alpha()
        self.imageMaster = pygame.transform.scale(self.imageMaster, (self.width, self.height))
        self.image = self.imageMaster

        #mask
        self.mask = pygame.mask.from_surface(self.image)

    def turnLeft(self):
        self.dir += 45
        if self.dir > 360:
            self.dir = 45

    def turnRight(self):
        self.dir -= 45
        if self.dir < 0:
            self.dir = 315
    def update(self):
        #Rotate functions
        oldCenter = self.rect.center
        self.image = pygame.transform.rotate(self.imageMaster, self.dir)
        self.rect = self.image.get_rect()
        self.rect.center = oldCenter

And here is my main function:

def main():
    pygame.init()

screensize = (640,700)
screen = pygame.display.set_mode(screensize)

background = pygame.Surface(screen.get_size())
background.fill((0, 255, 0))

clock = pygame.time.Clock()

pong = Pong(screensize)
player_paddle = PlayerPaddle(screensize)
ai_paddle = AIPaddle(screensize)

paddleSprite = pygame.sprite.Group(player_paddle)
pongSprite = pygame.sprite.Group(pong)

while running:
    running = True

        #object updating phase
        ai_paddle.update(pong, player_paddle)
        player_paddle.update()
        pong.update(player_paddle, ai_paddle)

        if pygame.sprite.spritecollide(player_paddle, pong, False, pygame.sprite.collide_mask):
            print("Collided")

    #rendering phase
        ai_paddle.render(screen)
        player_paddle.render(screen)
        pong.render(screen)

        paddleSprite.clear(screen, background)
        paddleSprite.update()
        paddleSprite.draw(screen)

        pongSprite.clear(screen,background)
        pongSprite.update()
        pongSprite.draw(screen)

        pygame.display.flip()

    pygame.quit()

main()

I made two "group" objects (the pong and the player_paddle) but I'm not sure why I'm even failing to run the program. Additionally, I know the collision will not work because the pong ball will hit the rectangle of the original image, but not the rotated image, but I'm not sure why that will happen if I use the built in sprite function. Thanks.

Body:
Read documentation for spritecollide

Find sprites in a group that intersect another sprite.

  spritecollide(sprite, group, dokill, collided = None) -> Sprite_list

Second argument has to be group (pygame.sprite.Group), not single Sprite.

It can be group event with one sprite. But you use pong which is single sprite, not group.

See documentation for collide_mask

Collision detection between two sprites, using masks.

  collide_mask(SpriteLeft, SpriteRight) -> point

It checks collision between two sprites using mask.

EDIT: in your code you have problem with

spritecollide(player_paddle, pong,...)

because pong is single Sprite, not Group.

With pong you should use collide_mask

collide_mask(player_paddle, pong)

You can use spritecollidewith pongSprite which is Group

spritecollide(player_paddle, pongSprite,...)`

BTW: you could use better names ie. pong_group instead of pongSprite.

And eventually pong_sprite instead of pong (but pong is OK, too).


问:
Python pandas Filtering out nan from a data selection of a column of strings
Without using groupby how would I filter out data without NaN?

Let say I have a matrix where customers will fill in 'N/A','n/a' or any of its variations and others leave it blank:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],
                  'rating': [3., 4., 5., np.nan, np.nan, np.nan],
                  'name': ['John', np.nan, 'N/A', 'Graham', np.nan, np.nan]})

nbs = df['name'].str.extract('^(N/A|NA|na|n/a)')
nms=df[(df['name'] != nbs) ]
</code>```

output:

```<code>>>> nms
  movie    name  rating
0   thg    John       3
1   thg     NaN       4
3   mol  Graham     NaN
4   lob     NaN     NaN
5   lob     NaN     NaN
</code>```

How would I filter out NaN values so I can get results to work with like this:

```<code>  movie    name  rating
0   thg    John       3
3   mol  Graham     NaN
</code>```

I am guessing I need something like ~np.isnan but the tilda does not work with strings.

答:
Simplest of all solutions:

```<code>filtered_df = df[df['name'].notnull()]
</code>```

Thus, it filters out only rows that doesn't have NaN values in 'name' column.

For multiple columns:

```<code>filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Without using groupby how would I filter out data without NaN?

Let say I have a matrix where customers will fill in 'N/A','n/a' or any of its variations and others leave it blank:

import pandas as pd
import numpy as np

df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],
                  'rating': [3., 4., 5., np.nan, np.nan, np.nan],
                  'name': ['John', np.nan, 'N/A', 'Graham', np.nan, np.nan]})

nbs = df['name'].str.extract('^(N/A|NA|na|n/a)')
nms=df[(df['name'] != nbs) ]

output:

>>> nms
  movie    name  rating
0   thg    John       3
1   thg     NaN       4
3   mol  Graham     NaN
4   lob     NaN     NaN
5   lob     NaN     NaN

How would I filter out NaN values so I can get results to work with like this:

  movie    name  rating
0   thg    John       3
3   mol  Graham     NaN

I am guessing I need something like ~np.isnan but the tilda does not work with strings.

Body:
Simplest of all solutions:

filtered_df = df[df['name'].notnull()]

Thus, it filters out only rows that doesn't have NaN values in 'name' column.

For multiple columns:

filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]


问:
How to crop circles (found with Hough Transform) in OpenCV?
I'm using the code from the page. It works very well and I get a circle that I am looking for. All my image have only 1 circle and I have modified parameters of HoughCircles() such that the code returns only 1 circle.

How can I crop my original image so that the new image has only the circle (and area within it) and save the new image as a JPEG or PNG file?

Based upon original code, the center of the circle is given by

```<code>(cvRound(circles[1][0]), cvRound(circles[1][1]));
</code>```

and the radius is given by

```<code>cvRound(circles[1][2]);
</code>```

答:
To crop circle after circles=HoughCircles(...)</p>

```<code>if len(circles) == 1:
    x, y, r = circles[0][0]
    print x, y, r
    mask = np.zeros((w0,h0),dtype=np.uint8)
    cv2.circle(mask,(x,y),r,(255,255,255),-1,8,0)
    #cv2.imwrite(argv[2],mask)
    out = img*mask
    white = 255-mask
    cv2.imwrite(argv[2],out+white)
</code>```

Body:
I'm using the code from the page. It works very well and I get a circle that I am looking for. All my image have only 1 circle and I have modified parameters of HoughCircles() such that the code returns only 1 circle.

How can I crop my original image so that the new image has only the circle (and area within it) and save the new image as a JPEG or PNG file?

Based upon original code, the center of the circle is given by

(cvRound(circles[1][0]), cvRound(circles[1][1]));

and the radius is given by

cvRound(circles[1][2]);

Body:
To crop circle after circles=HoughCircles(...)

if len(circles) == 1:
    x, y, r = circles[0][0]
    print x, y, r
    mask = np.zeros((w0,h0),dtype=np.uint8)
    cv2.circle(mask,(x,y),r,(255,255,255),-1,8,0)
    #cv2.imwrite(argv[2],mask)
    out = img*mask
    white = 255-mask
    cv2.imwrite(argv[2],out+white)


问:
Ho do I call a web service on a database change?
There is a business process that happens currently in a totally manual fashion, which seems to me to be a no-brainer to automate. Basically what happens is when a new row is added to a single table in a SQL server, a person then manually makes a change in another business system (based on some very simple business logic).

It's easy to capture the business logic and make the change in the 2nd system programmatically using a web-service. However I don't know how to trigger the calling of the web service when the new row is added into the SQL table.

I've been reading from older forums posts that there are 2 options - the SQL dependency class in .NET and a database trigger in SQL. I was wondering if those are still the 2 main options for a problem like this one.

A colleague of mine showed me the SignalR framework and it was very impressive, but I understand that only works for web applications with a HTML/Javascript front end? I was wondering if there was something similar to that, that's easy to use to simply call a webservice.

Thanks

答:
You can use sql dependency and you'll be notified each time your database changes
I wrote a tutorial a few years back on how to deal with this

Sql Dependency tutorial


问:
Whats wrong with my jquery here? - I am trying to submit this without having a refresh effect on the page
The button seems to trigger the JQuery, but the ajax isn't POSTing the data to the php file. If I place alert("working"); in the success, it won't alert.</p>

```<code>echo "
     <input type='submit' class='primaryButton' value='Cancel' id='cancel-button' style='display: float; float: left; margin-right: 1.5%;' onclick='return confirm("Cancel Ticket?")'>
     ";

$( "#cancel-button" ).click(function() {
    var ticketID = "<?php echo($_GET['id']); ?>";
    var ticketPosition = "ticket";
    var cancelTicketAuth = "G7D9-F9D8-S0BD-C8F9-D03F-G8V9";
    var dataStringCancel = "ticketID=" + ticketID + "&ticket-position=" + ticketPosition + "&cancelTicketAuth=" + cancelTicketAuth;
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '../../php/ticket/cancelTicket.php',
        data: dataStringCancel,
        success: function (CancelTicketReturn) {

        }
    });
});
</code>```

答:
You need to pass the parameter event (e) to the click function: function(e) {

```<code>$( "#cancel-button" ).click(function(e) {
    // Dont use the onclick on your submit button.
    // Let jQuery handle it.
    if(confirm("Cancel Ticket?") == false) return;

    var ticketID = "<?php echo($_GET['id']); ?>";
    var ticketPosition = "ticket";
    var cancelTicketAuth = "G7D9-F9D8-S0BD-C8F9-D03F-G8V9";
    var dataStringCancel = "ticketID=" + ticketID + "&ticket-position=" + ticketPosition + "&cancelTicketAuth=" + cancelTicketAuth;
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '../../php/ticket/cancelTicket.php',
        data: dataStringCancel,
        success: function (CancelTicketReturn) {

        }
    });
});
</code>```

EventData

Type: Anything
  An object containing data that will be passed to the event handler.
  https://api.jquery.com/click/

Body:
The button seems to trigger the JQuery, but the ajax isn't POSTing the data to the php file. If I place alert("working"); in the success, it won't alert.

echo "
     <input type='submit' class='primaryButton' value='Cancel' id='cancel-button' style='display: float; float: left; margin-right: 1.5%;' onclick='return confirm("Cancel Ticket?")'>
     ";

$( "#cancel-button" ).click(function() {
    var ticketID = "<?php echo($_GET['id']); ?>";
    var ticketPosition = "ticket";
    var cancelTicketAuth = "G7D9-F9D8-S0BD-C8F9-D03F-G8V9";
    var dataStringCancel = "ticketID=" + ticketID + "&ticket-position=" + ticketPosition + "&cancelTicketAuth=" + cancelTicketAuth;
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '../../php/ticket/cancelTicket.php',
        data: dataStringCancel,
        success: function (CancelTicketReturn) {

        }
    });
});

Body:
You need to pass the parameter event (e) to the click function: function(e) {

$( "#cancel-button" ).click(function(e) {
    // Dont use the onclick on your submit button.
    // Let jQuery handle it.
    if(confirm("Cancel Ticket?") == false) return;

    var ticketID = "<?php echo($_GET['id']); ?>";
    var ticketPosition = "ticket";
    var cancelTicketAuth = "G7D9-F9D8-S0BD-C8F9-D03F-G8V9";
    var dataStringCancel = "ticketID=" + ticketID + "&ticket-position=" + ticketPosition + "&cancelTicketAuth=" + cancelTicketAuth;
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '../../php/ticket/cancelTicket.php',
        data: dataStringCancel,
        success: function (CancelTicketReturn) {

        }
    });
});

EventData

Type: Anything
  An object containing data that will be passed to the event handler.
  https://api.jquery.com/click/


问:
ftp_put returned TRUE but no file uploaded
Trying to upload a file to an FTP server using HTML form and PHP. My HTML form is:

```<code><!DOCTYPE html>
<html>
<body>

<form action="uploader.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="files" id="files">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>
</code>```

uploader.php:

```<code><?php
$conn_id = ftp_connect ( 'ftp.mydomain.com' );
$ftp_user_name="<username>";
$ftp_user_pass="<password>";

// login with username and password
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass );

// check connection
if ((! $conn_id ) || (! $login_result )) {
    echo "FTP connection has failed!" ;
    exit;

} else {
    echo "Connected to for user $ftp_user_name" ;
}

if (empty($_FILES['files']['tmp_name'])) {
    echo "No file!!!!!!!!!";
    die();
}
// upload the file
$upload = ftp_put( $conn_id, "uploads/" , $_FILES['files']['tmp_name'] , FTP_BINARY );

// check upload status
if(!$upload){
    echo "FTP upload has failed!" ;
} else {
    echo "Successfully Uploaded." ;
}
?>
</code>```

The output I got is Successfully Uploaded., but no file in actual can be found uploaded in the server.

uploads/ directory is located in the same uploader.php directory. Trying to change it to uploads/somename.zip shows that uploads/somename.zip is not a valid directoty.

答:
The second argument of ftp_put is a path to a remote file, not a path to a local directory.

So it should be like:

```<code>ftp_put($conn_id, "/remote/path/somename.zip", $_FILES['files']['tmp_name'], FTP_BINARY);
</code>```

Also, you should use a passive mode. See PHP ftp_put fails.

Body:
Trying to upload a file to an FTP server using HTML form and PHP. My HTML form is:

<!DOCTYPE html>

<form action="uploader.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="files" id="files">
    <input type="submit" value="Upload Image" name="submit">
</form>

uploader.php:

<?php
$conn_id = ftp_connect ( 'ftp.mydomain.com' );
$ftp_user_name="<username>";
$ftp_user_pass="<password>";

// login with username and password
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass );

// check connection
if ((! $conn_id ) || (! $login_result )) {
    echo "FTP connection has failed!" ;
    exit;

} else {
    echo "Connected to for user $ftp_user_name" ;
}

if (empty($_FILES['files']['tmp_name'])) {
    echo "No file!!!!!!!!!";
    die();
}
// upload the file
$upload = ftp_put( $conn_id, "uploads/" , $_FILES['files']['tmp_name'] , FTP_BINARY );

// check upload status
if(!$upload){
    echo "FTP upload has failed!" ;
} else {
    echo "Successfully Uploaded." ;
}
?>

The output I got is Successfully Uploaded., but no file in actual can be found uploaded in the server.

uploads/ directory is located in the same uploader.php directory. Trying to change it to uploads/somename.zip shows that uploads/somename.zip is not a valid directoty.

Body:
The second argument of ftp_put is a path to a remote file, not a path to a local directory.

So it should be like:

ftp_put($conn_id, "/remote/path/somename.zip", $_FILES['files']['tmp_name'], FTP_BINARY);

Also, you should use a passive mode. See PHP ftp_put fails.


问:
ionic 2 and onesignal, how to save playerId to local storage
I am using one signal in ionic2 to do push notification, I have tested the plugin and it's working fine, but i want to go a step further by sending notification from my app server. Hence I need player ID, I followed the docs on the internet and I was able to show the playerId  as alert, but I want to store it my local storage. that is the challenge

below is my code

```<code> platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();

      window["plugins"].OneSignal.getIds(function(ids) {

        alert(JSON.stringify(ids.userId));

        this.storage.set('playersID',  ids.userId);

    });

      // OneSignal Code start:
      // Enable to debug issues:
      // window["plugins"].OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
      this._OneSignal.startInit("568ed291-8d30-441f-b7be-d0d99aaca596", '342271570971');

      this._OneSignal.inFocusDisplaying(this._OneSignal.OSInFocusDisplayOption.Notification);
      this._OneSignal.setSubscription(true);

      this._OneSignal.handleNotificationReceived().subscribe(() => {
        // handle received here how you wish.
      });
      this._OneSignal.handleNotificationOpened().subscribe(() => {
        // handle opened here how you wish.
      });
      this._OneSignal.endInit();

    })

    }
  }
</code>```

I even tried using below code to no avail

```<code>    window["plugins"].OneSignal.getIds(function(ids) {
      alert(JSON.stringify(ids));

       window.localStorage.setItem('playerID',  ids.userId);

  });
</code>```

I also comment out the alert, same story

答:
You need to be saving it after the init. You wont be getting ids before initialization. Also this._Onesignal.getIds() returns a promise with ids. It does not take a parameter.

```<code>this._OneSignal.startInit("568ed291-8d30-441f-b7be-d0d99aaca596", '342271570971');
this._OneSignal.inFocusDisplaying(this._OneSignal.OSInFocusDisplayOption.Notification);

this._OneSignal.getIds().then(ids => { //here

        alert(JSON.stringify(ids.userId));

        this.storage.set('playersID',  ids.userId);

});
</code>```

Body:
I am using one signal in ionic2 to do push notification, I have tested the plugin and it's working fine, but i want to go a step further by sending notification from my app server. Hence I need player ID, I followed the docs on the internet and I was able to show the playerId  as alert, but I want to store it my local storage. that is the challenge

below is my code

 platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();

      window["plugins"].OneSignal.getIds(function(ids) {

        alert(JSON.stringify(ids.userId));

        this.storage.set('playersID',  ids.userId);

    });

      // OneSignal Code start:
      // Enable to debug issues:
      // window["plugins"].OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
      this._OneSignal.startInit("568ed291-8d30-441f-b7be-d0d99aaca596", '342271570971');

      this._OneSignal.inFocusDisplaying(this._OneSignal.OSInFocusDisplayOption.Notification);
      this._OneSignal.setSubscription(true);

      this._OneSignal.handleNotificationReceived().subscribe(() => {
        // handle received here how you wish.
      });
      this._OneSignal.handleNotificationOpened().subscribe(() => {
        // handle opened here how you wish.
      });
      this._OneSignal.endInit();

    })

    }
  }

I even tried using below code to no avail

    window["plugins"].OneSignal.getIds(function(ids) {
      alert(JSON.stringify(ids));

       window.localStorage.setItem('playerID',  ids.userId);

  });

I also comment out the alert, same story

Body:
You need to be saving it after the init. You wont be getting ids before initialization. Also this._Onesignal.getIds() returns a promise with ids. It does not take a parameter.

this._OneSignal.startInit("568ed291-8d30-441f-b7be-d0d99aaca596", '342271570971');
this._OneSignal.inFocusDisplaying(this._OneSignal.OSInFocusDisplayOption.Notification);

this._OneSignal.getIds().then(ids => { //here

        alert(JSON.stringify(ids.userId));

        this.storage.set('playersID',  ids.userId);

});


问:
How to push to an external array using Async.Whilst
I'm trying to retrieve data from a service and store the results in an array for storing as a JSON, due to the structure of the data that i'm using, I need to nest Async.Whilst in this way:

Code:

```<code>var async = require('async');
var response = {};
async.whilst(function(){
    if(category <= externalCategory){
        category++;
        return true;
    }else{
        return false;
    }
},function(outerCallback){
    response[category] = [];
    async.whilst(function(){
        if(data == "pass"){
            return true;
        }else{
            //retry
            return false;
        }
    },function(callback) {
        var data = {
            //Retrieved data
        };
        response[category].push(data);
        callback();

    },function () {
        outerCallback();
    });
},function(){
    next(null, response);
});
</code>```

As I mentioned, i want an Object to save it in a JSON on my database, something like this:

Expected Result:

```<code>response:{
    0:[dataA, dataB],
    1:[dataC, dataD, dataE],
    2:[dataF],
    3:[dataG, dataH]
}
</code>```

But, i keep getting all the Object filled with the last value on the array that i pushed:

Actual Result:

```<code>response:{
    0:[dataB, dataB],
    1:[dataE, dataE, dataE],
    2:[dataF],
    3:[dataH, dataH]
}
</code>```

I'm new to asynchronus programming in Node.js, so I'm getting really confused about nesting async functions and why this happens, any help or alternatives?

答:
I hope your problem may solve by using 'eachOfSeries' of async in which you get the index value , so that you can avoid nested async and eachOfSeries is serial in action . so don't worry about asynchronus

https://caolan.github.io/async/docs.html#eachOfSeries

Body:
I'm trying to retrieve data from a service and store the results in an array for storing as a JSON, due to the structure of the data that i'm using, I need to nest Async.Whilst in this way:

Code:

var async = require('async');
var response = {};
async.whilst(function(){
    if(category <= externalCategory){
        category++;
        return true;
    }else{
        return false;
    }
},function(outerCallback){
    response[category] = [];
    async.whilst(function(){
        if(data == "pass"){
            return true;
        }else{
            //retry
            return false;
        }
    },function(callback) {
        var data = {
            //Retrieved data
        };
        response[category].push(data);
        callback();

    },function () {
        outerCallback();
    });
},function(){
    next(null, response);
});

As I mentioned, i want an Object to save it in a JSON on my database, something like this:

Expected Result:

response:{
    0:[dataA, dataB],
    1:[dataC, dataD, dataE],
    2:[dataF],
    3:[dataG, dataH]
}

But, i keep getting all the Object filled with the last value on the array that i pushed:

Actual Result:

response:{
    0:[dataB, dataB],
    1:[dataE, dataE, dataE],
    2:[dataF],
    3:[dataH, dataH]
}

I'm new to asynchronus programming in Node.js, so I'm getting really confused about nesting async functions and why this happens, any help or alternatives?


问:
Unity - Moving the player or the scenario - Endless runner
I'm going to create an endless runner in Unity and I was wondering if I should move the player or the scenario during the runs.

The most obvious answer sounds like "the player" because you are moving fewer objects but... does the performance get affected if the size of the scenes is too large? I don't think so but my real worry is about the coordinate:

What happens if the player runs so far away that the coordinates can't fit in a float variable? I think that the transform component uses a Vector3 to store the coordinates and this Vector3 uses float variables (with a limit of +3.4E+38) for each of the coordinates.

Thank you for your answers in advance,
Guillem Poy

答:
Even if I don't know what happens if the value of the coordenates exceeds the capacity of a float variable (I think that then the number simply will be wrong) doing some calculus...

Even if the player is moving 1000 units per second, to create that problem, the player should be playing during 9.4+E32 hours (2.5+E29 years). I think that nobody is going to play this much.

So, the best option I think that is to move the player.


问:
JSON URL specific item to DIV
```<code><html>
<script>
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: todos1
    });
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>
</code>```

how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

```<code><div id="3rd_title_here">fugiat veniam minus</div>
</code>```

to any ones curiousity this is what the JSON structure looks like if u view the URL link

```<code>{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}
</code>```

答:
You should use:

```<code>function gettodo()
        {
            var TODOS ='https://jsonplaceholder.typicode.com/todos';
            $.ajax({
                cache: false,
                dataType: "json",
                url: TODOS,
                success: function(data) {
                   $("#3rd_title_here").html(data[2].title);
                }
            });
        }
    setInterval(gettodo(),1000);
</code>```

the .html() method of jquery renders the text into the html, just like what you are trying to achieve.

Title: JSON URL specific item to DIV

Body:
how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

fugiat veniam minus

to any ones curiousity this is what the JSON structure looks like if u view the URL link

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}

Body:
You should use:

function gettodo()
        {
            var TODOS ='https://jsonplaceholder.typicode.com/todos';
            $.ajax({
                cache: false,
                dataType: "json",
                url: TODOS,
                success: function(data) {
                   $("#3rd_title_here").html(data[2].title);
                }
            });
        }
    setInterval(gettodo(),1000);

the .html() method of jquery renders the text into the html, just like what you are trying to achieve.


问:
Cascading grid layout with flexbox
I have a lot of box of different height and i would like to have this result:

But box are aligned relative to the biggest box height.
I add this to container but size line is the bigger element.

```<code>display: flex;
margin: 9px;
flex-wrap: wrap;
</code>```

Demo

答:
This is little approach from modern grid layout. If you try you can manipulate grid row and column easily! Here is an example....

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 40px;
}

.wrapper {
  margin: 0 0 20px 0;
  width: 500px;
  height: 400px;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(3, 100px);
  justify-content: center;
  align-content: end;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.item1 {
  grid-column: 1 / 3;
  grid-row: 1/3;
}

.item2 {
  grid-column: 1 / 3;
  grid-row: 3 / 4;
}

.item3 {
  grid-column: 3 / 5;
}

.item4 {
  grid-column: 3 / 5;
  grid-row: 2/4;
}

.item5 {
  grid-column: 5 / 7;
  grid-row: 1/ 3;
}

.item6 {
  grid-column: 5 / 7;
  grid-row: 3/ 4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="box item1">One</div>
  <div class="box item2">Two</div>
  <div class="box item3">Three</div>
  <div class="box item4">Four</div>
  <div class="box item5">Five</div>
  <div class="box item6">Six</div>
</div></code>```

Title: Cascading grid layout with flexbox

Body:
I have a lot of box of different height and i would like to have this result:

But box are aligned relative to the biggest box height.
I add this to container but size line is the bigger element.

display: flex;
margin: 9px;
flex-wrap: wrap;

Demo

Body:
This is little approach from modern grid layout. If you try you can manipulate grid row and column easily! Here is an example....

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 40px;
}

.wrapper {
  margin: 0 0 20px 0;
  width: 500px;
  height: 400px;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(3, 100px);
  justify-content: center;
  align-content: end;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.item1 {
  grid-column: 1 / 3;
  grid-row: 1/3;
}

.item2 {
  grid-column: 1 / 3;
  grid-row: 3 / 4;
}

.item3 {
  grid-column: 3 / 5;
}

.item4 {
  grid-column: 3 / 5;
  grid-row: 2/4;
}

.item5 {
  grid-column: 5 / 7;
  grid-row: 1/ 3;
}

.item6 {
  grid-column: 5 / 7;
  grid-row: 3/ 4;
}

<div class="wrapper">
  <div class="box item1">One</div>
  <div class="box item2">Two</div>
  <div class="box item3">Three</div>
  <div class="box item4">Four</div>
  <div class="box item5">Five</div>
  <div class="box item6">Six</div>
</div>


问:
Why do nullable numbers not preserve identity?
In kotlin nullable values are not preserving identity but equality:

```<code>val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'
</code>```

Why is this different ?

答:
a === b evaluates to true if and only if a and b point to the same
  object.

That's not true for boxedA === anotherBoxedA.

Kotlin - Equality

Body:
In kotlin nullable values are not preserving identity but equality:

val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'

Why is this different ?


问:
Multiple Eclipse projects in one Mercurial repository
I have a number of eclipse projects that I'd like to have in two separate hg repositories.

I've managed to do this by first creating the two hg repository using TortouiseHg and adding, committing my projects to each of the repositories first. By doing that I now have two hg repositories with two projects in each.

Next I clone that repositories in Eclipse using MercurialEclipse. The projects appear as expected in Eclipse.

Example 1:

```<code>Eclipse workspace
               |
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4
</code>```

But if I look in the directory structure it looks like this:

Example 2:

```<code>  c:--
     |
     |-workspace
               |
               hgRepository1
               |           |--.hg
               |           |--Project 1
               |           |--Project 2
               |
               |
               hgRepository2
                           |--.hg
                           |--Project 3
                           |--Project 4
</code>```

when I want it to look like this.

Example 3:

```<code>  c:--
     |
     |-workspace
               |--.hg
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4
</code>```

Is it possible to have a single Mercurial repository and somehow clone it and have the projects appear directly under workspace directory, and not in a subdirectory?

答: I don't quite understand. You cannot clone the repo to inside of itself. Why can't you just make a hard copy of Project1 and Project2, creating 3 and 4?</p>

Body:
I have a number of eclipse projects that I'd like to have in two separate hg repositories.

I've managed to do this by first creating the two hg repository using TortouiseHg and adding, committing my projects to each of the repositories first. By doing that I now have two hg repositories with two projects in each.

Next I clone that repositories in Eclipse using MercurialEclipse. The projects appear as expected in Eclipse.

Example 1:

Eclipse workspace
               |
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4

But if I look in the directory structure it looks like this:

Example 2:

  c:--
     |
     |-workspace
               |
               hgRepository1
               |           |--.hg
               |           |--Project 1
               |           |--Project 2
               |
               |
               hgRepository2
                           |--.hg
                           |--Project 3
                           |--Project 4

when I want it to look like this.

Example 3:

  c:--
     |
     |-workspace
               |--.hg
               |--Project 1
               |--Project 2
               |--Project 3
               |--Project 4

Is it possible to have a single Mercurial repository and somehow clone it and have the projects appear directly under workspace directory, and not in a subdirectory?


问:
Microsoft Dynamics CRM run script (or something similar) in background
I wrote a script that adds the values of field A and field B. It then writes the result in field C.

My problem now is that, as I'm using a script, it only runs if I the form is open. However, I need to run it whenever field A or field B changes, regardless whether the form is open or not. For example, if a workflow changes the value of field A in the background, I need the script to calculate the new value of field C in the background as well.

I know that scripts only run on forms. That's why I'm looking for an alternative for scripts. I am aware that I could normally solve this by using a workflow, but I can't access field A through the workflow (it's a calculated field).

Are there any other possibilities?

答:
1.Create an update message plugin with filtering attribute as A and B,
This will fire only when your form is updated and also only when attribute A and B has changed on that form.
2.write your logic in your plugin
3. choose async and sync depending on how frequent the changes are on A and B, ideally, I will use sync so that my value of C gets updated and be in sync all the time w.r.t A and B.</p>


问:
How to detect private browsing in iOS 11 Mobile Safari or MacOS High Sierra Safari?
On the new iOS 11 Safari and MacOS High Sierra Safari, that trick of seeing if window.localStorage.setItem('test', 1); (see https://stackoverflow.com/a/17741714/1330341) throws an error no longer works, because it no longer throws an error, and it also properly sets the localStorage item. Has anyone figured out any other way to check for private browsing mode in the new versions of Safari?

答:
I find a solution here:

https://gist.github.com/cou929/7973956#gistcomment-2272103

```<code>var isPrivate = false;
try {
   window.openDatabase(null, null, null, null);
} catch (_) {
   isPrivate = true;
}
alert((isPrivate ? 'You\'re' : 'You aren\'t')  + ' in private browsing mode');
</code>```

Hope it helps :)

Body:
I find a solution here:

https://gist.github.com/cou929/7973956#gistcomment-2272103

var isPrivate = false;
try {
   window.openDatabase(null, null, null, null);
} catch (_) {
   isPrivate = true;
}
alert((isPrivate ? 'You\'re' : 'You aren\'t')  + ' in private browsing mode');

Hope it helps :)


问:
How to make a particular peer 'endorsing peer' in hyperledger fabric v1.0

Having read the official doc, I know that endorsement policy is defined at chaincode instantiation using the '-P' flag.

The doc suggests something like this: -P "AND('Org1.member','Org2.member')" However, the 'member' field is not visible in the network-config.json.

Can anyone explain...

What is a 'member' representing in the 'Org1.member'

Can we directly mention peers like this: "AND('Org1.peer2',         'Org2.peer1')"`

Can we address peers with ip like this: "AND('localhost:7051',         'localhost:7052')"`

答:
What is a 'member' representing in the 'Org1.member'?

The member key word is a principal which identifies the role within the organization, so for example a member stays for regular entity, while for example admin, will mean that to endorse transaction one with admin rights has to sign it.

Can we directly mention peers like this: "AND('Org1.peer2', 'Org2.peer1')"`

No you cannot mention peer directly in the endorsement policies.

Can we address peers with ip like this: "AND('localhost:7051', 'localhost:7052')"`

And you cannot use endpoints neither.

In order to turn any peer to an endorsing peer for some chaincode, you have to install the chaincode on that peer, doing that will allow you to forward endorsement request to that peer. Of course assuming its part of the channel and chaincode is being instantiated in that channel.


问:
how to prevent undefined property when only one record found in Laravel
I was try to make a search function so i'm doing like this:

```<code>public function search(Request $request)
{
    $query = $request->query('q');

    $posts = DB::table('posts')->where('title', 'LIKE',  '%'.$query.'%')->get();

    return view('admin.dashboard.search')->with('users',$users)->with('posts',$posts);
}
</code>```

but when i try to fetch the result i got some errors like this:

Undefined property: stdClass::$user (View:
  E:\laragon\www\blog\resources\views\admin\dashboard\search.blade.php)

It was errors in this line:

```<code><td><?php echo e($post->user->name); ?></td>
</code>```

So how can i fix it?

答:
You can do something like

```<code><td>{{ $post->user->name ? $post->user->name : 'No User Found'  }}/td>
</code>```

This should work

Body:
I was try to make a search function so i'm doing like this:

public function search(Request $request)
{
    $query = $request->query('q');

    $posts = DB::table('posts')->where('title', 'LIKE',  '%'.$query.'%')->get();

    return view('admin.dashboard.search')->with('users',$users)->with('posts',$posts);
}

but when i try to fetch the result i got some errors like this:

Undefined property: stdClass::$user (View:
  E:\laragon\www\blog\resources\views\admin\dashboard\search.blade.php)

It was errors in this line:

<?php echo e($post->user->name); ?>

So how can i fix it?

Body:
You can do something like

<td>{{ $post->user->name ? $post->user->name : 'No User Found'  }}/td>

This should work


问:
How to catch error in RxJS 5.5
I am using Angular 5 along with RXJS 5.5

Before I could just do something like this

```<code>getProjectInfo(id): Observable<any> {
    const URL = `${this.API}/${id}`;
    return this.http.get(URL)
      .pipe(map(res => res)),
      catchError(this.handleServerError);
}

handleServerError(error: any) {
    console.log(error.error || error.json() || error);
    return Observable.throw(error.error || error.json() || error || 'Server error');
}
</code>```

But now I get this error

```<code>Error:(21, 5) TS2322:Type 'UnaryFunction<Observable<{}>, Observable<any>>' is not assignable to type 'Observable<any>'.
  Property '_isScalar' is missing in type 'UnaryFunction<Observable<{}>, Observable<any>>'.
</code>```

I've also tried this

```<code>getProjectInfo(id): Observable<any> {
    const URL = `${this.API}/${id}`;
    return this.http.get(URL)
      .pipe(map(res => res)),
      catchError(err => this.handleError('getProjInfo', URL));
}
private handleError(method: String, URL: string): any {
  return (err: any) => {
    const errMsg = `error in ${method}() retrieving ${URL}`;
    console.log(`${errMsg}:`, err);
    if (err instanceof HttpErrorResponse) {
      console.log(`status: ${err.status}, ${err.statusText}`);
    }
    return Observable.throw(errMsg);
  };
}
</code>```

What am I doing wrong?

答:
Keep in mind your brackets. You return pipe result and catchEror result divided by ,:

```<code>return this.http.get(URL)
  .pipe(map(res => res)),
  catchError(this.handleServerError);
</code>```

Place one bracket to own place:

```<code>return this.http.get(URL)
  .pipe(
    map(res => res),
    catchError(this.handleServerError)
  );
</code>```

Title: How to catch error in RxJS 5.5

Body:
I am using Angular 5 along with RXJS 5.5

Before I could just do something like this

getProjectInfo(id): Observable<any> {
    const URL = `${this.API}/${id}`;
    return this.http.get(URL)
      .pipe(map(res => res)),
      catchError(this.handleServerError);
}

handleServerError(error: any) {
    console.log(error.error || error.json() || error);
    return Observable.throw(error.error || error.json() || error || 'Server error');
}

But now I get this error

Error:(21, 5) TS2322:Type 'UnaryFunction<Observable<{}>, Observable<any>>' is not assignable to type 'Observable<any>'.
  Property '_isScalar' is missing in type 'UnaryFunction<Observable<{}>, Observable<any>>'.

I've also tried this

getProjectInfo(id): Observable<any> {
    const URL = `${this.API}/${id}`;
    return this.http.get(URL)
      .pipe(map(res => res)),
      catchError(err => this.handleError('getProjInfo', URL));
}
private handleError(method: String, URL: string): any {
  return (err: any) => {
    const errMsg = `error in ${method}() retrieving ${URL}`;
    console.log(`${errMsg}:`, err);
    if (err instanceof HttpErrorResponse) {
      console.log(`status: ${err.status}, ${err.statusText}`);
    }
    return Observable.throw(errMsg);
  };
}

What am I doing wrong?

Body:
Keep in mind your brackets. You return pipe result and catchEror result divided by ,:

return this.http.get(URL)
  .pipe(map(res => res)),
  catchError(this.handleServerError);

Place one bracket to own place:

return this.http.get(URL)
  .pipe(
    map(res => res),
    catchError(this.handleServerError)
  );


问:
query in mongoDb using JavaScript
This is my sample documents in DB.

```<code>{
    "_id":1,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":2,
    "object":{
        "featureOne":false,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":3,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}
</code>```

I want to get one object with "featureOne": true and another with "featureOne": false in a single query. I have knowledge on finding data using a particular key and value. But how can I get the data using same key of true and false values in a single query. Present I am using this code

```<code>db.collection(collectionName).find({"featureOne":true, {limit:1}).toArray(function(err, results) {
    db.collection(collectionName).find("featureOne":,false{limit:2}).toArray(function(err,res {
        console.log(results,res);
    });
});
</code>```

Is there any better way to achieve this?

答:
Using $aggregate, we can do this

Query to achieve the result

```<code>db.collection.aggregate([
    {$group:{"_id": {"featureOne":"$object.featureOne"},
             object:{$first:"$object"},
             origId:{$first:"$_id"}}
    },
    {$project:{_id:"$origId", object:"$object"}}
])
</code>```

$group and $project were used to get this result

Sample data

```<code>{ "_id" : 1, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 2, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 3, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 4, "object" : { "featureOne" : true, "featureTwo" : true, "featureThree" : false, "featureFour" : true } }
{ "_id" : 5, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : true } }
{ "_id" : 6, "object" : { "featureOne" : true, "featureTwo" : true, "featureThree" : false, "featureFour" : false } }
</code>```

After executing $group on this data we will be getting\

```<code>{ "_id" : { "featureOne" : false }, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : false }, "origId" : 2 }
{ "_id" : { "featureOne" : true }, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false }, "origId" : 1 }
</code>```

to make it presentable as it looks like the original collection we have to use $project, after executing the $project pipeline on our result we will be getting

```<code>{ "_id" : 2, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 1, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
</code>```

Title: query in mongoDb using JavaScript

Body:
This is my sample documents in DB.

{
    "_id":1,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":2,
    "object":{
        "featureOne":false,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}, {
    "_id":3,
    "object":{
        "featureOne":true,
        "featureTwo":false,
        "featureThree":false,
        "featureFour":false
    }
}

I want to get one object with "featureOne": true and another with "featureOne": false in a single query. I have knowledge on finding data using a particular key and value. But how can I get the data using same key of true and false values in a single query. Present I am using this code

db.collection(collectionName).find({"featureOne":true, {limit:1}).toArray(function(err, results) {
    db.collection(collectionName).find("featureOne":,false{limit:2}).toArray(function(err,res {
        console.log(results,res);
    });
});

Is there any better way to achieve this?

Body:
Using $aggregate, we can do this

Query to achieve the result

db.collection.aggregate([
    {$group:{"_id": {"featureOne":"$object.featureOne"},
             object:{$first:"$object"},
             origId:{$first:"$_id"}}
    },
    {$project:{_id:"$origId", object:"$object"}}
])

$group and $project were used to get this result

Sample data

{ "_id" : 1, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 2, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 3, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 4, "object" : { "featureOne" : true, "featureTwo" : true, "featureThree" : false, "featureFour" : true } }
{ "_id" : 5, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : true } }
{ "_id" : 6, "object" : { "featureOne" : true, "featureTwo" : true, "featureThree" : false, "featureFour" : false } }

After executing $group on this data we will be getting\

{ "_id" : { "featureOne" : false }, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : false }, "origId" : 2 }
{ "_id" : { "featureOne" : true }, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false }, "origId" : 1 }

to make it presentable as it looks like the original collection we have to use $project, after executing the $project pipeline on our result we will be getting

{ "_id" : 2, "object" : { "featureOne" : false, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }
{ "_id" : 1, "object" : { "featureOne" : true, "featureTwo" : false, "featureThree" : false, "featureFour" : false } }


问:
Copy from 2d dynamic char array to another 2d dynamic array in c
I wanted to copy the content of a two dimensional array into another two dimensional char array. I used the following for loop with memcpy but it is not working as desired. So I have two questions.

What is wrong with this code? and

Is there a way to do it without use of iteration?

```<code>for (int i = 0; i < count; i++) {
    memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));
}
</code>```

Both buf and buf_copy are 2d dynamic char arrays.

Edit: declarations of the arrays

```<code>char **buf;
char **buf_copy;
</code>```

EDIT 2: Here is how memory is allocated to them

```<code>void intit_buf()
{
    buf = (char**)malloc(BUFFER * sizeof(*buf));
    for (int i = 0; i < BUFFER; i++)
        buf[i] = (char*)malloc(sizeof(char) * 33);

    //initialize buf_copy
    buf_copy = (char**)malloc(BUFFER * sizeof(*buf_copy));
    for (int i = 0; i < BUFFER; i++)
        buf_copy[i] = (char*)malloc(sizeof(char) * 33);
}
</code>```

答:
What is wrong with this code?

The first and last parameters of the function call.

Change this:

```<code>memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));
</code>```

to this:

```<code>memcpy(buf_copy[i], buf[i], 33);
</code>```

since you need to give the size of the column, not the size of a pointer!

Moreover, notice that you need to pass buf_copy, just like you did for buf, without taking the address of it or something, since memcpy() expects pointers for its two first parameters, and buf_copy[i] and buf[i] are pointers already.

Is there a way to do it without use of iteration?

It cannot be done without ireation because malloc() may not have returned contigeous memory. Read more in C / C++ How to copy a multidimensional char array without nested loops?

PS: Unrelated to your problem, but in general: Do I cast the result of malloc? No!

Body:
I wanted to copy the content of a two dimensional array into another two dimensional char array. I used the following for loop with memcpy but it is not working as desired. So I have two questions.

What is wrong with this code? and

Is there a way to do it without use of iteration?

for (int i = 0; i < count; i++) {
    memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));
}

Both buf and buf_copy are 2d dynamic char arrays.

Edit: declarations of the arrays

char **buf;
char **buf_copy;

EDIT 2: Here is how memory is allocated to them

void intit_buf()
{
    buf = (char**)malloc(BUFFER * sizeof(*buf));
    for (int i = 0; i < BUFFER; i++)
        buf[i] = (char*)malloc(sizeof(char) * 33);

    //initialize buf_copy
    buf_copy = (char**)malloc(BUFFER * sizeof(*buf_copy));
    for (int i = 0; i < BUFFER; i++)
        buf_copy[i] = (char*)malloc(sizeof(char) * 33);
}

Body:
What is wrong with this code?

The first and last parameters of the function call.

Change this:

memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));

to this:

memcpy(buf_copy[i], buf[i], 33);

since you need to give the size of the column, not the size of a pointer!

Moreover, notice that you need to pass buf_copy, just like you did for buf, without taking the address of it or something, since memcpy() expects pointers for its two first parameters, and buf_copy[i] and buf[i] are pointers already.

Is there a way to do it without use of iteration?

It cannot be done without ireation because malloc() may not have returned contigeous memory. Read more in C / C++ How to copy a multidimensional char array without nested loops?

PS: Unrelated to your problem, but in general: Do I cast the result of malloc? No!


问:
Running mulitple process in Node JS
Okay so I'm trying to build a web service for twitter automation. I have build bots before that works only for a single account.

The service that I'm looking to build will enable users to register and then set up some preference (like follow users that tweets #ILoveProgramming).

My main question is - right now if I need to run the bot I just type "node bot.js" and the bot will run. How do I run multiple process for all the hundred users that'll be using my Web Service ?

答:
NodeJs provides clustering module which would spin up multiple process of your program.

It basically involves creating a master and workers processes.
The docs for it are available here

Also I would suggest using process managers like pm2, which provide support for clustering and manage them very well. You could read about it here.

With pm2, doing something like

```<code>pm2 start bot.js -i max
</code>```

would start the bot server for all the cpu's/cores in your device.

Title: Running mulitple process in Node JS

Body:
NodeJs provides clustering module which would spin up multiple process of your program.

It basically involves creating a master and workers processes.
The docs for it are available here

Also I would suggest using process managers like pm2, which provide support for clustering and manage them very well. You could read about it here.

With pm2, doing something like

pm2 start bot.js -i max

would start the bot server for all the cpu's/cores in your device.


问:
crop and upload photo using croppie.js ajax php jquery
I'm using a jquery crop plugin called croppie to crop an image before the user uploads the image into the database but for some reason, the image is inserted into the upload folder but the sql query doesn't work. Pls could anyone help me out

the html markup.

```<code><input type="file" id="upload">
<br/>
<button class="btn btn-success upload-result">Upload Image</button>
</code>```

The js for cropping and sending the photo to testcrop.php with ajax.

```<code>$uploadCrop = $('#upload-demo').croppie({
    enableExif: true,
    viewport: {
        width: 200,
        height: 200,
        type: 'circle'
    },
    boundary: {
        width: 300,
        height: 300
    }
});

$('#upload').on('change', function () {
    var reader = new FileReader();
    reader.onload = function (e) {
        $uploadCrop.croppie('bind', {
            url: e.target.result
        }).then(function () {
            console.log('jQuery bind complete');
        });

    }
    reader.readAsDataURL(this.files[0]);
});

$('.upload-result').on('click', function (ev) {
    $uploadCrop.croppie('result', {
        type: 'canvas',
        size: 'viewport'
    }).then(function (resp) {

        $.ajax({
            url: "components/testcrop.php",
            type: "POST",
            data: {"image": resp},
            success: function (data) {
                if (data == 'Image Uploaded Successfully') {
                    html = '<img src="' + resp + '" />';
                    $("#upload-demo-i").html(html);
                } else {
                    $("body").append("<div class='upload-error'>" + data + "</div>");

                }
            }
        });
    });
});
</code>```

testcrop.php

```<code><?php
session_start();
require('../includes/settings.php');

$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time() . '.png';

if ((($data == "image/gif") || ($data == "image/jpeg") || ($data == "image/jpg") || ($data == "image/pjpeg") || ($data == "image/x-png") || ($data == "image/png"))) {

    if ($data["error"] > 0) {
        echo "No Picture upload";
    } else {

        if (file_exists("../uploads/" . $data)) {
            echo 'This picture already exists';
        } else {
            file_put_contents('upload/' . $imageName, $data);
            $sql = "INSERT INTO " . $table_for_images . " (user_id, img_name, img_loc)
                       VALUES
                       ('" . $_SESSION['user_id'] . "',
                       '" . $ImageName . "',
                       'uploads/" . $data . "')";

            if (mysqli_query($con, $sql)) {
                echo "Image Uploaded Successfully";
            } else {
                echo('Something went wrong');
            }
        }
    }
} else {
    echo('Something went wrong');
}
?>
</code>```

答:
You just have to replace $data with $imageName in your query.</p>

```<code>$sql = "INSERT INTO " . $table_for_images . " (user_id, img_name, img_loc)
                   VALUES
                   ('" . $_SESSION['user_id'] . "',
                   '" . $ImageName . "',
                   'uploads/" . $ImageName . "')";
</code>```

Body:
I'm using a jquery crop plugin called croppie to crop an image before the user uploads the image into the database but for some reason, the image is inserted into the upload folder but the sql query doesn't work. Pls could anyone help me out

the html markup.

<input type="file" id="upload">

<button class="btn btn-success upload-result">Upload Image</button>

The js for cropping and sending the photo to testcrop.php with ajax.

$uploadCrop = $('#upload-demo').croppie({
    enableExif: true,
    viewport: {
        width: 200,
        height: 200,
        type: 'circle'
    },
    boundary: {
        width: 300,
        height: 300
    }
});

$('#upload').on('change', function () {
    var reader = new FileReader();
    reader.onload = function (e) {
        $uploadCrop.croppie('bind', {
            url: e.target.result
        }).then(function () {
            console.log('jQuery bind complete');
        });

    }
    reader.readAsDataURL(this.files[0]);
});

$('.upload-result').on('click', function (ev) {
    $uploadCrop.croppie('result', {
        type: 'canvas',
        size: 'viewport'
    }).then(function (resp) {

        $.ajax({
            url: "components/testcrop.php",
            type: "POST",
            data: {"image": resp},
            success: function (data) {
                if (data == 'Image Uploaded Successfully') {
                    html = '';
                    $("#upload-demo-i").html(html);
                } else {
                    $("body").append("
" + data + "
");

                }
            }
        });
    });
});

testcrop.php

<?php
session_start();
require('../includes/settings.php');

$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time() . '.png';

if ((($data == "image/gif") || ($data == "image/jpeg") || ($data == "image/jpg") || ($data == "image/pjpeg") || ($data == "image/x-png") || ($data == "image/png"))) {

    if ($data["error"] > 0) {
        echo "No Picture upload";
    } else {

        if (file_exists("../uploads/" . $data)) {
            echo 'This picture already exists';
        } else {
            file_put_contents('upload/' . $imageName, $data);
            $sql = "INSERT INTO " . $table_for_images . " (user_id, img_name, img_loc)
                       VALUES
                       ('" . $_SESSION['user_id'] . "',
                       '" . $ImageName . "',
                       'uploads/" . $data . "')";

            if (mysqli_query($con, $sql)) {
                echo "Image Uploaded Successfully";
            } else {
                echo('Something went wrong');
            }
        }
    }
} else {
    echo('Something went wrong');
}
?>

Body:
You just have to replace $data with $imageName in your query.

$sql = "INSERT INTO " . $table_for_images . " (user_id, img_name, img_loc)
                   VALUES
                   ('" . $_SESSION['user_id'] . "',
                   '" . $ImageName . "',
                   'uploads/" . $ImageName . "')";


问:
How to upload an image as drag and drop?
Here is my code:

```<code>$(".modal-dropzone-img").click(function() {
    $(this).siblings(".upload_image").trigger( "click" );
})

$('.upload_image').on('change', function () {
    var files = $(this)[0].files;
    processFileUpload(files, $(this).closest('form'));
    return false;
});

$('.modal-dropzone-img').on('drop dragdrop', function (e) {
    var files = e.originalEvent.dataTransfer.files;
    processFileUpload(files, $(this).closest('form'));
    return false;
});

function processFileUpload(droppedFiles, frm) {
    var uploadFormData = new FormData(frm[0]);
    uploadFormData.append("file", droppedFiles);
    console.log(droppedFiles);

    $.ajax({
        url: base_url +  frm.attr('action'),
        type: frm.attr('method'),
        data: uploadFormData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (arr) {
            // File Uploaded
        }
    });
}
</code>```

My code works as well when I click on the container, but it doesn't work when I drag the image into the container and leave it there. What's wrong?

Noted that the result of console.log(droppedFiles); seems good and identical for both cases (click, drag-and-drop)

答:
  (function(window) {
    function triggerCallback(e, callback) {
      if(!callback || typeof callback !== 'function') {
        return;
      }
      var files;
      if(e.dataTransfer) {
        files = e.dataTransfer.files;
      } else if(e.target) {
        files = e.target.files;
      }
      callback.call(null, files);
    }
    function makeDroppable(ele, callback) {
      var input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('multiple', true);
      input.style.display = 'none';
      input.addEventListener('change', function(e) {
        triggerCallback(e, callback);
      });
      ele.appendChild(input);

      ele.addEventListener('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.add('dragover');
      });

      ele.addEventListener('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.remove('dragover');
      });

      ele.addEventListener('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.remove('dragover');
        triggerCallback(e, callback);
      });

      ele.addEventListener('click', function() {
        input.value = null;
        input.click();
      });
    }
    window.makeDroppable = makeDroppable;
  })(this);
  (function(window) {
    makeDroppable(window.document.querySelector('.demo-droppable'), function(files) {

      var output = document.querySelector('.output');
      output.innerHTML = '';
      for(var i=0; i<files.length; i++) {
        if(files[i].type.indexOf('image/') === 0) {
          output.innerHTML += '';
        }
        output.innerHTML += '
'+files[i].name+'
';
      }
    });
  })(this);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .demo-droppable {
    background: #08c;
    color: #fff;
    padding: 100px 0;
    text-align: center;
  }
  .demo-droppable.dragover {
    background: #00CC71;
  }</code>```

Drag files here or click to upload

```

Hope this helps.

Body:
Here is my code:

$(".modal-dropzone-img").click(function() {
    $(this).siblings(".upload_image").trigger( "click" );
})

$('.upload_image').on('change', function () {
    var files = $(this)[0].files;
    processFileUpload(files, $(this).closest('form'));
    return false;
});

$('.modal-dropzone-img').on('drop dragdrop', function (e) {
    var files = e.originalEvent.dataTransfer.files;
    processFileUpload(files, $(this).closest('form'));
    return false;
});

function processFileUpload(droppedFiles, frm) {
    var uploadFormData = new FormData(frm[0]);
    uploadFormData.append("file", droppedFiles);
    console.log(droppedFiles);

    $.ajax({
        url: base_url +  frm.attr('action'),
        type: frm.attr('method'),
        data: uploadFormData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (arr) {
            // File Uploaded
        }
    });
}

My code works as well when I click on the container, but it doesn't work when I drag the image into the container and leave it there. What's wrong?

Noted that the result of console.log(droppedFiles); seems good and identical for both cases (click, drag-and-drop)

Body:
  (function(window) {
    function triggerCallback(e, callback) {
      if(!callback || typeof callback !== 'function') {
        return;
      }
      var files;
      if(e.dataTransfer) {
        files = e.dataTransfer.files;
      } else if(e.target) {
        files = e.target.files;
      }
      callback.call(null, files);
    }
    function makeDroppable(ele, callback) {
      var input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('multiple', true);
      input.style.display = 'none';
      input.addEventListener('change', function(e) {
        triggerCallback(e, callback);
      });
      ele.appendChild(input);

      ele.addEventListener('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.add('dragover');
      });

      ele.addEventListener('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.remove('dragover');
      });

      ele.addEventListener('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        ele.classList.remove('dragover');
        triggerCallback(e, callback);
      });

      ele.addEventListener('click', function() {
        input.value = null;
        input.click();
      });
    }
    window.makeDroppable = makeDroppable;
  })(this);
  (function(window) {
    makeDroppable(window.document.querySelector('.demo-droppable'), function(files) {

      var output = document.querySelector('.output');
      output.innerHTML = '';
      for(var i=0; i<files.length; i++) {
        if(files[i].type.indexOf('image/') === 0) {
          output.innerHTML += '<img width="200" src="' + URL.createObjectURL(files[i]) + '" />';
        }
        output.innerHTML += '<p>'+files[i].name+'</p>';
      }
    });
  })(this);

  .demo-droppable {
    background: #08c;
    color: #fff;
    padding: 100px 0;
    text-align: center;
  }
  .demo-droppable.dragover {
    background: #00CC71;
  }

<div class="demo-droppable">
  <p>Drag files here or click to upload</p>
</div>
<div class="output"></div>

Hope this helps.


问:
Import to the same Subversion repository directory multiple times?
For a number of reasons, the canonical source of some files I have can't be a working copy of the repository (the Subversion server is behind an inaccessible firewall, and the data doesn't natively exist in the file system in my preferred structure). So, I wrote a tool that downloads the data, generates a directory structure from it, and then uses SharpSvn to import the result into the repository. This works… the first time. The second time, of course, a directory of that name already exists in the repository, and I can't import again.

Instead, I could:

Delete the directory, then import. I haven't tested this, but aside from sounding stupid, it probably also deletes the revision history of the respective files, regarding the new ones as entirely different.

See if the directory exists, check it out, remotely delete the files that no longer exist in the canonical source, then replace the remainder and commit. This would probably work, but sounds error-prone and needlessly difficult.

Is my assumption correct that deleting files will mark new ones of the same ways as different files? Is there an easier way than the second approach?

答:
Since you can't overwrite the directories or you'll destroy the .svn directory and lose all the repository information, you have to copy the files over but only create new directories.  This is how I would do that, from within the subversion working copy you want to update:

```<code>(cd <newdirectory> ; tar -cf - * ) | tar -xf -
</code>```

Granted you need a Unix-y system.  It should work with Cygwin, unless Windows does something particularly bizarre with overwriting folders at the system level.

OwnerDisplayName: Sören Kuklau

Body:
Since you can't overwrite the directories or you'll destroy the .svn directory and lose all the repository information, you have to copy the files over but only create new directories.  This is how I would do that, from within the subversion working copy you want to update:

(cd <newdirectory> ; tar -cf - * ) | tar -xf -

Granted you need a Unix-y system.  It should work with Cygwin, unless Windows does something particularly bizarre with overwriting folders at the system level.

OwnerDisplayName: Otto


问:
Get data from dynamically added input
I have an input field where the user enters article ID and compare.
On first application load, the user has by default three input field, but he can dynamically add more inputs.My problem is, how to get the entered value of dynamically added inputs and send them to URL
for example like this (I know how to put id's to URL, this is only for showing what I need)
'https://someurl.com/' + ID + '/someurl'

I try to make function where I pass entered value to controller but I get UNDEFINED

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

 $scope.choices = [{id: ''}, {id: ''}, {id: ''}];

 $scope.addNewChoice = function() {
  var newItemNo = $scope.choices.length+1;
  $scope.choices.push({'id':newItemNo});
 };

 $scope.showChoiceLabel = function (choice) {
  return choice.id === $scope.choices[0].id;
 }

 $scope.submitChoice = function (name) {
  alert('url ' + name + ' url');
 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 font-family:Arial;
 color:#333;
}
label {
 font-weight:bold;
}
#choicesDisplay {
 margin-top:1em;
}
.form-group {
 width:70%;clear:both;
}
.form-group input {
 float:right;
 width:60%;
 padding:.3em;
}
button {
 background-color:#3f7ebc;
 color:white;
 padding: .5em .7em .5em .7em;
 font-weight:bold;
 border:none;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Custom Plunker</title>

  <link rel="stylesheet" href="style.css" />

   Choices
   <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
   <input type="text" ng-model="choice.name" name="" placeholder="enter id">
  <button ng-click="submitChoice(choice.name)">Submit</button>

   {{ choices }}

```

答:
choice.name in submit choice is undefined because your submit button is outside the scope of ng-repeat

```<code><div class="form-group" data-ng-repeat="choice in choices">
          <label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
          <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
          <input type="text" ng-model="choice.name" name="" placeholder="enter id">
</div>

<button ng-click="submitChoice(choice.name)">Submit</button>
</code>```

If you want to submit 1 choice you can place your button inside ng-repeat. If you want to submit all choices you can iterate through choices in your controller.

Update

you can use below code to iterate through choices and submit if name is not undefined

```<code>angular.forEach($scope.choices, function(value, key) {
    if(value.name != undefined)
        $scope.submitChoice(value.name)
});
</code>```

Title: Get data from dynamically added input

Body:
I have an input field where the user enters article ID and compare.
On first application load, the user has by default three input field, but he can dynamically add more inputs.My problem is, how to get the entered value of dynamically added inputs and send them to URL
for example like this (I know how to put id's to URL, this is only for showing what I need)
'https://someurl.com/' + ID + '/someurl'

I try to make function where I pass entered value to controller but I get UNDEFINED

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

 $scope.choices = [{id: ''}, {id: ''}, {id: ''}];

 $scope.addNewChoice = function() {
  var newItemNo = $scope.choices.length+1;
  $scope.choices.push({'id':newItemNo});
 };

 $scope.showChoiceLabel = function (choice) {
  return choice.id === $scope.choices[0].id;
 }

 $scope.submitChoice = function (name) {
  alert('url ' + name + ' url');
 }
});

body {
 font-family:Arial;
 color:#333;
}
label {
 font-weight:bold;
}
#choicesDisplay {
 margin-top:1em;
}
.form-group {
 width:70%;clear:both;
}
.form-group input {
 float:right;
 width:60%;
 padding:.3em;
}
button {
 background-color:#3f7ebc;
 color:white;
 padding: .5em .7em .5em .7em;
 font-weight:bold;
 border:none;
}

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Custom Plunker</title>

  <link rel="stylesheet" href="style.css" />

   Choices
   <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
   <input type="text" ng-model="choice.name" name="" placeholder="enter id">
  <button ng-click="submitChoice(choice.name)">Submit</button>

   {{ choices }}

Body:
choice.name in submit choice is undefined because your submit button is outside the scope of ng-repeat

<div class="form-group" data-ng-repeat="choice in choices">
          <label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
          <button ng-show="$last" ng-click="addNewChoice()">Add another choice</button>
          <input type="text" ng-model="choice.name" name="" placeholder="enter id">
</div>

<button ng-click="submitChoice(choice.name)">Submit</button>

If you want to submit 1 choice you can place your button inside ng-repeat. If you want to submit all choices you can iterate through choices in your controller.

Update

you can use below code to iterate through choices and submit if name is not undefined

angular.forEach($scope.choices, function(value, key) {
    if(value.name != undefined)
        $scope.submitChoice(value.name)
});


问:
Javascript - Replace all with regex
I want to replace some spaces between some parenthesis with regex. If I use regex only replace some spaces (only unique pairs).

The string may be have others spaces, but I want only the spaces between paranthesis.

```<code>var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s\)/g, "))");
console.log(mystring);
</code>```

Output is:

```<code>) ) ) ) ) )
)) )) ))
</code>```

But I want to have this output:

```<code>) ) ) ) ) )
))))))
</code>```

答:
The problem is that by consuming the ) ), you no longer have the leading ) when looking at the next part of the string.

Instead of replacing both ), use a positive lookahead assertion to replace only the first and the spaces after it if they're followed by another ):

```<code>mystring = mystring.replace(/\)\s(?=\))/g, ")");
//                  Lookahead ---^^^^^^     ^--- only one ) in replacement
</code>```

Live Example:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s(?=\))/g, ")");
console.log(mystring);```

Title: Javascript - Replace all with regex

Body:
I want to replace some spaces between some parenthesis with regex. If I use regex only replace some spaces (only unique pairs).

The string may be have others spaces, but I want only the spaces between paranthesis.

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s\)/g, "))");
console.log(mystring);

Output is:

) ) ) ) ) )
)) )) ))

But I want to have this output:

) ) ) ) ) )
))))))

Body:
The problem is that by consuming the ) ), you no longer have the leading ) when looking at the next part of the string.

Instead of replacing both ), use a positive lookahead assertion to replace only the first and the spaces after it if they're followed by another ):

mystring = mystring.replace(/\)\s(?=\))/g, ")");
//                  Lookahead ---^^^^^^     ^--- only one ) in replacement

Live Example:

var mystring = ") ) ) ) ) )";
console.log(mystring);
mystring = mystring.replace(/\)\s(?=\))/g, ")");
console.log(mystring);