问:
VB 2010 XML files with namespaces are causing trouble
I'm trying to parse out an XML file using LINQ (XDocument) and there's something about having a namespace in the document that screws everything up.

I found this SO question about the same thing affecting element names, and I got past that (using the Name.LocalName property). But it's causing the same problem with other functions, such as getting an element with a specific name. For example:

The XML code in brief:

```<code><FeatureDefinitions xmlns="http://website.com/schema/features">
    <FeatureDefinition  Name="FeatureOne" >
      <Attributes>
        <ListAttribute Name="TYPE" Description="MATERIAL USED.">
          <ListItems>
            <Item>Material 1</Item>
            <Item>Material 2</Item>
            <Item>OTHER </Item>
          </ListItems>
        </ListAttribute>
        <ListAttribute Name="POSITION">
          <ListItems>
            <Item>BEGIN</Item>
            <Item>EDGE</Item>
            <Item>END</Item>
            <Item>TOE</Item>
            <Item>TOP</Item>
          </ListItems>
        </ListAttribute>
        <StringAttribute Name="NOTES" />
      </Attributes>
    </FeatureDefinition>
</FeatureDefinitions>
</code>```

Then in the code:

```<code>Dim nodeFeatureDef as XElement = nodeFeatureDefinitions.Element("Attributes")
</code>```

So, what's happening now is that when the name space is included in the first line of the XML, I can't get the element("Attributes") and its associated nodes. But if I delete the namespace attribute in the first line, it works fine.

There are lots of forums in which it is suggested that the VB source code import the namespace, but I can't be sure every file that this processes will have the same namespace. It worked by using the Name.LocalName property to the Name property, but I don't know how to do the same thing to the Elements property.

Any ideas?

Thanks!

答:
If the namespace is unknown, you could get it from the root element:

```<code>Dim xml As XDocument = ...
Dim ns = xml.Root.Name.Namespace
</code>```

You can then use the XNamespace.GetName method to create a qualified name, e.g.

```<code>Dim attrs = xml.Descendants(ns.GetName("ListAttribute"))
</code>```

This should also work OK if there is no namespace on the root element.

Body:
I'm trying to parse out an XML file using LINQ (XDocument) and there's something about having a namespace in the document that screws everything up.

I found this SO question about the same thing affecting element names, and I got past that (using the Name.LocalName property). But it's causing the same problem with other functions, such as getting an element with a specific name. For example:

The XML code in brief:

<FeatureDefinitions xmlns="http://website.com/schema/features">
    <FeatureDefinition  Name="FeatureOne" >
      <Attributes>
        <ListAttribute Name="TYPE" Description="MATERIAL USED.">
          <ListItems>
            <Item>Material 1</Item>
            <Item>Material 2</Item>
            <Item>OTHER </Item>
          </ListItems>
        </ListAttribute>
        <ListAttribute Name="POSITION">
          <ListItems>
            <Item>BEGIN</Item>
            <Item>EDGE</Item>
            <Item>END</Item>
            <Item>TOE</Item>
            <Item>TOP</Item>
          </ListItems>
        </ListAttribute>
        <StringAttribute Name="NOTES" />
      </Attributes>
    </FeatureDefinition>
</FeatureDefinitions>

Then in the code:

Dim nodeFeatureDef as XElement = nodeFeatureDefinitions.Element("Attributes")

So, what's happening now is that when the name space is included in the first line of the XML, I can't get the element("Attributes") and its associated nodes. But if I delete the namespace attribute in the first line, it works fine.

There are lots of forums in which it is suggested that the VB source code import the namespace, but I can't be sure every file that this processes will have the same namespace. It worked by using the Name.LocalName property to the Name property, but I don't know how to do the same thing to the Elements property.

Any ideas?

Thanks!

Body:
If the namespace is unknown, you could get it from the root element:

Dim xml As XDocument = ...
Dim ns = xml.Root.Name.Namespace

You can then use the XNamespace.GetName method to create a qualified name, e.g.

Dim attrs = xml.Descendants(ns.GetName("ListAttribute"))

This should also work OK if there is no namespace on the root element.


来源: stackexchange

问:
terminal messing up stick figure drawing
Im making a python program that plays hangman and for the incorrect answers I have several different strings that are "Drawings" of the stickfigure that look something like this

```<code>"""_______
  |
  |     O
  |    /|\
  |   / | \
  |    / \
  |   /   \
  |
  -----------"""
</code>```

But when it is actually run in the terminal it distorts the image a lot such that its virtually unrecognizable. how do I fix this

答:
Use a raw string:

```<code>r"""_______
  |
  |     O
  |    /|\
  |   / | \
  |    / \
  |   /   \
  |
  -----------"""
</code>```

The problem is that otherwise the backslashes at the end of a line are interpreted as line continuation marker.

ContentLicense: CC BY-SA 3.0

Body:
Im making a python program that plays hangman and for the incorrect answers I have several different strings that are "Drawings" of the stickfigure that look something like this

"""_______
  |
  |     O
  |    /|\
  |   / | \
  |    / \
  |   /   \
  |
  -----------"""

But when it is actually run in the terminal it distorts the image a lot such that its virtually unrecognizable. how do I fix this

Body:
Use a raw string:

r"""_______
  |
  |     O
  |    /|\
  |   / | \
  |    / \
  |   /   \
  |
  -----------"""

The problem is that otherwise the backslashes at the end of a line are interpreted as line continuation marker.


问:
Laravel - how to know if the attribute exists in relacional table
im doing a property sales website, and i have todo an advanced search, with number of bedroom for example.

but i have properties like shop that dont have bedroom attributes,how to know each table i have to search like apartment or house.
i'm using scopes and for location and type of properties works fine.

My property model

```<code>public function atributos(){
        //se for moradia
        if ($this->tipoimovel_id == 1) {
            return $this->hasOne(Moradia::class);
        }
        //se for apartamento
        else if ($this->tipoimovel_id == 2) {
            return $this->hasOne(Apartamento::class);
        }
        //se for loja
        else if ($this->tipoimovel_id == 3) {
            return $this->hasOne(Loja::class);
        }
        //se for armazem
        else if ($this->tipoimovel_id == 4) {
            return $this->hasOne(Armazem::class);
        }
        //se for terreno para construção
        else if ($this->tipoimovel_id == 5) {
            return $this->hasOne(TerrenoConstrucao::class);
        }
        // se for terreno para outros fins
        else if ($this->tipoimovel_id == 6) {
            return $this->hasOne(TerrenoOutrosFins::class);
        }
    }
</code>```

Warehouse dont have number of bedrooms

```<code>Schema::create('armazens', function (Blueprint $table) {
    $table->integer('imovel_id');
    $table->integer('areaAcessoria');
    $table->integer('areaTotal');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});
</code>```

house have

```<code>Schema::create('moradias', function (Blueprint $table) {
    $table->integer('imovel_id');
    $table->integer('nrPisosConstrucao');
    $table->integer('nrQuartos');
    $table->integer('nrWcs');
    $table->integer('areaConstrucao');
    $table->integer('areaTerreno');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});
</code>```

My scope to search by number of bedrooms

```<code>public function scopeProcuraNrQuartos($query,$nrQuartos){
    if ($nrQuartos) $query->where( $this->atributos()->nrQuartos , '>=' , $nrQuartos);
}
</code>```

i know that its wrong, but exist some validation to know if that attribute exists in the table?
Thanks

答:
IF i got you right, you need to check if attribute (column) exists in database?

If so, here is how you do it:

```<code>Schema::hasColumn($model->getTable(), $column);
</code>```

So in your case just put this check in place of

```<code>if ($nrQuartos)
</code>```

with your model and columns names of course

Originally posted here: https://laracasts.com/discuss/channels/eloquent/test-attributescolumns-existence?page=1

Body:
im doing a property sales website, and i have todo an advanced search, with number of bedroom for example.

but i have properties like shop that dont have bedroom attributes,how to know each table i have to search like apartment or house.
i'm using scopes and for location and type of properties works fine.

My property model

public function atributos(){
        //se for moradia
        if ($this->tipoimovel_id == 1) {
            return $this->hasOne(Moradia::class);
        }
        //se for apartamento
        else if ($this->tipoimovel_id == 2) {
            return $this->hasOne(Apartamento::class);
        }
        //se for loja
        else if ($this->tipoimovel_id == 3) {
            return $this->hasOne(Loja::class);
        }
        //se for armazem
        else if ($this->tipoimovel_id == 4) {
            return $this->hasOne(Armazem::class);
        }
        //se for terreno para construção
        else if ($this->tipoimovel_id == 5) {
            return $this->hasOne(TerrenoConstrucao::class);
        }
        // se for terreno para outros fins
        else if ($this->tipoimovel_id == 6) {
            return $this->hasOne(TerrenoOutrosFins::class);
        }
    }

Warehouse dont have number of bedrooms

Schema::create('armazens', function (Blueprint $table) {
    $table->integer('imovel_id');
    $table->integer('areaAcessoria');
    $table->integer('areaTotal');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

house have

Schema::create('moradias', function (Blueprint $table) {
    $table->integer('imovel_id');
    $table->integer('nrPisosConstrucao');
    $table->integer('nrQuartos');
    $table->integer('nrWcs');
    $table->integer('areaConstrucao');
    $table->integer('areaTerreno');
    $table->smallInteger('anoConstrucao');
    $table->timestamps();
});

My scope to search by number of bedrooms

public function scopeProcuraNrQuartos($query,$nrQuartos){
    if ($nrQuartos) $query->where( $this->atributos()->nrQuartos , '>=' , $nrQuartos);
}

i know that its wrong, but exist some validation to know if that attribute exists in the table?
Thanks

Body:
IF i got you right, you need to check if attribute (column) exists in database?

If so, here is how you do it:

Schema::hasColumn($model->getTable(), $column);

So in your case just put this check in place of

if ($nrQuartos)

with your model and columns names of course

Originally posted here: https://laracasts.com/discuss/channels/eloquent/test-attributescolumns-existence?page=1


问:
Linking keywords from python to a csv that stores the solutions to the issue the user is experiencing
I have a code that allows me to identify keywords inputted from a user and the system displays the problem the keyword linked to and asks if it is correct. If the user inputs yes a solution is given </p>

```<code># The following is a database of problems, keywords, and solutions.

PROBLEMS = (('My phone does not turn on.',
             {'power', 'turn', 'on', 'off'},
             ('put it on charger.',))

# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', 'correct')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', 'incorrect')))

def main():
    """Find out what problem is being experienced and provide a solution."""
    description = input('Welcome to the repair centre. Please state the problem with your device: ')
    words = {''.join(filter(str.isalpha, word))
             for word in description.lower().split()}
    for problem, keywords, steps in PROBLEMS:
        if words & keywords:
            print('This may be what you are experiencing:')
            print(problem)
            if get_response('Does this match your problem? '):
                print('Please follow the solution given')
                for number, step in enumerate(steps, 1):
                    print('{}. {}'.format(number, step))
                print('Once you have carried out the solution suggested by the system the problem with your device should be fixed .')
                print('If you have carried out the solution suggested by the system and the problem is not fixed, please take the device  to either the manufacturer or to the repair shop to get it fixed professionally.')
                break
    else:
        print('Unfortunately the repair centre cannot help you with your problem.')

def get_response(query):
    """Ask the user yes/no style questions and return the results."""
    while True:
        answer = input(query).casefold()
        if answer:
            if any(option.startswith(answer) for option in POSITIVE):
                return True
            if any(option.startswith(answer) for option in NEGATIVE):
                return False
        print('Please respond with the positive or negative answer listed : yes, true, correct, no, false, incorrect.')

if __name__ == '__main__':
    main()
</code>```

<p>However how can i store all the solutions in a text file and make the keywords stored in python link to it depending on the user input.
I want a specific line from the text file to be outputted to the user.
Help will be appreciated </p>

答:
We're going to store the keywords and solutions in a csv file. The first entry on each line will be the solution, and all the others will be keywords that direct to this solution.

```<code>from collections import defaultdict
import csv

sol_dict = defaultdict(set)
with open('solutions.csv', newline='') as f:
    r = csv.reader(f, quotechar='|')
    for solution, *keywords in r:
        for keyword in keywords:
            sol_dict['keyword'].add(solution)
</code>```

So now we have this dictionary, sol_dict.  We can query a keyword sol_dict['power'] and you get back a set of strings, each a solution.  (When you make the csv, if you want commas in the solution, you can wrap it in the quotechar, |).

Then walking through the solutions would look something like

```<code>problem = input('What is your problem?')
for solution in set.union(*(sol_dict[word] for word in problem.split())):
    # Whatever you want to do with solutions
    print(solution)
</code>```

Body:
I have a code that allows me to identify keywords inputted from a user and the system displays the problem the keyword linked to and asks if it is correct. If the user inputs yes a solution is given

# The following is a database of problems, keywords, and solutions.

PROBLEMS = (('My phone does not turn on.',
             {'power', 'turn', 'on', 'off'},
             ('put it on charger.',))

# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', 'correct')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', 'incorrect')))

def main():
    """Find out what problem is being experienced and provide a solution."""
    description = input('Welcome to the repair centre. Please state the problem with your device: ')
    words = {''.join(filter(str.isalpha, word))
             for word in description.lower().split()}
    for problem, keywords, steps in PROBLEMS:
        if words & keywords:
            print('This may be what you are experiencing:')
            print(problem)
            if get_response('Does this match your problem? '):
                print('Please follow the solution given')
                for number, step in enumerate(steps, 1):
                    print('{}. {}'.format(number, step))
                print('Once you have carried out the solution suggested by the system the problem with your device should be fixed .')
                print('If you have carried out the solution suggested by the system and the problem is not fixed, please take the device  to either the manufacturer or to the repair shop to get it fixed professionally.')
                break
    else:
        print('Unfortunately the repair centre cannot help you with your problem.')

def get_response(query):
    """Ask the user yes/no style questions and return the results."""
    while True:
        answer = input(query).casefold()
        if answer:
            if any(option.startswith(answer) for option in POSITIVE):
                return True
            if any(option.startswith(answer) for option in NEGATIVE):
                return False
        print('Please respond with the positive or negative answer listed : yes, true, correct, no, false, incorrect.')

if __name__ == '__main__':
    main()

However how can i store all the solutions in a text file and make the keywords stored in python link to it depending on the user input.
I want a specific line from the text file to be outputted to the user.
Help will be appreciated

Body:
We're going to store the keywords and solutions in a csv file. The first entry on each line will be the solution, and all the others will be keywords that direct to this solution.

from collections import defaultdict
import csv

sol_dict = defaultdict(set)
with open('solutions.csv', newline='') as f:
    r = csv.reader(f, quotechar='|')
    for solution, *keywords in r:
        for keyword in keywords:
            sol_dict['keyword'].add(solution)

So now we have this dictionary, sol_dict.  We can query a keyword sol_dict['power'] and you get back a set of strings, each a solution.  (When you make the csv, if you want commas in the solution, you can wrap it in the quotechar, |).

Then walking through the solutions would look something like

problem = input('What is your problem?')
for solution in set.union(*(sol_dict[word] for word in problem.split())):
    # Whatever you want to do with solutions
    print(solution)


问:
css how to cancel a transition in progress

const myButt = document.getElementById('my-butt');

myButt.style.transform = 'rotate(1turn)';

myButt.addEventListener('mouseenter', function() {
  myButt.style.transition = 'transform 10s';

  myButt.classList.add('no');
});

myButt.addEventListener('mouseleave', function() {
  myButt.style.removeProperty('transition');

  myButt.style.transform = 'rotate(0turn)';
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#my-butt{
  width: 100px;
  height:100px;
}
.no{
  transform:  none!important;
}</code>```

<button id="my-butt">
  over my dead butt
</button>```

the button is initially rotated 360 degrees. When mouse over it, the button starts to rotate back to 0 degree, this takes 10 seconds. While the animation is playing, if the mouse leaves the button, the button should immediately jump to 0 degree without any further transitions.

So, in other words, I want the transition to end immediately if mouse leaves button and just jump to 0 degrees.

You can run the code snippet, it currently doesn't work.

答:
Ok, never mind.

Removing the transform: none!important class in the mouseleave event before setting rotate(0turn) seems to work.

Body:
const myButt = document.getElementById('my-butt');

myButt.style.transform = 'rotate(1turn)';

myButt.addEventListener('mouseenter', function() {
  myButt.style.transition = 'transform 10s';

  myButt.classList.add('no');
});

myButt.addEventListener('mouseleave', function() {
  myButt.style.removeProperty('transition');

  myButt.style.transform = 'rotate(0turn)';
});

#my-butt{
  width: 100px;
  height:100px;
}
.no{
  transform:  none!important;
}

<button id="my-butt">
  over my dead butt
</button>

the button is initially rotated 360 degrees. When mouse over it, the button starts to rotate back to 0 degree, this takes 10 seconds. While the animation is playing, if the mouse leaves the button, the button should immediately jump to 0 degree without any further transitions.

So, in other words, I want the transition to end immediately if mouse leaves button and just jump to 0 degrees.

You can run the code snippet, it currently doesn't work.


问:
Codenameone ShareButton - Sharing URL and Image content to Facebook
I have a Codenameone ShareButton in my app, when pressed opens a dialog containing a list of the standard social media apps, that i have on my device, eg. Facebook, SMS, Email, Twitter.

I am trying to get a combination of text, image and URL into the ShareButton dialog for Facebook, but failing. It seems to work for the other types of media. I have scoured StackOverflow without luck on this one.

I can share an image to facebook successfully:

```<code>ShareButton sb = new ShareButton();
sb.setImageToShare(imageFile, "image/png");
</code>```

I can share a URL to facebook successfully:

```<code>ShareButton sb = new ShareButton();
sb.setTextToShare("www.mywebsite.co.uk");
</code>```

My goal is to share a piece of text, a URL and an image to facebook (which i can do to other media). My issues are:

Text wont display in the facebook app dialog:

ShareButton sb = new ShareButton();

sb.setTextToShare("The text i want to display");

I have seen conflicting posts over the years about FB support for this, so maybe i'm doomed on this one.
I tried to trick it and prefix or suffix text to the URL but this didn't display that text still.

So I want to display an image and a URL in the post to FB and it really is just one or the other it seems. So the code below will display just the URL on its own in the FB dialog without the image (swapping out the URL for regular text, displays the image and no text):

ShareButton sb = new ShareButton();

sb.setImageToShare(imageFile, "image/png");

sb.setTextToShare("www.mywebsite.co.uk");

I'd be happy with just option 2 if needs be.

To be clear i'm using the facebook app on my device to share and not a token connection direct to facebook.
And if it helps i do have my own website, if there was a way to send it content and it dynamically build up the content for display, but that may not be possible (i'm no web developer).

答:
As far as I recall from the last time I was dealing with posting to facebook, they don't allow you to post both an image and text, or a URL and text together.  If you want to have something show up in the user's feed that includes both an image and a description, you'll need to create a web page that includes Facebook's supported Open Graph markup, which will cause it to be displayed "nicely" in the user's feed.

In projects I have worked on in the past, they used dynamic webpages so that it was easy to create a webpage that was specific to the content you want to post in the user's feed.  You can essentially generate a separate webpage for each "share" if necessary.

We used the feed API directly.  I'm not sure if it works from the share button, but if you were able to post a URL, then it probably works.

Body:
I have a Codenameone ShareButton in my app, when pressed opens a dialog containing a list of the standard social media apps, that i have on my device, eg. Facebook, SMS, Email, Twitter.

I am trying to get a combination of text, image and URL into the ShareButton dialog for Facebook, but failing. It seems to work for the other types of media. I have scoured StackOverflow without luck on this one.

I can share an image to facebook successfully:

ShareButton sb = new ShareButton();
sb.setImageToShare(imageFile, "image/png");

I can share a URL to facebook successfully:

ShareButton sb = new ShareButton();
sb.setTextToShare("www.mywebsite.co.uk");

My goal is to share a piece of text, a URL and an image to facebook (which i can do to other media). My issues are:

Text wont display in the facebook app dialog:

ShareButton sb = new ShareButton();

sb.setTextToShare("The text i want to display");

I have seen conflicting posts over the years about FB support for this, so maybe i'm doomed on this one.
I tried to trick it and prefix or suffix text to the URL but this didn't display that text still.

So I want to display an image and a URL in the post to FB and it really is just one or the other it seems. So the code below will display just the URL on its own in the FB dialog without the image (swapping out the URL for regular text, displays the image and no text):

ShareButton sb = new ShareButton();

sb.setImageToShare(imageFile, "image/png");

sb.setTextToShare("www.mywebsite.co.uk");

I'd be happy with just option 2 if needs be.

To be clear i'm using the facebook app on my device to share and not a token connection direct to facebook.
And if it helps i do have my own website, if there was a way to send it content and it dynamically build up the content for display, but that may not be possible (i'm no web developer).


问:
Getting Pixel Color from an Image using CGPoint in Swift 3
I am try this PixelExtractor class in Swift 3, get a error;
Cannot invoke initializer for type 'UnsafePointer' with an argument list of type '(UnsafeMutableRawPointer?)'

```<code>class PixelExtractor: NSObject {

let image: CGImage
let context: CGContextRef?

var width: Int {
    get {
        return CGImageGetWidth(image)
    }
}

var height: Int {
    get {
        return CGImageGetHeight(image)
    }
}

init(img: CGImage) {
    image = img
    context = PixelExtractor.createBitmapContext(img)
}

class func createBitmapContext(img: CGImage) -> CGContextRef {

    // Get image width, height
    let pixelsWide = CGImageGetWidth(img)
    let pixelsHigh = CGImageGetHeight(img)

    let bitmapBytesPerRow = pixelsWide * 4
    let bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh)

    // Use the generic RGB color space.
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    // Allocate memory for image data. This is the destination in memory
    // where any drawing to the bitmap context will be rendered.
    let bitmapData = malloc(bitmapByteCount)
    let bitmapInfo = CGBitmapInfo(rawValue:   CGImageAlphaInfo.PremultipliedFirst.rawValue)
    let size = CGSizeMake(CGFloat(pixelsWide), CGFloat(pixelsHigh))
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    // create bitmap
    let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, 8,
    bitmapBytesPerRow, colorSpace, bitmapInfo.rawValue)

    // draw the image onto the context
    let rect = CGRect(x: 0, y: 0, width: pixelsWide, height: pixelsHigh)
    CGContextDrawImage(context, rect, img)

    return context!
}

func colorAt(x x: Int, y: Int)->UIColor {

    assert(0<=x && x<width)
    assert(0<=y && y<height)

    let uncastedData = CGBitmapContextGetData(context)
    let data = UnsafePointer<UInt8>(uncastedData)

    let offset = 4 * (y * width + x)

    let alpha: UInt8 = data[offset]
    let red: UInt8 = data[offset+1]
    let green: UInt8 = data[offset+2]
    let blue: UInt8 = data[offset+3]

    let color = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)

    return color
}
</code>```

}

Fix this error.

```<code>let data = UnsafePointer<UInt8>(uncastedData)
</code>```

->

```<code>let data = UnsafeRawPointer(uncastedData)
</code>```

Get other error; 'Type 'UnsafeRawPointer?' has no subscript members'

How to modify this error?

答:
SWIFT 3 (updated March 2017) Xcode 8 / IOS 10

Important: note that return value corresponds to red: b, green:r and blue: r as in the data they are stored backwards

First, create the extension (you can copy&paste somewhere in your
code)

```<code>extension UIImage {

    func getPixelColor(pos: CGPoint) -> UIColor {

        if let pixelData = self.cgImage?.dataProvider?.data {
            let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

            let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4

            let r = CGFloat(data[pixelInfo+0]) / CGFloat(255.0)
            let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
            let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
            let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)

            return UIColor(red: b, green: g, blue: r, alpha: a)
        } else {
        //IF something is wrong I returned WHITE, but change as needed
            return UIColor.white
        }
    }
}
</code>```

Then just call it as:

```<code>let colorAtPixel : UIColor = (theView.image?.getPixelColor(pos: CGPoint(x: 2, y: 2)))!
</code>```

Although the code returns de exact color, it seems that is not returning the correct one for different CGPoints.

Might it be because of the screen resolution? (x1,x2,x3)?

It would be great if someone can add some light to the mystery...

Body:
I am try this PixelExtractor class in Swift 3, get a error;
Cannot invoke initializer for type 'UnsafePointer' with an argument list of type '(UnsafeMutableRawPointer?)'

class PixelExtractor: NSObject {

let image: CGImage
let context: CGContextRef?

var width: Int {
    get {
        return CGImageGetWidth(image)
    }
}

var height: Int {
    get {
        return CGImageGetHeight(image)
    }
}

init(img: CGImage) {
    image = img
    context = PixelExtractor.createBitmapContext(img)
}

class func createBitmapContext(img: CGImage) -> CGContextRef {

    // Get image width, height
    let pixelsWide = CGImageGetWidth(img)
    let pixelsHigh = CGImageGetHeight(img)

    let bitmapBytesPerRow = pixelsWide * 4
    let bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh)

    // Use the generic RGB color space.
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    // Allocate memory for image data. This is the destination in memory
    // where any drawing to the bitmap context will be rendered.
    let bitmapData = malloc(bitmapByteCount)
    let bitmapInfo = CGBitmapInfo(rawValue:   CGImageAlphaInfo.PremultipliedFirst.rawValue)
    let size = CGSizeMake(CGFloat(pixelsWide), CGFloat(pixelsHigh))
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    // create bitmap
    let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, 8,
    bitmapBytesPerRow, colorSpace, bitmapInfo.rawValue)

    // draw the image onto the context
    let rect = CGRect(x: 0, y: 0, width: pixelsWide, height: pixelsHigh)
    CGContextDrawImage(context, rect, img)

    return context!
}

func colorAt(x x: Int, y: Int)->UIColor {

    assert(0<=x && x<width)
    assert(0<=y && y<height)

    let uncastedData = CGBitmapContextGetData(context)
    let data = UnsafePointer<UInt8>(uncastedData)

    let offset = 4 * (y * width + x)

    let alpha: UInt8 = data[offset]
    let red: UInt8 = data[offset+1]
    let green: UInt8 = data[offset+2]
    let blue: UInt8 = data[offset+3]

    let color = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)

    return color
}

}

Fix this error.

let data = UnsafePointer<UInt8>(uncastedData)

->

let data = UnsafeRawPointer(uncastedData)

Get other error; 'Type 'UnsafeRawPointer?' has no subscript members'

How to modify this error?

Body:
SWIFT 3 (updated March 2017) Xcode 8 / IOS 10

Important: note that return value corresponds to red: b, green:r and blue: r as in the data they are stored backwards

First, create the extension (you can copy&paste somewhere in your
code)

extension UIImage {

    func getPixelColor(pos: CGPoint) -> UIColor {

        if let pixelData = self.cgImage?.dataProvider?.data {
            let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

            let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4

            let r = CGFloat(data[pixelInfo+0]) / CGFloat(255.0)
            let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
            let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
            let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)

            return UIColor(red: b, green: g, blue: r, alpha: a)
        } else {
        //IF something is wrong I returned WHITE, but change as needed
            return UIColor.white
        }
    }
}

Then just call it as:

let colorAtPixel : UIColor = (theView.image?.getPixelColor(pos: CGPoint(x: 2, y: 2)))!

Although the code returns de exact color, it seems that is not returning the correct one for different CGPoints.

Might it be because of the screen resolution? (x1,x2,x3)?

It would be great if someone can add some light to the mystery...


问:
Berkeley Db platform migration
I have a large (several Gb) berkeley db that I am thinking of migrating from windows (2K) to Linux (either Redhat or Ubuntu). I am not sure how to go about this. Can I merely move the db files accross, or do I need a special conversion utility?</p>

答:
Database and log files are portable across different endian systems.  Berkeley DB will recognize the kind of system it is on and swap bytes accordingly for data structures it manages that make up the database itself.  Berkeley DB's region files, which are memory mapped, are not portable.  That's not such a big deal because they region files hold the cache and locks which, because your application will not be running during the transition, will be re-created on the new system.

But, be careful, Berkeley DB doesn't know anything about the byte-order or types in your data (in your keys and values, stored at "DBTs").  Your application code is responsible for knowing what kind of system it is running on, how it stored the data (big or little endian) and how to transition it (or simple re-order on access).  Also, pay close attention to your btree comparison function.  That too may be different depending on your system's architecture.

Database and log files are also portable across operating systems with the same caveat as with byte-ordering -- the application's data is the application's responsibility.

You might consider reviewing the following:

Selecting a Byte Order

DB->set_lorder()

Berkeley DB's Getting Started Guide for Transactional Applications

Berkeley DB's Reference Guide

Voice-over presentation about Berkeley DB/DS (Data Store)

Voice-over presentation about Berkeley DB/CDS (Concurrent Data Store)

Berkeley DB's Documentation

Disclosure: I work for Oracle as a product manager for Berkeley DB products.  :)

ContentLicense: CC BY-SA 2.5

Title: Berkeley Db platform migration


问:
Calling void function before main()
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...

```<code>#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}

int g_foo = (earlyInit(), 0);

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}
</code>```

...I have no need for g_foo and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?

答:
Check if your compiler supports #pragma startup (or equivalent), eg:

```<code>#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}
#pragma startup earlyInit

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}
</code>```

Title: Calling void function before main()

Body:
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...

#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}

int g_foo = (earlyInit(), 0);

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}

...I have no need for g_foo and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?

Body:
Check if your compiler supports #pragma startup (or equivalent), eg:

#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}
#pragma startup earlyInit

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}


问:
interactive brokers api lagging behind tws when using 100 symbols
I haven't been having this problem until I started putting more symbols up on my screeen.  I don't think it's a processing thing, my cpu has been fine and I'm not doing anything super super fancy anyways (just storing data to objects and writing to txt files every so often).

From day 1 with the api, I noticed that I had to put a sleep(1) in the while loop that constantly checks for messages, like so:

```<code>PosixTestClient client;
client.connect( host, port, clientId);
while( client.isConnected()) {
        sleep(1);
        client.processMessages();
    }
</code>```

If I don't have that sleep(1) there, it just crashes.  So I guess my first question is:  is that normal?  Or is something wrong with that?

And my next question is... any tips as to why there might be a lag in the api data as compared to the tws data?  I know there's a lag because as the data comes into the api, I'm storing it to strings and then every minute writing the data to text files.  Then I go back through my text files and compare it to the charts in tws... and I notice there's about a 2min lag!  I also notice it seems to get better (the lag goes away) after the first half hour of the trading day, when things are pretty active.

So... any advice?

答:
So... with the help of the very helpful and friendly yahoo TWS API users group: https://groups.io/g/twsapi/messages

I was able to find the answer, which was simply:

reduce the sleep time!  Running it with no sleep in between the client.proccessMessages() would cause my cpu to run pretty high, but all I needed to really relax cpu was to just sleep for a milisecond... not a whole second.  Sleeping for a whole second was causing a lag in data (I suspect that IB ques the data and then 'sends' it to you when you call proccessMessages(), so you need to call that often enough to stay ahead of the tick data you are receiving!)

For anyone who wants to read it in more detail, here was the thread: https://groups.io/g/twsapi/topic/4702705#37186

Fingers crossed that it continues to work, but today I got good data on 100 high-volume tickers with no lag :)

Body:
I haven't been having this problem until I started putting more symbols up on my screeen.  I don't think it's a processing thing, my cpu has been fine and I'm not doing anything super super fancy anyways (just storing data to objects and writing to txt files every so often).

From day 1 with the api, I noticed that I had to put a sleep(1) in the while loop that constantly checks for messages, like so:

PosixTestClient client;
client.connect( host, port, clientId);
while( client.isConnected()) {
        sleep(1);
        client.processMessages();
    }

If I don't have that sleep(1) there, it just crashes.  So I guess my first question is:  is that normal?  Or is something wrong with that?

And my next question is... any tips as to why there might be a lag in the api data as compared to the tws data?  I know there's a lag because as the data comes into the api, I'm storing it to strings and then every minute writing the data to text files.  Then I go back through my text files and compare it to the charts in tws... and I notice there's about a 2min lag!  I also notice it seems to get better (the lag goes away) after the first half hour of the trading day, when things are pretty active.

So... any advice?


问:
Rotating a triangle around a fixed point
I'm trying to recreate the game Asteroids and I'm currently getting the ship to display and move on the screen. At the moment I've got the function below which draws a triangle on the screen around an origin. What I'm trying to do is rotate the ship around the origin too.

At the moment the triangle gets completely warped by this function and I'm not sure what's going wrong. The angle I'm trying to rotate around is shipHeading and I'm trying to follow this formula:

x' = x cos f - y sin f
y' = y cos f + x sin f

where f is equal to the angle of rotation

```<code>void drawShip(void){
    int shipX = getShipX();
    int shipY = getShipY();
    int shipHeading = getShipHeading();

    int x1, y1, x2, y2, x3, y3;

    x1 = shipX;
    y1 = shipY - 20;
    x2 = shipX - 10;
    y2 = shipY + 10;
    x3 = shipX + 10;
    y3 = shipY + 10;

    screen->drawTriangle(x1, y1, x2, y2, x3, y3, RED); //pre rotation

    x1 = (x1 * cos(double(shipHeading))) - (y1 * sin(double(shipHeading)));
    y1 = (x1 * sin(double(shipHeading))) + (y1 * cos(double(shipHeading)));
    x2 = (x2 * cos(double(shipHeading))) - (y2 * sin(double(shipHeading)));
    y2 = (x2 * sin(double(shipHeading))) + (y2 * cos(double(shipHeading)));
    x3 = (x3 * cos(double(shipHeading))) - (y3 * sin(double(shipHeading)));
    y3 = (x3 * sin(double(shipHeading))) + (y3 * cos(double(shipHeading)));

    x1 *= -1;
    y1 *= -1;
    x2 *= -1;
    y2 *= -1;
    x3 *= -1;
    y3 *= -1;

    screen->drawTriangle(x1, y1, x2, y2, x3, y3, BLUE); //post rotation
</code>```

答:
The issue seems to be related to overwriting x1, y1, ... during the rotation.
Introduce post transformation versions of your coordinates and it might work better.</p>

Body:
I'm trying to recreate the game Asteroids and I'm currently getting the ship to display and move on the screen. At the moment I've got the function below which draws a triangle on the screen around an origin. What I'm trying to do is rotate the ship around the origin too.

At the moment the triangle gets completely warped by this function and I'm not sure what's going wrong. The angle I'm trying to rotate around is shipHeading and I'm trying to follow this formula:

x' = x cos f - y sin f
y' = y cos f + x sin f

where f is equal to the angle of rotation

void drawShip(void){
    int shipX = getShipX();
    int shipY = getShipY();
    int shipHeading = getShipHeading();

    int x1, y1, x2, y2, x3, y3;

    x1 = shipX;
    y1 = shipY - 20;
    x2 = shipX - 10;
    y2 = shipY + 10;
    x3 = shipX + 10;
    y3 = shipY + 10;

    screen->drawTriangle(x1, y1, x2, y2, x3, y3, RED); //pre rotation

    x1 = (x1 * cos(double(shipHeading))) - (y1 * sin(double(shipHeading)));
    y1 = (x1 * sin(double(shipHeading))) + (y1 * cos(double(shipHeading)));
    x2 = (x2 * cos(double(shipHeading))) - (y2 * sin(double(shipHeading)));
    y2 = (x2 * sin(double(shipHeading))) + (y2 * cos(double(shipHeading)));
    x3 = (x3 * cos(double(shipHeading))) - (y3 * sin(double(shipHeading)));
    y3 = (x3 * sin(double(shipHeading))) + (y3 * cos(double(shipHeading)));

    x1 *= -1;
    y1 *= -1;
    x2 *= -1;
    y2 *= -1;
    x3 *= -1;
    y3 *= -1;

    screen->drawTriangle(x1, y1, x2, y2, x3, y3, BLUE); //post rotation


问:
Since tvOS 10.2 the Apple TV displays a Airplay connection requires iOS 7.1 or later error
I have an Android app that can use AirPlay to play videos. Since my Apple TV 4 updated to tvOS 10.2 it has stopped working. I tried several other apps on Android and they all get the same error.

Does anyone know how to get around this issue?

Thanks.

答:
In my scenario the AirPlay connection message shows every 30 seconds even though I am not trying to AirPlay to the Apple TV.
I have a hunch this may be related to the mDNS gateway on my Cisco 2504 Wireless LAN Controller.
The 2504 WLAN controller has mDNS support for apple Airplay but acts as a mDNS proxy/gateway between WLAN traffic encapsulated within the CAPWAP tunnel and LAN traffic.

But i have not confirmed this yet.


问:
Bintray gradle plugin not uploading artifacts
I am using bintray gradle plugin to upload java artifact on Bintray. I have written this code from example, it creates package and version successfully but there are not files in files directory. What am I missing here??</p>

```<code>bintray {
    user = 'user name'
    key = 'my key'
    pkg {
        repo = 'androids'
        name = 'name'
        licenses = ['Apache-2.0']
        vcsUrl = 'https://github.com/bintray/gradle-bintray-plugin.git'
        version {
            name = 'version'
            desc = 'Gradle Bintray Plugin 1.0 final'
            released  = new Date()
            vcsTag = '1.3.0'
            attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin']
        }

        filesSpec {
            from 'build/libs'
            into 'standalone_files/level1'
        }
    }

}
</code>```

答:
From your tag I assume you are working on an Android project. I had a similar problem. Then I realized build/lib from the plugin documentation is just a placeholder. I had to set mine to where my library's aar was stored:

```<code>filesSpec {
    from 'build/outputs/aar'
    into '.'
}
</code>```

If you're ever unclear you can always just upload current directory, see what actually gets uploaded to Bintray, and then get a gauge of where it's actually looking:

```<code>filesSpec {
    from '.'
    into '.'
}
</code>```

Body:
I am using bintray gradle plugin to upload java artifact on Bintray. I have written this code from example, it creates package and version successfully but there are not files in files directory. What am I missing here??

bintray {
    user = 'user name'
    key = 'my key'
    pkg {
        repo = 'androids'
        name = 'name'
        licenses = ['Apache-2.0']
        vcsUrl = 'https://github.com/bintray/gradle-bintray-plugin.git'
        version {
            name = 'version'
            desc = 'Gradle Bintray Plugin 1.0 final'
            released  = new Date()
            vcsTag = '1.3.0'
            attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin']
        }

        filesSpec {
            from 'build/libs'
            into 'standalone_files/level1'
        }
    }

}

Body:
From your tag I assume you are working on an Android project. I had a similar problem. Then I realized build/lib from the plugin documentation is just a placeholder. I had to set mine to where my library's aar was stored:

filesSpec {
    from 'build/outputs/aar'
    into '.'
}

If you're ever unclear you can always just upload current directory, see what actually gets uploaded to Bintray, and then get a gauge of where it's actually looking:

filesSpec {
    from '.'
    into '.'
}


问:
Using Dropwizard Authentication manual
I'm currently using http://www.dropwizard.io/1.1.0/docs/manual/auth.html# Dropwizard-Authentication in my Application. But i like to do the authentication "manualy" which means from a specific login/logout API call on a not authenticated REST interface.

Is there any possibility to forward an REST Call to the Authentication?

```<code>@POST
@Path("login")
@Consumes(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Optional<LoginResponse> login(LoginRequest request) {
    // TODO forward login request to authentication
    return null;
}
</code>```

Thx in advance

答:
Thx for helping me. I found a solution like that:

Adding an Authenticator to the REST Client

```<code>    client = ClientBuilder.newClient();
    authenticator = new Authenticator();
    client.register(authenticator);
</code>```

Setup the Authenticator on Login-Successfull

```<code>    final UserAPIResponse response = create(request, UserAPI.PATH_ATTRIBUTE_DEFINITION_LOGIN);
    if (response == null || response.isFailed()) {
        connector.setupAuthenticator(null, null);
    } else {
        connector.setupAuthenticator(request.getUsername(), request.getPassword());
    }
</code>```

And here is the Authenticator

```<code>class Authenticator implements ClientRequestFilter {

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    final MultivaluedMap<String, Object> headers = requestContext.getHeaders();
    final String basicAuthentication = getBasicAuthentication();
    if (basicAuthentication == null) return;
    headers.add("Authorization", basicAuthentication);

}

void setup(String username, String password) {
    this.user = username;
    this.password = password;
}

private String getBasicAuthentication() {
    if (user == null || password == null) return null;
    final String token = this.user + ":" + this.password;
    try {
        return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException ex) {
        throw new IllegalStateException("Cannot encode with UTF-8", ex);
    }
}

private String password;

private String user;
</code>```

}

on the server side i have an Authenticator

```<code>public class UserAuthenticator implements Authenticator<BasicCredentials, User> {

UserAuthenticator(UserDAO userDAO) {
    this.userDAO = userDAO;
}

@UnitOfWork
@Override
public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
    final String username = credentials.getUsername();
    final Optional<DbUser> result = userDAO.getByName(username);
    if (!result.isPresent()) return Optional.empty();

    final DbUser user = result.get();
    final String password = credentials.getPassword();
    if (!StringUtils.equals(password, user.getPassword())) return Optional.empty();

    if (!user.isOnline()) return Optional.empty();
    user.handleAction();
    userDAO.save(user);

    return Optional.of(UserMgr.convert(user));
}

private final UserDAO userDAO;
</code>```

}

And to get em working correctly:

```<code>SessionDao dao = new SessionDao(hibernateBundle.getSessionFactory());
ExampleAuthenticator exampleAuthenticator = new      UnitOfWorkAwareProxyFactory(hibernateBundle)
           .create(ExampleAuthenticator.class, SessionDao.class, dao);
</code>```

So finally there is one REST-Call to login the User and the authentication is done on the result by the client automatically.

Title: Using Dropwizard Authentication manual

Body:
I'm currently using http://www.dropwizard.io/1.1.0/docs/manual/auth.html# Dropwizard-Authentication in my Application. But i like to do the authentication "manualy" which means from a specific login/logout API call on a not authenticated REST interface.

Is there any possibility to forward an REST Call to the Authentication?

@POST
@Path("login")
@Consumes(MediaType.APPLICATION_JSON)
@Timed
@UnitOfWork
public Optional<LoginResponse> login(LoginRequest request) {
    // TODO forward login request to authentication
    return null;
}

Thx in advance

Body:
Thx for helping me. I found a solution like that:

Adding an Authenticator to the REST Client

    client = ClientBuilder.newClient();
    authenticator = new Authenticator();
    client.register(authenticator);

Setup the Authenticator on Login-Successfull

    final UserAPIResponse response = create(request, UserAPI.PATH_ATTRIBUTE_DEFINITION_LOGIN);
    if (response == null || response.isFailed()) {
        connector.setupAuthenticator(null, null);
    } else {
        connector.setupAuthenticator(request.getUsername(), request.getPassword());
    }

And here is the Authenticator

class Authenticator implements ClientRequestFilter {

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    final MultivaluedMap<String, Object> headers = requestContext.getHeaders();
    final String basicAuthentication = getBasicAuthentication();
    if (basicAuthentication == null) return;
    headers.add("Authorization", basicAuthentication);

}

void setup(String username, String password) {
    this.user = username;
    this.password = password;
}

private String getBasicAuthentication() {
    if (user == null || password == null) return null;
    final String token = this.user + ":" + this.password;
    try {
        return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException ex) {
        throw new IllegalStateException("Cannot encode with UTF-8", ex);
    }
}

private String password;

private String user;

}

on the server side i have an Authenticator

public class UserAuthenticator implements Authenticator<BasicCredentials, User> {

UserAuthenticator(UserDAO userDAO) {
    this.userDAO = userDAO;
}

@UnitOfWork
@Override
public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
    final String username = credentials.getUsername();
    final Optional<DbUser> result = userDAO.getByName(username);
    if (!result.isPresent()) return Optional.empty();

    final DbUser user = result.get();
    final String password = credentials.getPassword();
    if (!StringUtils.equals(password, user.getPassword())) return Optional.empty();

    if (!user.isOnline()) return Optional.empty();
    user.handleAction();
    userDAO.save(user);

    return Optional.of(UserMgr.convert(user));
}

private final UserDAO userDAO;

}

And to get em working correctly:

SessionDao dao = new SessionDao(hibernateBundle.getSessionFactory());
ExampleAuthenticator exampleAuthenticator = new      UnitOfWorkAwareProxyFactory(hibernateBundle)
           .create(ExampleAuthenticator.class, SessionDao.class, dao);

So finally there is one REST-Call to login the User and the authentication is done on the result by the client automatically.


问:
Should we base heavily on local jwt token expiry date to authenticate user
I am learning angular2 by following some tutorials on the web. When making a login page using jwt token, lots of examples approach like:
- when user inputs email and password, submit event will call authentication api
- successed authentication will return a token with expiry date in payload. This token is stored in localstorage
- restricted routes navigation will check authenticated user by getItem from localstorage, check token existence and expiry date

My problem is:
I can easily go to jwt.io with the token in localstorage, change the expiry number to something else later, copy the new generated token and manually paste back to localstorage item

My thought:
Call api tokenValidation before any route navigation, bit it seems will introduce lots of server calls

Appriciate your thoughts

答:
No, you can't do that. The whole point of JWT tokens is that they are cryptographically signed, using a key that only the server knows. So if you try to tamper with the expiry date or anything else in the token, the server will detect that the signature does not match, and will reject the token.

So yes, you'll be able to go to the guarded route, but as soon as you try to make an HTTP request, you'll get an error from the backend (or at least you should get one). The client-side guard is not really a security measure: the code of the component is available anyway in the downloaded bundle. It's an ergonomic measure: if the user can't access a route, he/she can be automatically redirected to the login page, for example.


问:
GraphQL wont return results (returns null)
The following code creates the queries and interacts with my API as I see message: 'Cast to ObjectId failed for value "58d" at path "_id" foron my api logs when I type a random number in to graphqli.

So I know its hitting the API using node-fetch but don't know why it isn't returning my name. I'm using:

```<code>{
  language(id:"58d80f843ad415941d8f908b"){
    name
  }
}
</code>```

I have build my API with mongoose and NodeJS. Can someone please help :(

```<code>var fetch = require('node-fetch');
var { GraphQLSchema } = require('graphql');
var { GraphQLObjectType } = require('graphql');
var { GraphQLString } = require('graphql');

var BASE_URL = "http://localhost:3030";

function getLanguageByURL(relativeURL){
  return fetch(`${BASE_URL}${relativeURL}`)
     .then(res => res.json())
     .then(json => json.language)
}
var LanguageType = new GraphQLObjectType({
  name: 'Language',
  description: '...',

  fields: () => ({
    name: {type: GraphQLString},
  }),
});

var QueryType = new GraphQLObjectType({
  name: 'Query',
  description: '...',

  fields: () => ({
    language: {
        type: LanguageType,
        args: {
            id: {type: GraphQLString},
        },

        resolve: (root, args) =>
            getLanguageByURL(`/languages/${args.id}`)
    }
  }),
});

module.exports.schema = new GraphQLSchema({
  query: QueryType,
});
</code>```

答: I was getting node-fetch to return the wrong data in my getLanguageByURL function where I was converting the response into JSON which is great but right after I was doing (json => json.language)which was going into that json and asking for a "language" object which didn't exist in my array of objects. I removed this line and my query works perfectly.

Body:
The following code creates the queries and interacts with my API as I see message: 'Cast to ObjectId failed for value "58d" at path "_id" foron my api logs when I type a random number in to graphqli.

So I know its hitting the API using node-fetch but don't know why it isn't returning my name. I'm using:

{
  language(id:"58d80f843ad415941d8f908b"){
    name
  }
}

I have build my API with mongoose and NodeJS. Can someone please help :(

var fetch = require('node-fetch');
var { GraphQLSchema } = require('graphql');
var { GraphQLObjectType } = require('graphql');
var { GraphQLString } = require('graphql');

var BASE_URL = "http://localhost:3030";

function getLanguageByURL(relativeURL){
  return fetch(`${BASE_URL}${relativeURL}`)
     .then(res => res.json())
     .then(json => json.language)
}
var LanguageType = new GraphQLObjectType({
  name: 'Language',
  description: '...',

  fields: () => ({
    name: {type: GraphQLString},
  }),
});

var QueryType = new GraphQLObjectType({
  name: 'Query',
  description: '...',

  fields: () => ({
    language: {
        type: LanguageType,
        args: {
            id: {type: GraphQLString},
        },

        resolve: (root, args) =>
            getLanguageByURL(`/languages/${args.id}`)
    }
  }),
});

module.exports.schema = new GraphQLSchema({
  query: QueryType,
});


问:
Neested loops in pandas python
I have two DataFrames One with many rows and another one with a few rows and I need to merge these two Dataframes according some conditions (in strings). I used nested loops in Pandas like this:

```<code>density = []

for row in df.itertuples():
    for row1 in df2.itertuples():
        if(row['a'].find(row1['b']))>0:
            density.append(row1['c'])
</code>```

But I receive the error message:

```<code>TypeError: tuple indices must be integers, not str
</code>```

What's wrong?

答:
The method DataFrame.itertuples returns namedtuples and to access the values in a namedtuple you have to use the dot notation.

```<code>density = []
for row in df.itertuples():
    for row1 in df2.itertuples():
        if row.a.find(row1.b) > 0:
            density.append(row1.c)
</code>```

Nevertheless, this does not produce a merge of the two DataFrames.

Title: Neested loops in pandas python

Body:
I have two DataFrames One with many rows and another one with a few rows and I need to merge these two Dataframes according some conditions (in strings). I used nested loops in Pandas like this:

density = []

for row in df.itertuples():
    for row1 in df2.itertuples():
        if(row['a'].find(row1['b']))>0:
            density.append(row1['c'])

But I receive the error message:

TypeError: tuple indices must be integers, not str

What's wrong?

Body:
The method DataFrame.itertuples returns namedtuples and to access the values in a namedtuple you have to use the dot notation.

density = []
for row in df.itertuples():
    for row1 in df2.itertuples():
        if row.a.find(row1.b) > 0:
            density.append(row1.c)

Nevertheless, this does not produce a merge of the two DataFrames.


问:
Getting 'too many parameters passed' to stored procedure on ASPX page
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

```<code>"Procedure or function <sp_name> has too many arguments specified."
</code>```

Here is the code for the grid and the datasource:

```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>
</code>```

Here's the code from the stored procedure:

```<code>ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END
</code>```

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

```<code>        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }
</code>```

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?

答:
It is security related, your web.config must indicate a different connection string setup (digest authentication or user login)
while your stored procedure requires either one of them
check your stored procedure security.</p>

Body:
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

"Procedure or function <sp_name> has too many arguments specified."

Here is the code for the grid and the datasource:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>

Here's the code from the stored procedure:

ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?


问:
Java- How to manage a database connection in a large java project
The main question is that in a a large/big java project with multiple classes having multiple db connection,

Should we use a global Single Connection to db and run it till the program ends and close it at the end of program or
Should we use multiple db connections whenever it is required ?
which is better in terms of security , ease of access.

答:
Better to hand over connection management to a connection pool like Tomcat JDBC Pool.

List of advantages taken from Official doc,

Features added over other connection pool implementations

1.Support for highly concurrent environments and multi core/cpu systems.

2.Dynamic implementation of interface, will support java.sql and javax.sql interfaces for your runtime environment (as long as your
  JDBC driver does the same), even when compiled with a lower version of
  the JDK.

3.Validation intervals - we don't have to validate every single time we use the connection, we can do this when we borrow or return the
  connection, just not more frequent than an interval we can configure.

4.Run-Once query, a configurable query that will be run only once, when the connection to the database is established. Very useful to
  setup session settings, that you want to exist during the entire time
  the connection is established.

5.Ability to configure custom interceptors. This allows you to write custom interceptors to enhance the functionality. You can use
  interceptors to gather query stats, cache session states, reconnect
  the connection upon failures, retry queries, cache query results, and
  so on. Your options are endless and the interceptors are dynamic, not
  tied to a JDK version of a java.sql/javax.sql interface.

6.High performance - we will show some differences in performance later on

7.Extremely simple, due to the very simplified implementation, the line count and source file count are very low, compare with c3p0 that
  has over 200 source files(last time we checked), Tomcat jdbc has a
  core of 8 files, the connection pool itself is about half that. As
  bugs may occur, they will be faster to track down, and easier to fix.
  Complexity reduction has been a focus from inception.

8.Asynchronous connection retrieval - you can queue your request for a connection and receive a Future back.

9.Better idle connection handling. Instead of closing connections directly, it can still pool connections and sizes the idle pool with a
  smarter algorithm.

10.You can decide at what moment connections are considered abandoned, is it when the pool is full, or directly at a timeout by specifying a
  pool usage threshold.

11.The abandon connection timer will reset upon a statement/query activity. Allowing a connections that is in use for a long time to not
  timeout. This is achieved using the ResetAbandonedTimer

12.Close connections after they have been connected for a certain time. Age based close upon return to the pool.

13.Get JMX notifications and log entries when connections are suspected for being abandoned. This is similar to the
  removeAbandonedTimeout but it doesn't take any action, only reports
  the information. This is achieved using the suspectTimeout attribute.

14.Connections can be retrieved from a java.sql.Driver, javax.sql.DataSource or javax.sql.XADataSource This is achieved using
  the dataSource and dataSourceJNDI attributes.

15.XA connection support

Sample:

And here is an example on how to configure a resource for JNDI lookups.

```<code><Resource name="jdbc/TestDB"
          auth="Container"
          type="javax.sql.DataSource"
          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
          testWhileIdle="true"
          testOnBorrow="true"
          testOnReturn="false"
          validationQuery="SELECT 1"
          validationInterval="30000"
          timeBetweenEvictionRunsMillis="30000"
          maxActive="100"
          minIdle="10"
          maxWait="10000"
          initialSize="10"
          removeAbandonedTimeout="60"
          removeAbandoned="true"
          logAbandoned="true"
          minEvictableIdleTimeMillis="30000"
          jmxEnabled="true"
          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
            org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
          username="root"
          password="password"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/mysql"/>
</code>```

Body:
Better to hand over connection management to a connection pool like Tomcat JDBC Pool.

List of advantages taken from Official doc,

Features added over other connection pool implementations

1.Support for highly concurrent environments and multi core/cpu systems.

2.Dynamic implementation of interface, will support java.sql and javax.sql interfaces for your runtime environment (as long as your
  JDBC driver does the same), even when compiled with a lower version of
  the JDK.

3.Validation intervals - we don't have to validate every single time we use the connection, we can do this when we borrow or return the
  connection, just not more frequent than an interval we can configure.

4.Run-Once query, a configurable query that will be run only once, when the connection to the database is established. Very useful to
  setup session settings, that you want to exist during the entire time
  the connection is established.

5.Ability to configure custom interceptors. This allows you to write custom interceptors to enhance the functionality. You can use
  interceptors to gather query stats, cache session states, reconnect
  the connection upon failures, retry queries, cache query results, and
  so on. Your options are endless and the interceptors are dynamic, not
  tied to a JDK version of a java.sql/javax.sql interface.

6.High performance - we will show some differences in performance later on

7.Extremely simple, due to the very simplified implementation, the line count and source file count are very low, compare with c3p0 that
  has over 200 source files(last time we checked), Tomcat jdbc has a
  core of 8 files, the connection pool itself is about half that. As
  bugs may occur, they will be faster to track down, and easier to fix.
  Complexity reduction has been a focus from inception.

8.Asynchronous connection retrieval - you can queue your request for a connection and receive a Future back.

9.Better idle connection handling. Instead of closing connections directly, it can still pool connections and sizes the idle pool with a
  smarter algorithm.

10.You can decide at what moment connections are considered abandoned, is it when the pool is full, or directly at a timeout by specifying a
  pool usage threshold.

11.The abandon connection timer will reset upon a statement/query activity. Allowing a connections that is in use for a long time to not
  timeout. This is achieved using the ResetAbandonedTimer

12.Close connections after they have been connected for a certain time. Age based close upon return to the pool.

13.Get JMX notifications and log entries when connections are suspected for being abandoned. This is similar to the
  removeAbandonedTimeout but it doesn't take any action, only reports
  the information. This is achieved using the suspectTimeout attribute.

14.Connections can be retrieved from a java.sql.Driver, javax.sql.DataSource or javax.sql.XADataSource This is achieved using
  the dataSource and dataSourceJNDI attributes.

15.XA connection support

Sample:

And here is an example on how to configure a resource for JNDI lookups.

<Resource name="jdbc/TestDB"
          auth="Container"
          type="javax.sql.DataSource"
          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
          testWhileIdle="true"
          testOnBorrow="true"
          testOnReturn="false"
          validationQuery="SELECT 1"
          validationInterval="30000"
          timeBetweenEvictionRunsMillis="30000"
          maxActive="100"
          minIdle="10"
          maxWait="10000"
          initialSize="10"
          removeAbandonedTimeout="60"
          removeAbandoned="true"
          logAbandoned="true"
          minEvictableIdleTimeMillis="30000"
          jmxEnabled="true"
          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
            org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
          username="root"
          password="password"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/mysql"/>


问:
iOS Force Clear CoreData on App Update
I'm releasing an update with a few changes to the values in CoreData. The schema is unchanged (it's just JSON strings), but the JSON has. The data is trivial, so I think it's best to just remove it. What's the best way to do this?</p>

答: Fastest way is to delete the sqlite file. But I prefer clearing data of tables one by one because this way I can be sure about what I am deleting. After you cleared the tables it is obvious that you need to keep a flag in DB or UserDefaults to make sure you will not repeat the process.</p>

Title: iOS Force Clear CoreData on App Update


问:
Wordpress Custom Post Type rewrite page and category slug
I have set up a custom post type

```<code>register_post_type( 'Communities',
    array(
        'labels' => array(
        'name' => __( 'Communities' ),
        'singular_name' => __( 'Community' ),
        'not_found' => __( 'No Communities Found' )
        ),
        'public' => true,
        'rewrite' => array( 'slug' => '/%category%/communities', 'with_front' => false),
        'has_archive' => true,
        'hierarchical'  => true,
        'taxonomies'  => array( 'category' ),
        'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
        'menu_icon' => 'dashicons-admin-home'
    )
);
</code>```

I have a pages setup with a city name that I need to remain as a page for different reasons, but I want communities in that city to be stored as a custom post type. I have setup categories for each city that I am adding communities to but I would like them to treat the cityname page as the parent.

like this

```<code>www.sitename.com/cityname/communities/communityname/
</code>```

I would like cityname to be a page, communities to be an archive page and the communityname to be a single page.

Every solution I have found thus far generates 404 errors or conflicts with the parent page.

Any help is appreciated. Thanks!

答:
This should do it for you, but first there are 2 things you should know.

1.) I wouldn't recommend this URL structure as it mandates that every entry have at least ONE category. It will always grab the first in the array. You'll need to write a small plugin to let your authors know. This may do the trick:

https://srd.wordpress.org/plugins/require-post-category/

2.) Before you can view a post, you'll need to visit Settings > permalinks after you add the code so it will force a rewrite flush.

```<code>/**
 * Register Community Custom Post Type
 */
function community_post_type() {

    $labels = array(
        'name'                  => 'Communities',
        'singular_name'         => 'Community',
        'menu_name'             => 'Communities',
        'name_admin_bar'        => 'Communities',
        'archives'              => 'Community Archives',
        'attributes'            => 'Community Attributes',
        'parent_item_colon'     => 'Parent Community:',
        'all_items'             => 'All Communities',
        'add_new_item'          => 'Add New Community',
        'add_new'               => 'Add New',
        'new_item'              => 'New Community',
        'edit_item'             => 'Edit Community',
        'update_item'           => 'Update Community',
        'view_item'             => 'View Community',
        'view_items'            => 'View Communities',
        'search_items'          => 'Search Communities',
        'not_found'             => 'Community Not found',
        'not_found_in_trash'    => 'Not found in Trash',
        'featured_image'        => 'Featured Image',
        'set_featured_image'    => 'Set featured image',
        'remove_featured_image' => 'Remove featured image',
        'use_featured_image'    => 'Use as featured image',
        'insert_into_item'      => 'Insert into item',
        'uploaded_to_this_item' => 'Uploaded to this Community',
        'items_list'            => 'Communities list',
        'items_list_navigation' => 'Communities list navigation',
        'filter_items_list'     => 'Filter Communities list',
    );
    $rewrite = array(
        'slug'                  => '/%category%/communities',
        'with_front'            => true,
        'pages'                 => true,
        'feeds'                 => true,
    );
    $args = array(
        'label'                 => 'Community',
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields', ),
        'taxonomies'            => array( 'category' ),
        'hierarchical'          => true,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-universal-access',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'rewrite'               => $rewrite,
        'capability_type'       => 'page',
        'show_in_rest'          => true,
    );
    register_post_type( 'communities', $args );

}
add_action( 'init', 'community_post_type', 0 );

/**
 * Add category slug to community post links
 * @param  $post_link
 * @param  $id
 */

function my_commmunity_post_link( $post_link, $id = 0 ){
    $post = get_post($id);
    if ( is_object( $post ) && $post->post_type == 'communities' ){
        $terms = wp_get_object_terms( $post->ID, 'category' );
        if( !empty($terms) ){
            return str_replace( '%category%' , $terms[0]->slug , $post_link );
        }
    }
    return $post_link;
}
add_filter( 'post_type_link', 'my_commmunity_post_link', 1, 3 );
</code>```

Body:
I have set up a custom post type

register_post_type( 'Communities',
    array(
        'labels' => array(
        'name' => __( 'Communities' ),
        'singular_name' => __( 'Community' ),
        'not_found' => __( 'No Communities Found' )
        ),
        'public' => true,
        'rewrite' => array( 'slug' => '/%category%/communities', 'with_front' => false),
        'has_archive' => true,
        'hierarchical'  => true,
        'taxonomies'  => array( 'category' ),
        'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
        'menu_icon' => 'dashicons-admin-home'
    )
);

I have a pages setup with a city name that I need to remain as a page for different reasons, but I want communities in that city to be stored as a custom post type. I have setup categories for each city that I am adding communities to but I would like them to treat the cityname page as the parent.

like this

www.sitename.com/cityname/communities/communityname/

I would like cityname to be a page, communities to be an archive page and the communityname to be a single page.

Every solution I have found thus far generates 404 errors or conflicts with the parent page.

Any help is appreciated. Thanks!

Body:
This should do it for you, but first there are 2 things you should know.

1.) I wouldn't recommend this URL structure as it mandates that every entry have at least ONE category. It will always grab the first in the array. You'll need to write a small plugin to let your authors know. This may do the trick:

https://srd.wordpress.org/plugins/require-post-category/

2.) Before you can view a post, you'll need to visit Settings > permalinks after you add the code so it will force a rewrite flush.

/**
 * Register Community Custom Post Type
 */
function community_post_type() {

    $labels = array(
        'name'                  => 'Communities',
        'singular_name'         => 'Community',
        'menu_name'             => 'Communities',
        'name_admin_bar'        => 'Communities',
        'archives'              => 'Community Archives',
        'attributes'            => 'Community Attributes',
        'parent_item_colon'     => 'Parent Community:',
        'all_items'             => 'All Communities',
        'add_new_item'          => 'Add New Community',
        'add_new'               => 'Add New',
        'new_item'              => 'New Community',
        'edit_item'             => 'Edit Community',
        'update_item'           => 'Update Community',
        'view_item'             => 'View Community',
        'view_items'            => 'View Communities',
        'search_items'          => 'Search Communities',
        'not_found'             => 'Community Not found',
        'not_found_in_trash'    => 'Not found in Trash',
        'featured_image'        => 'Featured Image',
        'set_featured_image'    => 'Set featured image',
        'remove_featured_image' => 'Remove featured image',
        'use_featured_image'    => 'Use as featured image',
        'insert_into_item'      => 'Insert into item',
        'uploaded_to_this_item' => 'Uploaded to this Community',
        'items_list'            => 'Communities list',
        'items_list_navigation' => 'Communities list navigation',
        'filter_items_list'     => 'Filter Communities list',
    );
    $rewrite = array(
        'slug'                  => '/%category%/communities',
        'with_front'            => true,
        'pages'                 => true,
        'feeds'                 => true,
    );
    $args = array(
        'label'                 => 'Community',
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields', ),
        'taxonomies'            => array( 'category' ),
        'hierarchical'          => true,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-universal-access',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'rewrite'               => $rewrite,
        'capability_type'       => 'page',
        'show_in_rest'          => true,
    );
    register_post_type( 'communities', $args );

}
add_action( 'init', 'community_post_type', 0 );

/**
 * Add category slug to community post links
 * @param  $post_link
 * @param  $id
 */

function my_commmunity_post_link( $post_link, $id = 0 ){
    $post = get_post($id);
    if ( is_object( $post ) && $post->post_type == 'communities' ){
        $terms = wp_get_object_terms( $post->ID, 'category' );
        if( !empty($terms) ){
            return str_replace( '%category%' , $terms[0]->slug , $post_link );
        }
    }
    return $post_link;
}
add_filter( 'post_type_link', 'my_commmunity_post_link', 1, 3 );


问:
Facing issue while running PHP script
I have a form in HTML which posts two values hostname and ip_address.

```<code><form action="demo-select.php" method="post" />
    <p>HOSTNAME/IPADDRESS: <input type="text" name="HOSTNAME" name="IP_ADDRESS" /></p>
    <input type="submit" value="Submit" />
</form>
</code>```

If I enter the hostname/ip_address and submit it, it will take me to demo-select.php script.

In demo-select.php script I'm able to get the output for hostname from my MySQL db. How should I get the output based on ip_address?

```<code>$value = $_POST['HOSTNAME'];
$query = "SELECT * FROM <tablename> WHERE HOSTNAME='$value'";
$result = mysql_query($query);
</code>```

This script connects to a MySQL db and gets the output based on the hostname. What modifications should I make to get the output based on ip_address as well?

Table columns:

```<code>HOSTNAME
IP_ADDRESS
cpus
MEMORY
</code>```

答:
HTML:

You can't assign two names to an HTML element. I'd suggest that you either use two fields or use a dropdown / radio button along with the form field for the user to specify whether they're entering a hostname or an ip_address:

```<code><form action="demo-select.php" method="post" />

    <select name="address_type">
      <option value="ip"> IP Address </option>
      <option value="host"> Host Name </option>
    </select>

    <input type="text" name="host_name_or_address" />
    <input type="submit" value="Submit" />
</form>
</code>```

An assumption here is that you'd want the user to enter as input only one of hostname or ip_address in a single submit. If you want both to be relayed to the PHP at once, then please get rid of the select dropdown and use two input fields instead.

PHP:

Check what's been received in address_type and determine what query to use accordingly:

```<code>$address_type = $_POST['address_type'];
$value = $_POST['host_name_or_address'];

if($address_type == "host"){
    // If looking for partial matches, use... WHERE HOSTNAME LIKE '%$value'
    $sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value' ";
}
else{
    $sql = "SELECT * FROM <tablename> WHERE IP_ADDRESS = '$value' ";
}
</code>```

Again, if you want both fields to be searched for at once, then along with the HTML edits indicated in the narration above, you'll have to receive in a PHP variable the value of the second input field too. Also then please get rid of the if-else construct here above and write a single, combined query as:

```<code>$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value1' AND IP_ADDRESS = '$value2' ";
</code>```

Finally, please don't use mysql_*() functions in any PHP code. They're long deprecated and are very vulnerable to SQL Injection Attacks as Daniel has already suggested in his answer. Please have a look at MySQLi and PDO Prepared Statements instead. These utilities provide a cleaner way to write your queries and also a much safer mechanism to shield them against potential risks.

Title: Facing issue while running PHP script

Body:
I have a form in HTML which posts two values hostname and ip_address.

<form action="demo-select.php" method="post" />

HOSTNAME/IPADDRESS: <input type="text" name="HOSTNAME" name="IP_ADDRESS" />

    <input type="submit" value="Submit" />
</form>

If I enter the hostname/ip_address and submit it, it will take me to demo-select.php script.

In demo-select.php script I'm able to get the output for hostname from my MySQL db. How should I get the output based on ip_address?

$value = $_POST['HOSTNAME'];
$query = "SELECT * FROM <tablename> WHERE HOSTNAME='$value'";
$result = mysql_query($query);

This script connects to a MySQL db and gets the output based on the hostname. What modifications should I make to get the output based on ip_address as well?

Table columns:

HOSTNAME
IP_ADDRESS
cpus
MEMORY

Body:
HTML:

You can't assign two names to an HTML element. I'd suggest that you either use two fields or use a dropdown / radio button along with the form field for the user to specify whether they're entering a hostname or an ip_address:

<form action="demo-select.php" method="post" />

    <select name="address_type">
      <option value="ip"> IP Address </option>
      <option value="host"> Host Name </option>
    </select>

    <input type="text" name="host_name_or_address" />
    <input type="submit" value="Submit" />
</form>

An assumption here is that you'd want the user to enter as input only one of hostname or ip_address in a single submit. If you want both to be relayed to the PHP at once, then please get rid of the select dropdown and use two input fields instead.

PHP:

Check what's been received in address_type and determine what query to use accordingly:

$address_type = $_POST['address_type'];
$value = $_POST['host_name_or_address'];

if($address_type == "host"){
    // If looking for partial matches, use... WHERE HOSTNAME LIKE '%$value'
    $sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value' ";
}
else{
    $sql = "SELECT * FROM <tablename> WHERE IP_ADDRESS = '$value' ";
}

Again, if you want both fields to be searched for at once, then along with the HTML edits indicated in the narration above, you'll have to receive in a PHP variable the value of the second input field too. Also then please get rid of the if-else construct here above and write a single, combined query as:

$sql = "SELECT * FROM <tablename> WHERE HOSTNAME = '$value1' AND IP_ADDRESS = '$value2' ";

Finally, please don't use mysql_*() functions in any PHP code. They're long deprecated and are very vulnerable to SQL Injection Attacks as Daniel has already suggested in his answer. Please have a look at MySQLi and PDO Prepared Statements instead. These utilities provide a cleaner way to write your queries and also a much safer mechanism to shield them against potential risks.