问:
How do you promote innovation in your organization?
Innovation seems to be a Buzz word these days. Each organization is giving a lot of emphasis on it and at the same time it is also becoming the most abusive word. Every new thing is not an innovation. In my organization also there is a drive started to promote the innovation culture and some how i got involved in that.

I want to know how do you promote an Innovative culture. Are there some verified ways which drive people to think in that way.  I am looking for an answer that tells me how I can motivate people and give them some direction so that they stretch their imagination and come up with new ideas.

答:
Innovation is necessary going forward to achieve personal as well as organization growth.

Why Innovation is buzzword now days?
Answer : Because

1. Cost cutting is not way to achieve growth or profits. Today world is at point where too much cost cutting is done to make profit.

2. Product and services life cycle is shortened due to fierce competition. Only innovative products and services lead in market. But to remain competitive we have innovate whenever there is degrowth.

3. Technological and business model changes opened up new ways to perform certain task. It creates technological innovation and business model innovation.

LastEditorDisplayName: Rich B


来源: stackexchange

问:
how to convert Hijari date into Gregorian date in javascript?
I am using intalio editor in that I want to convert the Hijri date into a Gregorian date or vice-versa. we write code in javascript using jsx3 so please help me.</p>

答: Try dojox.date.islamic</p>

ContentLicense: CC BY-SA 4.0

Body: Try dojox.date.islamic

ContentLicense: CC BY-SA 2.5


问:
Why instantiate a new list before recursion call?
```<code>public void dfsSearch (TreeNode root, List<String> curr, List<List<String>> res) {
        curr.add(String.valueOf(root.val));
        // a leaf node has been reached
        if (root.left == null && root.right == null) {
            res.add(curr);
            return;
        }
        if (root.left != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.left, temp, res);
        }
        if (root.right != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.right, temp, res);
        }
    }
</code>```

The code above is a a method using dfs to find all the paths from root to leaves in a binary tree, and my question is, in the two lines above the recursive call, why do I need to instantiate a new list and pass this temp list (temp) to the recursive call, why can't I just use the curr (the argument in the function)?

答: Concurrent Modification is one reason.  But additionally, the algorithm collects "all paths" from root to leaves in the List of Lists result.  If you didn't create new lists at each level on the recursive way down, you would end up with one big jumbled list after the recursion bubbles back up (all paths from root to leaves collected in one mixed list instead of each path in its own list).</p>

ContentLicense: CC BY-SA 3.0

Body:
public void dfsSearch (TreeNode root, List<String> curr, List<List<String>> res) {
        curr.add(String.valueOf(root.val));
        // a leaf node has been reached
        if (root.left == null && root.right == null) {
            res.add(curr);
            return;
        }
        if (root.left != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.left, temp, res);
        }
        if (root.right != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.right, temp, res);
        }
    }

The code above is a a method using dfs to find all the paths from root to leaves in a binary tree, and my question is, in the two lines above the recursive call, why do I need to instantiate a new list and pass this temp list (temp) to the recursive call, why can't I just use the curr (the argument in the function)?


问:
How do I change the distance between text and underline in TimePicker?
There is currently 12 pixels between the text and underline for timepicker and I want to set it to 7 pixels.

```<code><materialDesign:TimePicker  SelectedTime="{Binding LabCase.AptTime}" />
</code>```

In resource dictionary I have made these changes to style:

```<code><Style TargetType="materialDesign:TimePicker" BasedOn="{StaticResource {x:Type materialDesign:TimePicker}}">
     <Setter Property="HorizontalAlignment" Value="Left" />
     <Setter Property="MinWidth" Value="200" />
     <Setter Property="materialDesign:HintAssist.Hint" Value="" />
     <Setter Property="Margin" Value="0,-3,0,0" />
</Style>
</code>```

Padding didn't work

```<code><Setter Property="Padding" Value="0,7,0,0"/>
</code>```

https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/blob/master/MaterialDesignThemes.Wpf/Themes/MaterialDesignTheme.TimePicker.xaml

It seems like margin is the problem but I can't see to override it when I can override everything else

答:
You will have to override this whole control template:

```<code><Style TargetType="materialDesign:TimePicker" BasedOn="{StaticResource {x:Type materialDesign:TimePicker}}">
     <Setter Property="HorizontalAlignment" Value="Left" />
     <Setter Property="MinWidth" Value="200" />
     <Setter Property="materialDesign:HintAssist.Hint" Value="" />
<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type wpf:TimePicker}">
                    <ControlTemplate.Resources>
                        <ControlTemplate x:Key="TextBoxTemplate" TargetType="{x:Type TextBox}">
                            <Grid>
                                <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"
                                              />
                                <wpf:SmartHint x:Name="Hint"
                                               FontSize="{TemplateBinding FontSize}"
                                               UseFloating="{Binding Path=(wpf:HintAssist.IsFloating), RelativeSource={RelativeSource TemplatedParent}}"
                                               Hint="{Binding Path=(wpf:HintAssist.Hint), RelativeSource={RelativeSource TemplatedParent}}"
                                               HintProxy="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={x:Static converters:HintProxyFabricConverter.Instance}}"
                                               HintOpacity="{Binding Path=(wpf:HintAssist.HintOpacity), RelativeSource={RelativeSource TemplatedParent}}"/>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition SourceName="Hint" Property="IsContentNullOrEmpty" Value="False" />
                                        <Condition Property="IsKeyboardFocused" Value="True" />
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="Hint" Property="Foreground" Value="{DynamicResource PrimaryHueMidBrush}" />
                                    <Setter TargetName="Hint" Property="HintOpacity" Value="1" />
                                </MultiTrigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                        <ControlTemplate x:Key="DropDownButtonTemplate" TargetType="{x:Type Button}">
                            <Grid Background="Transparent">
                                <VisualStateManager.VisualStateGroups>
                                    <VisualStateGroup x:Name="CommonStates">
                                        <VisualStateGroup.Transitions>
                                            <VisualTransition GeneratedDuration="0"/>
                                            <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                                            <VisualTransition GeneratedDuration="0:0:0.1" To="Pressed"/>
                                        </VisualStateGroup.Transitions>
                                        <VisualState x:Name="Normal"/>
                                        <VisualState x:Name="MouseOver"/>
                                        <VisualState x:Name="Pressed"/>
                                        <VisualState x:Name="Disabled"/>
                                    </VisualStateGroup>
                                </VisualStateManager.VisualStateGroups>
                                <Viewbox>
                                    <Canvas Width="24" Height="24">
                                        <Path Data="M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M12.5,7V12.25L17,14.92L16.25,16.15L11,13V7H12.5Z" Fill="{TemplateBinding Foreground}" />
                                    </Canvas>
                                </Viewbox>
                            </Grid>
                        </ControlTemplate>
                    </ControlTemplate.Resources>
                    <Grid x:Name="TemplateRoot">
                        <Border BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Background="{TemplateBinding Background}"
                                x:Name="border"
                                Padding="0 4 0 4"
                                SnapsToDevicePixels="True">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="Auto" />
                                </Grid.ColumnDefinitions>
                                <TextBox BorderThickness="0" x:Name="PART_TextBox"
                                         wpf:TextFieldAssist.TextBoxViewMargin=".5 0 0 0"
                                         Margin="0"
                                         Template="{StaticResource TextBoxTemplate}"
                                         />
                                <Button Grid.Column="1" Foreground="{TemplateBinding BorderBrush}" Focusable="False" HorizontalAlignment="Right" Margin="4 0 0 -3" Grid.Row="0" Padding="0"
                                        x:Name="PART_Button"
                                        Height="17">
                                        Template="{StaticResource DropDownButtonTemplate}" />
                                <Popup x:Name="PART_Popup" AllowsTransparency="True"
                                       Placement="Custom"
                                       CustomPopupPlacementCallback="{x:Static wpf:CustomPopupPlacementCallbackHelper.LargePopupCallback}"
                                       PlacementTarget="{Binding ElementName=PART_TextBox}" StaysOpen="False"
                                       PopupAnimation="Fade"/>
                            </Grid>
                        </Border>
                        <wpf:Underline x:Name="Underline" Visibility="{Binding Path=(wpf:TextFieldAssist.DecorationVisibility), RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" TargetName="TemplateRoot" Value="0.56"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}"/>
                        </Trigger>
                        <Trigger Property="IsKeyboardFocusWithin" Value="true">
                            <Setter Property="IsActive" TargetName="Underline" Value="True"/>
                            <Setter Property="BorderBrush"  Value="{DynamicResource PrimaryHueMidBrush}"/>
                        </Trigger>
                        <Trigger Property="Validation.HasError" Value="true">
                            <Setter Property="BorderBrush" Value="{DynamicResource ValidationErrorBrush}"/>
                            <Setter TargetName="Underline" Property="Background" Value="{DynamicResource ValidationErrorBrush}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Inside the template you should ovveride Button with name x:Name="PART_Button"  ( for exmaple Height="17" ) or TextBox nearest to the button or x:Name="border"padding property.

Body:
There is currently 12 pixels between the text and underline for timepicker and I want to set it to 7 pixels.

<materialDesign:TimePicker  SelectedTime="{Binding LabCase.AptTime}" />

In resource dictionary I have made these changes to style:

Padding didn't work

<Setter Property="Padding" Value="0,7,0,0"/>

https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/blob/master/MaterialDesignThemes.Wpf/Themes/MaterialDesignTheme.TimePicker.xaml

It seems like margin is the problem but I can't see to override it when I can override everything else

Body:
You will have to override this whole control template:

<Style TargetType="materialDesign:TimePicker" BasedOn="{StaticResource {x:Type materialDesign:TimePicker}}">
     <Setter Property="HorizontalAlignment" Value="Left" />
     <Setter Property="MinWidth" Value="200" />
     <Setter Property="materialDesign:HintAssist.Hint" Value="" />
<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type wpf:TimePicker}">
                    <ControlTemplate.Resources>
                        <ControlTemplate x:Key="TextBoxTemplate" TargetType="{x:Type TextBox}">
                            <Grid>
                                <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"
                                              />
                                <wpf:SmartHint x:Name="Hint"
                                               FontSize="{TemplateBinding FontSize}"
                                               UseFloating="{Binding Path=(wpf:HintAssist.IsFloating), RelativeSource={RelativeSource TemplatedParent}}"
                                               Hint="{Binding Path=(wpf:HintAssist.Hint), RelativeSource={RelativeSource TemplatedParent}}"
                                               HintProxy="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={x:Static converters:HintProxyFabricConverter.Instance}}"
                                               HintOpacity="{Binding Path=(wpf:HintAssist.HintOpacity), RelativeSource={RelativeSource TemplatedParent}}"/>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition SourceName="Hint" Property="IsContentNullOrEmpty" Value="False" />
                                        <Condition Property="IsKeyboardFocused" Value="True" />
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="Hint" Property="Foreground" Value="{DynamicResource PrimaryHueMidBrush}" />
                                    <Setter TargetName="Hint" Property="HintOpacity" Value="1" />
                                </MultiTrigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                        <ControlTemplate x:Key="DropDownButtonTemplate" TargetType="{x:Type Button}">
                            <Grid Background="Transparent">
                                <VisualStateManager.VisualStateGroups>
                                    <VisualStateGroup x:Name="CommonStates">
                                        <VisualStateGroup.Transitions>
                                            <VisualTransition GeneratedDuration="0"/>
                                            <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                                            <VisualTransition GeneratedDuration="0:0:0.1" To="Pressed"/>
                                        </VisualStateGroup.Transitions>
                                        <VisualState x:Name="Normal"/>
                                        <VisualState x:Name="MouseOver"/>
                                        <VisualState x:Name="Pressed"/>
                                        <VisualState x:Name="Disabled"/>
                                    </VisualStateGroup>
                                </VisualStateManager.VisualStateGroups>
                                <Viewbox>
                                    <Canvas Width="24" Height="24">
                                        <Path Data="M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M12.5,7V12.25L17,14.92L16.25,16.15L11,13V7H12.5Z" Fill="{TemplateBinding Foreground}" />
                                    </Canvas>
                                </Viewbox>
                            </Grid>
                        </ControlTemplate>
                    </ControlTemplate.Resources>
                    <Grid x:Name="TemplateRoot">
                        <Border BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Background="{TemplateBinding Background}"
                                x:Name="border"
                                Padding="0 4 0 4"
                                SnapsToDevicePixels="True">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="Auto" />
                                </Grid.ColumnDefinitions>
                                <TextBox BorderThickness="0" x:Name="PART_TextBox"
                                         wpf:TextFieldAssist.TextBoxViewMargin=".5 0 0 0"
                                         Margin="0"
                                         Template="{StaticResource TextBoxTemplate}"
                                         />
                                <Button Grid.Column="1" Foreground="{TemplateBinding BorderBrush}" Focusable="False" HorizontalAlignment="Right" Margin="4 0 0 -3" Grid.Row="0" Padding="0"
                                        x:Name="PART_Button"
                                        Height="17">
                                        Template="{StaticResource DropDownButtonTemplate}" />
                                <Popup x:Name="PART_Popup" AllowsTransparency="True"
                                       Placement="Custom"
                                       CustomPopupPlacementCallback="{x:Static wpf:CustomPopupPlacementCallbackHelper.LargePopupCallback}"
                                       PlacementTarget="{Binding ElementName=PART_TextBox}" StaysOpen="False"
                                       PopupAnimation="Fade"/>
                            </Grid>
                        </Border>
                        <wpf:Underline x:Name="Underline" Visibility="{Binding Path=(wpf:TextFieldAssist.DecorationVisibility), RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" TargetName="TemplateRoot" Value="0.56"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}"/>
                        </Trigger>
                        <Trigger Property="IsKeyboardFocusWithin" Value="true">
                            <Setter Property="IsActive" TargetName="Underline" Value="True"/>
                            <Setter Property="BorderBrush"  Value="{DynamicResource PrimaryHueMidBrush}"/>
                        </Trigger>
                        <Trigger Property="Validation.HasError" Value="true">
                            <Setter Property="BorderBrush" Value="{DynamicResource ValidationErrorBrush}"/>
                            <Setter TargetName="Underline" Property="Background" Value="{DynamicResource ValidationErrorBrush}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Inside the template you should ovveride Button with name x:Name="PART_Button"  ( for exmaple Height="17" ) or TextBox nearest to the button or x:Name="border"padding property.


问:
Setting a date on the x axis of a graph with matplotlib + tkinter
Having alot of trouble finding a solution that works when trying to put dates along the xaxis. Im not pulling any data from the internet, all of it is coming from a notepad file at the moment. Many of the solutions i have found give me errors, and the youtube videos i have watched explaining how to do this, all draw in information i think by using urllib.

```<code>Fig = Figure(figsize=(10,4), dpi=80)
a = Fig.add_subplot(111)
Fig.subplots_adjust(left=0.1, right=0.974, top=0.9, bottom=0.1)
Fig.patch.set_visible(False)
a.title.set_text('Graph')
a.set_xlabel('Date')
a.set_ylabel('Cost (GBP)')
</code>```

the code above is the code i currently have to make the graph, before it get overwritten using the code below.

```<code>  def animate_graph(self, i):
    pullData = open('financeData.txt','r').read()
    dataList = pullData.split('\n')
    xAxisList = []
    yAxisList = []
    taxList = []
    outgoingsList = []
    for eachLine in dataList:
      if len(eachLine) > 1:
        x, y, o= eachLine.split(',')
        xAxisList.append(int(x))
        yAxisList.append(int(y))
        intY = int(y)
        taxGraphData = intY * TAXRATE
        taxList.append(taxGraphData)
        outgoingsList.append(int(o))
    a.clear()
    a.plot(xAxisList, yAxisList, label='Profits line', color='green')
    a.plot(xAxisList, outgoingsList, label='Outgoings line')
    a.plot(xAxisList, taxList, label='Tax line')
    a.title.set_text('Pyraknight Finance Graph')
    a.set_xlabel('Date')
    a.set_ylabel('Cost (GBP)')
    a.legend()
</code>```

And then to place the graph onto my frame i have used the code below

```<code>canvas = FigureCanvasTkAgg(Fig, graphFrame)
canvas.show()
canvas.get_tk_widget().grid(row=0,column=0,padx=10,pady=10,sticky='nsew')

self.ani = animation.FuncAnimation (Fig, self.animate_graph, interval=1000)
</code>```

THese are the libraries im importing:

```<code>#importing tkinter libraries
import tkinter as tk
from tkinter.ttk import Combobox,Treeview,Scrollbar

#importing matplotlib libraries
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
import matplotlib.dates as mdates

#Other libraries
import hashlib
import sqlite3
import os
import time
import datetime
</code>```

How would i go about adding dates to my x axis? Thanks in advance, Nas

答:
I'm currently using this

```<code>import datetime

ax = plt.gca()
plt.gcf().autofmt_xdate(rotation=30)
#stepsize = 2592000 # 30 days
#stepsize = 864000 # 10 days
stepsize = 86400 # 1 day
#stepsize = 3600 # 1 hour
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange((end - end%3600), start, -stepsize))
def timestamp(x, pos):
        return (datetime.datetime.fromtimestamp(x)).strftime('%Y-%m-%d')
        #return (datetime.datetime.fromtimestamp(x)).strftime('%m/%d %H:%M')
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(timestamp))
</code>```

This will plot one labeled tick on every day counting from most recent whole hour back in time.

samples:

reference:

http://strftime.org/

http://matplotlib.org/api/ticker_api.html

http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter

http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.autofmt_xdate

http://matplotlib.org/devdocs/api/_as_gen/matplotlib.axis.XAxis.set_ticks.html

Body:
Having alot of trouble finding a solution that works when trying to put dates along the xaxis. Im not pulling any data from the internet, all of it is coming from a notepad file at the moment. Many of the solutions i have found give me errors, and the youtube videos i have watched explaining how to do this, all draw in information i think by using urllib.

Fig = Figure(figsize=(10,4), dpi=80)
a = Fig.add_subplot(111)
Fig.subplots_adjust(left=0.1, right=0.974, top=0.9, bottom=0.1)
Fig.patch.set_visible(False)
a.title.set_text('Graph')
a.set_xlabel('Date')
a.set_ylabel('Cost (GBP)')

the code above is the code i currently have to make the graph, before it get overwritten using the code below.

  def animate_graph(self, i):
    pullData = open('financeData.txt','r').read()
    dataList = pullData.split('\n')
    xAxisList = []
    yAxisList = []
    taxList = []
    outgoingsList = []
    for eachLine in dataList:
      if len(eachLine) > 1:
        x, y, o= eachLine.split(',')
        xAxisList.append(int(x))
        yAxisList.append(int(y))
        intY = int(y)
        taxGraphData = intY * TAXRATE
        taxList.append(taxGraphData)
        outgoingsList.append(int(o))
    a.clear()
    a.plot(xAxisList, yAxisList, label='Profits line', color='green')
    a.plot(xAxisList, outgoingsList, label='Outgoings line')
    a.plot(xAxisList, taxList, label='Tax line')
    a.title.set_text('Pyraknight Finance Graph')
    a.set_xlabel('Date')
    a.set_ylabel('Cost (GBP)')
    a.legend()

And then to place the graph onto my frame i have used the code below

canvas = FigureCanvasTkAgg(Fig, graphFrame)
canvas.show()
canvas.get_tk_widget().grid(row=0,column=0,padx=10,pady=10,sticky='nsew')

self.ani = animation.FuncAnimation (Fig, self.animate_graph, interval=1000)

THese are the libraries im importing:

#importing tkinter libraries
import tkinter as tk
from tkinter.ttk import Combobox,Treeview,Scrollbar

#importing matplotlib libraries
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
import matplotlib.dates as mdates

#Other libraries
import hashlib
import sqlite3
import os
import time
import datetime

How would i go about adding dates to my x axis? Thanks in advance, Nas

Body:
I'm currently using this

import datetime

ax = plt.gca()
plt.gcf().autofmt_xdate(rotation=30)
#stepsize = 2592000 # 30 days
#stepsize = 864000 # 10 days
stepsize = 86400 # 1 day
#stepsize = 3600 # 1 hour
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange((end - end%3600), start, -stepsize))
def timestamp(x, pos):
        return (datetime.datetime.fromtimestamp(x)).strftime('%Y-%m-%d')
        #return (datetime.datetime.fromtimestamp(x)).strftime('%m/%d %H:%M')
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(timestamp))

This will plot one labeled tick on every day counting from most recent whole hour back in time.

samples:

reference:

http://strftime.org/

http://matplotlib.org/api/ticker_api.html

http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter

http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.autofmt_xdate

http://matplotlib.org/devdocs/api/_as_gen/matplotlib.axis.XAxis.set_ticks.html


问:
Python parse output of mixed format text file to key value pair dictionaries
I am trying to parse the output of a command from the EMC OneFS CLI. We are trying to collect inventory data, and since we're on an older version of the API we can't use the REST SDK.

Instead we have decided to do it the "hacky" way and parse the output of CLI commands.

How can I reliably parse this data in Python, given the varying formats of text? Notice the varying amounts of white space, and the fact that some of these are separated by : while others are separated by =.

I have a decent start on this, I was able to split up each line into a list and handle the cases where the = sign is nested within parenthesis.

I am still stuck on the other parts:

Take the first column as the "hostname"

Build a separate dictionary for each hostname that contains all key value pairs (some are separated by : others are separated by =)

RAW OUTPUT THAT NEEDS TO BE PARSED:

```<code>visi-91:   SerNo: S123456789P
visi-91:  Config: 912-111-231
visi-91:   Class: storage
visi-91:  Series: x_series
visi-91: Product: IQ 32000x-ssd
visi-91: Comps:  Chassis CPU     Motherboard     NVRam   FlashDrive      Disk_Controller Disk_Expander   Power_Supplies
visi-91:   HWGen: MaunaLoa (MaunaLoa Hardware)
visi-91: Chassis: ISI36 (Isilon (CIDesigns) 36-Bay Chassis)
visi-91:     CPU: GenuineIntel (2.33GHz, stepping 0x0001067a)
visi-91:    PROC: Dual-proc, Quad-core
visi-91:     RAM: 17150812160 Bytes
visi-91:    Mobo: SupMicX7DBU (SuperMicro X7DBU Motherboard)
visi-91:   NVRam: MT25208 (Mellanox 25208 based Card) (492MB card) (size 515899392B)
visi-91: FlshDrv: None (No physical dongle supported) ((null))
visi-91:  DskCtl: LSI3081E-HBA (LSI SAS3081E SAS Controller -- HBA) (8 ports)
visi-91:  DskExp: VIT7156 (Vitesse 7156 Disk Expander)
visi-91: PwrSupl: PS1 (type=Emerson, fw=v.01.00.00)
visi-91: PwrSupl: PS2 (type=Emerson, fw=v.01.00.00)
visi-91: ChasCnt: 1 (Single-Chassis System)
visi-91:   NetIF: em*4,ib*2 (4x Intel, 2x IB)
visi-91:  IBType: ISI25208 (Isilon MT25208-based IB Card)
visi-91:  LCDver: NoriVFD (Noritake VFD)
visi-91:     IMB: Board Version 0x20f
visi-91: Power Supplies OK
visi-91: CPU Operation (raw 0x882F0000)  = Normal
visi-91: CPU Speed Limit                 = 100.00%
visi-91: Chassis Fan1 (ISI F1)           = 7469
visi-91: Chassis Fan2 (ISI F2)           = 7552
visi-91: Chassis Fan3 (ISI F3)           = 7387
visi-91: Power Supply 1 Fan              = 5504
visi-91: Power Supply 2 Fan              = 5792
visi-91: Temp Until CPU Throttle (CPU 0) = 46.0
visi-91: Temp Until CPU Throttle (CPU 1) = 42.0
visi-91: Temp Front Panel                = 17.0
visi-91: Temp Chassis 2 (ISI T2)         = 22.0
visi-91: Temp System                     = 25.0
visi-92:   SerNo: S123456785K
visi-92:  Config: 912-111-231
visi-92:   Class: storage
visi-92:  Series: x_series
visi-92: Product: IQ 32000x-ssd
visi-92: Comps:  Chassis CPU     Motherboard     NVRam   FlashDrive      Disk_Controller Disk_Expander   Power_Supplies
visi-92:   HWGen: MaunaLoa (MaunaLoa Hardware)
visi-92: Chassis: ISI36 (Isilon (CIDesigns) 36-Bay Chassis)
visi-92:     CPU: GenuineIntel (2.33GHz, stepping 0x0001067a)
visi-92:    PROC: Dual-proc, Quad-core
visi-92:     RAM: 17150812160 Bytes
visi-92:    Mobo: SupMicX7DBU (SuperMicro X7DBU Motherboard)
visi-92:   NVRam: MT25208 (Mellanox 25208 based Card) (492MB card) (size 515899392B)
visi-92: FlshDrv: None (No physical dongle supported) ((null))
visi-92:  DskCtl: LSI3081E-HBA (LSI SAS3081E SAS Controller -- HBA) (8 ports)
visi-92:  DskExp: VIT7156 (Vitesse 7156 Disk Expander)
visi-92: PwrSupl: PS1 (type=Emerson, fw=v.01.00.00)
visi-92: PwrSupl: PS2 (type=Emerson, fw=v.01.00.00)
visi-92: ChasCnt: 1 (Single-Chassis System)
visi-92:   NetIF: em*4,ib*2 (4x Intel, 2x IB)
visi-92:  IBType: ISI25208 (Isilon MT25208-based IB Card)
visi-92:  LCDver: NoriVFD (Noritake VFD)
visi-92:     IMB: Board Version 0x20f
visi-92: Power Supplies OK
visi-92: CPU Operation (raw 0x882E0000)  = Normal
visi-92: CPU Speed Limit                 = 100.00%
visi-92: Chassis Fan1 (ISI F1)           = 7268
visi-92: Chassis Fan2 (ISI F2)           = 7307
visi-92: Chassis Fan3 (ISI F3)           = 7190
visi-92: Power Supply 1 Fan              = 5376
visi-92: Power Supply 2 Fan              = 5696
visi-92: Temp Until CPU Throttle (CPU 0) = 46.0
visi-92: Temp Until CPU Throttle (CPU 1) = 46.0
visi-92: Temp Front Panel                = 17.2
visi-92: Temp Chassis 2 (ISI T2)         = 24.0
visi-92: Temp System                     = 27.0
visi-93:   SerNo: S987654321P
visi-93:  Config: 912-111-231
visi-93:   Class: storage
visi-93:  Series: x_series
visi-93: Product: IQ 32000x-ssd
visi-93: Comps:  Chassis CPU     Motherboard     NVRam   FlashDrive      Disk_Controller Disk_Expander   Power_Supplies
visi-93:   HWGen: MaunaLoa (MaunaLoa Hardware)
visi-93: Chassis: ISI36 (Isilon (CIDesigns) 36-Bay Chassis)
visi-93:     CPU: GenuineIntel (2.33GHz, stepping 0x0001067a)
visi-93:    PROC: Dual-proc, Quad-core
visi-93:     RAM: 17150812160 Bytes
visi-93:    Mobo: SupMicX7DBU (SuperMicro X7DBU Motherboard)
visi-93:   NVRam: MT25208 (Mellanox 25208 based Card) (492MB card) (size 515899392B)
visi-93: FlshDrv: None (No physical dongle supported) ((null))
visi-93:  DskCtl: LSI3081E-HBA (LSI SAS3081E SAS Controller -- HBA) (8 ports)
visi-93:  DskExp: VIT7156 (Vitesse 7156 Disk Expander)
visi-93: PwrSupl: PS1 (type=Emerson, fw=v.03.05.00)
visi-93: PwrSupl: PS2 (type=Emerson, fw=v.03.05.00)
visi-93: ChasCnt: 1 (Single-Chassis System)
visi-93:   NetIF: em*4,ib*2 (4x Intel, 2x IB)
visi-93:  IBType: ISI25208 (Isilon MT25208-based IB Card)
visi-93:  LCDver: NoriVFD (Noritake VFD)
visi-93:     IMB: Board Version 0x20f
visi-93: Power Supplies OK
visi-93: CPU Operation (raw 0x88250000)  = Normal
visi-93: CPU Speed Limit                 = 100.00%
visi-93: Chassis Fan1 (ISI F1)           = 7387
visi-93: Chassis Fan2 (ISI F2)           = 7152
visi-93: Chassis Fan3 (ISI F3)           = 7152
visi-93: Power Supply 1 Fan              = 8512
visi-93: Power Supply 2 Fan              = 8512
visi-93: Temp Until CPU Throttle (CPU 0) = 37.0
visi-93: Temp Until CPU Throttle (CPU 1) = 38.0
visi-93: Temp Front Panel                = 17.4
visi-93: Temp Chassis 2 (ISI T2)         = 25.0
visi-93: Temp System                     = 28.0
</code>```

MY CODE SO FAR:

```<code>#Read text file
file = open("test_itry.txt", "r")
lines = file.readlines()
file.close()

for line in lines:
    #Remove whitespaces
    line = line.replace(' ','')
    #Remove newlines
    line = line.replace('\n','')
    #Handler values that have equals signs nested within parenthesis
    #If line has closed parenthesis and equals sign
    if line.count(")") > 0 and line.count("=") > 0:
        #Get first position of open parenthesis
        poscp = line.find(")")
        #Get first position of equals sign
        poseq = line.find("=")
        #If position of equals sign comes before position of first parenthesis
        if poscp < poseq:
            #Split by first equals sign
            line = line.split("=", 1)
    #If line doesn't have closed parenthesis and an equals sign
    else:
        line = line.split("=", 1)
    #If line has not been split into a list yet create a list
    if isinstance(line, str):
        line = line.split()
    print(line)
</code>```

OUTPUT OF MY CODE SO FAR:

```<code>['visi-91:SerNo:S123456789P']
['visi-91:Config:912-111-231']
['visi-91:Class:storage']
['visi-91:Series:x_series']
['visi-91:Product:IQ32000x-ssd']
['visi-91:Comps:ChassisCPUMotherboardNVRamFlashDriveDisk_ControllerDisk_ExpanderPower_Supplies']
['visi-91:HWGen:MaunaLoa(MaunaLoaHardware)']
['visi-91:Chassis:ISI36(Isilon(CIDesigns)36-BayChassis)']
['visi-91:CPU:GenuineIntel(2.33GHz,stepping0x0001067a)']
['visi-91:PROC:Dual-proc,Quad-core']
['visi-91:RAM:17150812160Bytes']
['visi-91:Mobo:SupMicX7DBU(SuperMicroX7DBUMotherboard)']
['visi-91:NVRam:MT25208(Mellanox25208basedCard)(492MBcard)(size515899392B)']
['visi-91:FlshDrv:None(Nophysicaldonglesupported)((null))']
['visi-91:DskCtl:LSI3081E-HBA(LSISAS3081ESASController--HBA)(8ports)']
['visi-91:DskExp:VIT7156(Vitesse7156DiskExpander)']
['visi-91:PwrSupl:PS1(type=Emerson,fw=v.01.00.00)']
['visi-91:PwrSupl:PS2(type=Emerson,fw=v.01.00.00)']
['visi-91:ChasCnt:1(Single-ChassisSystem)']
['visi-91:NetIF:em*4,ib*2(4xIntel,2xIB)']
['visi-91:IBType:ISI25208(IsilonMT25208-basedIBCard)']
['visi-91:LCDver:NoriVFD(NoritakeVFD)']
['visi-91:IMB:BoardVersion0x20f']
['visi-91:PowerSuppliesOK']
['visi-91:CPUOperation(raw0x882F0000)', 'Normal']
['visi-91:CPUSpeedLimit', '100.00%']
['visi-91:ChassisFan1(ISIF1)', '7469']
['visi-91:ChassisFan2(ISIF2)', '7552']
['visi-91:ChassisFan3(ISIF3)', '7387']
['visi-91:PowerSupply1Fan', '5504']
['visi-91:PowerSupply2Fan', '5792']
['visi-91:TempUntilCPUThrottle(CPU0)', '46.0']
['visi-91:TempUntilCPUThrottle(CPU1)', '42.0']
['visi-91:TempFrontPanel', '17.0']
['visi-91:TempChassis2(ISIT2)', '22.0']
['visi-91:TempSystem', '25.0']
['visi-92:SerNo:S123456785K']
['visi-92:Config:912-111-231']
['visi-92:Class:storage']
['visi-92:Series:x_series']
['visi-92:Product:IQ32000x-ssd']
['visi-92:Comps:ChassisCPUMotherboardNVRamFlashDriveDisk_ControllerDisk_ExpanderPower_Supplies']
['visi-92:HWGen:MaunaLoa(MaunaLoaHardware)']
['visi-92:Chassis:ISI36(Isilon(CIDesigns)36-BayChassis)']
['visi-92:CPU:GenuineIntel(2.33GHz,stepping0x0001067a)']
['visi-92:PROC:Dual-proc,Quad-core']
['visi-92:RAM:17150812160Bytes']
['visi-92:Mobo:SupMicX7DBU(SuperMicroX7DBUMotherboard)']
['visi-92:NVRam:MT25208(Mellanox25208basedCard)(492MBcard)(size515899392B)']
['visi-92:FlshDrv:None(Nophysicaldonglesupported)((null))']
['visi-92:DskCtl:LSI3081E-HBA(LSISAS3081ESASController--HBA)(8ports)']
['visi-92:DskExp:VIT7156(Vitesse7156DiskExpander)']
['visi-92:PwrSupl:PS1(type=Emerson,fw=v.01.00.00)']
['visi-92:PwrSupl:PS2(type=Emerson,fw=v.01.00.00)']
['visi-92:ChasCnt:1(Single-ChassisSystem)']
['visi-92:NetIF:em*4,ib*2(4xIntel,2xIB)']
['visi-92:IBType:ISI25208(IsilonMT25208-basedIBCard)']
['visi-92:LCDver:NoriVFD(NoritakeVFD)']
['visi-92:IMB:BoardVersion0x20f']
['visi-92:PowerSuppliesOK']
['visi-92:CPUOperation(raw0x882E0000)', 'Normal']
['visi-92:CPUSpeedLimit', '100.00%']
['visi-92:ChassisFan1(ISIF1)', '7268']
['visi-92:ChassisFan2(ISIF2)', '7307']
['visi-92:ChassisFan3(ISIF3)', '7190']
['visi-92:PowerSupply1Fan', '5376']
['visi-92:PowerSupply2Fan', '5696']
['visi-92:TempUntilCPUThrottle(CPU0)', '46.0']
['visi-92:TempUntilCPUThrottle(CPU1)', '46.0']
['visi-92:TempFrontPanel', '17.2']
['visi-92:TempChassis2(ISIT2)', '24.0']
['visi-92:TempSystem', '27.0']
['visi-93:SerNo:S987654321P']
['visi-93:Config:912-111-231']
['visi-93:Class:storage']
['visi-93:Series:x_series']
['visi-93:Product:IQ32000x-ssd']
['visi-93:Comps:ChassisCPUMotherboardNVRamFlashDriveDisk_ControllerDisk_ExpanderPower_Supplies']
['visi-93:HWGen:MaunaLoa(MaunaLoaHardware)']
['visi-93:Chassis:ISI36(Isilon(CIDesigns)36-BayChassis)']
['visi-93:CPU:GenuineIntel(2.33GHz,stepping0x0001067a)']
['visi-93:PROC:Dual-proc,Quad-core']
['visi-93:RAM:17150812160Bytes']
['visi-93:Mobo:SupMicX7DBU(SuperMicroX7DBUMotherboard)']
['visi-93:NVRam:MT25208(Mellanox25208basedCard)(492MBcard)(size515899392B)']
['visi-93:FlshDrv:None(Nophysicaldonglesupported)((null))']
['visi-93:DskCtl:LSI3081E-HBA(LSISAS3081ESASController--HBA)(8ports)']
['visi-93:DskExp:VIT7156(Vitesse7156DiskExpander)']
['visi-93:PwrSupl:PS1(type=Emerson,fw=v.03.05.00)']
['visi-93:PwrSupl:PS2(type=Emerson,fw=v.03.05.00)']
['visi-93:ChasCnt:1(Single-ChassisSystem)']
['visi-93:NetIF:em*4,ib*2(4xIntel,2xIB)']
['visi-93:IBType:ISI25208(IsilonMT25208-basedIBCard)']
['visi-93:LCDver:NoriVFD(NoritakeVFD)']
['visi-93:IMB:BoardVersion0x20f']
['visi-93:PowerSuppliesOK']
['visi-93:CPUOperation(raw0x88250000)', 'Normal']
['visi-93:CPUSpeedLimit', '100.00%']
['visi-93:ChassisFan1(ISIF1)', '7387']
['visi-93:ChassisFan2(ISIF2)', '7152']
['visi-93:ChassisFan3(ISIF3)', '7152']
['visi-93:PowerSupply1Fan', '8512']
['visi-93:PowerSupply2Fan', '8512']
['visi-93:TempUntilCPUThrottle(CPU0)', '37.0']
['visi-93:TempUntilCPUThrottle(CPU1)', '38.0']
['visi-93:TempFrontPanel', '17.4']
['visi-93:TempChassis2(ISIT2)', '25.0']
['visi-93:TempSystem', '28.0']
</code>```

DESIRED OUTPUT - Dictionary key/value pairs with first word as hostname.
Separate dictionaries for each hostname:

```<code>{'hostname':'visi-91', 'SerNo':'S123456789P', 'Config':'912-111-231', 'Class':'storage', 'Series':'x_series', 'PwrSupl':'PS1(type=Emerson,fw=v.01.00.00)', 'Chassis':'ISI36(Isilon(CIDesigns)36-BayChassis)', 'NetIF':'em*4,ib*2(4xIntel,2xIB)', 'IBType':'ISI25208(IsilonMT25208-basedIBCard)'} //etc...

{'hostname':'visi-92', 'SerNo':'S123456785K', 'Config':'912-111-231', 'Class':'storage', 'Series':'x_series', 'PwrSupl':'PS1(type=Emerson,fw=v.01.00.00)' 'Chassis':'ISI36(Isilon(CIDesigns)36-BayChassis)', 'NetIF':'em*4,ib*2(4xIntel,2xIB)', 'IBType':'ISI25208(IsilonMT25208-basedIBCard)'}  //etc...
</code>```

答:
You need to split each of those lines at colons.
Plop the first one into the dictionary as "hostname", then process the remaining ones in pairs.  Something like:

```<code>fields = line.split(':')
my_dict["hostname"] = field[0]
for pos in range(1, len(fields), 2):
    my_dict[field(pos)] = field(pos+1)
</code>```

That's the basic tactic; I'll leave implementation details to you.  :-)

Body:
I am trying to parse the output of a command from the EMC OneFS CLI. We are trying to collect inventory data, and since we're on an older version of the API we can't use the REST SDK.

Instead we have decided to do it the "hacky" way and parse the output of CLI commands.

How can I reliably parse this data in Python, given the varying formats of text? Notice the varying amounts of white space, and the fact that some of these are separated by : while others are separated by =.

I have a decent start on this, I was able to split up each line into a list and handle the cases where the = sign is nested within parenthesis.

I am still stuck on the other parts:

Take the first column as the "hostname"

Build a separate dictionary for each hostname that contains all key value pairs (some are separated by : others are separated by =)

RAW OUTPUT THAT NEEDS TO BE PARSED:

visi-91:   SerNo: S123456789P
visi-91:  Config: 912-111-231
visi-91:   Class: storage
visi-91:  Series: x_series
visi-91: Product: IQ 32000x-ssd
visi-91: Comps:  Chassis CPU     Motherboard     NVRam   FlashDrive      Disk_Controller Disk_Expander   Power_Supplies
visi-91:   HWGen: MaunaLoa (MaunaLoa Hardware)
visi-91: Chassis: ISI36 (Isilon (CIDesigns) 36-Bay Chassis)
visi-91:     CPU: GenuineIntel (2.33GHz, stepping 0x0001067a)
visi-91:    PROC: Dual-proc, Quad-core
visi-91:     RAM: 17150812160 Bytes
visi-91:    Mobo: SupMicX7DBU (SuperMicro X7DBU Motherboard)
visi-91:   NVRam: MT25208 (Mellanox 25208 based Card) (492MB card) (size 515899392B)
visi-91: FlshDrv: None (No physical dongle supported) ((null))
visi-91:  DskCtl: LSI3081E-HBA (LSI SAS3081E SAS Controller -- HBA) (8 ports)
visi-91:  DskExp: VIT7156 (Vitesse 7156 Disk Expander)
visi-91: PwrSupl: PS1 (type=Emerson, fw=v.01.00.00)
visi-91: PwrSupl: PS2 (type=Emerson, fw=v.01.00.00)
visi-91: ChasCnt: 1 (Single-Chassis System)
visi-91:   NetIF: em*4,ib*2 (4x Intel, 2x IB)
visi-91:  IBType: ISI25208 (Isilon MT25208-based IB Card)
visi-91:  LCDver: NoriVFD (Noritake VFD)
visi-91:     IMB: Board Version 0x20f
visi-91: Power Supplies OK
visi-91: CPU Operation (raw 0x882F0000)  = Normal
visi-91: CPU Speed Limit                 = 100.00%
visi-91: Chassis Fan1 (ISI F1)           = 7469
visi-91: Chassis Fan2 (ISI F2)           = 7552
visi-91: Chassis Fan3 (ISI F3)           = 7387
visi-91: Power Supply 1 Fan              = 5504
visi-91: Power Supply 2 Fan              = 5792
visi-91: Temp Until CPU Throttle (CPU 0) = 46.0
visi-91: Temp Until CPU Throttle (CPU 1) = 42.0
visi-91: Temp Front Panel                = 17.0
visi-91: Temp Chassis 2 (ISI T2)         = 22.0
visi-91: Temp System                     = 25.0
visi-92:   SerNo: S123456785K
visi-92:  Config: 912-111-231
visi-92:   Class: storage
visi-92:  Series: x_series
visi-92: Product: IQ 32000x-ssd
visi-92: Comps:  Chassis CPU     Motherboard     NVRam   FlashDrive      Disk_Controller Disk_Expander   Power_Supplies
visi-92:   HWGen: MaunaLoa (MaunaLoa Hardware)
visi-92: Chassis: ISI36 (Isilon (CIDesigns) 36-Bay Chassis)
visi-92:     CPU: GenuineIntel (2.33GHz, stepping 0x0001067a)
visi-92:    PROC: Dual-proc, Quad-core
visi-92:     RAM: 17150812160 Bytes
visi-92:    Mobo: SupMicX7DBU (SuperMicro X7DBU Motherboard)
visi-92:   NVRam: MT25208 (Mellanox 25208 based Card) (492MB card) (size 515899392B)
visi-92: FlshDrv: None (No physical dongle supported) ((null))
visi-92:  DskCtl: LSI3081E-HBA (LSI SAS3081E SAS Controller -- HBA) (8 ports)
visi-92:  DskExp: VIT7156 (Vitesse 7156 Disk Expander)
visi-92: PwrSupl: PS1 (type=Emerson, fw=v.01.00.00)
visi-92: PwrSupl: PS2 (type=Emerson, fw=v.01.00.00)
visi-92: ChasCnt: 1 (Single-Chassis System)
visi-92:   NetIF: em*4,ib*2 (4x Intel, 2x IB)
visi-92:  IBType: ISI25208 (Isilon MT25208-based IB Card)
visi-92:  LCDver: NoriVFD (Noritake VFD)
visi-92:     IMB: Board Version 0x20f
visi-92: Power Supplies OK
visi-92: CPU Operation (raw 0x882E0000)  = Normal
visi-92: CPU Speed Limit                 = 100.00%
visi-92: Chassis Fan1 (ISI F1)           = 7268
visi-92: Chassis Fan2 (ISI F2)           = 7307
visi-92: Chassis Fan3 (ISI F3)           = 7190
visi-92: Power Supply 1 Fan              = 5376
visi-92: Power Supply 2 Fan              = 5696
visi-92: Temp Until CPU Throttle (CPU 0) = 46.0
visi-92: Temp Until CPU Throttle (CPU 1) = 46.0
visi-92: Temp Front Panel                = 17.2
visi-92: Temp Chassis 2 (ISI T2)         = 24.0
visi-92: Temp System                     = 27.0
visi-93:   SerNo: S987654321P
visi-93:  Config: 912-111-231
visi-93:   Class: storage
visi-93:  Series: x_series
visi-93: Product: IQ 32000x-ssd
visi-93: Comps:  Chassis CPU     Motherboard     NVRam   FlashDrive      Disk_Controller Disk_Expander   Power_Supplies
visi-93:   HWGen: MaunaLoa (MaunaLoa Hardware)
visi-93: Chassis: ISI36 (Isilon (CIDesigns) 36-Bay Chassis)
visi-93:     CPU: GenuineIntel (2.33GHz, stepping 0x0001067a)
visi-93:    PROC: Dual-proc, Quad-core
visi-93:     RAM: 17150812160 Bytes
visi-93:    Mobo: SupMicX7DBU (SuperMicro X7DBU Motherboard)
visi-93:   NVRam: MT25208 (Mellanox 25208 based Card) (492MB card) (size 515899392B)
visi-93: FlshDrv: None (No physical dongle supported) ((null))
visi-93:  DskCtl: LSI3081E-HBA (LSI SAS3081E SAS Controller -- HBA) (8 ports)
visi-93:  DskExp: VIT7156 (Vitesse 7156 Disk Expander)
visi-93: PwrSupl: PS1 (type=Emerson, fw=v.03.05.00)
visi-93: PwrSupl: PS2 (type=Emerson, fw=v.03.05.00)
visi-93: ChasCnt: 1 (Single-Chassis System)
visi-93:   NetIF: em*4,ib*2 (4x Intel, 2x IB)
visi-93:  IBType: ISI25208 (Isilon MT25208-based IB Card)
visi-93:  LCDver: NoriVFD (Noritake VFD)
visi-93:     IMB: Board Version 0x20f
visi-93: Power Supplies OK
visi-93: CPU Operation (raw 0x88250000)  = Normal
visi-93: CPU Speed Limit                 = 100.00%
visi-93: Chassis Fan1 (ISI F1)           = 7387
visi-93: Chassis Fan2 (ISI F2)           = 7152
visi-93: Chassis Fan3 (ISI F3)           = 7152
visi-93: Power Supply 1 Fan              = 8512
visi-93: Power Supply 2 Fan              = 8512
visi-93: Temp Until CPU Throttle (CPU 0) = 37.0
visi-93: Temp Until CPU Throttle (CPU 1) = 38.0
visi-93: Temp Front Panel                = 17.4
visi-93: Temp Chassis 2 (ISI T2)         = 25.0
visi-93: Temp System                     = 28.0

MY CODE SO FAR:

#Read text file
file = open("test_itry.txt", "r")
lines = file.readlines()
file.close()

for line in lines:
    #Remove whitespaces
    line = line.replace(' ','')
    #Remove newlines
    line = line.replace('\n','')
    #Handler values that have equals signs nested within parenthesis
    #If line has closed parenthesis and equals sign
    if line.count(")") > 0 and line.count("=") > 0:
        #Get first position of open parenthesis
        poscp = line.find(")")
        #Get first position of equals sign
        poseq = line.find("=")
        #If position of equals sign comes before position of first parenthesis
        if poscp < poseq:
            #Split by first equals sign
            line = line.split("=", 1)
    #If line doesn't have closed parenthesis and an equals sign
    else:
        line = line.split("=", 1)
    #If line has not been split into a list yet create a list
    if isinstance(line, str):
        line = line.split()
    print(line)

OUTPUT OF MY CODE SO FAR:

['visi-91:SerNo:S123456789P']
['visi-91:Config:912-111-231']
['visi-91:Class:storage']
['visi-91:Series:x_series']
['visi-91:Product:IQ32000x-ssd']
['visi-91:Comps:ChassisCPUMotherboardNVRamFlashDriveDisk_ControllerDisk_ExpanderPower_Supplies']
['visi-91:HWGen:MaunaLoa(MaunaLoaHardware)']
['visi-91:Chassis:ISI36(Isilon(CIDesigns)36-BayChassis)']
['visi-91:CPU:GenuineIntel(2.33GHz,stepping0x0001067a)']
['visi-91:PROC:Dual-proc,Quad-core']
['visi-91:RAM:17150812160Bytes']
['visi-91:Mobo:SupMicX7DBU(SuperMicroX7DBUMotherboard)']
['visi-91:NVRam:MT25208(Mellanox25208basedCard)(492MBcard)(size515899392B)']
['visi-91:FlshDrv:None(Nophysicaldonglesupported)((null))']
['visi-91:DskCtl:LSI3081E-HBA(LSISAS3081ESASController--HBA)(8ports)']
['visi-91:DskExp:VIT7156(Vitesse7156DiskExpander)']
['visi-91:PwrSupl:PS1(type=Emerson,fw=v.01.00.00)']
['visi-91:PwrSupl:PS2(type=Emerson,fw=v.01.00.00)']
['visi-91:ChasCnt:1(Single-ChassisSystem)']
['visi-91:NetIF:em*4,ib*2(4xIntel,2xIB)']
['visi-91:IBType:ISI25208(IsilonMT25208-basedIBCard)']
['visi-91:LCDver:NoriVFD(NoritakeVFD)']
['visi-91:IMB:BoardVersion0x20f']
['visi-91:PowerSuppliesOK']
['visi-91:CPUOperation(raw0x882F0000)', 'Normal']
['visi-91:CPUSpeedLimit', '100.00%']
['visi-91:ChassisFan1(ISIF1)', '7469']
['visi-91:ChassisFan2(ISIF2)', '7552']
['visi-91:ChassisFan3(ISIF3)', '7387']
['visi-91:PowerSupply1Fan', '5504']
['visi-91:PowerSupply2Fan', '5792']
['visi-91:TempUntilCPUThrottle(CPU0)', '46.0']
['visi-91:TempUntilCPUThrottle(CPU1)', '42.0']
['visi-91:TempFrontPanel', '17.0']
['visi-91:TempChassis2(ISIT2)', '22.0']
['visi-91:TempSystem', '25.0']
['visi-92:SerNo:S123456785K']
['visi-92:Config:912-111-231']
['visi-92:Class:storage']
['visi-92:Series:x_series']
['visi-92:Product:IQ32000x-ssd']
['visi-92:Comps:ChassisCPUMotherboardNVRamFlashDriveDisk_ControllerDisk_ExpanderPower_Supplies']
['visi-92:HWGen:MaunaLoa(MaunaLoaHardware)']
['visi-92:Chassis:ISI36(Isilon(CIDesigns)36-BayChassis)']
['visi-92:CPU:GenuineIntel(2.33GHz,stepping0x0001067a)']
['visi-92:PROC:Dual-proc,Quad-core']
['visi-92:RAM:17150812160Bytes']
['visi-92:Mobo:SupMicX7DBU(SuperMicroX7DBUMotherboard)']
['visi-92:NVRam:MT25208(Mellanox25208basedCard)(492MBcard)(size515899392B)']
['visi-92:FlshDrv:None(Nophysicaldonglesupported)((null))']
['visi-92:DskCtl:LSI3081E-HBA(LSISAS3081ESASController--HBA)(8ports)']
['visi-92:DskExp:VIT7156(Vitesse7156DiskExpander)']
['visi-92:PwrSupl:PS1(type=Emerson,fw=v.01.00.00)']
['visi-92:PwrSupl:PS2(type=Emerson,fw=v.01.00.00)']
['visi-92:ChasCnt:1(Single-ChassisSystem)']
['visi-92:NetIF:em*4,ib*2(4xIntel,2xIB)']
['visi-92:IBType:ISI25208(IsilonMT25208-basedIBCard)']
['visi-92:LCDver:NoriVFD(NoritakeVFD)']
['visi-92:IMB:BoardVersion0x20f']
['visi-92:PowerSuppliesOK']
['visi-92:CPUOperation(raw0x882E0000)', 'Normal']
['visi-92:CPUSpeedLimit', '100.00%']
['visi-92:ChassisFan1(ISIF1)', '7268']
['visi-92:ChassisFan2(ISIF2)', '7307']
['visi-92:ChassisFan3(ISIF3)', '7190']
['visi-92:PowerSupply1Fan', '5376']
['visi-92:PowerSupply2Fan', '5696']
['visi-92:TempUntilCPUThrottle(CPU0)', '46.0']
['visi-92:TempUntilCPUThrottle(CPU1)', '46.0']
['visi-92:TempFrontPanel', '17.2']
['visi-92:TempChassis2(ISIT2)', '24.0']
['visi-92:TempSystem', '27.0']
['visi-93:SerNo:S987654321P']
['visi-93:Config:912-111-231']
['visi-93:Class:storage']
['visi-93:Series:x_series']
['visi-93:Product:IQ32000x-ssd']
['visi-93:Comps:ChassisCPUMotherboardNVRamFlashDriveDisk_ControllerDisk_ExpanderPower_Supplies']
['visi-93:HWGen:MaunaLoa(MaunaLoaHardware)']
['visi-93:Chassis:ISI36(Isilon(CIDesigns)36-BayChassis)']
['visi-93:CPU:GenuineIntel(2.33GHz,stepping0x0001067a)']
['visi-93:PROC:Dual-proc,Quad-core']
['visi-93:RAM:17150812160Bytes']
['visi-93:Mobo:SupMicX7DBU(SuperMicroX7DBUMotherboard)']
['visi-93:NVRam:MT25208(Mellanox25208basedCard)(492MBcard)(size515899392B)']
['visi-93:FlshDrv:None(Nophysicaldonglesupported)((null))']
['visi-93:DskCtl:LSI3081E-HBA(LSISAS3081ESASController--HBA)(8ports)']
['visi-93:DskExp:VIT7156(Vitesse7156DiskExpander)']
['visi-93:PwrSupl:PS1(type=Emerson,fw=v.03.05.00)']
['visi-93:PwrSupl:PS2(type=Emerson,fw=v.03.05.00)']
['visi-93:ChasCnt:1(Single-ChassisSystem)']
['visi-93:NetIF:em*4,ib*2(4xIntel,2xIB)']
['visi-93:IBType:ISI25208(IsilonMT25208-basedIBCard)']
['visi-93:LCDver:NoriVFD(NoritakeVFD)']
['visi-93:IMB:BoardVersion0x20f']
['visi-93:PowerSuppliesOK']
['visi-93:CPUOperation(raw0x88250000)', 'Normal']
['visi-93:CPUSpeedLimit', '100.00%']
['visi-93:ChassisFan1(ISIF1)', '7387']
['visi-93:ChassisFan2(ISIF2)', '7152']
['visi-93:ChassisFan3(ISIF3)', '7152']
['visi-93:PowerSupply1Fan', '8512']
['visi-93:PowerSupply2Fan', '8512']
['visi-93:TempUntilCPUThrottle(CPU0)', '37.0']
['visi-93:TempUntilCPUThrottle(CPU1)', '38.0']
['visi-93:TempFrontPanel', '17.4']
['visi-93:TempChassis2(ISIT2)', '25.0']
['visi-93:TempSystem', '28.0']

DESIRED OUTPUT - Dictionary key/value pairs with first word as hostname.
Separate dictionaries for each hostname:

{'hostname':'visi-91', 'SerNo':'S123456789P', 'Config':'912-111-231', 'Class':'storage', 'Series':'x_series', 'PwrSupl':'PS1(type=Emerson,fw=v.01.00.00)', 'Chassis':'ISI36(Isilon(CIDesigns)36-BayChassis)', 'NetIF':'em*4,ib*2(4xIntel,2xIB)', 'IBType':'ISI25208(IsilonMT25208-basedIBCard)'} //etc...

{'hostname':'visi-92', 'SerNo':'S123456785K', 'Config':'912-111-231', 'Class':'storage', 'Series':'x_series', 'PwrSupl':'PS1(type=Emerson,fw=v.01.00.00)' 'Chassis':'ISI36(Isilon(CIDesigns)36-BayChassis)', 'NetIF':'em*4,ib*2(4xIntel,2xIB)', 'IBType':'ISI25208(IsilonMT25208-basedIBCard)'}  //etc...

Body:
You need to split each of those lines at colons.
Plop the first one into the dictionary as "hostname", then process the remaining ones in pairs.  Something like:

fields = line.split(':')
my_dict["hostname"] = field[0]
for pos in range(1, len(fields), 2):
    my_dict[field(pos)] = field(pos+1)

That's the basic tactic; I'll leave implementation details to you.  :-)


问:
Web service only let me get 1000 rows at a time but the total is over 30000
I am using some web services provided by Netsuite
https://system.netsuite.com/help/helpcenter/en_US/Output/Help/SuiteFlex/WebServices/STP_searchMore.html#1087957

It only let me get 1000 rows at a time and then I need to perform a second search for the next set of 1000 rows and so on. There's some example code but it only returns the second set of rows, I am not sure on how to get the third, fourth and so on.

My code so far is:

```<code>private void getAllCustomers()
{
    // Instantiate a search object for customers.
    CustomerSearch custSearch = new CustomerSearch();
    CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();

    // Search the customer status which is a list field (16,13,15)
    String statusKeysValue = "16,13,15";
    SearchMultiSelectField status = null;
    if (statusKeysValue != null && !statusKeysValue.Trim().Equals(""))
    {
        status = new SearchMultiSelectField();
        status.@operator = SearchMultiSelectFieldOperator.anyOf;
        status.operatorSpecified = true;
        string[] nskeys = statusKeysValue.Split(new Char[] { ',' });

        RecordRef[] recordRefs = new RecordRef[statusKeysValue.Length];
        for (int i = 0; i < nskeys.Length; i++)
        {
            RecordRef recordRef = new RecordRef();
            recordRef.internalId = nskeys[i];
            recordRefs[i] = recordRef;
        }
        status.searchValue = recordRefs;
        custSearchBasic.entityStatus = status;
    }

    custSearch.basic = custSearchBasic;

    // Invoke search() web services operation
    SearchResult response = _service.search(custSearch);

     // Process response
    if (response.status.isSuccess)
    {
        // Process the records returned in the response
        // Here I get the first 1000 records
        processGetAllCustomersResponse(response);

        // Since pagination controls what is returned, check to see
        // if there are anymore pages to retrieve.

        SearchResult seachMoreResult = searchMore(response);

        if (seachMoreResult != null)
        {
            // Process response
            if (seachMoreResult.status.isSuccess)
            {
                // Here I get the next 1000 records
                    processGetAllCustomersResponse(seachMoreResult);

                // My problem now is to get the third set of 1000 customers, then the fourth and so on till I got all 34500 something
            }
            else
            {

            }

        }
    }
    else
    {

    }
}

private SearchResult searchMore(SearchResult response)
{
    // Keep getting pages until there are no more pages to get
    while (response.totalRecords > (response.pageSize * response.pageIndex))
    {
        return _service.searchMore(response.pageIndex + 1);
    }

    return null;
}
</code>```

In processGetAllCustomersResponse I simply insert the rows in another database which works fine (apart from not getting all the rows I want).

答:
i have changed SearchMore function ,now it will return a list of all  responses , you need to change getAllCustomer function accordingly

EDIT : updated getAllCustomer Also

```<code> private void getAllCustomers()
    {
        // Instantiate a search object for customers.
        CustomerSearch custSearch = new CustomerSearch();
        CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();

        // Search the customer status which is a list field (16,13,15)
        String statusKeysValue = "16,13,15";
        SearchMultiSelectField status = null;
        if (statusKeysValue != null && !statusKeysValue.Trim().Equals(""))
        {
            status = new SearchMultiSelectField();
            status.@operator = SearchMultiSelectFieldOperator.anyOf;
            status.operatorSpecified = true;
            string[] nskeys = statusKeysValue.Split(new Char[] { ',' });

            RecordRef[] recordRefs = new RecordRef[statusKeysValue.Length];
            for (int i = 0; i < nskeys.Length; i++)
            {
                RecordRef recordRef = new RecordRef();
                recordRef.internalId = nskeys[i];
                recordRefs[i] = recordRef;
            }
            status.searchValue = recordRefs;
            custSearchBasic.entityStatus = status;
        }

        custSearch.basic = custSearchBasic;

        // Invoke search() web services operation
        SearchResult response = _service.search(custSearch);

        // Process response
        if (response.status.isSuccess)
        {
            // Process the records returned in the response
            // Here I get the first 1000 records
            processGetAllCustomersResponse(response);

            // Since pagination controls what is returned, check to see
            // if there are anymore pages to retrieve.

            List<SearchResult> seachMoreResult = searchMore(response);

            if (seachMoreResult != null)
            {
                foreach (SearchResult sr in seachMoreResult)
                {
                    if (sr.status.isSuccess)
                    {
                        // Here I get the next 1000 records
                        processGetAllCustomersResponse(sr);

                        // My problem now is to get the third set of 1000 customers, then the fourth and so on till I got all 34500 something
                    }
                    else
                    {

                    }
                }
                // Process response

            }
        }
        else
        {

        }
    }

private IEnumerable<SearchResult> searchMore(SearchResult response)
    {
        // Keep getting pages until there are no more pages to get
        int tempTotalRecords = response.totalRecords;
        int pageSize = response.pageSize * response.pageIndex;
        SearchResult tempResponse = null;
        List<SearchResult> records = new List<SearchResult>();
        while (tempTotalRecords > (pageSize))
        {
            SearchResult tempResponse = _service.searchMore(response.pageIndex + 1);

            if (tempResponse.totalRecords > tempResponse.pageSize * tempResponse.pageIndex)
            {
                tempTotalRecords = tempResponse.totalRecords;
                pageSize = tempResponse.pageSize * tempResponse.pageIndex;
                records.Add(response);
            }
            else
                records.Add(response);

        }

        return records;
    }
</code>```

Body:
I am using some web services provided by Netsuite
https://system.netsuite.com/help/helpcenter/en_US/Output/Help/SuiteFlex/WebServices/STP_searchMore.html#1087957

It only let me get 1000 rows at a time and then I need to perform a second search for the next set of 1000 rows and so on. There's some example code but it only returns the second set of rows, I am not sure on how to get the third, fourth and so on.

My code so far is:

private void getAllCustomers()
{
    // Instantiate a search object for customers.
    CustomerSearch custSearch = new CustomerSearch();
    CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();

    // Search the customer status which is a list field (16,13,15)
    String statusKeysValue = "16,13,15";
    SearchMultiSelectField status = null;
    if (statusKeysValue != null && !statusKeysValue.Trim().Equals(""))
    {
        status = new SearchMultiSelectField();
        status.@operator = SearchMultiSelectFieldOperator.anyOf;
        status.operatorSpecified = true;
        string[] nskeys = statusKeysValue.Split(new Char[] { ',' });

        RecordRef[] recordRefs = new RecordRef[statusKeysValue.Length];
        for (int i = 0; i < nskeys.Length; i++)
        {
            RecordRef recordRef = new RecordRef();
            recordRef.internalId = nskeys[i];
            recordRefs[i] = recordRef;
        }
        status.searchValue = recordRefs;
        custSearchBasic.entityStatus = status;
    }

    custSearch.basic = custSearchBasic;

    // Invoke search() web services operation
    SearchResult response = _service.search(custSearch);

     // Process response
    if (response.status.isSuccess)
    {
        // Process the records returned in the response
        // Here I get the first 1000 records
        processGetAllCustomersResponse(response);

        // Since pagination controls what is returned, check to see
        // if there are anymore pages to retrieve.

        SearchResult seachMoreResult = searchMore(response);

        if (seachMoreResult != null)
        {
            // Process response
            if (seachMoreResult.status.isSuccess)
            {
                // Here I get the next 1000 records
                    processGetAllCustomersResponse(seachMoreResult);

                // My problem now is to get the third set of 1000 customers, then the fourth and so on till I got all 34500 something
            }
            else
            {

            }

        }
    }
    else
    {

    }
}

private SearchResult searchMore(SearchResult response)
{
    // Keep getting pages until there are no more pages to get
    while (response.totalRecords > (response.pageSize * response.pageIndex))
    {
        return _service.searchMore(response.pageIndex + 1);
    }

    return null;
}

In processGetAllCustomersResponse I simply insert the rows in another database which works fine (apart from not getting all the rows I want).

Body:
i have changed SearchMore function ,now it will return a list of all  responses , you need to change getAllCustomer function accordingly

EDIT : updated getAllCustomer Also

 private void getAllCustomers()
    {
        // Instantiate a search object for customers.
        CustomerSearch custSearch = new CustomerSearch();
        CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();

        // Search the customer status which is a list field (16,13,15)
        String statusKeysValue = "16,13,15";
        SearchMultiSelectField status = null;
        if (statusKeysValue != null && !statusKeysValue.Trim().Equals(""))
        {
            status = new SearchMultiSelectField();
            status.@operator = SearchMultiSelectFieldOperator.anyOf;
            status.operatorSpecified = true;
            string[] nskeys = statusKeysValue.Split(new Char[] { ',' });

            RecordRef[] recordRefs = new RecordRef[statusKeysValue.Length];
            for (int i = 0; i < nskeys.Length; i++)
            {
                RecordRef recordRef = new RecordRef();
                recordRef.internalId = nskeys[i];
                recordRefs[i] = recordRef;
            }
            status.searchValue = recordRefs;
            custSearchBasic.entityStatus = status;
        }

        custSearch.basic = custSearchBasic;

        // Invoke search() web services operation
        SearchResult response = _service.search(custSearch);

        // Process response
        if (response.status.isSuccess)
        {
            // Process the records returned in the response
            // Here I get the first 1000 records
            processGetAllCustomersResponse(response);

            // Since pagination controls what is returned, check to see
            // if there are anymore pages to retrieve.

            List<SearchResult> seachMoreResult = searchMore(response);

            if (seachMoreResult != null)
            {
                foreach (SearchResult sr in seachMoreResult)
                {
                    if (sr.status.isSuccess)
                    {
                        // Here I get the next 1000 records
                        processGetAllCustomersResponse(sr);

                        // My problem now is to get the third set of 1000 customers, then the fourth and so on till I got all 34500 something
                    }
                    else
                    {

                    }
                }
                // Process response

            }
        }
        else
        {

        }
    }

private IEnumerable<SearchResult> searchMore(SearchResult response)
    {
        // Keep getting pages until there are no more pages to get
        int tempTotalRecords = response.totalRecords;
        int pageSize = response.pageSize * response.pageIndex;
        SearchResult tempResponse = null;
        List<SearchResult> records = new List<SearchResult>();
        while (tempTotalRecords > (pageSize))
        {
            SearchResult tempResponse = _service.searchMore(response.pageIndex + 1);

            if (tempResponse.totalRecords > tempResponse.pageSize * tempResponse.pageIndex)
            {
                tempTotalRecords = tempResponse.totalRecords;
                pageSize = tempResponse.pageSize * tempResponse.pageIndex;
                records.Add(response);
            }
            else
                records.Add(response);

        }

        return records;
    }


问:
Knockout doesn't use supplied view model instance
I have a knockout component that I add to the page. I am trying to call ko.applyBindings with an instance of the view model that I created. But knockout seems to ignore it and create its own instance.

Code:

```<code>ko.components.register("my-component", {viewModel: MyViewModel, template: "....."});
ko.applyBindings(new MyViewModel(this.config), document.getElementsByTagName("my-component")[0]);
</code>```

I have a console.log in the constructor of MyViewModel and I am seeing that two instances are created: One with the parameters I pass and one without. And knockout seems to be using the one without.

What am I doing wrong?

答:
Components actually have their own view models by design. You can, however, pass them an instance of a viewmodel you've created earlier:</p>

```<code>var myViewModel = new MyViewModel(this.config);
ko.components.register("my-component", { viewModel: { instance: myViewModel }});
ko.applyBindings(myViewModel);
</code>```

Body:
I have a knockout component that I add to the page. I am trying to call ko.applyBindings with an instance of the view model that I created. But knockout seems to ignore it and create its own instance.

Code:

ko.components.register("my-component", {viewModel: MyViewModel, template: "....."});
ko.applyBindings(new MyViewModel(this.config), document.getElementsByTagName("my-component")[0]);

I have a console.log in the constructor of MyViewModel and I am seeing that two instances are created: One with the parameters I pass and one without. And knockout seems to be using the one without.

What am I doing wrong?

Body:
Components actually have their own view models by design. You can, however, pass them an instance of a viewmodel you've created earlier:

var myViewModel = new MyViewModel(this.config);
ko.components.register("my-component", { viewModel: { instance: myViewModel }});
ko.applyBindings(myViewModel);


问:
Is it possible to retrieve data from a 3rd party App by my own Android app?
I'm too much of an android novice to comprehend the more detailed postings wrt this topic on stackoverflow, so I hope I can ask this simple yes/no question instead.
I have my own flashcard android app and (due to lack of translation APIs, a different story ...) I thought I could utilized a 3rd party dictionary app I have installed on my phone (this is just for me, not for productation, so no concern about how this scales to other phones/envs).
So it sounds like it might be possible to launch the 3rd party app from my app, but it doesn't sound possible to retrieve data from the 3rd party app and consume it in my own i.e. I would have to know the source code of the 3rd party app to understand intent and activity names (and its manifest ?)

So here's the naive/simple question, is it possible to simply launch the app, navigate to the page/activity I'm interested in (since I assume I can't jump directly to it since I don't know the details) and 'swipe/parse' the output of that app and return to my app ?

答:
Unless the other app has specifically taken that option into account and is ready to return something back to yours, no. You can't just read an arbitrary app or interact with it without permission. Which makes sense, think bank apps, email, and all sorts of personal information that could be leaked.

If the phone is rooted, as specified in the comments by @Gabe Sechan, you could read the files where they store their data, but that doesn't mean you could access their logic, for instance, with a dictionary app, it could mean that you may read cached translations if they stored those, but you'd still wouldn't be able to say here's this word, give it to me translated

Google does provide a translations API but I'm not sure if it will fit your needs.


问:
NativeScript TAB button double functionalaty
We need for our mobile application to bind two events on tab. When loaded it needs to load a page, and on click on the same button it needs to change the view.
The problem is that, when TAB page, when it is rendered, can't get another event handler when new page is inserted, if am not wrong. IONIC can achieve this functionality, but we need nativescript.

Any idea how?!

thnx

答:
To add any addition tap handlers that you want, is fairly simple in NativeScript.   I'm not sure I understand your question or use-case; but to add another tap handler (assuming you want the tap event)

You can use:
     element.on('tap', anotherTapHandler);

To get the element you can use the built in view.getViewById('id') or you can use a plugin like my Nativescript-Dom plugin (disclaimer: I'm the auther) to do things like getElementsByClassName('MyButton')[0].on('tap', anotherTapHandler);  or the additional helper functions that find all elements and run your function against each one...  runAgainstTagNames('Button', function(element) { element.on('tap', anotherTapHandler); });


问:
itertools.combinations_with_replacement() with regard to ordering
I need to produce, given an order and a max, a list of all 'order' length lists with each element in range(max). itertools.combinations_with_replacement() doesn't work because while it does give most, in an example where I want

```<code>max, order = 3, 2
[(0,0), (0,1), (0,2), (0,3), (1,0), (1,1), (1,2), (1,3), (2,0), (2,1), (2,2), (2,3), (3,0), (3,1), (3,2), (3,3)]
</code>```

the following code shorts me a few elements

```<code>list(itertools.combinations_with_replacement([x for x in range(max+1)], order))

[(0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)]
</code>```

specifically I need to know if there is an itertools, or other package that will give me the first list above. i.e. I need both (0,1) and (1,0). or in an order=3 case, (0, 0, 1) (0, 1, 0) and (1, 0, 0) will all need to be included

Body:
I need to produce, given an order and a max, a list of all 'order' length lists with each element in range(max). itertools.combinations_with_replacement() doesn't work because while it does give most, in an example where I want

max, order = 3, 2
[(0,0), (0,1), (0,2), (0,3), (1,0), (1,1), (1,2), (1,3), (2,0), (2,1), (2,2), (2,3), (3,0), (3,1), (3,2), (3,3)]

the following code shorts me a few elements

list(itertools.combinations_with_replacement([x for x in range(max+1)], order))

[(0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)]

specifically I need to know if there is an itertools, or other package that will give me the first list above. i.e. I need both (0,1) and (1,0). or in an order=3 case, (0, 0, 1) (0, 1, 0) and (1, 0, 0) will all need to be included

Body:
You are looking for itertools.product:

>>> max, order = 3, 2
>>> print(list(itertools.product(range(max + 1), repeat=order)))
[(0, 0), (0, 1), (0, 2), (0, 3),
 (1, 0), (1, 1), (1, 2), (1, 3),
 (2, 0), (2, 1), (2, 2), (2, 3),
 (3, 0), (3, 1), (3, 2), (3, 3)]


问:
Measure-object -average for values stored in percentage (%)
I'm familiar with using the "measure-object" function to count, and get averages, etc, however, i'm having some difficult using it to get the average based on data that's stored in csv as percentage (%)

```<code>Platform    Cap Used %
P1          0%
P2          18%
</code>```

I originally included logic in the script that generates the csv to save in % using the normal method "{0:P0}"

However, when i now try to run a measure-object -average on the "Cap Used %" array, i get the following error over and over again::

```<code>Measure : Input object "" is not numeric.
At line:1 char:36
+ $TempData | Select $_"Cap used %" |Measure -average
+                                    ~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidType: (:PSCustomObject) [Measure-
 Object],PSInvalidOperationException
            + FullyQualifiedErrorId  :NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand
</code>```

I'm able to sort the same data via the following code, but i'm not able to run it through measure-object -average

```<code>$TempData | Select {[int]($_."Cap Used %" -replace '%')}
</code>```

I could probably store the data without the %, but i'd rather keep it intact. Is there an ez way to sum a bunch of percentages and get the average %? When i import the data into excel and select the column, the expected average result is shown, so i know the data is good, however, i believe excel has some extra logic built into it to auto-detected the correct data format

any help is appreciated

答:
In general, when posting an example with xml or csv data, it is
  helpful to use here-strings to represent the data instead of
  referencing a file that others do not have.

Next code snippet returns 8 as expected.

```<code>$hereStr=@'
Platform,"Cap Used %"
P1,0%
P2,18%
P3,6%
'@

$TempData = $hereStr | ConvertFrom-Csv
(($TempData."Cap Used %").Replace('%','') | Measure-Object -Average).Average
</code>```

Body:
I'm familiar with using the "measure-object" function to count, and get averages, etc, however, i'm having some difficult using it to get the average based on data that's stored in csv as percentage (%)

Platform    Cap Used %
P1          0%
P2          18%

I originally included logic in the script that generates the csv to save in % using the normal method "{0:P0}"

However, when i now try to run a measure-object -average on the "Cap Used %" array, i get the following error over and over again::

Measure : Input object "" is not numeric.
At line:1 char:36
+ $TempData | Select $_"Cap used %" |Measure -average
+                                    ~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidType: (:PSCustomObject) [Measure-
 Object],PSInvalidOperationException
            + FullyQualifiedErrorId  :NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand

I'm able to sort the same data via the following code, but i'm not able to run it through measure-object -average

$TempData | Select {[int]($_."Cap Used %" -replace '%')}

I could probably store the data without the %, but i'd rather keep it intact. Is there an ez way to sum a bunch of percentages and get the average %? When i import the data into excel and select the column, the expected average result is shown, so i know the data is good, however, i believe excel has some extra logic built into it to auto-detected the correct data format

any help is appreciated

Body:
In general, when posting an example with xml or csv data, it is
  helpful to use here-strings to represent the data instead of
  referencing a file that others do not have.

Next code snippet returns 8 as expected.

$hereStr=@'
Platform,"Cap Used %"
P1,0%
P2,18%
P3,6%
'@

$TempData = $hereStr | ConvertFrom-Csv
(($TempData."Cap Used %").Replace('%','') | Measure-Object -Average).Average


问:
How to print the elements in odd positions in a list using an iterative function in Lisp?
I have to make a recursive function in lisp which takes a list and makes another list with only the elements on odd position in the given list.

If I have (1 2 3 4 5) I have to output (1 3 5)

I have a code here:

```<code>(defun pozpar(lst) (do(
(l lst (cddr l))
(x '() (cons x (car l))))
((null l) x)))
</code>```

This outputs:

```<code>(5 3 1)
</code>```

I know cons adds the elements at the beginning and I tried with append or list but nothing worked.

答:
With using loop it's very easy to get the elements in the order you processed them. It is also the most effective and the only one guaranteed to work with all length arguments:

```<code>(defun pozpar1 (lst)
  (loop :for e :in lst :by #'cddr
        :collect e)))
</code>```

If you really want recursion I would have done it with an accumulator with a linear update reverse in the end:

```<code>(defun pozpar2 (lst)
  (labels ((helper (lst acc)
             (if (endp lst)
                 (nreverse acc)
                 (helper (cddr lst) (cons (car lst) acc)))))
    (helper lst '())))
</code>```

However a classical not tail recursive version would look like this:

```<code>(defun pozpar3 (lst)
  (if (endp lst)
      '()
      (cons (car lst) (pozpar3 (cddr lst)))))
</code>```

Body:
I have to make a recursive function in lisp which takes a list and makes another list with only the elements on odd position in the given list.

If I have (1 2 3 4 5) I have to output (1 3 5)

I have a code here:

(defun pozpar(lst) (do(
(l lst (cddr l))
(x '() (cons x (car l))))
((null l) x)))

This outputs:

(5 3 1)

I know cons adds the elements at the beginning and I tried with append or list but nothing worked.

Body:
With using loop it's very easy to get the elements in the order you processed them. It is also the most effective and the only one guaranteed to work with all length arguments:

(defun pozpar1 (lst)
  (loop :for e :in lst :by #'cddr
        :collect e)))

If you really want recursion I would have done it with an accumulator with a linear update reverse in the end:

(defun pozpar2 (lst)
  (labels ((helper (lst acc)
             (if (endp lst)
                 (nreverse acc)
                 (helper (cddr lst) (cons (car lst) acc)))))
    (helper lst '())))

However a classical not tail recursive version would look like this:

(defun pozpar3 (lst)
  (if (endp lst)
      '()
      (cons (car lst) (pozpar3 (cddr lst)))))


问:
ordering a list of string according to name (month)
I have a list of figures and I want to create a text file (using python) with their names listed in a specific order (for a movie creation with mencoder). In particular here, the figure names include months (April, August...). I want the one for Januray first, then February and so on.

I know I could do it in an ugly way, but I am interested in a solution which would be both elegant (=pythonic?) and eventually more general.

My files are, in natural order:

cld_for_April_EISopt_1000.png

cld_for_August_EISopt_1000.png

cld_for_December_EISopt_1000.png

cld_for_February_EISopt_1000.png

cld_for_January_EISopt_1000.png

cld_for_July_EISopt_1000.png

cld_for_June_EISopt_1000.png

cld_for_March_EISopt_1000.png

cld_for_May_EISopt_1000.png

cld_for_November_EISopt_1000.png

cld_for_October_EISopt_1000.png

cld_for_September_EISopt_1000.png

And I want to have a text file with this inside:

cld_for_January_EISopt_1000.png

cld_for_February_EISopt_1000.png

cld_for_March_EISopt_1000.png

cld_for_April_EISopt_1000.png

cld_for_May_EISopt_1000.png

cld_for_June_EISopt_1000.png

cld_for_July_EISopt_1000.png

cld_for_August_EISopt_1000.png

cld_for_September_EISopt_1000.png

cld_for_October_EISopt_1000.png

cld_for_November_EISopt_1000.png

cld_for_December_EISopt_1000.png

Or more generally, if I have a list or an array or a dictionnay like:

{'pattern1': rank_in_output_list_1, ..., 'pattern12': rank_in_output_list_12}

how should I do to use it to order my file names?

So far I have played with: os.listdir, os.path.isfile, numpyp.ma.array, .compressed() or .compress() ; but I haven't been so successful.

Thanks a lot.

Christophe.

答:
As the key for the sort, split by _ and map the third element.

```<code>sorted(filenames, key=lambda x: monthdict[x.split('_')[2]])
</code>```

Body:
As the key for the sort, split by _ and map the third element.

sorted(filenames, key=lambda x: monthdict[x.split('_')[2]])


问:
Cannot publish a MongoDB collection from the server to client Meteor
I want to publish a sever side collection to the client side.

In Server Side

```<code>MedicalCenters = new Mongo.Collection('medicalCenters');

Meteor.publish('medicalCenters',function () {
    return MedicalCenters.find({});
});
</code>```

I want this collection only to be accessed by a particular template. Thefore,

In Client Side

```<code>Template.doctor.onCreated(function () {
    Meteor.subscribe('medicalCenters');
});
</code>```

Now I can pass the data from client side template and even write to the serve side collection. But it seems to be subscription did not work and therefore, I cannot display collection data in the template.
(The collection is not displayed in the meteortoys Mongol)

How do I fix this?

答:
Try adding a helper to send the data to the template:

```<code>Template.doctor.helpers({
  medicalcenters() {
    return MedicalCenters.find();
  }
});
</code>```

Then in your template you can loop through the medical centers

```<code><template name="doctor">
    {{#each medicalcenters}}
        {{name}}
    {{/each}}
</template>
</code>```

Body:
I want to publish a sever side collection to the client side.

In Server Side

MedicalCenters = new Mongo.Collection('medicalCenters');

Meteor.publish('medicalCenters',function () {
    return MedicalCenters.find({});
});

I want this collection only to be accessed by a particular template. Thefore,

In Client Side

Template.doctor.onCreated(function () {
    Meteor.subscribe('medicalCenters');
});

Now I can pass the data from client side template and even write to the serve side collection. But it seems to be subscription did not work and therefore, I cannot display collection data in the template.
(The collection is not displayed in the meteortoys Mongol)

How do I fix this?

Body:
Try adding a helper to send the data to the template:

Template.doctor.helpers({
  medicalcenters() {
    return MedicalCenters.find();
  }
});

Then in your template you can loop through the medical centers

<template name="doctor">
    {{#each medicalcenters}}
        {{name}}
    {{/each}}
</template>