问:
Jobtastic/Celery/RabbitMQ - AsyncResult is always PENDING
I am using Django, Celery, and Jobtastic to try to set up some tasks that I will be polling for on my main webapp. I am using RabbitMQ as my broker.

The problem is that while the tasks show up properly after starting Celery, attempting to get the status as shown below:

```<code>def get_state(request, task_id):
    if request.is_ajax():
        task = AsyncResult(task_id)
        data = task.result or task.state
        print(data)
        json_data = json.dumps(data)
        return JsonResponse(json_data)
</code>```

I am unable to get any other status but PENDING. My terminal shows that the task has completed yet I still get a PENDING status. I have tried changing the backend below under CELERY_RESULT_BACKEND to multiple backends, including DJCelery, AMQP, and RPC. They all show up properly when launching Celery so I know they are being registered. I also try to start Celery with the --pools=solo option, as suggested for Windows platforms but have not had any luck with that either. Below is my celery.py file where I initialize the celery app.

```<code>from __future__ import absolute_import

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arbitrage.settings')

from django.conf import settings  # noqa

app = Celery('arbitrage')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.conf.update(
    CELERY_RESULT_BACKEND='amqp',
    BROKER_URL='amqp://'
)
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))
</code>```

I instantiate Celery with the following command:

```<code>celery -A arbitrage worker -l info --pool=solo
</code>```

Any help would be greatly appreciated, I am on Celery 3.1.5 as Jobtastic will not function with Celery version >4.0.

答: Ended up being something completely unrelated. The task_id was invalid when passing it into AsyncResult, thus I was always getting a Pending status since Pending means the status is not known, even for bogus id values.</p>

Body:
I am using Django, Celery, and Jobtastic to try to set up some tasks that I will be polling for on my main webapp. I am using RabbitMQ as my broker.

The problem is that while the tasks show up properly after starting Celery, attempting to get the status as shown below:

def get_state(request, task_id):
    if request.is_ajax():
        task = AsyncResult(task_id)
        data = task.result or task.state
        print(data)
        json_data = json.dumps(data)
        return JsonResponse(json_data)

I am unable to get any other status but PENDING. My terminal shows that the task has completed yet I still get a PENDING status. I have tried changing the backend below under CELERY_RESULT_BACKEND to multiple backends, including DJCelery, AMQP, and RPC. They all show up properly when launching Celery so I know they are being registered. I also try to start Celery with the --pools=solo option, as suggested for Windows platforms but have not had any luck with that either. Below is my celery.py file where I initialize the celery app.

from __future__ import absolute_import

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arbitrage.settings')

from django.conf import settings  # noqa

app = Celery('arbitrage')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.conf.update(
    CELERY_RESULT_BACKEND='amqp',
    BROKER_URL='amqp://'
)
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

I instantiate Celery with the following command:

celery -A arbitrage worker -l info --pool=solo

Any help would be greatly appreciated, I am on Celery 3.1.5 as Jobtastic will not function with Celery version >4.0.


来源: stackexchange

问:
Oracle Preparations
I am new to oracle.can anyone tell me the books and web sites suitable to learn oracle ?</p>

ContentLicense: CC BY-SA 2.5

Title: Oracle Preparations


问:
Place an image between custom lines in a plot in python
What I would like is to use specified functions or lines to create the border of the images, and then inside the borders place custom images.

I used fill between as an example, but maybe there is an easier way of achieving this. This is what I have in mind:

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

x   = np.linspace(0,100,1000)
y   = (3 + np.sin(x/5.)) * np.exp(-abs(x-50)/25.)*10

x2  = np.linspace(20,40,1000)
y2  = np.sqrt(100 - (x2 - 30)**2) + 40
y3  = -np.sqrt(100 - (x2 - 30)**2) + 40

plt.figure()
ax1 = plt.subplot(1,1,1, aspect='equal')
plt.fill_between(x=x, y1=y, y2=0,  alpha=0.5, color='orange', linewidth=3)
plt.fill_between(x=x2, y1=y2, y2=y3,  alpha=0.5, color='green', linewidth=3)
ax1.axis('off')
</code>```

the output of that code is this image, what I have:

and I would like something like this, what I want:

Please have in mind that I would like to have a border around the image that I can customize it, and if I have more than one fillbetween, I can choose what to put inside the different curves.
And also if its possible to respect the axis ratio of the image so its shape doesn't get distorted when I place it in the plot.

答:
There are a lot of different ways to obtain an image clipped to some shape. I personally like to use of an OffsetImage inside an AnnotationBbox. In the solution below a Patch is used as a clip_path for the image. If the input to the function is a Path, it is converted to a patch first.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

plt.figure()
ax1 = plt.subplot(1,1,1, aspect='equal')
ax1.axis('off')

def img_to_path( fn, path, zoom=0.72, ax = None, **kwargs):
    if ax==None: ax=plt.gca()
    kwargs.pop("facecolor", None)
    im = plt.imread(fn, format='png')
    if type(path) == Path:
        xmin = path.vertices[:,0].min()
        ymin = path.vertices[:,1].min()
        patch = PathPatch(path, facecolor='none', zorder=3, **kwargs)
    else:
        patch = path
        xmin = patch.get_verts()[:,0].min()
        ymin = patch.get_verts()[:,1].min()

    ax.add_patch(patch)
    imagebox = OffsetImage(im, zoom=zoom, clip_path=patch, zorder=-10)
    boxoffset = np.array(im.shape[:2][::-1])/2.*zoom
    ab = AnnotationBbox(imagebox, (xmin,ymin), xycoords='data',
                        xybox=boxoffset, boxcoords="offset points",
                        pad=0, frameon=False)
    ax.add_artist(ab)

# two images
fn1 = "data/raspberries.png"
fn2 = "data/blueberries.png"

# use a Path
x   = np.linspace(0,100,1000)
y   = (3 + np.sin(x/5.)) * np.exp(-abs(x-50)/25.)*10
x = np.append(x,[x[-1],x[0], x[0]])
y = np.append(y,[0,0,y[0]])
path = Path(np.c_[x,y], [1]+[2]*(len(x)-2)+[79])
img_to_path(fn1, path, edgecolor="red", lw=4, ax=ax1 )

# use a Patch
circ = plt.Circle((30,40), 10, edgecolor="gold", lw=13, zorder=3 )
img_to_path(fn2, circ, zoom=0.15, ax=ax1 )

ax1.relim()
ax1.autoscale_view()
plt.show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What I would like is to use specified functions or lines to create the border of the images, and then inside the borders place custom images.

I used fill between as an example, but maybe there is an easier way of achieving this. This is what I have in mind:

import matplotlib.pyplot as plt
import numpy as np

x   = np.linspace(0,100,1000)
y   = (3 + np.sin(x/5.)) * np.exp(-abs(x-50)/25.)*10

x2  = np.linspace(20,40,1000)
y2  = np.sqrt(100 - (x2 - 30)**2) + 40
y3  = -np.sqrt(100 - (x2 - 30)**2) + 40

plt.figure()
ax1 = plt.subplot(1,1,1, aspect='equal')
plt.fill_between(x=x, y1=y, y2=0,  alpha=0.5, color='orange', linewidth=3)
plt.fill_between(x=x2, y1=y2, y2=y3,  alpha=0.5, color='green', linewidth=3)
ax1.axis('off')

the output of that code is this image, what I have:

and I would like something like this, what I want:

Please have in mind that I would like to have a border around the image that I can customize it, and if I have more than one fillbetween, I can choose what to put inside the different curves.
And also if its possible to respect the axis ratio of the image so its shape doesn't get distorted when I place it in the plot.

Body:
There are a lot of different ways to obtain an image clipped to some shape. I personally like to use of an OffsetImage inside an AnnotationBbox. In the solution below a Patch is used as a clip_path for the image. If the input to the function is a Path, it is converted to a patch first.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

plt.figure()
ax1 = plt.subplot(1,1,1, aspect='equal')
ax1.axis('off')

def img_to_path( fn, path, zoom=0.72, ax = None, **kwargs):
    if ax==None: ax=plt.gca()
    kwargs.pop("facecolor", None)
    im = plt.imread(fn, format='png')
    if type(path) == Path:
        xmin = path.vertices[:,0].min()
        ymin = path.vertices[:,1].min()
        patch = PathPatch(path, facecolor='none', zorder=3, **kwargs)
    else:
        patch = path
        xmin = patch.get_verts()[:,0].min()
        ymin = patch.get_verts()[:,1].min()

    ax.add_patch(patch)
    imagebox = OffsetImage(im, zoom=zoom, clip_path=patch, zorder=-10)
    boxoffset = np.array(im.shape[:2][::-1])/2.*zoom
    ab = AnnotationBbox(imagebox, (xmin,ymin), xycoords='data',
                        xybox=boxoffset, boxcoords="offset points",
                        pad=0, frameon=False)
    ax.add_artist(ab)

# two images
fn1 = "data/raspberries.png"
fn2 = "data/blueberries.png"

# use a Path
x   = np.linspace(0,100,1000)
y   = (3 + np.sin(x/5.)) * np.exp(-abs(x-50)/25.)*10
x = np.append(x,[x[-1],x[0], x[0]])
y = np.append(y,[0,0,y[0]])
path = Path(np.c_[x,y], [1]+[2]*(len(x)-2)+[79])
img_to_path(fn1, path, edgecolor="red", lw=4, ax=ax1 )

# use a Patch
circ = plt.Circle((30,40), 10, edgecolor="gold", lw=13, zorder=3 )
img_to_path(fn2, circ, zoom=0.15, ax=ax1 )

ax1.relim()
ax1.autoscale_view()
plt.show()


问:
Spring Cloud - how to allow access to endpoint for specific microservice only?
I have simple microservice architecture:

edge service

service registry

auth service (I am using JWT and OAuth2)

user service

frontend and some core services

When the user tries to log in, the credentials are passing from edge service to auth service. Auth service fetches user's data from user service (using @FeignClient) and if username/password matches, it generates token. Nothing fancy about it.

There a 'little' problem with this approach: the endpoint /api/user/{username} in user service, which is used by auth service to fetch user's data, might be used by any user to get any other user's data (password, roles etc.). The one solution would be somehow create JWT token for auth-service with role AUTH_SERVICE and at the user service side check JWT and if the role is different than AUTH_SERVICE reject the request.

Are there any other solutions?

EDIT

I thought that my design is quite common but apparently I should have been more specific in the first place:

Auth-servie is my Authorization Server and the other services are Resource servers

I use API gateway pattern and my auth-service is also behin proxy

After the client application obtains JWT it adds it to every request and based on that the authentication and authorization is performed; every Resource server has a public key which is used to verify signature; if it's valid, the service knows that JWT has been generated by trusted auth-service and the service based on JWT creates OAuth2Authenication object which contains all the user information

EDIT2:

I ended up merging auth-service to user-service, which was the suggestion given from a couple of SO users. After thinking about it it seemed unnecessary to have a seperate auth-service for just JWT generation. I've accepted @Abhijit Sarkar answer because it has some valid points even though he wasn't right about additional call to auth-service to verify validity of the token.

答:
Looks to me that you split your services too thin; this happens, and with time, you start to realize that the services need to be more coarse-grained because of maintenance and performance issues. The cost of another HTTP call from auth to user service, and the overhead of maintaining inter-service auth is not trivial.

IMO, user service can exist for other user information, like address etc if those exist, but auth service should be responsible for managing its own data. This is exactly why Spring Security has a UserDetailsService.

This is really a design choice whether the user credentials and other user information should be in the same table, or even the same database. Different people will give you different answers, but in my opinion and experience, a shared database between a small number of related services is acceptable, especially because these tables are gonna be related by a foreign key (userId). Distributed transaction is pure evil with microservices so I'm not even going there. When you delete/update a user, go for eventual consistency using events.

Edit:

After chatting with the OP, I learned that user service is really the OAuth resource server in his design. It's not clear to him, and thus to me, where is the OAuth authorization server. Regardless, I stand by my suggestion to merge the user service and the auth service.


问:
What is the default color space for UIColor?
I can not find an article or a document describing which color space should be used for RGB values when initialising an instance from UIColor class.

The article Getting the right colors in your ios app says we should use Generic RGB. On the other hand, I have found several posts saying that we should definitely use sRGB on iOS.

It seems the default color space is sRGB as written here in CGColorSpace Reference

There is a new color space called "Display P3" used in the iPad Pro and iPhone 7.  The profile in the existing image resources has to be converted to the Display P3. For Digital Color Meter app the P3 profile has to be selected in order to get "Display P3" RGB values. See the screenshot.

答:
I wrote a blog post that explains this in detail:

http://www.vsanthanam.com/writing/2017/7/6/colors-in-ios-ensuring-consistency-between-designs-interface-builder-and-uicolor

Essentially, while Sketch uses a custom color picker that assumes sRGB color components, Xcode's color pick does not.

UIColor's most common factory method +colorWithRed:green:blue:alpha: assumes the sRGB Color Space (Extended sRGB if linked with iOS 10.x), but it also has another factory method, colorWithDisplayP3Red:green:blue:alpha: which will take in your Display P3 color space RGBA components, but stores them internally as translated values with a reference to the sRGB color space.

As always, take a look at Apple's documentation on UIColor for more info:

https://developer.apple.com/documentation/uikit/uicolor?changes=latest_minor

Interestingly enough, AppKit's UIColor counterpart, NSColor, supports way more flexibility with more available factory methods (including one designed with a custom color space specifically to mimic UIColor's +colorWithRed:green:blue:alpha: behavior). I'm not sure why UIColor is more limited.


问:
Python "Function call with parameter: Converting measurements?"
I am taking my first programming course, so my apologies if this is a dumb question/possibly classified by the wrong category on this site. One of the exercise problems I am working on is the following:

Define a function print_total_inches, with parameters num_feet and num_inches, that prints the total number of inches. Note: There are 12 inches in a foot. Ex:

   print_total_inches(5, 8) prints:

Total inches: 68

The photo attached is the code that I did along with the error that I received. Any help/resources are greatly appreciated. Thanks!

答:
```<code>def print_total_inches(num_feet, num_inches):
    totalinches = (12*num_feet) + num_inches
    print('total inches:' + str(totalinches))

print_total_inches(5, 8)
</code>```

You do not need to return, as your function name says print_total_inches

Alternatively you can use format as well to print

print('total inches:{0}'.format(total_inches))

Body:
def print_total_inches(num_feet, num_inches):
    totalinches = (12*num_feet) + num_inches
    print('total inches:' + str(totalinches))

print_total_inches(5, 8)

You do not need to return, as your function name says print_total_inches

Alternatively you can use format as well to print

print('total inches:{0}'.format(total_inches))


问:
Display Array in a JTextArea with ability to scroll
I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.

```<code>public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;

// this is called in my initComponent method to create both
    textAreaDisplay = new JTextArea();

    for (Object obj : lake)
    {
        textAreaDisplay.append(obj.toString() + " ");
    }

    spDisplay = new JScrollPane(textAreaDisplay);

    textAreaDisplay.setLineWrap(true);
    textAreaDisplay.setWrapStyleWord(true);
    spDisplay.setPreferredSize(new Dimension(500, 500));

    // this is called in my createEvents method. After creating lakes in the database
    // it will display the else statement but it is empty

    btnDisplayLake.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try
            {
                if (lake.size() == 0)
                {
                    JOptionPane.showMessageDialog(null, "No Lakes in database!");
                }
                else
                    JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
            }
            catch (Exception e1)
            {

            }

        }
    });
</code>```

Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.

答:
I was setting textAreaDisplay before anything was entered into the ArrayList and it would not run again after anything was entered. I moved the for loop down and into the actionPerformed event and works well now.

```<code>    btnDisplayLake.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try
            {
                for (Object obj : lake)
                {
                    textAreaDisplay.append(obj.toString() + "\n");
                }
                if (lake.size() == 0)
                {
                    JOptionPane.showMessageDialog(null, "No Lakes in database!");
                }
                else
                    JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
            }
            catch (Exception e1)
            {
</code>```

Body:
I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.

public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;

// this is called in my initComponent method to create both
    textAreaDisplay = new JTextArea();

    for (Object obj : lake)
    {
        textAreaDisplay.append(obj.toString() + " ");
    }

    spDisplay = new JScrollPane(textAreaDisplay);

    textAreaDisplay.setLineWrap(true);
    textAreaDisplay.setWrapStyleWord(true);
    spDisplay.setPreferredSize(new Dimension(500, 500));

    // this is called in my createEvents method. After creating lakes in the database
    // it will display the else statement but it is empty

    btnDisplayLake.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try
            {
                if (lake.size() == 0)
                {
                    JOptionPane.showMessageDialog(null, "No Lakes in database!");
                }
                else
                    JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
            }
            catch (Exception e1)
            {

            }

        }
    });

Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.

Body:
I was setting textAreaDisplay before anything was entered into the ArrayList and it would not run again after anything was entered. I moved the for loop down and into the actionPerformed event and works well now.

    btnDisplayLake.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try
            {
                for (Object obj : lake)
                {
                    textAreaDisplay.append(obj.toString() + "\n");
                }
                if (lake.size() == 0)
                {
                    JOptionPane.showMessageDialog(null, "No Lakes in database!");
                }
                else
                    JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
            }
            catch (Exception e1)
            {


问:
Returning other related nodes when one of the Nodes is known
I have data in the form

```<code>(n:Node)-[HAS_ADDRESS]->(r:Address{name:'Goa'}),
(n:Node)-[HAS_ADDRESS]->(r:Address{name:'India'}),
(n:Node)-[HAS_ANCHOR]->(k:Keyword{name:'accounting'}),
(n:Node)-[HAS_ANCHOR]->(k:Keyword{name:'Keyword 2'}),
(n:Node)-[HAS_ANCHOR]->(k:Keyword{name:'Keyword 3'}),
(n:Node)-[HAS_PHOTO]->(ph:Photo{name:'photo1'}),
(n:Node)-[HAS_PHOTO]->(ph:Photo{name:'photo2'}),
etc...
</code>```

nodes are stored in the following format

```<code>(n:Node{name:'',rating:'',international_phone_number:''})
(ph:Photo{id:''})
(k:Keyword{name:''})
</code>```

I have the value of 'k' and 'n' so i used

```<code>MATCH (k:Keyword { name: 'accounting'})<-[:HAS_ANCHOR]-(p)-[:HAS_ADDRESS]->(l:Address),(p)-[:HAS_PHOTO]->(ph)
WHERE ph.crawl=1 AND l.name = 'Goa'
WITH p, l
MATCH (p)-[:HAS_ADDRESS]->(other_r:Address)
return p.name as name, p.rating as rating, p.formatted_address as address,p.international_phone_number as international_phone_number,collect(ph.photo_reference) as photos, l as locations, other_r as other_addresses
ORDER BY p.rating DESC
</code>```

I am clueless on how to get the node with all the details.

答:
Since you only know about "Node 1", you need to take "n" from the first match and use it to get the other peers of "r".

```<code>// your original query that matches n and r based on the known node r
MATCH (n:Node)->[k:HAS_ANCHOR]->(r:Node)
WHERE r.name = 'Node 1'

// use the result of n from the first query to find peers of r
WITH n, r
MATCH (n)-[:HAS_ANCHOR]->(other_r:Node)
RETURN n, r, other_r
</code>```

UPDATE
Based on comments, does this work?

```<code>// match the anchor based on the keyword
MATCH (k:Keyword { name: 'accounting'})<-[:HAS_ANCHOR]-(p)
WHERE (p)-[:HAS_ADDRESS]->(:Address {name: 'Goa'})

// optionally match and collect the photos
WITH p
OPTIONAL MATCH (p)-[:HAS_PHOTO]->(ph)
WHERE ph.crawl=1

//match and collect all of the addresses
WITH p, l, collect(ph.photo_reference) as photos
MATCH (p)-[:HAS_ADDRESS]->(r:Address)
RETURN p.name as name,
   p.rating as rating,
   p.formatted_address as address,
   p.international_phone_number as international_phone_number,
   photos,
   collect(r) as addresses
ORDER BY p.rating DESC
</code>```

Body:
I have data in the form

(n:Node)-[HAS_ADDRESS]->(r:Address{name:'Goa'}),
(n:Node)-[HAS_ADDRESS]->(r:Address{name:'India'}),
(n:Node)-[HAS_ANCHOR]->(k:Keyword{name:'accounting'}),
(n:Node)-[HAS_ANCHOR]->(k:Keyword{name:'Keyword 2'}),
(n:Node)-[HAS_ANCHOR]->(k:Keyword{name:'Keyword 3'}),
(n:Node)-[HAS_PHOTO]->(ph:Photo{name:'photo1'}),
(n:Node)-[HAS_PHOTO]->(ph:Photo{name:'photo2'}),
etc...

nodes are stored in the following format

(n:Node{name:'',rating:'',international_phone_number:''})
(ph:Photo{id:''})
(k:Keyword{name:''})

I have the value of 'k' and 'n' so i used

MATCH (k:Keyword { name: 'accounting'})<-[:HAS_ANCHOR]-(p)-[:HAS_ADDRESS]->(l:Address),(p)-[:HAS_PHOTO]->(ph)
WHERE ph.crawl=1 AND l.name = 'Goa'
WITH p, l
MATCH (p)-[:HAS_ADDRESS]->(other_r:Address)
return p.name as name, p.rating as rating, p.formatted_address as address,p.international_phone_number as international_phone_number,collect(ph.photo_reference) as photos, l as locations, other_r as other_addresses
ORDER BY p.rating DESC

I am clueless on how to get the node with all the details.

Body:
Since you only know about "Node 1", you need to take "n" from the first match and use it to get the other peers of "r".

// your original query that matches n and r based on the known node r
MATCH (n:Node)->[k:HAS_ANCHOR]->(r:Node)
WHERE r.name = 'Node 1'

// use the result of n from the first query to find peers of r
WITH n, r
MATCH (n)-[:HAS_ANCHOR]->(other_r:Node)
RETURN n, r, other_r

UPDATE
Based on comments, does this work?

// match the anchor based on the keyword
MATCH (k:Keyword { name: 'accounting'})<-[:HAS_ANCHOR]-(p)
WHERE (p)-[:HAS_ADDRESS]->(:Address {name: 'Goa'})

// optionally match and collect the photos
WITH p
OPTIONAL MATCH (p)-[:HAS_PHOTO]->(ph)
WHERE ph.crawl=1

//match and collect all of the addresses
WITH p, l, collect(ph.photo_reference) as photos
MATCH (p)-[:HAS_ADDRESS]->(r:Address)
RETURN p.name as name,
   p.rating as rating,
   p.formatted_address as address,
   p.international_phone_number as international_phone_number,
   photos,
   collect(r) as addresses
ORDER BY p.rating DESC


问:
MVVM framework AND Prism 4?
I just read this question. It has some nice answers, but they are over 1-year-old, and a lot have changed in this space over the last year. Some of the most popular frameworks have come out in a new mayor release such as Prism and MVVM Light Toolkit.

My question is somehow the same, but with one twist, I'm already using Prism 4.0 because of the region and module features.

Prism 4.0 embraces MVVM, but I feel there are some things which are "not lightweight", for instance interaction requests.
So I'm thinking would it better to use another MVVM framework either as a substitute or a supplement for Prism 4.0?

答: MVVMLight is quickly becoming the standard MVVM Implementation. In particular due to its multi platform support (wpf, silverlight, wp7), extreme blendability, and exactly the stuff you need to make MVVM applications ... nothing more ... nothing less. </p>

Title: MVVM framework AND Prism 4?


问:
Take a record to update and let no other update take and update that record during the process
I'm using Entity Framework to develop a website.

The problem I'm having here is a client select 1 record and update it, but if there is another client running the same select query the db will return the same record selected before and rewrite.

How do I avoid this? Is there anyway I can select a record and let no other touch that record?

答:
How do I avoid this. Is there anyway I can select a record and let no other touch that record?

You need to implmenent concurency management :

your table must have a row version column. When users query the data you send row version along the data.

each update from your user must include the row version.

if the row version is different with the current value stored in the database then you throw an exception.

if the row version is same with the one stored in your table then update the data and regenerate the row version column.

Entity Framework make it easy to handle concurrency just take a look at this tutorial. It will help you a lot.


问:
How to fix '`render` method found on the returned component instance' error in my code?
For some reason my React component is showing this error:

```<code>Warning: ReactComponent(...): No `render` method found on the returned component instance: you may have forgotten to define 'render'.
</code>```

Even though I have defined render in my component:

```<code>import React, { Component } from 'react';
import {addCart} from './Shop';
import { connect } from 'react-redux';

export class Cart extends Component {
    render() {
        console.log('cart', this.props.cart);
        return(
            <div className= "Webcart" id="Webcart">
                <Component cartItem={this.props.cartItem} />
            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
    }
}

function mapStateToProps(state) {
  return { cart: state.cart };
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);
</code>```

What is wrong with my component that is causing this error?

答:
This line right here:

```<code><Component cartItem={this.props.cartItem} />
</code>```

Here Component is referring to React.Component, or ReactComponent you see in the error message which doesn't implement the render method, it's just the superclass for your components. You're trying to create an element of Component but that doesn't have a render method and makes no sense.

You may have used the wrong component, and forgot to import and use the correct component.

Body:
For some reason my React component is showing this error:

Warning: ReactComponent(...): No `render` method found on the returned component instance: you may have forgotten to define 'render'.

Even though I have defined render in my component:

import React, { Component } from 'react';
import {addCart} from './Shop';
import { connect } from 'react-redux';

export class Cart extends Component {
    render() {
        console.log('cart', this.props.cart);
        return(

                <Component cartItem={this.props.cartItem} />

        );
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
    }
}

function mapStateToProps(state) {
  return { cart: state.cart };
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart);

What is wrong with my component that is causing this error?

Body:
This line right here:

<Component cartItem={this.props.cartItem} />

Here Component is referring to React.Component, or ReactComponent you see in the error message which doesn't implement the render method, it's just the superclass for your components. You're trying to create an element of Component but that doesn't have a render method and makes no sense.

You may have used the wrong component, and forgot to import and use the correct component.


问:
How can I show a div, then hide the other divs when a link is clicked?
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

```<code><div id="resourceLinks">
  <a href="#" name="resource" id="resource1">General Information</a><br />
  <a href="#" name="resource" id="resource2">Automatic 401(k)</a><br />
  <a href="#" name="resource" id="resource3">Consumer Fraud</a><br />
  <a href="#" name="resource" id="resource4">Direct Deposit</a><br />
  <a href="#" name="resource" id="resource5">Diversity</a><br />
  <a href="#" name="resource" id="resource6">Women</a><br />
  <a href="#" name="resource" id="resource7">Young Adults (20s - 40s)</a>
  </div>

<div id="resource1></div>
<div id="resource2></div>
<div id="resource3></div>
<div id="resource4></div>
<div id="resource5></div>
<div id="resource6></div>
<div id="resource7></div>
</code>```

CSS:

```<code>#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}
</code>```

jQuery:

```<code>$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});
</code>```

答:
Using classNames

```<code><div id="resourceLinks">
      <a href="#" class="resource1">General Information</a><br />
      <a href="#" class="resource2">Automatic</a><br />
      <a href="#" class="resource3">Consumer Fraud</a><br />
      <a href="#" class="resource4">Direct Deposit</a><br />
      <a href="#" class="resource5">Diversity</a><br />
      <a href="#" class="resource6">Women</a><br />
      <a href="#" class="resource7">Young</a>
</div>
<div class="resources">
    <div id="resource1" class="current"></div>
    <div id="resource2"></div>
    <div id="resource3"></div>
    <div id="resource4"></div>
    <div id="resource5"></div>
    <div id="resource6"></div>
    <div id="resource7"></div>
</div>
</code>```

jQuery:

```<code>$(document).ready(function(){
     $('#resourceLinks a').click(function() {
        $('div.resources div').hide().removeClass('current');
        $("#" + $(this).attr('className')).show().addClass('current');
    });
});
</code>```

Body:
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

  General Information

  Automatic 401(k)

  Consumer Fraud

  Direct Deposit

  Diversity

  Women

  Young Adults (20s - 40s)

CSS:

#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}

jQuery:

$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});

Body:
Using classNames

<div id="resourceLinks">
      <a href="#" class="resource1">General Information</a><br />
      <a href="#" class="resource2">Automatic</a><br />
      <a href="#" class="resource3">Consumer Fraud</a><br />
      <a href="#" class="resource4">Direct Deposit</a><br />
      <a href="#" class="resource5">Diversity</a><br />
      <a href="#" class="resource6">Women</a><br />
      <a href="#" class="resource7">Young</a>
</div>
<div class="resources">
    <div id="resource1" class="current"></div>
    <div id="resource2"></div>
    <div id="resource3"></div>
    <div id="resource4"></div>
    <div id="resource5"></div>
    <div id="resource6"></div>
    <div id="resource7"></div>
</div>

jQuery:

$(document).ready(function(){
     $('#resourceLinks a').click(function() {
        $('div.resources div').hide().removeClass('current');
        $("#" + $(this).attr('className')).show().addClass('current');
    });
});


问:
How would I normalize dates in a csv file? python
I have a CSV file with a field named  start_date that contains data in a variety of formats.

Some of the formats include e.g., June 23, 1912 or 5/11/1930 (month, day, year). But not all values are valid dates.

I want to add a start_date_description field adjacent to the start_date column to filter invalid date values into. Lastly, normalize all valid date values in start_date to ISO 8601 (i.e., YYYY-MM-DD).

So far I was only able to load the start_date into my file, I am stuck and would appreciate ant help. Please, any solution especially without using a library would be great!

```<code>import csv

date_column = ("start_date")
f = open("test.csv","r")
csv_reader = csv.reader(f)

headers = None
results = []
for row in csv_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in date_column:
            headers.append(i)
    else:
        results.append(([row[i] for i in headers]))

print results
</code>```

答:
Question: ... add a start_date_description ... normalize ... to ISO 8601

This reads the File test.csv and validates the Date String in Column start_date with Date Directive Patterns and returns a
dict{description, ISO}.  The returned dict is used to update the current Row dict and the updated Row dict is writen to the File test_update.csv.

Put this in a NEW Python File and run it!

A missing valid Date Directive Pattern could be simple added to the Array.

Python » 3.6 Documentation: 8.1.8. strftime() and strptime() Behavior

```<code>from datetime import datetime as dt
import re

def validate(date):
    def _dict(desc, date):
        return {'start_date_description':desc, 'ISO':date}

    for format in [('%m/%d/%y','Valid'), ('%b-%y','Short, missing Day'), ('%d-%b-%y','Valid'),
                   ('%d-%b','Short, missing Year')]: #, ('%B %d. %Y','Valid')]:
        try:
            _dt = dt.strptime(date, format[0])
            return _dict(format[1], _dt.strftime('%Y-%m-%d'))
        except:
            continue

    if not re.search(r'\d+', date):
        return _dict('No Digit', None)

    return _dict('Unknown Pattern', None)

with open('test.csv') as fh_in, open('test_update.csv', 'w') as fh_out:
    csv_reader = csv.DictReader(fh_in)
    csv_writer = csv.DictWriter(fh_out,
                                fieldnames=csv_reader.fieldnames +
                                           ['start_date_description', 'ISO'] )
    csv_writer.writeheader()

    for row, values in enumerate(csv_reader,2):
        values.update(validate(values['start_date']))

        # Show only Invalid Dates
        if any(w in values['start_date_description']
               for w in ['Unknown', 'No Digit', 'missing']):

            print('{:>3}: {v[start_date]:13.13} {v[start_date_description]:<22} {v[ISO]}'.
                  format(row, v=values))

        csv_writer.writerow(values)
</code>```

Output:

```<code>start_date    start_date_description ISO
June 23. 1912 Valid                  1912-06-23
12/31/91      Valid                  1991-12-31
Oct-84        Short, missing Day     1984-10-01
Feb-09        Short, missing Day     2009-02-01
10-Dec-80     Valid                  1980-12-10
10/7/81       Valid                  1981-10-07
Facere volupt No Digit               None
... (omitted for brevity)
</code>```

Tested with Python: 3.4.2

Body:
I have a CSV file with a field named  start_date that contains data in a variety of formats.

Some of the formats include e.g., June 23, 1912 or 5/11/1930 (month, day, year). But not all values are valid dates.

I want to add a start_date_description field adjacent to the start_date column to filter invalid date values into. Lastly, normalize all valid date values in start_date to ISO 8601 (i.e., YYYY-MM-DD).

So far I was only able to load the start_date into my file, I am stuck and would appreciate ant help. Please, any solution especially without using a library would be great!

import csv

date_column = ("start_date")
f = open("test.csv","r")
csv_reader = csv.reader(f)

headers = None
results = []
for row in csv_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in date_column:
            headers.append(i)
    else:
        results.append(([row[i] for i in headers]))

print results

Body:
Question: ... add a start_date_description ... normalize ... to ISO 8601

This reads the File test.csv and validates the Date String in Column start_date with Date Directive Patterns and returns a
dict{description, ISO}.  The returned dict is used to update the current Row dict and the updated Row dict is writen to the File test_update.csv.

Put this in a NEW Python File and run it!

A missing valid Date Directive Pattern could be simple added to the Array.

Python » 3.6 Documentation: 8.1.8. strftime() and strptime() Behavior

from datetime import datetime as dt
import re

def validate(date):
    def _dict(desc, date):
        return {'start_date_description':desc, 'ISO':date}

    for format in [('%m/%d/%y','Valid'), ('%b-%y','Short, missing Day'), ('%d-%b-%y','Valid'),
                   ('%d-%b','Short, missing Year')]: #, ('%B %d. %Y','Valid')]:
        try:
            _dt = dt.strptime(date, format[0])
            return _dict(format[1], _dt.strftime('%Y-%m-%d'))
        except:
            continue

    if not re.search(r'\d+', date):
        return _dict('No Digit', None)

    return _dict('Unknown Pattern', None)

with open('test.csv') as fh_in, open('test_update.csv', 'w') as fh_out:
    csv_reader = csv.DictReader(fh_in)
    csv_writer = csv.DictWriter(fh_out,
                                fieldnames=csv_reader.fieldnames +
                                           ['start_date_description', 'ISO'] )
    csv_writer.writeheader()

    for row, values in enumerate(csv_reader,2):
        values.update(validate(values['start_date']))

        # Show only Invalid Dates
        if any(w in values['start_date_description']
               for w in ['Unknown', 'No Digit', 'missing']):

            print('{:>3}: {v[start_date]:13.13} {v[start_date_description]:<22} {v[ISO]}'.
                  format(row, v=values))

        csv_writer.writerow(values)

Output:

start_date    start_date_description ISO
June 23. 1912 Valid                  1912-06-23
12/31/91      Valid                  1991-12-31
Oct-84        Short, missing Day     1984-10-01
Feb-09        Short, missing Day     2009-02-01
10-Dec-80     Valid                  1980-12-10
10/7/81       Valid                  1981-10-07
Facere volupt No Digit               None
... (omitted for brevity)

Tested with Python: 3.4.2


问:
How do i disable the horizontal scroll bar in Electron BrowserWindow?
How do i disable the horizontal scroll bar in a fixed width and height browser window in Electron?

Thank you.

答:
I think you just have to disable horizontal scrolling in your HTML file.
One way to do so is by using css:

```<code><style>
  body {
    overflow-x: hidden;
  }
</style>
</code>```

Try to add this in the .

Body:
I think you just have to disable horizontal scrolling in your HTML file.
One way to do so is by using css:

<style>
  body {
    overflow-x: hidden;
  }
</style>

Try to add this in the <head>.


问:
Encode Swift array for Alamofire post using URLEncoding
Reposting as I messed up with the type of encoding before...
I need to send an array to the server with Alamofire using URLEncoding. However, it needs to be encoded in some way for Alamofire to send it properly. This is my code:

```<code>let parameters: [String : Any] = [
    "names" : ["bob", "fred"]
]

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default)
   .responseJSON { response in
       // etc
   }
</code>```

However the parameters never get encoded and just get sent as nil. How can I encode it?

答:
Try this code, hope it will work for you. In this code the array is being encoded with NSJSONSerialization :</p>

```<code>var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let values = ["06786984572365", "06644857247565", "06649998782227"]

request.httpBody = try! JSONSerialization.data(withJSONObject: values)

Alamofire.request(request)
.responseJSON { response in
    // do whatever you want here
    switch response.result {
    case .failure(let error):
        print(error)

        if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
            print(responseString)
        }
    case .success(let responseObject):
        print(responseObject)
    }
}
</code>```

Body:
Reposting as I messed up with the type of encoding before...
I need to send an array to the server with Alamofire using URLEncoding. However, it needs to be encoded in some way for Alamofire to send it properly. This is my code:

let parameters: [String : Any] = [
    "names" : ["bob", "fred"]
]

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default)
   .responseJSON { response in
       // etc
   }

However the parameters never get encoded and just get sent as nil. How can I encode it?

Body:
Try this code, hope it will work for you. In this code the array is being encoded with NSJSONSerialization :

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let values = ["06786984572365", "06644857247565", "06649998782227"]

request.httpBody = try! JSONSerialization.data(withJSONObject: values)

Alamofire.request(request)
.responseJSON { response in
    // do whatever you want here
    switch response.result {
    case .failure(let error):
        print(error)

        if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
            print(responseString)
        }
    case .success(let responseObject):
        print(responseObject)
    }
}


问:
Facebook: How to get back the short PID from an FBID for a photo?
I am using this code to post a photo to my applications photo album.  My question is how can i convert the FBID that this code returns into a shore PID for the photo?

```<code>$file= 'test.jpg';
$args = array('message' => 'Photo Caption');
$args['image'] = '@' . realpath($file);
$data = $facebook->api('/me/photos', 'post', $args);
print_r($data);
</code>```

This returns an array with ID being the FBID of the photo uploaded.  I need the PID of the photo.

Thanks

答:
I figured it out.  For anyone who wants to know i did FQL like this: </p>

```<code>SELECT pid FROM photo WHERE object_id = "FBID"
</code>```

Body:
I am using this code to post a photo to my applications photo album.  My question is how can i convert the FBID that this code returns into a shore PID for the photo?

$file= 'test.jpg';
$args = array('message' => 'Photo Caption');
$args['image'] = '@' . realpath($file);
$data = $facebook->api('/me/photos', 'post', $args);
print_r($data);

This returns an array with ID being the FBID of the photo uploaded.  I need the PID of the photo.

Thanks

Body:
I figured it out.  For anyone who wants to know i did FQL like this:

SELECT pid FROM photo WHERE object_id = "FBID"


问:
Saving phpMyAdmin settings does not work
After installing phpMyAdmin on my Debian server, everything works fine except that saving settings opens the JSON answer as document and no settings are saved. Any ideas?</p>

答: that means the default settings are being used.  The configuration file is only for custom configurations.  As you have not created any custom configurations, the file will be empty.</p>


问:
AngluarJS Reuse Functions (Where do i put them)
Lets say i want to reuse a function in angularjs that returns a specific value  but i want to call it in other parts controllers of the app so i don't rewrite it in other places (dry) , where would i put that function in an angularjs app? Would i make a service of factory for this?

Say i have two controllers and in those two controllers i want to call function foo() that returns a certain number when i pass a variable through it. Where would i put function foo() in my angular structure?

答:
AngularJS has three very similar concepts services, factories, and providers. Each one can be used to expose apis using DRY patterns. Most often it's a matter of preference between using a service, factory, or provider. I tend to prefer using factories.

Here is a jsfiddle of a simple example where I use a factory to expose an api: https://jsfiddle.net/kaxtxL1h/

```<code>var app = angular
  .module("app", [])
  .factory("myapi", function() {
    var api = {
      foo: function (bar) {
        return bar + "_baz"
      }
    };
    //now api is exposed to whoever injects myapi
    return api;
  })
  .controller("ControllerOne", function($scope, myapi) {
    $scope.value = myapi.foo("one");
  })
  .controller("ControllerTwo", function($scope, myapi) {
    $scope.value = myapi.foo("two");
  });
</code>```

Here is a good reference for understanding the similarities and differences between services, factories, and providers: AngularJS: Service vs provider vs factory

Body:
AngularJS has three very similar concepts services, factories, and providers. Each one can be used to expose apis using DRY patterns. Most often it's a matter of preference between using a service, factory, or provider. I tend to prefer using factories.

Here is a jsfiddle of a simple example where I use a factory to expose an api: https://jsfiddle.net/kaxtxL1h/

var app = angular
  .module("app", [])
  .factory("myapi", function() {
    var api = {
      foo: function (bar) {
        return bar + "_baz"
      }
    };
    //now api is exposed to whoever injects myapi
    return api;
  })
  .controller("ControllerOne", function($scope, myapi) {
    $scope.value = myapi.foo("one");
  })
  .controller("ControllerTwo", function($scope, myapi) {
    $scope.value = myapi.foo("two");
  });

Here is a good reference for understanding the similarities and differences between services, factories, and providers: AngularJS: Service vs provider vs factory


问:
Generate a random point within a circle (uniformly)
I need to generate a uniformly random point within a circle of radius R.

I realize that by just picking a uniformly random angle in the interval [0 ... 2π), and uniformly random radius in the interval (0 ... R) I would end up with more points towards the center, since for two given radii, the points in the smaller radius will be closer to each other than for the points in the larger radius.

I found a blog entry on this over here but I don't understand his reasoning. I suppose it is correct, but I would really like to understand from where he gets (2/R2)×r and how he derives the final solution.

Update: 7 years after posting this question I still hadn't received a satisfactory answer on the actual question regarding the math behind the square root algorithm. So I spent a day writing an answer myself. Link to my answer.

答:
Let ρ (radius) and  φ (azimuth) be two random variables corresponding to polar coordinates of an arbitrary point inside the circle. If the points are uniformly distributed then what is the disribution function of ρ and φ?

For any r: 0 < r < R the probability of radius coordinate ρ to be less then r is

P[ρ < r] = P[point is within a circle of radius r] = S1 / S0 =(r/R)2

Where S1 and S0 are the areas of circle of radius r and R respectively.
So the CDF can be given as:

```<code>          0          if r<=0
  CDF =   (r/R)**2   if 0 < r <= R
          1          if r > R
</code>```

And PDF:

```<code>PDF = d/dr(CDF) = 2 * (r/R**2) (0 < r <= R).
</code>```

Note that for R=1 random variable sqrt(X) where X is uniform on [0, 1) has this exact CDF (because P[sqrt(X) < y] = P[x < y**2] = y**2 for 0 < y <= 1).

The distribution of φ is obviously uniform from 0 to 2*π. Now you can create random polar coordinates and convert them to Cartesian using trigonometric equations:

```<code>x = ρ * cos(φ)
y = ρ * sin(φ)
</code>```

Can't resist to post python code for R=1.

```<code>from matplotlib import pyplot as plt
import numpy as np

rho = np.sqrt(np.random.uniform(0, 1, 5000))
phi = np.random.uniform(0, 2*np.pi, 5000)

x = rho * np.cos(phi)
y = rho * np.sin(phi)

plt.scatter(x, y, s = 4)
</code>```

You will get

ContentLicense: CC BY-SA 4.0

Body:
Let ρ (radius) and  φ (azimuth) be two random variables corresponding to polar coordinates of an arbitrary point inside the circle. If the points are uniformly distributed then what is the disribution function of ρ and φ?

For any r: 0 < r < R the probability of radius coordinate ρ to be less then r is

P[ρ < r] = P[point is within a circle of radius r] = S1 / S0 =(r/R)2

Where S1 and S0 are the areas of circle of radius r and R respectively.
So the CDF can be given as:

          0          if r<=0
  CDF =   (r/R)**2   if 0 < r <= R
          1          if r > R

And PDF:

PDF = d/dr(CDF) = 2 * (r/R**2) (0 < r <= R).

Note that for R=1 random variable sqrt(X) where X is uniform on [0, 1) has this exact CDF (because P[sqrt(X) < y] = P[x < y**2] = y**2 for 0 < y <= 1).

The distribution of φ is obviously uniform from 0 to 2*π. Now you can create random polar coordinates and convert them to Cartesian using trigonometric equations:

x = ρ * cos(φ)
y = ρ * sin(φ)

Can't resist to post python code for R=1.

from matplotlib import pyplot as plt
import numpy as np

rho = np.sqrt(np.random.uniform(0, 1, 5000))
phi = np.random.uniform(0, 2*np.pi, 5000)

x = rho * np.cos(phi)
y = rho * np.sin(phi)

plt.scatter(x, y, s = 4)

You will get


问:
React-native open google maps with specific address on Android
So I want to open the Google Maps app with specific address from my react- native App but all modules I found required to know the exact latitude and longitude of the address which I don't know I just want the app itself to find them by the address that is given to it.

What could be the best way to do it? Is there like some specific url that I can use?

答:
You Can use Linking Api to do that </p>

```<code>Linking.openURL('https://www.google.com/maps/search/?api=1&query=centurylink+field');
</code>```

<p>just change query value to what you want </p>

Body:
You Can use Linking Api to do that

Linking.openURL('https://www.google.com/maps/search/?api=1&query=centurylink+field');

just change query value to what you want


问:
Are there cases where a singleton is the best option?
There is a lot of discussion on this site about why singletons should be avoided but are there any cases where a singleton makes sense and is the best option?

An example where I think that a singleton is the best option is when implementing an Identity Map where you need to keep track of all models that have already been loaded from the database in your mapping layer. In this case it is important that the map is effectively global so that all client code uses the same instance of the map and they are all accessing the same list of loaded models. The simplest solution seems to be to implement the class as a singleton (or as static methods). Is this the best approach or is there another way?

Are there any other cases where it is OK to use a singleton or are they always bad?

答: See this thread.</p>

Body: See this thread.

OwnerDisplayName: metao


问:
What does the error "ERROR: index ‘product’: raw_hits: write error: 122070 of 262017 bytes written" mean in Sphinx?
Some of my indexes appear to be failing during the nightly rebuild with this error:

```<code>ERROR: index ‘product’: raw_hits: write error: 122070 of 262017 bytes written
</code>```

The only reference I can find on the internet is in some multibyte language that I can't read.  Has anyone experienced this error before?

答:
Sphinx is getting an error from the operating system that it can't write the file.

It sounds like you're running out of hard drive space, or encountering some other disk error.

If you are sure these are not the case, try reducing the max_iosize in your configuration.

Body:
Some of my indexes appear to be failing during the nightly rebuild with this error:

ERROR: index ‘product’: raw_hits: write error: 122070 of 262017 bytes written

The only reference I can find on the internet is in some multibyte language that I can't read.  Has anyone experienced this error before?


问:
How to set ImageView using Bitmap Array
I'm doing one demo of getting Image URLs through JSON and after getting the ULR I'm downloading that images and display them into the GridView. For storing downloaded images I'm using Bitmap array and passing it to ImageAdapter. And now I want to display that images on next activity on ImageView for that I'm using following code in second activity..

```<code>        // get intent data
    Intent i = getIntent();
    // Selected image id
    int position = i.getExtras().getInt("id");
    ImageAdapter imageAdapter = new ImageAdapter(this);
    ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    imageView.setBackgroundDrawable(imageAdapter.bm[position]);
</code>```

but It giving me error like The method setImageDrawable(Drawable) in the type ImageView is not applicable for the arguments (Bitmap). Please tell me how can I set the Image from Bitmap array to ImageView..

ImageAdapter Class:

```<code>    public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    public Bitmap bm[]=new Bitmap[4];
    ImageView imageView;

    // Constructor
    public ImageAdapter(Context c, Bitmap[] bm){
        mContext = c;
        this.bm = bm;
    }

    public ImageAdapter(Context c) {
        mContext = c;
    }

    @Override
    public int getCount() {
        return bm.length;
    }

    @Override
    public Object getItem(int position) {
        return bm[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        imageView = new ImageView(mContext);
        imageView.setImageBitmap(bm[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
        return imageView;
    }

}
</code>```

Main Class:

```<code>    public class AndroidGridLayoutActivity extends Activity {

    public static final  Bitmap bm[]=new Bitmap[4];
    public static  ImageAdapter img;
    public static  String[] imageurls;
    public static  GridView gridView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_layout);
        Log.d("LOG", "1");
        new GetImageUrls().execute();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d("LOG", "7");
        gridView = (GridView) findViewById(R.id.grid_view);
        // Instance of ImageAdapter Class
        Log.d("LOG", "8");
        img = new ImageAdapter(getApplicationContext(), bm);
        Log.d("LOG", "9");
        gridView.setAdapter(img);
        Log.d("LOG", "10");

        /**
         * On Click event for Single Gridview Item
         * */
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                Log.d("LOG", "11");
                // Sending image id to FullScreenActivity
                Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
                Log.d("LOG", "12");
                // passing array index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }

    public class GetImageUrls  extends AsyncTask<Void, Void, Void>
    {
        Context context;
        private ProgressDialog pDialog;
        // URL to get JSON
        private static final String url= "http://xxx.x.xxx/demo/test.json";
        private static final String MAIN = "mainCategory";
        private static final String IMAGE = "mcatimage";
        // JSONArray
        JSONArray loginjsonarray=null;
        //result from url

        protected void onPreExecute() {
            Log.d("LOG", "2");
            // Showing progress dialog
            pDialog = new ProgressDialog(getApplicationContext());
            pDialog.setMessage("Loading...");
            pDialog.setCancelable(false);
            //pDialog.show();
            Log.d("LOG", "3");
        }
        protected Void doInBackground(Void... arg) {
            Log.d("LOG", "4");
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();
            Log.d("LOG", "5");
             // Making a request to url and getting response
            String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
            Log.d("Response: ", ">"+jsonstr);
            if(jsonstr!=null)
            {
                try {
                        JSONObject jsonObj =new JSONObject(jsonstr);
                        loginjsonarray=jsonObj.getJSONArray(MAIN);
                        imageurls=new String[loginjsonarray.length()];
                        for(int i=0;i<loginjsonarray.length();i++){
                            JSONObject l=loginjsonarray.getJSONObject(i);
                            imageurls[i]=l.getString(IMAGE);
                            Log.d("imageurls: ", imageurls[i]);
                        }
                        for(int i=0;i<imageurls.length;i++)
                        {
                            bm[i]=DownloadImage(imageurls[i]);
                            Log.d("LOG", bm[i].toString());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }else{
                Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
            }
            return null;
        }

        public Bitmap DownloadImage(String STRURL) {
            Bitmap bitmap = null;
            InputStream in = null;
            try {
                    int response = -1;
                    URL url = new URL(STRURL);
                    Log.d("DownloadImage: ", url.toString());
                    URLConnection conn = url.openConnection();
                    if (!(conn instanceof HttpURLConnection))
                        throw new IOException("Not an HTTP connection");
                    try{
                        HttpURLConnection httpConn = (HttpURLConnection) conn;
                        httpConn.setAllowUserInteraction(false);
                        httpConn.setInstanceFollowRedirects(true);
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();
                        response = httpConn.getResponseCode();
                        Log.d("DownloadImage response: ", Integer.toString(response));
                        if (response == HttpURLConnection.HTTP_OK) {
                            in = httpConn.getInputStream();
                            Log.d("DownloadImage: ", in.toString());
                        }
                    } catch (Exception ex) {
                        throw new IOException("Error connecting");
                    }
                    bitmap = BitmapFactory.decodeStream(in);
                    Log.d("DownloadImage Bitmap: ", bitmap.toString());
                    in.close();
                }catch (IOException e1) {
                    e1.printStackTrace();
                }
            Log.d("LOG", "6");
            return bitmap;
        }

        protected void onPostExecute(Integer result) {
            // Dismiss the progress dialog
            if(pDialog.isShowing()){
                pDialog.dismiss();
            }

        }
    }

}
</code>```

FullActivity Class:

```<code>public class FullImageActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.full_image);

    // get intent data
    Intent i = getIntent();

    // Selected image id
    int position = i.getExtras().getInt("id");
    Log.d("Position", Integer.toString(position));
    ImageAdapter imageAdapter = new ImageAdapter(this);
    ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    imageView.setImageBitmap(imageAdapter.bm[position]);
}
</code>```

}

答:
here i give you my code of my app that works with a gallery from drawable resources with int position, modify it for your needs, should work with your code.

My intent of gallery is:

```<code>@Override
public void onItemClick(AdapterView<?> parent, View  view, int position, long id) {
    int selectedId = imgs[position];
    Intent intent = new Intent(Gallery3DActivity.this,MainActivity.class);
    intent.putExtra("imageId", selectedId);
    startActivity(intent);
}
</code>```

In the main activity i receive the intent and set it on the imageview:

```<code>Intent avatar = getIntent();
int imageId = avatar.getIntExtra("imageId", -0);
// -0 would be a default value
// -1 will crash with a missing resource

if (getIntent().getExtras() != null) {
    Avatar.setImageResource(imageId);
    savedAvatar.setImageResource(imageId);
} else {
    Avatar.setImageResource(R.mipmap.ic_launcher);
}
</code>```

Your code is similiar as mine, but you get it from url them to bitmap, me i get it from drawable resources, with long id list set on the activity java for name and position, i chose the one i want to set as avatar them pass it inside intent to main activity and define the intent name that contains the drawable cache to an imageview, after in button onclick i convert to bitmap, bitmap to string, string to image to restore imageview view on start main activity, and i save the string to sharedpreferences, getting the imageview view back again even after close the app.

Good luck

Title: How to set ImageView using Bitmap Array

Body:
I'm doing one demo of getting Image URLs through JSON and after getting the ULR I'm downloading that images and display them into the GridView. For storing downloaded images I'm using Bitmap array and passing it to ImageAdapter. And now I want to display that images on next activity on ImageView for that I'm using following code in second activity..

        // get intent data
    Intent i = getIntent();
    // Selected image id
    int position = i.getExtras().getInt("id");
    ImageAdapter imageAdapter = new ImageAdapter(this);
    ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    imageView.setBackgroundDrawable(imageAdapter.bm[position]);

but It giving me error like The method setImageDrawable(Drawable) in the type ImageView is not applicable for the arguments (Bitmap). Please tell me how can I set the Image from Bitmap array to ImageView..

ImageAdapter Class:

    public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    public Bitmap bm[]=new Bitmap[4];
    ImageView imageView;

    // Constructor
    public ImageAdapter(Context c, Bitmap[] bm){
        mContext = c;
        this.bm = bm;
    }

    public ImageAdapter(Context c) {
        mContext = c;
    }

    @Override
    public int getCount() {
        return bm.length;
    }

    @Override
    public Object getItem(int position) {
        return bm[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        imageView = new ImageView(mContext);
        imageView.setImageBitmap(bm[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
        return imageView;
    }

}

Main Class:

    public class AndroidGridLayoutActivity extends Activity {

    public static final  Bitmap bm[]=new Bitmap[4];
    public static  ImageAdapter img;
    public static  String[] imageurls;
    public static  GridView gridView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_layout);
        Log.d("LOG", "1");
        new GetImageUrls().execute();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d("LOG", "7");
        gridView = (GridView) findViewById(R.id.grid_view);
        // Instance of ImageAdapter Class
        Log.d("LOG", "8");
        img = new ImageAdapter(getApplicationContext(), bm);
        Log.d("LOG", "9");
        gridView.setAdapter(img);
        Log.d("LOG", "10");

        /**
         * On Click event for Single Gridview Item
         * */
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                Log.d("LOG", "11");
                // Sending image id to FullScreenActivity
                Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
                Log.d("LOG", "12");
                // passing array index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }

    public class GetImageUrls  extends AsyncTask<Void, Void, Void>
    {
        Context context;
        private ProgressDialog pDialog;
        // URL to get JSON
        private static final String url= "http://xxx.x.xxx/demo/test.json";
        private static final String MAIN = "mainCategory";
        private static final String IMAGE = "mcatimage";
        // JSONArray
        JSONArray loginjsonarray=null;
        //result from url

        protected void onPreExecute() {
            Log.d("LOG", "2");
            // Showing progress dialog
            pDialog = new ProgressDialog(getApplicationContext());
            pDialog.setMessage("Loading...");
            pDialog.setCancelable(false);
            //pDialog.show();
            Log.d("LOG", "3");
        }
        protected Void doInBackground(Void... arg) {
            Log.d("LOG", "4");
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();
            Log.d("LOG", "5");
             // Making a request to url and getting response
            String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
            Log.d("Response: ", ">"+jsonstr);
            if(jsonstr!=null)
            {
                try {
                        JSONObject jsonObj =new JSONObject(jsonstr);
                        loginjsonarray=jsonObj.getJSONArray(MAIN);
                        imageurls=new String[loginjsonarray.length()];
                        for(int i=0;i<loginjsonarray.length();i++){
                            JSONObject l=loginjsonarray.getJSONObject(i);
                            imageurls[i]=l.getString(IMAGE);
                            Log.d("imageurls: ", imageurls[i]);
                        }
                        for(int i=0;i<imageurls.length;i++)
                        {
                            bm[i]=DownloadImage(imageurls[i]);
                            Log.d("LOG", bm[i].toString());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }else{
                Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
            }
            return null;
        }

        public Bitmap DownloadImage(String STRURL) {
            Bitmap bitmap = null;
            InputStream in = null;
            try {
                    int response = -1;
                    URL url = new URL(STRURL);
                    Log.d("DownloadImage: ", url.toString());
                    URLConnection conn = url.openConnection();
                    if (!(conn instanceof HttpURLConnection))
                        throw new IOException("Not an HTTP connection");
                    try{
                        HttpURLConnection httpConn = (HttpURLConnection) conn;
                        httpConn.setAllowUserInteraction(false);
                        httpConn.setInstanceFollowRedirects(true);
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();
                        response = httpConn.getResponseCode();
                        Log.d("DownloadImage response: ", Integer.toString(response));
                        if (response == HttpURLConnection.HTTP_OK) {
                            in = httpConn.getInputStream();
                            Log.d("DownloadImage: ", in.toString());
                        }
                    } catch (Exception ex) {
                        throw new IOException("Error connecting");
                    }
                    bitmap = BitmapFactory.decodeStream(in);
                    Log.d("DownloadImage Bitmap: ", bitmap.toString());
                    in.close();
                }catch (IOException e1) {
                    e1.printStackTrace();
                }
            Log.d("LOG", "6");
            return bitmap;
        }

        protected void onPostExecute(Integer result) {
            // Dismiss the progress dialog
            if(pDialog.isShowing()){
                pDialog.dismiss();
            }

        }
    }

}

FullActivity Class:

public class FullImageActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.full_image);

    // get intent data
    Intent i = getIntent();

    // Selected image id
    int position = i.getExtras().getInt("id");
    Log.d("Position", Integer.toString(position));
    ImageAdapter imageAdapter = new ImageAdapter(this);
    ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    imageView.setImageBitmap(imageAdapter.bm[position]);
}

}

Body:
here i give you my code of my app that works with a gallery from drawable resources with int position, modify it for your needs, should work with your code.

My intent of gallery is:

@Override
public void onItemClick(AdapterView<?> parent, View  view, int position, long id) {
    int selectedId = imgs[position];
    Intent intent = new Intent(Gallery3DActivity.this,MainActivity.class);
    intent.putExtra("imageId", selectedId);
    startActivity(intent);
}

In the main activity i receive the intent and set it on the imageview:

Intent avatar = getIntent();
int imageId = avatar.getIntExtra("imageId", -0);
// -0 would be a default value
// -1 will crash with a missing resource

if (getIntent().getExtras() != null) {
    Avatar.setImageResource(imageId);
    savedAvatar.setImageResource(imageId);
} else {
    Avatar.setImageResource(R.mipmap.ic_launcher);
}

Your code is similiar as mine, but you get it from url them to bitmap, me i get it from drawable resources, with long id list set on the activity java for name and position, i chose the one i want to set as avatar them pass it inside intent to main activity and define the intent name that contains the drawable cache to an imageview, after in button onclick i convert to bitmap, bitmap to string, string to image to restore imageview view on start main activity, and i save the string to sharedpreferences, getting the imageview view back again even after close the app.

Good luck


问:
Salesforce: is it possible to develop a web application on top of Salesforce
Let me start with a bit of background: I'm helping a non-profit organization that would like to have a browser-based application that is backed by Salesforce, but has very specific requirements.

I see Salesforce has a REST API that we can call, so we can develop a standalone application to serve the web pages they want and use the REST API to call Salesforce when needed.

I'm wondering if there is a way to host a web application directly on Salesforce; this way we don't have to have a separate application server. Any recommendations or pointers to documentation/open source products is greatly appreciated.

答:
Yes, both Force.com Sites and Site.com features allow you to host webpages on the Force.com Platform.  The markup is stored in Visualforce Pages and can use Apex to access records in the Database.  I have migrated multiple websites (including our company's www.mkpartners.com) to Force.com using Force.com Sites.

One thing to keep in mind is that you are limited to 500,000 views per month and the rendering of a page with images that are also stored on the platform will incur a single view for the page and a single view for each image.  If you already have a very popular website, I wouldn't migrate.  If you're a small business or nonprofit, then it should be fine.
Another thing to keep in mind is that dynamic functionality based on records in the database will not work during maintenance windows.  There is the ability to upload a static version of your website to be rendered during these windows though.


问:
'adb' is not recognized as a command
In my new MacBook, I installed latest Android Studio. Then, in terminal, I created the .bash_profile, and added following lines to the file:

```<code>export ANDROID_HOME=~/Library/Android/sdk

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS
</code>```

After that, I run command source .bash_profile, then I type adb command, but get error that adb is not recognized as a command. Why? I also echo $PATH, I saw the platform_tools directory of Android sdk is there & there is adb file under that directory.

====== UPDATE =====

It is interesting, if I do following, it works:

```<code>export PATH=$PATH:/Users/myname/Library/Android/sdk/platform-tools
export PATH=$PATH:/Users/myname/Library/Android/sdk/tools
export ANDROID_HOME=/Users/myname/Library/Android/sdk
</code>```

WHY? Isn't ~ above identical to /Users/myname? Why my original script doesn't work but the above one works? I don't understand....Please someone explain to me.

答:
This pretty fundamental stuff:

In the current directory (./) execute command "adb"

./adb (you say this works).

what you want is adb (execute command adb found from the PATH variable), if the command "adb" can be found after searching in ALL paths in the PATH variable, execute the command adb where it is found.

A common precursor in the path entries is "." (current directory) but is discouraged due to executable name abuse (same name in a random directory).

Different paths are separated by the path separation variable (in windows it is semicolon ";" UNIX usually colon ":" ALSO MAC).
Your multiple exports SEEM to be over writing each other, do it once with the appropriate separator ":" and all your paths in one (or ALWAYS include $PATH: to retain all previous exports).

it should be in ../somewhere../sdk/platform-tools/adb

(where ever your SDK resides) export PATH=$PATH:/Users/myname/Library/Android/sdk/platform-tools seems ok (be careful not to over-ride it[erase]).

After a re-boot all paths should be honored.

NB

in UNIX we have the "which adb" command which tells us where the executable resides. In Windows with tools like cygwin we can also do the same thing.

I believe Mac has  Homebrew.

Title: 'adb' is not recognized as a command

Body:
In my new MacBook, I installed latest Android Studio. Then, in terminal, I created the .bash_profile, and added following lines to the file:

export ANDROID_HOME=~/Library/Android/sdk

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS

After that, I run command source .bash_profile, then I type adb command, but get error that adb is not recognized as a command. Why? I also echo $PATH, I saw the platform_tools directory of Android sdk is there & there is adb file under that directory.

====== UPDATE =====

It is interesting, if I do following, it works:

export PATH=$PATH:/Users/myname/Library/Android/sdk/platform-tools
export PATH=$PATH:/Users/myname/Library/Android/sdk/tools
export ANDROID_HOME=/Users/myname/Library/Android/sdk

WHY? Isn't ~ above identical to /Users/myname? Why my original script doesn't work but the above one works? I don't understand....Please someone explain to me.


问:
Linux server, locating files containing nothing but 4 specific lines
I'm dealing with a compromised website, in which hackers injected an htaccess instruction to redirect traffic. I can easily locate .htaccess files that contain the forwarding hack, BUT in cases where the directory already contained an htaccess file, they appended the dangerous instructions, so I cannot just deleted any htaccess file or could harm the site by letting formerly pw-protected directories wide open, or urlrewrite instructions (WordPress) be deleted, etc.
I could not find the way to locate files that only contain those 4 lines of redirect hack, could you shed some light ?
So far, using

find . -type f -exec grep -q targetpiratedomain {} \; -exec echo rm {} \;

Thanks !

答:
You could use the size of the .htaccess file - all the simple ones should be the same size?

You should also restrict your find command to only include files with the right name.

Also, as in the comments, what you should really do, is just restore the site from source control.


问:
Bitlocker script to unlock drive
What I am trying to achieve is to create a very small script to unlock my bitlocker drive, using the password, not the recovery password.

There is a Microsoft command for that, which is:

```<code>manage-bde -unlock D: -password
</code>```

where D is my bit locker drive. If I run this command line it will ask me for the password, and then the drive is properly unlocked.

At first I thought about creating a variable to ask for the password to the user, and then use this variable in the above command line, so that the script would look like:

```<code>set /p pass= what is your pass
manage-bde -unlock D: -password %pass%
</code>```

The problem is that -password does not seem to accept any argument, would it be the variable, or the password in clear, it will fail.
So, the only way to make it work seems to be an automatic reply to the prompt for the password, with the data in the variable.
But I don't know how to do that. I assume there is an extra command line to add after the manage-dbe...

My programming skills are quite weak, so any help would be appreciated.

答:
Just write this in Notepad and save it as .bat file.

You can then set up new task in the Task Scheduler to run the script on startup. Don't forget to check the task to be Run as Administrator:

```<code>@echo off
manage-bde D: -unlock -recoverypassword XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX
pause
</code>```

Title: Bitlocker script to unlock drive

Body:
What I am trying to achieve is to create a very small script to unlock my bitlocker drive, using the password, not the recovery password.

There is a Microsoft command for that, which is:

manage-bde -unlock D: -password

where D is my bit locker drive. If I run this command line it will ask me for the password, and then the drive is properly unlocked.

At first I thought about creating a variable to ask for the password to the user, and then use this variable in the above command line, so that the script would look like:

set /p pass= what is your pass
manage-bde -unlock D: -password %pass%

The problem is that -password does not seem to accept any argument, would it be the variable, or the password in clear, it will fail.
So, the only way to make it work seems to be an automatic reply to the prompt for the password, with the data in the variable.
But I don't know how to do that. I assume there is an extra command line to add after the manage-dbe...

My programming skills are quite weak, so any help would be appreciated.

Body:
Just write this in Notepad and save it as .bat file.

You can then set up new task in the Task Scheduler to run the script on startup. Don't forget to check the task to be Run as Administrator:

@echo off
manage-bde D: -unlock -recoverypassword XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX-XXXXXX
pause


问:
Angular JS : Failed to instantiate module test due to:
I'm running some Javascript inside a HTML file. And I'm trying to use some Angular JS with the function ng-repeat. Each time I run it, I get this error in the console :

```<code>angular.js:38 Uncaught Error: [$injector:modulerr]
</code>```

And when I click on the link within the error message in the console, I get this:

Failed to instantiate module test due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.6.4/$injector/nomod?p0=test
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:6:425
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:270
    at b (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:25:299)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:44
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:42:117
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:7:495)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:41:476)
    at eb (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:46:44)
    at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:21:373)
    at Sc (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:22:179

Here is my Javascript inside my HTML file:

```<code>//Get User ID and Trip ID in URL

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam)
    {
        return sParameterName[1];
    }
}
}

 var userid = GetURLParameter('userid');
 var tripid = GetURLParameter('tripid');

  </script>

<script>

 //Get photos URL inside a particular Trip ID from a User ID

  var database = firebase.database();
  database.ref(`photos/${userid}/trips/${tripid}`).once('value') //
  will return you all the photo objects inside the `tripId`
  .then(photosSnap => {
  var photosObj = photosSnap.val();
  var photosUrl = Object.keys(photosObj).map(key =>
  photosObj[key].photourl);
  // then you can return the array or use it here;

   var app = angular.module('test', []);

     app.controller('MainCtrl', function($scope) {
       $scope.urls = photosUrl;

   });

console.log(photosUrl); // will be an array of all the photourls
}).catch(err => alert(err));
</code>```

And finally my HTML which uses ng-repeat:

```<code><div class="spot" ng-app="test" ng-controller="MainCtrl">

     <ul>
        <li ng-repeat="url in urls">{{url}}</li>
     </ul>

 </div>
</code>```

I'm using a controller with scope to loop inside my HTML with an array. So first I don't know where my error message comes from, and second I'm not sure i'm using the controller and ng-repeat properly.

Thanks

PS: I included in the head tag of my HTML file this link :

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</code>```

EDIT: my Javascript inside my HTML updated (I moved everything inside the controller)

The error message is gone, my html just doesn't display any url (though the console shows there are 4 urls in my array photosUrl)

```<code> <script>

  //Get photos URL inside a particular Trip ID from a User ID

var app = angular.module('test', []);

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

    var database = firebase.database();
    database.ref(`photos/${userid}/trips/${tripid}`).once('value') //
    will return you all the photo objects inside the `tripId`
    .then(photosSnap => {
    var photosObj = photosSnap.val();
    var photosUrl = Object.keys(photosObj).map(key =>
    photosObj[key].photourl);
    // then you can return the array or use it here;

    $scope.urls = photosUrl;

console.log(photosUrl); // will be an array of all the photourls
}).catch(err => alert(err));

     });

  </script>
</code>```

答:
nomod is Angular's error indicating a module you've asked it to use hasn't been defined.

When you specify ng-app, AngularJS will automatically try to find the module you've defined with that name to load it into that block. But you're defining your module asynchronously, in the callback of a Firebase .once(). That callback can happen very quickly in some cases, but it's still asynchronous and won't be ready when Angular gets going here.

Move your angular.module() definition outside the Firebase callback.

Add $scope.$apply() just below setting $scope.urls = in the Firebase data callback.

Body:
I'm running some Javascript inside a HTML file. And I'm trying to use some Angular JS with the function ng-repeat. Each time I run it, I get this error in the console :

angular.js:38 Uncaught Error: [$injector:modulerr]

And when I click on the link within the error message in the console, I get this:

Failed to instantiate module test due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.6.4/$injector/nomod?p0=test
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:6:425
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:270
    at b (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:25:299)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:44
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:42:117
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:7:495)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:41:476)
    at eb (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:46:44)
    at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:21:373)
    at Sc (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:22:179

Here is my Javascript inside my HTML file:

//Get User ID and Trip ID in URL

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam)
    {
        return sParameterName[1];
    }
}
}

 var userid = GetURLParameter('userid');
 var tripid = GetURLParameter('tripid');

  </script>

EDIT: my Javascript inside my HTML updated (I moved everything inside the controller)

The error message is gone, my html just doesn't display any url (though the console shows there are 4 urls in my array photosUrl)


问:
How do you kill zombie process using wait()
I have this code that requires a parent to fork 3 children.

How do you know (and) where to put the "wait()" statement to kill

zombie processes?

What is the command to view zombie processes if you have Linux
virtual box?

```<code>main(){

 pid_t child;
 printf("-----------------------------------\n");
 about("Parent");
 printf("Now ..  Forking !!\n");
 child = fork();
 int i=0;

 for (i=0; i<3; i++){
    if (child < 0) {
        perror ("Unable to fork");
        break;
    }
    else if (child == 0){
        printf ("creating child #%d\n", (i+1));
        about ("Child");
        break;
    }

    else{
        child = fork();
    }
  }
}

void about(char * msg){

 pid_t me;
 pid_t oldone;

 me = getpid();
 oldone = getppid();

 printf("***[%s] PID = %d   PPID = %d.\n", msg, me, oldone);

}
</code>```

答:
How do you know (and) where to put the "wait()" statement to kill
  zombie processes?

You can register a signal handler for SIGCHLD that sets a global volatile sig_atomic_t flag = 0 variable to 1. Then, at some convenient place in your program, test whether flag is set to 1, and, if so, set it back to 0 and afterwards (for otherwise you might miss a signal) call waitpid(-1, NULL, WNOHANG) in a loop until it tells you that no more processes are to be waited for. Note that the signal will interrupt system calls with EINTR, which is a good condition to check for the value of flag. If you use an indefinitely blocking system call like select(), you might want to specify a timeout after which you check for flag, since otherwise you might miss a signal that was raised after your last waitpid() call but before entering the indefinitely blocking system call. An alternative to this kludge is to use pselect().

Body:
I have this code that requires a parent to fork 3 children.

How do you know (and) where to put the "wait()" statement to kill

zombie processes?

What is the command to view zombie processes if you have Linux
virtual box?

main(){

 pid_t child;
 printf("-----------------------------------\n");
 about("Parent");
 printf("Now ..  Forking !!\n");
 child = fork();
 int i=0;

 for (i=0; i<3; i++){
    if (child < 0) {
        perror ("Unable to fork");
        break;
    }
    else if (child == 0){
        printf ("creating child #%d\n", (i+1));
        about ("Child");
        break;
    }

    else{
        child = fork();
    }
  }
}

void about(char * msg){

 pid_t me;
 pid_t oldone;

 me = getpid();
 oldone = getppid();

 printf("***[%s] PID = %d   PPID = %d.\n", msg, me, oldone);

}


问:
Duplicate hash into independent hash (shallow copy)
What is the best way to duplicate a hash in Ruby, and have it independent from the original? For example:

```<code>a = { foo1: "bar1" }
b = a # or b = a.clone / b = a.dup for that matter
b[:foo2] = "bar2"
</code>```

This results in:

```<code>{:foo1=>"bar1", :foo2=>"bar2"} # a
{:foo1=>"bar1", :foo2=>"bar2"} # b
</code>```

Where I would like it to be

```<code>{:foo1=>"bar1"}                # a
{:foo1=>"bar1", :foo2=>"bar2"} # b
</code>```

Now I know about b = Marshal.load(Marshal.dump(a)) but that seems like a little overkill, and I was wondering if there is a better way, because I can't really find it.

答:
Kernel#dup and Kernel#clone do just what you want :

```<code>a = {foo1: "bar1"}
b = a.dup # or a.clone

b[:foo2] = "bar2"

p b
# {:foo1=>"bar1", :foo2=>"bar2"}
p a
# {:foo1=>"bar1"}
</code>```

As you requested, it's a shallow copy, though:

```<code>a = {foo1: ["bar1"]}
b = a.clone

b[:foo1] << 'bar2'
b[:foo3] = 'bar3'

p a
# {:foo1=>["bar1", "bar2"]}
p b
# {:foo1=>["bar1", "bar2"], :foo3=>"bar3"}
</code>```

Body:
What is the best way to duplicate a hash in Ruby, and have it independent from the original? For example:

a = { foo1: "bar1" }
b = a # or b = a.clone / b = a.dup for that matter
b[:foo2] = "bar2"

This results in:

{:foo1=>"bar1", :foo2=>"bar2"} # a
{:foo1=>"bar1", :foo2=>"bar2"} # b

Where I would like it to be

{:foo1=>"bar1"}                # a
{:foo1=>"bar1", :foo2=>"bar2"} # b

Now I know about b = Marshal.load(Marshal.dump(a)) but that seems like a little overkill, and I was wondering if there is a better way, because I can't really find it.

Body:
Kernel#dup and Kernel#clone do just what you want :

a = {foo1: "bar1"}
b = a.dup # or a.clone

b[:foo2] = "bar2"

p b
# {:foo1=>"bar1", :foo2=>"bar2"}
p a
# {:foo1=>"bar1"}

As you requested, it's a shallow copy, though:

a = {foo1: ["bar1"]}
b = a.clone

b[:foo1] << 'bar2'
b[:foo3] = 'bar3'

p a
# {:foo1=>["bar1", "bar2"]}
p b
# {:foo1=>["bar1", "bar2"], :foo3=>"bar3"}


问:
why is my draw of 3-degree polymonial so weird?
I am studying LinearRegression and Polynomial regression with scikit learn. I generated 2-degree polynomial dataset, and trained a 3-degree polynomial model. I hope to overfit in the plot with the original data. But the plot does not look like a 3-degree curve. If I change degree to 1, it would shows a line which is fine. What am I missing here?

```<code># over fit
poly_features_3 = PolynomialFeatures(degree=3, include_bias=False)
X_poly_3 = poly_features_3.fit_transform(X)
lin_reg_3 = LinearRegression()
lin_reg_3.fit(X_poly_3, y)
y_predict = lin_reg_3.predict(X_poly_3)
plt.scatter(X, y, color='black')
plt.plot(X, y_predict, color='red')
plt.show()
</code>```

答:
The values are not sorted, such that the plot jumps back and forth.

I guess you would want to plot

```<code>plt.plot(np.sort(X), y_predict[np.argsort(X)], color='red')
</code>```

Body:
I am studying LinearRegression and Polynomial regression with scikit learn. I generated 2-degree polynomial dataset, and trained a 3-degree polynomial model. I hope to overfit in the plot with the original data. But the plot does not look like a 3-degree curve. If I change degree to 1, it would shows a line which is fine. What am I missing here?

# over fit
poly_features_3 = PolynomialFeatures(degree=3, include_bias=False)
X_poly_3 = poly_features_3.fit_transform(X)
lin_reg_3 = LinearRegression()
lin_reg_3.fit(X_poly_3, y)
y_predict = lin_reg_3.predict(X_poly_3)
plt.scatter(X, y, color='black')
plt.plot(X, y_predict, color='red')
plt.show()

Body:
The values are not sorted, such that the plot jumps back and forth.

I guess you would want to plot

plt.plot(np.sort(X), y_predict[np.argsort(X)], color='red')