问:
Xamarin Left margin in iPad
I face strange behavior when I am populate list view all cells have left margin

tested Device iPad 9 in simulator , iPad 12 in simulator

here is screen of my issue
and my second list

here is my Xaml

```<code> <customRender:ExtList x:Name="listViewFlights" BackgroundColor ="{StaticResource white_color}"
                      ItemTapped="ListView_OnItemTapped" SeparatorColor="Gray" SeparatorVisibility="Default"
                      MinimumHeightRequest="40" IsPullToRefreshEnabled="True" Refreshing="ListViewFlights_Refreshing"  >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <customRender:CustomViewCell >
                            <StackLayout  Spacing="0" BackgroundColor="Aqua">

                                <Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"   x:Name="gridCell"  RowSpacing="0" ColumnSpacing="0">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="3.25*"></ColumnDefinition>
                                        <ColumnDefinition Width="4*"></ColumnDefinition>
                                        <ColumnDefinition Width="4.75*"></ColumnDefinition>
                                        <ColumnDefinition Width="Auto"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <Label Grid.Row="0" Grid.Column="0" Text="{Binding FirstListColumn}" Style="{StaticResource GridItemStyleLabelStart_os}" Margin="10,0,0,0"/>
                                    <StackLayout Grid.Row="0" Grid.Column="1" Padding="{Binding FlightListColumn2Padding}" VerticalOptions="Center"  >
                                        <Label Text="{Binding Dep_Dest}" Style="{StaticResource GridItemStyleLabel_os}" HorizontalTextAlignment="Start"></Label>
                                    </StackLayout>
                                    <Grid Grid.Row="0" Grid.Column="2"  HorizontalOptions="FillAndExpand"  RowSpacing="0" >
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="*"></RowDefinition>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="1.5*"></ColumnDefinition>
                                            <ColumnDefinition Width="3*"></ColumnDefinition>
                                            <ColumnDefinition Width="5.5*"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <Frame Grid.Row="0" Grid.Column="0"  IsVisible="{Binding IsRecalculated}"  Padding="0" Margin="0,7" OutlineColor="#5C768E" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" HasShadow="False" BackgroundColor="Transparent">
                                        <Label  Text="R" Style="{StaticResource GridItemStyleLabelStart}"  HorizontalOptions="CenterAndExpand"  IsVisible ="{Binding IsRecalculated}"  />
                                        </Frame>
                                        <Label Grid.Row="0" Grid.Column="1" Text="{Binding ATCCtot }" Style="{StaticResource GridItemStyleLabelStart}" TextColor="Red" HorizontalOptions="Start" />
                                        <Label Grid.Row="0" Grid.Column="2" Text="{Binding PreparedStd}" Style="{StaticResource GridItemStyleLabelEnd_os}" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End"  />
                                    </Grid>
                                    <BoxView x:Name="SelectedBox" Grid.Row="0" Grid.Column="3"  Opacity="{Binding IsSelected}" BackgroundColor="{StaticResource sub_header}" >
                                        <BoxView.WidthRequest>
                                            <OnIdiom x:TypeArguments="x:Double" Tablet="5"  />
                                        </BoxView.WidthRequest>
                                    </BoxView>

                                </Grid>
                            </StackLayout>
                        </customRender:CustomViewCell>

                    </DataTemplate>
                </ListView.ItemTemplate>
            </customRender:ExtList>
</code>```

my tries to fix the issue :

after long search I find soluation in xamarin site , is to make custom render to my list view but it docent work

```<code> public class CustomListViewRenderer : ListViewRenderer
    {
        protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.ListView> e)
        {
            base.OnElementChanged (e);
            if (e.NewElement != null) {
                var listView = Control as UITableView;
                listView.CellLayoutMarginsFollowReadableWidth = false;
            }
        }
    }
</code>```

reference https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/viewcell/

答: This is a known bug that is in the process of being fixed.</p>

Title: Xamarin Left margin in iPad

Body:
I face strange behavior when I am populate list view all cells have left margin

tested Device iPad 9 in simulator , iPad 12 in simulator

here is screen of my issue
and my second list

here is my Xaml

 <customRender:ExtList x:Name="listViewFlights" BackgroundColor ="{StaticResource white_color}"
                      ItemTapped="ListView_OnItemTapped" SeparatorColor="Gray" SeparatorVisibility="Default"
                      MinimumHeightRequest="40" IsPullToRefreshEnabled="True" Refreshing="ListViewFlights_Refreshing"  >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <customRender:CustomViewCell >
                            <StackLayout  Spacing="0" BackgroundColor="Aqua">

                                <Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"   x:Name="gridCell"  RowSpacing="0" ColumnSpacing="0">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="3.25*"></ColumnDefinition>
                                        <ColumnDefinition Width="4*"></ColumnDefinition>
                                        <ColumnDefinition Width="4.75*"></ColumnDefinition>
                                        <ColumnDefinition Width="Auto"></ColumnDefinition>
                                    </Grid.ColumnDefinitions>

                                    <StackLayout Grid.Row="0" Grid.Column="1" Padding="{Binding FlightListColumn2Padding}" VerticalOptions="Center"  >

                                    </StackLayout>
                                    <Grid Grid.Row="0" Grid.Column="2"  HorizontalOptions="FillAndExpand"  RowSpacing="0" >
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="*"></RowDefinition>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="1.5*"></ColumnDefinition>
                                            <ColumnDefinition Width="3*"></ColumnDefinition>
                                            <ColumnDefinition Width="5.5*"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <Frame Grid.Row="0" Grid.Column="0"  IsVisible="{Binding IsRecalculated}"  Padding="0" Margin="0,7" OutlineColor="#5C768E" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" HasShadow="False" BackgroundColor="Transparent">

                                        </Frame>

                                    </Grid>
                                    <BoxView x:Name="SelectedBox" Grid.Row="0" Grid.Column="3"  Opacity="{Binding IsSelected}" BackgroundColor="{StaticResource sub_header}" >
                                        <BoxView.WidthRequest>
                                            <OnIdiom x:TypeArguments="x:Double" Tablet="5"  />
                                        </BoxView.WidthRequest>
                                    </BoxView>

                                </Grid>
                            </StackLayout>
                        </customRender:CustomViewCell>

                    </DataTemplate>
                </ListView.ItemTemplate>
            </customRender:ExtList>

my tries to fix the issue :

after long search I find soluation in xamarin site , is to make custom render to my list view but it docent work

 public class CustomListViewRenderer : ListViewRenderer
    {
        protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.ListView> e)
        {
            base.OnElementChanged (e);
            if (e.NewElement != null) {
                var listView = Control as UITableView;
                listView.CellLayoutMarginsFollowReadableWidth = false;
            }
        }
    }

reference https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/viewcell/


来源: stackexchange

问:
I can't see Android SDK javadoc in Eclipse
I am developing for Android in Eclipse Helios. I'm using the latest ADT plugin 8.0.1. Previously, I could see method javadoc description, when moving my mouse over a method name and waiting for about a second. Now it stopped working for some reason.</p>

答:
Eclipse Helios is known to have slow code completion with the Android SDK. Perhaps your problems are related to that? If you have problems with the latest Eclipse version, you should probably try using Eclipse 3.5 http://www.eclipse.org/galileo/, which doesn't have these issues.

This could be due to some sort of temporary error in Eclipse.

You can check Window -> Show View (-> General ) -> Error Log to check whether there has been an Eclipse exception which has caused the Eclipse designer to bail out.

Have you tried to restart Eclipse? If it still doesn't work you can try to restart eclipse with

c:\path\to\eclipse.exe -clean

You can also check the Windows-Preferences and Project->Properties if you can find anything related to Javadoc there and try to reset the java perspective using Window -> Reset perspective.

ContentLicense: CC BY-SA 2.5


问:
iterate through a list and get user response to each item using tkinter GUI
I am being particularly obtuse. I am iterating through a list of technical italian words and wanting to insert a translation using a tkinter interface. There is no problem doing this without the GUI: My problem is that I cannot figure out how to do an iteration, load a word into a ttk.Label and wait for a user entry in a ttk.Entry field. I have searched and found explanations, but I am at a loss how to apply the suggestions. This is my code using a trivial list of words:

```<code>from tkinter import ttk
import tkinter as tk

def formd():

    list_of_terms = ['aardvark', 'ant','zombie', 'cat', 'dog', 'buffalo','eagle', 'owl','caterpiller', 'zebra',  'orchid','arum lily' ]
    discard_list = []
    temp_dict={}
    list_of_terms.sort()

    for item in list_of_terms:
        listKey.set(item)

    # need to wait and get user input
        translation =dictValue.get()
        temp_dict[item]=translation
        discard_list.append(item)
    # check if it has worked
    for key, value in temp_dict.items():
        print(key, value)
# GUI for dict from list
LARGE_FONT= ("Comic sans MS", 12)

root = tk.Tk()
root.title('Nautical Term Bilingual Dictionary')
ttk.Style().configure("mybtn.TButton", font = ('Comic sans MS','12'), padding = 1,  foreground = 'DodgerBlue4')
ttk.Style().configure('red.TButton', foreground='red', padding=6, font=('Comic sans MS',' 10'))
ttk.Style().configure('action.TLabelframe', foreground = 'dodger blue3')
#.......contents frames.....................
nb = ttk.Notebook(root)
page5 = ttk.Frame(nb)
# declare variables
listKey= tk.StringVar()
dictValue = tk.StringVar()
# widgets
keyLabel =ttk.Label( page5, text = "key from list", font=LARGE_FONT).grid(row=3, column = 0)
Keyfromlist =ttk.Label(page5, width = 10, textvariable = listKey).grid(row = 3, column = 1)

valueLabel =ttk.Label( page5, text = "enter translation", font=LARGE_FONT).grid(row=3, column = 2)
listValue =ttk.Entry(page5, textvariable =dictValue, width = 15).grid(row = 3, column = 3)
#listValue.delete(0,'end')
#listValue.focus_set()

# add buttons
b1 = ttk.Button(page5, text="add to dictionary",style = "mybtn.TButton", command = formd)
b1.grid(row = 5, column = 0)
b5 = ttk.Button(page5, text="clear entry", style ="mybtn.TButton")
b5.grid(row = 5, column = 2)
nb.add(page5, text='From List')

nb.pack(expand=1, fill="both")

for child in root.winfo_children():
    child.grid_configure(padx =5, pady=5)

if __name__ == "__main__":
    root.mainloop()
</code>```

I wonder whether someone could take the time to suggest a solution, please. How to stop a while loop to get input from user using Tkinter? was the one suggestion that I cannot figure how to use in my example

答:
tkinter doesn't "play nice" with while loops.

Fortunately for you, you don't need to use one.

You can do something like the below:

```<code>from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        self.list = ['aardvark', 'ant','zombie', 'cat', 'dog', 'buffalo','eagle', 'owl','caterpiller', 'zebra',  'orchid','arum lily' ]
        self.text = Label(self.root, text="aardvark")
        self.entry = Entry(self.root)
        self.button = Button(self.root, text="Ok", command=self.command)
        self.text.pack()
        self.entry.pack()
        self.button.pack()
    def command(self):
        print(self.text.cget("text")+" - "+self.entry.get())
        try:
            self.text.configure(text = self.list[self.list.index(self.text.cget("text"))+1])
        except IndexError:
            self.entry.destroy()
            self.button.destroy()
            self.text.configure(text = "You have completed the test")

root = Tk()
App(root)
root.mainloop()
</code>```

This essentially uses the Button widget to iterate to the next text and get the next input.

ContentLicense: CC BY-SA 3.0

Body:
I am being particularly obtuse. I am iterating through a list of technical italian words and wanting to insert a translation using a tkinter interface. There is no problem doing this without the GUI: My problem is that I cannot figure out how to do an iteration, load a word into a ttk.Label and wait for a user entry in a ttk.Entry field. I have searched and found explanations, but I am at a loss how to apply the suggestions. This is my code using a trivial list of words:

from tkinter import ttk
import tkinter as tk

def formd():

    list_of_terms = ['aardvark', 'ant','zombie', 'cat', 'dog', 'buffalo','eagle', 'owl','caterpiller', 'zebra',  'orchid','arum lily' ]
    discard_list = []
    temp_dict={}
    list_of_terms.sort()

    for item in list_of_terms:
        listKey.set(item)

    # need to wait and get user input
        translation =dictValue.get()
        temp_dict[item]=translation
        discard_list.append(item)
    # check if it has worked
    for key, value in temp_dict.items():
        print(key, value)
# GUI for dict from list
LARGE_FONT= ("Comic sans MS", 12)

root = tk.Tk()
root.title('Nautical Term Bilingual Dictionary')
ttk.Style().configure("mybtn.TButton", font = ('Comic sans MS','12'), padding = 1,  foreground = 'DodgerBlue4')
ttk.Style().configure('red.TButton', foreground='red', padding=6, font=('Comic sans MS',' 10'))
ttk.Style().configure('action.TLabelframe', foreground = 'dodger blue3')
#.......contents frames.....................
nb = ttk.Notebook(root)
page5 = ttk.Frame(nb)
# declare variables
listKey= tk.StringVar()
dictValue = tk.StringVar()
# widgets
keyLabel =ttk.Label( page5, text = "key from list", font=LARGE_FONT).grid(row=3, column = 0)
Keyfromlist =ttk.Label(page5, width = 10, textvariable = listKey).grid(row = 3, column = 1)

valueLabel =ttk.Label( page5, text = "enter translation", font=LARGE_FONT).grid(row=3, column = 2)
listValue =ttk.Entry(page5, textvariable =dictValue, width = 15).grid(row = 3, column = 3)
#listValue.delete(0,'end')
#listValue.focus_set()

# add buttons
b1 = ttk.Button(page5, text="add to dictionary",style = "mybtn.TButton", command = formd)
b1.grid(row = 5, column = 0)
b5 = ttk.Button(page5, text="clear entry", style ="mybtn.TButton")
b5.grid(row = 5, column = 2)
nb.add(page5, text='From List')

nb.pack(expand=1, fill="both")

for child in root.winfo_children():
    child.grid_configure(padx =5, pady=5)

if __name__ == "__main__":
    root.mainloop()

I wonder whether someone could take the time to suggest a solution, please. How to stop a while loop to get input from user using Tkinter? was the one suggestion that I cannot figure how to use in my example

Body:
tkinter doesn't "play nice" with while loops.

Fortunately for you, you don't need to use one.

You can do something like the below:

from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        self.list = ['aardvark', 'ant','zombie', 'cat', 'dog', 'buffalo','eagle', 'owl','caterpiller', 'zebra',  'orchid','arum lily' ]
        self.text = Label(self.root, text="aardvark")
        self.entry = Entry(self.root)
        self.button = Button(self.root, text="Ok", command=self.command)
        self.text.pack()
        self.entry.pack()
        self.button.pack()
    def command(self):
        print(self.text.cget("text")+" - "+self.entry.get())
        try:
            self.text.configure(text = self.list[self.list.index(self.text.cget("text"))+1])
        except IndexError:
            self.entry.destroy()
            self.button.destroy()
            self.text.configure(text = "You have completed the test")

root = Tk()
App(root)
root.mainloop()

This essentially uses the Button widget to iterate to the next text and get the next input.


问:
What is a 'type assertion' between the function name and parameters, on calling a function?
In this Typescript React starter guide it gives:

```<code>import { createStore } from 'redux';

interface StoreState {
    languageName: string;
    enthusiasmLevel: number;
}

function enthusiasm(state: StoreState, action: EnthusiasmAction): StoreState {
    // returns a StoreState
}
const store = createStore<StoreState>(enthusiasm, {
     enthusiasmLevel: 1,
     languageName: 'TypeScript',
});
</code>```

What is this  assertion doing there?

I couldn't find where this syntax is defined, and can't "deduce" what it means.

答:
This isn't a type assertion, it is a type argument, which is used for generic types.

Type Assertions

Firstly, here's a type assertion...

```<code>const x = <HTMLAnchorElement>document.getElementById('myLink');
</code>```

The type assertion appears before the expression and says "actually this is an anchor, not just a general element".

Generics

Now let's look at generics...

This function takes a string and returns it.

```<code>function example(input: string): string {
    return input;
}
</code>```

Now we can add another function that takes a number and returns it, but actually our function doesn't care about the type of the parameter, or the return type - as long as they are the same...

So instead of repeating the function for each type, we can say, "the type will be T, where T will be defined later on".

```<code>function example<T>(input: T): T {
    return input;
}
</code>```

Explicit Type Argument

When you use something generic (it can be a class, or a function, or a method), you can supply the type argument explicitly, like this:

```<code>function example<T>(input: T): T {
    return input;
}

const str = example<string>('str');

const num = example<number>(3);
</code>```

They look a bit like type assertions, but they appear in a different location.

Implicit Type Argument

In many cases, you don't need to explicitly pass the type argument, as the compiler can work it out for you.

```<code>function example<T>(input: T): T {
    return input;
}

const str = example('str');

const num = example(3);
</code>```

Body:
In this Typescript React starter guide it gives:

import { createStore } from 'redux';

interface StoreState {
    languageName: string;
    enthusiasmLevel: number;
}

function enthusiasm(state: StoreState, action: EnthusiasmAction): StoreState {
    // returns a StoreState
}
const store = createStore<StoreState>(enthusiasm, {
     enthusiasmLevel: 1,
     languageName: 'TypeScript',
});

What is this  assertion doing there?

I couldn't find where this syntax is defined, and can't "deduce" what it means.

Body:
This isn't a type assertion, it is a type argument, which is used for generic types.

Type Assertions

Firstly, here's a type assertion...

const x = <HTMLAnchorElement>document.getElementById('myLink');

The type assertion appears before the expression and says "actually this is an anchor, not just a general element".

Generics

Now let's look at generics...

This function takes a string and returns it.

function example(input: string): string {
    return input;
}

Now we can add another function that takes a number and returns it, but actually our function doesn't care about the type of the parameter, or the return type - as long as they are the same...

So instead of repeating the function for each type, we can say, "the type will be T, where T will be defined later on".

function example<T>(input: T): T {
    return input;
}

Explicit Type Argument

When you use something generic (it can be a class, or a function, or a method), you can supply the type argument explicitly, like this:

function example<T>(input: T): T {
    return input;
}

const str = example<string>('str');

const num = example<number>(3);

They look a bit like type assertions, but they appear in a different location.

Implicit Type Argument

In many cases, you don't need to explicitly pass the type argument, as the compiler can work it out for you.

function example<T>(input: T): T {
    return input;
}

const str = example('str');

const num = example(3);


问:
Mac $PATH executables not available in Terminal
I'm new to Mac and am trying to add things to my $PATH so I can call things like "mysql" and "mongod" anywhere on the terminal.  Here's my current .bash_profile.  What am I doing wrong?  Running OSX Yosemite 10.10.5</p>

```<code># Additional binary folders
export PATH=$PATH:/Users/iqm377/bin

# MongoDB
export PATH=$PATH:/Users/iqm377/mongodb-osx-x86_64-3.0.5/bin

# MySQL
export PATH=$PATH:/Users/iqm377/XAMPP/bin
</code>```

答:
You should add quotes in you $PATH variable just like this</p>

```<code>export PATH="~/mongodb/bin:$PATH"
</code>```

Body:
I'm new to Mac and am trying to add things to my $PATH so I can call things like "mysql" and "mongod" anywhere on the terminal.  Here's my current .bash_profile.  What am I doing wrong?  Running OSX Yosemite 10.10.5

# Additional binary folders
export PATH=$PATH:/Users/iqm377/bin

# MongoDB
export PATH=$PATH:/Users/iqm377/mongodb-osx-x86_64-3.0.5/bin

# MySQL
export PATH=$PATH:/Users/iqm377/XAMPP/bin

Body:
You should add quotes in you $PATH variable just like this

export PATH="~/mongodb/bin:$PATH"


问:
How to do an ODBC connection to OmniTracker?
I am set to do some statistics in Excel based on ticket and timeregistration data from OmniTracker (ITSM)

Does anybody know how to do an odbc connection to OmniTracker? I have googled it and found ODBC items - but not related to OmniTracker.

答:
There is no direct ODBC connection to OmniTracker itself. You can connect to SQL database OT uses.
Start "OMNITRACKER Service Control Panel" (use Windows search) on your Omnitracker application server to find "ODBC connection string" of your SQL server.
Omnitracker folders can be found in set of DB tables like "[dbo].[UserFields580]".
Every child folder inherits parent fields. So you have to "join" several DB tables [UserFieldsXXX] to get full set of fields.</p>


问:
Cannot get theme to work on catalog view
I have theme i am trying to get work on a remote server that works fine on my local copy.  This is for magento 1.4.1.1.  On the working local copy I have 'theme144' within the 'base' package, there are 3 store views; .  In the admin there are 3 design change(System>Design), one for each store view.  These are the only changes i see in the admin pertaining to design.  When testing the site on the remote server, the correct templates are being used for everything except the catalog view. Magento reverts to the 'default' theme inside the 'base' package. All the images, and it seems like the templates, are all using the other theme.

I've tried specifying the theme explicitly in System>Configuration>Design for the Skin, Layout, and Templates, even though on the working local copy these are not set.  This got magento to find the images and style sheets, but it was still using 'default' for the templates.

At this point i don't where else to look to give me hints as to why this is happening.  I eliminated all the differences between the local and remote site, both in the admin and the template file structure.

edit: This issue also extends to the product detail view

答:
I guess this is a reported bug in Magento.  Apparently if you apply the design change to a store that is not the 'All store views'(like the local machine view), then the design changes wont propagate properly.  If this occurs, the you can get Magento apply the updated design by selecting the template in the 'Custom Design' tab on the root category(make sure to apply changes to child elements as well). I reverted these changes and the theme finally stuck.

http://www.magentocommerce.com/boards/viewthread/35761/


问:
How do I configure the snapshot_users option, in packer, using a user variable
I have a packer .json file, that governs the build/provisioning of several different AMI builds.  The different between each AMI is configured by passing a different base-config.json variable set to packer, depending on what's changing (for example, I have a base_config-us-west-1.json and base_config-us-east-2.json, and select one, to populate the vpc_id, subnet_id & security_group_id fields).

Now I need to build an AMI that uses a kms_key_id for an external account_id, and grant access to the newly created snapshot, to the account_id that owns the key.

If the .json was just for this new AMI, I could easily add "snapshot_users" : [ "{{user external_account_id}}" ] to the json and be done with it.  However, even having "snapshot_users" : [ "" ] in the .json causes the bake to fail with error "Cannot share snapshot encrypted with default KMS key" problem, if the default kms_key_id is used (as you get with "kms_key_id": "").

Is there any way that I can only insert the snapshot_users option to the builders section, by some criteria specified to the packer command, or am I stuck having to script using ec2-api-tools to change the permissions on the build ami, after the bake has finished (having multiple complete .json files, to build different AMIs is not an option).

Perhaps, this is also a packer bug, as packer should recognise if the snapsho_users array is either empty, or contains only empty strings, it can be ignored.

答:
Packer splits variables on , into arrays. So you could just define:

```<code>{
  "variables": {
    "snap_users": ""
  },
  "builders": [
    {
      "type": "amazon-ebs",
      "snapshot_users": "{{user `snap_users`}}"
    }
  ]
}
</code>```

Body:
Packer splits variables on , into arrays. So you could just define:

{
  "variables": {
    "snap_users": ""
  },
  "builders": [
    {
      "type": "amazon-ebs",
      "snapshot_users": "{{user `snap_users`}}"
    }
  ]
}


问:
Webpack: Is it possible to load svg with the file-loader? If yes, how?
I want to load my svg via the file-loader with webpack. Is this even possible and if yes, how do I do that.

webpack.config.js

```<code>test: /\.(jpe?g|png|gif|svg)$/i,
use: [
  {
    loader: 'file-loader',
    options: {
      name:'[name].[ext]',
      outputPath: 'img/',
      publicPath: '../',
    }
  }
]
</code>```

答: I found my fault, it was because I never used the svg in my project so it never got compiled. Now the file-loader compiles my svg too.</p>

Body:
I want to load my svg via the file-loader with webpack. Is this even possible and if yes, how do I do that.

webpack.config.js

test: /\.(jpe?g|png|gif|svg)$/i,
use: [
  {
    loader: 'file-loader',
    options: {
      name:'[name].[ext]',
      outputPath: 'img/',
      publicPath: '../',
    }
  }
]


问:
Set default value for dropdown list FormGroup
I have 2 response data from my API like as:
List all roles:

```<code>{
  "content": [{
      "id": 1,
      "roleName": "admin",
    },
    {
      "id": 2,
      "roleName": "user",

    },
    {
      "id": 3,
      "roleName": "other",

    }
  ],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}
</code>```

and user info:

```<code>{
  "id": 1,
  "userName": "admin"
  userRole[
    "id": 1,
    "roleName": "admin",
  ]
}
</code>```

in HTML, I want to show the list role:

```<code><div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">{{ls.roleName}}</option>
  </select>
</div>
</code>```

but, the UI shows : [admin],[admin],[user],[other]

I try to remove the duplicate role by using *ngIf:

```<code><div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">
      <div *ngIf="user.userRole.roleName!=ls.roleName">{{ls.roleName}}</div>
    </option>
  </select>
</div>
</code>```

but the UI shows:[admin],[blank],[user],[other]

Please advice me to show the list role correctly.

答:
```<code><div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option *ngFor="let ls of roles" [selected]="ls.id === user.userRole.id">
      {{ls.roleName}}
    </option>
  </select>
</div>
</code>```

Body:
I have 2 response data from my API like as:
List all roles:

{
  "content": [{
      "id": 1,
      "roleName": "admin",
    },
    {
      "id": 2,
      "roleName": "user",

    },
    {
      "id": 3,
      "roleName": "other",

    }
  ],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}

and user info:

{
  "id": 1,
  "userName": "admin"
  userRole[
    "id": 1,
    "roleName": "admin",
  ]
}

in HTML, I want to show the list role:

  Roles
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">{{ls.roleName}}</option>
  </select>

but, the UI shows : [admin],[admin],[user],[other]

I try to remove the duplicate role by using *ngIf:

  Roles
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">

{{ls.roleName}}

    </option>
  </select>

but the UI shows:[admin],[blank],[user],[other]

Please advice me to show the list role correctly.


问:
How to wake up the app with Eddystone in Android
I want to wake up my app with Eddystone, however nothing happened when my phone get close to the signal of Eddystone. I did it with Android Beacon library. And it is as blew:

```<code>    `
onCreate(){
    mBeaconManager = BeaconManager.getInstanceForApplication(this);
    // Detect the main Eddystone-UID frame:
    mBeaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));
    mBeaconManager.setBackgroundBetweenScanPeriod(50);
    mBeaconManager.setBackgroundScanPeriod(50);
    mBeaconManager.setForegroundBetweenScanPeriod(50);
    mBeaconManager.setForegroundScanPeriod(50);
    mBeaconManager.setBackgroundBetweenScanPeriod(50);
    mBeaconManager.setForegroundScanPeriod(50);
    mBeaconManager.applySettings();
    mBeaconManager.bind(this);
</code>```

}`

Android.xml:

```<code><application
    android:name="com.example.MyApplicationName"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <!-- Note:  the singleInstance below is important to keep two copies of your activity from getting launched on automatic startup -->
    <activity
        android:launchMode="singleInstance"
        android:name="com.example.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
    <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

Is there anyone did it before, please help me with it. Thanks

答:
Yes, it is possible to wake up an app with Eddystone-UID using the Android Beacon Library.  It works the same way as with AltBeacon or iBeacon.

The easiest way to get this to happen is to start with the reference app here:

https://github.com/altbeacon/android-beacon-library-reference

The only modification you need to make is to add the beacon parser for Eddystone-UID:

```<code>mBeaconManager.getBeaconParsers().add(new BeaconParser().
        setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));
</code>```

Looking at the code in the question, setting the scan periods to 50 is going to be a problem, as 50ms is not long enough to reliably detect a beacon.  I would remove these custom scan period configurations and use the defaults.

A few tips:

Make sure you can detect beacons in the foreground before trying to make your app work in the background.

Make sure your app is using RegionBootstrap as in the reference app as described in the "Starting an App in the Background" section here

When testing background detection, make sure you are out of region before starting the test.  To do this, bring your app to the foreground, and have your beacon(s) turned off for 30 seconds.  This will ensure you are out of region.  Always to this before starting a background detection test.

If you kill your app from the task switcher, wait 5 minutes to ensure it is restarted in the background before starting your testing.

Be realistic about how long it might take to detect a beacon in the background.  Read here for more info.

Body:
I want to wake up my app with Eddystone, however nothing happened when my phone get close to the signal of Eddystone. I did it with Android Beacon library. And it is as blew:

    `
onCreate(){
    mBeaconManager = BeaconManager.getInstanceForApplication(this);
    // Detect the main Eddystone-UID frame:
    mBeaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));
    mBeaconManager.setBackgroundBetweenScanPeriod(50);
    mBeaconManager.setBackgroundScanPeriod(50);
    mBeaconManager.setForegroundBetweenScanPeriod(50);
    mBeaconManager.setForegroundScanPeriod(50);
    mBeaconManager.setBackgroundBetweenScanPeriod(50);
    mBeaconManager.setForegroundScanPeriod(50);
    mBeaconManager.applySettings();
    mBeaconManager.bind(this);

}`

Android.xml:

<application
    android:name="com.example.MyApplicationName"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:launchMode="singleInstance"
        android:name="com.example.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
    <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Is there anyone did it before, please help me with it. Thanks

Body:
Yes, it is possible to wake up an app with Eddystone-UID using the Android Beacon Library.  It works the same way as with AltBeacon or iBeacon.

The easiest way to get this to happen is to start with the reference app here:

https://github.com/altbeacon/android-beacon-library-reference

The only modification you need to make is to add the beacon parser for Eddystone-UID:

mBeaconManager.getBeaconParsers().add(new BeaconParser().
        setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));

Looking at the code in the question, setting the scan periods to 50 is going to be a problem, as 50ms is not long enough to reliably detect a beacon.  I would remove these custom scan period configurations and use the defaults.

A few tips:

Make sure you can detect beacons in the foreground before trying to make your app work in the background.

Make sure your app is using RegionBootstrap as in the reference app as described in the "Starting an App in the Background" section here

When testing background detection, make sure you are out of region before starting the test.  To do this, bring your app to the foreground, and have your beacon(s) turned off for 30 seconds.  This will ensure you are out of region.  Always to this before starting a background detection test.

If you kill your app from the task switcher, wait 5 minutes to ensure it is restarted in the background before starting your testing.

Be realistic about how long it might take to detect a beacon in the background.  Read here for more info.


问:
How do you do negative random number (gamemaker studio)?
Can you use

```<code>irandom(-10,10)
</code>```

to generate negative numbers? Or does this function provides only number >=0?
There is no information in documentation of GML.

答:
A few examples:</p>

```<code>a = -1 * irandom(10);

a = -irandom(10);

a = irandom(20) - 10;

a = irandom_range(-10, 10);
</code>```

Body:
Can you use

irandom(-10,10)

to generate negative numbers? Or does this function provides only number >=0?
There is no information in documentation of GML.

Body:
A few examples:

a = -1 * irandom(10);

a = -irandom(10);

a = irandom(20) - 10;

a = irandom_range(-10, 10);


问:
Code not running in IE 11, works fine in Chrome
The following code can be run without a problem in Chrome, but throws the following error in Internet Explorer 11.

Object doesn't support property or method 'startsWith'

I am storing the element's ID in a variable. What is the issue?

function changeClass(elId) {
  var array = document.getElementsByTagName('td');

  for (var a = 0; a < array.length; a++) {
    var str = array[a].id;

    if (str.startsWith('REP')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    } else if (str.startsWith('D')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td id="REP1" onclick="changeClass('REP1');">REPS</td>
    <td id="td1"> </td>
  </tr>
  <tr>
    <td id="td1"> </td>
    <td id="D1" onclick="changeClass('D1');">Doors</td>
  </tr>
  <tr>
    <td id="td1"> </td>
    <td id="D12" onclick="changeClass('D12');">Doors</td>
  </tr>
</table></code>```

答:
As others have said startsWith and endsWith are part of ES6 and not available in IE11. Our company always uses lodash library as a polyfill solution for IE11. https://lodash.com/docs/4.17.4</p>

```<code>_.startsWith([string=''], [target], [position=0])
</code>```

Body:
The following code can be run without a problem in Chrome, but throws the following error in Internet Explorer 11.

Object doesn't support property or method 'startsWith'

I am storing the element's ID in a variable. What is the issue?

function changeClass(elId) {
  var array = document.getElementsByTagName('td');

  for (var a = 0; a < array.length; a++) {
    var str = array[a].id;

    if (str.startsWith('REP')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    } else if (str.startsWith('D')) {
      if (str == elId) {
        array[a].style.backgroundColor = "Blue";
        array[a].style.color = "white";
      } else {
        array[a].style.backgroundColor = "";
        array[a].style.color = "";
      }
    }
  }
}

    REPS

    Doors

    Doors

Body:
As others have said startsWith and endsWith are part of ES6 and not available in IE11. Our company always uses lodash library as a polyfill solution for IE11. https://lodash.com/docs/4.17.4

_.startsWith([string=''], [target], [position=0])


问:
How does ConcurrentReferenceHashMap work?
We have a situation using spring-cloud-netflix-core library which is described here. I think the issue is with the way CachingSpringLoadBalancerFactory is using ConcurrentReferenceHashMap which is reported here.

And also from the documentation of ConcurrentReferenceHashMap (which uses soft references):

The use of references means that there is no guarantee that items placed into the map will be subsequently available. The garbage collector may discard references at any time, so it may appear that an unknown thread is silently removing entries.

Now my questions are:

1. Is my understanding in the following correct?

```<code>// Original code is in CachingSpringLoadBalancerFactory in spring-cloud-netflix-core
// cache is a field of type ConcurrentReferenceHashMap
if (this.cache.containsKey(clientName)) {
  return this.cache.get(clientName); // This can be null, right?
}
</code>```

2. Is there anyway to write a test case for it. We managed to reproduce it once in an standalone application with limited memory (-Xmx50m). But how can we write a unit test to cover such scenario?

答:
As to your question, yes, that's correct. Generally, this is a variation on WeakHashMap, as stated in the docs.

The JavaDoc for WeakHashMap says:

"The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements."

Because of this behavior, it is quite difficult to test. You can use the getReference() method of the map and the release() method of the corresponding elements to simulate the purges if you want to test some invariants.

Body:
We have a situation using spring-cloud-netflix-core library which is described here. I think the issue is with the way CachingSpringLoadBalancerFactory is using ConcurrentReferenceHashMap which is reported here.

And also from the documentation of ConcurrentReferenceHashMap (which uses soft references):

The use of references means that there is no guarantee that items placed into the map will be subsequently available. The garbage collector may discard references at any time, so it may appear that an unknown thread is silently removing entries.

Now my questions are:

1. Is my understanding in the following correct?

// Original code is in CachingSpringLoadBalancerFactory in spring-cloud-netflix-core
// cache is a field of type ConcurrentReferenceHashMap
if (this.cache.containsKey(clientName)) {
  return this.cache.get(clientName); // This can be null, right?
}

2. Is there anyway to write a test case for it. We managed to reproduce it once in an standalone application with limited memory (-Xmx50m). But how can we write a unit test to cover such scenario?


问:
Error writing .htaccess to protect Symfony Directories in Web App
I'm trying to publish my first Symfony Project in production, but I'm very worried about security, I have taken the following measures:

1) First: Delete on /var these directories: cache, logs and sessions

2) Second: Changed of default name for cookie session (client side: symfony)

3) Trhee: Creating a .htaccess in root directory of application

My problem is about the .htaccess. The goal is dennied access to others directories of application like: /app, /src, /test, /var, /vendor.

I'll write the follow rules in .htaccess and puted it in root directory of my app: myDevelopedApp/.htaccess.

```<code>.htaccess
#Checking if module is avalaible
<IfModule mod_rewrite.c>
   #Using the rewrite engine
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   #Rewrite rule to redirect the request
   RewriteRule ^(.*)$ web/$1 [QSA,L]
<IfModule>
</code>```

The problem it's not working, I can not access to web folder when I write the rules. Apache hides the application myDevelopedApp when I try to access it by browser

What I'm wrong?
Any other recommendation to improve security in production enviroment is welcome, thanks so much.

答:
htaccess file code
    ```
    .htaccess
    #Checking if module is avalaible

       #Using the rewrite engine
       RewriteEngine On
       RewriteCond %{REQUEST_FILENAME} !-f
       #Rewrite rule to redirect the request
       RewriteRule ^(.*)$ web/$1 [QSA,L]

    ```

and this code too on your .htaccess file

```<code>```
.htaccess
#Checking if module is avalaible
<IfModule mod_rewrite.c>
   #Using the rewrite engine
   RewriteEngine On
   RewriteBase /folder/ /*location address if localhost localhost/project */
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   #Rewrite rule to redirect the request
   RewriteRule ^(.*)$ web/$1 [QSA,L]
<IfModule>
```
</code>```

RewriteBase solve this problem

Body:
I'm trying to publish my first Symfony Project in production, but I'm very worried about security, I have taken the following measures:

1) First: Delete on /var these directories: cache, logs and sessions

2) Second: Changed of default name for cookie session (client side: symfony)

3) Trhee: Creating a .htaccess in root directory of application

My problem is about the .htaccess. The goal is dennied access to others directories of application like: /app, /src, /test, /var, /vendor.

I'll write the follow rules in .htaccess and puted it in root directory of my app: myDevelopedApp/.htaccess.

.htaccess
#Checking if module is avalaible
<IfModule mod_rewrite.c>
   #Using the rewrite engine
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   #Rewrite rule to redirect the request
   RewriteRule ^(.*)$ web/$1 [QSA,L]
<IfModule>

The problem it's not working, I can not access to web folder when I write the rules. Apache hides the application myDevelopedApp when I try to access it by browser

What I'm wrong?
Any other recommendation to improve security in production enviroment is welcome, thanks so much.

Body:
htaccess file code

    .htaccess
    #Checking if module is avalaible

       #Using the rewrite engine
       RewriteEngine On
       RewriteCond %{REQUEST_FILENAME} !-f
       #Rewrite rule to redirect the request
       RewriteRule ^(.*)$ web/$1 [QSA,L]

and this code too on your .htaccess file

<pre>
.htaccess
#Checking if module is avalaible
<IfModule mod_rewrite.c>
   #Using the rewrite engine
   RewriteEngine On
   RewriteBase /folder/ /*location address if localhost localhost/project */
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   #Rewrite rule to redirect the request
   RewriteRule ^(.*)$ web/$1 [QSA,L]
<IfModule>
</pre>

RewriteBase solve this problem


问:
Are C constant character strings always null terminated?
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

```<code>const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}
</code>```

答:
In C, there isn't really a "string" datatype like in C++ and Java.

Important principle that every competent computer science degree program should mention: Information is symbols plus interpretation.

A "string" is defined conventionally as any sequence of characters ending in a null byte ('\0').

The "gotcha" that's being posted (character/byte arrays with the value 0 in the middle of them) is only a difference of interpretation. Treating a byte array as a string versus treating it as bytes (numbers in [0, 255]) has different applications. Obviously if you're printing to the terminal you might want to print characters until you reach a null byte. If you're saving a file or running an encryption algorithm on blocks of data you will need to support 0's in byte arrays.

It's also valid to take a "string" and optionally interpret as a byte array.

Body:
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}


问:
Akka: What jar file contains jdocs.AbstractJavaTest?
What jar-file dependency do I add to resolve this import?

```<code>import jdocs.AbstractJavaTest;
</code>```

It's imported in Akka's own example code (https://doc.akka.io/docs/akka/current/java/testing.html) yet after a lot of searching I can't find any mention of the actual jar dependency and the Akka documentation search function is so unhelpful that it claims there are no mentions of "jdocs.AbstractJavaTest" even when the code is on the screen in front of me.

Note that the following artifacts do not contain it:

```<code>'com.typesafe.akka:akka-actor_2.12:2.5.6'
'com.typesafe.akka:akka-testkit_2.12:2.5.3'
</code>```

Thanks for any help you can give.

答:
AbstractJavaTest is located in the akka-docs module in the Akka repository and is not packaged in any of the published jars. All it does is extend JUnitSuite:

/*
 * Copyright (C) 2016-2017 Lightbend Inc. <http://www.lightbend.com>
 */
package jdocs

import org.scalatest.junit.JUnitSuite

/**
 * Base class for all runnable example tests written in Java
 */
abstract class AbstractJavaTest extends JUnitSuite {

}
```

As documented in the pull request that brought in this class, it was added to (1) hide the detail that the Java test suites in the Akka documentation need to extend JUnitSuite, and (2) to define that in one location. Feel free to manually add this class or its equivalent to your code, or simply have your test suites directly extend JUnitSuite.

Body:
What jar-file dependency do I add to resolve this import?

import jdocs.AbstractJavaTest;

It's imported in Akka's own example code (https://doc.akka.io/docs/akka/current/java/testing.html) yet after a lot of searching I can't find any mention of the actual jar dependency and the Akka documentation search function is so unhelpful that it claims there are no mentions of "jdocs.AbstractJavaTest" even when the code is on the screen in front of me.

Note that the following artifacts do not contain it:

'com.typesafe.akka:akka-actor_2.12:2.5.6'
'com.typesafe.akka:akka-testkit_2.12:2.5.3'

Thanks for any help you can give.

Body:
AbstractJavaTest is located in the akka-docs module in the Akka repository and is not packaged in any of the published jars. All it does is extend JUnitSuite:

/*
 * Copyright (C) 2016-2017 Lightbend Inc. <http://www.lightbend.com>
 */
package jdocs

import org.scalatest.junit.JUnitSuite

/**
 * Base class for all runnable example tests written in Java
 */
abstract class AbstractJavaTest extends JUnitSuite {

}

As documented in the pull request that brought in this class, it was added to (1) hide the detail that the Java test suites in the Akka documentation need to extend JUnitSuite, and (2) to define that in one location. Feel free to manually add this class or its equivalent to your code, or simply have your test suites directly extend JUnitSuite.


问:
Android Studio gradle build stuck at app:processDebugResources
I'm on Windows. I created a new project on Android Studio for Marshmallow at least.
The only thing I've done so far is generating the main activity which is a tabbed activity with view pager. Also, you should know that this project is a private git repo that I cloned.

I'm working on this project with another developer and the project is perfectly working on his side.

The problem is:

When I try to launch the app (wether it is a virtual device or my real phone), the gradle build gets stuck at the app:processDebugResources step. I waited more than an hour and nothing happened. Moreover, when I want to cancel the gradle build, it doesn't respond and I have to kill Android Studio process. Then I restart Android Studio and I have to kill a gradle process that prevents the initial gradle build (at Android Studio startup) from working.

The crazy thing is that I was able to launch the app before. I even installed it on my phone!

What I've tried so far:

Do what stackoverflow was giving as solutions like tick the offline mode in the settings

Create a new project --> It doesn't change anything

Reinstall Android Studio --> It doesn't change anything

Deactivating Avast antivirus

Invalidate cache/restart + Clean + rebuild (the rebuild gets stuck like when I try to launch the app)

And maybe other solutions that I forgot...

It's getting very annoying as it's making me lose days of development.

If you have any more solutions, or if you think I should try again some of the previous solutions, help would be greatly appreciated !

答: Maybe your gradle version is not compatible with it. Try again with latest version of gradle in your project.</p>


问:
Getting the name of the city clicked in GoogleMaps
Using GoogleMaps API in JavaScript, I am trying to get the name (and the location) of city clicked on my map.

Firstly, I though I could use the PointOfInterest Event feature as explained in this example, however cities do not seem to provide the placeId required.

Secondly, I tried to use the reverse geocoding mechanism described here to get the complete address of the location, and from here, extract the name of the city (locality):

```<code>this.map.addListener('click', (event) => {
    this.geocoder.geocode({
        location: event.latLng,
    }, (results, status) => {
        if(status === 'OK')
        {
            if(results && results.length)
            {
                const addressResult = results[0];

                if(addressResult.address_components)
                {
                    addressResult.address_components.forEach((component) => {
                        if(component.types.includes('locality'))
                        {
                            console.log(component.long_name);
                        }
                    });
                }
            }
        }
    });
});
</code>```

This method gave me pretty good results however it also showed some issues:

Despite setting the map locale to en, I am still getting the name of the city as it appears in the address returned by the geocoder.
For example, I got Genève (french name of Geneva) instead of Geneva, I got
Munchen (german name of Munich) instead of Munich

Clicking on a city, I sometime get another city if the location clicked belong to another locality.

Any advise to get the name of the city clicked would be much appreciated.

答:
When you execute reverse geocoding, the service will return results of different types. The first is typically a nearest street address, after that you will have other results like neighborhood, POIs, locality, administrative areas and country.

In your code you choose the first result (nearest street address) to get the name of the city. In this case you should be aware that geocoding service returns names of streets and localities in local language rather than in the language you specified in Maps JavaScript API initialization. You can read about this policy in this blog post:

https://maps-apis.googleblog.com/2014/11/localization-of-street-addresses-in.html

For political entities this rule is not applied, so you will get items of type locality or administrative area in language you specified in your JavaScript API initialization.

In order to get the name of the locality in English you should filter the results by type locality and read its address components to get locality name.

I slightly modified your code to get localities in English, note the variable filtered_array that does a trick.

var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 47.295077, lng: 9.211874},
      zoom: 8
    });

    var geocoder = new google.maps.Geocoder();

    map.addListener('click', (event) => {
      geocoder.geocode({
        location: event.latLng,
      }, (results, status) => {
        if(status === 'OK') {
            if(results && results.length) {
                var filtered_array = results.filter(result => result.types.includes("locality"));
                var addressResult = filtered_array.length ? filtered_array[0]: results[0];

                if(addressResult.address_components) {
                    addressResult.address_components.forEach((component) => {
                        if(component.types.includes('locality')) {
                            console.log(component.long_name);
                        }
                    });
                }
            }
        }
    });
  });
} ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

I hope this helps!

Body:
Using GoogleMaps API in JavaScript, I am trying to get the name (and the location) of city clicked on my map.

Firstly, I though I could use the PointOfInterest Event feature as explained in this example, however cities do not seem to provide the placeId required.

Secondly, I tried to use the reverse geocoding mechanism described here to get the complete address of the location, and from here, extract the name of the city (locality):

this.map.addListener('click', (event) => {
    this.geocoder.geocode({
        location: event.latLng,
    }, (results, status) => {
        if(status === 'OK')
        {
            if(results && results.length)
            {
                const addressResult = results[0];

                if(addressResult.address_components)
                {
                    addressResult.address_components.forEach((component) => {
                        if(component.types.includes('locality'))
                        {
                            console.log(component.long_name);
                        }
                    });
                }
            }
        }
    });
});

This method gave me pretty good results however it also showed some issues:

Despite setting the map locale to en, I am still getting the name of the city as it appears in the address returned by the geocoder.
For example, I got Genève (french name of Geneva) instead of Geneva, I got
Munchen (german name of Munich) instead of Munich

Clicking on a city, I sometime get another city if the location clicked belong to another locality.

Any advise to get the name of the city clicked would be much appreciated.

Body:
When you execute reverse geocoding, the service will return results of different types. The first is typically a nearest street address, after that you will have other results like neighborhood, POIs, locality, administrative areas and country.

In your code you choose the first result (nearest street address) to get the name of the city. In this case you should be aware that geocoding service returns names of streets and localities in local language rather than in the language you specified in Maps JavaScript API initialization. You can read about this policy in this blog post:

https://maps-apis.googleblog.com/2014/11/localization-of-street-addresses-in.html

For political entities this rule is not applied, so you will get items of type locality or administrative area in language you specified in your JavaScript API initialization.

In order to get the name of the locality in English you should filter the results by type locality and read its address components to get locality name.

I slightly modified your code to get localities in English, note the variable filtered_array that does a trick.

var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 47.295077, lng: 9.211874},
      zoom: 8
    });

    var geocoder = new google.maps.Geocoder();

    map.addListener('click', (event) => {
      geocoder.geocode({
        location: event.latLng,
      }, (results, status) => {
        if(status === 'OK') {
            if(results && results.length) {
                var filtered_array = results.filter(result => result.types.includes("locality"));
                var addressResult = filtered_array.length ? filtered_array[0]: results[0];

                if(addressResult.address_components) {
                    addressResult.address_components.forEach((component) => {
                        if(component.types.includes('locality')) {
                            console.log(component.long_name);
                        }
                    });
                }
            }
        }
    });
  });
}

#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&language=en&callback=initMap"
    async defer></script>

I hope this helps!


问:
Converting Repeated Names in Dataframe to Single Values
Looking for this:
Anthony now equals 1
John now equals 2
Smith now equals 3
and this goes on and on even if the name is repeated.. Looking for this
1
1
2
2
3
3

The code is fairly long but here is the spot I need to convert the names to numbers

LM = frame[['Name','COMMENT']]    -> Name is currently characters in a movie and I want to change it over to Numbers to be able to run a SVM Model through the Response Variable 'Name'

答:
IIUC, you need to look at pd.factorize or convert name to pd.Categorical and use categorgy_codes.

```<code>np.random.seed(123)
df = pd.DataFrame({'Name':np.random.choice(['John','Smith','Anthony'],10)})

df['Name_Code'] = pd.factorize(df.Name)[0] + 1

df
</code>```

Output:

```<code>      Name  Name_Code
0  Anthony          1
1    Smith          2
2  Anthony          1
3  Anthony          1
4     John          3
5  Anthony          1
6  Anthony          1
7    Smith          2
8  Anthony          1
9    Smith          2
</code>```

OR

```<code>df['Name_Cat_Code'] = pd.Categorical(df.Name).codes + 1
</code>```

Output:

```<code>      Name  Name_Code  Name_Cat_Code
0  Anthony          1              1
1    Smith          2              3
2  Anthony          1              1
3  Anthony          1              1
4     John          3              2
5  Anthony          1              1
6  Anthony          1              1
7    Smith          2              3
8  Anthony          1              1
9    Smith          2              3
</code>```

Body:
IIUC, you need to look at pd.factorize or convert name to pd.Categorical and use categorgy_codes.

np.random.seed(123)
df = pd.DataFrame({'Name':np.random.choice(['John','Smith','Anthony'],10)})

df['Name_Code'] = pd.factorize(df.Name)[0] + 1

df

Output:

      Name  Name_Code
0  Anthony          1
1    Smith          2
2  Anthony          1
3  Anthony          1
4     John          3
5  Anthony          1
6  Anthony          1
7    Smith          2
8  Anthony          1
9    Smith          2

OR

df['Name_Cat_Code'] = pd.Categorical(df.Name).codes + 1

Output:

      Name  Name_Code  Name_Cat_Code
0  Anthony          1              1
1    Smith          2              3
2  Anthony          1              1
3  Anthony          1              1
4     John          3              2
5  Anthony          1              1
6  Anthony          1              1
7    Smith          2              3
8  Anthony          1              1
9    Smith          2              3


问:
Disable and enable jQuery context menu
I use

```<code>$('#test').unbind('click');
</code>```

to remove the click event on the #test item. How do I make the item clickable again?

Actually I have a table. On click event a context menu appears. But if there are no entries the menu has to be disabled. So I use unbind above. Since the context menu is generated by a plugin I do not know how to make it clickable again.

Any ideas?

Update: this is how the context menu is set up

```<code> $('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
      'sms': function(t) {},
      'delete': function(t) {}
    }
 });
</code>```

Since I am still not sure how to solve my problem I will describe it a little more. I use the lightweight context-menu plugin in jQuery to display context menus.

```<code>#contacts tbody tr
</code>```

are the table rows and myMenu1 is the context menu that appears on tr click.

On my page I have a table. Each row has its own context menu, well always the same but function(t) referes always to the clicked row.

Well, the table may be empty so I want to disable the context menu. I believe there are may ways to do that. One is to unbind the click event, this does not work for me.

I hope anyone has an idea.

答:
Cache the handler to a variable. Then bind and unbind using that reference.

Instead of binding your click event inline:

```<code>$('#test').bind('click', function(){
    alert('hi!');
});
</code>```

Declare the function to a variable:

```<code>var clickHandle = function(){
    alert('hi!');
};
</code>```

And then bind using the variable name:

```<code>$('#test').bind('click', clickHandle);
</code>```

Then you can unbind the specific click handler:

```<code>$('#test').unbind('click', clickHandle);
</code>```

Then you can still re-bind the same function:

```<code>$('#test').bind('click', clickHandle);
</code>```

Took a quick look at the source. The event is bound to contextmenu, not click.

You can access the function through the element's data.events property (similar to what j3frea was saying). Have a look at this fiddle example for a full resolution.

Essentially you can do this:

```<code>var cachedHandler = null;
// disable
cachedHandler = $('#demo2').data('events').contextmenu[0].handler;
$('#demo2').unbind('contextmenu', cachedHandler);
// enable
$('#demo2').bind('contextmenu', cachedHandler);
</code>```

Title: Disable and enable jQuery context menu

Body:
I use

$('#test').unbind('click');

to remove the click event on the #test item. How do I make the item clickable again?

Actually I have a table. On click event a context menu appears. But if there are no entries the menu has to be disabled. So I use unbind above. Since the context menu is generated by a plugin I do not know how to make it clickable again.

Any ideas?

Update: this is how the context menu is set up

 $('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
      'sms': function(t) {},
      'delete': function(t) {}
    }
 });

Since I am still not sure how to solve my problem I will describe it a little more. I use the lightweight context-menu plugin in jQuery to display context menus.

#contacts tbody tr

are the table rows and myMenu1 is the context menu that appears on tr click.

On my page I have a table. Each row has its own context menu, well always the same but function(t) referes always to the clicked row.

Well, the table may be empty so I want to disable the context menu. I believe there are may ways to do that. One is to unbind the click event, this does not work for me.

I hope anyone has an idea.

Body:
Cache the handler to a variable. Then bind and unbind using that reference.

Instead of binding your click event inline:

$('#test').bind('click', function(){
    alert('hi!');
});

Declare the function to a variable:

var clickHandle = function(){
    alert('hi!');
};

And then bind using the variable name:

$('#test').bind('click', clickHandle);

Then you can unbind the specific click handler:

$('#test').unbind('click', clickHandle);

Then you can still re-bind the same function:

$('#test').bind('click', clickHandle);

Took a quick look at the source. The event is bound to contextmenu, not click.

You can access the function through the element's data.events property (similar to what j3frea was saying). Have a look at this fiddle example for a full resolution.

Essentially you can do this:

var cachedHandler = null;
// disable
cachedHandler = $('#demo2').data('events').contextmenu[0].handler;
$('#demo2').unbind('contextmenu', cachedHandler);
// enable
$('#demo2').bind('contextmenu', cachedHandler);


问:
change state radio button if image is clicked
I have two radio buttons and each radio button has an image. Now I want that if you click on a image that also the state of the radio button changed. This is the html code:

```<code>        @if (Html.GebruikerContext().Klant.LogoIDSpecified)
        {
            <div class="property wide extra-margin">
                <label>
                    Kies header logo
                </label>
                <div class="email-logo">
                    <div class="email-logo-image">
                        <a href=""> <img src='/Beheer/Images/mainlogo_274x122.png' />      </a>

                        <div class="email-logo-button">
                            <label>
                                @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                <span>standaard logo</span>
                            </label>
                        </div>
                    </div>

                </div>

                <div class="email-logo">
                    <div class="email-logo-image">
                        <img src='/Beheer/Document/Download?documentID=@(Html.GebruikerContext().Klant.LogoID)' />
                    </div>
                    <div class="email-logo-button">
                        <label>
                            @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                            <span>eigen logo</span>
                        </label>
                    </div>
                </div>
            </div>
        }
</code>```

and this is the javascript code for the radio button:

```<code> $('#logo-selectie[value=standaard]').click(function () {
            $('#GebruikKlantLogo').val(false);
        });

        $('#logo-selectie[value=klant]').click(function () {
            $('#GebruikKlantLogo').val(true);
        });
</code>```

答:
The simple way which involves no JS code would be to modify your HTML so that the  element wraps both the radio button and the image, something like this:

    Kies header logo

          @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
          standaard logo

        @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
        eigen logo

```

<p>You can then amend your jQuery event handlers to use the <code>change</code> event instead, which is better for accessibility anyway:</p>

```$('#logo-selectie[value=standaard]').change(function () {
  $('#GebruikKlantLogo').val(false);
});

$('#logo-selectie[value=klant]').change(function () {
  $('#GebruikKlantLogo').val(true);
});
```

Body:
I have two radio buttons and each radio button has an image. Now I want that if you click on a image that also the state of the radio button changed. This is the html code:

        @if (Html.GebruikerContext().Klant.LogoIDSpecified)
        {

                    Kies header logo

                                @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                standaard logo

                            @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                            eigen logo

        }

and this is the javascript code for the radio button:

 $('#logo-selectie[value=standaard]').click(function () {
            $('#GebruikKlantLogo').val(false);
        });

        $('#logo-selectie[value=klant]').click(function () {
            $('#GebruikKlantLogo').val(true);
        });

Body:
The simple way which involves no JS code would be to modify your HTML so that the <label> element wraps both the radio button and the image, something like this:

<div class="property wide extra-margin">
  <label>
    Kies header logo
  </label>
  <div class="email-logo">
    <div class="email-logo-image">
      <label>
        <img src='/Beheer/Images/mainlogo_274x122.png' />
        <div class="email-logo-button">
          @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
          <span>standaard logo</span>
        </div>
      </label>
    </div>
  </div>

  <div class="email-logo">
    <label>
      <div class="email-logo-image">
        <img src='/Beheer/Document/Download?documentID=@(Html.GebruikerContext().Klant.LogoID)' />
      </div>
      <div class="email-logo-button">
        @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
        <span>eigen logo</span>
      </div>
    </label>
  </div>
</div>

You can then amend your jQuery event handlers to use the change event instead, which is better for accessibility anyway:

$('#logo-selectie[value=standaard]').change(function () {
  $('#GebruikKlantLogo').val(false);
});

$('#logo-selectie[value=klant]').change(function () {
  $('#GebruikKlantLogo').val(true);
});


问:
Dividing a bag of mixed candy
Assuming I have a bag of candy Ci with N pieces of candy. It's a mix of t different types of candy, Ti. I want to share it between my M friends.

Each of them has a preference for each type of candy, P(m,Ti) where m is one of the M friends. P(m,Ti) is an integer and distinct, and the sum of P(m,T) for each friend is 50 (each friend distributes 50 points as he wishes between the candy types, with no types getting the same amount of points).

We want to divide the N pieces of candy between all the m friends in such a way that everybody is pleased. All the candy needs to be divided. Each person does not need to be given the same amount of candy.

1) Is there any way to objectively reach a solution for the "perfect" way to divide the candy?

Assuming the answer to (1) is "no", we will define it as follows. Sm is sum[P(m,Tj)], where j is subset of i that m is given. The definition of the optimal solution is the distribution with the lowest possible standard deviation of Sm with highest possible average Sm as tie breaker.

2) What is the best way to approach this problem? Is there any known algorithms?

答: (1) https://en.wikipedia.org/wiki/Pareto_efficiency. A Pareto improvement is a change to a different allocation that makes at least one individual or preference criterion better off without making any other individual or preference criterion worse off, given a certain initial allocation of goods among a set of individuals. An allocation is defined as "Pareto efficient" or "Pareto optimal" when no further Pareto improvements can be made, in which case we are assumed to have reached Pareto optimality.</p>

Title: Dividing a bag of mixed candy


问:
How to apply class on the final html element in an AngularJs ui-select-match element?
I don't get this in the angular-js ui-select bootstrap example:

edit: can't link to the plunker directly, so use the fifth (Bootstrap) example on this page: http://angular-ui.github.io/ui-select/

But in my code the label with the select value gets a width: 100%; property from default ui-select classes, the padding is overwritten:

```<code>.ui-select-bootstrap .ui-select-match-text {
    width: 100%;
    padding-right: 1em;
}
</code>```

This causes the label to flow over the listbox:

I can cancel this effect by overriding the width property with width: auto;

I can apply a class by editing the html of the element directly. But when the class is added to the source HTML, it cannot be found in the resulting HTML.

So how can I apply a class there?

This is my source code:

```<code><label class="control-label">Bronhouder</label>
<ui-select ng-model="params.bronhouder" theme="bootstrap" on-select="selectBronhouder()">
    <ui-select-match ng-class="{'listboxSelectedLabelOverflowFix': true}">{{params.bronhouder.naam}}</ui-select-match>
    <ui-select-choices repeat="item in bronhouders | filter: $select.search">
        <span ng-bind-html="item.naam | highlight: $select.search"></span>
    </ui-select-choices>
</ui-select>
</code>```

I tried adding the class listboxSelectedLabelOverflowFix, on the ui-select-match element but it doesn't appear on the final HTML element.

The effect of this class can be achieved through using ng-class (edited the source code). However it causes a conflict in the Angular internals with the following error:

4angular.js:14328 Error: [$parse:syntax] Syntax Error: Token '{' is an
  unexpected token at column 35 of the expression
  [{"selectedLabelOverflowFix":true}
  {'btn-default-focus':$select.focus}] starting at
  [{'btn-default-focus':$select.focus}].
  http://errors.angularjs.org/1.6.1/$parse/syntax?p0=%7B&p1=is%20an%20unexpected%20token&p2=35&p3=%7BelectedLabelOverflowFix%22%3Atrue%7D%20%7B'btn-default-focus'%3A%select.focus%7D&p4=%7B'btn-default-focus'%3A%select.focus%7D

So it looks like there's already another ng-class on the html element that's being produced by Angular. ng-class expects a single {} block and can't be combined with mine.

答:
I've solved this by adapting the class that ui-select uses on the text element.</p>

```<code>.ui-select-match-text {
    width: auto !important;
}
</code>```

Body:
I don't get this in the angular-js ui-select bootstrap example:

edit: can't link to the plunker directly, so use the fifth (Bootstrap) example on this page: http://angular-ui.github.io/ui-select/

But in my code the label with the select value gets a width: 100%; property from default ui-select classes, the padding is overwritten:

.ui-select-bootstrap .ui-select-match-text {
    width: 100%;
    padding-right: 1em;
}

This causes the label to flow over the listbox:

I can cancel this effect by overriding the width property with width: auto;

I can apply a class by editing the html of the element directly. But when the class is added to the source HTML, it cannot be found in the resulting HTML.

So how can I apply a class there?

This is my source code:

Bronhouder
<ui-select ng-model="params.bronhouder" theme="bootstrap" on-select="selectBronhouder()">
    <ui-select-match ng-class="{'listboxSelectedLabelOverflowFix': true}">{{params.bronhouder.naam}}</ui-select-match>
    <ui-select-choices repeat="item in bronhouders | filter: $select.search">

    </ui-select-choices>
</ui-select>

I tried adding the class listboxSelectedLabelOverflowFix, on the ui-select-match element but it doesn't appear on the final HTML element.

The effect of this class can be achieved through using ng-class (edited the source code). However it causes a conflict in the Angular internals with the following error:

4angular.js:14328 Error: [$parse:syntax] Syntax Error: Token '{' is an
  unexpected token at column 35 of the expression
  [{"selectedLabelOverflowFix":true}
  {'btn-default-focus':$select.focus}] starting at
  [{'btn-default-focus':$select.focus}].
  http://errors.angularjs.org/1.6.1/$parse/syntax?p0=%7B&p1=is%20an%20unexpected%20token&p2=35&p3=%7BelectedLabelOverflowFix%22%3Atrue%7D%20%7B'btn-default-focus'%3A%select.focus%7D&p4=%7B'btn-default-focus'%3A%select.focus%7D

So it looks like there's already another ng-class on the html element that's being produced by Angular. ng-class expects a single {} block and can't be combined with mine.

Body:
I've solved this by adapting the class that ui-select uses on the text element.

.ui-select-match-text {
    width: auto !important;
}


问:
python pandas coloring of rows
I have this code that colors every time slot differently, so it is easier to navigate. The problem is, sometimes not all the slots will be populated and then i get the same color on the next slot and it will be hard to distinguish which slot is which.
how can i make this code more elegant and make python decide when there is a next slot to change the color. i want to have those colors changed "binary".</p>

```<code>def EPP_Break_boja(row):
    color = '#F5EEF8'
    if row.values[0] == '06:40':
        color = '#EBF5FB  '
    elif row.values[0] == '07:10':
        color = '#FEF9E7  '
    elif row.values[0] == '07:40':
        color = '#EBF5FB  '
    elif row.values[0] == '08:10':
        color = '#FEF9E7  '
    elif row.values[0] == '08:40':
        color = '#EBF5FB  '
    elif row.values[0] == '09:10':
        color = '#FEF9E7  '
    elif row.values[0] == '09:40':
        color = '#EBF5FB  '
    elif row.values[0] == '10:10':
        color = '#FEF9E7  '
    elif row.values[0] == '10:40':
        color = '#EBF5FB  '
    elif row.values[0] == '11:10':
        color = '#FEF9E7  '
    elif row.values[0] == '11:40':
        color = '#EBF5FB  '
    elif row.values[0] == '12:10':
        color = '#FEF9E7  '
    elif row.values[0] == '12:40':
        color = '#EBF5FB  '
    elif row.values[0] == '13:10':
        color = '#FEF9E7  '
    elif row.values[0] == '13:40':
        color = '#EBF5FB  '
    elif row.values[0] == '14:10':
        color = '#FEF9E7  '
    elif row.values[0] == '14:40':
        color = '#EBF5FB  '
    elif row.values[0] == '15:10':
        color = '#FEF9E7  '
    elif row.values[0] == '15:40':
        color = '#EBF5FB  '
    elif row.values[0] == '16:10':
        color = '#FEF9E7  '
    elif row.values[0] == '16:40':
        color = '#EBF5FB  '
    elif row.values[0] == '17:10':
        color = '#FEF9E7  '
    elif row.values[0] == '17:40':
        color = '#EBF5FB  '
    elif row.values[0] == '18:10':
        color = '#FEF9E7  '
    elif row.values[0] == '18:40':
        color = '#EBF5FB  '
    elif row.values[0] == '19:10':
        color = '#FEF9E7  '
    elif row.values[0] == '19:40':
        color = '#EBF5FB  '
    elif row.values[0] == '20:10':
        color = '#FEF9E7  '
    elif row.values[0] == '20:40':
        color = '#EBF5FB  '
    elif row.values[0] == '21:10':
        color = '#FEF9E7  '
    elif row.values[0] == '21:40':
        color = '#EBF5FB  '
    elif row.values[0] == '22:10':
        color = '#FEF9E7  '
    elif row.values[0] == '22:40':
        color = '#EBF5FB  '
    elif row.values[0] == '23:10':
        color = '#FEF9E7  '
    elif row.values[0] == '23:40':
        color = '#EBF5FB  '
    elif row.values[0] == 'Thursday 12-October-2017':
        color = '#FDEDEC  '
    elif row.values[0] == 'Thursday 13-October-2017':
        color = '#EAFAF1'
    return ['background-color: %s' % color]*len(row.values)

dataframe_spotovi = dataframe_spotovi.style.apply(EPP_Break_boja, axis=1)
dataframe_spotovi
</code>```

Title: python pandas coloring of rows

Body:
I have this code that colors every time slot differently, so it is easier to navigate. The problem is, sometimes not all the slots will be populated and then i get the same color on the next slot and it will be hard to distinguish which slot is which.
how can i make this code more elegant and make python decide when there is a next slot to change the color. i want to have those colors changed "binary".

def EPP_Break_boja(row):
    color = '#F5EEF8'
    if row.values[0] == '06:40':
        color = '#EBF5FB  '
    elif row.values[0] == '07:10':
        color = '#FEF9E7  '
    elif row.values[0] == '07:40':
        color = '#EBF5FB  '
    elif row.values[0] == '08:10':
        color = '#FEF9E7  '
    elif row.values[0] == '08:40':
        color = '#EBF5FB  '
    elif row.values[0] == '09:10':
        color = '#FEF9E7  '
    elif row.values[0] == '09:40':
        color = '#EBF5FB  '
    elif row.values[0] == '10:10':
        color = '#FEF9E7  '
    elif row.values[0] == '10:40':
        color = '#EBF5FB  '
    elif row.values[0] == '11:10':
        color = '#FEF9E7  '
    elif row.values[0] == '11:40':
        color = '#EBF5FB  '
    elif row.values[0] == '12:10':
        color = '#FEF9E7  '
    elif row.values[0] == '12:40':
        color = '#EBF5FB  '
    elif row.values[0] == '13:10':
        color = '#FEF9E7  '
    elif row.values[0] == '13:40':
        color = '#EBF5FB  '
    elif row.values[0] == '14:10':
        color = '#FEF9E7  '
    elif row.values[0] == '14:40':
        color = '#EBF5FB  '
    elif row.values[0] == '15:10':
        color = '#FEF9E7  '
    elif row.values[0] == '15:40':
        color = '#EBF5FB  '
    elif row.values[0] == '16:10':
        color = '#FEF9E7  '
    elif row.values[0] == '16:40':
        color = '#EBF5FB  '
    elif row.values[0] == '17:10':
        color = '#FEF9E7  '
    elif row.values[0] == '17:40':
        color = '#EBF5FB  '
    elif row.values[0] == '18:10':
        color = '#FEF9E7  '
    elif row.values[0] == '18:40':
        color = '#EBF5FB  '
    elif row.values[0] == '19:10':
        color = '#FEF9E7  '
    elif row.values[0] == '19:40':
        color = '#EBF5FB  '
    elif row.values[0] == '20:10':
        color = '#FEF9E7  '
    elif row.values[0] == '20:40':
        color = '#EBF5FB  '
    elif row.values[0] == '21:10':
        color = '#FEF9E7  '
    elif row.values[0] == '21:40':
        color = '#EBF5FB  '
    elif row.values[0] == '22:10':
        color = '#FEF9E7  '
    elif row.values[0] == '22:40':
        color = '#EBF5FB  '
    elif row.values[0] == '23:10':
        color = '#FEF9E7  '
    elif row.values[0] == '23:40':
        color = '#EBF5FB  '
    elif row.values[0] == 'Thursday 12-October-2017':
        color = '#FDEDEC  '
    elif row.values[0] == 'Thursday 13-October-2017':
        color = '#EAFAF1'
    return ['background-color: %s' % color]*len(row.values)

dataframe_spotovi = dataframe_spotovi.style.apply(EPP_Break_boja, axis=1)
dataframe_spotovi

Body:
what about the following approach:

In [112]: colors=['#EBF5FB  ','#FEF9E7  ']

In [113]: df
Out[113]:
    Time title     x
0  06:40     a  2011
1  06:40     b  2010
2  07:10     c  2000
3  08:10     d  1983

In [114]: df.assign(col=np.take(colors, df.groupby('Time').ngroup() % 2))
Out[114]:
    Time title     x        col
0  06:40     a  2011  #EBF5FB
1  06:40     b  2010  #EBF5FB
2  07:10     c  2000  #FEF9E7
3  08:10     d  1983  #EBF5FB


问:
Multiple triggers for a jquery-click-event
Sorry for that simple question, but how do I add multiple triggers to a jquery-click-event?

I tried that one here

```<code>$("#trigger1","#trigger2").click(function() {
    //something
});
</code>```

But that doesn't work. What is the correct syntax there?

答:
The reason why your code is not working is you are using a context selector. So what it is saying is: Find #trigger2 and inside of that look for #trigger1.

But what you want is to use a multiple selector.

```<code>$("#trigger1, #trigger2").click( ... )
</code>```

Or I would just use a common class so you do not have to keep track of the ids

```<code>$(".commonClass").click( ... )
</code>```

Body:
Sorry for that simple question, but how do I add multiple triggers to a jquery-click-event?

I tried that one here

$("#trigger1","#trigger2").click(function() {
    //something
});

But that doesn't work. What is the correct syntax there?

Body:
The reason why your code is not working is you are using a context selector. So what it is saying is: Find #trigger2 and inside of that look for #trigger1.

But what you want is to use a multiple selector.

$("#trigger1, #trigger2").click( ... )

Or I would just use a common class so you do not have to keep track of the ids

$(".commonClass").click( ... )


问:
Already Answered Uncaught TypeError: state.concat is not a function error
I am following a tutorial for React and redux but at the end of the video I get an error even due I have the same code.

Uncaught TypeError: state.concat is not a function

Any help will be appreciate it!

//action is a parameter and the reducer is the function
//We will make change to the state based on the action (function)

//Function will be reducers
const cards = (state, action) => {
    switch (action.type){
        case 'ADD_CARD':
            let newCard = Object.assign({}, action.data, {
                score: 1,
                id: +new Date
            });
//error is here
            return state.concat([newCard]);
        default:
            return state || {};
    }

};

//Redux helper function to pass reducer functions
const store = Redux.createStore(Redux.combineReducers({
    cards: cards
}));

//Keep an eye on the store for changes
store.subscribe(() => {
    console.log(store.getState());
});

//activate store action
store.dispatch({
    type: 'ADD_CARD',
    data: {
        front: 'front',
        back: 'back'
    }
});

//Another action
store.dispatch({
    type: 'ADD_CARD',
    data: {}
});```

答:
try this code </p>

```<code>const cards = (state = [], action) => {
    switch (action.type){
        case 'ADD_CARD':
            let newCard = Object.assign({}, action.data, {
                score: 1,
                id: +new Date
            });
            //error is here
            return state.concat(newCard);
        default:
            return state || {};
    }
};
</code>```

Body:
try this code

const cards = (state = [], action) => {
    switch (action.type){
        case 'ADD_CARD':
            let newCard = Object.assign({}, action.data, {
                score: 1,
                id: +new Date
            });
            //error is here
            return state.concat(newCard);
        default:
            return state || {};
    }
};


问:
Notepad++ Keyboard Language just Changed
Notepad++ suddenly changed its keyboard settings, which now means it thinks I use a English keyboard, although I have a Nowegian keyboard.

To this end, for instance shift + 2 becomes @, as opposed to " whcih it should be.

How do I reset this?

Thanks!

答: Press ALT+SHIFT. That could happen if you try to make rectangular selections...</p>


问:
Effective way to copy file in linux using C++?
How to efficiently copy file in linux using C++?
Is there any syscalls/standard libraries that allow file copying without making loops?</p>

答:
assuming argv[1] is the filename source and argv[2] is the filename dest:

```<code>#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>

int wid;
if(fork() == 0) {
    execve("/bin/cp", &argv[1], NULL);
    exit(-1);
}
wait(&wid);
</code>```

What this does is fork the program and in the child execute the cp binary
For more information on the functions used:

```<code>man 2 fork
man 2 execve
man 2 wait
</code>```

Body:
assuming argv[1] is the filename source and argv[2] is the filename dest:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>

int wid;
if(fork() == 0) {
    execve("/bin/cp", &argv[1], NULL);
    exit(-1);
}
wait(&wid);

What this does is fork the program and in the child execute the cp binary
For more information on the functions used:

man 2 fork
man 2 execve
man 2 wait


问:
Using alias inside a class instead of declaring a new class
I have a complex event args class in a webservice

```<code>public partial class PROJECT.WCF.MyActionCompletedEventArgs
{
...
};
</code>```

Now I have a class that wraps this web service in some way

```<code>public class WebserviceCtrl
{
...
</code>```

Now I want to add my own handler with the same event args already defined. So I want a using alias (like a typedef in C++) inside the class like this:

```<code>public class WebserviceCtrl
{
  using ActionCompletedEventArgs = PROJECT.WCF.MyActionCompletedEventArgs;
  ...
</code>```

But I get a syntax error directly in front of the using statement. I can use this using statement directly in front of the class declaration (inside a namespace). It doesn't matter where I place this statement inside the class definition.

I know about the possibilities of declaring my own ActionCompletedEventArgs class, but in this case I have to provide specific constructors and forces me to write specific constructors that aren't "needed", if I just use an alias...
 So I don't want to declare my own class!

I already studied the C# using documentation, but I could find any information about this.

My question is, why can't I use using classx = classy; inside my class?

答:
Aliases only apply to the current file (or the current namespace scope within the current file), and they do not exist in the compiled output. Just like the other using statements that "include" a namespace.

There's no reason to place them elsewhere at all, it would just make code harder to read.

Body:
I have a complex event args class in a webservice

public partial class PROJECT.WCF.MyActionCompletedEventArgs
{
...
};

Now I have a class that wraps this web service in some way

public class WebserviceCtrl
{
...

Now I want to add my own handler with the same event args already defined. So I want a using alias (like a typedef in C++) inside the class like this:

public class WebserviceCtrl
{
  using ActionCompletedEventArgs = PROJECT.WCF.MyActionCompletedEventArgs;
  ...

But I get a syntax error directly in front of the using statement. I can use this using statement directly in front of the class declaration (inside a namespace). It doesn't matter where I place this statement inside the class definition.

I know about the possibilities of declaring my own ActionCompletedEventArgs class, but in this case I have to provide specific constructors and forces me to write specific constructors that aren't "needed", if I just use an alias...
 So I don't want to declare my own class!

I already studied the C# using documentation, but I could find any information about this.

My question is, why can't I use using classx = classy; inside my class?


问:
Implicit sharing for custom classes in Qt
The implicit sharing is an interesting feature of Qt value container classes, so having custom implicitly shared classes would be a great in case of performance and memory usage, i am figuring out how to implementing it.

For a custom class containing some POD members and Qt value type members the implicit sharing would be automatically available for each member which is a Qt value types such as QString, QByteArray and ...

In this approach, the problem is the each member has its specific sharedPtr and reference count, for a big object with more than 50 implicitly shared members, it think its a loss of performance to check the reference count of each object independently  (for detaching)
From my point of view, its better to make whole object implicitly shared, which reduces the total memory consumption and operations needed for shared classes.

From COW (Copy on Write) point of view, this approach is better because the COW will be performed on smaller granularity, how ever for read only objects it doesn't worth much

Q1:
Can anyone explain me the drawback and advantages of implicitly sharing of custom class containing large number of members (>50)

Q2:
As far as i know, the implicitly shared class will benefits from SharedData Class inside Qt namespace, so is it possible to have a custom implicitly shared class at all ?! what about Qt type members inside custom class?
I don't mean move semantics of C++11 which is already known, the Qt one is more powerful

答:
The drawbacks and advantages of implicit sharing for classes containing a large number of members depends on the size of the said members. And they are exactly the same as for other classes like QString. You pay a constant time for the reference counting for each write operation, but you do not have to pay for the deep copy (memory allocation, member variable constructor calls, etc.), at least not immediately. Whether or not you should pay for reference counting, depend on your use case: if you make a lot of read only copy of a large data set, then implicit sharing will boost your performance, but if you make a lot of copy of small objects that will be written to, there is no point to implicit sharing.

QSharedData and QSharedDataPointer are useful tools, but you are free to use any other implementation of copy-on-write for your own classes. Even if they contain Qt classes.

Also do not compare move semantics and copy-on-write, they do different things.