问:
Python: 'object in list' checks and '__cmp__' overflow
this is my first time at stack overflow so I'm sorry if the format doesn't fit quite right with the site.
I just recently started learning programming, almost 2 weeks have passed since.  I'm learning python from http://openbookproject.net/thinkcs/python/english3e/index.html  and everything had been quite nice until now, where I just got stuck for hours.
I googled a lot but couldn't find a proper solution to my problem so here I am.

I'm trying to get the OldMaidGame() run without problems as explained on CH17. http://openbookproject.net/thinkcs/python/english3e/ch17.html
- Most of the code also comes from the previous chapter.

What I've found out is I can't get the Deck.remove, Hand.remove_matches, or any other kind of remove function to work.  After some debugging I found out
that the problem occurs when the program checks if the given card is present in the deck/hand/etc.  It can't ever make a match.  Then after some looking back on
the chapter, (in ch16), I found out that 'if card in deck/hand/etc: remove(card)' etc looks up the .cmp() of the object to determine if the card actually exists in the deck/hand/etc.  This is my version of the cmp after doing the additions for 'ace's on the given code from the e-book.

```<code>def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    # check the suits
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    # suits are the same... check ranks
    # check for aces first.
    if self.rank == 1 and other.rank == 1: return 0
    if self.rank == 1 and other.rank != 1: return 1
    if self.rank != 1 and other.rank == 1: return -1
    # check for non-aces.
    if self.rank > other.rank: return 1
    if self.rank < other.rank: return -1
    # ranks are the same... it's a tie
    return 0
</code>```

The cmp itself seems fine afaik, ofc I could use some tips on how to make it better (like with ace checks).
So I have no idea why the card in deck/hand checks always return false.
This was the given remove function:

```<code>class Deck:
    ...
    def remove(self, card):
        if card in self.cards:
            self.cards.remove(card)
            return True
        else:
            return False
</code>```

Desperately trying to get it to work, I came up with this:

```<code>class Deck:
    ...
    def remove(self, card):
        """ Removes the card from the deck, returns true if successful """
        for lol in self.cards:
            if lol.__cmp__(card) == 0:
                self.cards.remove(lol)
                return True
        return False
</code>```

Seemed to work fine, until I moved on to the other non-working remove functions:

```<code>class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            if match in self.cards:
                self.cards.remove(card)
                self.cards.remove(match)
                print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                count = count + 1
        return count
</code>```

I again made some adjustments:

```<code>class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            for lol in self.cards:
                if lol.__cmp__(match) == 0:
                    self.cards.remove(card)
                    self.cards.remove(match)
                    print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                    count = count + 1
        return count
</code>```

The removing worked fine for the card, but it would give an error (x not in list) when I tried to remove match.  Another our or so, I might've been able to make that work too, but since it already feels like I'm on the wrong road since I can't fix the original 'card in deck/hand/etc' etc, I came here looking for some answers/tips.

Thanks for reading and I greatly appreciate any help you can give :)

--------------------- EDIT 1 *>

This is my current code:
http://pastebin.com/g77Y4Tjr

--------------------- EDIT 2 *>

I've tried every single cmp advised here, and I still can't get it to find a card with 'in'.

```<code>>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
 Ace of Clubs
  Ace of Spades
>>> d in hand.cards
False
>>>
</code>```

I've also tried the card.py @DSM has used successfully, and I get errors there too, like at the sort function it says it cant compare the two card objects.

So I was wondering, maybe it is a problem with Python 3.2, or maybe the syntax has changed somewhere?

答:
It sounds like you've got a problem with your deck variable. Either the remove function is pointing to a different object with a blank deck, or else you have a namespace issue. Is the remove function part of the deck object?

I'd suggest adding a few print deck lines. One just after it is initialized, to see what it has inside it, and one just as you call remove.

Body:
this is my first time at stack overflow so I'm sorry if the format doesn't fit quite right with the site.
I just recently started learning programming, almost 2 weeks have passed since.  I'm learning python from http://openbookproject.net/thinkcs/python/english3e/index.html  and everything had been quite nice until now, where I just got stuck for hours.
I googled a lot but couldn't find a proper solution to my problem so here I am.

I'm trying to get the OldMaidGame() run without problems as explained on CH17. http://openbookproject.net/thinkcs/python/english3e/ch17.html
- Most of the code also comes from the previous chapter.

What I've found out is I can't get the Deck.remove, Hand.remove_matches, or any other kind of remove function to work.  After some debugging I found out
that the problem occurs when the program checks if the given card is present in the deck/hand/etc.  It can't ever make a match.  Then after some looking back on
the chapter, (in ch16), I found out that 'if card in deck/hand/etc: remove(card)' etc looks up the .cmp() of the object to determine if the card actually exists in the deck/hand/etc.  This is my version of the cmp after doing the additions for 'ace's on the given code from the e-book.

def __cmp__(self, other):
    """ Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
    # check the suits
    if self.suit > other.suit: return 1
    if self.suit < other.suit: return -1
    # suits are the same... check ranks
    # check for aces first.
    if self.rank == 1 and other.rank == 1: return 0
    if self.rank == 1 and other.rank != 1: return 1
    if self.rank != 1 and other.rank == 1: return -1
    # check for non-aces.
    if self.rank > other.rank: return 1
    if self.rank < other.rank: return -1
    # ranks are the same... it's a tie
    return 0

The cmp itself seems fine afaik, ofc I could use some tips on how to make it better (like with ace checks).
So I have no idea why the card in deck/hand checks always return false.
This was the given remove function:

class Deck:
    ...
    def remove(self, card):
        if card in self.cards:
            self.cards.remove(card)
            return True
        else:
            return False

Desperately trying to get it to work, I came up with this:

class Deck:
    ...
    def remove(self, card):
        """ Removes the card from the deck, returns true if successful """
        for lol in self.cards:
            if lol.__cmp__(card) == 0:
                self.cards.remove(lol)
                return True
        return False

Seemed to work fine, until I moved on to the other non-working remove functions:

class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            if match in self.cards:
                self.cards.remove(card)
                self.cards.remove(match)
                print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                count = count + 1
        return count

I again made some adjustments:

class OldMaidHand(Hand):
    def remove_matches(self):
        count = 0
        original_cards = self.cards[:]
        for card in original_cards:
            match = Card(3 - card.suit, card.rank)
            for lol in self.cards:
                if lol.__cmp__(match) == 0:
                    self.cards.remove(card)
                    self.cards.remove(match)
                    print("Hand {0}: {1} matches {2}".format(self.name, card, match))
                    count = count + 1
        return count

The removing worked fine for the card, but it would give an error (x not in list) when I tried to remove match.  Another our or so, I might've been able to make that work too, but since it already feels like I'm on the wrong road since I can't fix the original 'card in deck/hand/etc' etc, I came here looking for some answers/tips.

Thanks for reading and I greatly appreciate any help you can give :)

--------------------- EDIT 1 *>

This is my current code:
http://pastebin.com/g77Y4Tjr

--------------------- EDIT 2 *>

I've tried every single cmp advised here, and I still can't get it to find a card with 'in'.

>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
 Ace of Clubs
  Ace of Spades
>>> d in hand.cards
False
>>>

I've also tried the card.py @DSM has used successfully, and I get errors there too, like at the sort function it says it cant compare the two card objects.

So I was wondering, maybe it is a problem with Python 3.2, or maybe the syntax has changed somewhere?


来源: stackexchange

问:
Android Navigation Component : Pass value (arguments) in fragments

What I have done:

I have created Navigation Drawer Activity, As updated new format of Navigation Drawer Activity, As per new Android architecture, I got it with Navigation Component structure.

The NavigationView code with NavController and NavigationUI is below which is opening fragment when I click on any navigation item.

DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
        R.id.nav_home, R.id.nav_profile, R.id.nav_privacy_policy,
        R.id.nav_terms, R.id.nav_contact_us, R.id.nav_share, R.id.nav_send)
        .setDrawerLayout(drawer)
        .build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
```
<p>This is for <code>nav_host_fragment</code>:</p>
<pre class="lang-xml prettyprint-override"><code><fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/mobile_navigation" />
</code>```

The navigation is happening using this navigation/mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_home"
        android:name="com.sohamerp.marsremedies.fragment.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/nav_profile"
        android:name="com.sohamerp.marsremedies.fragment.ProfileFragment"
        android:label="@string/menu_my_profile"
        tools:layout="@layout/fragment_profile" />

    <fragment
        android:id="@+id/nav_privacy_policy"
        android:name="com.sohamerp.marsremedies.fragment.PrivacyPolicyFragment"
        android:label="@string/menu_privacy_policy"
        tools:layout="@layout/fragment_privacy_policy" />

    <fragment
        android:id="@+id/nav_terms"
        android:name="com.sohamerp.marsremedies.fragment.TermsConditionFragment"
        android:label="@string/menu_terms"
        tools:layout="@layout/fragment_terms_condition" />

    <fragment
        android:id="@+id/nav_contact_us"
        android:name="com.sohamerp.marsremedies.fragment.ContactUsFragment"
        android:label="@string/menu_contact_us"
        tools:layout="@layout/fragment_terms_condition" />

</navigation>
```

What I want to do:

Now I want to pass some values as a bundle (arguments) in Fragment when it's called.

Scenario: I have two fragments PrivacyPolicyFragment and TermsConditionsFragment, In both fragments, I am just opening links inside WebView accordingly. So When I click on the menu item of Privacy Policy, I will pass a link related to the same.

In this new structure navigation/mobile_navigation.xml opening fragments, How can I pass arguments?

Any help?

答:
You can also pass serializable objects, enum values and arrays of primitive types.
For example:

```<code>enum class ObjectType : Serializable {
    FIRST, SECOND
}
</code>```

Then, add arguments to the xml

```<code><fragment
        android:id="@+id/nav_profile"
        android:name="com.sohamerp.marsremedies.fragment.ProfileFragment"
        android:label="@string/menu_my_profile"
        tools:layout="@layout/fragment_profile" >

        <argument
            android:name="myObjectType"
            android:defaultValue="SECOND"
            app:argType="com.project.app.data.ObjectType" />
</fragment>
</code>```

Note, that you should specify complete path!

ContentLicense: CC BY-SA 4.0

Body:
What I have done:

I have created Navigation Drawer Activity, As updated new format of Navigation Drawer Activity, As per new Android architecture, I got it with Navigation Component structure.

The NavigationView code with NavController and NavigationUI is below which is opening fragment when I click on any navigation item.

DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
        R.id.nav_home, R.id.nav_profile, R.id.nav_privacy_policy,
        R.id.nav_terms, R.id.nav_contact_us, R.id.nav_share, R.id.nav_send)
        .setDrawerLayout(drawer)
        .build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);

This is for nav_host_fragment:

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/mobile_navigation" />

The navigation is happening using this navigation/mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_home"
        android:name="com.sohamerp.marsremedies.fragment.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/nav_profile"
        android:name="com.sohamerp.marsremedies.fragment.ProfileFragment"
        android:label="@string/menu_my_profile"
        tools:layout="@layout/fragment_profile" />

    <fragment
        android:id="@+id/nav_privacy_policy"
        android:name="com.sohamerp.marsremedies.fragment.PrivacyPolicyFragment"
        android:label="@string/menu_privacy_policy"
        tools:layout="@layout/fragment_privacy_policy" />

    <fragment
        android:id="@+id/nav_terms"
        android:name="com.sohamerp.marsremedies.fragment.TermsConditionFragment"
        android:label="@string/menu_terms"
        tools:layout="@layout/fragment_terms_condition" />

    <fragment
        android:id="@+id/nav_contact_us"
        android:name="com.sohamerp.marsremedies.fragment.ContactUsFragment"
        android:label="@string/menu_contact_us"
        tools:layout="@layout/fragment_terms_condition" />

</navigation>

What I want to do:

Now I want to pass some values as a bundle (arguments) in Fragment when it's called.

Scenario: I have two fragments PrivacyPolicyFragment and TermsConditionsFragment, In both fragments, I am just opening links inside WebView accordingly. So When I click on the menu item of Privacy Policy, I will pass a link related to the same.

In this new structure navigation/mobile_navigation.xml opening fragments, How can I pass arguments?

Any help?

Body:
You can also pass serializable objects, enum values and arrays of primitive types.
For example:

enum class ObjectType : Serializable {
    FIRST, SECOND
}

Then, add arguments to the xml

<fragment
        android:id="@+id/nav_profile"
        android:name="com.sohamerp.marsremedies.fragment.ProfileFragment"
        android:label="@string/menu_my_profile"
        tools:layout="@layout/fragment_profile" >

        <argument
            android:name="myObjectType"
            android:defaultValue="SECOND"
            app:argType="com.project.app.data.ObjectType" />
</fragment>

Note, that you should specify complete path!


问:
dynamic xpath in xslt?
I have follwing set of files:

SourceFile.xml:

```<code>      <?xml version="1.0" encoding="utf-8" ?>
     <Employees>
     <Employee id="1">
          <firstname relationship="headnote">Atif</firstname>
          <lastname relationship="lname">Bashir</lastname>
          <age relationship="age">32</age>
          </Employee>
     </Employees>
</code>```

ParamerterSettings.xml

```<code>        <?xml version="1.0" encoding="utf-8"?>
        <Settings>
        <Employee id="1">
             <sourceFile>Lookup1.xml</sourceFile>
             <sourceXpathfield>Employees/Employee[@id</sourceXpathfield>
             <lookupXpathfield>Employees/Employee[@id='1']</lookupXpathfield>
             <elementstoinsert>xyz</elementstoinsert>
             </Employee>
         </Settings>
</code>```

Lookup.xml

```<code><?xml version="1.0" encoding="utf-8"?>
 <Employees>
  <Employee id="1">
      <department code="102">HR</department>
   </Employee>
   </Employees>
</code>```

transform.xsl

```<code>  <?xml version="1.0" encoding="UTF-8" ?>
   <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

   <xsl:include href="identity.xsl"/>

  <xsl:param name="EmployeeId" select="'1,2'" />
  <xsl:variable name="FileSettings" select="document('test3.xml')" />
  <xsl:variable name="SuppressSetting" select="$FileSettings/Settings/Employee[@id = tokenize($EmployeeId, ',')]" />

  <xsl:template match="Employee">
  <xsl:copy>
  <xsl:apply-templates select="@*"/>
  <xsl:apply-templates select="publisher" />
  <xsl:apply-templates select="node() except publisher"/>
  <xsl:variable name="outerfile" select="document($SuppressSetting/sourceFile)"></xsl:variable>
  <xsl:variable name="outerfiledetails" select="$outerfile/$SuppressSetting/lookupXpathfield"></xsl:variable>
  <xsl:value-of select="$outerfiledetails"></xsl:value-of>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

The output should be:

```<code>     <?xml version="1.0" encoding="utf-8" ?>
     <Employees>
     <Employee id="1">
          <firstname relationship="headnote">Atif</firstname>
          <lastname relationship="lname">Bashir</lastname>
          <age relationship="age">32</age>
          HR
          </Employee>
     </Employees>
</code>```

I changed the below line in Transform.xsl

```<code><xsl:variable name="outerfiledetails" select="$outerfile/$SuppressSetting/lookupXpathfield"></xsl:variable>
</code>```

into

```<code><xsl:variable name="outerfiledetails" select="$outerfile/Employees/Employee[@id='1']"></xsl:variable>
</code>```

then I am getting my output but I want to keep the XPath epression for both SourceFile.xml and Lookup.xml into ParamerterSettings.xml so that I can write a more generic script. Can this be done in any other way then the dynamic xpath? Any idea or hint to impelement the same will be highly appreciated.

答:
One possible trick is to call an parametrized xsl:template which carries out the crucial select comparison part and evaluate it's output as string.
See this answer

ContentLicense: CC BY-SA 3.0

Title: dynamic xpath in xslt?

Body:
I have follwing set of files:

SourceFile.xml:

      <?xml version="1.0" encoding="utf-8" ?>
     <Employees>
     <Employee id="1">
          <firstname relationship="headnote">Atif</firstname>
          <lastname relationship="lname">Bashir</lastname>
          <age relationship="age">32</age>
          </Employee>
     </Employees>

ParamerterSettings.xml

        <?xml version="1.0" encoding="utf-8"?>
        <Settings>
        <Employee id="1">
             <sourceFile>Lookup1.xml</sourceFile>
             <sourceXpathfield>Employees/Employee[@id</sourceXpathfield>
             <lookupXpathfield>Employees/Employee[@id='1']</lookupXpathfield>
             <elementstoinsert>xyz</elementstoinsert>
             </Employee>
         </Settings>

Lookup.xml

<?xml version="1.0" encoding="utf-8"?>
 <Employees>
  <Employee id="1">
      <department code="102">HR</department>
   </Employee>
   </Employees>

transform.xsl

  <?xml version="1.0" encoding="UTF-8" ?>
   <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

   <xsl:include href="identity.xsl"/>

  <xsl:param name="EmployeeId" select="'1,2'" />
  <xsl:variable name="FileSettings" select="document('test3.xml')" />
  <xsl:variable name="SuppressSetting" select="$FileSettings/Settings/Employee[@id = tokenize($EmployeeId, ',')]" />

  <xsl:template match="Employee">
  <xsl:copy>
  <xsl:apply-templates select="@*"/>
  <xsl:apply-templates select="publisher" />
  <xsl:apply-templates select="node() except publisher"/>
  <xsl:variable name="outerfile" select="document($SuppressSetting/sourceFile)"></xsl:variable>
  <xsl:variable name="outerfiledetails" select="$outerfile/$SuppressSetting/lookupXpathfield"></xsl:variable>
  <xsl:value-of select="$outerfiledetails"></xsl:value-of>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>

The output should be:

     <?xml version="1.0" encoding="utf-8" ?>
     <Employees>
     <Employee id="1">
          <firstname relationship="headnote">Atif</firstname>
          <lastname relationship="lname">Bashir</lastname>
          <age relationship="age">32</age>
          HR
          </Employee>
     </Employees>

I changed the below line in Transform.xsl

<xsl:variable name="outerfiledetails" select="$outerfile/$SuppressSetting/lookupXpathfield"></xsl:variable>

into

<xsl:variable name="outerfiledetails" select="$outerfile/Employees/Employee[@id='1']"></xsl:variable>

then I am getting my output but I want to keep the XPath epression for both SourceFile.xml and Lookup.xml into ParamerterSettings.xml so that I can write a more generic script. Can this be done in any other way then the dynamic xpath? Any idea or hint to impelement the same will be highly appreciated.


问:
Matlab or Octave plot auto-generated dates on x axis
I have a few hundred integer measurements. They are taken daily. I know the first measurement was taken on the 3/3/2019. I do not have any date explicitly related to each measurement.   I would like to plot these values on the y axis and the consecutive dates on the x axis.  I would also like to plot a subset of these measurements.For example, from 6/6/2019 until 11/11/2019, preferably by supplying only the initial start date and the two subset dates.</p>

答:
Something like this should work (I tried it in Octave, but should also work in MATLAB):

```<code>data = randi(100,50,1); % some random data

start_date = datenum('03/03/2019','dd/mm/yyyy');
dates = start_date + (1:length(data));

% Plot data
figure
plot(dates,data)
datetick('dd/mm')

% Plot subset of the data
dates_start  = datenum('16/03/2019','dd/mm/yyyy'); % change to your actual start date
dates_end = datenum('05/04/2019','dd/mm/yyyy'); % change to your actual end date
dates_subset = dates(dates>=dates_start & dates <=dates_end);
data_subset = data(dates>=dates_start & dates <=dates_end);
figure
plot(dates_subset,data_subset)
datetick('dd/mm')
</code>```

This produces the following plots:

Body:
Something like this should work (I tried it in Octave, but should also work in MATLAB):

data = randi(100,50,1); % some random data

start_date = datenum('03/03/2019','dd/mm/yyyy');
dates = start_date + (1:length(data));

% Plot data
figure
plot(dates,data)
datetick('dd/mm')

% Plot subset of the data
dates_start  = datenum('16/03/2019','dd/mm/yyyy'); % change to your actual start date
dates_end = datenum('05/04/2019','dd/mm/yyyy'); % change to your actual end date
dates_subset = dates(dates>=dates_start & dates <=dates_end);
data_subset = data(dates>=dates_start & dates <=dates_end);
figure
plot(dates_subset,data_subset)
datetick('dd/mm')

This produces the following plots:


问:
Error reading data from the old files, writing it into the new files and then deleting the old files in Python
I'm trying to use below code to read 5 files from source, write them in destination and then deleting the files in source. I get the following error: [Errno 13] Permission denied: 'c:\\data\\AM\\Desktop\\tester1. The file by the way look like this:

```<code>import os
import time

source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    file_path = os.path.join(source, file)
    if not os.path.isfile:
        continue
    print(file_path)

with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
    data ={
            'Power': None,
            }
    for line in IN:
        splitter = (ID, Item, Content, Status) = line.strip().split()
        if Item in data == "Power":
            Content = str(int(Content) * 10)

os.remove(IN)
</code>```

答:
I'm not sure what you're going for here, but here's what I could come up with the question put into the title.</p>

```<code>import os

# Takes the text from the old file
with open('old file path.txt', 'r') as f:
    text = f.read()

# Takes text from old file and writes it to the new file
with open('new file path.txt', 'w') as f:
    f.write(text)

# Removes the old text file
os.remove('old file path.txt')
</code>```

Body:
I'm trying to use below code to read 5 files from source, write them in destination and then deleting the files in source. I get the following error: [Errno 13] Permission denied: 'c:\\data\\AM\\Desktop\\tester1. The file by the way look like this:

import os
import time

source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    file_path = os.path.join(source, file)
    if not os.path.isfile:
        continue
    print(file_path)

with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
    data ={
            'Power': None,
            }
    for line in IN:
        splitter = (ID, Item, Content, Status) = line.strip().split()
        if Item in data == "Power":
            Content = str(int(Content) * 10)

os.remove(IN)

Body:
I'm not sure what you're going for here, but here's what I could come up with the question put into the title.

import os

# Takes the text from the old file
with open('old file path.txt', 'r') as f:
    text = f.read()

# Takes text from old file and writes it to the new file
with open('new file path.txt', 'w') as f:
    f.write(text)

# Removes the old text file
os.remove('old file path.txt')


问:
Hybris extension .project file
I have taken custom hybris extension folder from git and it does not contains any .project file. Will eclipse autogenerate this file while import or I need to make a new one?</p>

答:
See this answer: https://stackoverflow.com/a/53880050/90513

If the Git project / repository is what your team is using, it's probably better to ask your team mate to push the .project file.

Title: Hybris extension .project file


问:
How to keep keys/values in same order as declared?
I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.

So if I have the dictionary:

```<code>d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}
</code>```

It isn't in that order if I view it or iterate through it. Is there any way to make sure Python will keep the explicit order that I declared the keys/values in?

答:
I had a similar problem when developing a Django project. I couldn't use OrderedDict, because I was running an old version of python, so the solution was to use Django's SortedDict class:

https://code.djangoproject.com/wiki/SortedDict

e.g.,

```<code>from django.utils.datastructures import SortedDict
d2 = SortedDict()
d2['b'] = 1
d2['a'] = 2
d2['c'] = 3
</code>```

Note: This answer is originally from 2011. If you have access to Python version 2.7 or higher, then you should have access to the now standard collections.OrderedDict, of which many examples have been provided by others in this thread.

Body:
I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.

So if I have the dictionary:

d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}

It isn't in that order if I view it or iterate through it. Is there any way to make sure Python will keep the explicit order that I declared the keys/values in?

Body:
I had a similar problem when developing a Django project. I couldn't use OrderedDict, because I was running an old version of python, so the solution was to use Django's SortedDict class:

https://code.djangoproject.com/wiki/SortedDict

e.g.,

from django.utils.datastructures import SortedDict
d2 = SortedDict()
d2['b'] = 1
d2['a'] = 2
d2['c'] = 3

Note: This answer is originally from 2011. If you have access to Python version 2.7 or higher, then you should have access to the now standard collections.OrderedDict, of which many examples have been provided by others in this thread.


问:
R Rearrange columns in dataframe based on date values in column names
I've got a dataframe that has monthly survey scores for a certain hospitals. Each month, we store the score obtained by the hospital (_Score column) and the corresponding average score for all hospitals for that month (_Average column).

Here's a short sample of what it looks like -

```<code>df = data.frame(Hospital=c(rep("Hospital A",10),rep("Hospital B",10),rep("Hospital C",10),rep("Hospital D",10)),
                Question=c(rep("Q1",40)),
                key=c(rep(c("2020-01-31_Average","2020-01-31_Score","2020-02-29_Average","2020-02-29_Score",
                      "2020-03-31_Average","2020-03-31_Score","2020-04-30_Average","2020-04-30_Score",
                      "2020-05-31_Average","2020-05-31_Score"),4)),
                value=c(round(runif(40,0,1),2)))

library(tidyr)
df = df %>% spread(key,value)
</code>```

I would like to transform this dataframe such that -

1) The first two columns, Hospital and Question remain the same

2) _Score columns for the three most recent months only are kept

3) _Average column for the most recent month is kept

4) Ideally, the columns need to be reordered from oldest to most recent (i.e. in the following order: Month M-2_Score, Month M-1_Score, Month M_Score, Month M_Average)

5) Calculate a column Variance at the end, which is the difference between Score M and Score M-1

What I'm trying to achieve

Using dplyr, this can be done manually by reordering the columns. But I'm looking for a way to build a logic that automatically reorders columns for the 3 most recent months in the sequence described above. By taking the date values embedded in the column names and reordering according to them.

The resulting table would look like this -

```<code>#Final table
df_transformed = df %>%
  select(1:2,8,10,12,11) %>%
  mutate(Variance=.[[5]]-.[[4]])
</code>```

Any tips on how to do this more efficiently using the date values in the column names would be highly appreciated.

答:
I don't really get questions 4 and 5, but they feel a little like "Can you do my homework, please?". For questions 1 to 3, consider this:</p>

```<code>library(tidyverse)
library(lubridate)

df <- data.frame(Hospital=c(rep("Hospital A",10),rep("Hospital B",10),rep("Hospital C",10),rep("Hospital D",10)),
                Question=c(rep("Q1",40)),
                key=c(rep(c("2020-01-31_Average","2020-01-31_Score","2020-02-29_Average","2020-02-29_Score",
                      "2020-03-31_Average","2020-03-31_Score","2020-04-30_Average","2020-04-30_Score",
                      "2020-05-31_Average","2020-05-31_Score"),4)),
                value=c(round(runif(40,0,1),2)))

# take the dataframe
df %>%
    # get month as a date and key separately
    mutate(month = str_replace(key, "_[[:alpha:]]*$", "") %>% ymd()
           , key = str_extract(key, "[[:alpha:]]*$")) %>%
    # filter Score for the last 3 and Average for the last 1 months
    filter(!(today() - month > months(3) &
                 key == "Score")) %>%
    filter(!(today() - month > months(1) &
                 key == "Average"))
</code>```

Body:
I've got a dataframe that has monthly survey scores for a certain hospitals. Each month, we store the score obtained by the hospital (_Score column) and the corresponding average score for all hospitals for that month (_Average column).

Here's a short sample of what it looks like -

df = data.frame(Hospital=c(rep("Hospital A",10),rep("Hospital B",10),rep("Hospital C",10),rep("Hospital D",10)),
                Question=c(rep("Q1",40)),
                key=c(rep(c("2020-01-31_Average","2020-01-31_Score","2020-02-29_Average","2020-02-29_Score",
                      "2020-03-31_Average","2020-03-31_Score","2020-04-30_Average","2020-04-30_Score",
                      "2020-05-31_Average","2020-05-31_Score"),4)),
                value=c(round(runif(40,0,1),2)))

library(tidyr)
df = df %>% spread(key,value)

I would like to transform this dataframe such that -

1) The first two columns, Hospital and Question remain the same

2) _Score columns for the three most recent months only are kept

3) _Average column for the most recent month is kept

4) Ideally, the columns need to be reordered from oldest to most recent (i.e. in the following order: Month M-2_Score, Month M-1_Score, Month M_Score, Month M_Average)

5) Calculate a column Variance at the end, which is the difference between Score M and Score M-1

What I'm trying to achieve

Using dplyr, this can be done manually by reordering the columns. But I'm looking for a way to build a logic that automatically reorders columns for the 3 most recent months in the sequence described above. By taking the date values embedded in the column names and reordering according to them.

The resulting table would look like this -

#Final table
df_transformed = df %>%
  select(1:2,8,10,12,11) %>%
  mutate(Variance=.[[5]]-.[[4]])

Any tips on how to do this more efficiently using the date values in the column names would be highly appreciated.

Body:
I don't really get questions 4 and 5, but they feel a little like "Can you do my homework, please?". For questions 1 to 3, consider this:

library(tidyverse)
library(lubridate)

df <- data.frame(Hospital=c(rep("Hospital A",10),rep("Hospital B",10),rep("Hospital C",10),rep("Hospital D",10)),
                Question=c(rep("Q1",40)),
                key=c(rep(c("2020-01-31_Average","2020-01-31_Score","2020-02-29_Average","2020-02-29_Score",
                      "2020-03-31_Average","2020-03-31_Score","2020-04-30_Average","2020-04-30_Score",
                      "2020-05-31_Average","2020-05-31_Score"),4)),
                value=c(round(runif(40,0,1),2)))

# take the dataframe
df %>%
    # get month as a date and key separately
    mutate(month = str_replace(key, "_[[:alpha:]]*$", "") %>% ymd()
           , key = str_extract(key, "[[:alpha:]]*$")) %>%
    # filter Score for the last 3 and Average for the last 1 months
    filter(!(today() - month > months(3) &
                 key == "Score")) %>%
    filter(!(today() - month > months(1) &
                 key == "Average"))


问:
Remove metadata from non-picture file using PHP
I've recently learned about Imagick and removing image exif/metadata.

However for my work, I was wondering if there was an alternative for the following file types:

Audio/mp3/wav/ogg/flac
text/txt/rtf
pdf
application/word/power point/excel

Imagick works as intended for stripping the file's metadata. I'm just unsure/can't find much info on removing metadata for other file tpyes!

Users will chose a file to upload, and whether its metadata is removed at all.

Cheers :)

答:
Different filetypes will require different tools.

For the audio formats, the metadata is embedded in a container. I think ffmpeg will be able to strip most of it .

And then for the pdf and Microsoft formats: these can be a bit more challenging. exiftool should be able to help you out in most cases.

I don't think txt, text and rtf can contain metadata. What are you aiming for with these?


问:
Xamarin Android bindings library for Jitsi
I'm trying to create in Xamarin Android the Jitsi Bindings Library. I've got all the dependecies aar (66 items) by following this guide:

https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-android-sdk

(Maven repository https://github.com/jitsi/jitsi-maven-repository/raw/master/releases)

And this is the result so far: it is missing JitsiMeetActivity

Any help? Thanks

答:
I have the same issue..

It seems that the binding process misses all the classes that extend from a base class...

as an example try also looking for the JitsiMeetActivityInterface interface definition, its a really simple class but its also missing from the binding process as well as a few others.

Happy to work with you on this too if you like.


问:
simultaneous page load and ajax call
I have a web application with some pages take quite a long time to load because of what they have to do in code behind. I would like to show what is going on to the user by showing the different status of the process.

I was thinking about calling recursively (by ajax) a page which ready a value in the session. This value is set by the page that take time to load.
The problem is that the page called by ajax is not executed while the other page load is finished.
Is there some way to do that?

Thanks advance

答: Separate the part of the code that takes a long time and call it asynchronously (e.g. as a WebMethod) on page load, e.g. if using jQuery, on document.ready. You could also fake this using an UpdatePanel which is set to conditional refresh, and the code is never run by default. Then refresh it from script using __doPostBack('updatePanelUniqueID','').

Title: simultaneous page load and ajax call


问:
Can't convert Pytorch to ONNX
Trying to convert this pytorch model with ONNX gives me this error. I've searched github and this error came up before in version 1.1.0 but was apparently rectified. Now I'm on torch 1.4.0. (python 3.6.9) and I see this error.

```<code>File "/usr/local/lib/python3.6/dist-packages/torch/onnx/init.py", line 148, in export
strip_doc_string, dynamic_axes, keep_initializers_as_inputs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 66, in export
dynamic_axes=dynamic_axes, keep_initializers_as_inputs=keep_initializers_as_inputs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 416, in _export
fixed_batch_size=fixed_batch_size)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 296, in _model_to_graph
fixed_batch_size=fixed_batch_size, params_dict=params_dict)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 135, in _optimize_graph
graph = torch._C._jit_pass_onnx(graph, operator_export_type)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/init.py", line 179, in _run_symbolic_function
return utils._run_symbolic_function(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 657, in _run_symbolic_function
return op_fn(g, *inputs, **attrs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/symbolic_helper.py", line 128, in wrapper
args = [_parse_arg(arg, arg_desc) for arg, arg_desc in zip(args, arg_descriptors)]
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/symbolic_helper.py", line 128, in
args = [_parse_arg(arg, arg_desc) for arg, arg_desc in zip(args, arg_descriptors)]
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/symbolic_helper.py", line 81, in _parse_arg
"', since it's not constant, please try to make "
RuntimeError: Failed to export an ONNX attribute 'onnx::Gather', since it's not constant, please try to make things (e.g., kernel size) static if possible
</code>```

How to fix it? I've also tried latest nightly build, same error comes up.

My code:

```<code>from model import BiSeNet
import torch.onnx
import torch

net = BiSeNet(19)
net.cuda()
net.load_state_dict(torch.load('/content/drive/My Drive/Collab/fp/res/cp/79999_iter.pth'))
net.eval()

dummy = torch.rand(1,3,512,512).cuda()
torch.onnx.export(net, dummy, "Model.onnx", input_names=["image"], output_names=["output"])
</code>```

I added print (v.node ()) to symbolic_helper.py just before the runtime error is raised to see what's causing the error.

This is the output: %595 : Long() = onnx::Gather[axis=0](%592, %594) # /content/drive/My Drive/Collab/fp/model.py:111:0

And that line in 111 in model.py is: avg = F.avg_pool2d(feat32, feat32.size()[2:])

This source suggests that tensor.size method in pytorch cannot be recognized by onnx and needs to be modified into a constant.

答:
I have struggled with same issue.

F.adaptive_avg_pool2d is not supported in my case. you have to try other operations.

I hope this helps.

Thanks

Title: Can't convert Pytorch to ONNX

Body:
Trying to convert this pytorch model with ONNX gives me this error. I've searched github and this error came up before in version 1.1.0 but was apparently rectified. Now I'm on torch 1.4.0. (python 3.6.9) and I see this error.

File "/usr/local/lib/python3.6/dist-packages/torch/onnx/init.py", line 148, in export
strip_doc_string, dynamic_axes, keep_initializers_as_inputs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 66, in export
dynamic_axes=dynamic_axes, keep_initializers_as_inputs=keep_initializers_as_inputs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 416, in _export
fixed_batch_size=fixed_batch_size)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 296, in _model_to_graph
fixed_batch_size=fixed_batch_size, params_dict=params_dict)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 135, in _optimize_graph
graph = torch._C._jit_pass_onnx(graph, operator_export_type)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/init.py", line 179, in _run_symbolic_function
return utils._run_symbolic_function(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/utils.py", line 657, in _run_symbolic_function
return op_fn(g, *inputs, **attrs)
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/symbolic_helper.py", line 128, in wrapper
args = [_parse_arg(arg, arg_desc) for arg, arg_desc in zip(args, arg_descriptors)]
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/symbolic_helper.py", line 128, in
args = [_parse_arg(arg, arg_desc) for arg, arg_desc in zip(args, arg_descriptors)]
File "/usr/local/lib/python3.6/dist-packages/torch/onnx/symbolic_helper.py", line 81, in _parse_arg
"', since it's not constant, please try to make "
RuntimeError: Failed to export an ONNX attribute 'onnx::Gather', since it's not constant, please try to make things (e.g., kernel size) static if possible

How to fix it? I've also tried latest nightly build, same error comes up.

My code:

from model import BiSeNet
import torch.onnx
import torch

net = BiSeNet(19)
net.cuda()
net.load_state_dict(torch.load('/content/drive/My Drive/Collab/fp/res/cp/79999_iter.pth'))
net.eval()

dummy = torch.rand(1,3,512,512).cuda()
torch.onnx.export(net, dummy, "Model.onnx", input_names=["image"], output_names=["output"])

I added print (v.node ()) to symbolic_helper.py just before the runtime error is raised to see what's causing the error.

This is the output: %595 : Long() = onnx::Gather[axis=0](%592, %594) # /content/drive/My Drive/Collab/fp/model.py:111:0

And that line in 111 in model.py is: avg = F.avg_pool2d(feat32, feat32.size()[2:])

This source suggests that tensor.size method in pytorch cannot be recognized by onnx and needs to be modified into a constant.


问:
Space in Batch File
I'm fairly new to batches. Starting to learn the basics but already run into a problem.

So my Code looks something like this:

```<code>findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\*.* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause
</code>```

The Problem here is, that I also receive Files with spaces. For Example "File with Spacer.pdf".
I already tried to use quotation marks. But these didnt work out for me.

Maybe you can give me a hint how to solve this one.

Thanks!

Edit:

Tried to use the quotation marks direct at the file name ("* ".*).

```<code>findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\"*".* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause
</code>```

And I tried to use it for the whole path ("C:\Users\XY\Desktop\Start*.*")

```<code>findstr /i /m Findthisstring "C:\Users\XY\Desktop\Start\*.*" > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause
</code>```

答:
As you've seemingly ignored some of the advice provided in the comments, here's my comment again as an answer instead.

You don't really need to output to a text file then read that file, (and then optionally delete that file), you can do it all within the same loop:

@For /F Delims^=^ EOL^= %%I In (
    '%__AppDir__%findstr.exe /IMP "FindThisString" "%UserProfile%\Desktop\Start\*" 2^>NUL'
) Do @Move /Y "%%I" "%UserProfile%\Desktop\Target"
```

Depending upon your FindThisString you may wish to change the options to /IMPC:"FindThisString" or /LIMP "FindThisString"

Title: Space in Batch File

Body:
I'm fairly new to batches. Starting to learn the basics but already run into a problem.

So my Code looks something like this:

findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\*.* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause

The Problem here is, that I also receive Files with spaces. For Example "File with Spacer.pdf".
I already tried to use quotation marks. But these didnt work out for me.

Maybe you can give me a hint how to solve this one.

Thanks!

Edit:

Tried to use the quotation marks direct at the file name ("* ".*).

findstr /i /m Findthisstring C:\Users\XY\Desktop\Start\"*".* > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause

And I tried to use it for the whole path ("C:\Users\XY\Desktop\Start*.*")

findstr /i /m Findthisstring "C:\Users\XY\Desktop\Start\*.*" > test.lst
for /f %%I in (C:\Users\XY\Desktop\test.lst) do @move %%I C:\Users\XY\Desktop\Target\

pause

Body:
As you've seemingly ignored some of the advice provided in the comments, here's my comment again as an answer instead.

You don't really need to output to a text file then read that file, (and then optionally delete that file), you can do it all within the same loop:

@For /F Delims^=^ EOL^= %%I In (
    '%__AppDir__%findstr.exe /IMP "FindThisString" "%UserProfile%\Desktop\Start\*" 2^>NUL'
) Do @Move /Y "%%I" "%UserProfile%\Desktop\Target"

Depending upon your FindThisString you may wish to change the options to /IMPC:"FindThisString" or /LIMP "FindThisString"


问:
How to get clicked/selected items of a QTreeWidget
I'm currently looking to a way to get the name of the selected items of a QTreeWidget.

I have create multiple QTreeWidgetItems to generate a file browser-like.

I need to know how to get the name of the folder selected.

I have found the

```<code>this->MyTree->selectedItems();
</code>```

to get it but I'm not able to store the feedback which is supposed to be a QList format.

Any examples on how to store the selectedItems list ?

答:
```<code>{
    ...
    connect(treeWidget, &QTreeWidget::itemClicked, this, &MyForm::onItemClicked);
    connect(treeWidget, &QTreeWidget::itemActivated, this, &MyForm::onItemClicked);
}

void MyForm::onItemClicked(QTreeWidgetItem *item, int) {
    if (item == item0) {
        stackedWidget->setCurrentWidget(widget0);
    }
    else if (item == item1) {
        stackedWidget->setCurrentWidget(widget1);
    }
}
</code>```

Body:
I'm currently looking to a way to get the name of the selected items of a QTreeWidget.

I have create multiple QTreeWidgetItems to generate a file browser-like.

I need to know how to get the name of the folder selected.

I have found the

this->MyTree->selectedItems();

to get it but I'm not able to store the feedback which is supposed to be a QList format.

Any examples on how to store the selectedItems list ?


问:
How to get list of All Node Names from XML document using Java
```<code>import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class comparexmls {
  public static void main(String[] argv) throws Exception {
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(is);

    NodeList list = doc.getChildNodes();
    //System.out.println(doc.getChildNodes().item(2));
    for (int i = 0; i < list.getLength(); i++) {
      if (list.item(i) instanceof Element) {
        Element root = (Element) list.item(i);
        System.out.println(root.getNodeName());

        break;
      }
    }
  }

  static String xmlRecords =
      "<Search.UDB.OUT TraceId=\"1234\">\r\n" +
      "    <Response>Success</Response>\r\n" +
      "    <Status>\r\n" +
      "        <System Name=\"X\">\r\n" +
      "            <Code>00</Code>\r\n" +
      "            <Message></Message>\r\n" +
      "        </System>\r\n" +
      "        <System Name=\"Y\">\r\n" +
      "            <Code>00</Code>\r\n" +
      "            <Message></Message>\r\n" +
      "        </System>\r\n" +
      "        <System Name=\"Z\">\r\n" +
      "            <Code>00</Code>\r\n" +
      "            <Message></Message>\r\n" +
      "        </System>\r\n" +
      "    </Status>\r\n" +
      "    <NumberFound>1</NumberFound>\r\n" +
      "    <AccountList>\r\n" +
      "        <Account>\r\n" +
      "            <AccountNumber>XXXXXXXXXXXX</AccountNumber>\r\n" +
      "            <CorpNo>XX</CorpNo>\r\n" +
      "            <Name>Chandra</Name>\r\n" +
      "            <AddressLine1>100 MAIN ST</AddressLine1>\r\n" +
      "            <AddressLine2>ANYTOWN</AddressLine2>\r\n" +
      "            <AddressLine3> GA 123456789</AddressLine3>\r\n" +
      "            <Block />\r\n" +
      "            <Reclass />\r\n" +
      "            <EmbossLine4 />\r\n" +
      "            <Phone>1234567890</Phone>\r\n" +
      "        </Account>\r\n" +
      "    </AccountList>\r\n" +
      "</Search.UDB.OUT>";

}
</code>```

<p>I am getting Search.UDB.OUT only.. How to iterate all the parent and childnodes.. </p>

答:
Take a look at the XmlSlurper class in http://stefanfrings.de/bfUtilities/bfUtilities.zip. It's a recursive algorithm.

It reads the whole XML into a simple flat HashMap collecting all element names in the format:

```<code>Search.UDB.OUT.TraceId
Search.UDB.OUT.Response
Search.UDB.OUT.Status.System.Name
...
</code>```

Source code of that class:

```<code>package de.stefanfrings.parsing;

import de.stefanfrings.container.ConvertingHashMap;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlSlurper
{

    public static ConvertingHashMap parse(String xmlDocument) throws ParserConfigurationException, SAXException, IOException
    {
        ConvertingHashMap targetMap=new ConvertingHashMap();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xmlDocument));
        Document doc=builder.parse(is);
        Element rootElement=doc.getDocumentElement();
        collectData(rootElement,rootElement.getNodeName().toLowerCase(),targetMap);
        return targetMap;
    }

    /** Collect the content of one element */
    private static void collectData(Element element, String currentPath, ConvertingHashMap targetMap)
    {
        if (element==null)
        {
            return;
        }
        // Collect all attributes of this ode
        NamedNodeMap attributes = element.getAttributes();
        if (attributes!=null)
        {
            for (int i=0; i<attributes.getLength(); i++)
            {
                Attr attribute = (Attr) attributes.item(i);
                String name = attribute.getLocalName();
                if (name==null)
                {
                    name = attribute.getNodeName();
                }
                String value = attribute.getNodeValue();
                targetMap.put(currentPath+"."+name.toLowerCase(), value);
            }
        }
        // Collect all child elements recursively
        boolean hasChildren=false;
        NodeList children=element.getChildNodes();
        if (children!=null)
        {
            int count=0;
            for (int i=0; i<children.getLength(); i++)
            {
                Node node=children.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE)
                {
                    hasChildren=true;
                    Element child = (Element)children.item(i);
                    String name=child.getLocalName();
                    if (name==null)
                    {
                        name=child.getNodeName();
                    }
                    String key=currentPath+"."+name.toLowerCase();
                    // do we have already a children with same name?
                    if (targetMap.containsKey(key))
                    {
                        // duplicate the first (existing) item
                        if (count==0)
                        {
                            // Make a copy of the first element and all of its sub elements by inserting the number 0
                            Set<String> keySet = new HashSet<>();
                            keySet.addAll(targetMap.keySet());
                            for (String k:keySet)
                            {
                                if (k.equals(key) || k.startsWith(key+"."))
                                {
                                   String existing=targetMap.get(k);
                                   targetMap.put(k.replace(key,key+"0"),existing);
                                }
                            }
                        }
                        // add new item
                        collectData(child,key+String.valueOf(++count),targetMap);
                    }
                    else
                    {
                        collectData(child,key,targetMap);
                    }
                }
            }
        }
        if (!hasChildren)
        {
            // Get the text content
            String text=element.getTextContent();
            targetMap.put(currentPath, text);
        }
        else
        {
            targetMap.put(currentPath, ""); // no text
        }
    }
}
</code>```

You may replace the ConvertingHashMap by a regular HashMap. The difference is that the ConvertingHash has methods like getInteger() and getDate().

Body:
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class comparexmls {
  public static void main(String[] argv) throws Exception {
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(is);

    NodeList list = doc.getChildNodes();
    //System.out.println(doc.getChildNodes().item(2));
    for (int i = 0; i < list.getLength(); i++) {
      if (list.item(i) instanceof Element) {
        Element root = (Element) list.item(i);
        System.out.println(root.getNodeName());

        break;
      }
    }
  }

  static String xmlRecords =
      "<Search.UDB.OUT TraceId=\"1234\">\r\n" +
      "    <Response>Success</Response>\r\n" +
      "    <Status>\r\n" +
      "        <System Name=\"X\">\r\n" +
      "            00\r\n" +
      "            <Message></Message>\r\n" +
      "        </System>\r\n" +
      "        <System Name=\"Y\">\r\n" +
      "            00\r\n" +
      "            <Message></Message>\r\n" +
      "        </System>\r\n" +
      "        <System Name=\"Z\">\r\n" +
      "            00\r\n" +
      "            <Message></Message>\r\n" +
      "        </System>\r\n" +
      "    </Status>\r\n" +
      "    <NumberFound>1</NumberFound>\r\n" +
      "    <AccountList>\r\n" +
      "        <Account>\r\n" +
      "            <AccountNumber>XXXXXXXXXXXX</AccountNumber>\r\n" +
      "            <CorpNo>XX</CorpNo>\r\n" +
      "            <Name>Chandra</Name>\r\n" +
      "            <AddressLine1>100 MAIN ST</AddressLine1>\r\n" +
      "            <AddressLine2>ANYTOWN</AddressLine2>\r\n" +
      "            <AddressLine3> GA 123456789</AddressLine3>\r\n" +
      "            <Block />\r\n" +
      "            <Reclass />\r\n" +
      "            <EmbossLine4 />\r\n" +
      "            <Phone>1234567890</Phone>\r\n" +
      "        </Account>\r\n" +
      "    </AccountList>\r\n" +
      "</Search.UDB.OUT>";

}

I am getting Search.UDB.OUT only.. How to iterate all the parent and childnodes..

Body:
Take a look at the XmlSlurper class in http://stefanfrings.de/bfUtilities/bfUtilities.zip. It's a recursive algorithm.

It reads the whole XML into a simple flat HashMap collecting all element names in the format:

Search.UDB.OUT.TraceId
Search.UDB.OUT.Response
Search.UDB.OUT.Status.System.Name
...

Source code of that class:

package de.stefanfrings.parsing;

import de.stefanfrings.container.ConvertingHashMap;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlSlurper
{

    public static ConvertingHashMap parse(String xmlDocument) throws ParserConfigurationException, SAXException, IOException
    {
        ConvertingHashMap targetMap=new ConvertingHashMap();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xmlDocument));
        Document doc=builder.parse(is);
        Element rootElement=doc.getDocumentElement();
        collectData(rootElement,rootElement.getNodeName().toLowerCase(),targetMap);
        return targetMap;
    }

    /** Collect the content of one element */
    private static void collectData(Element element, String currentPath, ConvertingHashMap targetMap)
    {
        if (element==null)
        {
            return;
        }
        // Collect all attributes of this ode
        NamedNodeMap attributes = element.getAttributes();
        if (attributes!=null)
        {
            for (int i=0; i<attributes.getLength(); i++)
            {
                Attr attribute = (Attr) attributes.item(i);
                String name = attribute.getLocalName();
                if (name==null)
                {
                    name = attribute.getNodeName();
                }
                String value = attribute.getNodeValue();
                targetMap.put(currentPath+"."+name.toLowerCase(), value);
            }
        }
        // Collect all child elements recursively
        boolean hasChildren=false;
        NodeList children=element.getChildNodes();
        if (children!=null)
        {
            int count=0;
            for (int i=0; i<children.getLength(); i++)
            {
                Node node=children.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE)
                {
                    hasChildren=true;
                    Element child = (Element)children.item(i);
                    String name=child.getLocalName();
                    if (name==null)
                    {
                        name=child.getNodeName();
                    }
                    String key=currentPath+"."+name.toLowerCase();
                    // do we have already a children with same name?
                    if (targetMap.containsKey(key))
                    {
                        // duplicate the first (existing) item
                        if (count==0)
                        {
                            // Make a copy of the first element and all of its sub elements by inserting the number 0
                            Set<String> keySet = new HashSet<>();
                            keySet.addAll(targetMap.keySet());
                            for (String k:keySet)
                            {
                                if (k.equals(key) || k.startsWith(key+"."))
                                {
                                   String existing=targetMap.get(k);
                                   targetMap.put(k.replace(key,key+"0"),existing);
                                }
                            }
                        }
                        // add new item
                        collectData(child,key+String.valueOf(++count),targetMap);
                    }
                    else
                    {
                        collectData(child,key,targetMap);
                    }
                }
            }
        }
        if (!hasChildren)
        {
            // Get the text content
            String text=element.getTextContent();
            targetMap.put(currentPath, text);
        }
        else
        {
            targetMap.put(currentPath, ""); // no text
        }
    }
}

You may replace the ConvertingHashMap by a regular HashMap. The difference is that the ConvertingHash has methods like getInteger() and getDate().


问:
Problem with large size of v-checkbox element in Vuetify
I am using Vuetify in a Vue app, and I am attempting to create a checkbox/textfield combo (as shown here in the Vuetify docs). However, when I attempt to implement it in my app, the size of the checkbox element is large, and so it creates a large space between the checkbox and the textfield:

And this is the markup that I am using::

```<code><v-container grid-list-lg>
  <v-layout row>
    <v-flex xs1>
      <v-checkbox @change="disableText($event, 'alertBackgroundColor')"></v-checkbox>
    </v-flex>
    <v-flex xs4>
      <v-text-field
        v-bind="fields.alertBackgroundColor"
        v-model="templateModel.alertBackgroundColor"
        placeholder="#4A4A4A"
        :disabled="true"
      />
      </v-flex>
      <v-flex xs1>
        <ColorPickerButton
          v-bind:field-name="'alertBackgroundColor'"
          v-bind:init-color="templateModel.alertBackgroundColor"
          v-on:update-color="getUpdatedColor">
        </ColorPickerButton>
      </v-flex>
      <!-- Alert Text Color -->
      <v-flex xs1>
        <v-checkbox @change="disableText($event, 'alertBackgroundColor')"></v-checkbox>
      </v-flex>
      <v-flex xs4>
        <v-text-field
          v-bind="fields.alertTextColor"
          v-model="templateModel.alertTextColor"
          placeholder="#4A4A4A"
          :disabled="true"
        />
      </v-flex>
      <v-flex xs1>
        <ColorPickerButton
          v-bind:field-name="'alertTextColor'"
          v-bind:init-color="templateModel.alertTextColor"
          v-on:update-color="getUpdatedColor"
        ></ColorPickerButton>
      </v-flex>
    </v-layout>
  </v-container>
</code>```

If I modify my markup to mimic the docs example, like so:

```<code><v-container grid-list-lg>
  <v-layout row>
    <v-flex xs5>
      <v-checkbox @change="disableText($event, 'alertBackgroundColor')""></v-checkbox>
      <v-text-field
        v-bind="fields.alertBackgroundColor"
        v-model="templateModel.alertBackgroundColor"
        placeholder="#4A4A4A"
        :disabled="true"
      />
    </v-flex>
    <v-flex xs1>
      <ColorPickerButton
        v-bind:field-name="'alertBackgroundColor'"
        v-bind:init-color="templateModel.alertBackgroundColor"
        v-on:update-color="getUpdatedColor">
      </ColorPickerButton>
    </v-flex>
  </v-layout>
</v-container>

</code>```

They don't even fit on one line:

How do I get these two elements to fit together side-by-side as they do in the docs example? The issue is the calculated size of the element itself, not the padding or margin, so playing with the spacing helpers doesn't make a difference.

答:
```<code><v-checkbox class="shrink mr-0 mt-0"></v-checkbox>
</code>```

Body:
I am using Vuetify in a Vue app, and I am attempting to create a checkbox/textfield combo (as shown here in the Vuetify docs). However, when I attempt to implement it in my app, the size of the checkbox element is large, and so it creates a large space between the checkbox and the textfield:

And this is the markup that I am using::

<v-container grid-list-lg>
  <v-layout row>
    <v-flex xs1>
      <v-checkbox @change="disableText($event, 'alertBackgroundColor')"></v-checkbox>
    </v-flex>
    <v-flex xs4>
      <v-text-field
        v-bind="fields.alertBackgroundColor"
        v-model="templateModel.alertBackgroundColor"
        placeholder="#4A4A4A"
        :disabled="true"
      />
      </v-flex>
      <v-flex xs1>
        <ColorPickerButton
          v-bind:field-name="'alertBackgroundColor'"
          v-bind:init-color="templateModel.alertBackgroundColor"
          v-on:update-color="getUpdatedColor">
        </ColorPickerButton>
      </v-flex>

      <v-flex xs1>
        <v-checkbox @change="disableText($event, 'alertBackgroundColor')"></v-checkbox>
      </v-flex>
      <v-flex xs4>
        <v-text-field
          v-bind="fields.alertTextColor"
          v-model="templateModel.alertTextColor"
          placeholder="#4A4A4A"
          :disabled="true"
        />
      </v-flex>
      <v-flex xs1>
        <ColorPickerButton
          v-bind:field-name="'alertTextColor'"
          v-bind:init-color="templateModel.alertTextColor"
          v-on:update-color="getUpdatedColor"
        ></ColorPickerButton>
      </v-flex>
    </v-layout>
  </v-container>

If I modify my markup to mimic the docs example, like so:

<v-container grid-list-lg>
  <v-layout row>
    <v-flex xs5>
      <v-checkbox @change="disableText($event, 'alertBackgroundColor')""></v-checkbox>
      <v-text-field
        v-bind="fields.alertBackgroundColor"
        v-model="templateModel.alertBackgroundColor"
        placeholder="#4A4A4A"
        :disabled="true"
      />
    </v-flex>
    <v-flex xs1>
      <ColorPickerButton
        v-bind:field-name="'alertBackgroundColor'"
        v-bind:init-color="templateModel.alertBackgroundColor"
        v-on:update-color="getUpdatedColor">
      </ColorPickerButton>
    </v-flex>
  </v-layout>
</v-container>

They don't even fit on one line:

How do I get these two elements to fit together side-by-side as they do in the docs example? The issue is the calculated size of the element itself, not the padding or margin, so playing with the spacing helpers doesn't make a difference.


问:
How do I grab an index from an array in a HashMap?
I've got a HashMap<Object, String[]> I just want to grab the 0 index position from the String[]. How do I do that?

Can I just do this? mMap.get(position)[0]?

答:
Here is a little demo program that does what you're asking.

```<code>import java.util.Map;
import java.util.HashMap;

public class FirstElementInHashMap {

    public static void main(String[] args) {
        Map<Object,String[]> mMap = new HashMap<Object,String[]>();
        mMap.put("myKeyA", new String[] { "myValue1", "myValue2", "myValue3" });
        mMap.put("myKeyB", new String[] { "myValue4", "myValue5", "myValue6" });
        mMap.put("myKeyC", new String[] { "myValue7", "myValue8", "myValue9" });

        Object position = "myKeyB";
        String[] strings = mMap.get(position);

        // make sure position exists in the Map and contains a non-empty array
        // so we don't throw an NullPointerException
        String firstStringInArray = null;
        if (strings != null && strings.length > 0) {
            firstStringInArray = strings[0];
        }
        System.out.println(firstStringInArray);
    }
}
</code>```

The output of the above program is:

```<code>myValue4
</code>```

Body:
Here is a little demo program that does what you're asking.

import java.util.Map;
import java.util.HashMap;

public class FirstElementInHashMap {

    public static void main(String[] args) {
        Map<Object,String[]> mMap = new HashMap<Object,String[]>();
        mMap.put("myKeyA", new String[] { "myValue1", "myValue2", "myValue3" });
        mMap.put("myKeyB", new String[] { "myValue4", "myValue5", "myValue6" });
        mMap.put("myKeyC", new String[] { "myValue7", "myValue8", "myValue9" });

        Object position = "myKeyB";
        String[] strings = mMap.get(position);

        // make sure position exists in the Map and contains a non-empty array
        // so we don't throw an NullPointerException
        String firstStringInArray = null;
        if (strings != null && strings.length > 0) {
            firstStringInArray = strings[0];
        }
        System.out.println(firstStringInArray);
    }
}

The output of the above program is:

myValue4


问:
Remove default flags on cmake
The following CMakeLists.txt

```<code> SET(CMAKE_CXX_FLAGS "/DWIN32")
 SET(CMAKE_C_FLAGS ${CMAKE_CXX_FLAGS})
 add_executable(hello hello.cpp)
</code>```

ends up running

```<code> C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\x86_amd64\CL.exe /c /nologo /W1 /WX- /O2 /Ob2 /D WIN32 /D NDEBUG /D "CMAKE_INTDIR=\"Release\"" /D _MBCS /Gm- /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Fo"hello.dir\Release\\" /Fd"C:/Users/monso/code/playground/cmakeworld/build/Release /hello.pdb" /Gd /TP /errorReport:queue ..\hello.cpp
</code>```

with flags /c /nologo /W1 /WX- /O2 /Ob2 /D WIN32 /D NDEBUG.

How can I remove them to put my own? setting CMAKE_CXX_FLAGS appends any flag I put (/w for example). While printing CMAKE_CXX_FLAGS before and after the set call does change its values.

答:
use set_target_property.

```<code>add_executable(help
               helpMe.cpp
)
get_target_property(LOVE PROPERTIES COMPILE_FLAGS)
message("Target Compiler flags are: ${MAIN_CFLAGS}")

set_target_properties(LOVE PROPERTIES COMPILE_FLAGS "")
get_target_property(LOVE PROPERTIES COMPILE_FLAGS)
message("Target Compiler flags are: ${MAIN_CFLAGS}")
</code>```

it will work.

Title: Remove default flags on cmake

Body:
The following CMakeLists.txt

 SET(CMAKE_CXX_FLAGS "/DWIN32")
 SET(CMAKE_C_FLAGS ${CMAKE_CXX_FLAGS})
 add_executable(hello hello.cpp)

ends up running

 C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\x86_amd64\CL.exe /c /nologo /W1 /WX- /O2 /Ob2 /D WIN32 /D NDEBUG /D "CMAKE_INTDIR=\"Release\"" /D _MBCS /Gm- /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Fo"hello.dir\Release\\" /Fd"C:/Users/monso/code/playground/cmakeworld/build/Release /hello.pdb" /Gd /TP /errorReport:queue ..\hello.cpp

with flags /c /nologo /W1 /WX- /O2 /Ob2 /D WIN32 /D NDEBUG.

How can I remove them to put my own? setting CMAKE_CXX_FLAGS appends any flag I put (/w for example). While printing CMAKE_CXX_FLAGS before and after the set call does change its values.

Body:
use set_target_property.

add_executable(help
               helpMe.cpp
)
get_target_property(LOVE PROPERTIES COMPILE_FLAGS)
message("Target Compiler flags are: ${MAIN_CFLAGS}")

set_target_properties(LOVE PROPERTIES COMPILE_FLAGS "")
get_target_property(LOVE PROPERTIES COMPILE_FLAGS)
message("Target Compiler flags are: ${MAIN_CFLAGS}")

it will work.


问:
How can I use multiprocessing for a function in python?
I am trying to learn multiprocessing in python but it does not work in its very early steps.
for example in the code below:

```<code>counter = 2
def train_func():
    counter1 = counter*2

p1 = mp.Process(target=train_func)
p2 = mp.Process(target=train_func)

p1.start()
p2.start()

p1.join()
p2.join()

print(counter1)
</code>```

the result is that NameError: name 'counter1' is not defined. It seems that it does not enter the function. what is wrong with that?

答:
If you have to use some simple functions the easyest way is to use a Pool. Your code will look somethig like:</p>

```<code>from multiprocessing import Pool

def f(x):
    return x*x

results = []
def saveres(res):
   results.append(res)

pool = Pool(nJobs)
print pool.map(f, range(10))

for i in range(10):
    pool.apply_async(f, (i,), callback=saveres)
</code>```

Body:
I am trying to learn multiprocessing in python but it does not work in its very early steps.
for example in the code below:

counter = 2
def train_func():
    counter1 = counter*2

p1 = mp.Process(target=train_func)
p2 = mp.Process(target=train_func)

p1.start()
p2.start()

p1.join()
p2.join()

print(counter1)

the result is that NameError: name 'counter1' is not defined. It seems that it does not enter the function. what is wrong with that?

Body:
If you have to use some simple functions the easyest way is to use a Pool. Your code will look somethig like:

from multiprocessing import Pool

def f(x):
    return x*x

results = []
def saveres(res):
   results.append(res)

pool = Pool(nJobs)
print pool.map(f, range(10))

for i in range(10):
    pool.apply_async(f, (i,), callback=saveres)


问:
Text alignment differs between canvas and HTML
I want to be able to switch between canvas and HTML view with the same result but It already fails when I'm trying to center text inside an area. How can I fix the example below so that the both labels overlap exactly indepentent from the font family and size.

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.translate(canvas.width/2, canvas.height/2);
ctx.font = '64px Tahoma';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'BlueViolet';
ctx.fillText('Hello World!', 0, 0);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas
  height="160"
  id="canvas"
  style="
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
  "
  width="480"
></canvas>
<div
  style="
    align-items: center;
    color: FireBrick;
    display: flex;
    font-family: Tahoma;
    font-size: 64px;
    height: 160px;
    justify-content: center;
    left: 0;
    line-height: 1;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 480px;
  "
>Hello World!</div></code>```

答:
Can you adjust the ctx.translate to make it work? If yes, change to the following: canvas.height/2+6

```<code>ctx.translate(canvas.width/2, canvas.height/2+6);
</code>```

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.translate(canvas.width/2, canvas.height/2+6);
ctx.font = '64px Tahoma';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'BlueViolet';
ctx.fillText('Hello World!', 0, 0);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas
  height="160"
  id="canvas"
  style="
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
  "
  width="480"
></canvas>
<div
  style="
    align-items: center;
    color: FireBrick;
    display: flex;
    font-family: Tahoma;
    font-size: 64px;
    height: 160px;
    justify-content: center;
    left: 0;
    line-height: 1;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 480px;
  "
>Hello World!</div></code>```

Body:
I want to be able to switch between canvas and HTML view with the same result but It already fails when I'm trying to center text inside an area. How can I fix the example below so that the both labels overlap exactly indepentent from the font family and size.

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.translate(canvas.width/2, canvas.height/2);
ctx.font = '64px Tahoma';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'BlueViolet';
ctx.fillText('Hello World!', 0, 0);

<canvas
  height="160"
  id="canvas"
  style="
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
  "
  width="480"
></canvas>

Hello World!

Body:
Can you adjust the ctx.translate to make it work? If yes, change to the following: canvas.height/2+6

ctx.translate(canvas.width/2, canvas.height/2+6);

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.translate(canvas.width/2, canvas.height/2+6);
ctx.font = '64px Tahoma';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'BlueViolet';
ctx.fillText('Hello World!', 0, 0);

<canvas
  height="160"
  id="canvas"
  style="
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
  "
  width="480"
></canvas>
<div
  style="
    align-items: center;
    color: FireBrick;
    display: flex;
    font-family: Tahoma;
    font-size: 64px;
    height: 160px;
    justify-content: center;
    left: 0;
    line-height: 1;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 480px;
  "
>Hello World!</div>


问:
Access variable of a class inside other classes Flutter
I have a class which has variables like this:

```<code>class MyDragTarget extends StatefulWidget {
  final String assetImage;
  final String name;

  MyDragTarget(this.name, this.assetImage);
}
</code>```

EDIT: Sorry for wrong code below. I knew how to use widget.name to get name of the parent. But how can i get name of other class.
Should i use InheritedWidget? To use InheritedWidget must i learn Provider?

I want to access the name and assetImage of MyDragTarget in another class such as:

```<code>class Another extends StatefulWidget {
  print(MyDragTarget.name);
}
</code>```

答:
you can get using widget </p>

```<code>    widget.assetImage
    wiget.name
    print('${wiget.name}');
</code>```

Body:
I have a class which has variables like this:

class MyDragTarget extends StatefulWidget {
  final String assetImage;
  final String name;

  MyDragTarget(this.name, this.assetImage);
}

EDIT: Sorry for wrong code below. I knew how to use widget.name to get name of the parent. But how can i get name of other class.
Should i use InheritedWidget? To use InheritedWidget must i learn Provider?

I want to access the name and assetImage of MyDragTarget in another class such as:

class Another extends StatefulWidget {
  print(MyDragTarget.name);
}

Body:
you can get using widget

    widget.assetImage
    wiget.name
    print('${wiget.name}');


问:
JSON body response find index for value
Given this JSON response:

```<code>[{"brukergruppeSperret":false,"virksomhetsnavn":"HELFO","brukerGruppe":"Brukerstøtte"},{"brukergruppeSperret":false,"virksomhetsnavn":"Klubbgaten Legesenter","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Sjøsiden Legesenter","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Athene legekontor Helsedirektoratet","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Xeon Legekontor","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Østmarka legekontor","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Hultemyra shamansamling","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"AMIS Testsenter","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"GLØSHAUGEN LEGESENTER DA","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Helse Møre og Romsdal HF","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"St. Olavs hospital HF","brukerGruppe":"Saksbehandler"},{"brukergruppeSperret":false,"virksomhetsnavn":"HELSEDIREKTORATET","brukerGruppe":"Saksbehandler"},{"brukergruppeSperret":false,"virksomhetsnavn":"Østmarka legekontor","brukerGruppe":"Saksbehandler"}]
</code>```

I want to obtain the first index in the JSON response that has the value "Lege" as "brukerGruppe".
In the above example this corresponds to index 6.

How can I in session in Gatling do a check that implements this?
I guess the function "find" could be used somewhat like this:

```<code>.check(jsonPath("$.brukerGruppe").find("Lege").indexvalue ??
</code>```

Thanks

答:
JsonPath support condition and you can find like this:

```<code>jsonPath("$.[6][?(@.brukerGruppe=='Lege')]"
</code>```

It's returned :

```<code>[
  {
    "brukergruppeSperret": false,
    "virksomhetsnavn": "Hultemyra shamansamling",
    "brukerGruppe": "Lege"
  }
]
</code>```

You can also get all items where brukerGruppe equals Lege

```<code>$.[?(@.brukerGruppe=='Lege')]
</code>```

Title: JSON body response find index for value

Body:
Given this JSON response:

[{"brukergruppeSperret":false,"virksomhetsnavn":"HELFO","brukerGruppe":"Brukerstøtte"},{"brukergruppeSperret":false,"virksomhetsnavn":"Klubbgaten Legesenter","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Sjøsiden Legesenter","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Athene legekontor Helsedirektoratet","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Xeon Legekontor","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Østmarka legekontor","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Hultemyra shamansamling","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"AMIS Testsenter","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"GLØSHAUGEN LEGESENTER DA","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"Helse Møre og Romsdal HF","brukerGruppe":"Lege"},{"brukergruppeSperret":false,"virksomhetsnavn":"St. Olavs hospital HF","brukerGruppe":"Saksbehandler"},{"brukergruppeSperret":false,"virksomhetsnavn":"HELSEDIREKTORATET","brukerGruppe":"Saksbehandler"},{"brukergruppeSperret":false,"virksomhetsnavn":"Østmarka legekontor","brukerGruppe":"Saksbehandler"}]

I want to obtain the first index in the JSON response that has the value "Lege" as "brukerGruppe".
In the above example this corresponds to index 6.

How can I in session in Gatling do a check that implements this?
I guess the function "find" could be used somewhat like this:

.check(jsonPath("$.brukerGruppe").find("Lege").indexvalue ??

Thanks

Body:
JsonPath support condition and you can find like this:

jsonPath("$.[6][?(@.brukerGruppe=='Lege')]"

It's returned :

[
  {
    "brukergruppeSperret": false,
    "virksomhetsnavn": "Hultemyra shamansamling",
    "brukerGruppe": "Lege"
  }
]

You can also get all items where brukerGruppe equals Lege

$.[?(@.brukerGruppe=='Lege')]


问:
How to list/delete Cloudformation stack from a Lambda function
In my application, I need to create resources from a given Cloudformation template.

There will be many stacks created from the same CloudFormation template.
And a schedule job will be triggered on a daily basis to remove the stacks created more than 1 day.

I plan to do this with a Lambda function (best to be in Python)
From Setup Lambda function to run a CloudFormation stack I found a way to create stack from Lambda.

But may I know how to list/delete stacks from Lambda function, too?

Thanks.
Jeff

答:
But may I know how to list/delete stacks from Lambda function, too?

In boto3 you can use the following functions:

list_stacks: Returns the summary information for stacks whose status matches the specified StackStatusFilte

delete_stack: Deletes a specified stack. Once the call completes successfully, stack deletion starts.


问:
Arbitrary precision decimals in C#?
Is there an arbitrary-precision decimal class available for C#? I've seen a couple of arbitrary precision integer classes, but that's not quite the same thing.

答:
You can use J# library's java.math.BigDecimal class if you have it installed. Just add a reference to vjslib.

```<code>/me remembers one of the betas in which we had System.Numeric.BigDecimal, sigh
</code>```

OwnerDisplayName: sassafrass

ContentLicense: CC BY-SA 2.5

Title: Arbitrary precision decimals in C#?

Body:
You can use J# library's java.math.BigDecimal class if you have it installed. Just add a reference to vjslib.

/me remembers one of the betas in which we had System.Numeric.BigDecimal, sigh

OwnerDisplayName: Mehrdad Afshari


问:
IE8/Compat View Bug - All images stack on each other at top of Div. Need Help
A very strange behavior is occuring on the website I'm working on in a animal display list.

The animals are laid out in a grid format.  When in IE8 and with compat mode turned on, the animals pictures all shoot to the top of the screen and stack under each other.

This is completely perplexing to me.  I need to call upon the talent of this community to help me fix this bug.

Example Page found here - http://www.petango.com/Forms/AnimalSearchResults.aspx?z=L2R%205W3&d=2147483647&sh=0&s=1&b=650&g=All&size=All&c=All&a=All&dec=All&p=False&sid=0&zs=True&ht=False

In IE8, it looks okay, when compat mode is turned on, the images shoot to the top of the page.  I can only assume this behavior is found in IE7.

I'm at a loss at where to start troubleshooting this.

UPDATE 1 - 12:16PM

I tried a test where I took the animal display code and removed the unordered list and replaced it with a table.

The Div within the LI element doesn't seem to be the culprit?

答:
You can't have
 inside
. I would also get your page to have fewer errors when you validate it at validator.w3.org.

Body: You can't have <div> inside <li>. I would also get your page to have fewer errors when you validate it at validator.w3.org.


问:
How to unlock jenkins on windows 10
I installed jenkins on my window 10 machine by using the msi I downloaded. It installed fine and has now launched the browser prompting me to unlock jenkins with the initialadminpassword. I can't find this file anywhere. I looked in the install directory C:\Program Files (x86)\Jenkins and I have checked the log files and no password was written to it. I even did a search on my whole C: for initialadminpassword and nothing came up. I do have a file called secret.key in my Jenkins install directory but the key in this file isn't working. Any ideas on how I can get around this would be very helpful

Thanks

答:
Jenkins do this because it want to ensure Jenkins is securely set up by the administrator ,
So you cannot open this file direct you must going step by step to the path it given to you .
C:\WINDOWS\system32\config\systemprofile.jenkins\secrets\initialAdminPassword

Go to : C:\WINDOWS\ .

Go to : system32

.......

.......

Continue tracking path

And you will found it .

Title: How to unlock jenkins on windows 10


问:
Android Picasso "fit().centerCrop()" doesn't load image
I want to display image (URL) into my imageview as max width and variable height    according to width size, when I use this code part:

```<code>imageView = (ImageView) convertView.findViewById(R.id.imageView);
Picasso.with(context).load(product.getImage()).into(imageView);
</code>```

I can display my image into imageview. I also tried use resize().centerCrop() methods and it worked successfully.

But however, when I use

Picasso.with(context).load(product.getImage()).fit().centerCrop().into(imageView);

or

Picasso.with(context).load(product.getImage()).fit().centerInside().into(imageView);

my imageview display nothing. I don't understand why. Maybe the problem my list design and imageview. Here is my list_content_item.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:weightSum="1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.80"
        app:srcCompat="@mipmap/ic_launcher" />

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.2"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_weight="0.3"
            android:layout_height="match_parent" />
        <TextView
            android:id="@+id/tv_stats"
            android:layout_weight="0.7"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"/>

    </LinearLayout>

</LinearLayout>
</code>```

I tried set wrap_content and match_parent  both of ImageView's width and height and it didn't worked, too. Where am I missing? Thanks in advance.

答:
public Builder resize(int targetWidth, int targetHeight)

Resize the image to the specified size in pixels.
  Use 0 as desired dimension to resize keeping aspect ratio.

use this.

```<code>fun Fragment.getDeviceWidth(): Int {
    val displayMetrics = DisplayMetrics()
    requireActivity().windowManager.defaultDisplay.getRealMetrics(displayMetrics)

    return displayMetrics.widthPixels
}

.resize(getDeviceWidth(), 0)
</code>```

Body:
I want to display image (URL) into my imageview as max width and variable height    according to width size, when I use this code part:

imageView = (ImageView) convertView.findViewById(R.id.imageView);
Picasso.with(context).load(product.getImage()).into(imageView);

I can display my image into imageview. I also tried use resize().centerCrop() methods and it worked successfully.

But however, when I use

Picasso.with(context).load(product.getImage()).fit().centerCrop().into(imageView);

or

Picasso.with(context).load(product.getImage()).fit().centerInside().into(imageView);

my imageview display nothing. I don't understand why. Maybe the problem my list design and imageview. Here is my list_content_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:weightSum="1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.80"
        app:srcCompat="@mipmap/ic_launcher" />

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="1"
        android:layout_weight="0.2"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_weight="0.3"
            android:layout_height="match_parent" />
        <TextView
            android:id="@+id/tv_stats"
            android:layout_weight="0.7"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"/>

    </LinearLayout>

</LinearLayout>

I tried set wrap_content and match_parent  both of ImageView's width and height and it didn't worked, too. Where am I missing? Thanks in advance.

Body:
public Builder resize(int targetWidth, int targetHeight)

Resize the image to the specified size in pixels.
  Use 0 as desired dimension to resize keeping aspect ratio.

use this.

fun Fragment.getDeviceWidth(): Int {
    val displayMetrics = DisplayMetrics()
    requireActivity().windowManager.defaultDisplay.getRealMetrics(displayMetrics)

    return displayMetrics.widthPixels
}

.resize(getDeviceWidth(), 0)


问:
How do I check when a UITextField changes?
I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:

```<code>  func textFieldDidBeginEditing(textField: UITextField) {
        if self.status.text == "" && self.username.text == "" {
            self.topRightButton.enabled = false
        } else {
            self.topRightButton.enabled = true
        }
    }
</code>```

Which kind of works, but the topRightButton is enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?

答:
In case it is not possible to bind the addTarget to your UITextField, I advise you to bind one of them as suggested above, and insert the code for execution at the end of the shouldChangeCharactersIn method.

```<code>nameTextField.addTarget(self, action: #selector(RegistrationViewController.textFieldDidChange(_:)), for: .editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {
    if phoneNumberTextField.text!.count == 17 && nameTextField.text!.count > 0 {
        continueButtonOutlet.backgroundColor = UIColor(.green)
    } else {
        continueButtonOutlet.backgroundColor = .systemGray
    }
}
</code>```

And in call in shouldChangeCharactersIn func.

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let text = textField.text else {
        return true
    }
    let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String

    if phoneNumberTextField == textField {
        textField.text = lastText.format("+7(NNN)-NNN-NN-NN", oldString: text)
        textFieldDidChange(phoneNumberTextField)
        return false
    }
    return true
}
</code>```

Body:
I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:

  func textFieldDidBeginEditing(textField: UITextField) {
        if self.status.text == "" && self.username.text == "" {
            self.topRightButton.enabled = false
        } else {
            self.topRightButton.enabled = true
        }
    }

Which kind of works, but the topRightButton is enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?

Body:
In case it is not possible to bind the addTarget to your UITextField, I advise you to bind one of them as suggested above, and insert the code for execution at the end of the shouldChangeCharactersIn method.

nameTextField.addTarget(self, action: #selector(RegistrationViewController.textFieldDidChange(_:)), for: .editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {
    if phoneNumberTextField.text!.count == 17 && nameTextField.text!.count > 0 {
        continueButtonOutlet.backgroundColor = UIColor(.green)
    } else {
        continueButtonOutlet.backgroundColor = .systemGray
    }
}

And in call in shouldChangeCharactersIn func.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let text = textField.text else {
        return true
    }
    let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String

    if phoneNumberTextField == textField {
        textField.text = lastText.format("+7(NNN)-NNN-NN-NN", oldString: text)
        textFieldDidChange(phoneNumberTextField)
        return false
    }
    return true
}


答: You can use widget.name. For example, if you are trying to access assetImage you can use print('${widget.assetImage}'); Just a side note, this is to access the variables in your StatefulWidget. You can't do it for any class.

Title: Access variable of a class inside other classes Flutter