问:
Proper way to get a specific item by it's property from Doctrine's collections
I'm working with doctrine for the first time in my own project. I'm facing a problem with finding the right object from a collection returned from a doctrine one-to-many relation.

Let's say I have an entity Page which has a lot of Section sub-entities.

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="Pages")
 */
class Page
{
    // bunch of properties

    /**
     * @ORM\OneToMany(targetEntity="Section", mappedBy="page")
     * @var Collection
     */
    protected $sections;

    public function __construct()
    {
        $this->sections = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getSections(): Collection
    {
        return $this->sections;
    }

}
</code>```

Now what I want to achieve is to be able to get the Section by it's name (I should probably mention that the name is a property of the Section entity).

So at the end I want to be able to achieve something similar to:

```<code>class SomeController
{

    public function HomePageAction()
    {
        $page = $this->getEntityManager()
                     ->getRepository('App:Entity:Page')
                     ->findOneBy(array('name' => 'homepage'));

        $section = $page->findSectionByName('header');

        // rendering etc.
    }

}
</code>```

I can, of course, loop through all of the sections and return one that matches the name I'm looking for (throw the exception if none) or I'm wondering if there isn't some easier way to do that? Also, is it something I should do in some sort of custom repository class, or is it ok to leave the method findSectionByName inside the Entity class? Thank you in advance.

So, what I tried so far...

```<code>// class App\Entity\Page
public function getSectionByName(string $name)
{
    foreach ($this->getSections() as $section) {
        if ($section->getName() === $name)
            return $section;
    }
    return null;
}
</code>```

答:
The best practice is to use the matching(Criteria $criteria) function on your collection.

So:

```<code>use Doctrine\Common\Collections\Criteria;

public function getSectionByName(string $name)
{
    $criteria = Criteria::create()
        ->where(Criteria::expr()->eq('name', $name))
        ->setFirstResult(0)
        ->setMaxResults(1);

    return $this->getSections()->matching($criteria)->first();
}
</code>```

If you want to throw a not found exception, the best practice would be to do it in your action:

```<code>public function HomePageAction()
{
    $page = $this->getEntityManager()
                 ->getRepository('App:Entity:Page')
                 ->findOneBy(array('name' => 'homepage'));

    $section = $page->findSectionByName('header');

    if($section === false) {
        //here throw your exception.
    }
    // rendering etc.
}
</code>```

More about filtering doctrine's collections can be found in Doctrine - Working with Associations

Body:
I'm working with doctrine for the first time in my own project. I'm facing a problem with finding the right object from a collection returned from a doctrine one-to-many relation.

Let's say I have an entity Page which has a lot of Section sub-entities.

/**
 * @ORM\Entity
 * @ORM\Table(name="Pages")
 */
class Page
{
    // bunch of properties

    /**
     * @ORM\OneToMany(targetEntity="Section", mappedBy="page")
     * @var Collection
     */
    protected $sections;

    public function __construct()
    {
        $this->sections = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getSections(): Collection
    {
        return $this->sections;
    }

}

Now what I want to achieve is to be able to get the Section by it's name (I should probably mention that the name is a property of the Section entity).

So at the end I want to be able to achieve something similar to:

class SomeController
{

    public function HomePageAction()
    {
        $page = $this->getEntityManager()
                     ->getRepository('App:Entity:Page')
                     ->findOneBy(array('name' => 'homepage'));

        $section = $page->findSectionByName('header');

        // rendering etc.
    }

}

I can, of course, loop through all of the sections and return one that matches the name I'm looking for (throw the exception if none) or I'm wondering if there isn't some easier way to do that? Also, is it something I should do in some sort of custom repository class, or is it ok to leave the method findSectionByName inside the Entity class? Thank you in advance.

So, what I tried so far...

// class App\Entity\Page
public function getSectionByName(string $name)
{
    foreach ($this->getSections() as $section) {
        if ($section->getName() === $name)
            return $section;
    }
    return null;
}

Body:
The best practice is to use the matching(Criteria $criteria) function on your collection.

So:

use Doctrine\Common\Collections\Criteria;

public function getSectionByName(string $name)
{
    $criteria = Criteria::create()
        ->where(Criteria::expr()->eq('name', $name))
        ->setFirstResult(0)
        ->setMaxResults(1);

    return $this->getSections()->matching($criteria)->first();
}

If you want to throw a not found exception, the best practice would be to do it in your action:

public function HomePageAction()
{
    $page = $this->getEntityManager()
                 ->getRepository('App:Entity:Page')
                 ->findOneBy(array('name' => 'homepage'));

    $section = $page->findSectionByName('header');

    if($section === false) {
        //here throw your exception.
    }
    // rendering etc.
}

More about filtering doctrine's collections can be found in Doctrine - Working with Associations


来源: stackexchange

问:
Protractor hard to click popup/dropdown
Hey guys I am trying to click on an element called practitioner access on my company's web site and I have tried looking up documentation on stack over flow and have not figured out how to do this exactly I need help. What I am trying to do is click on the practitioner access popup/drop down and I have not been able to find the code to do it. Please see epic at the bottom:

This is how far I have gotten so far but protractor cant find the element

```<code>var pracaccess = element(by.xpath("//contains(@onclick, 'Practitioner Access')"))
pracaccess.click();
browser.sleep(10000);
</code>```

I have tried to use these site to try and help myself but I can't piece it together. Any help would be appreciated. I am new to xpath as well.

new info to possibly help:
Here is a more expanded view

Also this is what it looks like in vb-script but its basically the same any suggestions?

```<code>Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").WaitProperty "visible",True,30000
        Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").Object.Click
</code>```

答:
The answer by alecxe is correct but if you want it to be as xpath:</p>

```<code>element(by.xpath('//a[text()="Practitioner Access"]'));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Protractor hard to click popup/dropdown

Body:
Hey guys I am trying to click on an element called practitioner access on my company's web site and I have tried looking up documentation on stack over flow and have not figured out how to do this exactly I need help. What I am trying to do is click on the practitioner access popup/drop down and I have not been able to find the code to do it. Please see epic at the bottom:

This is how far I have gotten so far but protractor cant find the element

var pracaccess = element(by.xpath("//contains(@onclick, 'Practitioner Access')"))
pracaccess.click();
browser.sleep(10000);

I have tried to use these site to try and help myself but I can't piece it together. Any help would be appreciated. I am new to xpath as well.

new info to possibly help:
Here is a more expanded view

Also this is what it looks like in vb-script but its basically the same any suggestions?

Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").WaitProperty "visible",True,30000
        Browser("ADP_2").Page("ADP_3").Link("html tag:=A","innertext:=Practitioner Access").Object.Click

Body:
The answer by alecxe is correct but if you want it to be as xpath:

element(by.xpath('//a[text()="Practitioner Access"]'));


问:
checkin a one drive document using graph api
I am trying to checkout a drive item using microsoft graph API
as mentioned in https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_checkout#example

But when I am trying to use graph API explorer it gives me an error
Unsupported segment type. ODataQuery: sites/bluejdemo.sharepoint.com/drives/...

答:
Check-in and check-out are only available in the /beta/ version of Microsoft Graph. I can see how the documentation doesn't make that clear, so sorry about that. I'll make sure we get those docs updated.

Here's call you need to make:

https://graph.microsoft.com/beta/sites/{insert your URL here}/checkout


问:
How can I get the printer HDC
I have a COM component written in C++ that has a Print function. This print function takes the Printer hDC as a parameter that includes all settings to use for the print. Previously, this was called from VB6 code, and Printer.hdc would work here after setting everything on the Printer object.

The code was converted from VB6 to VB.NET, and I have figured out most of things that I need to do. The old Printer object is available through the Microsoft.VisualBasic.PowerPacks.Printing.Compability.VB6.Printer class, but the old hdc property is not supported here.

Can anyone tell me how to get this hdc?
Is this hdc the same as GetHdevmode() on a System.Drawing.Printing.PrinterSettings object?

答:
Here's a similar approach to the one suggested by Hans but it uses a form control. If you are using a form control anyway, this might be a cleaner approach.

Place a PrintDocument from the Windows Forms toolbox to your form.

Then add the following code to handle the print page (as an example):

```<code>Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
  Dim printerhdc As IntPtr = e.Graphics.GetHdc()

  ' Do whatever you need to do to get the right image
  XYZ.Load file(currentpagenumber)
  XYZ.Render(printerhdc.ToInt64, 25, 25, Width, Height)

  CurrentPageNumber += 1

  If CurrentPageNumber < TotalPageCount Then
   e.HasMorePages = True
  Else
   e.HasMorePages = False
  End If
  e.Graphics.ReleaseHdc(printerhdc)
End Sub

...

'Gather all the files you need and put their names in an arraylist.
'Then issue the print command
PrintDocument1.Print

' You've just printed your files
</code>```

source: http://www.vbforums.com/showthread.php?247493-Good-ol-Printer-hDC

(source: http://www.vbforums.com/showthread.php?247493-Good-ol-Printer-hDC)

ContentLicense: CC BY-SA 2.5

Title: How can I get the printer HDC

Body:
Here's a similar approach to the one suggested by Hans but it uses a form control. If you are using a form control anyway, this might be a cleaner approach.

Place a PrintDocument from the Windows Forms toolbox to your form.

Then add the following code to handle the print page (as an example):

Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
  Dim printerhdc As IntPtr = e.Graphics.GetHdc()

  ' Do whatever you need to do to get the right image
  XYZ.Load file(currentpagenumber)
  XYZ.Render(printerhdc.ToInt64, 25, 25, Width, Height)

  CurrentPageNumber += 1

  If CurrentPageNumber < TotalPageCount Then
   e.HasMorePages = True
  Else
   e.HasMorePages = False
  End If
  e.Graphics.ReleaseHdc(printerhdc)
End Sub

...

'Gather all the files you need and put their names in an arraylist.
'Then issue the print command
PrintDocument1.Print

' You've just printed your files

source: http://www.vbforums.com/showthread.php?247493-Good-ol-Printer-hDC

(source: http://www.vbforums.com/showthread.php?247493-Good-ol-Printer-hDC)


问:
Javascript reduce() - What does the return line do?
I understand that it does reduce () in the most basic examples but not in one like this, especially the return line. It would be great if someone could explain how it works or put a more understandable example that returns the same result.</p>

```<code>var line = 'abazzzzax'
var obj = line.split('').reduce(function(p, c){
    return (p[c] = ++p[c] || 1, p);
}, {});
console.log(obj)
// Output => { a: 3, b: 1, z: 4, x: 1 }
</code>```

答:
It counts occurrences of each character in the string.

It's basically

```<code>if accumulator[character] exists, increase number stored in accumulator[character] by 1 (this happens if we have set it already to 1, somewhere in the past, because otherwise it will not exist)
else set accumulator[character] to 1 (this happens when we notice a first character of a new kind)
return accumulator object
</code>```

Body:
I understand that it does reduce () in the most basic examples but not in one like this, especially the return line. It would be great if someone could explain how it works or put a more understandable example that returns the same result.

var line = 'abazzzzax'
var obj = line.split('').reduce(function(p, c){
    return (p[c] = ++p[c] || 1, p);
}, {});
console.log(obj)
// Output => { a: 3, b: 1, z: 4, x: 1 }

Body:
It counts occurrences of each character in the string.

It's basically

if accumulator[character] exists, increase number stored in accumulator[character] by 1 (this happens if we have set it already to 1, somewhere in the past, because otherwise it will not exist)
else set accumulator[character] to 1 (this happens when we notice a first character of a new kind)
return accumulator object


问:
dictionary with assigned value raises referenced before assignment error
I need to write a code that is supposed to put items from a dictionary in a list and sort them either after the key or the value. This is the code I came up with:

```<code>import copy
dict_ip_attempts = {"180.237.210.112": 9, "180.237.210.54": 5,
                     "180.237.210.13": 2, "180.237.210.30": 5}

d=copy.deepcopy(dict_ip_attempts)
ip_adress=[]
for key in dict_ip_attempts:
    var=key.split(".")
    ip_adress.append(int("".join(var)))

ip_adress.sort()

def sortip_adress():
    output=[0]*(len(ip_adress))
    for key in dict_ip_attempts:
        var=key.split(".")
        for i in range(len(ip_adress)):
            if int("".join(var)) == ip_adress[i]:
                output[i]=((key, dict_ip_attempts[key]))
    return output

def sortattempts():
    output=[]
    for key in dict_ip_attempts:
        if dict_ip_attempts[key]==min(dict_ip_attempts.values()):
            output.append((key, dict_ip_attempts[key]))
            dict_ip_attempts.pop(key)
    dict_ip_attempts=copy.deepcoy(d)
    return output

print("The dictionary sorted after the ip_adresses is:", sortip_adress())
print("The dictionary sorted after the attempts is:", sortattempts())
</code>```

The function sortip_adress() works just fine, but the sortattempts() function doesn't. When python reaches line 30 it prints: UnboundLocalError: local variable 'dict_ip_attempts' referenced before assignment

line 30 is this one:

```<code>for key in dict_ip_attempts:
</code>```

I don't understand why I get this error, since I defined dict_ip_attempts in line 2. Can someone explain it to me please?

答:
Add global dict_ip_attempts at the beginning of sortattempts function.

Edit:
Basically, what you try to do is described here in a much more pythonic way.

Body:
I need to write a code that is supposed to put items from a dictionary in a list and sort them either after the key or the value. This is the code I came up with:

import copy
dict_ip_attempts = {"180.237.210.112": 9, "180.237.210.54": 5,
                     "180.237.210.13": 2, "180.237.210.30": 5}

d=copy.deepcopy(dict_ip_attempts)
ip_adress=[]
for key in dict_ip_attempts:
    var=key.split(".")
    ip_adress.append(int("".join(var)))

ip_adress.sort()

def sortip_adress():
    output=[0]*(len(ip_adress))
    for key in dict_ip_attempts:
        var=key.split(".")
        for i in range(len(ip_adress)):
            if int("".join(var)) == ip_adress[i]:
                output[i]=((key, dict_ip_attempts[key]))
    return output

def sortattempts():
    output=[]
    for key in dict_ip_attempts:
        if dict_ip_attempts[key]==min(dict_ip_attempts.values()):
            output.append((key, dict_ip_attempts[key]))
            dict_ip_attempts.pop(key)
    dict_ip_attempts=copy.deepcoy(d)
    return output

print("The dictionary sorted after the ip_adresses is:", sortip_adress())
print("The dictionary sorted after the attempts is:", sortattempts())

The function sortip_adress() works just fine, but the sortattempts() function doesn't. When python reaches line 30 it prints: UnboundLocalError: local variable 'dict_ip_attempts' referenced before assignment

line 30 is this one:

for key in dict_ip_attempts:

I don't understand why I get this error, since I defined dict_ip_attempts in line 2. Can someone explain it to me please?


问:
Where does IIS 7.5 log errors?
Where does IIS 7.5 log errors?

Event Viewer?
Log File?

I get a very nonspecific internal 500 error. I would like to find out more.

I'm running PHP and I did what this last comment on this post said. But still it is not logging to the C:\windows\temp folder.

答:
There should be a "Logging" icon on the site setup in IIS.

If you haven't changed the directory for that it looks like it defaults to %SystemDrive%\inetpub\logs\LogFiles

Look in your settings and I'd also recommend creating a logs folder above your site files to keep your logs separated.

ContentLicense: CC BY-SA 4.0

Title: Where does IIS 7.5 log errors?


问:
Compare the Euclidean distance of two lists of tuples with fewer comparisons python
I am trying to calculate the Euclidean distance of two list of tuples with the threshold of 4 . If the threshold is less than a particular value then increment the counter . Each tuple is the x,y,z coordinate of the point . Is there anyway i can lower of the comparison of list1 with list2 ..

```<code>  X = [ (1,2,3),(2,3,4), (4,5,6) ]
  Y = [ (1,2,2) , (3,4,5),(6,7,8) ]
  from math import sqrt
  dist_X = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in X]
  dist_Y = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in Y]
  for x in dist_X:
     print (x ,  [ i for i,y in enumerate(dist_Y) if abs(x-y) <= 4])
</code>```

I was thinking of first calculating the Euclidean distance of each point with the origin (0,0,0) so that both the lists now contain the points that are close to each other but it didnt work because its a scalar value .. Am i going in the right direction?

EDIT

```<code>   visited1 = [ (1,2,3),(2,3,4), (4,5,6) ]
   visited2   = [ (1,2,2) , (3,4,5),(6,7,8) ]
    def euclidean(a,b):
        return sqrt((a[0] - b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)
   comparison = 0
   for i,j in enumerate(visited2):
     for k,l in enumerate(visited1):
         if euclidean(visited2[i],visited1[k]) < 4:
                 count += 1
         comparison += 1
</code>```

In this every element of the list1 is compared with every element in the list2 .. I want to know if there is a way i can minimise the comparisons given the points(x,y,z) that i have?

答:
Draw this out in 2D to see how it looks.  Points that are roughly the same distance from the origin are not necessarily close to each other -- you have the triangle inequality backwards, there.  For instance, compare the points (0, 10), (0, 11), and (-8, -6).  They're all 10-11 units from the origin, but the last is nowhere near the other two.

If you want to know whether two points are close to each other, you need to compute the distance between those two points, not the distance to an arbitrary third point.  The problem is quadratic in complexity, not linear.

Body:
I am trying to calculate the Euclidean distance of two list of tuples with the threshold of 4 . If the threshold is less than a particular value then increment the counter . Each tuple is the x,y,z coordinate of the point . Is there anyway i can lower of the comparison of list1 with list2 ..

  X = [ (1,2,3),(2,3,4), (4,5,6) ]
  Y = [ (1,2,2) , (3,4,5),(6,7,8) ]
  from math import sqrt
  dist_X = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in X]
  dist_Y = [ sqrt((p[0] - 0)**2 + (p[1] - 0)**2 + (p[2] - 0)**2) for p in Y]
  for x in dist_X:
     print (x ,  [ i for i,y in enumerate(dist_Y) if abs(x-y) <= 4])

I was thinking of first calculating the Euclidean distance of each point with the origin (0,0,0) so that both the lists now contain the points that are close to each other but it didnt work because its a scalar value .. Am i going in the right direction?

EDIT

   visited1 = [ (1,2,3),(2,3,4), (4,5,6) ]
   visited2   = [ (1,2,2) , (3,4,5),(6,7,8) ]
    def euclidean(a,b):
        return sqrt((a[0] - b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)
   comparison = 0
   for i,j in enumerate(visited2):
     for k,l in enumerate(visited1):
         if euclidean(visited2[i],visited1[k]) < 4:
                 count += 1
         comparison += 1

In this every element of the list1 is compared with every element in the list2 .. I want to know if there is a way i can minimise the comparisons given the points(x,y,z) that i have?


问:
Get products with condition 'new' in Prestashop cart
I get the products in the cart like this:

```<code>$cart_products = $this->context->cart->getProducts();
</code>```

And I want to filter them in order to show only the products with condition 'new' so I do:

```<code>foreach ($cart_products as $cart_product) {
          if ($cart_product->condition == 'new')
                .....
         }
</code>```

It doesn't work. The page gets blocked and I cannot click in any part of this and also I cant move scroll down or up.

Anyone knows how to solve this?

答:
The condition field is not contained in the array retrieved by the method getProducts of Cart class.

Before you can use the condition field you should edit or override the getProducts method in the Cart class and add the "p.`condition`" in the SQL query, like this:

```<code>// Build SELECT
$sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
                    pl.`description_short`, pl.`available_now`, pl.`available_later`, p.`condition`, product_shop.`id_category_default`, p.`id_supplier`,
                    p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
                    product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`,
                    stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
                    p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
                    CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
                    product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference');
</code>```

Then as sayd @sadlyblue, you can use the condition field and show only the new products.

Body:
I get the products in the cart like this:

$cart_products = $this->context->cart->getProducts();

And I want to filter them in order to show only the products with condition 'new' so I do:

foreach ($cart_products as $cart_product) {
          if ($cart_product->condition == 'new')
                .....
         }

It doesn't work. The page gets blocked and I cannot click in any part of this and also I cant move scroll down or up.

Anyone knows how to solve this?

Body:
The condition field is not contained in the array retrieved by the method getProducts of Cart class.

Before you can use the condition field you should edit or override the getProducts method in the Cart class and add the "p.`condition`" in the SQL query, like this:

// Build SELECT
$sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
                    pl.`description_short`, pl.`available_now`, pl.`available_later`, p.`condition`, product_shop.`id_category_default`, p.`id_supplier`,
                    p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
                    product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`,
                    stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
                    p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
                    CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
                    product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference');

Then as sayd @sadlyblue, you can use the condition field and show only the new products.


问:
Wordpress- How to pass query string to all pages
I tried searching multiple threads and read a few tutorials but cannot seem to find the right answer.

When a user comes to my site through a referral link, I have the referral source as the query string EXAMPLE: "website.com/?REF=FnameLname123"

I need the whole query string to remain in the url as the user browses the site.

I have tried the code found here

```<code>function append_query_string($url) {
    return add_query_arg($_GET, $url);
}
add_filter('the_permalink', 'append_query_string');
</code>```

But this code doesn't work. I am currently building the site on my localhost. I do not know if that is problem, or if the problem is with how my theme builds the links.

Any help would be greatly appreciated!

Thank you!

I tried the following code

```<code>function add_query_vars_filter( $vars ){
   $vars[] = "REF";
   return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
</code>```

as well as

```<code>function add_query_vars_filter( $vars ){
   $vars['REF'] = "my_var";
   return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
</code>```

Neither of those worked.

答:
Maybe you can use:

```<code>function add_query_vars_filter( $vars ){
  $vars[] = "my_var";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
</code>```

Where $vars contain REF=FnameLname123 like $vars['REF']

Reference: https://codex.wordpress.org/Function_Reference/get_query_var

Body:
I tried searching multiple threads and read a few tutorials but cannot seem to find the right answer.

When a user comes to my site through a referral link, I have the referral source as the query string EXAMPLE: "website.com/?REF=FnameLname123"

I need the whole query string to remain in the url as the user browses the site.

I have tried the code found here

function append_query_string($url) {
    return add_query_arg($_GET, $url);
}
add_filter('the_permalink', 'append_query_string');

But this code doesn't work. I am currently building the site on my localhost. I do not know if that is problem, or if the problem is with how my theme builds the links.

Any help would be greatly appreciated!

Thank you!

I tried the following code

function add_query_vars_filter( $vars ){
   $vars[] = "REF";
   return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

as well as

function add_query_vars_filter( $vars ){
   $vars['REF'] = "my_var";
   return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

Neither of those worked.

Body:
Maybe you can use:

function add_query_vars_filter( $vars ){
  $vars[] = "my_var";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

Where $vars contain REF=FnameLname123 like $vars['REF']

Reference: https://codex.wordpress.org/Function_Reference/get_query_var


问:
How does Observables (Rx.js) compare to ES2015 generators?
As far as I understand, following are the techniques to solve asynchronous programming workflows:

Callbacks (CSP)

Promises

Newer approaches:

Rx.js Observables (or mostjs, bacon.js, xstream etc)

ES6 generators

Async/Await

We are now moving away from callbacks & promises to these newer approaches. What I understand currently is - Async/Await is more like a cleaner abstraction on top of ES2015 generators.

What I am not able to understand is the conceptual difference between Observables and Generators. I have used both extensively and have no trouble in using them.

What confuses me is the use case for Observables and Generators. I have come to conclusion that, in the end, they are addressing the same problem - asynchronicity. Only potential difference I see is generators inherently provide imperative semantics to code while Observables using Rxjs seem to provide reactive paradigm. But is that it?

Should that be the criteria to choose between Observable and Generator? What are the pros and cons.

Am I missing the big picture?

Also with Observable eventually making into future Ecmascript, are Promises (with cancelable-token)/Observable/Generators going to compete with each other?

答:
You can consider the rxjs observables as asynchronous generators i.e. generators yielding promises. Just because the content is not guaranteed to be ready at the time we call .next (in opposition to regular generators)

The subscriber will permanently consume into an infinite loop the generator’s content (calling .next)

Wait on the returned promise to be resolved (or revoked) to do what you want

The observable (made with an async generator) will complete on the generators return.

More reading

asynchronous Iterators proposal


问:
Can't assign array element to class variable while overloading "=" operator
I am quite new in C++ programming, so maybe that's why I can't figure out why this assignment is not working.
In my class, I want to overload "=" operator.
I have specified a function, that outputs variables as an array. In overloading, I want to assign those variables to new object.

```<code> obj_new = obj_with_variables
</code>```

overloading:

```<code>  obj_new_x=obj_with_values_parameters()[0];
  obj_new_y=obj_with_values_parameters()[1];
</code>```

Here is a code:

```<code>// Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "string"

using namespace std;

class Vector2D
{
public:
Vector2D()
{

}
Vector2D(int& a, int& b)
    :x(a), y(b)
{

}
void Drukuj()
{
    cout << "wektor [" << x << ',' << y << "] \n";
}
void Wspolrzedne(int&a, int&b)
{
    x = a;
    y = b;
}
int* Wspolrzedne()
{
    int tab[2] = { x,y };
    return tab;
}
void operator = (Vector2D& obj)
{
    int* a = obj.Wspolrzedne();
    cout << a[0] << "\n";
    x = a[0];
    cout << x << " what? \n";
    y = a[1];
}

private:
int x, y;

};

int main()
{
int x1 = 2, x2 = 3;
Vector2D wektor(x1, x2);
wektor.Drukuj();
Vector2D wektor2;
wektor2 = wektor;
wektor2.Drukuj();
wektor.Drukuj();

return 0;
}
</code>```

The problem is that it assigns some strange values. However, if I don't use a reference, but declare 2 int values (j,k) and assign array element to them [0,1], it works fine.
Also, when using static numbers (for example, instead of a[0] ; use "2") it works fine too.

What is going on?

I would be glad if somebody could point me to right answer/ resources.

Regards,

答:
Your interface is dangerous, as returning raw pointers from functions means the caller must know how to manage it.  That is, the caller needs to be astutely aware of the answers to questions like, "should the caller delete the pointer or does the object I got it from retain ownership?" What is this pointer pointing to?  If it's an array, now many elements are there?  If I must delete it, do I use delete or delete[]?

And so on.  This is not good because it's very, very error prone.

Next you have a function that returns a pointer to stack-local data.  When the function returns, that memory is already invalid so the return value is always going to result in undefined behavior to read.

```<code>int* Wspolrzedne()
{
    int tab[2] = { x,y };
    return tab;  // BAD - returns pointer to function stack data
}
</code>```

Where does tab live?  It's destroyed when the function exits, but you're returning a pointer to it.

This is a dangerous interface and should be changed.  Perhaps you should return the values as a pair:

```<code>std::pair<int, int> Wspolrzedne()
{
    return std::pair{ x,y }; // assuming c++17
    // return std::pair<int, int>{x, y}; // older compilers
}
</code>```

An interface like this avoids pointers, and removes all the issues mentioned above.

Body:
I am quite new in C++ programming, so maybe that's why I can't figure out why this assignment is not working.
In my class, I want to overload "=" operator.
I have specified a function, that outputs variables as an array. In overloading, I want to assign those variables to new object.

 obj_new = obj_with_variables

overloading:

  obj_new_x=obj_with_values_parameters()[0];
  obj_new_y=obj_with_values_parameters()[1];

Here is a code:

// Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "string"

using namespace std;

class Vector2D
{
public:
Vector2D()
{

}
Vector2D(int& a, int& b)
    :x(a), y(b)
{

}
void Drukuj()
{
    cout << "wektor [" << x << ',' << y << "] \n";
}
void Wspolrzedne(int&a, int&b)
{
    x = a;
    y = b;
}
int* Wspolrzedne()
{
    int tab[2] = { x,y };
    return tab;
}
void operator = (Vector2D& obj)
{
    int* a = obj.Wspolrzedne();
    cout << a[0] << "\n";
    x = a[0];
    cout << x << " what? \n";
    y = a[1];
}

private:
int x, y;

};

int main()
{
int x1 = 2, x2 = 3;
Vector2D wektor(x1, x2);
wektor.Drukuj();
Vector2D wektor2;
wektor2 = wektor;
wektor2.Drukuj();
wektor.Drukuj();

return 0;
}

The problem is that it assigns some strange values. However, if I don't use a reference, but declare 2 int values (j,k) and assign array element to them [0,1], it works fine.
Also, when using static numbers (for example, instead of a[0] ; use "2") it works fine too.

What is going on?

I would be glad if somebody could point me to right answer/ resources.

Regards,

Body:
Your interface is dangerous, as returning raw pointers from functions means the caller must know how to manage it.  That is, the caller needs to be astutely aware of the answers to questions like, "should the caller delete the pointer or does the object I got it from retain ownership?" What is this pointer pointing to?  If it's an array, now many elements are there?  If I must delete it, do I use delete or delete[]?

And so on.  This is not good because it's very, very error prone.

Next you have a function that returns a pointer to stack-local data.  When the function returns, that memory is already invalid so the return value is always going to result in undefined behavior to read.

int* Wspolrzedne()
{
    int tab[2] = { x,y };
    return tab;  // BAD - returns pointer to function stack data
}

Where does tab live?  It's destroyed when the function exits, but you're returning a pointer to it.

This is a dangerous interface and should be changed.  Perhaps you should return the values as a pair:

std::pair<int, int> Wspolrzedne()
{
    return std::pair{ x,y }; // assuming c++17
    // return std::pair<int, int>{x, y}; // older compilers
}

An interface like this avoids pointers, and removes all the issues mentioned above.


问:
How do I get my contact form to work after mod_rewrite?
I've built a site using CMS Made Simple. I have to point the host URL for everything EXCEPT the admin page and the contact forms. I was able to successfully do this with mod_rewrite to the config.php and changing up the .htaccess, but now my contact forms are no longer working (one in the footer and one on the contact page). Here is what my .htaccess file looks like:

```<code>  Options +FollowSymLinks
  RewriteEngine on
  RewriteBase /

  RewriteCond %{HTTP_HOST} ^energyfa.ipower.com$ [NC]
  RewriteCond %{REQUEST_URI} !^/ai/admin/
  RewriteRule ^(.*)$ http://accimpress.com/$1 [R=301,L]

  # 301 Redirect all requests that don't contain a dot or trailing slash to
  # include a trailing slash
  # except for form POSTS
  RewriteCond %{REQUEST_URI} !/$
  RewriteCond %{REQUEST_URI} !\.
  RewriteCond %{REQUEST_METHOD} !^POST$
  RewriteRule ^(.*) %{REQUEST_URI}/ [R=301,L]

  # Rewrites urls in the form of /parent/child/
  # but only rewrites if the requested URL is not a file or directory
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.+)$ index.php?page=$1 [QSA]
</code>```

Is there a reason my POST exception might not be working? Any suggestions will be much obliged. The website is: http://energyfa.ipower.com/ai/

Thanks,
Cory

答:
I see that the action on your form is set to http://energyfa.ipower.com/ai/contact-us/.  What I believe will happen is that the POST will go to that URL.  You will hit your first RewriteRule and get redirected to the contact form again, but since it's a browser redirect, it will probably just be a GET, so your POST content never makes it to your script.

Try changing the form action to http://accimpress.com/contact-us/ and see what happens.

Body:
I've built a site using CMS Made Simple. I have to point the host URL for everything EXCEPT the admin page and the contact forms. I was able to successfully do this with mod_rewrite to the config.php and changing up the .htaccess, but now my contact forms are no longer working (one in the footer and one on the contact page). Here is what my .htaccess file looks like:

  Options +FollowSymLinks
  RewriteEngine on
  RewriteBase /

  RewriteCond %{HTTP_HOST} ^energyfa.ipower.com$ [NC]
  RewriteCond %{REQUEST_URI} !^/ai/admin/
  RewriteRule ^(.*)$ http://accimpress.com/$1 [R=301,L]

  # 301 Redirect all requests that don't contain a dot or trailing slash to
  # include a trailing slash
  # except for form POSTS
  RewriteCond %{REQUEST_URI} !/$
  RewriteCond %{REQUEST_URI} !\.
  RewriteCond %{REQUEST_METHOD} !^POST$
  RewriteRule ^(.*) %{REQUEST_URI}/ [R=301,L]

  # Rewrites urls in the form of /parent/child/
  # but only rewrites if the requested URL is not a file or directory
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.+)$ index.php?page=$1 [QSA]

Is there a reason my POST exception might not be working? Any suggestions will be much obliged. The website is: http://energyfa.ipower.com/ai/

Thanks,
Cory


问:
Visualforce: Hide controlling field in field dependency
I am currently working on a vf page that has two picklists, and a dependency

Identity Type --controlling picklist
AND
Identity Status --Dependent picklist

View

```<code><apex:outputField value="{!Identity__c.EE_Identity_Type__c}">
<apex:inputField value="{!Identity__c.Identity_Status__c}"/>
</code>```

I am unable to set the controlling field as an outputfield "{!Identity__c.EE_Identity_Type__c}", salesforce send an error saying that the controlling field must be editable, but that must not be editable since the user should not be able to change it, this value will come from an integration with another system and the user should only be able to select the available values in the dependent picklist, is there a way to hide EE_Identity_Type__c, using javascript or something, to bypass the salesforce error.

Error Message from Salesforce=

The dependent picklist 'Identity Status' requires its controlling field 'Identity Type' to be present on the page.

Thanks

答:
Try setting the style to display:none and the label to an empty string
</p>

Body:
I am currently working on a vf page that has two picklists, and a dependency

Identity Type --controlling picklist
AND
Identity Status --Dependent picklist

View

<apex:outputField value="{!Identity__c.EE_Identity_Type__c}">
<apex:inputField value="{!Identity__c.Identity_Status__c}"/>

I am unable to set the controlling field as an outputfield "{!Identity__c.EE_Identity_Type__c}", salesforce send an error saying that the controlling field must be editable, but that must not be editable since the user should not be able to change it, this value will come from an integration with another system and the user should only be able to select the available values in the dependent picklist, is there a way to hide EE_Identity_Type__c, using javascript or something, to bypass the salesforce error.

Error Message from Salesforce=

The dependent picklist 'Identity Status' requires its controlling field 'Identity Type' to be present on the page.

Thanks


问:
Auto shrink a button without interaction
I'd like to add a menu button in the top right corner of my site - just a simple circle with an icon. I'd like to to load at a certain height and width and then automatically shrink, a few moments later, to another height and width - all without any user interaction.

Is this possible?

Any CSS gurus out there?

Many thanks,

答:
You can do it with the CSS3 Animation:

div {
  width: 50px;
  height: 50px;
  background: #00f;
  border-radius: 50%;
  animation-name: shrink; /* "calling" the animation */
  animation-duration: 1s; /* adjust */
  animation-timing-function: linear; /* specifies the speed curve of an animation / also try other values */
  animation-delay: 3s; /* adjust */
  animation-fill-mode: forwards; /* retains in the state set by the last keyframe */
}

@keyframes shrink { /* let's call it "shrink" */
  0%   {width: 50px; height: 50px}
  100% {width: 25px; height: 25px} /* final state */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><div></code>```

Experiment and adjust to your needs.

Note: There are also other animation properties & values so you might take a closer look to see what you can do.

Body:
You can do it with the CSS3 Animation:

div {
  width: 50px;
  height: 50px;
  background: #00f;
  border-radius: 50%;
  animation-name: shrink; /* "calling" the animation */
  animation-duration: 1s; /* adjust */
  animation-timing-function: linear; /* specifies the speed curve of an animation / also try other values */
  animation-delay: 3s; /* adjust */
  animation-fill-mode: forwards; /* retains in the state set by the last keyframe */
}

@keyframes shrink { /* let's call it "shrink" */
  0%   {width: 50px; height: 50px}
  100% {width: 25px; height: 25px} /* final state */
}

<div><div>

Experiment and adjust to your needs.

Note: There are also other animation properties & values so you might take a closer look to see what you can do.


问:
why doesn't the second rectangle stay visible in my SVG code
I have this piece of code which as I understand it should draw the first rect tangle and then the second. The second has animation which simply expands the width. So with this code I see the blue bar appear then I see the yellow bar appear and it grows as expected but when it finishes it disappears.The both have the same start points and width so it making a progress bar. The blue bar is 400 pixels in length, the yellow is only 250 so I should see 150 pixels of blue at least that is what I think should be happening

```<code><svg xmlns='http://www.w3.org/2000/svg'>
    <rect x='10' y='10' height='20' width='400' style='stroke:#ff0000; fill: #0000ff'>
    </rect>
    <rect x='10' y='10' height='20' width='0' style='stroke:#ff0000; fill: #ffff00'>
<animate attributeName='width' attributeType='XML'
    to='250'
    begin='0s'
    dur='2s' />
    </rect>
</svg>
</code>```

I am still new to SVG but this should work from what I have read the yellow bar is done last so it be on top.

答:
Your animate tag have to include an explicit fill parameter with the value 'freeze'. Otherwise, the default fill='remove' is used, which means the animated parameter reverts back to the value it had before the animation (in this case, "0").

```<code><svg xmlns='http://www.w3.org/2000/svg'>
    <rect x='10' y='10' height='20' width='400' style='stroke:#ff0000; fill: #0000ff'>
    </rect>
    <rect id="r1" x='10' y='10' height='20' width='0'  style='stroke:#ff0000; fill: #ffff00'>
<animate attributeName='width' attributeType='XML'
    from='0'
    to='250'
    begin='0s'
    dur='2s'
    fill='freeze'
         />
    </rect>
</svg>
</code>```

(full reference at: https://www.w3.org/TR/SVG/animate.html#ValueAttributes)

Body:
I have this piece of code which as I understand it should draw the first rect tangle and then the second. The second has animation which simply expands the width. So with this code I see the blue bar appear then I see the yellow bar appear and it grows as expected but when it finishes it disappears.The both have the same start points and width so it making a progress bar. The blue bar is 400 pixels in length, the yellow is only 250 so I should see 150 pixels of blue at least that is what I think should be happening

<svg xmlns='http://www.w3.org/2000/svg'>
    <rect x='10' y='10' height='20' width='400' style='stroke:#ff0000; fill: #0000ff'>
    </rect>
    <rect x='10' y='10' height='20' width='0' style='stroke:#ff0000; fill: #ffff00'>
<animate attributeName='width' attributeType='XML'
    to='250'
    begin='0s'
    dur='2s' />
    </rect>
</svg>

I am still new to SVG but this should work from what I have read the yellow bar is done last so it be on top.

Body:
Your animate tag have to include an explicit fill parameter with the value 'freeze'. Otherwise, the default fill='remove' is used, which means the animated parameter reverts back to the value it had before the animation (in this case, "0").

<svg xmlns='http://www.w3.org/2000/svg'>
    <rect x='10' y='10' height='20' width='400' style='stroke:#ff0000; fill: #0000ff'>
    </rect>
    <rect id="r1" x='10' y='10' height='20' width='0'  style='stroke:#ff0000; fill: #ffff00'>
<animate attributeName='width' attributeType='XML'
    from='0'
    to='250'
    begin='0s'
    dur='2s'
    fill='freeze'
         />
    </rect>
</svg>

(full reference at: https://www.w3.org/TR/SVG/animate.html#ValueAttributes)


问:
Using system() in C with an agument
I wish to write a program that uses system() and compress a folder. The folder name is given via command-line. This is what I have:

```<code>#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv){
  int i;
  char buf[64]
  char string[]="tar -cf stent.tar ";
  if(argc>1){
    for(i=1;i<argc;i++){
      string[16]=(char)argv[i];
      printf("%s",argv[i]);
    }
  }
  snprintf(buf,sizeof(buf), "tar -cf stent.tar %s," argv);
  printf(string);
  printf(buf);
  return 0;
}
</code>```

Basically I wish to do this:

```<code>system("tar -cf stent.tar %s", buf);
</code>```

buf should be the input argument of the user. The folders he wants to compress

答:
Perhaps this will pass the folder name argument to the tar command. But it's a mystery why you don't just do it from the command line.

```<code>#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]){
    char buf[1024];
    if(argc > 1){
        sprintf(buf, "tar -cf stent.tar %s", argv[1]);
        system(buf);
    }
    return 0;
}
</code>```

Leaving the possibility of buffer overflow out of it.

Title: Using system() in C with an agument

Body:
I wish to write a program that uses system() and compress a folder. The folder name is given via command-line. This is what I have:

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv){
  int i;
  char buf[64]
  char string[]="tar -cf stent.tar ";
  if(argc>1){
    for(i=1;i<argc;i++){
      string[16]=(char)argv[i];
      printf("%s",argv[i]);
    }
  }
  snprintf(buf,sizeof(buf), "tar -cf stent.tar %s," argv);
  printf(string);
  printf(buf);
  return 0;
}

Basically I wish to do this:

system("tar -cf stent.tar %s", buf);

buf should be the input argument of the user. The folders he wants to compress

Body:
Perhaps this will pass the folder name argument to the tar command. But it's a mystery why you don't just do it from the command line.

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]){
    char buf[1024];
    if(argc > 1){
        sprintf(buf, "tar -cf stent.tar %s", argv[1]);
        system(buf);
    }
    return 0;
}

Leaving the possibility of buffer overflow out of it.


问:
Is there a name for this design pattern?
There's a specific snippet of code that I often use for recycling objects in a list based on a data provider. I thought of making a class to run through the snippet, using a given class to handle each step. This problem is... I don't know what to name it. Does a design pattern exist that describes this reusing of snippets?</p>

```<code>package
{
    public class RecycleOperationRunner implements IRecycleOperationRunner
    {
        public function RecycleOperationRunner()
        {

        }

        public function run(operation:IRecycleOperation):void
        {
            const m:int = Math.max(numObjects, numDataItems);

            for (var i:int = 0; i < m; i++)
            {
                if (i < numDataItems)
                {
                    if (i < numObjects)
                    {
                        operation.reuseItem(i);
                    }
                    else
                    {
                        operation.createItem(i);
                    }

                    operation.setupItem(i);
                }
                else
                {
                    operation.removeItem(i);
                }
            }

            operation.dispose();
        }
    }
}
</code>```

答:
It seems like what you have could be described as a "pool".  As in "thread pool" or "connection pool."

Pool (computer science)

Object pool pattern

It seems to deviate slightly in that typically you request a resource from a pool, and if all the resources are currently being used (leased) then you block until one becomes available.  In your example, you create one.  So you have a pool that automatically grows in size to be non-blocking.

Body:
There's a specific snippet of code that I often use for recycling objects in a list based on a data provider. I thought of making a class to run through the snippet, using a given class to handle each step. This problem is... I don't know what to name it. Does a design pattern exist that describes this reusing of snippets?

package
{
    public class RecycleOperationRunner implements IRecycleOperationRunner
    {
        public function RecycleOperationRunner()
        {

        }

        public function run(operation:IRecycleOperation):void
        {
            const m:int = Math.max(numObjects, numDataItems);

            for (var i:int = 0; i < m; i++)
            {
                if (i < numDataItems)
                {
                    if (i < numObjects)
                    {
                        operation.reuseItem(i);
                    }
                    else
                    {
                        operation.createItem(i);
                    }

                    operation.setupItem(i);
                }
                else
                {
                    operation.removeItem(i);
                }
            }

            operation.dispose();
        }
    }
}


问:
Segmentation Fault from class function
I have a function "printWorld" in a class that prints a 2D array called "world". Whenever I use this function and run my program in the terminal it appears to print the array but then a massive amount of random numbers and at the end says "Segmentation Fault" and closes my program. As soon as I take this function out of my code though everything works just fine.

```<code>void printWorld()
{
    for(int r = 0; r <= (2*WORLD_SIZE + 1); r++)
    {
        for(int c = 0; r <= (2*WORLD_SIZE + 1); c++)
            cout << world[r][c];
        cout << endl;
    }
}
</code>```

This is how the function is written in the class

```<code>game.printWorld();
</code>```

This is how I'm calling the function.

This is what is showing in termninal

If it helps I have this array initialized all to 0.

答:
As others have already stated, the mistake is the inner for loop where you compare 'r <= (2*WORLD_SIZE + 1)'

This causes an infinite loop.

Change the inner for loop to be:

```<code>    for(int c = 0; c <= (2*WORLD_SIZE + 1); c++)
        cout << world[r][c];
    cout << endl;
</code>```

That should do it for you : )

Title: Segmentation Fault from class function

Body:
I have a function "printWorld" in a class that prints a 2D array called "world". Whenever I use this function and run my program in the terminal it appears to print the array but then a massive amount of random numbers and at the end says "Segmentation Fault" and closes my program. As soon as I take this function out of my code though everything works just fine.

void printWorld()
{
    for(int r = 0; r <= (2*WORLD_SIZE + 1); r++)
    {
        for(int c = 0; r <= (2*WORLD_SIZE + 1); c++)
            cout << world[r][c];
        cout << endl;
    }
}

This is how the function is written in the class

game.printWorld();

This is how I'm calling the function.

This is what is showing in termninal

If it helps I have this array initialized all to 0.

Body:
As others have already stated, the mistake is the inner for loop where you compare 'r <= (2*WORLD_SIZE + 1)'

This causes an infinite loop.

Change the inner for loop to be:

    for(int c = 0; c <= (2*WORLD_SIZE + 1); c++)
        cout << world[r][c];
    cout << endl;

That should do it for you : )


问:
How to read DataInputStream until the end without needing to catch an EOFException?
Suppose we have some binary data byte[] data that only contains Integers. If I wanted to read this data utilizing a DataInputStream, the only approach I can come up with is the following:

```<code>DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
try {
    while (true){
        int i = in.readInt();
    }
} catch (EOFException e) {
    // we're done!
} catch (IOException e){
    throw new RuntimeException(e);
}
</code>```

What bugs me about this is that reaching the end of the stream is expected and it would exceptional only if no exception was thrown, what IMO defeats the purpose of exceptions in the first place.

When using Java NIO's IntBuffer, there's no such problem.

```<code>IntBuffer in = ByteBuffer.wrap(data).asIntBuffer();
while (in.hasRemaining()){
    int i = in.get();
}
</code>```

Coming from C# and being in the process of learning Java I refuse to believe that this is the intended way of doing this.

Moreover, I just came across Java NIO which seems to be "quite new". Using IntBuffer here instead would be my way of procrastinating the matter. Regardless, I wanna know how this is properly done in Java.

答: You can't. readInt() can return any integer value, so an out-of-band mechanism is required to signal end of stream, so an exception is thrown. That's how the API was designed. Nothing you can do about it.

Body:
Suppose we have some binary data byte[] data that only contains Integers. If I wanted to read this data utilizing a DataInputStream, the only approach I can come up with is the following:

DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
try {
    while (true){
        int i = in.readInt();
    }
} catch (EOFException e) {
    // we're done!
} catch (IOException e){
    throw new RuntimeException(e);
}

What bugs me about this is that reaching the end of the stream is expected and it would exceptional only if no exception was thrown, what IMO defeats the purpose of exceptions in the first place.

When using Java NIO's IntBuffer, there's no such problem.

IntBuffer in = ByteBuffer.wrap(data).asIntBuffer();
while (in.hasRemaining()){
    int i = in.get();
}

Coming from C# and being in the process of learning Java I refuse to believe that this is the intended way of doing this.

Moreover, I just came across Java NIO which seems to be "quite new". Using IntBuffer here instead would be my way of procrastinating the matter. Regardless, I wanna know how this is properly done in Java.


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答:
At first glance, I'd say that the objectives of Code Refactoring are similar in an abstract way to the objectives of normalization.  But that's pretty abstract.

Update: I almost wrote earlier that "we need to get Jon Skeet in on this one."  I posted my answer and who beat me?  You guessed it...

OwnerDisplayName: meade

Title: Object Normalization

LastEditorDisplayName: meade

OwnerDisplayName: Mark Brittingham

LastEditorDisplayName: Mark Brittingham


问:
rename multiple attributes with simpleXML
```<code><root>
  <gallery name="First"/>
  <gallery name="Second"/>
  <gallery name="Third"/>
</root>
</code>```

I'm trying to rename multiple "name" attributes at once:

```<code>$rename = array();
foreach($_POST['name'] as $value) {
    $rename[] = $value;
}

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$gallery = $objXML->xpath('/root/gallery/@name');
print_r($gallery);
print_r($rename);

$objXML->asXML(XML_FILE_NAME);
</code>```

Returns:

```<code>Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => First ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Second ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Third ) ) )

Array ( [0] => First New [1] => Second New [2] => Third New )
</code>```

How can I get php to save the New values back to the XML? Does it need another foreach loop? The code seems to be getting too complex already.

I'm trying this, but no dice:

```<code>foreach( $objXML->xpath('/root/gallery/@name') as $gallery ) {
    $gallery = $_POST['name'];
}
</code>```

答:
Simplexml is buid to returns node only. That's weird, but '/root/gallery/@name' and '/root/gallery'.

These two queries

```<code>$aList = $objXML->xpath('/root/gallery/@name');
$bList = $objXML->xpath('/root/gallery');
</code>```

will return the same instances

```<code>for($i=0, $count=count($aList); $i<$count; $i++) {
  $a = $aList[$i];
  $b = $aList[$i];
  var_dump($a==$b); // true
}
</code>```

So the only way for changing the attribute of a node is with the array syntaxe

```<code>foreach($aList as $node) {
  $node['name'] = 'foo' . $i;
}
var_dump($objXML);
</code>```

Body:
<root>
  <gallery name="First"/>
  <gallery name="Second"/>
  <gallery name="Third"/>
</root>

I'm trying to rename multiple "name" attributes at once:

$rename = array();
foreach($_POST['name'] as $value) {
    $rename[] = $value;
}

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$gallery = $objXML->xpath('/root/gallery/@name');
print_r($gallery);
print_r($rename);

$objXML->asXML(XML_FILE_NAME);

Returns:

Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => First ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Second ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Third ) ) )

Array ( [0] => First New [1] => Second New [2] => Third New )

How can I get php to save the New values back to the XML? Does it need another foreach loop? The code seems to be getting too complex already.

I'm trying this, but no dice:

foreach( $objXML->xpath('/root/gallery/@name') as $gallery ) {
    $gallery = $_POST['name'];
}

Body:
Simplexml is buid to returns node only. That's weird, but '/root/gallery/@name' and '/root/gallery'.

These two queries

$aList = $objXML->xpath('/root/gallery/@name');
$bList = $objXML->xpath('/root/gallery');

will return the same instances

for($i=0, $count=count($aList); $i<$count; $i++) {
  $a = $aList[$i];
  $b = $aList[$i];
  var_dump($a==$b); // true
}

So the only way for changing the attribute of a node is with the array syntaxe

foreach($aList as $node) {
  $node['name'] = 'foo' . $i;
}
var_dump($objXML);


问:
Twig: conditionally return from a macro
I'd like to conditionally return from a macro, like this pseudocode:

```<code>{% macro example() %}
    ...
    {% if condition %} {% return %} {% endif %}
    ...
{% endmacro %}
</code>```

Is this possible with Twig, perhaps with a Twig extension?

答:
Here is example:

```<code>{# macro #}

{% macro check(isTrue) %}
    {% if isTrue %}
        show-paywall
    {% else %}
        show-content
    {% endif %}
{% endmacro %}

{# usage #}
{% import _self as self %}

{% set per = self.check(true)|trim %}

{%  if per == 'show-paywall' %}

{{'Show paywall man.'}}

{% else %}

{{ 'You are good man.' }}

{% endif %}
</code>```

You can play online :
https://twigfiddle.com/etn6ef

Title: Twig: conditionally return from a macro

Body:
I'd like to conditionally return from a macro, like this pseudocode:

{% macro example() %}
    ...
    {% if condition %} {% return %} {% endif %}
    ...
{% endmacro %}

Is this possible with Twig, perhaps with a Twig extension?

Body:
Here is example:

{# macro #}

{% macro check(isTrue) %}
    {% if isTrue %}
        show-paywall
    {% else %}
        show-content
    {% endif %}
{% endmacro %}

{# usage #}
{% import _self as self %}

{% set per = self.check(true)|trim %}

{%  if per == 'show-paywall' %}

{{'Show paywall man.'}}

{% else %}

{{ 'You are good man.' }}

{% endif %}

You can play online :
https://twigfiddle.com/etn6ef


问:
Need to download the PDF, NOT the content of the webpage
So as it stands I am able to get the content of the webpage of the PDF link EXAMPLE OF THE LINK HERE BUT, I don't want the content of the webpage I want the content of the PDF so I can put the content into a PDF on my computer in a folder.

I have been successful in doing this on sites that I don't need to log into and without a proxy server.

Relevant CODE:

```<code>import os
import urllib2
import time
import requests
import urllib3
from random import *

s = requests.Session()
data = {"Username":"username", "Password":"password"}
url = "https://login.url.com"

print "doing things"
r2 = s.post(url, data=data, proxies = {'https' : 'https://PROXYip:PORT'}, verify=False)

#I get a response 200 from printing r2
print r2

downlaod_url = "http://msds.walmartstores.com/client/document?productid=1000527&productguid=54e8aa24-0db4-4973-a81f-87368312069a&DocumentKey=undefined&HazdocumentKey=undefined&MSDS=0&subformat=NAM"

file = open("F:\my_filepath\document" + str(maxCounter) + ".pdf", 'wb')
temp = s.get(download_url, proxies = {'https' : 'https://PROXYip:PORT'}, verify=False)

#This prints out the response from the proxy server (i.e. 200)
print temp

something = uniform(5,6)
print something
time.sleep(something)

#This gets me the content of the web page, not the content of the PDF
print temp.content

file.write(temp.content)
file.close()
</code>```

I need help figuring out how to "download" the content of the PDF

答:
try this:

```<code>import requests

url = 'http://msds.walmartstores.com/client/document?productid=1000527&productguid=54e8aa24-0db4-4973-a81f-87368312069a&DocumentKey=undefined&HazdocumentKey=undefined&MSDS=0&subformat=NAM'

pdf = requests.get(url)
with open('walmart.pdf', 'wb') as file:
    file.write(pdf.content)
</code>```

Edit

Try again with a requests session to manage cookies (assuming they send you those after login) and also maybe a different proxy

```<code>proxy_dict = {'https': 'ip:port'}

with requests.Session() as session:
    # Authentication request, use GET/POST whatever is needed
    # data variable should hold user/password information
    auth = session.get(login_url, data=data, proxies=proxy_dict, verify=False)
    if auth.status_code == 200:
        print(auth.cookies) # Tell me if you got anything
        pdf = auth.get('download_url')  # Were continuing the same session
        with open('walmart.pdf', 'wb') as file:
            file.write(pdf.content)
    else:
        print('No go, got {0} response'.format(auth.status_code))
</code>```

Body:
So as it stands I am able to get the content of the webpage of the PDF link EXAMPLE OF THE LINK HERE BUT, I don't want the content of the webpage I want the content of the PDF so I can put the content into a PDF on my computer in a folder.

I have been successful in doing this on sites that I don't need to log into and without a proxy server.

Relevant CODE:

import os
import urllib2
import time
import requests
import urllib3
from random import *

s = requests.Session()
data = {"Username":"username", "Password":"password"}
url = "https://login.url.com"

print "doing things"
r2 = s.post(url, data=data, proxies = {'https' : 'https://PROXYip:PORT'}, verify=False)

#I get a response 200 from printing r2
print r2

downlaod_url = "http://msds.walmartstores.com/client/document?productid=1000527&productguid=54e8aa24-0db4-4973-a81f-87368312069a&DocumentKey=undefined&HazdocumentKey=undefined&MSDS=0&subformat=NAM"

file = open("F:\my_filepath\document" + str(maxCounter) + ".pdf", 'wb')
temp = s.get(download_url, proxies = {'https' : 'https://PROXYip:PORT'}, verify=False)

#This prints out the response from the proxy server (i.e. 200)
print temp

something = uniform(5,6)
print something
time.sleep(something)

#This gets me the content of the web page, not the content of the PDF
print temp.content

file.write(temp.content)
file.close()

I need help figuring out how to "download" the content of the PDF

Body:
try this:

import requests

url = 'http://msds.walmartstores.com/client/document?productid=1000527&productguid=54e8aa24-0db4-4973-a81f-87368312069a&DocumentKey=undefined&HazdocumentKey=undefined&MSDS=0&subformat=NAM'

pdf = requests.get(url)
with open('walmart.pdf', 'wb') as file:
    file.write(pdf.content)

Edit

Try again with a requests session to manage cookies (assuming they send you those after login) and also maybe a different proxy

proxy_dict = {'https': 'ip:port'}

with requests.Session() as session:
    # Authentication request, use GET/POST whatever is needed
    # data variable should hold user/password information
    auth = session.get(login_url, data=data, proxies=proxy_dict, verify=False)
    if auth.status_code == 200:
        print(auth.cookies) # Tell me if you got anything
        pdf = auth.get('download_url')  # Were continuing the same session
        with open('walmart.pdf', 'wb') as file:
            file.write(pdf.content)
    else:
        print('No go, got {0} response'.format(auth.status_code))


问:
UPN - User Principal Name
How I get my UPN from Active Directory? I need to test an app which uses Upn Claim type...</p>

答: If you have administrative rights in Active Directory, you can run Active Directory Users and Computers and look at the Account tab of the User Properties window and see it with it being a combination of the User logon name and the domain suffix (first one listed).</p>

Title: UPN - User Principal Name


问:
Protractor: More specific feedback to User?
Say I have a page of 10 images and the 3rd and 5th don't load. How can I say something like:

2/5 images didn't load.

Or "image2.jpeg" and image5.jpeg" hasn't loaded.

```<code>browser.waitForAngularEnabled(false);

it('should find all images', function () {
  browser.get('https://popeyes.com/');
  var imagesBrokenCount = browser.executeScript(`
  var elms = document.querySelectorAll("img");
  return [].filter.call(elms, e => e.offsetHeight > 1 && e.naturalHeight <= 1).length;
  `);
browser.sleep(1000);
expect(imagesBrokenCount).toEqual(0);

});
</code>```

答:
I would switch to Protractor-specific functionality here - using filter() to filter out the broken images, then, using map() to get an array of src values and then using Jasmine's fail() to fail with a desired error message:

```<code>it('should find all images', function () {
  browser.get('https://www.popeyes.com');
  var brokenImages = $$("img").filter(function (img) {
    return img.getAttribute("offsetHeight").then(function (offsetHeight) {
        return img.getAttribute("naturalHeight").then(function (naturalHeight) {
            return offsetHeight > 1 && naturalHeight <= 1;
        });
    });
});
brokenImages.count().then(function (countBrokenImages) {
    if (countBrokenImages > 0) {
      console.log(countBrokenImages + " images loaded successfully");
        brokenImages.map(function (img) {
            return img.getAttribute("src");
        }).then(function (sources) {
          fail("Failed to load the following images: " + sources.join(","));
        })
        }
    });
});
</code>```

Body:
Say I have a page of 10 images and the 3rd and 5th don't load. How can I say something like:

2/5 images didn't load.

Or "image2.jpeg" and image5.jpeg" hasn't loaded.

browser.waitForAngularEnabled(false);

it('should find all images', function () {
  browser.get('https://popeyes.com/');
  var imagesBrokenCount = browser.executeScript(`
  var elms = document.querySelectorAll("img");
  return [].filter.call(elms, e => e.offsetHeight > 1 && e.naturalHeight <= 1).length;
  `);
browser.sleep(1000);
expect(imagesBrokenCount).toEqual(0);

});

Body:
I would switch to Protractor-specific functionality here - using filter() to filter out the broken images, then, using map() to get an array of src values and then using Jasmine's fail() to fail with a desired error message:

it('should find all images', function () {
  browser.get('https://www.popeyes.com');
  var brokenImages = $$("img").filter(function (img) {
    return img.getAttribute("offsetHeight").then(function (offsetHeight) {
        return img.getAttribute("naturalHeight").then(function (naturalHeight) {
            return offsetHeight > 1 && naturalHeight <= 1;
        });
    });
});
brokenImages.count().then(function (countBrokenImages) {
    if (countBrokenImages > 0) {
      console.log(countBrokenImages + " images loaded successfully");
        brokenImages.map(function (img) {
            return img.getAttribute("src");
        }).then(function (sources) {
          fail("Failed to load the following images: " + sources.join(","));
        })
        }
    });
});


问:
What's the difference between this and super keywords in java?
Check my coolMethod, babes:

```<code>package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}
</code>```

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

```<code>package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}
</code>```

And my main, that calls my Moo class functionalities.

```<code>package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}
</code>```

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

答:
"this" refers to the object you're in. "super" refers to the parent of this object. I think you're missing the difference because of some other things you have going on.

For example, this code

```<code>
public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}
</code>```

The method "coolMethod" is defined in Zoo, but it's a public method so it is naturally inherited by Moo. So, when you're within your Moo class and you call this.coolMethod or super.coolMethod, you end up with exactly the same thing. Where things get far more interesting is if you override the coolMethod in your subclass, like this:

```<code>
public class Zoo {
    public String coolMethod() {
        return "Wow baby!";
    }
}

public class Moo extends Zoo {

    @Override
    public String coolMethod() {
        return "Moo baby!";
    }

    public void doIt() {
        System.out.println("Using super: " + super.coolMethod());
        System.out.println("Using this: " + this.coolMethod());
    }
}
</code>```

Try executing "doIt" in that case and I think you'll see the difference much easier.

Body:
Check my coolMethod, babes:

package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

And my main, that calls my Moo class functionalities.

package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

Body:
"this" refers to the object you're in. "super" refers to the parent of this object. I think you're missing the difference because of some other things you have going on.

For example, this code

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

The method "coolMethod" is defined in Zoo, but it's a public method so it is naturally inherited by Moo. So, when you're within your Moo class and you call this.coolMethod or super.coolMethod, you end up with exactly the same thing. Where things get far more interesting is if you override the coolMethod in your subclass, like this:

public class Zoo {
    public String coolMethod() {
        return "Wow baby!";
    }
}

public class Moo extends Zoo {

    @Override
    public String coolMethod() {
        return "Moo baby!";
    }

    public void doIt() {
        System.out.println("Using super: " + super.coolMethod());
        System.out.println("Using this: " + this.coolMethod());
    }
}

Try executing "doIt" in that case and I think you'll see the difference much easier.


问:
How do I stop Xcode 9 from continuously building or at least make it not run build scripts?
After migrating to Xcode 9, I noticed that it constantly fully builds my project. I found that it is somehow related to the "show live issues" setting. Disabling that setting stops builds, but it makes development inconvenient.

I would like to disable this continuous build loop, or make it work without launching all build scripts.

My custom build scripts contain linting and formatting, so what happens is, I try to edit a file, but Xcode starts building, thus launching the formatting routine that changes exactly the same file I am trying to edit.

答: Open any .storyboard file in your project and go to the Editor menu, uncheck 'Automatically Refresh Views'.


问:
c# streamwriter datagrid.backcolor write *txt
```<code>StreamWriter dosya = File.AppendText(yol);
dosya.Write(comboBox1.Text + "*");
dosya.Write(txtLikitadi.Text + "*");
dosya.Write(textBox3.Text + "*");
dosya.Write(textBox1.Text + "*");
dosya.Write(lblAroma.Text + "*");
dosya.Write(lblBase.Text + "*");
dosya.Write(lblGliserin.Text + "*");
dosya.WriteLine(lblPG.Text + "*");
dosya.Close();
liste();
</code>```

I am transferring information from the program to a text file.

How can I add datagridview currentrow backcolor information this text ?

then I'll split it up and get this info

Thanks

答:
The term back color is ambiguous. Back colors can be set on the whole grid, a row and even on individual cells. All of the following might be valid answers, depending on what you're talking about:</p>

```<code>dosya.Write(dataGridView1.RowsDefaultCellStyle.BackColor);
dosya.Write(datagridview1.CurrentRow.DefaultCellStyle.BackColor);
dosya.Write(datagridview1.CurrentRow.Cells[0].Style.BackColor);
</code>```

Body:
StreamWriter dosya = File.AppendText(yol);
dosya.Write(comboBox1.Text + "*");
dosya.Write(txtLikitadi.Text + "*");
dosya.Write(textBox3.Text + "*");
dosya.Write(textBox1.Text + "*");
dosya.Write(lblAroma.Text + "*");
dosya.Write(lblBase.Text + "*");
dosya.Write(lblGliserin.Text + "*");
dosya.WriteLine(lblPG.Text + "*");
dosya.Close();
liste();

I am transferring information from the program to a text file.

How can I add datagridview currentrow backcolor information this text ?

then I'll split it up and get this info

Thanks

Body:
The term back color is ambiguous. Back colors can be set on the whole grid, a row and even on individual cells. All of the following might be valid answers, depending on what you're talking about:

dosya.Write(dataGridView1.RowsDefaultCellStyle.BackColor);
dosya.Write(datagridview1.CurrentRow.DefaultCellStyle.BackColor);
dosya.Write(datagridview1.CurrentRow.Cells[0].Style.BackColor);


问:
Why does css button lose its style when clicked?
Im completely lost with this one. Ok so I create a button with CSS, take a look at the CSS code:

```<code>.UploadPhotos a:link{
    display:block;
    width:100px;
    height:22px;
    padding-top:2px;
    margin-left:auto;
    margin-right:auto;
    text-align:center;
    background:url(../images/btn_image.png) 0 0 no-repeat;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:hover{
    background-position: 0 -24px;
    text-decoration:none;
    color:#060;
}
.UploadPhotos a:active{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:visited{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}
</code>```

Now here is the HTML code:

```<code><div class="UploadPhotos">
    <a id="UpLd" href="uploader/upload.php">Upload Photos</a>
</div>
</code>```

The problem begins when I click on it. The link is opening up another page within an iframe which is done with js. Once I click this button, all the styles for this button is gone. I get the same problem even if I set the href="#" on the link. So I don't believe its the js opening the page. I can't figure out why the style suddenly disappears once clicked on.

I added images to give you guys an idea:

Regular

Hover

After click

Highlighting text with cursor after click

答:
a:visited and a:active need background colors.  Once the button is clicked it's now active and visited.  If you change focus it just becomes visited.  Also, if you tab onto the control (before clicking it) you will see the same behavior because the state changes to active.

Also add another class:

```<code>.UploadPhotos a {
display:block;
width:100px;
height:22px;
padding-top:2px;
margin-left:auto;
margin-right:auto;
text-align:center;
background:url(../images/btn_image.png) 0 0 no-repeat;
text-decoration:none;
color:#FFF;
}
</code>```

Body:
Im completely lost with this one. Ok so I create a button with CSS, take a look at the CSS code:

.UploadPhotos a:link{
    display:block;
    width:100px;
    height:22px;
    padding-top:2px;
    margin-left:auto;
    margin-right:auto;
    text-align:center;
    background:url(../images/btn_image.png) 0 0 no-repeat;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:hover{
    background-position: 0 -24px;
    text-decoration:none;
    color:#060;
}
.UploadPhotos a:active{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}
.UploadPhotos a:visited{
    background-position: 0 0px;
    text-decoration:none;
    color:#FFF;
}

Now here is the HTML code:

    Upload Photos

The problem begins when I click on it. The link is opening up another page within an iframe which is done with js. Once I click this button, all the styles for this button is gone. I get the same problem even if I set the href="#" on the link. So I don't believe its the js opening the page. I can't figure out why the style suddenly disappears once clicked on.

I added images to give you guys an idea:

Regular

Hover

After click

Highlighting text with cursor after click

Body:
a:visited and a:active need background colors.  Once the button is clicked it's now active and visited.  If you change focus it just becomes visited.  Also, if you tab onto the control (before clicking it) you will see the same behavior because the state changes to active.

Also add another class:

.UploadPhotos a {
display:block;
width:100px;
height:22px;
padding-top:2px;
margin-left:auto;
margin-right:auto;
text-align:center;
background:url(../images/btn_image.png) 0 0 no-repeat;
text-decoration:none;
color:#FFF;
}


问:
In tensorflow, how to make any entry >0.5 becomes 1 in a tensor?
For example, a = [0,0.2,0.8]

I want to make it a = [0,0.2,1]

I searched for a long time, but I only found tf.bool_mask which can only get a bool tensor and I dont know what to do next.

I know at least in numpy, its very easy, but how to do it in tensorflow?

答:
You can do this using the tf.where() and tf.ones_like() ops:

```<code>a = tf.constant([0.0, 0.2, 0.8])

result = tf.where(a > 0.5, tf.ones_like(a), a)  # result is [0.0, 0.2, 1.0]
</code>```

Body:
You can do this using the tf.where() and tf.ones_like() ops:

a = tf.constant([0.0, 0.2, 0.8])

result = tf.where(a > 0.5, tf.ones_like(a), a)  # result is [0.0, 0.2, 1.0]


问:
Regular expression to extract specific part of a URL
I have a vector of URLs and need to extract a certain part of it. I've tried using a regex tester to see if my attempts worked, but they were no good.

The URLs I have are in this format: https://www.baseball-reference.com/teams/MIL/1976.shtml

I ned to extract the three letters after "teams/" (so for the example above, I need "MIL")

Does anyone have any idea how to get the correct regular expression to get this working? Thanks.

答:
Or

```<code>x <- c('https://www.baseball-reference.com/teams/MIL/1976.shtml')
pattern <- "/teams/([^/]+)"
m <- regexec(pattern, x)
res = regmatches(x, m)[[1]]
res[2]
</code>```

which yields

```<code>[1] "MIL"
</code>```

Body:
Or

x <- c('https://www.baseball-reference.com/teams/MIL/1976.shtml')
pattern <- "/teams/([^/]+)"
m <- regexec(pattern, x)
res = regmatches(x, m)[[1]]
res[2]

which yields

[1] "MIL"


问:
How to null N indices following a number in pandas?
I have a Series containing values and NaN's like so:

```<code>0    NaN
1    1.0
2    NaN
3    2.0
4    3.0
5    NaN
6    NaN
7    4.0
8    5.0
9    NaN
dtype: float64
</code>```

And say for example I'd like to null out the next four indices after each initial value, like so:

```<code>0    NaN
1    1.0
2    NaN
3    NaN
4    NaN
5    NaN
6    NaN
7    4.0
8    NaN
9    NaN
dtype: float64
</code>```

(The four directly after the first 1.0 are null'd, as well as the last two directly after the next value, 4.0.)

答:
The loop way, with numba optimisation :

```<code>@numba.njit
def Naning(arr,n=4):
    c=0
    for i in range(arr.size):
        if c>0:
            arr[i]=np.NaN
            c-=1
        elif not np.isnan(arr[i]):
            c=n
</code>```

Run :

```<code>In [419]: df=pd.read_clipboard(header=None,index_col=0)

In [420]: df
Out[420]:
     1
0
0  NaN
1  1.0
2  NaN
3  2.0
4  3.0
5  NaN
6  NaN
7  4.0
8  5.0
9  NaN

In [421]: arr=df.values.squeeze()

In [422]: %timeit Naning(arr)
662 ns ± 9.46 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
</code>```

Result

```<code>In [423]: df
Out[423]:
     1
0
0  NaN
1  1.0
2  NaN
3  NaN
4  NaN
5  NaN
6  NaN
7  4.0
8  NaN
9  NaN
</code>```

Body:
I have a Series containing values and NaN's like so:

0    NaN
1    1.0
2    NaN
3    2.0
4    3.0
5    NaN
6    NaN
7    4.0
8    5.0
9    NaN
dtype: float64

And say for example I'd like to null out the next four indices after each initial value, like so:

0    NaN
1    1.0
2    NaN
3    NaN
4    NaN
5    NaN
6    NaN
7    4.0
8    NaN
9    NaN
dtype: float64

(The four directly after the first 1.0 are null'd, as well as the last two directly after the next value, 4.0.)

Body:
The loop way, with numba optimisation :

@numba.njit
def Naning(arr,n=4):
    c=0
    for i in range(arr.size):
        if c>0:
            arr[i]=np.NaN
            c-=1
        elif not np.isnan(arr[i]):
            c=n

Run :

In [419]: df=pd.read_clipboard(header=None,index_col=0)

In [420]: df
Out[420]:
     1
0
0  NaN
1  1.0
2  NaN
3  2.0
4  3.0
5  NaN
6  NaN
7  4.0
8  5.0
9  NaN

In [421]: arr=df.values.squeeze()

In [422]: %timeit Naning(arr)
662 ns ± 9.46 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Result

In [423]: df
Out[423]:
     1
0
0  NaN
1  1.0
2  NaN
3  NaN
4  NaN
5  NaN
6  NaN
7  4.0
8  NaN
9  NaN


问:
Star-shaped graph in dot?
Ḧi,

I'd like to draw a graph using the dot language that looks like a star ( a central node, wih all the other nodes with one link to this other node).

I've been googling around without finding much. Do you have a basic example ?

thanks

答:
use this example

```<code>    graph g {

    node1 [label="1"]
    node2 [label="2"]
    node3 [label="3"]
    node4 [label="4"]
    node5 [label="5"]
    node6 [label="6"]
    node7 [label="7"]

   node4 -- node3
   node4 -- node2
   node4 -- node1
   node4 -- node5
   node4 -- node7
   node4 -- node6

   }
</code>```

Then invoke this commmand:
        neato -T svg -o direct.svg direct.dot

output as shown:

Title: Star-shaped graph in dot?

Body:
use this example

    graph g {

    node1 [label="1"]
    node2 [label="2"]
    node3 [label="3"]
    node4 [label="4"]
    node5 [label="5"]
    node6 [label="6"]
    node7 [label="7"]

   node4 -- node3
   node4 -- node2
   node4 -- node1
   node4 -- node5
   node4 -- node7
   node4 -- node6

   }

Then invoke this commmand:
        neato -T svg -o direct.svg direct.dot

output as shown:


问:
Length of time representation in Go
Under Unix, I'm working on a program that needs to behave differently depending on whether time is 32-bit (will wrap in 2038) or 64-bit.

I presume Go time is not magic and will wrap in 2038 on a platform with a 32-bit time_t.  If this is false and it is somehow always 64-bit, clue me in because that will prevent much grief.

What's the simplest way in Go to write a test for the platform's time_t size?  Is there any way simpler than the obvious hack with cgo?

答:
If you really want to find the size of time_t, you can use cgo to link to time.h. Then the sizeof time_t will be available as C.sizeof_time_t. It doesn't get much simpler.

```<code>package main

// #include <time.h>
import "C"

import (
    "fmt"
)

func main() {
    fmt.Println(C.sizeof_time_t);
}
</code>```

Other than trying to set the system time to increasingly distant dates, which is not very polite to anything else running on that system, I don't know of any way to directly query the limits of the hardware clock in a portable fashion in any programming language. C simply hard codes the size of time_t in a file provided by the operating system (on OS X it's /usr/include/i386/_types.h), so you're probably best off taking advantage of that information by querying the size of time_t via cgo.

But there's very few reasons to do this. Go does not use time_t and does not appear to suffer from 2038 issues unless you actually plan to have code running on a 32-bit machine in 2038. If that's your plan, I'd suggest finding a better plan.

I presume Go time is not magic and will wrap in 2038 on a platform with a 32-bit time_t. If this is false and it is somehow always 64-bit, clue me in because that will prevent much grief.

Most of the the Year 2038 Problem is programs assuming that the time since 1970 will fit in a 32-bit signed integer. This effects time and date functions, as well as network and data formats which choose to represent time as a 32-bit signed integer since 1970. This is not some hardware limit (except if it's actually 2038, see below), but rather a design limitation of older programming languages and protocols. There's nothing stopping you from using 64 bit integers to represent time, or choosing a different epoch. And that's exactly what newer programming languages do, no magic required.

Go was first released in 2009 long after issues such as Unicode, concurrency, and 32-bit time (ie. the Year 2038 Problem) were acknowledged as issues any programming language would have to tackle. Given how many issues there are with C's time library, I highly doubt that Go is using it at all. A quick skim of the source code confirms.

While I can't find any explicit mention in the Go documentation of the limits of its Time representation, it appears to be completely disconnected from C's time.h structures such as time_t. Since Time uses 64 bit integers, it seems to be clear of 2038 problems unless you're asking for actual clock time.

Digging into the Go docs for Time we find their 0 is well outside the range of a 32-bit time_t which ranges from 1901 to 2038.

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC

time.Unix takes seconds and nanoseconds as 64 bit integers leaving no doubt that it is divorced from the size of time_t.

time.Parse will parse a year "in the range 0000..9999", again well outside the range of a 32-bit time_t.

And so on. The only limitation I could find is that a Duration is limited to 290 years because it has a nanosecond accuracy and 290 years is about 63 bits worth of nanoseconds.

Of course, you should test your code on a machine with a 32-bit time_t.

One side issue of the 2038 Problem is time zones. Computers calculate time zone information from a time zone database, usually the IANA time zone database. This allows one to get the time offset for a certain location at a certain time.

Computers have their own copy of the time zone database installed. Unfortunately its difficult to know where they are located or when they were last updated. To avoid this issue, most programming languages supply their own copy of the time zone database. Go does as well.

The only real limitation on a machine with 32-bit time is the limits of its hardware clock. This tells the software what time it is right now. A 32-bit clock only becomes an issue if your program is still running on a 32-bit machine in 2038. There isn't much point to mitigating that because everything on that machine will have the same problem and its unlikely they took it into account. You're better off decommissioning that hardware before 2038.

Title: Length of time representation in Go

Body:
If you really want to find the size of time_t, you can use cgo to link to time.h. Then the sizeof time_t will be available as C.sizeof_time_t. It doesn't get much simpler.

package main

// #include <time.h>
import "C"

import (
    "fmt"
)

func main() {
    fmt.Println(C.sizeof_time_t);
}

Other than trying to set the system time to increasingly distant dates, which is not very polite to anything else running on that system, I don't know of any way to directly query the limits of the hardware clock in a portable fashion in any programming language. C simply hard codes the size of time_t in a file provided by the operating system (on OS X it's /usr/include/i386/_types.h), so you're probably best off taking advantage of that information by querying the size of time_t via cgo.

But there's very few reasons to do this. Go does not use time_t and does not appear to suffer from 2038 issues unless you actually plan to have code running on a 32-bit machine in 2038. If that's your plan, I'd suggest finding a better plan.

I presume Go time is not magic and will wrap in 2038 on a platform with a 32-bit time_t. If this is false and it is somehow always 64-bit, clue me in because that will prevent much grief.

Most of the the Year 2038 Problem is programs assuming that the time since 1970 will fit in a 32-bit signed integer. This effects time and date functions, as well as network and data formats which choose to represent time as a 32-bit signed integer since 1970. This is not some hardware limit (except if it's actually 2038, see below), but rather a design limitation of older programming languages and protocols. There's nothing stopping you from using 64 bit integers to represent time, or choosing a different epoch. And that's exactly what newer programming languages do, no magic required.

Go was first released in 2009 long after issues such as Unicode, concurrency, and 32-bit time (ie. the Year 2038 Problem) were acknowledged as issues any programming language would have to tackle. Given how many issues there are with C's time library, I highly doubt that Go is using it at all. A quick skim of the source code confirms.

While I can't find any explicit mention in the Go documentation of the limits of its Time representation, it appears to be completely disconnected from C's time.h structures such as time_t. Since Time uses 64 bit integers, it seems to be clear of 2038 problems unless you're asking for actual clock time.

Digging into the Go docs for Time we find their 0 is well outside the range of a 32-bit time_t which ranges from 1901 to 2038.

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC

time.Unix takes seconds and nanoseconds as 64 bit integers leaving no doubt that it is divorced from the size of time_t.

time.Parse will parse a year "in the range 0000..9999", again well outside the range of a 32-bit time_t.

And so on. The only limitation I could find is that a Duration is limited to 290 years because it has a nanosecond accuracy and 290 years is about 63 bits worth of nanoseconds.

Of course, you should test your code on a machine with a 32-bit time_t.

One side issue of the 2038 Problem is time zones. Computers calculate time zone information from a time zone database, usually the IANA time zone database. This allows one to get the time offset for a certain location at a certain time.

Computers have their own copy of the time zone database installed. Unfortunately its difficult to know where they are located or when they were last updated. To avoid this issue, most programming languages supply their own copy of the time zone database. Go does as well.

The only real limitation on a machine with 32-bit time is the limits of its hardware clock. This tells the software what time it is right now. A 32-bit clock only becomes an issue if your program is still running on a 32-bit machine in 2038. There isn't much point to mitigating that because everything on that machine will have the same problem and its unlikely they took it into account. You're better off decommissioning that hardware before 2038.