content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import click import requests from bs4 import BeautifulSoup from modules.Word.managers.DictionaryManager import DictionaryManager import re
[ 11748, 3904, 198, 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 13103, 13, 26449, 13, 805, 10321, 13, 35, 14188, 13511, 1330, 28261, 13511, 198, 11748, 302, 628 ]
4.242424
33
"""Datasets to be used in search and related functions""" from .DATASET import *
[ 37811, 27354, 292, 1039, 284, 307, 973, 287, 2989, 290, 3519, 5499, 37811, 198, 198, 6738, 764, 35, 1404, 1921, 2767, 1330, 1635 ]
3.521739
23
# -*- coding: utf-8 -*- import matplotlib as mpl import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from cell2cell.clustering import compute_linkage from cell2cell.preprocessing.manipulate_dataframes import check_symmetry from cell2cell.plotting.aesthetics import map_colors_to_metadata def clustermap_cci(interaction_space, method='ward', optimal_leaf=True, metadata=None, sample_col='#SampleID', group_col='Groups', meta_cmap='gist_rainbow', colors=None, excluded_cells=None, title='', cbar_title='CCI score', cbar_fontsize=18, filename=None, **kwargs): '''Generates a clustermap (heatmap + dendrograms from a hierarchical clustering) based on CCI scores of cell-cell pairs. Parameters ---------- interaction_space : cell2cell.core.interaction_space.InteractionSpace Interaction space that contains all a distance matrix after running the the method compute_pairwise_cci_scores. Alternatively, this object can be a numpy-array or a pandas DataFrame. Also, a SingleCellInteractions or a BulkInteractions object after running the method compute_pairwise_cci_scores. method : str, default='ward' Clustering method for computing a linkage as in scipy.cluster.hierarchy.linkage optimal_leaf : boolean, default=True Whether sorting the leaf of the dendrograms to have a minimal distance between successive leaves. For more information, see scipy.cluster.hierarchy.optimal_leaf_ordering metadata : pandas.Dataframe, default=None Metadata associated with the cells, cell types or samples in the matrix containing CCI scores. If None, cells will not be colored by major groups. sample_col : str, default='#SampleID' Column in the metadata for the cells, cell types or samples in the matrix containing CCI scores. group_col : str, default='Groups' Column in the metadata containing the major groups of cells, cell types or samples in the matrix with CCI scores. meta_cmap : str, default='gist_rainbow' Name of the color palette for coloring the major groups of cells. colors : dict, default=None Dictionary containing tuples in the RGBA format for indicating colors of major groups of cells. If colors is specified, meta_cmap will be ignored. excluded_cells : list, default=None List containing cell names that are present in the interaction_space object but that will be excluded from this plot. title : str, default='' Title of the clustermap. cbar_title : str, default='CCI score' Title for the colorbar, depending on the score employed. cbar_fontsize : int, default=18 Font size for the colorbar title as well as labels for axes X and Y. filename : str, default=None Path to save the figure of the elbow analysis. If None, the figure is not saved. **kwargs : dict Dictionary containing arguments for the seaborn.clustermap function. Returns ------- hier : seaborn.matrix.ClusterGrid A seaborn ClusterGrid instance. ''' if hasattr(interaction_space, 'distance_matrix'): print('Interaction space detected as an InteractionSpace class') distance_matrix = interaction_space.distance_matrix space_type = 'class' elif (type(interaction_space) is np.ndarray) or (type(interaction_space) is pd.core.frame.DataFrame): print('Interaction space detected as a distance matrix') distance_matrix = interaction_space space_type = 'matrix' elif hasattr(interaction_space, 'interaction_space'): print('Interaction space detected as a Interactions class') if not hasattr(interaction_space.interaction_space, 'distance_matrix'): raise ValueError('First run the method compute_pairwise_interactions() in your interaction' + \ ' object to generate a distance matrix.') else: interaction_space = interaction_space.interaction_space distance_matrix = interaction_space.distance_matrix space_type = 'class' else: raise ValueError('First run the method compute_pairwise_interactions() in your interaction' + \ ' object to generate a distance matrix.') # Drop excluded cells if excluded_cells is not None: df = distance_matrix.loc[~distance_matrix.index.isin(excluded_cells), ~distance_matrix.columns.isin(excluded_cells)] else: df = distance_matrix # Check symmetry to get linkage symmetric = check_symmetry(df) if (not symmetric) & (type(interaction_space) is pd.core.frame.DataFrame): assert set(df.index) == set(df.columns), 'The distance matrix does not have the same elements in rows and columns' # Obtain info for generating plot linkage = _get_distance_matrix_linkages(df=df, kwargs=kwargs, method=method, optimal_ordering=optimal_leaf, symmetric=symmetric ) kwargs_ = kwargs.copy() # PLOT CCI MATRIX if space_type == 'class': df = interaction_space.interaction_elements['cci_matrix'] else: df = distance_matrix if excluded_cells is not None: df = df.loc[~df.index.isin(excluded_cells), ~df.columns.isin(excluded_cells)] # Colors if metadata is not None: col_colors = map_colors_to_metadata(metadata=metadata, ref_df=df, colors=colors, sample_col=sample_col, group_col=group_col, cmap=meta_cmap) if not symmetric: row_colors = col_colors else: row_colors = None else: col_colors = None row_colors = None # Plot hierarchical clustering (triangular) hier = _plot_triangular_clustermap(df=df, symmetric=symmetric, linkage=linkage, col_colors=col_colors, row_colors=row_colors, title=title, cbar_title=cbar_title, cbar_fontsize=cbar_fontsize, **kwargs_) if ~symmetric: hier.ax_heatmap.set_xlabel('Receiver cells', fontsize=cbar_fontsize) hier.ax_heatmap.set_ylabel('Sender cells', fontsize=cbar_fontsize) if filename is not None: plt.savefig(filename, dpi=300, bbox_inches='tight') return hier def _get_distance_matrix_linkages(df, kwargs, method='ward', optimal_ordering=True, symmetric=None): '''Computes linkages for the CCI matrix. Parameters ---------- df : pandas.DataFrame Contains the CCI scores in a form of distances (that is, smaller values represent stronger interactions). Diagonal must be filled by zeros. kwargs : dict Dictionary containing arguments for the seaborn.clustermap function. method : str, default='ward' Clustering method for computing a linkage as in scipy.cluster.hierarchy.linkage optimal_ordering : boolean, default=True Whether sorting the leaf of the dendrograms to have a minimal distance between successive leaves. For more information, see scipy.cluster.hierarchy.optimal_leaf_ordering symmetric : boolean, default=None Whether df is symmetric. Returns ------- linkage : ndarray The hierarchical clustering of cells encoded as a linkage matrix. ''' if symmetric is None: symmetric = check_symmetry(df) if symmetric: if 'col_cluster' in kwargs.keys(): kwargs['row_cluster'] = kwargs['col_cluster'] if kwargs['col_cluster']: linkage = compute_linkage(df, method=method, optimal_ordering=optimal_ordering) else: linkage = None elif 'row_cluster' in kwargs.keys(): if kwargs['row_cluster']: linkage = compute_linkage(df, method=method, optimal_ordering=optimal_ordering) else: linkage = None else: linkage = compute_linkage(df, method=method, optimal_ordering=optimal_ordering) else: linkage = None return linkage def _triangularize_distance_matrix(df, linkage=None, symmetric=None, **kwargs): '''Generates a mask to plot the upper triangle of the CCI matrix. Parameters ---------- df : pandas.DataFrame Contains the CCI scores. Must be a symmetric matrix. linkage : ndarray, default=None The hierarchical clustering of cells encoded as a linkage matrix. symmetric : boolean, default=None Whether df is symmetric. **kwargs : dict Dictionary containing arguments for the seaborn.clustermap function. Returns ------- mask : ndarray Mask that contains ones in the places to be hidden in the clustermap. Only the diagonal and the upper triangle are not masked (contain zeros). ''' if symmetric is None: symmetric = check_symmetry(df) # Triangular matrix if symmetric: order_map = dict() if linkage is None: mask = np.ones((df.shape[0], df.shape[1])) for i in range(mask.shape[0]): for j in range(i, mask.shape[1]): mask[i, j] = 0 else: # Plot hierarchical clustering for getting indexes according to linkage hier = sns.clustermap(df, col_linkage=linkage, row_linkage=linkage, **kwargs ) plt.close() ind_order = hier.dendrogram_col.reordered_ind mask = np.zeros((df.shape[0], df.shape[1])) for i, ind in enumerate(ind_order): order_map[i] = ind filter_list = [order_map[j] for j in range(i)] mask[ind, filter_list] = 1 else: mask = None return mask def _plot_triangular_clustermap(df, symmetric=None, linkage=None, mask=None, col_colors=None, row_colors=None, title='', cbar_title='CCI score', cbar_fontsize=12, **kwargs): '''Plots a triangular clustermap based on a mask. Parameters ---------- df : pandas.DataFrame Contains the CCI scores. Must be a symmetric matrix. linkage : ndarray, default=None The hierarchical clustering of cells encoded as a linkage matrix. mask : ndarray, default=None Mask that contains ones in the places to be hidden in the clustermap. Only the diagonal and the upper triangle are not masked (contain zeros). If None, a mask will be computed based on the CCI matrix symmetry. col_colors : dict, default=None Dictionary containing tuples in the RGBA format for indicating colors of major groups of cells in the columns. row_colors : dict, default=None Dictionary containing tuples in the RGBA format for indicating colors of major groups of cells in the rows. title : str, default='' Title of the clustermap. cbar_title : str, default='CCI score' Title for the colorbar, depending on the score employed. cbar_fontsize : int, default=12 Font size for the colorbar title as well as labels for axes X and Y. **kwargs : dict Dictionary containing arguments for the seaborn.clustermap function. Returns ------- hier : seaborn.matrix.ClusterGrid A seaborn ClusterGrid instance. ''' if symmetric is None: symmetric = check_symmetry(df) if mask is None: mask = _triangularize_distance_matrix(df=df, linkage=linkage, symmetric=symmetric, **kwargs ) hier = sns.clustermap(df, col_linkage=linkage, row_linkage=linkage, mask=mask, col_colors=col_colors, row_colors=row_colors, **kwargs ) hier = _move_xticks_triangular_clustermap(clustermap=hier, symmetric=symmetric ) # Title if len(title) > 0: hier.ax_col_dendrogram.set_title(title, fontsize=16) # Color bar label cbar = hier.ax_heatmap.collections[0].colorbar cbar.ax.set_ylabel(cbar_title, fontsize=cbar_fontsize) cbar.ax.yaxis.set_label_position("left") return hier def _move_xticks_triangular_clustermap(clustermap, symmetric=True): '''Moves xticks to the diagonal when plotting a symmetric matrix in the form of a upper triangle. Parameters --------- clustermap : seaborn.matrix.ClusterGrid A seaborn ClusterGrid instance. symmetric : boolean, default=None Whether the CCI matrix plotted in the clustermap is symmetric. Returns ------- clustermap : seaborn.matrix.ClusterGrid A seaborn ClusterGrid instance, with the xticks moved to the diagonal if the CCI matrix was symmetric. If not, the same input clustermap is returned, but with rotated xtick labels. ''' if symmetric: # Apply offset transform to all xticklabels. clustermap.ax_row_dendrogram.set_visible(False) clustermap.ax_heatmap.tick_params(bottom=False) # Hide xtick line x_labels = clustermap.ax_heatmap.xaxis.get_majorticklabels() dpi_x = clustermap.fig.dpi_scale_trans.to_values()[0] dpi_y = clustermap.fig.dpi_scale_trans.to_values()[3] x0 = clustermap.ax_heatmap.transData.transform(x_labels[0].get_position()) x1 = clustermap.ax_heatmap.transData.transform(x_labels[1].get_position()) ylims = clustermap.ax_heatmap.get_ylim() bottom_points = clustermap.ax_heatmap.transData.transform((1.0, ylims[0]))[1] for i, xl in enumerate(x_labels): # Move labels in dx and dy points. swap_xy = (1.0, xl.get_position()[0] + 0.5) new_y_points = clustermap.ax_heatmap.transData.transform(swap_xy)[1] dx = -0.5 * abs(x1[0] - x0[0]) / dpi_x dy = (new_y_points - bottom_points) / dpi_y offset = mpl.transforms.ScaledTranslation(dx, dy, clustermap.fig.dpi_scale_trans) xl.set_transform(xl.get_transform() + offset) if symmetric: rot = 45 else: rot = 90 va = 'center' clustermap.ax_heatmap.set_xticklabels(clustermap.ax_heatmap.xaxis.get_majorticklabels(), rotation=rot, rotation_mode='anchor', va='bottom', ha='right') # , fontsize=9.5) clustermap.ax_heatmap.set_yticklabels(clustermap.ax_heatmap.yaxis.get_majorticklabels(), rotation=0, va=va, ha='left') # , fontsize=9.5) return clustermap
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, ...
2.188086
7,353
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os from spack.package import *
[ 2, 15069, 2211, 12, 1238, 1828, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, ...
3.4
70
from mp4box.box import CompositionTimeToSampleBox
[ 6738, 29034, 19, 3524, 13, 3524, 1330, 955, 9150, 7575, 2514, 36674, 14253, 201, 198, 201, 198 ]
3.117647
17
import pickle import numpy as np import matplotlib.pyplot as plt from lightweaver.rh_atoms import H_6_atom, C_atom, O_atom, OI_ord_atom, Si_atom, Al_atom, Fe_atom, FeI_atom, MgII_atom, N_atom, Na_atom, S_atom, CaII_atom from lightweaver.atmosphere import Atmosphere, ScaleType from lightweaver.atomic_table import DefaultAtomicAbundance from lightweaver.atomic_set import RadiativeSet, SpeciesStateTable from lightweaver.molecule import MolecularTable from lightweaver.LwCompiled import LwContext from lightweaver.utils import InitialSolution, planck, NgOptions, ConvergenceError, compute_radiative_losses, integrate_line_losses import lightweaver.constants as Const import lightweaver as lw from typing import List from copy import deepcopy from MsLightweaverAtoms import H_6, CaII, H_6_nasa, CaII_nasa import os import os.path as path import time from radynpy.matsplotlib import OpcFile from radynpy.utils import hydrogen_absorption from numba import njit from pathlib import Path from scipy.linalg import solve from scipy.interpolate import interp1d, PchipInterpolator # from HydroWeno.Simulation import Grid # from HydroWeno.Advector import Advector # from HydroWeno.BCs import zero_grad_bc # from HydroWeno.Weno import reconstruct_weno_nm_z import warnings from traceback import print_stack from weno4 import weno4 from RadynAdvection import an_sol, an_rad_sol, an_gml_sol import pdb # https://stackoverflow.com/a/21901260 import subprocess def convert_atomic_pops(atom): d = {} if atom.pops is not None: d['n'] = atom.pops else: d['n'] = atom.pops d['nStar'] = atom.nStar d['radiativeRates'] = atom.radiativeRates return d def distill_pops(eqPops): d = {} for atom in eqPops.atomicPops: d[atom.element.name] = convert_atomic_pops(atom) return d
[ 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1657, 732, 8770, 13, 17179, 62, 265, 3150, 1330, 367, 62, 21, 62, 37696, 11, 327, 62, 37696, 11, 440, 62,...
2.809598
646
# coding:utf-8 from openpyxl import load_workbook import openpyxl from openpyxl.styles import Font, colors def copy_excel(cese_path, report_path): """ report_path :param cese_path: :param report_path: :return: """ wb2 = openpyxl.Workbook() wb2.save(report_path) # excel # wb1 = openpyxl.load_workbook(cese_path) wb2 = openpyxl.load_workbook(report_path) sheets1 = wb1.sheetnames sheets2 = wb2.sheetnames sheet1 = wb1[sheets1[0]] # sheet sheet2 = wb2[sheets2[0]] max_row = sheet1.max_row # max_column = sheet1.max_column # for m in list(range(1, max_row + 1)): for n in list(range(97, 97 + max_column)): # chr(97)='a' n = chr(n) # ASCII,excel a b c i = '%s%d' % (n, m) # cell1 = sheet1[i].value # sheet2[i].value = cell1 # wb2.save(report_path) # wb1.close() # excel wb2.close() if __name__ == "__main__": # copy_excel("demo_api_3.xlsx", "test111.xlsx") wt = Write_excel("test111.xlsx") wt.write(4, 5, "HELLEOP") wt.write(4, 6, "HELLEOP")
[ 2, 19617, 25, 40477, 12, 23, 198, 6738, 1280, 9078, 87, 75, 1330, 3440, 62, 1818, 2070, 198, 11748, 1280, 9078, 87, 75, 198, 6738, 1280, 9078, 87, 75, 13, 47720, 1330, 24060, 11, 7577, 628, 198, 4299, 4866, 62, 1069, 5276, 7, 728,...
1.946087
575
# # Copyright (C) 2018 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # model = Model() i1 = Input("op1", "TENSOR_FLOAT32", "{1, 3, 3, 2}") f1 = Input("op2", "TENSOR_FLOAT32", "{1, 2, 2, 4}") b1 = Input("op3", "TENSOR_FLOAT32", "{4}") pad0 = Int32Scalar("pad0", 0) act = Int32Scalar("act", 0) stride = Int32Scalar("stride", 1) cm = Int32Scalar("channelMultiplier", 2) output = Output("op4", "TENSOR_FLOAT32", "{1, 2, 2, 4}") model = model.Operation("DEPTHWISE_CONV_2D", i1, f1, b1, pad0, pad0, pad0, pad0, stride, stride, cm, act).To(output) model = model.RelaxedExecution(True) # Example 1. Input in operand 0, input0 = {i1: # input 0 [10, 21, 10, 22, 10, 23, 10, 24, 10, 25, 10, 26, 10, 27, 10, 28, 10, 29], f1: [.25, 0, .2, 0, .25, 0, 0, .3, .25, 0, 0, 0, .25, .1, 0, 0], b1: [1, 2, 3, 4]} # (i1 (conv) f1) + b1 # filter usage: # in_ch1 * f_1 --> output_d1 # in_ch1 * f_2 --> output_d2 # in_ch2 * f_3 --> output_d3 # in_ch3 * f_4 --> output_d4 output0 = {output: # output 0 [11, 3, 7.2, 10.6, 11, 3, 7.4, 10.9, 11, 3, 7.8, 11.5, 11, 3, 8.0, 11.8]} # Instantiate an example Example((input0, output0))
[ 2, 198, 2, 15069, 357, 34, 8, 2864, 383, 5565, 4946, 8090, 4935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.042918
932
from typing import Sequence, Any from jina.executors.evaluators.rank import BaseRankingEvaluator from jina.executors.evaluators.decorators import as_aggregator
[ 6738, 19720, 1330, 45835, 11, 4377, 198, 198, 6738, 474, 1437, 13, 18558, 315, 669, 13, 18206, 84, 2024, 13, 43027, 1330, 7308, 49, 15230, 36, 2100, 84, 1352, 198, 6738, 474, 1437, 13, 18558, 315, 669, 13, 18206, 84, 2024, 13, 12501...
3.115385
52
from typedpy import Array, DoNotSerialize, Structure, mappers
[ 6738, 25683, 9078, 1330, 15690, 11, 2141, 3673, 32634, 1096, 11, 32522, 11, 285, 46629, 628 ]
3.9375
16
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import dataclasses from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Dict, Generic, List, Optional, Sequence, TypeVar from semantic_parsing_with_constrained_lm.datum import FullDatum, FullDatumSub from semantic_parsing_with_constrained_lm.model import ModelResult Pred = TypeVar("Pred") Target = TypeVar("Target") # TODO: Replcae this with a more flexible function suited to each domain
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 198, 11748, 4818, 330, 28958, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 1...
3.489655
145
# -*- coding: utf-8 -*- # # Copyright 2016 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command for spanner operations list.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import textwrap from googlecloudsdk.api_lib.spanner import backup_operations from googlecloudsdk.api_lib.spanner import database_operations from googlecloudsdk.api_lib.spanner import instance_config_operations from googlecloudsdk.api_lib.spanner import instance_operations from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions as c_exceptions from googlecloudsdk.command_lib.spanner import flags def _CommonRun(args): """Performs run actions common to all List stages.""" is_database_type = ( args.type == 'DATABASE_RESTORE' or args.type == 'DATABASE' or args.type == 'DATABASE_CREATE' or args.type == 'DATABASE_UPDATE_DDL') if args.backup or args.type == 'BACKUP': # Update output table for backup operations. # pylint:disable=protected-access args._GetParser().ai.display_info.AddFormat(""" table( name.basename():label=OPERATION_ID, done():label=DONE, metadata.'@type'.split('.').slice(-1:).join(), metadata.name.split('/').slice(-1:).join():label=BACKUP, metadata.database.split('/').slice(-1).join():label=SOURCE_DATABASE, metadata.progress.startTime:label=START_TIME, metadata.progress.endTime:label=END_TIME ) """) if args.type == 'DATABASE_RESTORE': # Update output table for restore operations. # pylint:disable=protected-access args._GetParser().ai.display_info.AddFormat(""" table( name.basename():label=OPERATION_ID, done():label=DONE, metadata.'@type'.split('.').slice(-1:).join(), metadata.name.split('/').slice(-1:).join():label=RESTORED_DATABASE, metadata.backupInfo.backup.split('/').slice(-1).join():label=SOURCE_BACKUP, metadata.progress.startTime:label=START_TIME, metadata.progress.endTime:label=END_TIME ) """) elif is_database_type: # Update output table for database operations. # pylint:disable=protected-access args._GetParser().ai.display_info.AddFormat(""" table( name.basename():label=OPERATION_ID, metadata.statements.join(sep="\n"), done():label=DONE, metadata.'@type'.split('.').slice(-1:).join(), database().split('/').slice(-1:).join():label=DATABASE_ID ) """) # Checks that user only specified either database or backup flag. if (args.IsSpecified('database') and args.IsSpecified('backup')): raise c_exceptions.InvalidArgumentException( '--database or --backup', 'Must specify either --database or --backup. To search backups for a ' 'specific database, use the --database flag with --type=BACKUP') # Checks that the user did not specify the backup flag with the type filter # set to a database operation type. if (args.IsSpecified('backup') and is_database_type): raise c_exceptions.InvalidArgumentException( '--backup or --type', 'The backup flag cannot be used with the type flag set to a ' 'database operation type.') if args.type == 'INSTANCE': if args.IsSpecified('database'): raise c_exceptions.InvalidArgumentException( '--database or --type', 'The `--database` flag cannot be used with `--type=INSTANCE`.') if args.IsSpecified('backup'): raise c_exceptions.InvalidArgumentException( '--backup or --type', 'The `--backup` flag cannot be used with `--type=INSTANCE`.') if args.type == 'BACKUP': if args.database: db_filter = backup_operations.BuildDatabaseFilter(args.instance, args.database) return backup_operations.List(args.instance, db_filter) if args.backup: return backup_operations.ListGeneric(args.instance, args.backup) return backup_operations.List(args.instance) if is_database_type: type_filter = database_operations.BuildDatabaseOperationTypeFilter( args.type) return database_operations.ListDatabaseOperations(args.instance, args.database, type_filter) if args.backup: return backup_operations.ListGeneric(args.instance, args.backup) if args.database: return database_operations.List(args.instance, args.database) return instance_operations.List(args.instance)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 1303, 198, 2, 15069, 1584, 3012, 11419, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198,...
2.57905
2,043
import os import unittest import numpy as np import networkx as nx import numpy.testing as npt from pgmpy.models import SEM, SEMGraph, SEMAlg
[ 11748, 28686, 198, 11748, 555, 715, 395, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 3127, 87, 355, 299, 87, 198, 11748, 299, 32152, 13, 33407, 355, 299, 457, 198, 198, 6738, 23241, 3149, 88, 13, 27530, 1330, 48603, 11, 48603...
3
49
# coding=utf-8 # This script is finished following HF's datasets' template: # https://github.com/huggingface/datasets/blob/master/templates/new_dataset_script.py # More examples as references to write a customized dataset can be found here: # https://github.com/huggingface/datasets/tree/master/datasets from __future__ import absolute_import, division, print_function import json import datasets _CITATION = """\ """ _DESCRIPTION = """\ """ _TRAIN_DOWNLOAD_URL = "data/train.json" _VAL_DOWNLOAD_URL = "data/val.json"
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 770, 4226, 318, 5201, 1708, 42253, 338, 40522, 6, 11055, 25, 198, 2, 3740, 1378, 12567, 13, 785, 14, 71, 1018, 2667, 2550, 14, 19608, 292, 1039, 14, 2436, 672, 14, 9866, 14, 11498, 17041, 14, ...
3.011494
174
import itertools from typing import Sequence, Iterator # Source: https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/core/utils/chat_formatting.py def error(text: str) -> str: """Get text prefixed with an error emoji. Returns ------- str The new message. """ return "\N{NO ENTRY SIGN} {}".format(text) def warning(text: str) -> str: """Get text prefixed with a warning emoji. Returns ------- str The new message. """ return "\N{WARNING SIGN} {}".format(text) def info(text: str) -> str: """Get text prefixed with an info emoji. Returns ------- str The new message. """ return "\N{INFORMATION SOURCE} {}".format(text) def question(text: str) -> str: """Get text prefixed with a question emoji. Returns ------- str The new message. """ return "\N{BLACK QUESTION MARK ORNAMENT} {}".format(text) def bold(text: str) -> str: """Get the given text in bold. Parameters ---------- text : str The text to be marked up. Returns ------- str The marked up text. """ return "**{}**".format(text) def box(text: str, lang: str = "") -> str: """Get the given text in a code block. Parameters ---------- text : str The text to be marked up. lang : `str`, optional The syntax highlighting language for the codeblock. Returns ------- str The marked up text. """ ret = "```{}\n{}\n```".format(lang, text) return ret def inline(text: str) -> str: """Get the given text as inline code. Parameters ---------- text : str The text to be marked up. Returns ------- str The marked up text. """ return "`{}`".format(text) def italics(text: str) -> str: """Get the given text in italics. Parameters ---------- text : str The text to be marked up. Returns ------- str The marked up text. """ return "*{}*".format(text) def bordered(*columns: Sequence[str], ascii_border: bool = False) -> str: """Get two blocks of text in a borders. Note ---- This will only work with a monospaced font. Parameters ---------- *columns : `sequence` of `str` The columns of text, each being a list of lines in that column. ascii_border : bool Whether or not the border should be pure ASCII. Returns ------- str The bordered text. """ borders = { "TL": "-" if ascii_border else "", # Top-left "TR": "-" if ascii_border else "", # Top-right "BL": "-" if ascii_border else "", # Bottom-left "BR": "-" if ascii_border else "", # Bottom-right "HZ": "-" if ascii_border else "", # Horizontal "VT": "|" if ascii_border else "", # Vertical } sep = " " * 4 # Separator between boxes widths = tuple( max(len(row) for row in column) + 9 for column in columns ) # width of each col colsdone = [False] * len(columns) # whether or not each column is done lines = [sep.join("{TL}" + "{HZ}" * width + "{TR}" for width in widths)] for line in itertools.zip_longest(*columns): row = [] for colidx, column in enumerate(line): width = widths[colidx] done = colsdone[colidx] if column is None: if not done: # bottom border of column column = "{HZ}" * width row.append("{BL}" + column + "{BR}") colsdone[colidx] = True # mark column as done else: # leave empty row.append(" " * (width + 2)) else: column += " " * (width - len(column)) # append padded spaces row.append("{VT}" + column + "{VT}") lines.append(sep.join(row)) final_row = [] for width, done in zip(widths, colsdone): if not done: final_row.append("{BL}" + "{HZ}" * width + "{BR}") else: final_row.append(" " * (width + 2)) lines.append(sep.join(final_row)) return "\n".join(lines).format(**borders) def strikethrough(text: str) -> str: """Get the given text with a strikethrough. Parameters ---------- text : str The text to be marked up. Returns ------- str The marked up text. """ return "~~{}~~".format(text) def underline(text: str) -> str: """Get the given text with an underline. Parameters ---------- text : str The text to be marked up. Returns ------- str The marked up text. """ return "__{}__".format(text) def escape(text: str, *, mass_mentions: bool = False, formatting: bool = False) -> str: """Get text with all mass mentions or markdown escaped. Parameters ---------- text : str The text to be escaped. mass_mentions : `bool`, optional Set to :code:`True` to escape mass mentions in the text. formatting : `bool`, optional Set to :code:`True` to escpae any markdown formatting in the text. Returns ------- str The escaped text. """ if mass_mentions: text = text.replace("@everyone", "@\u200beveryone") text = text.replace("@here", "@\u200bhere") if formatting: text = ( text.replace("`", "\\`") .replace("*", "\\*") .replace("_", "\\_") .replace("~", "\\~") ) return text
[ 11748, 340, 861, 10141, 198, 6738, 19720, 1330, 45835, 11, 40806, 1352, 198, 198, 2, 8090, 25, 3740, 1378, 12567, 13, 785, 14, 34, 519, 12, 16719, 669, 14, 7738, 12, 15642, 585, 20630, 14, 2436, 672, 14, 53, 18, 14, 16244, 14, 445...
2.294094
2,455
# @date 2018-12-28 # @author Frederic Scherma, All rights reserved without prejudices. # @license Copyright (c) 2018 Dream Overflow # Strategy trade for margin with multiples positions. from __future__ import annotations from typing import TYPE_CHECKING, Optional, Tuple if TYPE_CHECKING: from trader.trader import Trader from instrument.instrument import Instrument from strategy.strategytrader import StrategyTrader from strategy.strategytradercontext import StrategyTraderContextBuilder from common.signal import Signal from trader.order import Order from .strategytrade import StrategyTrade import logging logger = logging.getLogger('siis.strategy.margintrade') # # persistence # # # stats #
[ 2, 2488, 4475, 2864, 12, 1065, 12, 2078, 198, 2, 2488, 9800, 18669, 291, 47956, 2611, 11, 1439, 2489, 10395, 1231, 39800, 13, 198, 2, 2488, 43085, 15069, 357, 66, 8, 2864, 7610, 3827, 11125, 198, 2, 20561, 3292, 329, 10330, 351, 502...
3.465116
215
# local from .panels import SqlalchemyCsvDebugPanel __VERSION__ = "0.3.1" # ============================================================================== def includeme(config): """ Pyramid hook to install this debugtoolbar plugin. Update your ENVIRONMENT.ini file debugtoolbar.includes = pyramid_debugtoolbar_api_sqlalchemy """ config.add_debugtoolbar_panel(SqlalchemyCsvDebugPanel) config.add_route( "debugtoolbar.api_sqlalchemy.queries.csv", "/api-sqlalchemy/sqlalchemy-{request_id}.csv", ) config.scan("pyramid_debugtoolbar_api_sqlalchemy.views") config.commit() # ==============================================================================
[ 2, 1957, 198, 6738, 764, 6839, 1424, 1330, 311, 13976, 282, 26599, 34, 21370, 27509, 26639, 628, 198, 834, 43717, 834, 796, 366, 15, 13, 18, 13, 16, 1, 628, 198, 2, 38093, 25609, 28, 628, 198, 4299, 846, 34755, 7, 11250, 2599, 198...
3.094828
232
# -*- coding: utf-8 -*- import os,os.path import zipfile
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 11, 418, 13, 6978, 198, 11748, 19974, 7753 ]
2.28
25
#!/usr/bin/env python3 import boto import boto.ec2 import sys from pprint import pprint from collections import defaultdict output = defaultdict(lambda: []) comments = defaultdict(lambda: {}) skip_region_strings = ['us-gov', 'cn-', 'ca-'] #skip_region_strings = ['us-gov', 'cn-', 'ca-', 'eu-', 'ap-'] if len(sys.argv) > 1: filter = sys.argv[1] else: filter = False regions = boto.ec2.regions() for region in regions: if any (skip_string in region.name for skip_string in skip_region_strings): continue print('# Querying region:', region) ec2conn = boto.connect_ec2(region=region) reservations = ec2conn.get_all_instances() instances = [i for r in reservations for i in r.instances] for i in instances: if filter: if 'Name' in i.tags: if filter not in i.tags['Name']: continue if 'running' not in i.state: continue if 'Name' in i.tags: if 'Packer' in i.tags['Name']: continue if i.tags['Name'].count('_') == 2: try: (net, group, num) = i.tags['Name'].split('_') myregion = region.name except: print('Error parsing ', i.tags['Name']) continue elif i.tags['Name'].count('_') == 3: try: (net, myregion, group, num) = i.tags['Name'].split('_') except: print('Error parsing ', i.tags['Name']) continue groupname = "%ss" % group else: print('NONAME', end='') groupname = 'unknown' i.tags['Name'] = 'NONE' output[groupname].append(i.public_dns_name) try: comments[groupname][i.public_dns_name] = "# %s\t%s\t%s\t%s\t%s" % (i.tags['Name'], myregion, i.instance_type, i.ip_address, i.launch_time) except: comments[groupname][i.public_dns_name] = "# MISSING DATA" for group in output: print("[%s]" % group) hostlist = output[group] hostlist.sort() for host in hostlist: print("%s \t%s" % (host, comments[group][host])) print("\n")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 275, 2069, 198, 11748, 275, 2069, 13, 721, 17, 198, 11748, 25064, 198, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 22915,...
2.305459
861
"""Install exception handler for process crash.""" from selfdrive.swaglog import cloudlog from selfdrive.version import version import sentry_sdk from sentry_sdk.integrations.threading import ThreadingIntegration
[ 37811, 15798, 6631, 21360, 329, 1429, 7014, 526, 15931, 198, 6738, 2116, 19472, 13, 2032, 363, 6404, 1330, 6279, 6404, 198, 6738, 2116, 19472, 13, 9641, 1330, 2196, 198, 198, 11748, 1908, 563, 62, 21282, 74, 198, 6738, 1908, 563, 62, ...
3.890909
55
import math import visualization.panda.world as wd import modeling.geometric_model as gm import modeling.collision_model as cm import grasping.planning.antipodal as gpa import robot_sim.end_effectors.grippers.yumi_gripper.yumi_gripper as yg base = wd.World(cam_pos=[1, 1, 1],w=960, h=540, lookat_pos=[0, 0, 0]) gm.gen_frame().attach_to(base) # object object_tube = cm.CollisionModel("objects/tubebig.stl") object_tube.set_rgba([.9, .75, .35, 1]) object_tube.attach_to(base) # hnd_s gripper_s = yg.YumiGripper() grasp_info_list = gpa.plan_grasps(gripper_s, object_tube, angle_between_contact_normals=math.radians(177), openning_direction='loc_x', max_samples=15, min_dist_between_sampled_contact_points=.005, contact_offset=.005) gpa.write_pickle_file('tubebig', grasp_info_list, './', 'yumi_tube_big.pickle') for grasp_info in grasp_info_list: jaw_width, jaw_center_pos, jaw_center_rotmat, hnd_pos, hnd_rotmat = grasp_info gripper_s.grip_at_with_jcpose(jaw_center_pos, jaw_center_rotmat, jaw_width) gripper_s.gen_meshmodel(rgba=(1,0,0,0.01)).attach_to(base) base.run()
[ 11748, 10688, 198, 11748, 32704, 13, 79, 5282, 13, 6894, 355, 266, 67, 198, 11748, 21128, 13, 469, 16996, 62, 19849, 355, 308, 76, 198, 11748, 21128, 13, 26000, 1166, 62, 19849, 355, 12067, 198, 11748, 44787, 13, 11578, 768, 13, 415, ...
2.054908
601
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Main entry point into the Assignment service.""" import copy import itertools from oslo_log import log from keystone.common import cache from keystone.common import driver_hints from keystone.common import manager from keystone.common import provider_api import keystone.conf from keystone import exception from keystone.i18n import _ from keystone import notifications CONF = keystone.conf.CONF LOG = log.getLogger(__name__) PROVIDERS = provider_api.ProviderAPIs # This is a general cache region for assignment administration (CRUD # operations). MEMOIZE = cache.get_memoization_decorator(group='role') # This builds a discrete cache region dedicated to role assignments computed # for a given user + project/domain pair. Any write operation to add or remove # any role assignment should invalidate this entire cache region. COMPUTED_ASSIGNMENTS_REGION = cache.create_region(name='computed assignments') MEMOIZE_COMPUTED_ASSIGNMENTS = cache.get_memoization_decorator( group='role', region=COMPUTED_ASSIGNMENTS_REGION)
[ 2, 15069, 2321, 4946, 25896, 5693, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, ...
3.643498
446
import numpy as np import os from chainercv.chainer_experimental.datasets.sliceable import GetterDataset from chainercv.utils import read_image linemod_object_diameters = { 'ape': 0.103, 'benchvise': 0.286908, 'cam': 0.173, 'can': 0.202, 'cat': 0.155, 'driller': 0.262, 'duck': 0.109, 'eggbox': 0.176364, 'glue': 0.176, 'holepuncher': 0.162, 'iron': 0.303153, 'lamp': 0.285155, 'phone': 0.213}
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 198, 6738, 6333, 2798, 85, 13, 7983, 263, 62, 23100, 9134, 13, 19608, 292, 1039, 13, 48369, 540, 1330, 3497, 353, 27354, 292, 316, 198, 6738, 6333, 2798, 85, 13, 26791, 1330, 1100...
2.077982
218
import FWCore.ParameterSet.Config as cms process = cms.Process("BeamMonitor") #---------------------------- # Common part for PP and H.I Running #----------------------------- process.load("DQM.Integration.test.inputsource_cfi") #-------------------------- # HLT Filter process.load("HLTrigger.special.HLTTriggerTypeFilter_cfi") # 0=random, 1=physics, 2=calibration, 3=technical process.hltTriggerTypeFilter.SelectedTriggerType = 1 #---------------------------- # DQM Live Environment #----------------------------- process.load("DQM.Integration.test.environment_cfi") process.dqmEnv.subSystemFolder = 'BeamMonitor' import DQMServices.Components.DQMEnvironment_cfi process.dqmEnvPixelLess = DQMServices.Components.DQMEnvironment_cfi.dqmEnv.clone() process.dqmEnvPixelLess.subSystemFolder = 'BeamMonitor_PixelLess' #---------------------------- # BeamMonitor #----------------------------- process.load("DQM.BeamMonitor.BeamMonitor_cff") process.load("DQM.BeamMonitor.BeamMonitorBx_cff") process.load("DQM.BeamMonitor.BeamMonitor_PixelLess_cff") process.load("DQM.BeamMonitor.BeamConditionsMonitor_cff") #### SETUP TRACKING RECONSTRUCTION #### process.load("Configuration.StandardSequences.GeometryRecoDB_cff") process.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff') process.load("DQM.Integration.test.FrontierCondition_GT_cfi") process.load("Configuration.StandardSequences.RawToDigi_Data_cff") # Change Beam Monitor variables if process.dqmSaver.producer.value() is "Playback": process.dqmBeamMonitor.BeamFitter.WriteAscii = False process.dqmBeamMonitor.BeamFitter.AsciiFileName = '/nfshome0/yumiceva/BeamMonitorDQM/BeamFitResults.txt' process.dqmBeamMonitor.BeamFitter.WriteDIPAscii = True process.dqmBeamMonitor.BeamFitter.DIPFileName = '/nfshome0/dqmdev/BeamMonitorDQM/BeamFitResults.txt' else: process.dqmBeamMonitor.BeamFitter.WriteAscii = True process.dqmBeamMonitor.BeamFitter.AsciiFileName = '/nfshome0/yumiceva/BeamMonitorDQM/BeamFitResults.txt' process.dqmBeamMonitor.BeamFitter.WriteDIPAscii = True process.dqmBeamMonitor.BeamFitter.DIPFileName = '/nfshome0/dqmpro/BeamMonitorDQM/BeamFitResults.txt' #process.dqmBeamMonitor.BeamFitter.SaveFitResults = False #process.dqmBeamMonitor.BeamFitter.OutputFileName = '/nfshome0/yumiceva/BeamMonitorDQM/BeamFitResults.root' process.dqmBeamMonitorBx.BeamFitter.WriteAscii = True process.dqmBeamMonitorBx.BeamFitter.AsciiFileName = '/nfshome0/yumiceva/BeamMonitorDQM/BeamFitResults_Bx.txt' ## TKStatus process.dqmTKStatus = cms.EDAnalyzer("TKStatus", BeamFitter = cms.PSet( DIPFileName = process.dqmBeamMonitor.BeamFitter.DIPFileName ) ) process.dqmcommon = cms.Sequence(process.dqmEnv *process.dqmSaver) process.monitor = cms.Sequence(process.dqmBeamMonitor) #-------------------------- # Proton-Proton Stuff #-------------------------- if (process.runType.getRunType() == process.runType.pp_run or process.runType.getRunType() == process.runType.cosmic_run): print "Running pp" process.EventStreamHttpReader.SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('HLT_L1*', 'HLT_Jet*', 'HLT_*Cosmic*', 'HLT_HT*', 'HLT_MinBias_*', 'HLT_Physics*', 'HLT_ZeroBias_v*') ) process.load("Configuration.StandardSequences.Reconstruction_cff") process.load("RecoTracker.IterativeTracking.iterativeTk_cff") ## Pixelless Tracking process.load('RecoTracker/Configuration/RecoTrackerNotStandard_cff') process.MeasurementTracker.pixelClusterProducer = cms.string("") # Offline Beam Spot process.load("RecoVertex.BeamSpotProducer.BeamSpot_cff") ## Offline PrimaryVertices import RecoVertex.PrimaryVertexProducer.OfflinePrimaryVertices_cfi process.offlinePrimaryVertices = RecoVertex.PrimaryVertexProducer.OfflinePrimaryVertices_cfi.offlinePrimaryVertices.clone() process.dqmBeamMonitor.OnlineMode = True process.dqmBeamMonitor.resetEveryNLumi = 5 process.dqmBeamMonitor.resetPVEveryNLumi = 5 process.dqmBeamMonitor.PVFitter.minNrVerticesForFit = 25 process.dqmBeamMonitor.BeamFitter.TrackCollection = cms.untracked.InputTag('generalTracks') process.offlinePrimaryVertices.TrackLabel = cms.InputTag("generalTracks") process.offlinePrimaryVertices.label=cms.string("") process.offlinePrimaryVertices.minNdof=cms.double(0.0) process.offlinePrimaryVertices.useBeamConstraint=cms.bool(False) #TriggerName for selecting pv for DIP publication, NO wildcard needed here #it will pick all triggers which has these strings in theri name process.dqmBeamMonitor.jetTrigger = cms.untracked.vstring("HLT_ZeroBias_v", "HLT_Jet300_v", "HLT_QuadJet70_v") process.dqmBeamMonitor.hltResults = cms.InputTag("TriggerResults","","HLT") #fast general track reco process.iterTracking =cms.Sequence(process.InitialStep *process.LowPtTripletStep *process.PixelPairStep *process.DetachedTripletStep *process.MixedTripletStep *process.PixelLessStep *process.TobTecStep *process.generalTracks) process.tracking_FirstStep = cms.Sequence(process.siPixelDigis *process.siStripDigis *process.trackerlocalreco *process.offlineBeamSpot *process.recopixelvertexing *process.iterTracking) process.p = cms.Path(process.scalersRawToDigi *process.dqmTKStatus *process.hltTriggerTypeFilter *process.dqmcommon *process.tracking_FirstStep *process.offlinePrimaryVertices *process.monitor) #-------------------------------------------------- # Heavy Ion Stuff #-------------------------------------------------- if (process.runType.getRunType() == process.runType.hi_run): print "Running HI" process.castorDigis.InputLabel = cms.InputTag("rawDataRepacker") process.csctfDigis.producer = cms.InputTag("rawDataRepacker") process.dttfDigis.DTTF_FED_Source = cms.InputTag("rawDataRepacker") process.ecalDigis.InputLabel = cms.InputTag("rawDataRepacker") process.ecalPreshowerDigis.sourceTag = cms.InputTag("rawDataRepacker") process.gctDigis.inputLabel = cms.InputTag("rawDataRepacker") process.gtDigis.DaqGtInputTag = cms.InputTag("rawDataRepacker") process.gtEvmDigis.EvmGtInputTag = cms.InputTag("rawDataRepacker") process.hcalDigis.InputLabel = cms.InputTag("rawDataRepacker") process.muonCSCDigis.InputObjects = cms.InputTag("rawDataRepacker") process.muonDTDigis.inputLabel = cms.InputTag("rawDataRepacker") process.muonRPCDigis.InputLabel = cms.InputTag("rawDataRepacker") process.scalersRawToDigi.scalersInputTag = cms.InputTag("rawDataRepacker") #---------------------------- # Event Source #----------------------------- process.EventStreamHttpReader.SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring( 'HLT_HI*' ) ) process.dqmBeamMonitor.OnlineMode = True ## in MC the LS are not ordered?? process.dqmBeamMonitor.resetEveryNLumi = 10 process.dqmBeamMonitor.resetPVEveryNLumi = 10 process.dqmBeamMonitor.BeamFitter.MinimumTotalLayers = 3 ## using pixel triplets process.dqmBeamMonitor.PVFitter.minNrVerticesForFit = 20 process.dqmBeamMonitor.jetTrigger = cms.untracked.vstring("HLT_HI") process.dqmBeamMonitor.hltResults = cms.InputTag("TriggerResults","","HLT") ## Load Heavy Ion Sequence process.load("Configuration.StandardSequences.ReconstructionHeavyIons_cff") ## HI sequences # Select events based on the pixel cluster multiplicity import HLTrigger.special.hltPixelActivityFilter_cfi process.multFilter = HLTrigger.special.hltPixelActivityFilter_cfi.hltPixelActivityFilter.clone( inputTag = cms.InputTag('siPixelClusters'), minClusters = cms.uint32(150), maxClusters = cms.uint32(50000) ) process.filter_step = cms.Sequence( process.siPixelDigis *process.siPixelClusters #*process.multFilter ) process.HIRecoForDQM = cms.Sequence( process.siPixelDigis *process.siPixelClusters *process.siPixelRecHits *process.offlineBeamSpot *process.hiPixelVertices *process.hiPixel3PrimTracks ) # use HI pixel tracking and vertexing process.dqmBeamMonitor.BeamFitter.TrackCollection = cms.untracked.InputTag('hiPixel3PrimTracks') process.dqmBeamMonitorBx.BeamFitter.TrackCollection = cms.untracked.InputTag('hiPixel3PrimTracks') process.dqmBeamMonitor.primaryVertex = cms.untracked.InputTag('hiSelectedVertex') process.dqmBeamMonitor.PVFitter.VertexCollection = cms.untracked.InputTag('hiSelectedVertex') # make pixel vertexing less sensitive to incorrect beamspot process.hiPixel3ProtoTracks.RegionFactoryPSet.RegionPSet.originRadius = 0.2 process.hiPixel3ProtoTracks.RegionFactoryPSet.RegionPSet.fixedError = 0.5 process.hiSelectedProtoTracks.maxD0Significance = 100 process.hiPixelAdaptiveVertex.TkFilterParameters.maxD0Significance = 100 process.hiPixelAdaptiveVertex.vertexCollections.useBeamConstraint = False #not working due to wrong tag of reco process.hiPixelAdaptiveVertex.vertexCollections.maxDistanceToBeam = 1.0 process.p = cms.Path(process.scalersRawToDigi *process.dqmTKStatus *process.hltTriggerTypeFilter *process.filter_step *process.HIRecoForDQM *process.dqmcommon *process.monitor)
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 14681, 796, 269, 907, 13, 18709, 7203, 3856, 321, 35479, 4943, 198, 198, 2, 1783, 10541, 198, 2, 8070, 636, 329, 21082, 290, 367, 13, 40, 18162, 198, 2, 1783,...
2.193777
4,949
# flake8: noqa import json from src.models.hacker import Hacker from tests.base import BaseTestCase from datetime import datetime
[ 2, 781, 539, 23, 25, 645, 20402, 198, 11748, 33918, 198, 6738, 12351, 13, 27530, 13, 71, 10735, 1330, 34399, 198, 6738, 5254, 13, 8692, 1330, 7308, 14402, 20448, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628 ]
3.540541
37
""" sources.chicago =============== Reads a CSV file in the format (as of April 2017) of data available from: - https://catalog.data.gov/dataset/crimes-one-year-prior-to-present-e171f - https://catalog.data.gov/dataset/crimes-2001-to-present-398a4 The default data is loaded from a file "chicago.csv" which should be downloaded from one of the above links. The format of the data, frustratingly, differs between the snapshot of last year, and the total. The data is partly anonymous in that the address within a block is obscured, while the geocoding seems complicated (work in progress to understand)... The crime type "HOMICIDE" is reported multiple times in the dataset. """ import csv as _csv import os.path as _path import datetime import numpy as _np from ..data import TimedPoints _datadir = None _default_filename = "chicago.csv" _FEET_IN_METERS = 3937 / 1200 def set_data_directory(datadir): """Set the default location for search for the default input file.""" global _datadir _datadir = datadir def get_default_filename(): """Returns the default filename, if available. Otherwise raises AttributeError. """ global _datadir if _datadir is None: raise AttributeError("datadir not set; call `set_data_directory()`.") return _path.join(_datadir, _default_filename) def date_from_iso(iso_string): """Convert a datetime string in ISO format into a :class:`datetime` instance. :param iso_string: Like "2017-10-23T05:12:39" :return: A :class:`datetime` instance. """ return datetime.datetime.strptime(iso_string, "%Y-%m-%dT%H:%M:%S") _FIELDS = { "snapshot" : { "_DESCRIPTION_FIELD" : ' PRIMARY DESCRIPTION', "_X_FIELD" : 'X COORDINATE', "_Y_FIELD" : 'Y COORDINATE', "_TIME_FIELD" : 'DATE OF OCCURRENCE', "_GEOJSON_LOOKUP" : {"case": 'CASE#', "address": "BLOCK", "location": ' LOCATION DESCRIPTION', "crime": ' PRIMARY DESCRIPTION', "type": ' SECONDARY DESCRIPTION', "timestamp": 'DATE OF OCCURRENCE'}, "GEOJSON_COORDS" : ('LONGITUDE', 'LATITUDE'), "DT_CONVERT" : _date_from_csv }, "all" : { "_DESCRIPTION_FIELD" : 'Primary Type', "_X_FIELD" : 'X Coordinate', "_Y_FIELD" : 'Y Coordinate', "_TIME_FIELD" : 'Date', "_GEOJSON_LOOKUP" : {"case": 'Case Number', "address": "Block", "location": 'Location Description', "crime": 'Primary Type', "type": 'Description', "timestamp": 'Date'}, "GEOJSON_COORDS" : ('Longitude', 'Latitude'), "DT_CONVERT" : _date_from_csv }, "gen" : { "_DESCRIPTION_FIELD" : 'CRIME', "_X_FIELD" : 'X', "_Y_FIELD" : 'Y', "_TIME_FIELD" : 'TIMESTAMP', "_GEOJSON_LOOKUP" : {"case": 'CASE', "address": "BLOCK", "location": 'LOCATION', "crime": 'CRIME', "type": 'SUB-TYPE', "timestamp": 'TIMESTAMP'}, "GEOJSON_COORDS" : ('X', 'Y'), "DT_CONVERT" : _date_from_csv } } _FIELDS["all_other"] = dict(_FIELDS["all"]) _FIELDS["all_other"]["DT_CONVERT"] = _date_from_other def default_burglary_data(): """Load the default data, if available, giving just "THEFT" data. :return: An instance of :class:`open_cp.data.TimedPoints` or `None`. """ try: return load(get_default_filename(), {"THEFT"}) except Exception: return None def load(file, primary_description_names, to_meters=True, type="snapshot"): """Load data from a CSV file in the expected format. :param file: Name of the CSV file load, or a file-like object. :param primary_description_names: Set of names to search for in the "primary description field". E.g. pass `{"THEFT"}` to return only the "theft" crime type. :param to_meters: Convert the coordinates to meters; True by default. :param type: Either "snapshot" or "all" depending on whether the data has headers conforming the the data "last year" or "2001 to present". :return: An instance of :class:`open_cp.data.TimedPoints` or `None`. """ dic = _get_dic(type) if isinstance(file, str): with open(file) as file: data = _load_to_list(file, dic, primary_description_names) else: data = _load_to_list(file, dic, primary_description_names) data.sort(key = lambda triple : triple[0]) xcoords = _np.empty(len(data)) ycoords = _np.empty(len(data)) for i, (_, x, y) in enumerate(data): xcoords[i], ycoords[i] = x, y times = [t for t, _, _ in data] if to_meters: xcoords /= _FEET_IN_METERS ycoords /= _FEET_IN_METERS return TimedPoints.from_coords(times, xcoords, ycoords) def load_to_GeoJSON(filename, type="snapshot"): """Load the specified CSV file to a list of GeoJSON (see http://geojson.org/) features. Events with no location data have `None` as the geometry. Timestamps are converted to standard ISO string format. The returned "properties" have these keys: - "case" for the "CASE#" field - "crime" for the "PRIMARY DESCRIPTION" field - "type" for the "SECONDARY DESCRIPTION" field - "location" for the "LOCATION DESCRIPTION" field - "timestamp" for the "DATE OF OCCURRENCE" field - "address" for the "BLOCK" field :param filename: Filename of the CSV file to process :param type: Either "snapshot" or "all" depending on whether the data has headers conforming the the data "last year" or "2001 to present". :return: List of Python dictionaries in GeoJSON format. """ return list(generate_GeoJSON_Features(filename, type)) try: import geopandas as gpd import shapely.geometry as _geometry except: gpd = None _geometry = None def convert_null_geometry_to_empty(frame): """Utility method. Convert any geometry in the geoDataFrame which is "null" (`None` or empty) to a Point type geometry which is empty. The returned geoDateFrame is suitable for projecting and other geometrical transformations. """ newgeo = frame.geometry.map(null_to_point) return frame.set_geometry(newgeo) def convert_null_geometry_to_none(frame): """Utility method. Convert any geometry in the geoDataFrame which is "null" (`None` or empty) to `None`. The returned geoDateFrame is suitable for saving. """ newgeo = frame.geometry.map(null_to_none) return frame.set_geometry(newgeo) def load_to_geoDataFrame(filename, datetime_as_string=True, type="snapshot", empty_geometry="none"): """Return the same data as :func:`load_to_GeoJSON` but as a geoPandas data-frame. :param filename: Filename of the CSV file to process :param datetime_as_string: Write the timestamp as an ISO formatted string. Defaults to True which is best for saving the dataframe as e.g. a shape file. Set to False to get timestamps as python objects, which is best for using (geo)pandas to analyse the data. :param type: Either "snapshot" or "all" depending on whether the data has headers conforming the the data "last year" or "2001 to present". :param empty_geometry: Either "none" to return `None` as the geometry of crimes which have no location data in the CSV file (this is correct if you wish to save the data-frame); or "empty" to return an empty `Point` type (which is correct, for example, if you wish to re-project the data-frame). Yes, GeoPandas appears to be annoying like this. """ geo_data = load_to_GeoJSON(filename, type=type) if not datetime_as_string: for feature in geo_data: feature["properties"]["timestamp"] = _date_from_iso(feature["properties"]["timestamp"]) frame = gpd.GeoDataFrame.from_features(geo_data) if empty_geometry == "none": pass elif empty_geometry == "empty": frame = convert_null_geometry_to_empty(frame) else: raise ValueError("Unknown `empty_geometry` parameter `{}`".format(empty_geometry)) frame.crs = {"init":"epsg:4326"} return frame _sides = None def get_side(name): """Return a geometry (a polygon, typically) of the outline of the shape of the given "side" of Chicago, projected to {"init":"epsg:2790"}, which is Illinois in metres. Needs the file "Chicago_Areas.geojson" to be in the "datadir". This can be downloaded from: https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Community-Areas-current-/cauq-8yn6 :param name: One of "Far North", "Northwest", "North", "West", "Central", "South", "Southwest", "Far Southwest", "Far Southeast" """ _load_sides() return _sides[_sides.side == name].unary_union
[ 37811, 198, 82, 2203, 13, 354, 4549, 198, 25609, 18604, 198, 198, 5569, 82, 257, 44189, 2393, 287, 262, 5794, 357, 292, 286, 3035, 2177, 8, 286, 1366, 1695, 422, 25, 198, 198, 12, 3740, 1378, 9246, 11794, 13, 7890, 13, 9567, 14, 1...
2.543012
3,499
# https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L11_Sieve%20of%20Eratosthenes/11.2%20CountSemiprimes.md def solution(N, P, Q): """ PQN, O(N * log(log(N)) + M) :param N: :param P: :param Q: :return: , """ # 34(1, 3, 9, 27)(1, 5, 25, 125) # N0 semi_prime = [] k =0 for i in range(1, N + 1): factor_count = 0 sign = 0 for j in range(1, int(i ** 0.5) + 1): if i % j == 0: factor_count += 1 f = i / j if f != j: if f == j ** 2: sign = 1 semi_prime.append(0) break else: factor_count += 1 if factor_count > 4: sign = 1 semi_prime.append(0) break if sign != 1: if factor_count >= 3: semi_prime.append(i) else: semi_prime.append(0) index_dict = {} # semi_dict = {} # count = 0 for index, value in enumerate(semi_prime): if value != 0: count += 1 index_dict[value] = count semi_dict[value] = 0 else: index_dict[index + 1] = count # index_dict {1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 3, 10: 4, 11: 4, 12: 4, 13: 4, 14: 5, 15: 6, 16: 6, 17: 6, 18: 6, 19: 6, 20: 6, 21: 7, 22: 8, 23: 8, 24: 8, 25: 9, 26: 10} #semi_dict {4: 0, 6: 0, 9: 0, 10: 0, 14: 0, 15: 0, 21: 0, 22: 0, 25: 0, 26: 0} print("index_dict",index_dict) print("semi_dict",semi_dict) result_list = [] # for i, j in zip(P, Q): if i in semi_dict: result_list.append(index_dict[j] - index_dict[i] + 1) else: result_list.append(index_dict[j] - index_dict[i]) return result_list if __name__ == '__main__': solution(26,[1, 4, 16],[26, 10, 20])
[ 2, 3740, 1378, 12567, 13, 785, 14, 2025, 69, 1092, 14, 43806, 879, 12, 22058, 684, 12, 3886, 12, 37906, 18, 14, 2436, 672, 14, 9866, 14, 43, 1157, 62, 50, 12311, 4, 1238, 1659, 4, 1238, 9139, 265, 455, 831, 274, 14, 1157, 13, ...
1.709232
1,159
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Error related things. """ try: from html import escape except ImportError: # pragma: NO COVER from cgi import escape from zope.component import adapter from zope.interface import implementer from zope.interface import Invalid from zope.i18n import Message from zope.i18n import translate from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.browser import BrowserPage from zope.formlib.interfaces import IWidgetInputErrorView from zope.formlib.interfaces import IInvalidCSRFTokenError
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 4793, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, 5094, 13789, 11, 198, 2, 10628, 362, 13, ...
3.845638
298
# # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more information about nexB OSS projects. # import io import os from pathlib import Path import saneyaml from packagedcode import models from packageurl import PackageURL # TODO: Override get_package_resource so it returns the Resource that the ABOUT file is describing TRACE = os.environ.get('SCANCODE_DEBUG_PACKAGE', False) if TRACE: import logging import sys logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout) logger.setLevel(logging.DEBUG)
[ 2, 198, 2, 15069, 357, 66, 8, 497, 87, 33, 3457, 13, 290, 1854, 13, 1439, 2489, 10395, 13, 198, 2, 20937, 10669, 318, 257, 16028, 286, 497, 87, 33, 3457, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13...
3.064151
265
# -*- coding: utf-8 -*- #django from django.contrib import admin from django.db import transaction #python import csv from decimal import Decimal #gazepattern from .models import Experiment, ExperimentPoint, Image, ImageRectangle, ExperimentPointCSV, ExperimentFunction procesar.short_description = "Procesar CSV para generar experiments points" admin.site.register(ExperimentPointCSV, ExperimentPointCSVAdmin) admin.site.register(ExperimentPoint, ExperimentPointAdmin) admin.site.register(Image, ImageAdmin) admin.site.register(Experiment, ExperimentAdmin) admin.site.register(ImageRectangle, ImageRectangleAdmin) admin.site.register(ExperimentFunction, ExperimentFunctionAdmin)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 28241, 14208, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 220, 198, 2, 29412, 198, 11748, 269, 21370, 198, 673...
3.569948
193
from django.test import TestCase, Client from django.urls import reverse from orders.models import Order, OrderItem from datetime import datetime from django.utils.timezone import get_current_timezone import pytz
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 11, 20985, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 6266, 13, 27530, 1330, 8284, 11, 8284, 7449, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 42625, 14208, 13,...
3.785714
56
from codigo.hexagonal.app.domain.switchable_repository import Switchable
[ 6738, 14873, 14031, 13, 33095, 27923, 13, 1324, 13, 27830, 13, 31943, 540, 62, 260, 1930, 37765, 1330, 14645, 540, 628 ]
3.52381
21
from random import randint menor = 100 linha = 0 maior = 0 m = [] for i in range(10): m.append([]) for j in range(10): m[i].append(randint(1,99)) for i in range(10): for j in range(10): print(f'{m[i][j]:2}',end=' ') print() for i in range(10): for j in range(10): if m[i][j] > maior: maior = m[i][j] linha = i for i in range(10): if m[linha][i] < menor: menor = m[linha][i] print(f'o minimax {menor}, com o maior sendo {maior} na linha {linha+1}.')
[ 6738, 4738, 1330, 43720, 600, 198, 198, 3653, 273, 796, 1802, 198, 2815, 3099, 796, 657, 198, 2611, 1504, 796, 657, 198, 76, 796, 17635, 198, 1640, 1312, 287, 2837, 7, 940, 2599, 198, 220, 220, 220, 285, 13, 33295, 26933, 12962, 198...
1.908127
283
import os.path as osp import argparse import yaml from src.token_classification.archs.data_formatter import * # ********************* launch formating *********************** # cmd to launch : python -m src.token_classification.format --config ./src/token_classification/config/config.yml if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'formatting for labeling') parser.add_argument('--config', type=str, required=True, help='path to yaml config') args = parser.parse_args() with open(args.config, 'r') as f: config = yaml.safe_load(f) asigning_variables(config) print('.... Start formatting') path = osp.join(config['path'], config['offres']) yaml_path = osp.join(config['path'], config['yaml']) formatter = Formatter(path, yaml_path) formatter.generate_name() formatter.load() formatter.sort_desc() formatter.format_to_jsonl_in_proportions(n_desc = config['n_sequences']) print('done;') print() print('/!\ Be careful to change the owner of the file before pasting it in doccano with the following command : sudo chown <user> <file>')
[ 11748, 28686, 13, 6978, 355, 267, 2777, 198, 11748, 1822, 29572, 198, 11748, 331, 43695, 198, 198, 6738, 12351, 13, 30001, 62, 4871, 2649, 13, 34592, 13, 7890, 62, 687, 1436, 1330, 1635, 628, 628, 198, 198, 2, 220, 8412, 35625, 4219, ...
2.832924
407
from __future__ import absolute_import, division, print_function import os, sys, time import numpy as np import scipy.sparse import scipy.linalg import scipy.sparse.linalg from astropy.table import Table, Column import multiprocessing from desiutil.log import get_logger from desispec.interpolation import resample_flux from desispec.spectra import Spectra from desispec.resolution import Resolution from desispec.fiberbitmasking import get_all_fiberbitmask_with_amp, get_all_nonamp_fiberbitmask_val, get_justamps_fiberbitmask from desispec.specscore import compute_coadd_scores from desispec.coaddition import coadd_fibermap def add(spectra, cosmics_nsig=0.) : """ Coaddition the spectra for each target and each camera. The input spectra is modified. Args: spectra: desispec.spectra.Spectra object Options: cosmics_nsig: float, nsigma clipping threshold for cosmics rays """ log = get_logger() targets = np.unique(spectra.fibermap["TARGETID"]) ntarget=targets.size log.debug("number of targets= {}".format(ntarget)) for b in spectra.bands : log.debug("coadding band '{}'".format(b)) nwave=spectra.wave[b].size tflux=np.zeros((ntarget,nwave),dtype=spectra.flux[b].dtype) tivar=np.zeros((ntarget,nwave),dtype=spectra.ivar[b].dtype) if spectra.mask is not None : tmask=np.zeros((ntarget,nwave),dtype=spectra.mask[b].dtype) else : tmask=None trdata=np.zeros((ntarget,spectra.resolution_data[b].shape[1],nwave),dtype=spectra.resolution_data[b].dtype) fiberstatus_bits = get_all_fiberbitmask_with_amp(b) good_fiberstatus = ( (spectra.fibermap["FIBERSTATUS"] & fiberstatus_bits) == 0 ) for i,tid in enumerate(targets) : jj=np.where( (spectra.fibermap["TARGETID"]==tid) & good_fiberstatus )[0] #- if all spectra were flagged as bad (FIBERSTATUS != 0), contine #- to next target, leaving tflux and tivar=0 for this target if len(jj) == 0: continue if cosmics_nsig is not None and cosmics_nsig > 0 and len(jj)>2 : # interpolate over bad measurements # to be able to compute gradient next # to a bad pixel and identify outlier # many cosmics residuals are on edge # of cosmic ray trace, and so can be # next to a masked flux bin grad=[] gradvar=[] for j in jj : if spectra.mask is not None : ttivar = spectra.ivar[b][j]*(spectra.mask[b][j]==0) else : ttivar = spectra.ivar[b][j] good = (ttivar>0) bad = ~good if np.sum(good)==0 : continue nbad = np.sum(bad) ttflux = spectra.flux[b][j].copy() if nbad>0 : ttflux[bad] = np.interp(spectra.wave[b][bad],spectra.wave[b][good],ttflux[good]) ttivar = spectra.ivar[b][j].copy() if nbad>0 : ttivar[bad] = np.interp(spectra.wave[b][bad],spectra.wave[b][good],ttivar[good]) ttvar = 1./(ttivar+(ttivar==0)) ttflux[1:] = ttflux[1:]-ttflux[:-1] ttvar[1:] = ttvar[1:]+ttvar[:-1] ttflux[0] = 0 grad.append(ttflux) gradvar.append(ttvar) #tivar_unmasked= np.sum(spectra.ivar[b][jj],axis=0) tivar_unmasked = 1 / np.sum(1/spectra.ivar[b][jj],axis=0) if spectra.mask is not None : ivarjj=spectra.ivar[b][jj]*(spectra.mask[b][jj]==0) else : ivarjj=spectra.ivar[b][jj] if cosmics_nsig is not None and cosmics_nsig > 0 and len(jj)>2 : grad=np.array(grad) gradvar=np.array(gradvar) gradivar=(gradvar>0)/np.array(gradvar+(gradvar==0)) nspec=grad.shape[0] sgradivar=np.sum(gradivar) if sgradivar>0 : meangrad=np.sum(gradivar*grad,axis=0)/sgradivar deltagrad=grad-meangrad chi2=np.sum(gradivar*deltagrad**2,axis=0)/(nspec-1) bad = (chi2>cosmics_nsig**2) nbad = np.sum(bad) if nbad>0 : log.info("masking {} values for targetid={}".format(nbad,tid)) badindex=np.where(bad)[0] for bi in badindex : k=np.argmax(gradivar[:,bi]*deltagrad[:,bi]**2) ivarjj[k,bi]=0. log.debug("masking spec {} wave={}".format(k,spectra.wave[b][bi])) #tivar[i]=np.sum(ivarjj,axis=0) tivar[i]= 1 / np.sum(1/ivarjj,axis=0) tflux[i]=np.sum(spectra.flux[b][jj],axis=0) for r in range(spectra.resolution_data[b].shape[1]) : trdata[i,r]=np.sum((spectra.resolution_data[b][jj,r]),axis=0) # not sure applying mask is wise here bad=(tivar[i]==0) if np.sum(bad)>0 : tivar[i][bad] = 1 / np.sum(1/spectra.ivar[b][jj][:,bad],axis=0) # if all masked, keep original ivar tflux[i][bad] = np.sum(spectra.flux[b][jj][:,bad],axis=0) ok=(tivar[i]>0) #if np.sum(ok)>0 : #tflux[i][ok] /= tivar[i][ok] ok=(tivar_unmasked>0) if np.sum(ok)>0 : trdata[i][:,ok] /= tivar_unmasked[ok] if spectra.mask is not None : tmask[i] = np.bitwise_or.reduce(spectra.mask[b][jj],axis=0) spectra.flux[b] = tflux spectra.ivar[b] = tivar if spectra.mask is not None : spectra.mask[b] = tmask spectra.resolution_data[b] = trdata if spectra.scores is not None: orig_scores = Table(spectra.scores.copy()) orig_scores['TARGETID'] = spectra.fibermap['TARGETID'] else: orig_scores = None spectra.fibermap=coadd_fibermap(spectra.fibermap) spectra.scores=None compute_coadd_scores(spectra, orig_scores, update_coadd=True)
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 11748, 28686, 11, 25064, 11, 640, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 629, 541, 88, 13, 82, 29572, 198, 11748, 629, 541, 88, 13...
1.811048
3,530
from mock import patch import pytest from pontoon.base.models import User from pontoon.pretranslation.pretranslate import get_translations from pontoon.test.factories import ( EntityFactory, TranslationMemoryFactory, )
[ 6738, 15290, 1330, 8529, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 45443, 2049, 13, 8692, 13, 27530, 1330, 11787, 198, 6738, 45443, 2049, 13, 5310, 26084, 7592, 13, 5310, 26084, 17660, 1330, 651, 62, 7645, 49905, 198, 6738, 45443, 2...
3.484848
66
# -*- encoding: utf-8 -*- """Utility functions for computing combinations of dimensions and hierarchy levels""" from __future__ import absolute_import import re import os.path import json from collections import OrderedDict from .errors import ModelInconsistencyError, ArgumentError, ConfigurationError from . import compat __all__ = [ "IgnoringDictionary", "MissingPackage", "localize_common", "localize_attributes", "get_localizable_attributes", "decamelize", "to_identifier", "assert_instance", "assert_all_instances", "read_json_file", "sorted_dependencies", ] def assert_instance(obj, class_, label): """Raises ArgumentError when `obj` is not instance of `cls`""" if not isinstance(obj, class_): raise ModelInconsistencyError("%s should be sublcass of %s, " "provided: %s" % (label, class_.__name__, type(obj).__name__)) def assert_all_instances(list_, class_, label="object"): """Raises ArgumentError when objects in `list_` are not instances of `cls`""" for obj in list_ or []: assert_instance(obj, class_, label="object") def optional_import(name, feature=None, source=None, comment=None): """Optionally import package `name`. If package does not exist, import a placeholder object, that raises an exception with more detailed description about the missing package.""" try: return __import__(name) except ImportError: return MissingPackage(name, feature, source, comment) def expand_dictionary(record, separator='.'): """Return expanded dictionary: treat keys are paths separated by `separator`, create sub-dictionaries as necessary""" result = {} for key, value in record.items(): current = result path = key.split(separator) for part in path[:-1]: if part not in current: current[part] = {} current = current[part] current[path[-1]] = value return result def localize_common(obj, trans): """Localize common attributes: label and description""" if "label" in trans: obj.label = trans["label"] if "description" in trans: obj.description = trans["description"] def localize_attributes(attribs, translations): """Localize list of attributes. `translations` should be a dictionary with keys as attribute names, values are dictionaries with localizable attribute metadata, such as ``label`` or ``description``.""" for (name, atrans) in translations.items(): attrib = attribs[name] localize_common(attrib, atrans) def get_localizable_attributes(obj): """Returns a dictionary with localizable attributes of `obj`.""" # FIXME: use some kind of class attribute to get list of localizable attributes locale = {} try: if obj.label: locale["label"] = obj.label except: pass try: if obj.description: locale["description"] = obj.description except: pass return locale def to_label(name, capitalize=True): """Converts `name` into label by replacing underscores by spaces. If `capitalize` is ``True`` (default) then the first letter of the label is capitalized.""" label = name.replace("_", " ") if capitalize: label = label.capitalize() return label def coalesce_option_value(value, value_type, label=None): """Convert string into an object value of `value_type`. The type might be: `string` (no conversion), `integer`, `float`, `list` comma separated list of strings. """ value_type = value_type.lower() try: if value_type in ('string', 'str'): return_value = str(value) elif value_type == 'list': if isinstance(value, compat.string_type): return_value = value.split(",") else: return_value = list(value) elif value_type == "float": return_value = float(value) elif value_type in ["integer", "int"]: return_value = int(value) elif value_type in ["bool", "boolean"]: if not value: return_value = False elif isinstance(value, compat.string_type): return_value = value.lower() in ["1", "true", "yes", "on"] else: return_value = bool(value) else: raise ArgumentError("Unknown option value type %s" % value_type) except ValueError: if label: label = "parameter %s " % label else: label = "" raise ArgumentError("Unable to convert %svalue '%s' into type %s" % (label, astring, value_type)) return return_value def coalesce_options(options, types): """Coalesce `options` dictionary according to types dictionary. Keys in `types` refer to keys in `options`, values of `types` are value types: string, list, float, integer or bool.""" out = {} for key, value in options.items(): if key in types: out[key] = coalesce_option_value(value, types[key], key) else: out[key] = value return out def read_json_file(path, kind=None): """Read a JSON from `path`. This is convenience function that provides more descriptive exception handling.""" kind = "%s " % str(kind) if kind else "" if not os.path.exists(path): raise ConfigurationError("Can not find %sfile '%s'" % (kind, path)) try: f = compat.open_unicode(path) except IOError: raise ConfigurationError("Can not open %sfile '%s'" % (kind, path)) try: content = json.load(f) except ValueError as e: raise SyntaxError("Syntax error in %sfile %s: %s" % (kind, path, str(e))) finally: f.close() return content def sorted_dependencies(graph): """Return keys from `deps` ordered by dependency (topological sort). `deps` is a dictionary where keys are strings and values are list of strings where keys is assumed to be dependant on values. Example:: A ---> B -+--> C | +--> D --> E Will be: ``{"A": ["B"], "B": ["C", "D"], "D": ["E"],"E": []}`` """ graph = dict((key, set(value)) for key, value in graph.items()) # L Empty list that will contain the sorted elements L = [] # S Set of all nodes with no dependencies (incoming edges) S = set(parent for parent, req in graph.items() if not req) while S: # remove a node n from S n = S.pop() # insert n into L L.append(n) # for each node m with an edge e from n to m do # (n that depends on m) parents = [parent for parent, req in graph.items() if n in req] for parent in parents: graph[parent].remove(n) # remove edge e from the graph # if m has no other incoming edges then insert m into S if not graph[parent]: S.add(parent) # if graph has edges then -> error nonempty = [k for k, v in graph.items() if v] if nonempty: raise ArgumentError("Cyclic dependency of: %s" % ", ".join(nonempty)) return L
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 18274, 879, 5499, 329, 14492, 17790, 286, 15225, 290, 18911, 198, 46170, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 302,...
2.40617
3,144
import torch import torch.nn as nn import torch.nn.functional as F from modules import Conv, ResBlock
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 13103, 1330, 34872, 11, 1874, 12235, 628, 198 ]
3.586207
29
try: from gevent import monkey monkey.patch_all() except ImportError: # fine if no gevent is available pass import base64 import logging from unittest.mock import Mock from flask.app import Flask from flask_testing import TestCase from openbrokerapi.api import BrokerCredentials from openbrokerapi.log_util import basic_config
[ 28311, 25, 198, 220, 220, 220, 422, 4903, 1151, 1330, 21657, 198, 220, 220, 220, 21657, 13, 17147, 62, 439, 3419, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 1303, 3734, 611, 645, 4903, 1151, 318, 1695, 198, 220, 220, 220, 120...
3.242991
107
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, Michael Perzel # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: bigip_gtm_wide_ip short_description: "Manages F5 BIG-IP GTM wide ip" description: - "Manages F5 BIG-IP GTM wide ip" version_added: "2.0" author: - Michael Perzel (@perzizzle) - Tim Rupp (@caphrim007) notes: - "Requires BIG-IP software version >= 11.4" - "F5 developed module 'bigsuds' required (see http://devcentral.f5.com)" - "Best run as a local_action in your playbook" - "Tested with manager and above account privilege level" requirements: - bigsuds options: lb_method: description: - LB method of wide ip required: true choices: ['return_to_dns', 'null', 'round_robin', 'ratio', 'topology', 'static_persist', 'global_availability', 'vs_capacity', 'least_conn', 'lowest_rtt', 'lowest_hops', 'packet_rate', 'cpu', 'hit_ratio', 'qos', 'bps', 'drop_packet', 'explicit_ip', 'connection_rate', 'vs_score'] wide_ip: description: - Wide IP name required: true extends_documentation_fragment: f5 ''' EXAMPLES = ''' - name: Set lb method local_action: > bigip_gtm_wide_ip server=192.0.2.1 user=admin password=mysecret lb_method=round_robin wide_ip=my-wide-ip.example.com ''' try: import bigsuds except ImportError: bigsuds_found = False else: bigsuds_found = True from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.f5 import bigip_api, f5_argument_spec if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 357, 66, 8, 1853, 11, 3899, 2448, 17396, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 28038, 856, 198, 2, 198, ...
2.52381
945
#! /usr/bin/env python from __future__ import print_function import pandas as pd import numpy as np import argparse if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate sample tables to test joins.') parser.add_argument('--num-rows', '-r', type=int, default=100) parser.add_argument('--num-cols', '-c', type=int, required=True) parser.add_argument('--num-distinct-vals', '-d', type=int, required=True) parser.add_argument('--num-cols-overlap', '-o', type=int, default=1) args = parser.parse_args() NUM_ROWS = args.num_rows NUM_COLS = args.num_cols NUM_DISTINCT_VALS = args.num_distinct_vals num_overlap = args.num_cols_overlap if num_overlap > NUM_COLS: print('--num-cols-overlap cannot be greater than --num-cols') import sys sys.exit(1) generate_csv(0, 'table_a.csv') generate_csv(NUM_COLS - num_overlap, 'table_b.csv')
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 628, 198, 198, 361, 11593, 3672...
2.430412
388
indexWords = list() phrase = str(input()) phraseList = phrase.split(" ") length = len(phraseList) for item in phraseList : item = item.strip() if phrase != "" : for i in range(1, length-1) : lengthOfWord = len(phraseList[i]) if phraseList[i][0].isupper() : if PreviousWord(phraseList, phraseList[i])[-1] != "." : if phraseList[i][-1]=="." or phraseList[i][-1]=="," : indexWords.append(i + 1) indexWords.append(phraseList[i][: lengthOfWord-1]) elif phraseList[i][-1]== "]" and phraseList[i][-2]== "'" : indexWords.append(i + 1) indexWords.append(phraseList[i][: lengthOfWord-2]) else : indexWords.append(i + 1) indexWords.append(phraseList[i]) else: print("None") lengthOfIndexWord = len(indexWords) if lengthOfIndexWord == 0 : print("None") else: for i in range(0, lengthOfIndexWord//2): print("%i:%s" %(indexWords[2*i],indexWords[(2*i)+1]))
[ 198, 9630, 37117, 796, 1351, 3419, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 34675, 796, 965, 7, 15414, 28955, 198, 34675, 8053, 796, 9546, 13, 35312, 7203, 366, 8, 198, 13664, 796, 18896, 7, 34675, 8053, 8, 198, 1640, 2378,...
1.990792
543
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import json import mock import webapp2 from google.appengine.api import taskqueue from go.chromium.org.luci.buildbucket.proto.build_pb2 import Build from testing_utils.testing import AppengineTestCase from common.findit_http_client import FinditHttpClient from common.waterfall import buildbucket_client from handlers import completed_build_pubsub_ingestor from model.isolated_target import IsolatedTarget
[ 2, 15069, 2177, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 11748...
3.645963
161
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['OpenShiftManagedClusterArgs', 'OpenShiftManagedCluster'] def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, agent_pool_profiles: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OpenShiftManagedClusterAgentPoolProfileArgs']]]]] = None, auth_profile: Optional[pulumi.Input[pulumi.InputType['OpenShiftManagedClusterAuthProfileArgs']]] = None, location: Optional[pulumi.Input[str]] = None, master_pool_profile: Optional[pulumi.Input[pulumi.InputType['OpenShiftManagedClusterMasterPoolProfileArgs']]] = None, monitor_profile: Optional[pulumi.Input[pulumi.InputType['OpenShiftManagedClusterMonitorProfileArgs']]] = None, network_profile: Optional[pulumi.Input[pulumi.InputType['NetworkProfileArgs']]] = None, open_shift_version: Optional[pulumi.Input[str]] = None, plan: Optional[pulumi.Input[pulumi.InputType['PurchasePlanArgs']]] = None, refresh_cluster: Optional[pulumi.Input[bool]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, resource_name_: Optional[pulumi.Input[str]] = None, router_profiles: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['OpenShiftRouterProfileArgs']]]]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = OpenShiftManagedClusterArgs.__new__(OpenShiftManagedClusterArgs) __props__.__dict__["agent_pool_profiles"] = agent_pool_profiles __props__.__dict__["auth_profile"] = auth_profile __props__.__dict__["location"] = location __props__.__dict__["master_pool_profile"] = master_pool_profile __props__.__dict__["monitor_profile"] = monitor_profile __props__.__dict__["network_profile"] = network_profile if open_shift_version is None and not opts.urn: raise TypeError("Missing required property 'open_shift_version'") __props__.__dict__["open_shift_version"] = open_shift_version __props__.__dict__["plan"] = plan __props__.__dict__["refresh_cluster"] = refresh_cluster if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["resource_name"] = resource_name_ __props__.__dict__["router_profiles"] = router_profiles __props__.__dict__["tags"] = tags __props__.__dict__["cluster_version"] = None __props__.__dict__["fqdn"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["public_hostname"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:containerservice/v20191027preview:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-native:containerservice:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-nextgen:containerservice:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-native:containerservice/v20180930preview:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-nextgen:containerservice/v20180930preview:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-native:containerservice/v20190430:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-nextgen:containerservice/v20190430:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-native:containerservice/v20190930preview:OpenShiftManagedCluster"), pulumi.Alias(type_="azure-nextgen:containerservice/v20190930preview:OpenShiftManagedCluster")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(OpenShiftManagedCluster, __self__).__init__( 'azure-native:containerservice/v20191027preview:OpenShiftManagedCluster', resource_name, __props__, opts)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.378026
2,148
# Generated by Django 3.2.4 on 2021-06-17 02:01 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 19, 319, 33448, 12, 3312, 12, 1558, 7816, 25, 486, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
# -*- coding: iso-8859-1 -*- import os import shutil import datetime import sqlite3 from flask import Flask, request, session, render_template, g, redirect, url_for, abort, flash, make_response from random import randint import json import urllib2 import json from json.decoder import JSONObject from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/tmp' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) DBBACKUPPATH = os.path.abspath('db_backup') if os.path.exists(DBBACKUPPATH) == False: os.mkdir(DBBACKUPPATH) app = Flask(__name__) #app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app = Flask(__name__) app.config.from_object(__name__) # Load default config and override config from an environment variable app.config.update(dict( DATABASE=os.path.join(app.root_path, 'recipes.db'), SECRET_KEY='development key', USERNAME='admin', PASSWORD='default', UPLOAD_FOLDER='/tmp' )) app.config['UPPLOAD_FOLDER'] = '/tmp' app.config.from_envvar('FLASKR_SETTINGS', silent=True) def connect_db(): """Connects to the specific database.""" if os.path.exists(app.config['DATABASE']) == False: cmd = 'sqlite3 recipes.db < database.sql' os.system(cmd) rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def queryDbFetchOne(query): """Query database, return one result""" db = get_db() cur = db.cursor() cur.execute(query) return cur.fetchone() def queryDbFetchAll(query): """Query database, return one result""" db = get_db() cur = db.cursor() cur.execute(query) return cur.fetchall() def getRecipe(recipeKey): """Get recipe data""" return queryDbFetchOne('SELECT * FROM recipes WHERE key="%s"'%recipeKey) def getIngredients(recipeKey): """Get all ingredients for a recipe""" return queryDbFetchAll('SELECT * FROM recipeAmount WHERE recipeKey="%s"'%recipeKey) def getNextKey(): """Get next number for key""" currentHighKey = queryDbFetchOne('SELECT key FROM recipes ORDER BY key DESC') if currentHighKey is None: print "IS none %s"%currentHighKey currentHighKey = 0 else: currentHighKey = int(currentHighKey[0]) return currentHighKey +1 def insertIntoDb(table, names, values): """Insert into database""" if len(values) != len(names): return None query = 'INSERT INTO %s (%s) VALUES(%s)'%(table, ', '.join(names), ', '.join(values)) rowId = None try: db = get_db() cur = db.cursor() cur = get_db().cursor() cur.execute(query) db.commit() rowId = cur.lastrowid except: db.rollback() finally: return rowId def doRawQuery(query): """Do a raw query""" rowId = None try: db = get_db() cur = db.cursor() cur = get_db().cursor() cur.execute(query) db.commit() rowId = cur.lastrowid except: db.rollback() finally: return rowId def updateDb(table, names, values, where): """Update row in table""" if len(values) != len(names): return None query = 'UPDATE %s SET '%(table) qPairs = [] for name, value in zip(names,values): qPairs.append('%s=%s'%(name,value)) query += ', '.join(x for x in qPairs) query += ' %s'%where rowId = None try: db = get_db() cur = db.cursor() cur = get_db().cursor() cur.execute(query) db.commit() rowId = cur.lastrowid except: db.rollback() finally: return rowId # return redirect('login', code=304) def deleteAmount(recipeKey): query = 'DELETE FROM recipeAmount WHERE recipeKey=%s'%recipeKey try: db = get_db() cur = db.cursor() cur = get_db().cursor() cur.execute(query) db.commit() rowId = cur.lastrowid except: db.rollback() msg = "error in delete operation" print msg finally: return rowId def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS def displayRecipe(recipe): values = {'key':recipe['key'], 'title': recipe['title'], 'instructions': recipe['instructions'], 'portions': recipe['portions'], 'ingredients': getIngredients(recipe['key']), 'pageId': 'displayRecipe', 'popupMenuId': 'popupMenuId%d'%randint(1, 1048) } return render_template('displayRecipe_template.html', **values) def getFridgeJSON(): fridgeContent = queryDbFetchAll('SELECT key, title, fridge.portions AS portions FROM recipes INNER JOIN fridge ON recipes.key = fridge.recipeKey') fridgeJson = [] for row in fridgeContent: rowJson = {} for key in row.keys(): rowJson[key] = row[key] fridgeJson.append(rowJson) return json.dumps(fridgeJson) # Update fridge content def dobackup(name): dbF = open(os.path.join(DBBACKUPPATH, name), 'w') con = get_db() dbF.write('\n'.join(con.iterdump()).encode('utf8')) dbF.close() if __name__ == "__main__": # import logging # file_handler = RotatingFileHandler('/tmp/receptakuten.log', bakupCount=5) # file_handler.setLevel(logging.WARNING) # app.logger.addHandler(file_handler) app.run(host="0.0.0.0", debug=True) # app.run(debug=True)
[ 2, 532, 9, 12, 19617, 25, 47279, 12, 3459, 3270, 12, 16, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 4818, 8079, 198, 11748, 44161, 578, 18, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 6246, 11, 8543, 6...
2.307351
2,476
#coding:utf-8 # # id: bugs.core_2678 # title: Full outer join cannot use available indices (very slow execution) # decription: # tracker_id: CORE-2678 # min_versions: ['3.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [] init_script_1 = """""" db_1 = db_factory(sql_dialect=3, init=init_script_1) test_script_1 = """ create table td_data1 ( c1 varchar(20) character set win1251 not null collate win1251, c2 integer not null, c3 date not null, d1 float not null ); create index idx_td_data1 on td_data1(c1,c2,c3); commit; create table td_data2 ( c1 varchar(20) character set win1251 not null collate win1251, c2 integer not null, c3 date not null, d2 float not null ); create index idx_td_data2 on td_data2(c1,c2,c3); commit; set planonly; select d1.c1, d2.c1, d1.c2, d2.c2, d1.c3, d2.c3, coalesce(sum(d1.d1), 0) t1, coalesce(sum(d2.d2), 0) t2 from td_data1 d1 full join td_data2 d2 on d2.c1 = d1.c1 and d2.c2 = d1.c2 and d2.c3 = d1.c3 group by d1.c1, d2.c1, d1.c2, d2.c2, d1.c3, d2.c3; """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ PLAN SORT (JOIN (JOIN (D2 NATURAL, D1 INDEX (IDX_TD_DATA1)), JOIN (D1 NATURAL, D2 INDEX (IDX_TD_DATA2)))) """
[ 2, 66, 7656, 25, 40477, 12, 23, 198, 2, 198, 2, 4686, 25, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 11316, 13, 7295, 62, 2075, 3695, 198, 2, 3670, 25, 220, 220, 220, 220, 220, 220, 220, 6462, 12076, 4654, 2314, 779, 16...
1.895758
825
from flask import current_app
[ 6738, 42903, 1330, 1459, 62, 1324 ]
4.833333
6
"""Test suite for the {{ cookiecutter.project_slug_no_hyphen }} package."""
[ 37811, 14402, 18389, 329, 262, 22935, 19751, 8968, 353, 13, 16302, 62, 6649, 1018, 62, 3919, 62, 36362, 831, 34949, 5301, 526, 15931, 198 ]
3.166667
24
# SPDX-License-Identifier: MIT # Copyright (c) 2018-2020 The Pybricks Authors """Pybricks robotics module.""" from _pybricks.robotics import DriveBase
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 2, 15069, 357, 66, 8, 2864, 12, 42334, 383, 9485, 65, 23706, 46665, 198, 198, 37811, 20519, 65, 23706, 36359, 8265, 526, 15931, 198, 198, 6738, 4808, 9078, 65, 23706, 13, 305...
3.122449
49
#!/usr/bin/env python import psycopg2 import time from ..models import User
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 17331, 22163, 70, 17, 198, 11748, 640, 198, 6738, 11485, 27530, 1330, 11787, 628 ]
3.208333
24
"""Custon color that looks for colors of format `#RRGGBBAA` as `#AARRGGBB`.""" from coloraide.css.colors import Color, SRGB from coloraide.colors import _parse as parse from coloraide import util import copy import re class ColorAlphaHex(Color): """Color object whose sRGB color space looks for colors of format `#RRGGBBAA` as `#AARRGGBB`.""" CS_MAP = copy.copy(Color.CS_MAP) CS_MAP["srgb"] = ASRGB
[ 37811, 34, 436, 261, 3124, 326, 3073, 329, 7577, 286, 5794, 4600, 2, 21095, 38, 4579, 33, 3838, 63, 355, 4600, 2, 32, 26465, 38, 4579, 33, 63, 526, 15931, 198, 6738, 3124, 64, 485, 13, 25471, 13, 4033, 669, 1330, 5315, 11, 16808, ...
2.748344
151
import random import jobs import balance from economy import roman_numbers
[ 11748, 4738, 198, 198, 11748, 3946, 198, 11748, 5236, 198, 6738, 3773, 1330, 374, 5185, 62, 77, 17024, 628, 628, 220, 220, 220, 220, 198 ]
3.36
25
from django.db import models from .media import Water from .media import Electricity from .media import Gas from .media import WasteWater from .media import Telecommunication from .generic import Attachment from .generic import Photo from .generic import Location as EstateLocation from cigeo.models import GenericNote as EstateNote
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 764, 11431, 1330, 5638, 198, 6738, 764, 11431, 1330, 42048, 198, 6738, 764, 11431, 1330, 14345, 198, 6738, 764, 11431, 1330, 35304, 19184, 198, 6738, 764, 11431, 1330, 14318, 32560, 198...
4.246914
81
import json import ntpath import shutil from pathlib import Path import pickle5 def load_pickle_files_as_data(file_paths): """ Load pickle files containing decision outputs as an data array. :param file_paths: A List of file paths to the individual pickle files. :return: A data array. """ data = [] for file_path in file_paths: with (open(file_path, "rb")) as handle: data.append(pickle5.load(handle)) return data def dump_pusion_data(data, file_path): """ Dump classification output data to the given file using pickle. :param data: A data dictionary. :param file_path: Location of the output pickle file. """ with open(file_path, "wb") as handle: pickle5.dump(data, handle, protocol=pickle5.HIGHEST_PROTOCOL) def dump_data_as_txt(data, name, identifier): """ Dump a data dictionary to the JSON file for a given evaluation unit. :param data: A data dictionary. :param name: The file name. :param identifier: The identifier of the current evaluation unit (e.g. date/time). """ directory = "res/eval_" + identifier Path(directory).mkdir(parents=True, exist_ok=True) with open(directory + "/" + name + ".txt", 'w') as file: file.write(json.dumps(data, indent=4)) def save(plot_instance, name, identifier): """ Save the plot instance for a given evaluation unit to the SVG and the PDF file, respectively. :param plot_instance: `matplotlib.pyplot`-instance. :param name: The file name. :param identifier: The identifier of the current evaluation unit (e.g. date/time). """ directory = "res/eval_" + identifier Path(directory).mkdir(parents=True, exist_ok=True) plot_instance.savefig(directory + "/" + name + ".svg", bbox_inches="tight") plot_instance.savefig(directory + "/" + name + ".pdf", bbox_inches="tight") def save_evaluator(file, identifier): """ Save the evaluation script for a given evaluation unit. :param file: The Python file. (E.g. referenced by __file__). :param identifier: The identifier of the current evaluation unit (e.g. date/time). """ directory = "res/eval_" + identifier Path(directory).mkdir(parents=True, exist_ok=True) shutil.copy(file, directory + "/" + ntpath.basename(file) + ".txt")
[ 11748, 33918, 198, 11748, 299, 83, 6978, 198, 11748, 4423, 346, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 2298, 293, 20, 628, 198, 4299, 3440, 62, 27729, 293, 62, 16624, 62, 292, 62, 7890, 7, 7753, 62, 6978, 82, 2599, 198...
2.849449
817
from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAdminUser from goods.models import SPU, SPUSpecification from meiduo_admin.serializers.spus import SPUSimpleSerializer, SPUSpecSerializer # GET/meiduo_admin/goods/(?P<pk>\d+)/specs/
[ 6738, 1334, 62, 30604, 13, 8612, 873, 1330, 7343, 2969, 3824, 769, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 1148, 46787, 12982, 198, 198, 6738, 7017, 13, 27530, 1330, 311, 5105, 11, 6226, 2937, 43106, 2649, 198, 6738, 502, 312...
2.957447
94
# Hacked by Ry2uko :D import copy import random # Consider using the modules imported above. if __name__ == '__main__': # Test here pass
[ 2, 367, 6021, 416, 11089, 17, 29794, 1058, 35, 198, 11748, 4866, 198, 11748, 4738, 198, 2, 12642, 1262, 262, 13103, 17392, 2029, 13, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1303, 6208, ...
3.020833
48
import tkinter as tk from tkinter.messagebox import showerror from constants.frames import MAIN_FRAME_NAME from util import add_new_quantity
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 6738, 256, 74, 3849, 13, 20500, 3524, 1330, 14643, 1472, 198, 198, 6738, 38491, 13, 37805, 1330, 8779, 1268, 62, 10913, 10067, 62, 20608, 198, 6738, 7736, 1330, 751, 62, 3605, 62, 40972, 414, ...
3.325581
43
from setuptools import setup import versioneer setup(name='gym_pysc2', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), install_requires=['gym'] # And any other dependencies foo needs )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 11748, 2196, 28153, 198, 198, 40406, 7, 3672, 11639, 1360, 76, 62, 79, 28349, 17, 3256, 198, 220, 220, 220, 220, 220, 2196, 28, 690, 7935, 263, 13, 1136, 62, 9641, 22784, 198, 220, 220, 220,...
2.790123
81
import zmq import sys import os import math if __name__ == '__main__': main()
[ 11748, 1976, 76, 80, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 10688, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 628 ]
2.625
32
""" Neighborhood Components Analysis (NCA) Ported to Python from https://github.com/vomjom/nca """ from __future__ import absolute_import import numpy as np from six.moves import xrange from sklearn.utils.validation import check_X_y from .base_metric import BaseMetricLearner EPS = np.finfo(float).eps
[ 37811, 198, 46445, 2865, 2894, 36109, 14691, 357, 7792, 32, 8, 198, 47, 9741, 284, 11361, 422, 3740, 1378, 12567, 13, 785, 14, 85, 296, 73, 296, 14, 77, 6888, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198...
3.06
100
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Policy evaluation.""" import typing import tensorflow.compat.v2 as tf def evaluate( env, policy, num_episodes = 10, ctx_length = None, embed_training_window = None, state_mask_fn = None, # pylint: disable=g-bare-generic ): """Evaluates the policy. Args: env: Environment to evaluate the policy on. policy: Policy to evaluate. num_episodes: A number of episodes to average the policy on. ctx_length: number of previous steps to compute context from. embed_training_window: window size used during embed training. state_mask_fn: state masking function for partially obs envs. Returns: Averaged reward and a total number of steps. """ total_timesteps = 0 total_returns = 0.0 for _ in range(num_episodes): timestep = env.reset() if ctx_length: states = [apply_mask(timestep.observation) for _ in range(ctx_length)] actions = [ tf.zeros(policy.action_spec.shape)[None, :] for _ in range(ctx_length) ] rewards = [[0.] for _ in range(ctx_length)] latent_action = None i = 0 while not timestep.is_last(): if embed_training_window and (i % embed_training_window == 0 or embed_training_window <= 2): latent_action = None if ctx_length: states.append(apply_mask(timestep.observation)) if len(states) > ctx_length: states.pop(0) actions.pop(0) rewards.pop(0) action = policy.act( tf.stack(states, axis=1), actions=tf.stack(actions, axis=1), rewards=tf.stack(rewards, axis=1)) actions.append(action) else: if embed_training_window: action, latent_action = policy.act( apply_mask(timestep.observation), latent_action=latent_action) else: action = policy.act(apply_mask(timestep.observation)) timestep = env.step(action) if ctx_length: rewards.append(timestep.reward) total_returns += timestep.reward[0] total_timesteps += 1 i += 1 return total_returns / num_episodes, total_timesteps / num_episodes
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 33448, 383, 3012, 4992, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, ...
2.551471
1,088
"""Authors: Cody Baker and Ben Dichter.""" from pathlib import Path import spikeextractors as se from pynwb.ecephys import ElectricalSeries from ..baserecordingextractorinterface import BaseRecordingExtractorInterface from ....utils import get_schema_from_hdmf_class, FilePathType try: from pyintan.intan import read_rhd, read_rhs HAVE_PYINTAN = True except ImportError: HAVE_PYINTAN = False INSTALL_MESSAGE = "Please install pyintan to use this extractor!"
[ 37811, 30515, 669, 25, 27035, 14372, 290, 3932, 360, 488, 353, 526, 15931, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 20240, 2302, 974, 669, 355, 384, 198, 6738, 279, 2047, 39346, 13, 68, 344, 34411, 1330, 40224, 27996, 198, ...
3.064516
155
import os import youtube_dl os.system("setup.bat") playlist = input("Paste the Youtube Playlist URL Here.") track = 1 print("""THIS TOOL WILL ATTEMPT TO DOWNLOAD THE FIRST 1000 SONGS IN THE QUEUE.\n PLEASE DO NOT INTERRUPT THE TOOL. YOU MAY CLOSE THE TOOL WHEN IT DISPLAYS "DONE!". ALL DOWNLOADED SONGS WILL BE IN THE SAME DIRECTORY THIS FILE IS IN. TO EXTRACT THEM, FILTER BY MP3.""") for x in range(1000): file = open("Downloader.bat","w") file.write("youtube-dl -x --playlist-start {} --audio-format mp3 --playlist-end {} {}".format(str(track),str(track),playlist)) file.close os.system("Downloader.bat") track = track + 1 print("DONE! You may now close this window.")
[ 11748, 28686, 201, 198, 11748, 35116, 62, 25404, 201, 198, 418, 13, 10057, 7203, 40406, 13, 8664, 4943, 201, 198, 1759, 4868, 796, 5128, 7203, 47, 4594, 262, 27431, 3811, 4868, 10289, 3423, 19570, 201, 198, 11659, 796, 352, 201, 198, ...
2.620567
282
# coding: utf-8 """ manage.py ~~~~~~~~~ """ import os import sys import shutil import platform from app import app from gen import Gen from flask_script import Manager """""" if (platform.python_version().split('.')[0] == '2'): # reload(sys) is evil :) reload(sys) sys.setdefaultencoding('utf-8') """Git""" git_url = app.config['GIT_URL'] git_branch = app.config['BRANCH'] manager = Manager(app) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'build': _gen = Gen(app) _gen.gen() # update static resources update_static_res() elif len(sys.argv) > 1 and sys.argv[1] == 'first_upload': first_upload() elif len(sys.argv) > 1 and sys.argv[1] == 'other_upload': other_upload() else: manager.run()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 6687, 13, 9078, 198, 220, 220, 220, 220, 15116, 93, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 4423, 346, 198, 11748, 3859, 198, 6738, 598,...
2.308782
353
from typing import Any import torch import torch.nn as nn from cvmodels.segmentation import unet, deeplab as dl
[ 6738, 19720, 1330, 4377, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 198, 6738, 269, 85, 27530, 13, 325, 5154, 341, 1330, 555, 316, 11, 390, 68, 489, 397, 355, 288, 75, 628, 628, 628, 628, 628, 198 ]
2.928571
42
# Copyright (c) Uber Technologies, Inc. and its affiliates. # Copyright (c) 2021 Kuaishou AI Platform & DS3 Lab. # # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from distutils.version import LooseVersion import torch from torch.autograd.function import Function import torch.nn.functional as F from torch.nn.modules.batchnorm import _BatchNorm import bagua.torch_api as bagua from bagua.torch_api.communication import allgather, allreduce # Backward compat for old PyTorch if not hasattr(torch.jit, "unused"): torch.jit.unused = lambda x: x _SYNC_BN_V2 = LooseVersion(torch.__version__) >= LooseVersion("1.5.0") and LooseVersion( torch.__version__ ) <= LooseVersion("1.6.0") _SYNC_BN_V3 = LooseVersion(torch.__version__) >= LooseVersion("1.6.0") _SYNC_BN_V4 = LooseVersion(torch.__version__) >= LooseVersion("1.9.0")
[ 2, 15069, 357, 66, 8, 12024, 21852, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 15069, 357, 66, 8, 33448, 509, 6413, 680, 280, 9552, 19193, 1222, 17400, 18, 3498, 13, 198, 2, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, ...
2.916409
323
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import pandas as pd from aif360.datasets import BinaryLabelDataset from aif360.metrics import ClassificationMetric
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 299, 32152, ...
3.666667
78
city_country = {} for _ in range(int(input())): country, *cities = input().split() for city in cities: city_country[city] = country for _ in range(int(input())): print(city_country[input()])
[ 19205, 62, 19315, 796, 23884, 198, 1640, 4808, 287, 2837, 7, 600, 7, 15414, 28955, 2599, 198, 220, 1499, 11, 1635, 66, 871, 796, 5128, 22446, 35312, 3419, 198, 220, 329, 1748, 287, 4736, 25, 198, 220, 220, 220, 1748, 62, 19315, 58, ...
2.898551
69
import os from dotenv import load_dotenv load_dotenv() basedir = os.path.abspath(os.path.dirname(__file__)) config = { 'development': DevConfig, 'testing': TestConfig, 'production': ProductionConfig, 'default': DevConfig }
[ 11748, 28686, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 198, 2220, 62, 26518, 24330, 3419, 198, 3106, 343, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 628, ...
2.733333
90
import asyncio if __name__ == "__main__": import time s = time.perf_counter() asyncio.run(main()) # Completing unfinished tasks (throws a warning) # loop = asyncio.get_event_loop() # loop.run_until_complete(main()) # pending = asyncio.Task.all_tasks() # loop.run_until_complete(asyncio.gather(*pending)) elapsed = time.perf_counter() - s print(f"{__file__} executed in {elapsed:0.2f} seconds.")
[ 11748, 30351, 952, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1330, 640, 198, 220, 220, 220, 264, 796, 640, 13, 525, 69, 62, 24588, 3419, 198, 220, 220, 220, 30351, 952, 13, 5143, 7...
2.486034
179
# from vk_bot.core.modules.basicplug import BasicPlug # import math # class Calculator(BasicPlug): # doc = "" # command = ("",) # def main(self): # try: # x = self.text[1]; x = int(x) # encalc = self.text[2]; encalc = encalc.lower() # y = self.text[3]; y = int(y) # except: # self.sendmsg(""" : / 2 + 2 # 2 , """) # return # if encalc == "+" or encalc == "": # result = x + y # elif encalc == "-" or encalc == "": # result = x - y # elif encalc == "*" or encalc == "": # result = x * y # elif encalc == "**" or encalc == "" or encalc == "^": # if x > 999 or y > 999: # return # result = x ** y # elif encalc == "": # try: # x / y # except ZeroDivisionError: # result = " ?" # elif encalc == "": # result = math.sqrt(x), math.sqrt(y) # elif encalc == "": # result = math.sin(x), math.sin(y) # elif encalc == "": # result = math.cos(x), math.cos(y) # else: # return # self.sendmsg(f" : {result}")
[ 2, 422, 410, 74, 62, 13645, 13, 7295, 13, 18170, 13, 35487, 16875, 1330, 14392, 23257, 198, 2, 1330, 10688, 198, 2, 1398, 43597, 7, 26416, 23257, 2599, 198, 2, 220, 220, 220, 220, 2205, 796, 13538, 198, 2, 220, 220, 220, 220, 3141...
1.678191
752
import openmoc import openmoc.log as log import openmoc.plotter as plotter import openmoc.materialize as materialize log.set_log_level('NORMAL') ############################################################################### ########################### Creating Materials ############################ ############################################################################### log.py_printf('NORMAL', 'Importing materials data from HDF5...') materials = openmoc.materialize.load_from_hdf5('c5g7-mgxs.h5', '../') ############################################################################### ########################### Creating Surfaces ############################# ############################################################################### log.py_printf('NORMAL', 'Creating surfaces...') xmin = openmoc.XPlane(x=-5.0, name='xmin') xmax = openmoc.XPlane(x= 5.0, name='xmax') ymin = openmoc.YPlane(y=-5.0, name='ymin') ymax = openmoc.YPlane(y= 5.0, name='ymax') zmin = openmoc.ZPlane(z=-5.0, name='zmin') zmax = openmoc.ZPlane(z= 5.0, name='zmax') xmin.setBoundaryType(openmoc.REFLECTIVE) xmax.setBoundaryType(openmoc.REFLECTIVE) ymin.setBoundaryType(openmoc.REFLECTIVE) ymax.setBoundaryType(openmoc.REFLECTIVE) zmin.setBoundaryType(openmoc.REFLECTIVE) zmax.setBoundaryType(openmoc.REFLECTIVE) ############################################################################### ############################# Creating Cells ############################## ############################################################################### log.py_printf('NORMAL', 'Creating cells...') fuel = openmoc.Cell(name='fuel') fuel.setFill(materials['UO2']) moderator = openmoc.Cell(name='moderator') moderator.setFill(materials['UO2']) root_cell = openmoc.Cell(name='root cell') root_cell.addSurface(halfspace=+1, surface=xmin) root_cell.addSurface(halfspace=-1, surface=xmax) root_cell.addSurface(halfspace=+1, surface=ymin) root_cell.addSurface(halfspace=-1, surface=ymax) root_cell.addSurface(halfspace=+1, surface=zmin) root_cell.addSurface(halfspace=-1, surface=zmax) ############################################################################### ########################### Creating Universes ############################ ############################################################################### log.py_printf('NORMAL', 'Creating universes...') fue_univ = openmoc.Universe(name='homogeneous fue cell') fue_univ.addCell(fuel) mod_univ = openmoc.Universe(name='homogeneous mod cell') mod_univ.addCell(moderator) root_universe = openmoc.Universe(name='root universe') root_universe.addCell(root_cell) ############################################################################### ########################### Creating Lattices ############################# ############################################################################### log.py_printf('NORMAL', 'Creating simple 10 x 10 lattice...') f = fue_univ lattice = openmoc.Lattice(name='10x10 lattice') lattice.setWidth(width_x=1.0, width_y=1.0, width_z=1.0) lattice.setUniverses([[[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]], [[f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f], [f, f, f, f, f, f, f, f, f, f]]]) root_cell.setFill(lattice) ############################################################################### ########################## Creating the Geometry ########################## ############################################################################### log.py_printf('NORMAL', 'Creating geometry...') geometry = openmoc.Geometry() geometry.setRootUniverse(root_universe) geometry.initializeFlatSourceRegions()
[ 11748, 1280, 76, 420, 198, 11748, 1280, 76, 420, 13, 6404, 355, 2604, 198, 11748, 1280, 76, 420, 13, 29487, 353, 355, 7110, 353, 198, 11748, 1280, 76, 420, 13, 33665, 1096, 355, 2587, 1096, 198, 198, 6404, 13, 2617, 62, 6404, 62, ...
1.643916
5,597
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib import sys from google.ads.google_ads import util if sys.version_info < (3, 6): raise ImportError("This module requires Python 3.6 or later.") _lazy_name_to_package_map = { "account_budget_proposal_service_client": "google.ads.google_ads.v5.services", "account_budget_service_client": "google.ads.google_ads.v5.services", "account_link_service_client": "google.ads.google_ads.v5.services", "ad_group_ad_asset_view_service_client": "google.ads.google_ads.v5.services", "ad_group_ad_label_service_client": "google.ads.google_ads.v5.services", "ad_group_ad_service_client": "google.ads.google_ads.v5.services", "ad_group_audience_view_service_client": "google.ads.google_ads.v5.services", "ad_group_bid_modifier_service_client": "google.ads.google_ads.v5.services", "ad_group_criterion_label_service_client": "google.ads.google_ads.v5.services", "ad_group_criterion_service_client": "google.ads.google_ads.v5.services", "ad_group_criterion_simulation_service_client": "google.ads.google_ads.v5.services", "ad_group_extension_setting_service_client": "google.ads.google_ads.v5.services", "ad_group_feed_service_client": "google.ads.google_ads.v5.services", "ad_group_label_service_client": "google.ads.google_ads.v5.services", "ad_group_service_client": "google.ads.google_ads.v5.services", "ad_group_simulation_service_client": "google.ads.google_ads.v5.services", "ad_parameter_service_client": "google.ads.google_ads.v5.services", "ad_schedule_view_service_client": "google.ads.google_ads.v5.services", "ad_service_client": "google.ads.google_ads.v5.services", "age_range_view_service_client": "google.ads.google_ads.v5.services", "asset_service_client": "google.ads.google_ads.v5.services", "batch_job_service_client": "google.ads.google_ads.v5.services", "bidding_strategy_service_client": "google.ads.google_ads.v5.services", "billing_setup_service_client": "google.ads.google_ads.v5.services", "campaign_asset_service_client": "google.ads.google_ads.v5.services", "campaign_audience_view_service_client": "google.ads.google_ads.v5.services", "campaign_bid_modifier_service_client": "google.ads.google_ads.v5.services", "campaign_budget_service_client": "google.ads.google_ads.v5.services", "campaign_criterion_service_client": "google.ads.google_ads.v5.services", "campaign_criterion_simulation_service_client": "google.ads.google_ads.v5.services", "campaign_draft_service_client": "google.ads.google_ads.v5.services", "campaign_experiment_service_client": "google.ads.google_ads.v5.services", "campaign_extension_setting_service_client": "google.ads.google_ads.v5.services", "campaign_feed_service_client": "google.ads.google_ads.v5.services", "campaign_label_service_client": "google.ads.google_ads.v5.services", "campaign_service_client": "google.ads.google_ads.v5.services", "campaign_shared_set_service_client": "google.ads.google_ads.v5.services", "carrier_constant_service_client": "google.ads.google_ads.v5.services", "change_status_service_client": "google.ads.google_ads.v5.services", "click_view_service_client": "google.ads.google_ads.v5.services", "conversion_action_service_client": "google.ads.google_ads.v5.services", "conversion_adjustment_upload_service_client": "google.ads.google_ads.v5.services", "conversion_upload_service_client": "google.ads.google_ads.v5.services", "currency_constant_service_client": "google.ads.google_ads.v5.services", "custom_interest_service_client": "google.ads.google_ads.v5.services", "customer_client_link_service_client": "google.ads.google_ads.v5.services", "customer_client_service_client": "google.ads.google_ads.v5.services", "customer_extension_setting_service_client": "google.ads.google_ads.v5.services", "customer_feed_service_client": "google.ads.google_ads.v5.services", "customer_label_service_client": "google.ads.google_ads.v5.services", "customer_manager_link_service_client": "google.ads.google_ads.v5.services", "customer_negative_criterion_service_client": "google.ads.google_ads.v5.services", "customer_service_client": "google.ads.google_ads.v5.services", "detail_placement_view_service_client": "google.ads.google_ads.v5.services", "display_keyword_view_service_client": "google.ads.google_ads.v5.services", "distance_view_service_client": "google.ads.google_ads.v5.services", "domain_category_service_client": "google.ads.google_ads.v5.services", "dynamic_search_ads_search_term_view_service_client": "google.ads.google_ads.v5.services", "expanded_landing_page_view_service_client": "google.ads.google_ads.v5.services", "extension_feed_item_service_client": "google.ads.google_ads.v5.services", "feed_item_service_client": "google.ads.google_ads.v5.services", "feed_item_target_service_client": "google.ads.google_ads.v5.services", "feed_mapping_service_client": "google.ads.google_ads.v5.services", "feed_placeholder_view_service_client": "google.ads.google_ads.v5.services", "feed_service_client": "google.ads.google_ads.v5.services", "gender_view_service_client": "google.ads.google_ads.v5.services", "geo_target_constant_service_client": "google.ads.google_ads.v5.services", "geographic_view_service_client": "google.ads.google_ads.v5.services", "google_ads_field_service_client": "google.ads.google_ads.v5.services", "google_ads_service_client": "google.ads.google_ads.v5.services", "group_placement_view_service_client": "google.ads.google_ads.v5.services", "hotel_group_view_service_client": "google.ads.google_ads.v5.services", "hotel_performance_view_service_client": "google.ads.google_ads.v5.services", "income_range_view_service_client": "google.ads.google_ads.v5.services", "invoice_service_client": "google.ads.google_ads.v5.services", "keyword_plan_ad_group_keyword_service_client": "google.ads.google_ads.v5.services", "keyword_plan_ad_group_service_client": "google.ads.google_ads.v5.services", "keyword_plan_campaign_keyword_service_client": "google.ads.google_ads.v5.services", "keyword_plan_campaign_service_client": "google.ads.google_ads.v5.services", "keyword_plan_idea_service_client": "google.ads.google_ads.v5.services", "keyword_plan_service_client": "google.ads.google_ads.v5.services", "keyword_view_service_client": "google.ads.google_ads.v5.services", "label_service_client": "google.ads.google_ads.v5.services", "landing_page_view_service_client": "google.ads.google_ads.v5.services", "language_constant_service_client": "google.ads.google_ads.v5.services", "location_view_service_client": "google.ads.google_ads.v5.services", "managed_placement_view_service_client": "google.ads.google_ads.v5.services", "media_file_service_client": "google.ads.google_ads.v5.services", "merchant_center_link_service_client": "google.ads.google_ads.v5.services", "mobile_app_category_constant_service_client": "google.ads.google_ads.v5.services", "mobile_device_constant_service_client": "google.ads.google_ads.v5.services", "offline_user_data_job_service_client": "google.ads.google_ads.v5.services", "operating_system_version_constant_service_client": "google.ads.google_ads.v5.services", "paid_organic_search_term_view_service_client": "google.ads.google_ads.v5.services", "parental_status_view_service_client": "google.ads.google_ads.v5.services", "payments_account_service_client": "google.ads.google_ads.v5.services", "product_bidding_category_constant_service_client": "google.ads.google_ads.v5.services", "product_group_view_service_client": "google.ads.google_ads.v5.services", "reach_plan_service_client": "google.ads.google_ads.v5.services", "recommendation_service_client": "google.ads.google_ads.v5.services", "remarketing_action_service_client": "google.ads.google_ads.v5.services", "search_term_view_service_client": "google.ads.google_ads.v5.services", "shared_criterion_service_client": "google.ads.google_ads.v5.services", "shared_set_service_client": "google.ads.google_ads.v5.services", "shopping_performance_view_service_client": "google.ads.google_ads.v5.services", "third_party_app_analytics_link_service_client": "google.ads.google_ads.v5.services", "topic_constant_service_client": "google.ads.google_ads.v5.services", "topic_view_service_client": "google.ads.google_ads.v5.services", "user_data_service_client": "google.ads.google_ads.v5.services", "user_interest_service_client": "google.ads.google_ads.v5.services", "user_list_service_client": "google.ads.google_ads.v5.services", "user_location_view_service_client": "google.ads.google_ads.v5.services", "video_service_client": "google.ads.google_ads.v5.services", "account_budget_proposal_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "account_budget_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "account_link_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_ad_asset_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_ad_label_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_ad_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_audience_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_bid_modifier_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_criterion_label_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_criterion_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_criterion_simulation_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_extension_setting_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_feed_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_label_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_group_simulation_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_parameter_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_schedule_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "ad_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "age_range_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "asset_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "batch_job_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "bidding_strategy_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "billing_setup_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_asset_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_audience_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_bid_modifier_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_budget_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_criterion_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_criterion_simulation_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_draft_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_experiment_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_extension_setting_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_feed_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_label_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "campaign_shared_set_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "carrier_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "change_status_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "click_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "conversion_action_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "conversion_adjustment_upload_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "conversion_upload_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "currency_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "custom_interest_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_client_link_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_client_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_extension_setting_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_feed_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_label_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_manager_link_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_negative_criterion_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "customer_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "detail_placement_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "display_keyword_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "distance_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "domain_category_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "dynamic_search_ads_search_term_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "expanded_landing_page_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "extension_feed_item_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "feed_item_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "feed_item_target_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "feed_mapping_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "feed_placeholder_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "feed_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "gender_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "geo_target_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "geographic_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "google_ads_field_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "google_ads_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "group_placement_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "hotel_group_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "hotel_performance_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "income_range_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "invoice_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "keyword_plan_ad_group_keyword_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "keyword_plan_ad_group_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "keyword_plan_campaign_keyword_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "keyword_plan_campaign_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "keyword_plan_idea_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "keyword_plan_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "keyword_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "label_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "landing_page_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "language_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "location_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "managed_placement_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "media_file_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "merchant_center_link_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "mobile_app_category_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "mobile_device_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "offline_user_data_job_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "operating_system_version_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "paid_organic_search_term_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "parental_status_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "payments_account_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "product_bidding_category_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "product_group_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "reach_plan_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "recommendation_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "remarketing_action_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "search_term_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "shared_criterion_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "shared_set_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "shopping_performance_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "third_party_app_analytics_link_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "topic_constant_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "topic_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "user_data_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "user_interest_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "user_list_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "user_location_view_service_grpc_transport": "google.ads.google_ads.v5.services.transports", "video_service_grpc_transport": "google.ads.google_ads.v5.services.transports", } # Background on how this behaves: https://www.python.org/dev/peps/pep-0562/ def __getattr__(name): # Requires Python >= 3.7 """Lazily perform imports and class definitions on first demand.""" if name == "__all__": converted = ( util.convert_snake_case_to_upper_case(key) for key in _lazy_name_to_package_map ) all_names = sorted(converted) globals()["__all__"] = all_names return all_names elif name.endswith("Transport"): module = __getattr__(util.convert_upper_case_to_snake_case(name)) sub_mod_class = getattr(module, name) klass = type(name, (sub_mod_class,), {"__doc__": sub_mod_class.__doc__}) globals()[name] = klass return klass elif name.endswith("ServiceClient"): module = __getattr__(util.convert_upper_case_to_snake_case(name)) enums = __getattr__("enums") sub_mod_class = getattr(module, name) klass = type( name, (sub_mod_class,), {"__doc__": sub_mod_class.__doc__, "enums": enums}, ) globals()[name] = klass return klass elif name == "enums": path = "google.ads.google_ads.v5.services.enums" module = importlib.import_module(path) globals()[name] = module return module elif name == "types": path = "google.ads.google_ads.v5.types" module = importlib.import_module(path) globals()[name] = module return module elif name in _lazy_name_to_package_map: module = importlib.import_module( f"{_lazy_name_to_package_map[name]}.{name}" ) globals()[name] = module return module else: raise AttributeError(f"unknown sub-module {name!r}.") if not sys.version_info >= (3, 7): from pep562 import Pep562 Pep562(__name__)
[ 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
2.629301
8,457
""" Created on July 20, 2020 Updated on May 19, 2021 model: Product-based Neural Networks for User Response Prediction @author: Ziyao Geng(zggzy1996@163.com) """ import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.regularizers import l2 from tensorflow.keras.layers import Embedding, Dense, Layer, Dropout, Input from modules import DNN
[ 37811, 198, 41972, 319, 2901, 1160, 11, 12131, 198, 17354, 319, 1737, 678, 11, 33448, 198, 198, 19849, 25, 8721, 12, 3106, 47986, 27862, 329, 11787, 18261, 46690, 198, 198, 31, 9800, 25, 1168, 21008, 78, 402, 1516, 7, 89, 1130, 7357, ...
3.226087
115
nume1 = int(input("Digite um numero")) nume2 = int(input("Digite um numero")) nume3 = int(input("Digite um numero")) nume4 = int(input("Digite um numero")) nume5 = int(input("Digite um numero")) table = [nume1,nume2,nume3,nume4,nume5] tableM = (float((nume1 + nume2 + nume3 + nume4 + nume5))) print(float(tableM))
[ 77, 2454, 16, 796, 493, 7, 15414, 7203, 19511, 578, 23781, 997, 3529, 48774, 198, 77, 2454, 17, 796, 493, 7, 15414, 7203, 19511, 578, 23781, 997, 3529, 48774, 198, 77, 2454, 18, 796, 493, 7, 15414, 7203, 19511, 578, 23781, 997, 3529...
2.343284
134
from typing import TypeVar from .abstract import AbstractBox T = TypeVar('T')
[ 6738, 19720, 1330, 5994, 19852, 198, 198, 6738, 764, 397, 8709, 1330, 27741, 14253, 198, 198, 51, 796, 5994, 19852, 10786, 51, 11537, 628 ]
3.375
24
from mongoengine import *
[ 6738, 285, 25162, 18392, 1330, 1635 ]
4.166667
6
s = Solution() print(s.combinationSum([2,3,6,7], 7)) print(s.combinationSum([2,3,5], 8))
[ 198, 82, 796, 28186, 3419, 198, 4798, 7, 82, 13, 24011, 1883, 13065, 26933, 17, 11, 18, 11, 21, 11, 22, 4357, 767, 4008, 198, 4798, 7, 82, 13, 24011, 1883, 13065, 26933, 17, 11, 18, 11, 20, 4357, 807, 4008, 198 ]
2.142857
42
#!/usr/bin/env python # -*- coding: utf-8 -*- __doc__ = ''' Crawl comment from nicovideo.jp Usage: crawl_comments.py --url <url> --mail <mail> --pass <pass> [--sqlite <sqlite>] [--csv <csv>] Options: --url <url> --mail <mail> --pass <pass> --sqlite <sqlite> (optional) path of comment DB [default: comments.sqlite3] --csv <csv> (optional) path of csv file contains urls of videos [default: crawled.csv] ''' from docopt import docopt from nicocrawler.nicocrawler import NicoCrawler if __name__ == '__main__': # args = docopt(__doc__) url_channel_toppage = args['--url'] login_mail = args['--mail'] login_pass = args['--pass'] path_sqlite = args['--sqlite'] path_csv = args['--csv'] ncrawler = NicoCrawler(login_mail, login_pass) ncrawler.connect_sqlite(path_sqlite) df = ncrawler.get_all_video_url_of_season(url_channel_toppage) ncrawler.initialize_csv_from_db(path_csv) # # 1~300 # url = 'http://www.nicovideo.jp/ranking/fav/daily/all' # ncrawler.initialize_csv_from_url(url, path_csv, max_page=3) # ncrawler.get_all_comments_of_csv(path_csv, max_n_iter=1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 834, 15390, 834, 796, 705, 7061, 198, 34, 13132, 2912, 422, 9200, 709, 1651, 13, 34523, 198, 198, 28350, 25, 198...
2.343313
501
# Functions to do the greedy similarity maximisation for article:node assignments # All code is original import random def computeSimSum(G, similarityMatrix, asgn): """ Compute the total similarity sum for the current node:article assignment """ S = sum([similarityMatrix[asgn[j], asgn[i]] for j in range(len(G)) for i in list(G[j])]) return S
[ 2, 40480, 284, 466, 262, 31828, 26789, 12991, 5612, 329, 2708, 25, 17440, 25815, 198, 2, 1439, 2438, 318, 2656, 628, 198, 11748, 4738, 628, 198, 4299, 24061, 8890, 13065, 7, 38, 11, 26789, 46912, 11, 355, 4593, 2599, 198, 220, 37227, ...
2.867647
136
import sys import numpy as np import shutil import time import itertools as it import collections import ctypes as ct import os import copy sys.path.append(os.path.dirname(__file__)) from ThreadStoppable import ThreadStoppable # if __name__ == "__main__": main()
[ 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4423, 346, 198, 11748, 640, 198, 11748, 340, 861, 10141, 355, 340, 198, 11748, 17268, 198, 11748, 269, 19199, 355, 269, 83, 198, 11748, 28686, 198, 11748, 4866, 198, 198, 175...
3.090909
88
import sys, numpy, argparse, os if __name__ == '__main__': main()
[ 11748, 25064, 11, 299, 32152, 11, 1822, 29572, 11, 28686, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 197, 12417, 3419, 198 ]
2.518519
27
# This program reads a file representing web server logs in common log format and streams them into a PubSub topic # with lag characteristics as determined by command-line arguments import argparse from google.cloud import pubsub_v1 import time from datetime import datetime, timezone import random from anytree.importer import DictImporter import json from multiprocessing import Process parser = argparse.ArgumentParser(__file__, description="event_generator") parser.add_argument("--taxonomy", "-x", dest="taxonomy_fp", help="A .json file representing a taxonomy of web resources", default="taxonomy.json") parser.add_argument("--users_fp", "-u", dest="users_fp", help="A .csv file of users", default="users.csv") parser.add_argument("--off_to_on", "-off", dest="off_to_on_prob", type=float, help="A float representing the probability that a user who is offline will come online", default=.25) parser.add_argument("--on_to_off", "-on", dest="on_to_off_prob", type=float, help="A float representing the probability that a user who is online will go offline", default=.1) parser.add_argument("--max_lag_millis", '-l', dest="max_lag_millis", type=int, help="An integer representing the maximum amount of lag in millisecond", default=250) parser.add_argument("--project_id", "-p", type=str, dest="project_id", help="A GCP Project ID", required=True) parser.add_argument("--topic_name", "-t", dest="topic_name", type=str, help="The name of the topic where the messages to be published", required=True) avg_secs_between_events = 5 args = parser.parse_args() taxonomy_fp = args.taxonomy_fp users_fp = args.users_fp online_to_offline_probability = args.on_to_off_prob offline_to_online_probability = args.off_to_on_prob max_lag_millis = args.max_lag_millis project_id = args.project_id topic_name = args.topic_name min_file_size_bytes = 100 max_file_size_bytes = 500 verbs = ["GET"] responses = [200] log_fields = ["ip", "user_id", "lat", "lng", "timestamp", "http_request", "http_response", "num_bytes", "user_agent"] def extract_resources(taxonomy_filepath): """ Reads a .json representing a taxonomy and returns a data structure representing their hierarchical relationship :param taxonomy_file: a string representing a path to a .json file :return: Node representing root of taxonomic tree """ try: with open(taxonomy_filepath, 'r') as fp: json_str = fp.read() json_data = json.loads(json_str) root = DictImporter().import_(json_data) finally: fp.close() return root def read_users(users_fp): """ Reads a .csv from @user_fp representing users into a list of dictionaries, each elt of which represents a user :param user_fp: a .csv file where each line represents a user :return: a list of dictionaries """ users = [] with open(users_fp, 'r') as fp: fields = fp.readline().rstrip().split(",") for line in fp: user = dict(zip(fields, line.rstrip().split(","))) users.append(user) return users def sleep_then_publish_burst(burst, publisher, topic_path): """ :param burst: a list of dictionaries, each representing an event :param num_events_counter: an instance of Value shared by all processes to track the number of published events :param publisher: a PubSub publisher :param topic_path: a topic path for PubSub :return: """ sleep_secs = random.uniform(0, max_lag_millis/1000) time.sleep(sleep_secs) publish_burst(burst, publisher, topic_path) def publish_burst(burst, publisher, topic_path): """ Publishes and prints each event :param burst: a list of dictionaries, each representing an event :param num_events_counter: an instance of Value shared by all processes to track the number of published events :param publisher: a PubSub publisher :param topic_path: a topic path for PubSub :return: """ for event_dict in burst: json_str = json.dumps(event_dict) data = json_str.encode('utf-8') publisher.publish(topic_path, data=data, timestamp=event_dict['timestamp']) def create_user_process(user, root): """ Code for continuously-running process representing a user publishing events to pubsub :param user: a dictionary representing characteristics of the user :param root: an instance of AnyNode representing the home page of a website :param num_events_counter: a variable shared among all processes used to track the number of events published :return: """ publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_name) user['page'] = root user['is_online'] = True user['offline_events'] = [] while True: time_between_events = random.uniform(0, avg_secs_between_events * 2) time.sleep(time_between_events) prob = random.random() event = generate_event(user) if user['is_online']: if prob < online_to_offline_probability: user['is_online'] = False user['offline_events'] = [event] else: sleep_then_publish_burst([event], publisher, topic_path) else: user['offline_events'].append(event) if prob < offline_to_online_probability: user['is_online'] = True sleep_then_publish_burst(user['offline_events'], publisher, topic_path) user['offline_events'] = [] def generate_event(user): """ Returns a dictionary representing an event :param user: :return: """ user['page'] = get_next_page(user) uri = str(user['page'].name) event_time = datetime.now(tz=timezone.utc) current_time_str = event_time.strftime('%Y-%m-%dT%H:%M:%S.%fZ') file_size_bytes = random.choice(range(min_file_size_bytes, max_file_size_bytes)) http_request = "\"{} {} HTTP/1.0\"".format(random.choice(verbs), uri) http_response = random.choice(responses) event_values = [user['ip'], user['id'], float(user['lat']), float(user['lng']), current_time_str, http_request, http_response, file_size_bytes, user['user_agent']] return dict(zip(log_fields, event_values)) def get_next_page(user): """ Consults the user's representation of the web site taxonomy to determine the next page that they visit :param user: :return: """ possible_next_pages = [user['page']] if not user['page'].is_leaf: possible_next_pages += list(user['page'].children) if (user['page'].parent != None): possible_next_pages += [user['page'].parent] next_page = random.choice(possible_next_pages) return next_page if __name__ == '__main__': users = read_users(users_fp) root = extract_resources(taxonomy_fp) processes = [Process(target=create_user_process, args=(user, root)) for user in users] [process.start() for process in processes] while True: time.sleep(1)
[ 2, 770, 1430, 9743, 257, 2393, 10200, 3992, 4382, 17259, 287, 2219, 2604, 5794, 290, 15190, 606, 656, 257, 8525, 7004, 7243, 201, 198, 2, 351, 19470, 9695, 355, 5295, 416, 3141, 12, 1370, 7159, 201, 198, 201, 198, 11748, 1822, 29572, ...
2.486306
2,994
"""Database setup""" # Third party library from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate # initialization of the database and migration database = SQLAlchemy() migrate = Migrate()
[ 37811, 38105, 9058, 37811, 198, 198, 2, 10467, 2151, 5888, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 42903, 62, 76, 42175, 1330, 337, 42175, 198, 198, 2, 37588, 286, 262, 6831, 290, 13472, 198, 48806,...
3.888889
54
import datetime as dt import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd from powersimdata.input.check import _check_time_series from postreise.analyze.time import change_time_zone def plot_heatmap( series, time_zone=None, time_zone_label=None, title=None, cmap="PiYG", scale=None, save_filename=None, origin="upper", vmin=None, vmax=None, cbar_format=None, cbar_tick_values=None, cbar_label=None, cbar_tick_labels=None, contour_levels=None, figsize=(16, 8), ): """Show time-series values via an imshow where each column is one color-coded day. :param pandas.Series series: a time-series of values to be color-coded. :param str time_zone: a time zone to be passed as `tz` kwarg to :func:`postreise.analyze.time.change_time_zone`. :param str time_zone_label: a time zone label to be added to the y axis label. :param str title: a title to be added to the figure. :param str/matplotlib.colors.Colormap cmap: colormap specification to be passed as `cmap` kwarg to :func:`matplotlib.pyplot.imshow`. :param int/float scale: a scaling factor to be applied to the series values. :param str save_filename: a path to save the figure to. :param str origin: the vertical location of the origin, either "upper" or "lower". :param int/float vmin: Minimum value for coloring, to be passed as `vmin` kwarg to :func:`matplotlib.pyplot.imshow`. :param int/float vmax: Maximum value for coloring, to be passed as `vmax` kwarg to :func:`matplotlib.pyplot.imshow`. :param str/matplotlib.ticker.Formatter cbar_format: a formatter for colorbar labels, to be passed as `format` kwarg to :func:`matplotlib.pyplot.colorbar`. :param iterable cbar_tick_values: colorbar tick locations, to be passed as `ticks` kwarg to :func:`matplotlib.pyplot.colorbar`. :param str cbar_label: axis label for colorbar. :param iterable cbar_tick_labels: colorbar tick labels. :param iterable contour_levels: values at which to draw contours, passed as `levels` kwarg to :func:`matplotlib.pyplot.contour`. :param tuple(int/float, int/float) figsize: size of figure. """ _check_time_series(series, "series") df = series.to_frame(name="values").asfreq("H") year = df.index[0].year if time_zone is not None: df = change_time_zone(df, time_zone) df["date"] = df.index.date df["hour"] = df.index.hour df_reshaped = pd.pivot( df, index="date", columns="hour", values="values", ) xlims = mdates.date2num([df_reshaped.index[0], df_reshaped.index[-1]]) ylims = mdates.date2num([dt.datetime(year, 1, 1, 0), dt.datetime(year, 1, 1, 23)]) if scale is not None: df_reshaped *= scale fig = plt.figure(figsize=figsize) ax = fig.add_subplot() # if necessary, flip ylims so labels follow data from top to bottom extent = [*xlims, *ylims] if origin == "lower" else [*xlims, ylims[1], ylims[0]] im = plt.imshow( df_reshaped.T, cmap=cmap, aspect="auto", extent=extent, origin=origin, vmin=vmin, vmax=vmax, ) if contour_levels is not None: ax.contour(df_reshaped.T, extent=extent, levels=contour_levels, origin=origin) date_format = mdates.DateFormatter("%m/%d") ax.xaxis_date() ax.xaxis.set_major_formatter(date_format) ax.set_xlabel("Date") time_format = mdates.DateFormatter("%H:%M") ax.yaxis_date() ax.yaxis.set_major_formatter(time_format) y_axis_label = "Time" if time_zone_label is None else f"Time {time_zone_label}" ax.set_ylabel(y_axis_label) cbar = fig.colorbar(im, format=cbar_format, ticks=cbar_tick_values) if cbar_label is not None: cbar.set_label(cbar_label) if title is not None: plt.title(title) if cbar_tick_labels is not None: cbar.ax.set_yticklabels(cbar_tick_labels) if save_filename is not None: plt.savefig(save_filename, bbox_inches="tight")
[ 11748, 4818, 8079, 355, 288, 83, 198, 198, 11748, 2603, 29487, 8019, 13, 19581, 355, 285, 19581, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 5635, 320, 7890, 13, 15414...
2.398483
1,714
# Copyright 2018, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementations of the ClientData abstract base class.""" import collections import os.path from typing import Callable, Mapping import tensorflow as tf from tensorflow_federated.python import core as tff from tensorflow_federated.python.common_libs import py_typecheck from tensorflow_federated.python.simulation import client_data from tensorflow_federated.python.tensorflow_libs import tensor_utils
[ 2, 15069, 2864, 11, 383, 309, 22854, 37535, 35089, 515, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
3.665455
275
from django.contrib import admin from blog.models import Post, Comment # Register your models here. admin.site.register(Post) admin.site.register(Comment)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 201, 198, 6738, 4130, 13, 27530, 1330, 2947, 11, 18957, 201, 198, 201, 198, 2, 17296, 534, 4981, 994, 13, 201, 198, 28482, 13, 15654, 13, 30238, 7, 6307, 8, 201, 198, 28482, 13, 15654,...
3.24
50
from unittest.mock import NonCallableMock, sentinel from pytest import mark, raises, fixture from preacher.compilation.argument import Argument from preacher.compilation.error import CompilationError, NamedNode, IndexedNode from preacher.compilation.request.request import RequestCompiler, RequestCompiled from preacher.compilation.request.request_body import RequestBodyCompiler from preacher.core.request import Method PKG = "preacher.compilation.request.request" def test_given_an_empty_mapping(compiler: RequestCompiler): compiled = compiler.compile({}) assert compiled.method is sentinel.default_method assert compiled.path is sentinel.default_path assert compiled.headers is sentinel.default_headers assert compiled.params is sentinel.default_params assert compiled.body is sentinel.default_body def test_given_an_invalid_params(compiler: RequestCompiler, mocker): compile_params = mocker.patch(f"{PKG}.compile_url_params") compile_params.side_effect = CompilationError("msg", node=NamedNode("x")) with raises(CompilationError) as error_info: compiler.compile({"params": sentinel.params}) assert error_info.value.path == [NamedNode("params"), NamedNode("x")] compile_params.assert_called_once_with(sentinel.params, None) def test_given_valid_params(compiler: RequestCompiler, mocker): compile_params = mocker.patch(f"{PKG}.compile_url_params") compile_params.return_value = sentinel.compiled_params compiled = compiler.compile({"params": sentinel.params}, sentinel.args) assert compiled.params == sentinel.compiled_params compile_params.assert_called_once_with(sentinel.params, sentinel.args) def test_given_invalid_body(compiler: RequestCompiler, body): body.compile.side_effect = CompilationError("x", node=IndexedNode(1)) with raises(CompilationError) as error_info: compiler.compile({"body": sentinel.body_obj}) assert error_info.value.path == [NamedNode("body"), IndexedNode(1)] body.compile.assert_called_once_with(sentinel.body_obj, None) def test_given_valid_body(compiler: RequestCompiler, body): body.compile.return_value = sentinel.body compiled = compiler.compile({"body": sentinel.body_obj}, sentinel.args) assert compiled.body is sentinel.body body.compile.assert_called_once_with(sentinel.body_obj, sentinel.args) def test_given_a_string(compiler: RequestCompiler): compiled = compiler.compile(Argument("path"), {"path": "/path"}) assert compiled.method is sentinel.default_method assert compiled.path == "/path" assert compiled.headers is sentinel.default_headers assert compiled.params is sentinel.default_params assert compiled.body is sentinel.default_body def test_of_default_no_body(compiler: RequestCompiler, body, mocker): ctor = mocker.patch(f"{PKG}.RequestCompiler") ctor.return_value = sentinel.compiler_of_default new_default = RequestCompiled( method=sentinel.new_default_method, path=sentinel.new_default_path, headers=sentinel.new_default_headers, params=sentinel.new_default_params, ) new_compiler = compiler.of_default(new_default) assert new_compiler is sentinel.compiler_of_default ctor.assert_called_once_with( body=body, default=RequestCompiled( method=sentinel.new_default_method, path=sentinel.new_default_path, headers=sentinel.new_default_headers, params=sentinel.new_default_params, body=sentinel.default_body, ), ) body.of_default.assert_not_called() def test_of_default_body(compiler: RequestCompiler, body, mocker): ctor = mocker.patch(f"{PKG}.RequestCompiler") ctor.return_value = sentinel.compiler_of_default new_default = RequestCompiled(body=sentinel.new_default_body) new_compiler = compiler.of_default(new_default) assert new_compiler is sentinel.compiler_of_default ctor.assert_called_once_with( body=sentinel.new_body_compiler, default=RequestCompiled( method=sentinel.default_method, path=sentinel.default_path, headers=sentinel.default_headers, params=sentinel.default_params, body=sentinel.new_default_body, ), ) body.of_default.assert_called_once_with(sentinel.new_default_body)
[ 6738, 555, 715, 395, 13, 76, 735, 1330, 8504, 14134, 540, 44, 735, 11, 1908, 20538, 198, 198, 6738, 12972, 9288, 1330, 1317, 11, 12073, 11, 29220, 198, 198, 6738, 39797, 13, 5589, 10520, 13, 49140, 1330, 45751, 198, 6738, 39797, 13, ...
2.764669
1,585
# imports from telegram.ext import ( CommandHandler, MessageHandler, Filters, ConversationHandler, ) from handler_functions.start import start from handler_functions.bio import bio from handler_functions.gender import gender from handler_functions.photo import photo, skip_photo from handler_functions.location import location, skip_location from handler_functions.cancel import cancel from conversation_handlers.stage_constants import * # Adds conversation handler with the states GENDER, PHOTO, LOCATION and BIO for stage 1 of the sign up conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ GENDER: [MessageHandler(Filters.regex('^(Gentleman|Lady|I am a unicorn.)$'), gender)], PHOTO: [MessageHandler(Filters.photo, photo), CommandHandler('skip', skip_photo)], LOCATION: [ MessageHandler(Filters.location, location), CommandHandler('skip', skip_location), ], BIO: [MessageHandler(Filters.text & ~Filters.command, bio)], }, fallbacks=[CommandHandler('cancel', cancel)], )
[ 2, 17944, 198, 6738, 573, 30536, 13, 2302, 1330, 357, 198, 220, 220, 220, 9455, 25060, 11, 198, 220, 220, 220, 16000, 25060, 11, 198, 220, 220, 220, 7066, 1010, 11, 198, 220, 220, 220, 42427, 25060, 11, 198, 8, 198, 6738, 21360, 6...
3.021798
367
# value =float(input('')) unit =input('') if unit == 'in' or unit == '': print('%f = %f' % (value, value * 2.54)) elif unit == '' or unit == 'cm': print('%f = %f' % (value, value / 2.54)) else: print('')
[ 2, 220, 198, 198, 8367, 796, 22468, 7, 15414, 7, 7061, 4008, 198, 20850, 796, 15414, 7, 7061, 8, 198, 361, 4326, 6624, 705, 259, 6, 393, 4326, 6624, 10148, 25, 198, 220, 220, 220, 3601, 10786, 4, 69, 796, 4064, 69, 6, 4064, 357,...
2.20202
99
from ocean_lib.models.data_token import DataToken from ocean_lib.models.dtfactory import DTFactory from ocean_lib.ocean.util import to_base_18
[ 6738, 9151, 62, 8019, 13, 27530, 13, 7890, 62, 30001, 1330, 6060, 30642, 198, 6738, 9151, 62, 8019, 13, 27530, 13, 67, 27110, 9548, 1330, 360, 10234, 9548, 198, 6738, 9151, 62, 8019, 13, 78, 5829, 13, 22602, 1330, 284, 62, 8692, 62,...
3.2
45
# coding=utf-8 """PyTorch optimization for BERT model.""" from apex.contrib.optimizers import FP16_Optimizer
[ 2, 19617, 28, 40477, 12, 23, 198, 37811, 20519, 15884, 354, 23989, 329, 347, 17395, 2746, 526, 15931, 198, 198, 6738, 40167, 13, 3642, 822, 13, 40085, 11341, 1330, 31459, 1433, 62, 27871, 320, 7509, 628 ]
3.083333
36
from .generator import * from .types import *
[ 6738, 764, 8612, 1352, 1330, 1635, 198, 6738, 764, 19199, 1330, 1635, 198 ]
3.538462
13
import Bugdetectionuniversalframe import os import re
[ 11748, 15217, 15255, 3213, 403, 1191, 1604, 28073, 198, 11748, 28686, 198, 11748, 302, 628 ]
3.666667
15
""" station.py """ from datetime import datetime, timedelta import gzip import numpy as np import requests import urllib _BASEURL = 'http://www.ndbc.noaa.gov/data' _SENSOR_URL = _BASEURL+'/stations/buoyht.txt' _REALTIME_URL = _BASEURL+'/realtime2/' _RECENT_URL = _BASEURL+'/stdmet/' _HISTORICAL_URL = _BASEURL+'/historical/stdmet/' _STATION_URL = _BASEURL+'/stations/station_table.txt'
[ 37811, 198, 17529, 13, 9078, 198, 37811, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 11748, 308, 13344, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 7007, 198, 11748, 2956, 297, 571, 198, 198, 62, 33, 11159, 21886...
2.403727
161
# -*- coding: utf-8 -*- #!/usr/bin/env python __author__ = "Andres Mendez-Vazquez" __copyright__ = "Copyright 2018" __credits__ = ["Andres Mendez-Vazquez"] __license__ = "Apache" __version__ = "v1.0.0" __maintainer__ = "Andres Mendez-Vazquez" __email = "kajuna0kajuna@gmail.com" __status__ = "Development" from data_model.load_data import create_connection, select_all_tasks from tools.data_frames import dframe_t_db if __name__ == '__main__': df = main() print(df)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 834, 9800, 834, 796, 366, 1870, 411, 20442, 8471, 12, 53, 1031, 22281, 1, 198, 834, 22163, 4766, 834, 796, 366, ...
2.476923
195
# version of the graw package __version__ = "0.1.0"
[ 198, 2, 2196, 286, 262, 308, 1831, 5301, 198, 834, 9641, 834, 796, 366, 15, 13, 16, 13, 15, 1, 628 ]
2.571429
21
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __all__ = [ 'GetCertificateResult', 'AwaitableGetCertificateResult', 'get_certificate', ] def get_certificate(domain: Optional[str] = None, key_types: Optional[Sequence[str]] = None, most_recent: Optional[bool] = None, statuses: Optional[Sequence[str]] = None, tags: Optional[Mapping[str, str]] = None, types: Optional[Sequence[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCertificateResult: """ Use this data source to get the ARN of a certificate in AWS Certificate Manager (ACM), you can reference it by domain without having to hard code the ARNs as input. ## Example Usage ```python import pulumi import pulumi_aws as aws issued = aws.acm.get_certificate(domain="tf.example.com", statuses=["ISSUED"]) amazon_issued = aws.acm.get_certificate(domain="tf.example.com", most_recent=True, types=["AMAZON_ISSUED"]) rsa4096 = aws.acm.get_certificate(domain="tf.example.com", key_types=["RSA_4096"]) ``` :param str domain: The domain of the certificate to look up. If no certificate is found with this name, an error will be returned. :param Sequence[str] key_types: A list of key algorithms to filter certificates. By default, ACM does not return all certificate types when searching. Valid values are `RSA_1024`, `RSA_2048`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, and `EC_secp521r1`. :param bool most_recent: If set to true, it sorts the certificates matched by previous criteria by the NotBefore field, returning only the most recent one. If set to false, it returns an error if more than one certificate is found. Defaults to false. :param Sequence[str] statuses: A list of statuses on which to filter the returned list. Valid values are `PENDING_VALIDATION`, `ISSUED`, `INACTIVE`, `EXPIRED`, `VALIDATION_TIMED_OUT`, `REVOKED` and `FAILED`. If no value is specified, only certificates in the `ISSUED` state are returned. :param Mapping[str, str] tags: A mapping of tags for the resource. :param Sequence[str] types: A list of types on which to filter the returned list. Valid values are `AMAZON_ISSUED` and `IMPORTED`. """ __args__ = dict() __args__['domain'] = domain __args__['keyTypes'] = key_types __args__['mostRecent'] = most_recent __args__['statuses'] = statuses __args__['tags'] = tags __args__['types'] = types if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('aws:acm/getCertificate:getCertificate', __args__, opts=opts, typ=GetCertificateResult).value return AwaitableGetCertificateResult( arn=__ret__.arn, domain=__ret__.domain, id=__ret__.id, key_types=__ret__.key_types, most_recent=__ret__.most_recent, statuses=__ret__.statuses, tags=__ret__.tags, types=__ret__.types)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 24118, 687, 10290, 357, 27110, 5235, 8, 16984, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760...
2.611069
1,319
import numpy as np import matplotlib.pyplot as plt TOTAL = 200 STEP = 0.25 EPS = 0.1 INITIAL_THETA = [9, 14] X = np.arange(0, TOTAL * STEP, STEP) Y = np.array([y for y in generate_sample(TOTAL)]) # , X = (X - X.min()) / (X.max() - X.min()) A = np.empty((TOTAL, 2)) A[:, 0] = 1 A[:, 1] = X theta = np.linalg.pinv(A).dot(Y) print(theta, cost_function(A, Y, theta)) import time start = time.clock() theta_stochastic = stochastic_descent(A, Y, 0.1) print("St:", time.clock() - start, theta_stochastic) start = time.clock() theta_batch = batch_descent(A, Y, 0.001) print("Btch:", time.clock() - start, theta_batch)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 51, 27510, 796, 939, 198, 42135, 796, 657, 13, 1495, 198, 36, 3705, 796, 657, 13, 16, 198, 1268, 2043, 12576, 62, 4221, 20892, 79...
2.215548
283