# This file is covered by the BSD license. See LICENSE in the root directory.
from django import forms
from django.utils.safestring import mark_safe

from materials import models

class SearchForm(forms.Form):
    search_text = forms.CharField(label='Search term', max_length=100)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['search_text'].widget.attrs['class'] = 'form-control'

class AutoCharField(forms.CharField):
    """Like regular CharField but max_length is automatically determined."""
    def __init__(self, model=None, field=None, *args, **kwargs):
        if model:
            max_length = model._meta.get_field(field).max_length
        else:
            max_length = None
        super().__init__(required=False, max_length=max_length,
                         *args, **kwargs)

class AddReferenceForm(forms.Form):
    title = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Article title')
    journal = forms.CharField(
        label='Journal or Publisher',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Full name of the journal or publisher')
    vol = forms.CharField(
        required=False,
        label='Volume',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='')
    pages_start = forms.CharField(
        label='Starting page',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Number of the first page of the publication')
    pages_end = forms.CharField(
        label='Ending page',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Number of the last page of the publication')
    year = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Year of publication')
    doi_isbn = forms.CharField(
        required=False,
        label='DOI or ISBN',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Enter DOI or ISBN if applicable.')

class AddSystemForm(forms.Form):
    compound_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Compound name (most common name)')
    formula = forms.CharField(
        label='Chemical formula',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=200,
        help_text='Chemical formula')
    group = forms.CharField(
        required=False,
        label='Alternate names',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text=''
        'Please list all possible variations of this compound (besides '
        'those entered above), including different uses of parentheses - '
        'this makes the compound more easily searchable.')
    organic = forms.CharField(
        label='Organic component',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=100,
        help_text='Enter organic component')
    inorganic = forms.CharField(
        label='Inorganic component',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=100,
        help_text='Enter inorganic component')
    iupac = forms.CharField(
        label='IUPAC Name',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=100,
        help_text='Enter preffered IUPAC name (PIN)')
    description = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=1000,
        help_text='Description of the compound (optional)')
    related_systems = forms.CharField(
        label='Derived Systems',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
        'List of System IDs this system is directly derived from')
    dimensionality = forms.ChoiceField(
        initial=models.System.DIMENSIONALITIES[0],
        choices=(models.System.DIMENSIONALITIES),
        widget=forms.RadioSelect(),
        help_text=''
        'Enter the dimensionality of this system')
    n = forms.CharField(
        label='N',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=100,
        help_text='Enter n value for the dimensionality of this system if it applies')

class AddPropertyForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=100,
        help_text='Name of the physical property')
    method = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=100,
        help_text='Name of the method if applicable (no parentheses needed)',
        required=False,)

class AddUnitForm(forms.Form):
    label = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        max_length=100,
        help_text='Label of the unit')

class AddDataForm(forms.Form):
    """Main form for submitting data."""

    # Where to redirect after successfully submitting data
    return_url = forms.CharField(required=False, widget=forms.HiddenInput())
    # General
    related_data_sets = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
        'List of data set IDs directly related (linked) to this data (space '
        'separated). Two or more data sets can be linked if they are results '
        'of the same experiment or calculation but describe different '
        'physical properties (e.g., "band structure" and "band gap" or '
        '"absorption coefficient" and "absorption peak position"). Find the '
        'related data set IDs as "Data set ID" at the bottom of the data sets.'
    )
    select_reference = forms.ModelChoiceField(
        queryset=models.Reference.objects.all(),
        required=True,
        widget=forms.Select(attrs={'class': 'form-control'}),
        help_text=''
        'Select the reference that is associated with the inserted data.')
    # If set, the reference field becomes readonly.
    fixed_reference = forms.ModelChoiceField(
        queryset=models.Reference.objects.all(),
        required=False,
        widget=forms.HiddenInput())
    select_system = forms.ModelChoiceField(
        queryset=models.System.objects.all(),
        required=True,
        widget=forms.Select(attrs={'class': 'form-control'}),
        help_text=''
        'Select the system that is associated with the inserted data.')
    caption = AutoCharField(
        model=models.Dataset, field='caption',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
        'Main description of the data. This can include an explanation of the '
        'significance of the results.')
    extraction_method = AutoCharField(
        label='Data extraction protocol',
        model=models.Dataset, field='extraction_method',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
        'How was the current data obtained? For example, manually extracted '
        'from a publication, from author, from another database, ...')
    primary_property = forms.ModelChoiceField(
        queryset=models.Property.objects.all().order_by('name'),
        widget=forms.Select(attrs={'class': 'form-control'}),
        help_text=''
        'Define the primary property of interest (in a figure, this typically '
        'denotes the y-axis). If the property of interest is missing here, '
        'add it under "Define new property".')
    primary_unit = forms.ModelChoiceField(
        queryset=models.Unit.objects.all(),
        required=False,
        widget=forms.Select(attrs={'class': 'form-control',
                                   'disabled': 'true'}),
        help_text=''
        'Define the primary unit of interest. For dimensionless physical '
        'properties, leave empty. If the data is in arbitray units, select '
        '"a.u." (note that this is different from empty). If the unit of '
        'interest is missing here, add it under "Define new unit".')
    primary_property_label = AutoCharField(
        model=models.Dataset, field='primary_property_label',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Leave empty if not required'
        }),
        help_text=''
        'If present, this label is used on the y-axis of a figure. Default is '
        'to use the same name as the physical property.')
    secondary_property = forms.ModelChoiceField(
        queryset=models.Property.objects.all().order_by('name'),
        required=False,
        label='Secondary property (x-axis)',
        widget=forms.Select(attrs={'class': 'form-control'}),
        help_text=''
        'Define the secondary property of interest (in a figure, this '
        'typically denotes the x-axis). If the property of interest is '
        'missing here, add it under "Define new property".')
    secondary_unit = forms.ModelChoiceField(
        queryset=models.Unit.objects.all(),
        required=False,
        widget=forms.Select(attrs={'class': 'form-control',
                                   'disabled': 'true'}),
        help_text=''
        'Define the secondary unit of interest. If the unit of interest '
        'missing here, add it under "Define new unit".')
    secondary_property_label = AutoCharField(
        model=models.Dataset, field='secondary_property_label',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Leave empty if not required'
        }),
        help_text=''
        'If present, this label is used on the x-axis of a figure. Default is '
        'to use the same name as the physical property.')
    is_figure = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        required=False,
        help_text=''
        'Choose whether the data is more suitably presented as a figure or as '
        'a table. Especially for a large amount of data points, a figure '
        'might make more sense. This setting can be easily toggled later.')
    two_axes = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        initial=False,
        required=False,
        help_text=''
        'Select this if your data has independent (x) and dependent (y) '
        'variables.')
    visible_to_public = forms.BooleanField(
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        initial=True,
        required=False,
        help_text=''
        'Choose whether the data should be initially visible on the website. '
        'If not, only you can view the data. This setting can be easily '
        'toggled later.')
    origin_of_data = forms.ChoiceField(
        initial='is_experimental',
        choices=(
            ('is_experimental', 'experimental'),
            ('is_theoretical', 'theoretical'),
        ),
        widget=forms.RadioSelect(),
        help_text=''
        'Select whether the origin of data is experimental or theoretical.')
    dimensionality_of_the_inorganic_component = forms.ChoiceField(
        initial=models.Dataset.DIMENSIONALITIES[0],
        choices=(models.Dataset.DIMENSIONALITIES),
        widget=forms.RadioSelect(),
        help_text=''
        'Here the term dimensionality refers to the one typically used in the '
        'context of organic-inorganic perovskites (a certain arrangement of '
        'organic and inorganic components). This is not the standard '
        'definition of the dimensionality of a system (single crystal, '
        'film, ...). See "sample type" for that.')
    sample_type = forms.ChoiceField(
        initial=models.Dataset.SAMPLE_TYPES[0],
        choices=(models.Dataset.SAMPLE_TYPES),
        widget=forms.RadioSelect(),
        help_text='Select the type of the sample.')
    space_group = AutoCharField(
        model=models.Dataset, field='space_group',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Optional'
        }),
        help_text=''
        'Space group id. Refer to documentation for complete list.')

    # Synthesis
    with_synthesis_details = forms.BooleanField(
        required=False, initial=False, widget=forms.HiddenInput())
    starting_materials = AutoCharField(
        model=models.SynthesisMethod, field='starting_materials',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text='Specify the starting materials.')
    product = AutoCharField(
        model=models.SynthesisMethod, field='product',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text='Specify the final product of synthesis.')
    synthesis_description = AutoCharField(
        label='Description',
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}),
        help_text='Describe the steps of the synthesis process.')
    synthesis_comment = AutoCharField(
        label='Comments',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
        'Additional information not revelant or suitable for the description '
        'part.')

    # Experimental
    with_experimental_details = forms.BooleanField(
        required=False, initial=False, widget=forms.HiddenInput())
    experimental_method = AutoCharField(
        label='Method',
        model=models.ExperimentalDetails, field='method',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text='Short name of the method used, e.g., "X-ray diffraction".')
    experimental_description = AutoCharField(
        label='Description',
        model=models.ExperimentalDetails, field='description',
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}),
        help_text='Describe all experimental steps here.')
    experimental_comment = AutoCharField(
        label='Comments',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
        'Additional information not revelant or suitable for the description '
        'part.')

    # Computational
    with_computational_details = forms.BooleanField(
        required=False, initial=False, widget=forms.HiddenInput())
    code = AutoCharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Abinit, Quantum espresso...',
        }),
        help_text=''
        'Name of the code(s) used for calculations. It is recommended to also '
        'include other identifiers such as version number, branch name, or '
        'even the commit number if applicable.')
    level_of_theory = AutoCharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder':
            'DFT, Hartree-Fock, tight-binding, empirical model...',
        }),
        help_text=''
        'Level of theory summarizes the collection of physical approximations '
        'used in the calculation. It gives an overall picture of the physics '
        'involved. Finer details of the level of theory such as the level of '
        'relativity should be filled separately.')
    xc_functional = AutoCharField(
        label='Exchange-correlation functional',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'PBE, PW91...',
        }),
        help_text=''
        'Level of approximation used to treat the electron-electron '
        'interaction.')
    k_point_grid = AutoCharField(
        label='K-point grid',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '3x3x3, 4x5x4 (Monkhorst-Pack)...',
        }),
        help_text=''
        'Details of the k-point mesh.')
    level_of_relativity = AutoCharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder':
            'non-relativistic, atomic ZORA with SOC, Koelling-Harmon...',
        }),
        help_text=''
        'Specify the level of relativity. Note that this also includes the '
        'description of spin-orbit coupling!')
    basis_set_definition = AutoCharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'JTH PAW, TM PP with semicore...',
        }),
        help_text=''
        'Details of the basis set or of the algorithms directly related to '
        'the basis set. For example, in case of a plane wave calculation, '
        'also include details of the pseudopotential here if applicable.')
    numerical_accuracy = AutoCharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder':
            'SCF tol. 1 meV/atom, Lebedev grids for angular integration...',
        }),
        help_text=''
        'Include all parameters here that describe the accuracy of the '
        'calculation (tolerance parameters for an SCF cycle, quality of '
        'integration grids, number of excited states included, ...).')
    external_repositories = AutoCharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder':
            'http://dx.doi.org/00.00000/NOMAD/2000.01.30-5 ...',
        }),
        help_text=''
        'Provide link(s) to external repositories such as NOMAD, which host '
        'additional data related to the data entered here.')
    computational_comment = AutoCharField(
        label='Comments',
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
        'Additional information not revelant or suitable for the description '
        'part.')

    # Data subset
    number_of_subsets = forms.CharField(
        initial=1,
        widget=forms.NumberInput(attrs={'class': 'form-control mx-sm-3',
                                        'min': '1',
                                        'style': 'width:8em'}),
        help_text=''
        'Enter the number of data subgroups. For each subgroup, one or more '
        'properties or some other aspect of the experiment/calculation are '
        'typically fixed (see the help text for "Add fixed property"). In '
        'case of a figure, each curve is typically considered a separate data '
        'subset.')
    import_file_name = forms.CharField(
        required=False, widget=forms.HiddenInput())
    crystal_system = forms.ChoiceField(
        required=False,
        initial=models.Subset.CRYSTAL_SYSTEMS[0],
        choices=(models.Subset.CRYSTAL_SYSTEMS),
        widget=forms.RadioSelect(),
        help_text='Select the crystal system.')
    subset_label = AutoCharField(
        label='Label',
        model=models.Subset, field='label',
        widget=forms.TextInput(
            attrs={'class': 'form-control subset-label-class'}),
        help_text=''
        'Short description of the data subset (optional). In a figure, this '
        'information is typically shown in the legend. Not applicable with '
        'only one data subset set.')
    subset_datapoints = forms.CharField(
        required=False,
        label='Data points',
        widget=forms.Textarea(
            attrs={'class': 'form-control subset-datapoints', 'rows': '4',
                   'placeholder': 'value_1 value_2 ...'}),
        help_text=''
        'Insert data points here. These may be a single value, a series of '
        'values, or a series of value pairs. The latter applies when there '
        'are both primary and secondary properties, in which case the first '
        'column has values of the secondary property (x-values) and the '
        'second column corresponds to the primary property (y-values). Note: '
        'to resize this box, drag from the corner.')
    # Exceptions
    lattice_constant_a = forms.CharField(
        label='Lattice constants',
        required=False,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': 'a'}),
        help_text=''
        'Units of lattice constants are given by "Primary unit" above. When '
        'importing from file, two formats are allowed. In the first format, '
        'include "a", "b", "c", "alpha", "beta", and "gamma" followed by '
        'their respective values. This can be either on one line or on '
        'separate lines (e.g., "a val1 b val2 ..."). For the second format, '
        'see the help text of "Atomic coordinates" below.')
    lattice_constant_b = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': 'b'})
    )
    lattice_constant_c = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': 'c'})
    )
    lattice_constant_alpha = forms.CharField(
        label='Angles (deg)',
        required=False,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': 'α'})
    )
    lattice_constant_beta = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': 'β'})
        )
    lattice_constant_gamma = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': 'γ'})
    )
    placeholder_ = (
        '# Enter data here in any format\n# that JMol can read')
    atomic_coordinates = forms.CharField(
        required=False,
        widget=forms.Textarea(
            attrs={'class': 'form-control', 'rows': '3',
                   'placeholder': mark_safe(placeholder_)}),
        help_text=''
        'Enter atomic structure data in any format accepted by JMol. Note: to '
        'resize this box, drag from the corner.')
    geometry_format = forms.CharField(
        required=False, initial='aims', widget=forms.HiddenInput())
    phase_transition_crystal_system_final = forms.ChoiceField(
        label='Final crystal system',
        required=False,
        initial=models.Subset.CRYSTAL_SYSTEMS[0],
        choices=(models.Subset.CRYSTAL_SYSTEMS),
        widget=forms.RadioSelect(),
        help_text='Select the final crystal system.')
    phase_transition_space_group_initial = forms.CharField(
        label='Initial space group',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
    )
    phase_transition_space_group_final = forms.CharField(
        label='Final space group',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
    )
    phase_transition_direction = forms.CharField(
        label='Direction',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
    )
    phase_transition_hysteresis = forms.CharField(
        label='Hysteresis',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
    )
    phase_transition_value = forms.CharField(
        label='Value',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
        help_text=''
    )

    # Uploads
    uploaded_files = forms.FileField(
        required=False,
        widget=forms.ClearableFileInput(attrs={'multiple': True}),
        help_text=''
        'Upload files containing anything that is relevant to the current '
        'data (input files to a calculation, image of the sample, ...). '
        'Multiple files can be selected here.')

    # Qresp related
    qresp_fetch_url = forms.CharField(required=False,
                                      widget=forms.HiddenInput())
    qresp_chart_nr = forms.IntegerField(required=False,
                                        widget=forms.HiddenInput())
    qresp_search_url = forms.CharField(required=False,
                                       widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        """Dynamically add subsets and fixed properties."""
        super().__init__(*args, **kwargs)
        self.label_suffix = ''
        if args:
            for key, value in args[0].items():
                if key.startswith('subset_datapoints_'):
                    self.fields[key] = forms.CharField(
                        required=False, widget=forms.Textarea, initial=value)
                elif key.startswith('subset_label_'):
                    self.fields[key] = forms.CharField(required=False,
                                                       initial=value)
                elif key.startswith('import_file_name_'):
                    self.fields[key] = forms.CharField(
                        required=False,
                        initial=value,
                        widget=forms.HiddenInput())
                elif key.startswith('crystal_system_'):
                    self.fields[key] = forms.ChoiceField(
                        initial=value,
                        choices=(models.Subset.CRYSTAL_SYSTEMS),
                        widget=forms.RadioSelect())
                elif key.startswith('fixed_property_'):
                    self.fields[key] = forms.ModelChoiceField(
                        queryset=models.Property.objects.all().order_by('name'), initial=value)
                elif key.startswith('fixed_unit_'):
                    self.fields[key] = forms.ModelChoiceField(
                        queryset=models.Unit.objects.all(),
                        initial=value, required=False)
                elif key.startswith('fixed_value_'):
                    self.fields[key] = forms.CharField(initial=value)
                elif key.startswith('lattice_constant_'):
                    self.fields[key] = forms.CharField(required=False,
                                                       initial=value)
                elif key.startswith('atomic_coordinates_'):
                    self.fields[key] = forms.CharField(
                        required=False, widget=forms.Textarea, initial=value)
                elif key.startswith('geometry_format_'):
                    self.fields[key] = forms.CharField(
                        required=False,
                        widget=forms.HiddenInput(),
                        initial=value)
                elif key.startswith('phase_transition_crystal_system_final_'):
                    self.fields[key] = forms.ChoiceField(
                        required=False,
                        initial=value,
                        choices=(models.Subset.CRYSTAL_SYSTEMS),
                        widget=forms.RadioSelect())
                elif key.startswith('phase_transition_space_group_initial_'):
                    self.fields[key] = forms.CharField(required=False,
                                                       initial=value)
                elif key.startswith('phase_transition_space_group_final_'):
                    self.fields[key] = forms.CharField(required=False,
                                                       initial=value)
                elif key.startswith('phase_transition_direction_'):
                    self.fields[key] = forms.CharField(required=False,
                                                       initial=value)
                elif key.startswith('phase_transition_hysteresis_'):
                    self.fields[key] = forms.CharField(required=False,
                                                       initial=value)
                elif key.startswith('phase_transition_value_'):
                    self.fields[key] = forms.CharField(required=False,
                                                       initial=value)

    def clean(self):
        """Set secondary property conditionally required."""
        data = self.cleaned_data
        if data.get('two_axes') and not data.get('secondary_property'):
            self.add_error('secondary_property', 'This field is required.')
        if not all(map(lambda x: x.isdigit(),
                       data.get('related_data_sets').split())):
            self.add_error('related_data_sets',
                           'This must be a list of space separated integers.')

    def get_subset(self):
        """Return a list of initial values for data subset."""
        results = []
        for field in self.fields:
            if field.startswith('subset_datapoints_'):
                counter = field.split('subset_datapoints_')[1]
                crystal_system = self.fields[
                    'crystal_system_' + counter].initial
                import_file_name = self.fields[
                    'import_file_name_' + counter].initial
                if 'subset_label_' + counter in self.fields:
                    label = self.fields[f'subset_label_{counter}'].initial
                else:
                    label = ''
                datapoints = self.fields[field].initial
                results.append([counter,
                                import_file_name,
                                crystal_system,
                                label,
                                datapoints])
        return results

    def get_fixed_properties(self):
        """Return a list of fixed properties and their current values."""
        results = []
        for field in self.fields:
            if field.startswith('fixed_property_'):
                suffix = field.split('fixed_property_')[1]
                subset, counter = suffix.split('_')
                results.append([subset, counter,
                                self.fields[field].initial,
                                self.fields[f'fixed_unit_{suffix}'].initial,
                                self.fields[f'fixed_value_{suffix}'].initial])
        return results

    def get_lattice_parameters(self):
        results = []
        for field in self.fields:
            if field.startswith('lattice_constant_a_'):
                subset = field.split('lattice_constant_a_')[1]
                results.append([
                    subset,
                    self.fields[f'lattice_constant_a_{subset}'].initial,
                    self.fields[f'lattice_constant_b_{subset}'].initial,
                    self.fields[f'lattice_constant_c_{subset}'].initial,
                    self.fields[f'lattice_constant_alpha_{subset}'].initial,
                    self.fields[f'lattice_constant_beta_{subset}'].initial,
                    self.fields[f'lattice_constant_gamma_{subset}'].initial,
                    self.fields[f'atomic_coordinates_{subset}'].initial,
                    self.fields[f'geometry_format_{subset}'].initial,
                ])
        return results

    def get_phase_transitions(self):
        results = []
        for field in self.fields:
            if field.startswith('phase_transition_value_'):
                subset = field.split('phase_transition_value_')[1]
                p = 'phase_transition'
                results.append([
                    subset,
                    self.fields[f'{p}_crystal_system_final_{subset}'].initial,
                    self.fields[f'{p}_space_group_initial_{subset}'].initial,
                    self.fields[f'{p}_space_group_final_{subset}'].initial,
                    self.fields[f'{p}_direction_{subset}'].initial,
                    self.fields[f'{p}_hysteresis_{subset}'].initial,
                    self.fields[f'{p}_value_{subset}'].initial,
                ])
        return results


#! /usr/bin/env python
# coding: utf-8
import rospy
import numpy as np
import sys

from geometry_msgs.msg import WrenchStamped

class LPF(object):

    def __init__(self, input_topic, output_topic, lpf_factor, node_name="LPF"):
        """
        """

        rospy.init_node( node_name )

        self.sub = rospy.Subscriber( input_topic, WrenchStamped, self.callback )
        self.pub = rospy.Publisher( output_topic, WrenchStamped, queue_size=10 )
        self.lpf_factor = lpf_factor

        self.pre_F = np.zeros(3)
        self.pre_T =np.zeros(3)

    def callback( self, msg ):
        """
        """
        raw_F = np.array( [ msg.wrench.force.x, msg.wrench.force.y, msg.wrench.force.z ] )
        raw_T = np.array( [ msg.wrench.torque.x, msg.wrench.torque.y, msg.wrench.torque.z ] )

        pub_F = self.lpf_factor * raw_F + ( 1 - self.lpf_factor ) * self.pre_F
        pub_T = self.lpf_factor * raw_T + ( 1 - self.lpf_factor ) * self.pre_T

        self.pre_F = raw_F
        self.pre_T = raw_T

        publishdata = WrenchStamped()
        publishdata.header = msg.header
        publishdata.wrench.force.x = pub_F[0]
        publishdata.wrench.force.y = pub_F[1]
        publishdata.wrench.force.z = pub_F[2]
        publishdata.wrench.torque.x = pub_T[0]
        publishdata.wrench.torque.y = pub_T[1]
        publishdata.wrench.torque.z = pub_T[2]
        self.pub.publish( publishdata )

        print( "published. " + "F: " + str( pub_F ) + ", T: " + str( pub_T ) )

if __name__=="__main__":

    if len( sys.argv ) < 4:
        print( "usage: program <input topic name> <output topic name> <lpf_factor> <node name>" )
        sys.exit(1)

    a = LPF( sys.argv[1], sys.argv[2], float(sys.argv[3]), sys.argv[4] )
    rospy.spin()


import datetime
import dictionary

def createXml(layer) -> str:
    res = ''
    for elem in dictionary.xmlDict:
        if elem == 'layer':
            elem = layer
        if elem == 'date':
            elem = str(datetime.datetime.now())[:-3] + ' UTC'
        res += elem
    return res


import datetime
import itertools
import argparse
import sys
class apriori:
    def __init__(self,file, support, confidence , printing):
        self.support_value = support
        self.confidence = confidence
        self.filename = file
        self.printing = printing

    def loaddata(self):
        """
        This method is used the load the data from the text file
        :return: it returns a list of sets containing the transaction data
        """
        transactions = []
        with open(self.filename) as f:
            content = [x.strip() for x in f.readlines()]
            for x in content:
                transactions.append(set(x.split(' ')))
        return transactions

    def support_checker(self, unique_items):
        """
        This method is used for checking threshold support value given as a input
        :param unique_items:
        :return: only the items which has more than the threshold value
        """
        accepted = {}
        support = {}
        for key, value in unique_items.items():
            val = value/len(self.transactions)
            if (val >= self.support_value):
                accepted[key] = 1
                support[key] = (val)
        return accepted, support

    def writing(self,subset, leftover,support,coverage,f):
        """
        This is method is used to write only the strong association rule
        :param subset: it is the entire set or union of A and B
        :param leftover: it is set B
        :param support: support value for subset
        :param coverage: coverage value which was calculated for A and B
        :param f: file object to write to the file
        """
        counter = 0
        for i in sorted(list(leftover)):
            if len(leftover) - 1 != counter:
                f.write(i + ", ")
                counter += 1
            else:
                f.write(i)
        f.write(' -> ')
        counter = 0
        for i in sorted(list(subset)):
            if len(subset) - 1 != counter:
                f.write(i + ", ")
                counter += 1
            else:
                f.write(i)
        f.write(" ({0:.2f}".format(support) + ", {})".format(round(coverage,2)))
        f.write("\n")

    def association_rule_generation(self,accepted_list, support_data):
        """
        This method is for caluclating the strong association rule and writing to the file based on user input
        if f is given as an input it will frequent itemset to file
        if a is given as an input it will write frequent itemset and strong association rule
        if r is given as an input it will write strong association rule
        if it is absent then default value x is used and the number of frequent itemsets and number of string association rule is stored in the file
        :param accepted_list: accepted subsets
        :param support_data: it has the support value for all the subset
        """
        total_association_rule = 0
        f = open("apriori_output.txt", "w+")
        if self.printing == "f"or self.printing =="a":
            for i in accepted_list:
                for k in i:
                    counter = 0
                    for i in sorted(k):
                        if len(k) - 1 != counter:
                            f.write(i + ", ")
                            counter += 1
                        else:
                            f.write(str(i) +  " ({0:.2f})".format(support_data[k]) + "\n")
            f.write("\n")

        if self.printing == "x":
            for idx,val in enumerate(accepted_list):
                f.write("Number of frequent {}_itemset"
                        "s: {} \n" .format(idx+1,len(val)))

        if self.printing != "f":
            for i in accepted_list:
                for j in i:
                    if (len(j) > 1):
                        for k in range(len(j)):
                            for subset in itertools.combinations(j, k):
                                left_over = j - set(subset)
                                try:
                                    if k != 0:
                                        coverage = (support_data[j] / support_data[left_over])
                                        if coverage >= self.confidence:
                                            total_association_rule += 1
                                            if self.printing == "r" or self.printing =="a":
                                                self.writing(subset, left_over, support_data[j],coverage,f )
                                except:
                                    print("Exception found")
            if total_association_rule == 0 and self.printing != "x":
                f.write("Number of association rules: {}".format(total_association_rule))
        if self.printing == "x":
            f.write("Number of association rules: {}".format( total_association_rule))
        f.close()

    def generate_candidate(self, accepted_candidate):
        """
        It is used to generate all the possible candidates from the previously accepted candidates
        :param accepted_candidate: previoulsy accepted candidate
        :return: all possible candidate
        """
        accepted = {}
        for key1 in accepted_candidate.keys():
            for key2 in accepted_candidate.keys():
                x = key1 | key2
                if (len(x) == len(key1) + 1) and x not in accepted:
                    accepted[x] = 1
        return accepted
    def subsetchecker(self,item, accepted):
        """
        This is a pruning method here : if A,B,C,D is in item then it is necessary B,C,D ; A,C,D etc should be present. if these
        subsets are not present then its superset is not possible, and we are not checking for A,C ; A,D because if A,C,D is present
        then A,C and A,D will be present
        :param i: item
        :param accepted: previously accepted items
        :return: boolean value whether this itemset is possible or not
        """
        k = len(item) - 1
        for subset in itertools.combinations(item, k):
            if frozenset(subset) not in accepted:
                return False
        return True
    def generate_frequent(self, transaction, candiate,accepted):
        """
        This method calculates the count for the possible candidate and at the same time it prunes the candidate
        it saves a significant amount time since it prevents from checking the transactions and other following contions in it
        :param transaction: transaction data
        :param candiate: all possible candidate
        :param accepted: previously accepted candidates which has more than support value
        :return: total counts for possible candidate while pruning in between
        """
        builder = {}
        # count = 0
        for i in candiate:
            if self.subsetchecker(i,accepted):
                for transac in transaction:
                    # count += 1
                    if i.issubset(transac):
                        if i in builder:
                            builder[i] += 1
                        else:
                            builder[i] = 1
        # print (count)
        return builder

    def generator(self):
        self.transactions = self.loaddata()
        unique_items = {}
        self.first_frequent = True
        for trans in self.transactions:
            for i in trans:
                item = frozenset({i})                                # frequent one itemset is generated
                if item not in unique_items:
                    unique_items[item] = 1
                else:
                    unique_items[item] += 1
        accepted, support = self.support_checker(unique_items)
        accepted_list = [accepted]
        support_data = support
        k = 1
        """
        we will be generating further unique itemset and will be checking their support value, accepted itemset is add to the accepted
        dictionary and to the support dictionary
        """
        print("Execution for Apriori algorithm started..../")
        # start = datetime.datetime.now()
        while ( len(accepted_list[k-1]) > 0):
            # start = datetime.datetime.now()
            all_candidate = self.generate_candidate( accepted_list[k-1])
            candidate= self.generate_frequent(self.transactions,all_candidate,accepted_list[k-1])
            accepted, support = self.support_checker(candidate)
            accepted_list.append(accepted)
            support_data.update(support)
            k += 1
        # print(start)
        # print((  datetime.datetime.now()) - start)
        self.association_rule_generation(accepted_list,support_data)
        print("Execution completed check apriori_output.txt for ouput ")

def main(sys):
    try :
        file_name = sys.argv[1]
        min_support = float(sys.argv[2])
        min_conf = float(sys.argv[3])
        if (0 <= min_conf <=1) and (0<= min_support <=1):
            try :
                printing = sys.argv[4]
            except:
                printing = "x"
        else:
            raise Exception()
        a = apriori(file_name, min_support, min_conf,printing)
        # a = aprioir('./data100.txt',0.1,.8,"x")
        a.generator()
    except KeyboardInterrupt:
        print('Keyboard Interrupted - Run again to continue')
    except:
        print("Invalid inputs - please the check input")

if __name__ == '__main__':
    main(sys)


import httpx
import pytest

Response = httpx._models.Response

@pytest.mark.asyncio
async def test_get_answers(client):
    """Return a list of answers given a response."""
    response: Response = await client.get("/answers/")

    assert response.status_code == 200
    assert response.json() == []

@pytest.mark.asyncio
async def test_get_answer(client):
    """Return resource not found given an id that isn't in db."""
    answer_id: int = 100

    response: Response = await client.get(f"/answers/{answer_id}")

    assert response.status_code == 404
    assert response.json()["detail"] == f"Answer {answer_id} does not exist."

@pytest.mark.asyncio
async def test_malformed_get_answer(client):
    """Return unable to process contained instructions due to incorrect query."""
    bad_id: float = 5.2

    response: Response = await client.get(f"/answers/{bad_id}")

    assert response.status_code == 422
    assert response.json()["detail"][0]["msg"] == "value is not a valid integer"


import streamlit as st
import numpy as np
from PIL import Image
import tensorflow as tf
from streamlit_drawable_canvas import st_canvas

def show_models():
    magnifier = 5
    img_height = 32
    img_width = 128

    # Params
    drawing_mode = st.sidebar.selectbox(
        "Drawing tool:",
        ("freedraw", "line", "rect", "circle", "transform", "polygon", "point"),
    )
    stroke_width = st.sidebar.slider("Stroke width: ", 1, 25, 3)
    stroke_color = st.sidebar.color_picker("Stroke color hex: ")
    bg_color = st.sidebar.color_picker("Background color hex: ", "#eee")
    realtime_update = st.sidebar.checkbox("Update in realtime", True)
    # Create a canvas component
    canvas_result = st_canvas(
        fill_color="rgba(255, 165, 0, 0.3)",  # Fixed fill color with some opacity
        stroke_width=stroke_width,
        stroke_color=stroke_color,
        background_color=bg_color,
        background_image= None,
        update_streamlit=realtime_update,
        height=img_height * magnifier,
        width=img_width * magnifier,
        drawing_mode=drawing_mode,
        point_display_radius=0,
        display_toolbar=st.sidebar.checkbox("Display toolbar", True),
        key="full_app",
    )

    # Do something interesting with the image data
    if canvas_result.image_data is not None:
        with st.spinner('Predicting using the model...'):
            predict_canvas_image(canvas_result.image_data, (img_height, img_width))

def predict_canvas_image(img_data, img_size = ()):
    im = Image.fromarray(img_data.astype("uint8"), mode="RGBA").convert('L')
    im = im.resize(img_size)
    img_arr = np.array(im)
    img_arr = img_arr / 255.0
    X_test = np.array(img_arr).reshape(-1, img_size[0], img_size[1], 1)
    model = tf.keras.models.load_model('../pickle/image_letter_counter_mlp_model')
    y_pred = model.predict(X_test)
    st.write("Predicted length: {}".format(round(y_pred[0][0])))


#!/usr/bin/env python3

def compute(base, value):
    base_copy = base.copy()#创建一个临时的base
   # base_copy = base[:]
    base_copy.append(value)
    result = sum(base_copy)
    print(result)#打印后释放

if __name__ == '__main__':
    testlist =[10, 20, 30]
    compute(testlist, 15)
    compute(testlist, 25)
    compute(testlist, 35)


from methods import acceleration as acceleration
from methods import stop as stop

class Car():

    def __init__(self, carName, maxSpeed):
        self.carName = carName
        self.maxSpeed = maxSpeed
        self.engine_status = 0
        self.run_status = 0
        self.cnt_of_srart_engine = 0

    def desc(self):
        description = "Car name: " + self.carName + '\n' + "max speed: " + str(self.maxSpeed) + '\n' + 'число запусков двигателя: ' + str(self.cnt_of_srart_engine)
        return description

    def engine_start(self):
        if self.engine_status == 0:
            print('Автомобиль', self.carName, 'завёлся')
            self.engine_status = 1
            self.cnt_of_srart_engine += 1
        else:
            print('Автомобиль', self.carName, 'уже заведён')

    def engine_stop(self):
        if self.engine_status == 1:
            print('Автомобиль', self.carName, 'заглушен')
            self.engine_status = 0
        else:
            print('Автомобиль', self.carName, 'уже был заглушен')

    def acceleration(self):
        if self.engine_status == 1:
            print('Поiхали')
            self.run_status = 1
        else:
            print('Автомобиль', self.carName, 'не заведён')

    def stop(self):
        if self.run_status == 1:
            print('Останавливаемся')
        else:
            print('Мы и так стоим вообще то')

class Toyota(Car):
    def __init__(self, carName, maxSpeed):
        super().__init__(carName, maxSpeed)

class Ford(Car):
    def __init__(self, carName, maxSpeed):
        super().__init__(carName, maxSpeed)

ford = Ford('Ford', 200)
print(ford.desc())
ford.engine_start()
ford.engine_stop()
ford.acceleration()
ford.stop()
ford.stop()


import mido
import time
import os

#v nov format spremeniti
#zanima nas le note_on, time, note

#time atribut je podan v TICKS
def readSong(text):
    mid = mido.MidiFile("music/"+text, clip=True)
    #port = mido.open_output()
    #print(mido.ports)
    return mid
    #velik cajta slo stran ker sem glupo sestavljal midi play omfg, mid.play() sam pretvarja cas med igranjem in ima prakticno timeout
    #print("Playing msg: ",pretvori_v_noto(msg))
    #extractSongInfo(mid)
    #printSongInfo(mid)

def extractSongInfo(mid):

    #tempo - Vecji tempo, pocasneje
    #120BPM je 500ms
    #60BPM je 1s
    #tempo = 60/BPM v sekundah
    #BPM = 60/tempo

    #ticks_per_quarter = <PPQ from the header>  (960)  mid.ticks_per_beat
    #µs_per_quarter = <Tempo in latest Set Tempo event>  (909089)
    #µs_per_tick = µs_per_quarter / ticks_per_quarter  (909089/960 = 63,36)
    #seconds_per_tick = µs_per_tick / 1.000.000  (63,36 / 1.000.000)
    #seconds = ticks * seconds_per_tick (99840 * (63,36 / 1.000.000) = 6.3s)
    #ticks = seconds/seconds_per_tick

    #tick je time parameter v MIDI formatu
    tr = []
    meta_msgs = []

    for i, track in enumerate(mid.tracks):
        for msg in track:
            if not msg.is_meta:
                tr.append((msg.dict().get("type"),msg.dict().get("note"),msg.dict().get("time")))
            if msg.is_meta:
                meta_msgs.append(msg.dict())
                #print(msg.dict())
                #tr.append()
                #print(msg.st)
    #print(tempo_changes)
    printSongInfo(mid)
    timeSum = 0
    for x in tr:
        if x[1] is not None:
            timeSum+=(x[1])
    #print(timeSum)
    #calculateLength(mid, tempo_changes)

    tempo_set = []
    for x in meta_msgs:
        if x["type"]=="set_tempo":
            print("tempo set: ",mido.tick2second(1, mid.ticks_per_beat, x["tempo"])," pri casu ",x["time"])
            tempo_set.append((x["tempo"],x["time"]))

    print(tempo_set)
    #print(tr)
    print(mid.ticks_per_beat)
    print(mido.tick2second(1, mid.ticks_per_beat, 500_000))

    extract_notes(tr,tempo_set,mid.ticks_per_beat)
    #printTickLength(mid)

#ta funkcija gre po vrsti po delta casu znotraj midi datoteke in "prebira" note v casovnem zaporedju, naceloma se tukaj dela izris blokcev
def extract_notes(track,t2s,ticks_per_beat):

    #t2s je tempo change array
    #track je array vseh not znotrja glasbe (non-meta message) (ime_akcije, tipka, cas)

    current_play = [0]*88

    zacet = time.time();
    tempo_timer, tempo_timer_indeks, celoten_tempo, tempo = 0 , 1 , 0, 500_000 #timer za delta timer, indeks za array tempo set, default tempo

    print("tempo casi, ",t2s)

     #default tempo
    if len(t2s)>0 and t2s[0][1] == 0:
        tempo = t2s[0][0] #trenutni tempo
    print("zacetni tempo ", tempo, " zacetni tempo timer ",tempo_timer)
    print(t2s)
    #ce je cas 0, potem naj appenda vse v list za komande, ki se poslejo naprej v funkcijo za prebiranje komand
    komande = []
    #prve komande loop
    for tr in track:
        if tr[2]>0:
            break
        komande.append(tr)
    preberiKomande(current_play,komande)
    for i in range(len(track)):
        #if track[i][0]=="note_on" or track[i][0]=="note_off":
        if track[i][2]>0:
            #ce je komanda, ki ima delay, naj prebira dokler ni se ena komanda z delayom
            j = i+1
            komande.append(track[i])
            while(j<len(track) and track[j][2]==0):
                komande.append(track[j])
                #print("dodajam ", track[j])
                j+=1

            preberiKomande(current_play,komande)
            print(current_play)
            komande.clear()
            tempo_timer+=track[i][2]
            #print(track[i])
            #print("ayo timer ++ ",tempo_timer)
            if(tempo_timer_indeks<len(t2s)):
                #print(tempo_timer,t2s)
                if(t2s[tempo_timer_indeks][1] <= tempo_timer):
                    #print("TEMPO CHANGE ",t2s[tempo_timer_indeks-1]," -> ",t2s[tempo_timer_indeks], " @",tempo_timer)
                    tempo, celoten_tempo, tempo_timer = t2s[tempo_timer_indeks][0], tempo_timer+celoten_tempo, tempo_timer-t2s[tempo_timer_indeks][1] #tempo set kokr je znotraj arraya  #odsteje trenutni cas in delta cas za tempo
                    tempo_timer_indeks+=1 #gleda naslednji element
                    #print("current tempo ", tempo, " current tempo timer ",tempo_timer, ", indeks",tempo_timer_indeks)
            #print("sleep time: ", track[i][2] * tempo/1_000_000_000)
            time.sleep(track[i][2]*tempo/1_000_000_000)
        #print(track[i])
    #ta je na koncu, saj se lahko nahajajo komande po zadnjem timu (note-off za druge note, ko je le ena napisana na delay)
    #preberiKomande(komande)
    #print(time.time()-zacet)
    #print(celoten_tempo)

def pretvori_v_noto(i):
    note = ["C", "C#", 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
    if (i[0] == "note_on" or i[0] == "note_off"):
        m = note[int(i[1]) % 12]
        n = m+""+str(int(int(i[1])/12))+" "+i[0]+" "+str(i[2])
        return n

def preberiKomande(current_play,com):

    prvi = com[0][0]
    for i in com:

        if i[0]!=prvi: #Tukaj se bo poslal signal, naj se spusti tipko in ponovno pritisne
            prvi=i[0]
            #send current
            print(prvi)
        if(i[0]=='note_on'):
            current_play[i[1] - 9]=1
        elif(i[0]=='note_off'):
            current_play[i[1]-9]=0
        pretvori_v_noto(i)
    #os.system('cls' if os.name == 'nt' else 'clear')

def printTickLength(mid):
    tick_length=0
    for i, track in enumerate(mid.tracks):
        for msg in track:
            if not msg.is_meta:
                tick_length+=msg.dict().get("time")

    print(tick_length)

def calculateLength(mid,tempo_changes):
    prejsni_tempo = 0
    tempo_sum = 0
    for x in tempo_changes:
        if x.get("type") == "set_tempo":
            prejsni_time = x.get("time")
            tempo_sum += (prejsni_tempo / mid.ticks_per_beat) / 1000000 * prejsni_time
            prejsni_tempo = x.get("tempo")

        if x.get("type") == "end_of_track":
            tempo_sum += (mid.length-tempo_sum)#*(prejsni_tempo / mid.ticks_per_beat) / 1000000
    return tempo_sum

def play_song():
    pass

def printSongInfo(mid):
    for i, track in enumerate(mid.tracks):
        print('Track {}: {}'.format(i, track.name))
        for msg in track:
            #if not msg.is_meta:
            print(msg)

if __name__=="__main__":
    readSong("bseasy.mid")
    mid = mido.MidiFile("music/bseasy.mid")
    '''
    for i, track in enumerate(mid.tracks):
        print('Track {}: {}'.format(i, track.name))
        for msg in track:
            print(msg)
    '''


from django.shortcuts import get_object_or_404
from rest_framework.permissions import BasePermission
from rest_framework.permissions import SAFE_METHODS

from . import models

class IsTopicOwnerOrReadOnly(BasePermission):
    """
    Is the user the topic owner, or is it read only?
    """

    def has_object_permission(self, request, view, obj):
        if request.method in SAFE_METHODS:
            return True
        if type(obj) == models.Topic:
            return obj.owner == request.user
        elif type(obj) == models.Choice:
            return obj.question.topic.owner == request.user
        elif type(obj) in [models.TextAnswerableQuestion,
                           models.MultipleChoice]:
            return obj.topic.owner == request.user

class IsAbleToCreateOrChoose(BasePermission):
    """
    Is the user able to create or choose?
    """

    def has_permission(self, request, view):
        topic = get_object_or_404(models.Topic, id=view.kwargs['topic_id'])
        if 'id' in view.kwargs:
            return True
        if request.method not in SAFE_METHODS:
            return request.user == topic.owner
        return True

class IsOwnerOrTopicDone(BasePermission):
    """
    Is the user the owner or is the topic done?
    """
    message = "The survey isn't yet done or you're not the topic owner."

    def has_permission(self, request, view):
        topic_id = view.kwargs['topic_id']
        topic = get_object_or_404(models.Topic, id=topic_id)
        if topic.owner == request.user:
            return True
        return topic.done


# -*- coding: utf-8 -*-
from __future__ import print_function

import os
import sys
import math
import random
import argparse
from collections import defaultdict

import numpy as np
import h5py
import jieba
import tensorflow as tf

class Vocab(object):
    def __init__(self, start_word="<S>", end_word="</S>"):
        self.vocab_dict = {}
        self.vocab_lst = []
        self.occur_dict = {}
        self.last_index = 0
        self.start_id = self.add_to_vocab(start_word)
        self.end_id = self.add_to_vocab(end_word)

    @property
    def vocab_size(self):
        return len(self.vocab_lst)

    def dump_to_file(self, fname):
        with open(fname, "w") as f:
            for word in self.vocab_lst:
                print("{} {}".format(word.encode("utf-8"), self.occur_dict[word]), file=f)

    def word_to_id(self, word):
        return self.vocab_dict[word]

    def id_to_word(self, id_):
        return self.vocab_lst[id_]

    def add_to_vocab(self, word):
        if word in self.vocab_dict:
            self.occur_dict[word] = self.occur_dict[word] + 1
        else:
            self.vocab_dict[word] = self.last_index
            self.vocab_lst.append(word)
            self.occur_dict[word] = 1
            self.last_index += 1
        return self.vocab_dict[word]

def parse_caption_file(fname, vocab, seg_dict, cut):
    indexes = []
    index = None
    with open(fname, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                index = int(line)
                indexes.append(index)
            except ValueError:
                if cut:
                    seg_list = list(jieba.cut(line))
                else:
                    seg_list = list(line.decode("utf-8"))
                seg_dict[index].append([vocab.start_id] +
                                       [vocab.add_to_vocab(word) for word in seg_list] +
                                       [vocab.end_id])
    return indexes

def parse_image_feature_file(fnames):
    train_set = None
    val_set = None
    test_set = None
    for fname in fnames:
        dataset = h5py.File(fname, "r")
        assert set(dataset.keys()) == {u"test_set", u"train_set", u"validation_set"}
        if train_set is None:
            train_set, val_set, test_set = dataset["train_set"], dataset["validation_set"], dataset["test_set"]
        else:
            train_set, val_set, test_set = np.hstack((train_set, dataset["train_set"])), np.hstack((val_set, dataset["validation_set"])), np.hstack((test_set, dataset["test_set"])),
    return train_set, val_set, test_set

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _float_feature(value):
    if not isinstance(value, list):
        value = [value]
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))

def _int64_feature_list(values):
    return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])

def to_example(image_id, feature, seg):
    context = tf.train.Features(feature={
        "image/image_id": _int64_feature(image_id),
        "image/feature": _float_feature(feature.tolist())
    })
    feature_lists = tf.train.FeatureLists(feature_list={
        "image/caption_ids": _int64_feature_list(seg)
    })
    example = tf.train.SequenceExample(
        context=context, feature_lists=feature_lists)
    return example

def dump_tfrecord(indexes, image_features, seg_dict, tfr_dir, num_samples_per_record, split):
    # dump tfrecord files
    print("dump train tfrecords")
    samples = [(ind, image_features[i], seg) for i, ind in enumerate(indexes) for seg in seg_dict[ind]]
    print("{}: num of samples: {}".format(split, len(samples)))
    random.seed(12345)
    random.shuffle(samples)
    f_idx = 1
    f_num = 0
    fname = os.path.join(tfr_dir, "%s-%.5d.tfrecord"%(split, f_idx))
    print("writing {} records to {}".format(split, fname))
    writer = tf.python_io.TFRecordWriter(fname)
    for sample in samples:
        example = to_example(*sample)
        writer.write(example.SerializeToString())
        f_num += 1
        if f_num == num_samples_per_record:
            f_idx += 1
            f_num = 0
            fname = os.path.join(tfr_dir, "%s-%.5d.tfrecord"%(split, f_idx))
            print("writing {} records to {}".format(split, fname))
            writer = tf.python_io.TFRecordWriter(fname)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("train_file")
    parser.add_argument("val_file")
    parser.add_argument("vocab_file", help="dump vocabulary to file")
    parser.add_argument("tfrecord_dir", help="directory of tfrecord")
    parser.add_argument("--num-samples-per-record", default=400, type=int)
    parser.add_argument("--vocab-only", default=False, action="store_true")
    parser.add_argument("--no-cut", default=False, action="store_true")

    # TODO: multiple image feature file
    parser.add_argument("-f", "--image-feature-file", action="append", required=True,
                        help="HDF5 file contains the CNN-extracted features for each image id")

    args = parser.parse_args()

    vocab = Vocab()
    seg_dict = defaultdict(lambda : [])
    print("parsing caption from train: {}, val: {}".format(args.train_file, args.val_file))
    train_indexes = parse_caption_file(args.train_file, vocab, seg_dict, not args.no_cut)
    val_indexes = parse_caption_file(args.val_file, vocab, seg_dict, not args.no_cut)
    print("num train indexes: {}; num val indexes: {}".format(len(train_indexes), len(val_indexes)))
    # dump vocab file
    print("vocabulary size: {}; dump vocabulary to {}".format(vocab.vocab_size, args.vocab_file))
    vocab.dump_to_file(args.vocab_file)
    if args.vocab_only:
        return

    # load CNN-extracted image features
    print("loading features from {}".format(args.image_feature_file))
    train_features, val_features, _ = parse_image_feature_file(args.image_feature_file)
    assert len(train_indexes) == train_features.shape[0]
    assert len(val_indexes) == val_features.shape[0]

    # TODO: test_feature自己读并且喂placeholder...就不dump了
    dump_tfrecord(train_indexes, train_features, seg_dict, args.tfrecord_dir, args.num_samples_per_record, "train")
    dump_tfrecord(val_indexes, val_features, seg_dict, args.tfrecord_dir, args.num_samples_per_record, "val")

if __name__ == "__main__":
    main()


# M5T1a
# CTI - 110
# Schweikb0866
# 10/19/17

def main():

	import turtle
	wn = turtle.Screen()
	wn.bgcolor("black")
	wn.title("Kriina & Norgana")

	kriina = turtle.Turtle()
	kriina.color("pink")
	kriina.pensize(5)

	norgana = turtle.Turtle()
	norgana.color("green")
	norgana.pensize(4)

	i = 0
	while i < 8:
		kriina.forward(150)
		kriina.left(120)

		norgana.forward(50)
		norgana.left(90)

		i = i+1

main()


from ts_pygame_engine.coordinates import MovingCoordinate

class Limit:
    def __init__(self, left, right):
        self.left = left
        self.right = right

class PosLimit:
    def __init__(self, x, y):
        self.x = Limit(*x)
        self.y = Limit(*y)

class LimitedMovingCoordinate(MovingCoordinate):
    def __init__(self, pos=(0, 0), vel=None, acc=None, limits=None, bounce=1):
        super().__init__(pos, vel, acc)
        self.limits = limits
        self.collision = False
        if bounce < 0:
            raise ValueError('bounce must be not negative number or bool')
        self.bounce = float(bounce)

    def process(self, game, time):
        super().process(game, time)
        if self.limits is None:
            return

        self.collision = False
        if self.pos.x < self.limits.x.left:
            self.pos.x = self.limits.x.left
            self.vel.x *= -self.bounce
            self.collision = True
        if self.pos.x > self.limits.x.right:
            self.pos.x = self.limits.x.right
            self.vel.x *= -self.bounce
            self.collision = True
        if self.pos.y < self.limits.y.left:
            self.pos.y = self.limits.y.left
            self.vel.y *= -self.bounce
            self.collision = True
        if self.pos.y > self.limits.y.right:
            self.pos.y = self.limits.y.right
            self.vel.y *= -self.bounce
            self.collision = True


from discord.ext import commands, ipc

class IpcRoutes(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @ipc.server.route()
    async def send_(self, data):
        print(data.id)
        try:
            await (await self.bot.fetch_user(data.id)).send("로그인 성공")  # get the guild object using parsed guild_id
            return True  # return the member count to the client
        except:
            return False

    @ipc.server.route()
    async def guild_(self,data):
        print(data.us)
        li = []
        for i in self.bot.guilds:
            li.append(i.id)
        return li

def setup(bot):
    bot.add_cog(IpcRoutes(bot))
    print('ok')


# -*- coding: utf-8 -*-
"""
Created on Mon Jul 10 20:27:41 2017

@author: Home
"""

from eulerTools import sieve_for_primes_to, primeFactor_listset
from datetime import datetime
from math import sqrt

def ord10(p):
    n = 2
    p9 = 9*p
    target = 6*(p-1)
    divs = primeFactor_listset(target)
    for n in divs:
        if target%n == 0:
            while (target%n == 0) and (pow(10, target//n, p9) == 1):
                target //= n

    return target

startTime = datetime.now()
p_list = sieve_for_primes_to(100000)

res = sum(p_list[:3])
p_list = p_list[3:]
check_list = [[], [2], [5], [2, 5]]

for p in p_list:
    z = ord10(p)
    while z%2 == 0:
        z //= 2
    while z%5 == 0:
        z //= 5
    if z != 1:
        res += p

print("Result =", res)
print(datetime.now() - startTime)
#time: 3.6s


#NOT USED ANYMORE, FULL IMPLEMENTED IN FRONT

from fastapi import APIRouter, Query, Body
from ..lib import Coordinates
from ..lib import LoadCatalog
from ..dependencies import error
from datetime import datetime,date
from typing import List
from pydantic import BaseModel, Json, Field
from ..dependencies import config
from ..models.coordinates import TimeObject

router = APIRouter()
catalog = LoadCatalog.LoadCatalog()
catalog.open('data/deepsky.lst')
coordinates = Coordinates.Coordinates()
coordinates.set_location_coord(float(config.CONFIG["LOCATION"]["LAT"]),float(config.CONFIG["LOCATION"]["LON"]),float(config.CONFIG["LOCATION"]["HEIGHT"]))
today = str(date.today())
coordinates.set_time(coordinates.time_local_to_utc(datetime.strptime(today+" 23:59","%Y-%m-%d %H:%M")))

@router.post("")
async def set_coord(coord : Coordinates.Coord):
    coordinates.set_location_coord(coord.lat, coord.lon, coord.height)
    return error.no_error()

@router.post("/time")
async def set_time(time: TimeObject):
    coordinates.set_time(coordinates.time_local_to_utc(datetime.strptime(time.time,"%Y-%m-%d %H:%M")))
    return error.no_error()

@router.get("/visible")
def visible():
    coordinates.set_constraints();
    coordinates.get_catalog_visibility(catalog)
    return coordinates.get_catalog_visibility(catalog)

@router.get("/objects/{obj_list}")
async def get_objects(obj_list : str):
    objects = obj_list.split(",")
    ret = coordinates.get_catalogs_objects(objects, catalog.catalog)
    return ret

@router.get("/object/{obj_name}")
async def get_objects(obj_name : str):
    ret = coordinates.get_object(obj_name)
    ra = ret.ra.hour
    dec = ret.dec.deg
    return [ra,dec]

@router.get("/scheduled/{obj_list}")
async def get_schedule(obj_list : str):
    objects = obj_list.split(",")
    ret = coordinates.get_schedule(objects, catalog)
    return ret


import heapq
import sys

input = sys.stdin.readline
N = int(input())

arr = []
for _ in range(N):
    arr.append(list(map(int, input().split())))

arr.sort(key=lambda x: x[0])

class_lst = [0]
cnt = 1
for start, end in arr:
    if start >= class_lst[0]:
        heapq.heappop(class_lst)
    else:
        cnt += 1
    heapq.heappush(class_lst, end)

print(cnt)


import torch
import torch.nn as nn

class VGG(nn.Module):

    def __init__(self, features, num_classes=10, init_weights=True):
        super(VGG, self).__init__()
        self.features = features
        self.classifier = nn.Sequential(
            nn.Linear(512, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, num_classes),
        )
        if init_weights:
            self._initialize_weights()

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, 0, 0.01)
                nn.init.constant_(m.bias, 0)

def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == 'M':
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)

cfgs = {
    'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}

def _vgg(arch, cfg, batch_norm, pretrained, progress, **kwargs):
    if pretrained:
        kwargs['init_weights'] = False
    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)
    return model

def vgg16(pretrained=False, progress=True, **kwargs):
    return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)

def vgg16_bn(pretrained=False, progress=True, **kwargs):
    return _vgg('vgg16_bn', 'D', True, pretrained, progress, **kwargs)
#net = vgg16_bn()
#print(net)

def vgg19(pretrained=False, progress=True, **kwargs):
    return _vgg('vgg19', 'E', False, pretrained, progress, **kwargs)

def vgg19_bn(pretrained=False, progress=True, **kwargs):
    return _vgg('vgg19_bn', 'E', True, pretrained, progress, **kwargs)


import json
import boto3
import os

#define dynamodb item variables
hmb_request_item_table = os.environ['REQUEST_TABLE']

#define boto variables
dynamodb = boto3.client('dynamodb')

def get_request_items ():
    response = boto_scan(hmb_item_table)
    return response

def boto_scan (table_name) :
    response = dynamodb.scan(
        TableName = table_name,
        FilterExpression = "Quantity = :val",
        ExpressionAttributeValues = {":val": {"N": str(0)}}
    )
    return response

def lambda_function (event, context):
    result = get_request_items()
    print(response)

    to_return = {
        "statusCode": 200,
        "body": json.dumps(result['Items'])
    }
    return to_return


import RPi.GPIO as IO
import picamera
from time import sleep

IO.setmode(IO.BOARD)
IO.setup(12,IO.IN)

camera=picamera.PiCamera()

cameraOn = False

print('The push-button acts as a toggle to turn on and off the camera\
\nA while loop set to True is used to create the toggle behaviour\
\nYou have to code for the event the user does not want to use the\
\ncamera any more.\
\nTo get out of the program use the keys Ctrl C when the camera is\
\nin the off mode.')

input('Hit enter to activate the push-down button........')

while True: # This is a infinite loop. You hae to program for its exit.

    if IO.input(12):
        if cameraOn == True:
            cameraOn = False
            camera.stop_preview()
            while IO.input(12):
                sleep(0.01)

        else:
            cameraOn = True
            camera.start_preview()
            while IO.input(12):
                sleep(0.01)

IO.cleanup()


#!/usr/bin/python3

def showInstructions():
    """Show the game instructions when called"""
    #print a main menu and the commands
    print('''
    RPG Game
    ========
    Instructions:
      Get to the Garden with a key and a potion to win! Avoid the monsters!
    Commands:
      go [direction]
      get [item]
    ''')

def showStatus():
    """determine the current status of the player"""
    # print the player's current location
    print('---------------------------')
    print('You are in the ' + currentRoom)
    # print what the player is carrying
    print('Inventory:', inventory)
    # check if there's an item in the room, if so print it
    if "item" in rooms[currentRoom]:
      print('You see a ' + rooms[currentRoom]['item'])
    print("---------------------------")

inventory = []

rooms = {
        'Hall': {
            'south': 'Kitchen',
            'east': 'Dining Room',
            'item': 'key'
            },
        'Kitchen': {
            'north': 'Hall',
            'item': 'monster'
            },
        'Dining Room': {
            'west': 'Hall',
            'south': 'Garden',
            'item': 'potion'
            },
        'Garden': {
            'north': 'Dining Room'}
        }

currentRoom = 'Hall'

showInstructions()

while True:
    showStatus()

    move = ''
    while move == '':
        move = input('>')

    move = move.lower().split(" ", 1)

    if move[0] == 'go':
        if move[1] in rooms[currentRoom]:
            currentRoom = rooms[currentRoom][move[1]]
        else:
            print("You can't go that way!")

    if move[0] == 'get':
        if "item" in rooms[currentRoom] and move[1] in rooms[currentRoom]['item']:
            inventory.append(move[1])
            print(move[1] + ' got!')
            del rooms[currentRoom]['item']
        else:
            print("Can't get " + move[1] + "!")

    if 'item' in rooms[currentRoom] and 'monster' in rooms[currentRoom]['item']:
        print('A monster has got you... GAME OVER!')
        break

    if currentRoom == 'Garden' and 'key' in inventory and 'potion' in inventory:
        print('You escaped the house with the ultra rare key and magic potion... YOU WIN!')
        break


import numpy as np

mergeable_dtype_kinds = frozenset(("i", "u", "m", "M", "S"))

def merge_to_str(*arrs: np.ndarray) -> np.ndarray:
    """
    Convert one or more arrays of integers, bytes, datetime64, timedelta64 to \
    S(total_bytes + (last array is not "S")).

    We cannot use arr.byteswap().view("S8") because the trailing zeros get discarded \
    in np.char.add. Thus, we have to pad with ";" unless the last array is bytes.

    We copy bytes ("S"), datetime64, timedelta64 verbatim.
    """
    assert len(arrs) > 0
    size = len(arrs[0])
    lock = arrs[-1].dtype.kind != "S"
    str_len = sum(arr.dtype.itemsize for arr in arrs) + lock
    arena = np.full((size, str_len), ord(";") if lock else 0, dtype=np.uint8)
    pos = 0
    for arr in arrs:
        kind = arr.dtype.kind
        if kind not in mergeable_dtype_kinds:
            raise ValueError(
                f"array's dtype.kind {arr.dtype} must be one of "
                f"{', '.join(mergeable_dtype_kinds)}",
            )
        if len(arr) != size:
            raise ValueError(f"all arrays must have the same length: {len(arr)} != {size}")
        itemsize = arr.dtype.itemsize
        if itemsize > 1 and kind != "S":
            col = arr.byteswap()
        else:
            col = arr
        arena[:, pos : pos + itemsize] = col.view(np.uint8).reshape(size, itemsize)
        pos += itemsize
    return arena.ravel().view(f"S{str_len}")


from python.src.CardGame.CardGame import Deck
from python.src.CardGame.CardGame import CardGame
import time

class Snap(CardGame):

    userHand = 0
    computerHand = 1

    # Function: initialiseScore
    # Description: Initialises who turn it is the computer of the user and how many winning hands
    def initialiseScore(self):
        return [{"turn":True,"score":0},{"turn":False,"score":0}]

    # Function: isSnap
    # Description: Determine if it is snap by comparing two playing cards
    def isSnap(self,previousCard, nextCard):
        snap = False
        if previousCard[0] == nextCard[0]:
            snap = True
        return snap

    # Function: playCard
    # Description: Deals a card from either the computer or the users hands and prompts the console. The next card dealt
    # from either hand is then returned.
    def playCard(self,currentScore,hands):
        if currentScore[self.computerHand]["turn"]:
            nextCard = hands[1].playACard()
            prompt = "Computer plays "
            currentScore[self.computerHand]["turn"] = False
        else:
            # The next function returns a playing card. The playing card is the next card from the users hand. A list
            # "hands" is a list of lists of cards. The constant playCard.userHand is used to get the hand of cards for the
            # user
            nextCard = hands[self.deck.userHand].playACard()
            prompt = "You played "
            currentScore[self.userHand]["turn"] = False
        print(prompt + nextCard)
        return nextCard

    # Method: determineWinner
    # Description: Determine if the computer or the user has won and display the result. If the user call snap they must do
    # it in a given time set by the user.
    def determineWinner(self,currentScore,previousCard,nextCard,answer,waited,secondsToWait):
        if answer == "S" and self.isSnap(previousCard,nextCard) and waited < secondsToWait:
            print("Correct you win in " + str(waited))
            currentScore[self.userHand]["score"] += 1
            print("You have won " + str(currentScore[self.userHand]["score"]) + " hands")
        elif answer == "S" and self.isSnap(previousCard,nextCard) and waited > secondsToWait:
            print("Sorry to slow you waited " + str(waited))
            print("Computer wins")
            currentScore[self.computerHand]["score"] += 1
            print("Computer has won " + str(currentScore[self.computerHand]["score"]) + " hands")
        elif answer == "S" and not self.isSnap(previousCard, nextCard):
            print("Wrong the cards are different")
        elif answer == "N" and self.isSnap(previousCard,nextCard):
            print("Computer wins")
            currentScore[self.computerHand]["score"] += 1
            print("Computer has won " + str(currentScore[self.computerHand]["score"]) + " hands")

    # Method: main
    # Description: The main logic for snap given a hands of cards and a wait time.
    def snap(self,hands,secondsToWait):
        answer = "N"
        nextCard = "  "
        currentScore = self.initialiseScore()
        while answer.upper() in ["N","S"]:
            previousCard = nextCard
            nextCard = self.playCard(currentScore,hands)
            start = time.time()
            answer = input("Please enter (S)nap or (N)ext")
            waited = time.time() - start
            self.determineWinner(currentScore,previousCard,nextCard,answer,waited,secondsToWait)

    def main(self):

        self.startCardGame()
        secondsToWait = int(input("Seconds to wait"))
        self.snap(self.hands,secondsToWait)

if __name__ == '__main__':
    snap = Snap()
    snap.main()


from yarndevtools.cdsw.cdsw_common import JiraUmbrellaDataFetcherCdswUtils, GenericCdswConfigUtils
from yarndevtools.cdsw.cdsw_config import Include
from yarndevtools.cdsw.constants import CdswEnvVar
from yarndevtools.common.shared_command_utils import CommandType
from yarndevtools.constants import SummaryFile

def generate_runs(conf):
    runs = [
        {
            "name": f"run-{umbrella_id}",
            "variables": {},
            "email_settings": {
                "enabled": True,
                "send_attachment": True,
                "attachment_file_name": f"{conf.var('commandDataFileName')}",
                "email_body_file_from_command_data": SummaryFile.HTML.value,
                "sender": f"{conf.var('sender')}",
                "subject": f"YARN Upstream umbrella checker report: [UMBRELLA: {umbrella_id} ({title}), start date: {conf.job_start_date()}]",
            },
            "drive_api_upload_settings": {
                "enabled": True,
                "file_name": f"{conf.var('commandDataFileName')}",
            },
            "yarn_dev_tools_arguments": [umbrella_id],
        }
        for umbrella_id, title in JiraUmbrellaDataFetcherCdswUtils.fetch_umbrella_titles(
            GenericCdswConfigUtils.unquote(conf.var("jiraUmbrellaIds")).split(" ")
        ).items()
    ]
    return runs

config = {
    "job_name": "Jira umbrella data fetcher",
    "command_type": CommandType.JIRA_UMBRELLA_DATA_FETCHER,
    "env_sanitize_exceptions": ["UMBRELLA_IDS"],
    "mandatory_env_vars": [
        "MAIL_ACC_USER",
        "MAIL_ACC_PASSWORD",
        # OLD: umbrella_ids = ["YARN-10496", "YARN-6223", "YARN-8820"]
        # NEW: umbrella_ids = ["YARN-10888", "YARN-10889"]
        "UMBRELLA_IDS",
    ],
    "optional_env_vars": [],
    "yarn_dev_tools_arguments": [
        lambda conf: f"{Include.when(conf.var('debugMode'), '--debug', '')}",
        f"{CommandType.JIRA_UMBRELLA_DATA_FETCHER.name}",
        lambda conf: f"--branches {conf.var('branches')}",
        lambda conf: f"{Include.when(conf.var('forceMode'), '--force-mode', '')}",
        lambda conf: f"{Include.when(conf.var('ignoreChanges'), '--ignore-changes', '')}",
    ],
    "global_variables": {
        "debugMode": lambda conf: conf.env_or_default(CdswEnvVar.DEBUG_ENABLED.value, True),
        "sender": "YARN upstream umbrella checker",
        "branches": "origin/CDH-7.1-maint origin/cdpd-master origin/CDH-7.1.6.x",
        "commandDataFileName": lambda conf: f"command_data_{conf.job_start_date()}.zip",
        "jiraUmbrellaIds": lambda conf: conf.env("UMBRELLA_IDS"),
        "forceMode": True,
        "ignoreChanges": True,
    },
    "runs": lambda conf: generate_runs(conf),
}


import time
from socket import *

# variables initialized before use
time_count1 = 0
time_count2 = 0
ping_number = 1
packet_loss = 0
ELAPSED_SUM = 0

#Send ping 10 times
while ( ping_number < 11 ):
    #Create a UDP socket
    clientSocket = socket(AF_INET, SOCK_DGRAM)
    clientSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

    #Set a timeout value of 1 second
    clientSocket.settimeout(1)

    #Ping to server
    message = bytes("ping", 'utf-8')

    addr = ("127.0.0.1", 12000)
    #Send ping
    start = time.time()
    clientSocket.sendto(message, addr)

    #If data is received back from server, print , it will calculate elapsed time and avg elapsed time
    try:
        data, server = clientSocket.recvfrom(1024)
        end = time.time()
        elapsed = end - start
        ELAPSED_SUM = elapsed + ELAPSED_SUM
        AVG_ELAPSED = ELAPSED_SUM/10

        #if loop is used to calculate the min and max time vaules
        if elapsed > time_count1:
            time_count1 = elapsed
        if elapsed > time_count1:
            time_count1 = elapsed
        if elapsed < time_count2:
             time_count2 = elapsed
        # printing data, ping_number and elapsed time
        print (data, ping_number, elapsed)

    #If data is not received from server, print it will print timeout
    except timeout:
        print ("REQUEST TIMED OUT")
        packet_loss = packet_loss + 1

    ping_number = ping_number + 1
packet_loss = (packet_loss * 10)
# print min, max, avg and Packet loss as per requirement
print("RTT: Min: %sms Avg: %sms Max: %sms PacketLoss: %s " % (time_count2, AVG_ELAPSED,time_count1, packet_loss))


import tools

class memory_t(object):
    def __init__(self):
        self.anchor  = ""
        self.date    = ""
        self.details = ""
        self.color   = -1

    def set_memory(self, anchor, details, color):
        self.anchor = anchor
        self.date = tools.time_formatted()
        self.details = details
        self.color = color

    def save(self):
        return {
            "anchor"  : self.anchor,
            "date"    : self.date,
            "details" : self.details,
            "color"   : self.color
        }

    def load(self, data):
        pass


import sys
import sqlite3 as sql

def main():
    sqliteFile = 'pokedex.sqlite'

    try:
        con = sql.connect(sqliteFile)
        cur = con.cursor()

        print('Find all the pokemon related to ______')
        userInput = input('>')

        cur.execute('''SELECT a.identifier
                        FROM pokemon_species AS a
                        LEFT JOIN pokemon_species AS b
                            ON a.evolution_chain_id = b.evolution_chain_id
                        WHERE b.identifier = LOWER("%s");''' % userInput )

        for name, in cur:
            print(name, end=', ')
        print()

    except TypeError:
        print('Couldn\'t find %s in database' % userInput)

    except sql.Error as e:
        print("Error %s:" % e.args[0])

    finally:
        if con:
            con.close()

if __name__ == '__main__':
    sys.exit(main())


from rrb3 import *
from random import randint
from flask import Flask
from json import dumps

app = Flask(__name__)

rr = RRB3(12, 12) # Battery voltage 12V, motor 12V

T = 20  # 20 seconds to extend

extended = True

@app.route('/start/<delai>')
def start(delai):
    T=delai
    return "ready"

@app.route('/stop')
def stop():
    rr.cleanup() # Set all GPIO pins to safe input state

@app.route('/extending')
def extending():
    print("extending")
    rr.set_led2(True)
    rr.forward(T, 1.0)
    rr.set_led2(False)
    extended = True
    return True

@app.route('/retracting')
def retracting():
    print("retracting")
    rr.set_led1(True)  # LED 1 on
    rr.reverse(T, 1.0)
    rr.set_led1(False)
    extended = False
    return True

if __name__ == '__main__':
     app.run(port='5002')