content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # import ai_flow as af hourly_data_dir = '/tmp/hourly_data' process_result_base_path = '/tmp/hourly_processed' daily_data_base_path = '/tmp/daily_data' daily_result = '/tmp/daily_result' if __name__ == '__main__': af.init_ai_flow_context() init()
[ 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, ...
3.478405
301
from pyradioconfig.parts.ocelot.profiles.Profile_WiSUN import Profile_WiSUN_Ocelot from pyradioconfig.parts.common.profiles.bobcat_regs import build_modem_regs_bobcat from pyradioconfig.parts.common.profiles.profile_common import buildCrcOutputs, buildFecOutputs, buildFrameOutputs, \ buildWhiteOutputs
[ 6738, 279, 2417, 9189, 36221, 5647, 13, 42632, 13, 78, 5276, 313, 13, 5577, 2915, 13, 37046, 62, 31294, 50, 4944, 1330, 13118, 62, 31294, 50, 4944, 62, 46, 5276, 313, 198, 6738, 279, 2417, 9189, 36221, 5647, 13, 42632, 13, 11321, 13...
2.807339
109
import logging import pytest from . import auth from hydroengine_service import dgds_functions logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 12972, 9288, 198, 198, 6738, 764, 1330, 6284, 198, 198, 6738, 17173, 18392, 62, 15271, 1330, 288, 70, 9310, 62, 12543, 2733, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198 ...
3.214286
42
from math import log import numpy as np from numpy import linalg as la
[ 6738, 10688, 1330, 2604, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 1330, 300, 1292, 70, 355, 8591, 628 ]
3.428571
21
import numpy as np # TODO : add code for referee
[ 11748, 299, 32152, 355, 45941, 198, 198, 2, 16926, 46, 1058, 751, 2438, 329, 22957 ]
3.266667
15
from mpi4py.futures import MPIPoolExecutor import numpy as np import pandas as pd from quasinet.qnet import Qnet, qdistance, load_qnet, qdistance_matrix from quasinet.qsampling import qsample, targeted_qsample qnet=load_qnet('../results/PTSD_cognet_test.joblib') w = 304 h = w p_all = pd.read_csv("tmp_samples_as_strings.csv", header=None).values.astype(str)[:] if __name__ == '__main__': with MPIPoolExecutor() as executor: result = executor.map(dfunc_line, range(h)) result = pd.DataFrame(result) result = result.to_numpy() result = pd.DataFrame(np.maximum(result, result.transpose())) result.to_csv('tmp_distmatrix.csv',index=None,header=None)
[ 6738, 285, 14415, 19, 9078, 13, 69, 315, 942, 1330, 4904, 4061, 970, 23002, 38409, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 627, 292, 42504, 13, 80, 3262, 1330, 1195, 3262, 11, 10662, 30246,...
2.599206
252
# -*- coding: utf-8 -*- """Tests for Bio2BEL FamPlex."""
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 51, 3558, 329, 16024, 17, 33, 3698, 16513, 46383, 526, 15931, 198 ]
2.071429
28
from typing import List from pysat.solvers import Solver from ..variables import VarPool from .reductions import ClauseGenerator from ..examples import BaseExamplesProvider from ..logging_utils import * from ..statistics import STATISTICS from ..structures import APTA, DFA, InconsistencyGraph
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 279, 893, 265, 13, 34453, 690, 1330, 4294, 332, 198, 198, 6738, 11485, 25641, 2977, 1330, 12372, 27201, 198, 6738, 764, 445, 20847, 1330, 28081, 8645, 1352, 198, 6738, 11485, 1069, 12629, 1330, 7...
3.759494
79
## -*- coding: UTF8 -*- ## manager.py ## Copyright (c) 2020 libcommon ## ## Permission is hereby granted, free of charge, to any person obtaining a copy ## of this software and associated documentation files (the "Software"), to deal ## in the Software without restriction, including without limitation the rights ## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ## copies of the Software, and to permit persons to whom the Software is ## furnished to do so, subject to the following conditions: ## ## The above copyright notice and this permission notice shall be included in all ## copies or substantial portions of the Software. ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ## SOFTWARE. from getpass import getpass import os from pathlib import Path from typing import Any, Optional, Union from sqlalchemy import create_engine as sqla_create_engine, MetaData from sqlalchemy.engine import Engine from sqlalchemy.engine.url import make_url, URL from sqlalchemy.orm import scoped_session as ScopedSession, Session, sessionmaker as SessionMaker from sqlalchemy.orm.query import Query __author__ = "libcommon" DBManagerSessionFactory = Union[ScopedSession, SessionMaker] DBManagerSession = Union[ScopedSession, Session] ConnectionURL = Union[str, URL] if os.environ.get("ENVIRONMENT") == "TEST": import unittest from unittest.mock import patch, mock_open from tests.common import BaseTable, User
[ 2235, 220, 532, 9, 12, 19617, 25, 41002, 23, 532, 9, 12, 198, 2235, 4706, 13, 9078, 198, 2235, 15069, 357, 66, 8, 12131, 9195, 11321, 198, 2235, 198, 2235, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 167...
3.653021
513
# -*- coding: utf-8 -*- """mazeexperiment.__main__: executed when mazeexperiment directory is called as script.""" from .mazeexperiment import main main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 220, 198, 37811, 76, 6201, 23100, 3681, 13, 834, 12417, 834, 25, 10945, 618, 31237, 23100, 3681, 8619, 318, 1444, 355, 4226, 526, 15931, 198, 220, 198, 6738, 764, 76, ...
3.018868
53
from tweepy import StreamListener, OAuthHandler, Stream from configs import Configs import sys configs = Configs() producer = None try: producer = create_kafka_producer() client = create_twitter_client(producer, configs) client.filter(track=configs.twitter_topics) finally: exit_gracefully(producer)
[ 6738, 4184, 538, 88, 1330, 13860, 33252, 11, 440, 30515, 25060, 11, 13860, 198, 6738, 4566, 82, 1330, 17056, 82, 198, 11748, 25064, 628, 628, 628, 198, 11250, 82, 796, 17056, 82, 3419, 198, 18230, 2189, 796, 6045, 198, 28311, 25, 198,...
2.918919
111
""" Stability analysis of the D2Q4 solver for the advection equation d_t(u) + c_x d_x(u) + c_y d_y(u) = 0 """ import sympy as sp import pylbm # pylint: disable=invalid-name # symbolic variables U, X, Y = sp.symbols('U, X, Y') # symbolic parameters LA, CX, CY = sp.symbols('lambda, cx, cy', constants=True) S_1, S_2 = sp.symbols('s1, s2', constants=True) # numerical parameters la = 1. # velocity of the scheme s_1, s_2 = 2., 1. # relaxation parameters c_x, c_y = 0.5, 0.25 # velocity of the advection equation dico = { 'dim': 2, 'scheme_velocity': LA, 'schemes': [ { 'velocities': [1, 2, 3, 4], 'conserved_moments': U, 'polynomials': [1, X, Y, X**2-Y**2], 'relaxation_parameters': [0, S_1, S_1, S_2], 'equilibrium': [ U, CX*U, CY*U, (CX**2-CY**2)*U ], }, ], 'parameters': { LA: la, S_1: s_1, S_2: s_2, CX: c_x, CY: c_y, }, 'relative_velocity': [CX, CY], } scheme = pylbm.Scheme(dico) stab = pylbm.Stability(scheme) stab.visualize({ 'parameters': { CX: { 'range': [0, 1], 'init': c_x, 'step': 0.01, }, CY: { 'range': [0, 1], 'init': c_y, 'step': 0.01, }, S_1: { 'name': r"$s_1$", 'range': [0, 2], 'init': s_1, 'step': 0.01, }, S_2: { 'name': r"$s_2$", 'range': [0, 2], 'init': s_2, 'step': 0.01, }, }, 'number_of_wave_vectors': 4096, })
[ 198, 198, 37811, 198, 47865, 3781, 286, 262, 198, 360, 17, 48, 19, 1540, 332, 329, 262, 512, 303, 596, 16022, 628, 288, 62, 83, 7, 84, 8, 220, 220, 1343, 269, 62, 87, 288, 62, 87, 7, 84, 8, 1343, 269, 62, 88, 288, 62, 88, ...
1.649376
1,041
from numpy import reshape
[ 6738, 299, 32152, 1330, 27179, 1758, 628, 198 ]
3.5
8
# -*- coding: utf-8 -*- # ******************************************************* # Copyright (c) VMware, Inc. 2020-2021. All Rights Reserved. # SPDX-License-Identifier: MIT # ******************************************************* # * # * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT # * WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN, # * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED # * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, # * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. """Unit tests for the analysis engine""" import pytest from cbc_binary_toolkit import InitializationError from cbc_binary_toolkit.config import Config from cbc_binary_toolkit.engine import LocalEngineManager from cbc_binary_toolkit.schemas import EngineResponseSchema from tests.component.engine_fixtures.mock_engine import MockLocalEngine from tests.component.schema_fixtures.mock_data import VALID_BINARY_METADATA, MISSING_FIELDS_BINARY_METADATA ENGINE_NAME = "MockEngine" # ==================================== Unit TESTS BELOW ==================================== def test_create_engine(config): """Test successful creation of MockLocalEngine""" manager = LocalEngineManager(config) assert isinstance(manager.create_engine(), MockLocalEngine) def test_analyze(config): """Test analyze pass through""" manager = LocalEngineManager(config) assert EngineResponseSchema.validate(manager.analyze(VALID_BINARY_METADATA))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 41906, 8412, 2466, 8162, 198, 2, 15069, 357, 66, 8, 37754, 11, 3457, 13, 12131, 12, 1238, 2481, 13, 1439, 6923, 33876, 13, 198, 2, 30628, 55, 12, 34156, 12, ...
3.41387
447
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
"""PaccMann vanilla generator trained on polymer building blocks (catalysts/monomers).""" import logging import os from dataclasses import field from typing import ClassVar, Dict, Optional, TypeVar from ....domains.materials import SmallMolecule, validate_molecules from ....exceptions import InvalidItem from ....training_pipelines.core import TrainingPipelineArguments from ....training_pipelines.paccmann.core import PaccMannSavingArguments from ...core import AlgorithmConfiguration, GeneratorAlgorithm, Untargeted from ...registry import ApplicationsRegistry from .implementation import Generator logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) T = type(None) S = TypeVar("S", bound=SmallMolecule)
[ 37811, 47, 4134, 44, 1236, 16858, 17301, 8776, 319, 30528, 2615, 7021, 357, 9246, 3400, 6448, 14, 2144, 21499, 21387, 15931, 198, 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 4818, 330, 28958, 1330, 2214, 198, 6738, 19720, 1330, 5016,...
3.658416
202
# -*- coding: utf-8 -*- # import wx import wx.lib.newevent from form.panel.BasePanel import BasePanel from form.parts.SizingFileSet import SizingFileSet from module.MMath import MRect, MVector3D, MVector4D, MQuaternion, MMatrix4x4 # noqa from utils import MFileUtils # noqa from utils.MLogger import MLogger # noqa logger = MLogger(__name__)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 11748, 266, 87, 198, 11748, 266, 87, 13, 8019, 13, 3605, 15596, 198, 198, 6738, 1296, 13, 35330, 13, 14881, 26639, 1330, 7308, 26639, 198, 6738, 1296, 13, 4263...
2.572464
138
#!/usr/bin/env python """Androguard Gui""" import argparse import os import sys from androguard.core import androconf from androguard.gui.mainwindow import MainWindow from PyQt5 import QtWidgets, QtGui if __name__ == '__main__': parser = argparse.ArgumentParser(description="Androguard GUI") parser.add_argument("-d", "--debug", action="store_true", default=False) parser.add_argument("-i", "--input_file", default=None) parser.add_argument("-p", "--input_plugin", default=None) args = parser.parse_args() if args.debug: androconf.set_debug() # We need that to save huge sessions when leaving and avoid # RuntimeError: maximum recursion depth exceeded while pickling an object # or # RuntimeError: maximum recursion depth exceeded in cmp # http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-using-pythons-pickle-cpickle sys.setrecursionlimit(50000) app = QtWidgets.QApplication(sys.argv) app.setWindowIcon(QtGui.QIcon(os.path.join(androconf.CONF['data_prefix'], "androguard.ico"))) window = MainWindow(input_file=args.input_file, input_plugin=args.input_plugin) window.resize(1024, 768) window.show() sys.exit(app.exec_())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 1870, 3828, 84, 446, 1962, 72, 37811, 198, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 290, 3828, 84, 446, 13, 7295, 1330, 290, 305, 10414, 19...
2.654737
475
"""Translate strings to and from SOAP 1.2 XML name encoding Implements rules for mapping application defined name to XML names specified by the w3 SOAP working group for SOAP version 1.2 in Appendix A of "SOAP Version 1.2 Part 2: Adjuncts", W3C Working Draft 17, December 2001, <http://www.w3.org/TR/soap12-part2/#namemap> Also see <http://www.w3.org/2000/xp/Group/xmlp-issues>. Author: Gregory R. Warnes <gregory_r_warnes@groton.pfizer.com> Date:: 2002-04-25 Version 0.9.0 """ ident = "$Id: XMLname.py 25 2006-05-24 18:12:14Z misha $" from re import * def toXMLname(string): """Convert string to a XML name.""" if string.find(':') != -1 : (prefix, localname) = string.split(':',1) else: prefix = None localname = string T = unicode(localname) N = len(localname) X = []; for i in range(N) : if i< N-1 and T[i]==u'_' and T[i+1]==u'x': X.append(u'_x005F_') elif i==0 and N >= 3 and \ ( T[0]==u'x' or T[0]==u'X' ) and \ ( T[1]==u'm' or T[1]==u'M' ) and \ ( T[2]==u'l' or T[2]==u'L' ): X.append(u'_xFFFF_' + T[0]) elif (not _NCNameChar(T[i])) or (i==0 and not _NCNameStartChar(T[i])): X.append(_toUnicodeHex(T[i])) else: X.append(T[i]) return u''.join(X) def fromXMLname(string): """Convert XML name to unicode string.""" retval = sub(r'_xFFFF_','', string ) retval = sub(r'_x[0-9A-Za-z]+_', fun, retval ) return retval
[ 37811, 8291, 17660, 13042, 284, 290, 422, 12809, 2969, 352, 13, 17, 23735, 1438, 21004, 201, 198, 201, 198, 3546, 1154, 902, 3173, 329, 16855, 3586, 5447, 1438, 284, 23735, 3891, 201, 198, 23599, 416, 262, 266, 18, 12809, 2969, 1762, ...
1.923628
838
from __future__ import absolute_import, division, print_function from libtbx.utils import null_out from libtbx import easy_pickle from six.moves import cStringIO as StringIO if (__name__ == "__main__"): exercise_simple() print("OK")
[ 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 6738, 9195, 83, 65, 87, 13, 26791, 1330, 9242, 62, 448, 198, 6738, 9195, 83, 65, 87, 1330, 2562, 62, 27729, 293, 198, 6738, 2237, 13, 76, 5241...
3.064103
78
# Time: O(n) # Space: O(n) import collections
[ 2, 3862, 25, 220, 440, 7, 77, 8, 198, 2, 4687, 25, 440, 7, 77, 8, 198, 198, 11748, 17268, 628, 198 ]
2.272727
22
from flask import Flask, render_template, request app = Flask(__name__)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198 ]
3.47619
21
""" Usage: # From tensorflow/models/ # Create train data: python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=train.record # Create test data: python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=test.record """ from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import io import pandas as pd import tensorflow as tf from PIL import Image from collections import namedtuple, OrderedDict flags = tf.app.flags flags.DEFINE_string('image_dir', '', 'Path to the image directory') flags.DEFINE_string('csv_input', '', 'Path to the CSV input') flags.DEFINE_string('output_path', '', 'Path to output TFRecord') FLAGS = flags.FLAGS # TO-DO replace this with label map if __name__ == '__main__': tf.app.run()
[ 37811, 198, 28350, 25, 198, 220, 1303, 3574, 11192, 273, 11125, 14, 27530, 14, 198, 220, 1303, 13610, 4512, 1366, 25, 198, 220, 21015, 7716, 62, 27110, 22105, 13, 9078, 1377, 40664, 62, 15414, 28, 7890, 14, 27432, 62, 23912, 1424, 13,...
3.080586
273
from machine import Pin from lh_lib.sensors.sensor import AbstractSensor
[ 6738, 4572, 1330, 13727, 198, 198, 6738, 300, 71, 62, 8019, 13, 82, 641, 669, 13, 82, 22854, 1330, 27741, 47864, 628 ]
3.409091
22
import os import cv2 import albumentations as A from albumentations.pytorch import ToTensorV2 from torch.utils.data import Dataset, DataLoader from sklearn.model_selection import train_test_split __all__ = ['CatDogDataset', 'fetch_dataloader']
[ 11748, 28686, 198, 11748, 269, 85, 17, 198, 198, 11748, 435, 65, 1713, 602, 355, 317, 198, 6738, 435, 65, 1713, 602, 13, 9078, 13165, 354, 1330, 1675, 51, 22854, 53, 17, 198, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, ...
2.964286
84
from keras.preprocessing.text import text_to_word_sequence from keras.models import Sequential from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent, Embedding from keras.layers.recurrent import LSTM from keras.optimizers import Adam, RMSprop from nltk import FreqDist import numpy as np import os import datetime
[ 6738, 41927, 292, 13, 3866, 36948, 13, 5239, 1330, 2420, 62, 1462, 62, 4775, 62, 43167, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 13144, 341, 11, 3862, 20344, 6169, 11, 360, 1072, ...
3.44
100
"""Standard test images. """ import os from skimage.io import imread data_dir = os.path.abspath(os.path.dirname(__file__)) __all__ = ['data_dir', 'circle', 'skmuscimg'] def _load(f, as_gray=False): """Load an image file located in the data directory. Parameters ---------- f : string File name. as_gray : bool, optional Whether to convert the image to grayscale. Returns ------- img : ndarray Image loaded from ``data_dir``. """ # importing io is quite slow since it scans all the backends # we lazy import it here return imread(f, as_gray=as_gray) def circle(): """Synthetic image of a circle Returns ------- circle : (xdim, ydim) bool ndarray Circle image. """ return _load(os.path.join(data_dir, "circle.bmp")) def skmuscimg(): """Cropped US image of a musculoskeletal muscle """ return _load(os.path.join(data_dir, "skmuscle.jpg")) def panoimg(): """Panoramic US image of a musculoskeletal muscle """ return _load(os.path.join(data_dir, "panoramic_echo.jpg")) def simpleimg(): """Simple US image of a musculoskeletal muscle """ return _load(os.path.join(data_dir, "simple_echo.jpg")) def downloadFromDropbox(tok, path2file): """Download an image from a Dropbox account. Args: tok (string): access token that connects to the wanted app in Dropbox account path2file (string): Path of the file to download, in the app corresponding to the above token. Output: image (numpy.ndarray): 3-channel color image, with coefficients' type == uint8 Example: 1) Register a new app in the App Console of your Dropbox account. Set up parameters as you want. 2) In Dropbox>Applications>MyApp, import your data. 3) In the settings page of MyApp, generate a token and copy it. It should look like a random string of letters and figures, as below. (!!!This access token can be used to access your account via the API. Dont share your access token with anyone!!!) > token = 'Q8yhHQ4wquAAAAAAAAABRPb9LYdKAr2WGcmhhJ8egiX4_Qak6YZwBw4GUpX9DVeb' //token not available anymore > path = '/cropped_20181002_153426_image.jpg' > dt = downloadFromDropbox(token, path); """ import dropbox import numpy as np import cv2 dbx = dropbox.Dropbox(tok) try: metadata, file = dbx.files_download(path2file) except dropbox.exceptions.HttpError as err: print('*** HTTP error', err) return None data = np.frombuffer(file.content, np.uint8) image = cv2.imdecode(data, 1) return image
[ 220, 220, 198, 37811, 23615, 1332, 4263, 13, 628, 198, 37811, 198, 198, 11748, 28686, 198, 6738, 1341, 9060, 13, 952, 1330, 545, 961, 198, 198, 7890, 62, 15908, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 15908, ...
2.393401
1,182
# -*- coding: utf-8 -*- # @Time : 2020/11/9 9:13 # @Author : quanbing # @Email : quanbinks@sina.com import pandas as pd import numpy as np from unittest import TestCase from pandas_support import PandasSupport as PS # @File : test_pandas_support.py
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 1058, 12131, 14, 1157, 14, 24, 860, 25, 1485, 220, 198, 2, 2488, 13838, 1058, 627, 272, 4623, 198, 2, 2488, 15333, 1058, 627, 272, 65, 2973, 31, 82, ...
2.571429
98
# !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 # -*- coding:utf-8 -*- # @Author : Jiazhixiang # cmdline, from scrapy import cmdline # executescrapy cmdline.execute(['scrapy', 'crawl', 'douban'])
[ 2, 5145, 14, 23377, 14, 42026, 14, 37906, 13, 30604, 14, 45150, 14, 18, 13, 22, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 2488, 13838, 1058, 449, 17890, 71, 844, 15483, 198, 198...
2.5
86
from Array import empty_1d_array """ input array : [10, 22, 9, 33, 21, 50, 41, 60] # Element at each index `i` is representing length of longest LIS from index 0 to i in input array. output array: [1, 2, 1, 3, 2, 4, 4, 5] """ # Time complexity: O(n^2) # Space complexity: O(n) if __name__ == '__main__': arr = [10, 22, 9, 33, 21, 50, 41, 60] max_lis = lis_dp(arr) print "Length of longest increasing sub-sequence for given array is {}".format(max_lis)
[ 6738, 15690, 1330, 6565, 62, 16, 67, 62, 18747, 198, 198, 37811, 198, 15414, 7177, 1058, 685, 940, 11, 2534, 11, 860, 11, 4747, 11, 2310, 11, 2026, 11, 6073, 11, 3126, 60, 198, 198, 2, 11703, 379, 1123, 6376, 4600, 72, 63, 318, ...
2.534392
189
# Copyright (c) 2009-2014, gevent contributors # Based on eventlet.backdoor Copyright (c) 2005-2006, Bob Ippolito from __future__ import print_function import sys from code import InteractiveConsole from gevent import socket from gevent.greenlet import Greenlet from gevent.hub import PY3, PYPY, getcurrent from gevent.server import StreamServer if PYPY: import gc __all__ = ['BackdoorServer'] try: sys.ps1 except AttributeError: sys.ps1 = '>>> ' try: sys.ps2 except AttributeError: sys.ps2 = '... ' if __name__ == '__main__': if not sys.argv[1:]: print('USAGE: %s PORT' % sys.argv[0]) else: BackdoorServer(('127.0.0.1', int(sys.argv[1])), locals={'hello': 'world'}).serve_forever()
[ 2, 15069, 357, 66, 8, 3717, 12, 4967, 11, 4903, 1151, 20420, 198, 2, 13403, 319, 1785, 1616, 13, 1891, 9424, 15069, 357, 66, 8, 5075, 12, 13330, 11, 5811, 314, 381, 6212, 78, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818...
2.56446
287
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 17 16:12:56 2020 @author: dylanroyston """ # import/configure packages import numpy as np import pandas as pd #import pyarrow as pa import librosa import librosa.display from pathlib import Path #import Ipython.display as ipd #import matplotlib.pyplot as plt from pyspark.sql import * import pyspark.sql.functions as f from pyspark import SparkConf, SparkContext, SQLContext import boto3 from tinytag import TinyTag as tt import soundfile as sf import audioread from pydub import AudioSegment from io import BytesIO #from io import BytesIO import os import sys import time import struct sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/lib") #import config time_seq = [] ##### # create local Spark instance (for non-cluster dev) sc = SparkContext('local') spark = SparkSession (sc) spark.conf.set("spark.sql.execution.arrow.enabled", "true") # define Spark config spark = spark_conf() spark.conf.set("spark.sql.execution.arrow.enabled", "true") ##### # Function to write spark-dataframe to mySQL ##### # function to read audio files from S3 bucket and extract tags ##### if __name__ == '__main__': time_seq.append(['start', time.time()]) read_audio_files()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 7653, 1596, 1467, 25, 1065, 25, 3980, 12131, 198, 198, 31, 9800, 25, 288, 18554, 32...
2.811688
462
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """ ip . """ import ipaddress import sys import requests rs = requests.get('https://jarib.github.io/anon-history/RuGovEdits/ru/latest/ranges.json') # if not rs or not rs.json() or 'ranges' not in rs.json(): print(' ip ') sys.exit() # items = sorted(rs.json()['ranges'].items(), key=lambda x: x[0]) ip_counter = 0 for i, (name, ip_network_list) in enumerate(items, 1): print(f'{i}. {name}') # ip for ip_network in ip_network_list: print(f' {ip_network}:') # ip net4 = ipaddress.ip_network(ip_network) # ip for ip in net4.hosts(): print(f' {ip}') ip_counter += 1 print() print(' ip:', ip_counter)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 796, 705, 541, 21879, 1077, 6, 628, 198, 37811, 198, 220, 220, 20966, 220, 764, 198, 198, ...
2.05598
393
import unittest import requests from collection import Collection
[ 11748, 555, 715, 395, 198, 11748, 7007, 198, 198, 6738, 4947, 1330, 12251, 198 ]
4.785714
14
from . import nand_tests from . import and_tests from . import nor_tests from . import not_tests from . import or_tests from . import xor_tests from . import rotate_left_tests from . import rotate_right_tests from . import shift_left_tests from . import shift_right_tests
[ 6738, 764, 1330, 299, 392, 62, 41989, 198, 6738, 764, 1330, 290, 62, 41989, 198, 6738, 764, 1330, 4249, 62, 41989, 198, 6738, 764, 1330, 407, 62, 41989, 198, 6738, 764, 1330, 393, 62, 41989, 198, 6738, 764, 1330, 2124, 273, 62, 4198...
3.4
80
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """Misc helpers""" import math import random import re import signal import typing as t from datetime import datetime from enum import Enum from functools import reduce from inspect import isabstract from string import ascii_letters from subprocess import list2cmdline as _list2cmdline from typing import Mapping as Map import numpy as np from exot.exceptions import * __all__ = ( "call_with_leaves", "dict_depth", "dict_diff", "find_attributes", "flatten_dict", "get_concrete_subclasses", "get_subclasses", "get_valid_access_paths", "getitem", "has_method", "has_property", "has_type", "has_variable", "is_abstract", "is_scalar_numeric", "leaves", "list2cmdline", "map_to_leaves", "mro_getattr", "mro_hasattr", "random_string", "safe_eval", "sanitise_ansi", "setgetattr", "setitem", "stub_recursively", "unpack__all__", "validate_helper", "get_cores_and_schedules", ) """ Signatures ---------- call_with_leaves :: (function: Callable[[Any], Any], obj: ~T, _seq: bool = True) -> None dict_depth :: (obj: Any, level: int = 0) -> int dict_diff :: (left: Mapping, right: Mapping) -> List[Dict] find_attributes :: (attr: str, klass: Any) -> List flatten_dict :: (obj: Mapping, sep: str = '.') -> Mapping get_concrete_subclasses :: (klass, recursive=True, derived=True) -> List get_subclasses :: (klass, recursive=True, derived=True) -> List get_valid_access_paths :: (obj: Mapping, _limit: int = 8192, _leaf_only: bool = False, _use_lists: bool = True, _fallthrough_empty: bool = True) -> Generator getitem :: (obj: Mapping, query: Union[str, Tuple], *args: Any, sep: str = '/') -> Any has_method :: (klass: Union[type, object], name: str) -> bool has_property :: (klass: Union[type, object], name: str) -> bool has_type :: (klass: Union[type, object]) -> bool has_variable :: (klass: Union[type, object], name: str) -> bool is_abstract :: (klass: Union[type, object]) -> bool is_scalar_numeric :: (value: t.Any) -> bool map_to_leaves :: (function: Callable[[Any], Any], obj: ~T, _seq: bool = True) -> Any mro_getattr :: (cls: type, attr: str, *args: Any) -> Any mro_hasattr :: (cls: type, attr: str) -> bool random_string :: (length: int) -> str safe_eval :: (to_eval: str, expect: Tuple[type], timeout: int) -> object sanitise_ansi :: (value Union[List[str], str]) -> Union[List[str], str] setgetattr :: (klass: Union[type, object], attr: str, default: Any) -> None setitem :: (obj: MutableMapping, query: Tuple, value: Any) -> None stub_recursively :: (obj: ~T, stub: Any = None, _stub_list_elements: bool = True) -> Optional[~T] unpack__all__ :: (*imports: Collection[str]) -> Tuple[str] validate_helper :: (what: Mapping, key: Any, *types: type, msg: str = '') -> NoReturn """ def call_with_leaves(function: t.Callable[[t.Any], t.Any], obj: t.T, _seq: bool = True) -> None: """Calls a function on leaves of an object A leaf is considered to be an object that is not a Mapping (or, when _seq is set, also not a Sequence except a string, which is also a Sequence). Args: function (t.Callable[[t.Any], t.Any]): The callable obj (t.T): The tree-like or sequence-like object _seq (bool, optional): Should sequences be considered?. Defaults to True. """ inner(obj) def dict_depth(obj: t.Any, level: int = 0) -> int: """Get maximum depth of a dict-like object Args: obj (t.Any): The dict-like object level (int): For internal use only. Defaults to 0. .. note:: The depth of a non-dict-like object is considered to be 0. An empty dict increases the depth if `_empty_increments` is True. Examples: >>> dict_depth(1) # returns 0 >>> dict_depth([1,2,3]) # returns 0 >>> dict_depth({1: 1, 2: 2}) # returns 1 >>> dict_depth({1: {2: {3: 3}}}) # returns 3 >>> dict_depth({1: {2: {3: {}}}}) # returns 4 """ if not isinstance(obj, Map) or not obj: return level return max(dict_depth(v, level + 1) for k, v in obj.items()) def dict_diff(left: Map, right: Map) -> t.List[t.Dict]: """Get the difference between 2 dict-like objects Args: left (Map): The left dict-like object right (Map): The right dict-like object The value returned is a list of dictionaries with keys ["path", "left", "right"] which contain the query path and the differences between the left and right mapping. If a key is missing in either mapping, it will be indicated as a "None". `math.nan` (not-a-number) is used for default values in the comparison because of the property: `math.nan != math.nan`. Simple None cannot be used, since it would not handle keys that both have a value of None. In general, this function might report false-positives for keys that contain the math.nan (or np.nan) value simply due to this property. There is no workaround available. """ left_paths = set(get_valid_access_paths(left, _leaf_only=True, _use_lists=False)) right_paths = set(get_valid_access_paths(right, _leaf_only=True, _use_lists=False)) return list( { "path": path, "left": getitem(left, path, math.nan), "right": getitem(right, path, math.nan), } for path in left_paths.union(right_paths) if getitem(left, path, math.nan) != getitem(right, path, math.nan) ) def find_attributes(klass: t.Any, attr: str) -> t.List: """Find attributes in any of a class'es bases Args: klass (t.Any): The type object attr (str): The attribute Returns: t.List: List of found instances of the attribute in the class hierarchy """ if not isinstance(attr, str): raise TypeError(attr) mro = klass.__mro__ if hasattr(klass, "__mro__") else type(klass).mro() return [attr for base in mro if hasattr(base, attr)] def flatten_dict(obj: Map, sep: str = ".") -> Map: """Flatten a dict to a 1-level dict combining keys with a separator Args: obj (Map): The dict-like object sep (str): The separator used when combining keys. Defaults to ".". Returns: Map: A flattened object of same type as 'obj'. .. warning:: Flattening will enforce all keys to be string-types! `reducer` is a function accepted by the functools.reduce function, which is of form: f(a, b) where _a_ is the accumulated value, and _b_ is the updated value from the iterable. The .items() function produces key-value tuple-pairs. These can be expanded with *, e.g. `*("a", "b")` will expand to `"a", "b"`. This property is used to expand the `kv_pair` below. Example walkthrough on `flatten_dict({'a': 1, 'b': {'c': {'d': 2}}})`: :: `outer` <- obj: {'a': 1, 'b': {'c': {'d': 2}}}, prefix: '' `reducer` <- key: 'a', value: 1 `inner` <- acc: {}, key: 'a', value: 1, prefix: '' `inner` -> {'a': 1} `reducer` -> {'a': 1} `reducer` <- key: 'b', value: {'c': {'d': 2}} `inner` <- acc: {'a': 1}, key: 'b', value: {'c': {'d': 2}}, prefix: '' `outer` <- obj: {'c': {'d': 2}}, prefix: 'b.' `reducer` <- key: 'c', value: {'d': 2} `inner` <- acc: {}, key: 'c', value: {'d': 2}, prefix: 'b.' `outer` <- obj: {'d': 2}, prefix: 'b.c.' `reducer` <- key: 'd', value: 2 `inner` <- acc: {}, key: 'd', value: 2, prefix: 'b.c.' `inner` -> {'b.c.d': 2} `reducer` -> {'b.c.d': 2} `outer` -> {'b.c.d': 2} `inner` -> {'b.c.d': 2} `reducer` -> {'b.c.d': 2} `outer` -> {'b.c.d': 2} `inner` -> {'a': 1, 'b.c.d': 2} `reducer` -> {'a': 1, 'b.c.d': 2} `outer` -> {'a': 1, 'b.c.d': 2} """ if not isinstance(obj, Map): raise TypeError("flatten_dict works only on dict-like types", type(obj)) _t = type(obj) return outer(obj, "") def expand_dict(obj: Map, sep: str = ".") -> Map: """Expands a flattened mapping by splitting keys with the given separator Args: obj (Map): The flattened dict-like object to unflatten sep (str, optional): The key separator Raises: TypeError: If wrong type is supplied ValueError: If a non-flat dict is supplied Returns: Map: The expanded mapping object of same type as 'obj'. Example: >>> d = {'a': 1, 'b': 2, 'c.ca': 1, 'c.cb': 2} >>> expand_dict(d) {'a': 1, 'b': 2, 'c': {'ca': 1, 'cb': 2}} """ if not isinstance(obj, Map): raise TypeError("expand_dict works only on dict-like types", type(obj)) if dict_depth(obj) != 1: raise ValueError( "expand_dict works only on flat dict-like types, " "got a mapping of depth: {}".format(dict_depth(obj)) ) return inner(obj) def get_concrete_subclasses(klass, recursive: bool = True, derived: bool = True) -> t.List: """Get a list of non-abstract subclasses of a type Args: klass (t.Type): The type object recursive (bool): Should the classes be extracted recursively? Defaults to True. derived (bool): Use the 'derived' property of SubclassTracker-enhanced types? [True] Returns: t.List: A list of concrete subclasses of the type """ from exot.util.mixins import _SubclassTracker as __ if derived and hasattr(klass, __.concrete): return list(getattr(klass, __.concrete)) subclasses = get_subclasses(klass, recursive=recursive) return [k for k in subclasses if not isabstract(k)] def get_subclasses(klass, recursive: bool = True, derived: bool = True) -> t.List: """Get a list of subclasses of a type Args: klass (t.Type): The type object recursive (bool): Should the classes be extracted recursively? Defaults to True. derived (bool): Use the 'derived' property of SubclassTracker-enhanced types? [True] Returns: t.List: A list of concrete subclasses of the type """ from exot.util.mixins import _SubclassTracker as __ if not (hasattr(klass, "__subclasses__") or hasattr(klass, __.derived)): raise TypeError(f"__subclasses__ or {__.derived} attribute missing", klass) if derived: return list(getattr(klass, __.derived)) subclasses = klass.__subclasses__() if recursive: walker(subclasses) return subclasses def getitem(obj: Map, query: t.Union[str, t.Tuple], *args: t.Any, sep: str = "/") -> t.Any: """Get a value from a dict-like object using an XPath-like query, or a tuple-path Accesses an object that provides a dict-like interface using a query: either a tuple representing the path, or a string where consecutive keys are separated with a separator, e.g. "key1/key2". Returns the value of the object at the given key-sequence. Returns a default value if provided, or throws a LookupError. Args: obj (Map): a mapping query (t.Union[str, t.Tuple]): a query path using a separated string or a tuple *args (t.Any): an optional default value, similar to `getattr` sep (str, optional): a separator string used to split a string query path Returns: t.Any: the value stored in obj for the given query, or the default value Raises: LookupError: if query not found and no default value is provided TypeError: if obj is not a mapping, or query is not a str or tuple """ if not isinstance(obj, Map): raise TypeError("'obj' must be an instance of Mapping, e.g. dict", type(obj)) if not isinstance(query, (str, t.Tuple)): raise TypeError("'query' must be a str or a tuple", type(query)) if len(args) > 1: raise TypeError(f"getitem accepts at most 3 positional args, got {len(args)}") _obj = obj # handler for tuple queries if isinstance(query, t.Tuple): _valid = get_valid_access_paths(obj) if query not in _valid: if args: return args[0] else: raise LookupError(f"query {query!r} not found") else: for node in query: _obj = _obj[node] return _obj # handler for string queries else: try: # loop through components in the query, consecutively accessing the mapping for node in query.split(sep): # handle empty nodes in the query, e.g. when query="a///b" -> "a/b" if not node: continue if isinstance(_obj, Map): for k in _obj.keys(): node = type(k)(node) if str(k) == node else node elif isinstance(_obj, (t.List, t.Set)): try: node = int(node) except TypeError: raise LookupError( f"{node} not convertible to int when attempting to access " f"a list {_obj!r}" ) _obj = _obj[node] return _obj except LookupError as Error: if args: return args[0] else: Error.args += (query,) raise def has_method(klass: t.Union[type, object], name: str) -> bool: """Check if a method exists in any of a klass'es bases Args: klass (t.Union[type, object]): The type or object name (str): The name of the method Returns: bool: True if has a method with the given name. """ candidates = find_attributes(klass, name) if not candidates: return False return all(is_callable(f) for f in candidates) def has_property(klass: t.Union[type, object], name: str) -> bool: """Check if a variable exists in any of a klass'es bases Args: klass (t.Union[type, object]): The type or object name (str): The name of the property Returns: bool: True if has a property with the given name. """ candidates = find_attributes(klass, name) if not candidates: return False return all(is_property(f) for f in candidates) def has_type(klass: t.Union[type, object]) -> bool: """Check if a type or instance has a Type member type that derives from Enum Args: klass (t.Union[type, object]): The type or object Returns: bool: True if has the "Type" attribute. """ if not isinstance(klass, (type, object)): raise TypeError(klass) return issubclass(getattr(klass, "Type", type(None)), Enum) def has_variable(klass: t.Union[type, object], name: str) -> bool: """Check if a variable exists in any of a klass'es bases Args: klass (t.Union[type, object]): The type or object name (str): The name of the variable Returns: bool: True if has a variable with the given name. """ candidates = find_attributes(klass, name) if not candidates: return False return all(is_not_callable(f) for f in candidates) def is_abstract(klass: t.Union[type, object]) -> bool: """Check if a type or instance is abstract Args: klass (t.Union[type, object]): The type or object Returns: bool: True if the type/instance is abstract. """ if not isinstance(klass, (type, object)): raise TypeError(klass) if hasattr(klass, "__abstractmethods__"): return 0 != len(getattr(klass, "__abstractmethods__")) else: from inspect import isabstract return isabstract(klass) def is_scalar_numeric(value: t.Any) -> bool: """Check if is an int, a float, or a NumPy variant thereof Args: value (t.Any): The value to inspect Returns: bool: True if scalar and numeric. """ return isinstance(value, (float, int, np.integer, np.floating)) def leaves(obj: Map) -> t.Generator: """Get leaves of a mapping Args: obj (Map): The dict-like object Returns: t.Generator: A generator that yields the leaf elements of the mapping. """ paths = get_valid_access_paths(obj, _leaf_only=True, _use_lists=False) return (getitem(obj, path) for path in paths) def list2cmdline(seq: t.Iterable) -> str: """Translates a sequence of arguments into a command line string with "None" removal Args: seq (t.Iterable): The sequence of arguments Returns: str: The command-line string """ seq = [_ for _ in seq if _ is not None] return _list2cmdline(seq) def map_to_leaves(function: t.Callable[[t.Any], t.Any], obj: t.T, _seq: bool = True) -> t.Any: """Map a function to leaves of an object A leaf is considered to be an object that is not a Mapping (or, when _seq is set, also not a Sequence except a string, which is also a Sequence). Args: function (t.Callable[[t.Any], t.Any]): a function or signatude "a -> a" obj (t.T): a dict-like, list-like, or plain object _seq (bool, optional): map on elements of lists? Returns: t.T: the obj with transformed elements """ return inner(obj) def mro_getattr(cls: type, attr: str, *args: t.Any) -> t.Any: """Get an attribute from a type's class hierarchy Args: cls (type): The type attr (str): The attribute *args (t.Any): The default value (like in Python's default getattr) Returns: t.Any: The attribute, or when not found the default value (if provided) Raises: TypeError: Not called on a type TypeError: Wrong number of arguments AttributeError: Attribute not found and no default value provided """ if not isinstance(cls, type): raise TypeError(f"mro_getattr can only be used on types, got {type(cls)}") if len(args) > 1: raise TypeError(f"mro_getattr expected at most 3 arguments, got {2 + len(args)}") for klass in cls.mro()[1:]: if hasattr(klass, attr): # return first matching attribute return getattr(klass, attr) if args: # if provided, return args[0], i.e. the a default value return args[0] else: raise AttributeError(f"type object {cls.__name__!r} has not attribute {attr!r}") def mro_hasattr(cls: type, attr: str) -> bool: """Check if an attribute exists in a type's class hierarchy Args: cls (type): The type attr (str): The attribute Returns: bool: True if has the attribute. Raises: TypeError: Not called on a type """ if not isinstance(cls, type): raise TypeError(f"mro_getattr can only be used on types, got {type(cls)}") for klass in cls.mro()[1:]: if hasattr(klass, attr): return True return False def random_string(length: int) -> str: """Make a random string of specified length Args: length (int): The desired random string length Returns: str: The random string """ assert isinstance(length, int), f"'length' must be an int, got: {type(length)}" return "".join(random.choices(ascii_letters, k=length)) def timestamp() -> str: """Make a timestamp with current time Returns: str: The timestamp in ISO format """ return datetime.now().isoformat("_", timespec="seconds").replace(":", "-") def safe_eval( to_eval: str, *, expect: t.Tuple[type] = (list, np.ndarray), timeout: int = 10 ) -> object: """Evaluate a restricted subset of Python (and numpy) from a string Args: to_eval (str): The string to evaluate expect (t.Tuple[type]): The list of expected resulting types. Defaults to list, ndarray. timeout (int): The timeout after which the call fails in seconds. Defaults to 10. The `safe_eval` function allows using a subset of commands, listed in `_globals` and `_locals`, which includes a few numpy functions: linspace, arange, array, rand, and randint. Examples: >>> safe_eval("linspace(1, 10, 10, dtype=int).tolist()") [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> safe_eval("__import__('os').getcwd()") NameError Traceback (most recent call last) ... NameError: name '__import__' is not defined >>> safe_eval("range(5)") TypeError Traceback (most recent call last) ... TypeError: eval produced a <class 'range'>, expected: (<class 'list'>, <class 'numpy.ndarray'>) >>> safe_eval("list(round(rand(), 2) for _ in range(5))") [0.96, 0.41, 0.9, 0.98, 0.02] """ assert isinstance(to_eval, str), "'to_eval' must be a str" assert isinstance(expect, tuple), "'expect' must be a tuple" assert all(isinstance(_, type) for _ in expect), "'expect' must contain only types" _locals = {} _globals = { "__builtins__": {}, "list": list, "range": range, "len": len, "int": int, "float": float, "min": min, "max": max, "round": round, "linspace": np.linspace, "geomspace": np.geomspace, "logspace": np.logspace, "hstack": np.hstack, "vstack": np.vstack, "split": np.split, "arange": np.arange, "array": np.array, "rand": np.random.rand, "randint": np.random.randint, } signal.signal(signal.SIGALRM, signal_handler) signal.alarm(timeout) try: _ = eval(to_eval, _globals, _locals) except AlarmException: raise TimeoutError(f"safe_eval took longer than {timeout} seconds") else: signal.signal(signal.SIGALRM, signal.SIG_IGN) signal.alarm(0) if not isinstance(_, expect): raise EvalTypeError(f"eval produced a {type(_)}, expected: {expect}") return _ def sanitise_ansi(value: t.Union[t.List[str], str]) -> t.Union[t.List[str], str]: """Remove all ANSI escape characters from a str or a list of str Args: value (t.Union[t.List[str], str]): The string or list of strings Returns: t.Union[t.List[str], str]: The sanitised string or a list of sanitised strings """ _ansi_escape = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]") if isinstance(value, str): return _ansi_escape.sub("", value) elif isinstance(value, t.List): return list(map(lambda x: _ansi_escape.sub("", x).strip(), value)) else: raise TypeError("sanitise_ansi accepts only str or lists of str") def setgetattr(klass: t.Union[type, object], attr: str, default: t.Any) -> None: """Combines `setattr` and `getattr` to set attributes Args: klass (t.Union[type, object]): The type or object attr (str): The attribute default (t.Any): The default value """ if not any([isinstance(klass, type), isinstance(klass, object)]): raise TypeError("'klass' should be a type or an object", klass) if not isinstance(attr, str): raise TypeError("'attr' should be a str") if not attr: raise ValueError("'attr' should not be empty") setattr(klass, attr, getattr(klass, attr, default)) def setitem(obj: t.MutableMapping, query: t.Tuple, value: t.Any, force: bool = False) -> None: """Set a value in a dict-like object using a tuple-path query Args: obj (t.MutableMapping): a mutable mapping query (t.Tuple): a query path as a tuple value (t.Any): value to set Raises: TypeError: if obj is not a mutable mapping """ if not isinstance(obj, t.MutableMapping): raise TypeError("'obj' needs to be a mutable mapping", type(obj)) _obj = obj _valid = get_valid_access_paths(obj) if query not in _valid: if not force: raise KeyError(f"query-path {query!r} not found") else: for node in query[:-1]: if node not in _obj: _obj = dict() _obj = _obj[node] else: for node in query[:-1]: _obj = _obj[node] _obj[query[-1]] = value def stub_recursively( obj: t.T, stub: t.Any = None, _stub_list_elements: bool = True ) -> t.Optional[t.T]: """Produce a copy with all leaf values recursively set to a 'stub' value Args: obj (t.T): the object to stub stub (t.Any, optional): the value to set the leaf elements to _stub_list_elements (bool, optional): stub individual elements in collections? Returns: (t.T, optional): the stubbed object """ return inner(obj) def unpack__all__(*imports: t.Collection[str]) -> t.Tuple[str]: """Upacks a list of lists/tuples into a 1-dimensional list Args: *imports (t.Collection[str]): The collections of strings in "__all__" Returns: t.Tuple[str]: The flattened imports as a tuple of strings. """ from itertools import chain _name = f"{__name__}.unpack__all__" if not all(isinstance(e, (t.List, t.Tuple)) for e in imports): raise TypeError(f"{_name}: arguments should be lists or tuples") _ = chain(*imports) assert all( issubclass(type(e), str) for e in _ ), f"{_name}: values in unpacked containers were not scalar or 'str'" return tuple(_) def validate_helper(what: t.Mapping, key: t.Any, *types: type, msg: str = "") -> t.NoReturn: """Validate types of key in a mapping using key-paths Args: what (t.Mapping): The mapping key (t.Any): The key *types (type): The valid types msg (str): An additional error message. Defaults to "". """ if not isinstance(what, t.Mapping): raise TypeError(f"validate_helper works only on mappings, got {type(what)}") if not types: raise TypeError(f"validate helper expects at least 1 'types' argument") if isinstance(key, str) or not isinstance(key, t.Iterable): key = tuple([key]) elif not isinstance(key, tuple): key = tuple(key) # The `config` property setter guarantees that `config` is a fully # mutated AttributeDict, therefore :meth:`getattr` can be used. if not isinstance(getitem(what, key, None), types): raise MisconfiguredError( "{0}config key: '{1!s}' should be of type {2!r}, got {3!s}".format( f"{msg} " if msg else "", key, types, type(getitem(what, key, None)) ) )
[ 2, 15069, 357, 66, 8, 1853, 12, 42334, 11, 14780, 5618, 5136, 286, 8987, 357, 20702, 43412, 8, 198, 2, 1439, 2489, 10395, 13, 198, 2, 220, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 198, ...
2.422687
11,751
if __name__ == "__main__": maxProfitWithKTransactions([5, 11, 3, 50, 60, 90], 2)
[ 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 3509, 2964, 11147, 3152, 42, 8291, 4658, 26933, 20, 11, 1367, 11, 513, 11, 2026, 11, 3126, 11, 4101, 4357, 362, 8, 628, 628 ]
2.282051
39
import pandas as pd import numpy as np import io import time import uuid from flask import Flask, render_template, request, redirect, url_for, Response, session, send_file, make_response, send_from_directory from os.path import join, dirname, realpath from werkzeug.wsgi import FileWrapper app = Flask(__name__) app.config["DEBUG"] = True app.config["UPLOAD_FOLDER"] = 'media/dataset' app.config["EXPORT_FOLDER_CSV"] = 'media/result' app.config["SECRET_KEY"] = 'DBA2823#*@$&bdaiuwgdbi8238XBxjzhx@$@' app.config['SESSION_TYPE'] = 'filesystem' def cleanExcel(file_path, start_id): xls = pd.read_excel(file_path) xls.replace(to_replace=[r"\\t|\\n|\\r", "\t|\n|\r"], value=["",""], regex=True) print("Jumlah awal: {}".format(xls.shape)) xls.rename(columns = { 'NIK':'nik', 'NAMA':'nama', 'JENIS_KELAMIN':'jkel', 'TANGGAL_LAHIR':'tgl_lahir', 'NO_HP':'telp', 'INSTANSI_PEKERJAAN':'instansi', 'ALAMAT KTP': 'alamat', 'ALAMAT_KTP': 'alamat', 'KODE_KAB_KOTA_TEMPAT_KERJA': 'kab_id', 'KODE_KATEGORI': 'kategori' }, inplace = True) xls['nik'] = xls['nik'].astype(str) xls.insert(0, 'id', range(int(start_id), int(start_id) + len(xls))) xls.insert(2, 'nama_ktp', xls['nama']) xls.insert(6, 'status', 0) # del xls['NO'] del xls['UMUR'] del xls['JENIS_PEKERJAAN'] xls.drop(xls[xls['tgl_lahir'].isnull()].index, inplace = True) xls.drop(xls[xls['nik'].isnull()].index, inplace = True) xls.drop(xls[xls['nik'].str.len() > 16].index, inplace = True) xls.drop(xls[xls['nik'].str.len() < 16].index, inplace = True) xls.drop(xls[xls.duplicated(['nik'])].index, inplace = True) if xls['tgl_lahir'].dtypes == 'object': xls['tgl_lahir'] = pd.to_datetime(xls['tgl_lahir']) if xls['telp'].dtypes == 'float64': xls['telp'] = xls['telp'].astype(str) xls['telp'] = xls['telp'].str.split('.').str[0] xls['telp'] = xls['telp'].replace('nan',np.NaN) xls['telp'] = '0' + xls['telp'] if xls['telp'].dtypes == 'object': xls['telp'] = xls['telp'].str.split('/').str[0] xls['telp'] = xls['telp'].str.replace('\+62','0') xls['telp'] = xls['telp'].str.replace(' ','') xls['telp'] = xls['telp'].str.replace('-','') if xls['kab_id'].dtypes == 'float64': xls['kab_id'] = xls['kab_id'].astype(str) xls['kab_id'] = xls['kab_id'].str.split('.').str[0] xls['kab_id'] = xls['kab_id'].replace('nan',np.NaN) if xls['kategori'].dtypes == 'int64': xls['kategori'] = xls['kategori'].astype(str) xls['kategori'] = xls['kategori'].apply(lambda x: '0' + x if len(x) == 1 else x) xls['alamat'] = xls['alamat'].replace(';','') print("Jumlah akhir: {}".format(xls.shape)) uid = str(uuid.uuid4())[:4] path_file = 'media/result/' outfile_name = '{0}{1}'.format(time.strftime("%Y%m%d-%H%M%S-"),uid) session['csv_name'] = f'{outfile_name}' xls.to_csv(f'{path_file}{outfile_name}.csv', index=False, header=True, encoding="utf-8") if __name__ == '__main__': app.run(debug=True)
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33245, 198, 11748, 640, 198, 11748, 334, 27112, 198, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 11, 18941, 11, 19016, 62, 1640, 11, 18...
1.984326
1,595
# 11. Replace tabs into spaces # Replace every occurrence of a tab character into a space. Confirm the result by using sed, tr, or expand command. with open('popular-names.txt') as f: for line in f: print(line.strip().replace("\t", " "))
[ 2, 1367, 13, 40177, 22524, 656, 9029, 201, 198, 2, 40177, 790, 19810, 286, 257, 7400, 2095, 656, 257, 2272, 13, 7326, 2533, 262, 1255, 416, 1262, 10081, 11, 491, 11, 393, 4292, 3141, 13, 201, 198, 201, 198, 4480, 1280, 10786, 47568,...
2.988372
86
#!/usr/bin/env python # # wapo_link_graph_from_mongo.py # Jos Devezas <joseluisdevezas@gmail.com> # 2019-02-05 import logging import sys import warnings import networkx as nx from bs4 import BeautifulSoup from pymongo import MongoClient logging.basicConfig( format='%(asctime)s wapo_link_graph_from_mongo: %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) warnings.filterwarnings("ignore", category=UserWarning, module='bs4') if len(sys.argv) < 3: print("Usage: %s MONGO_DBNAME OUTPUT_GRAPH_PATH" % sys.argv[0]) sys.exit(1) database = sys.argv[1] output_graph_path = sys.argv[2] mongo = MongoClient() db = mongo[database] logging.info("Extracting anchors from content elements (using article_url as node ID) and building graph") g = nx.DiGraph() doc_count = 0 edge_count = 0 attr_keys = ['id', 'title', 'article_url', 'published_date', 'author', 'type'] for source in document_iterator(): if not 'contents' in source or source.get('contents') is None: continue for par in source['contents']: if par is None: continue html = par.get('content') if html is None: continue html = str(html) soup = BeautifulSoup(html, 'lxml') anchors = soup.find_all('a') for a in anchors: target_url = a.attrs.get('href') if target_url is None: continue query = {'article_url': target_url} attr_selector = { '_id': -1, 'id': 1, 'article_url': 1, 'title': 1, 'published_date': 1, 'author': 1, 'type': 1} target = db.articles.find_one(query, attr_selector) \ or db.blog_posts.find_one(query, attr_selector) if target is None: continue # graph[source_url].add(target_url) g.add_node( source['id'], **{k.replace('_', ''): source[k] for k in attr_keys if not source[k] is None}) g.add_node( target['id'], **{k.replace('_', ''): target[k] for k in attr_keys if not target[k] is None}) g.add_edge(source['id'], target['id']) edge_count += 1 doc_count += 1 if doc_count % 1000 == 0: logging.info("%d documents processed (%d edges created)" % (doc_count, edge_count)) logging.info("%d documents processed (%d edges created)" % (doc_count, edge_count)) logging.info("Saving graph to %s" % output_graph_path) if output_graph_path.endswith('.gml') or output_graph_path.endswith('.gml.gz'): nx.write_gml(g, output_graph_path) else: nx.write_graphml(g, output_graph_path)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 266, 41817, 62, 8726, 62, 34960, 62, 6738, 62, 76, 25162, 13, 9078, 198, 2, 22568, 1024, 33425, 292, 1279, 73, 577, 2290, 271, 2934, 33425, 292, 31, 14816, 13, 785, 29, ...
2.211047
1,213
# ------------------------------------------------------------------ # # vernierMask.py # ------------------------------------------------------------------ # # # A mask design used to align the 3D printer to a silicon photonic chip # # ------------------------------------------------------------------ # # VERSION HISTORY # 10 Apr 2018 - AMH - Initialization # # ------------------------------------------------------------------ # # ------------------------------------------------------------------ # # Import libraries # ------------------------------------------------------------------ # # Get project library path to import library files import sys import os d = os.path.dirname(os.getcwd()) libPath = os.path.abspath(os.path.join(d, 'lib')) sys.path.insert(0, libPath) # Import all other libraries import gdspy import numpy as np import objectLibrary as obLib # ------------------------------------------------------------------ # # Design Constants # ------------------------------------------------------------------ # # Cell parameters layerNumber = 1 # Vernier mask design parameters (all values in microns) numFingers = 10 # Number of fingers to have on top and bottom fingerWidth = 30 # Width of each finger fingerSpacing = 40 # Spacing between fingers longFingerLength = 200; # Length of the long, middle finger shortFingerLength = 150; # Length of the short, outer fingers baseThickness = 76; # Thickness of edge border of design separationDistance = 380 # distance from edge of pattern to origin buffer = 50 # Kerf width of blade innerBoxWidth = 8.78e3 # Actual dimensions of chip outerBoxWidth = innerBoxWidth + buffer # Buffered chip size numCells = 12 # number of repeated cells in each dimension # Now create a series of functions that return a cell. We'll leverage the recursive # nature of GDS files to keep things simple. # ------------------------------------------------------------------ # # Create single Vernier pattern # ------------------------------------------------------------------ # # ------------------------------------------------------------------ # # Create 2D Vernier pattern from single pattern # ------------------------------------------------------------------ # # ------------------------------------------------------------------ # # Create Box outline # ------------------------------------------------------------------ # # ------------------------------------------------------------------ # # Create Single Chip # ------------------------------------------------------------------ # # ------------------------------------------------------------------ # # Tapeout entire wafer # ------------------------------------------------------------------ # # ------------------------------------------------------------------ # # OUTPUT # ------------------------------------------------------------------ # vernierMask() # Output the layout to a GDSII file (default to all created cells). # Set the units we used to micrometers and the precision to nanometers. filename = 'vernierMask.gds' outPath = os.path.abspath(os.path.join(d, 'GDS/'+filename)) gdspy.write_gds(outPath, unit=1.0e-6, precision=1.0e-9)
[ 2, 16529, 438, 1303, 198, 2, 220, 933, 959, 45195, 13, 9078, 198, 2, 16529, 438, 1303, 198, 2, 198, 2, 317, 9335, 1486, 973, 284, 10548, 262, 513, 35, 20632, 284, 257, 29867, 2825, 9229, 11594, 198, 2, 198, 2, 16529, 438, 1303, ...
4.226869
789
from django.contrib.auth import get_user_model from rest_auth.registration.serializers import ( RegisterSerializer as BaseRegisterSerializer, ) from rest_auth.registration.serializers import ( SocialLoginSerializer as BaseSocialLoginSerializer, ) from rest_auth.serializers import LoginSerializer as BaseLoginSerializer from rest_auth.serializers import ( PasswordResetConfirmSerializer as BasePasswordResetConfirmSerializer, ) from rest_auth.serializers import UserDetailsSerializer as BaseUserDetailsSerializer from rest_framework import serializers from rest_framework.exceptions import ValidationError from core.models import Profile # noinspection PyAbstractClass # noinspection PyAbstractClass # noinspection PyAbstractClass # noinspection PyAbstractClass UserModel = get_user_model()
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 1334, 62, 18439, 13, 2301, 33397, 13, 46911, 11341, 1330, 357, 198, 220, 220, 220, 17296, 32634, 7509, 355, 7308, 38804, 32634, 7509, 11, 198, 8,...
3.747706
218
""" Copyright (c) 2016-2019 Keith Sterling http://www.keithsterling.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from programy.brain import Brain from programy.utils.classes.loader import ClassLoader from abc import abstractmethod, ABCMeta
[ 37811, 198, 15269, 357, 66, 8, 1584, 12, 23344, 14926, 23647, 2638, 1378, 2503, 13, 365, 342, 1706, 1359, 13, 785, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 3788, 29...
3.996753
308
import os import shutil import sys import tarfile if __name__ == "__main__": main()
[ 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 25064, 198, 11748, 13422, 7753, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.787879
33
# Copyright (c) 2020 ifly6 import html import io import re from datetime import datetime from functools import cache from typing import Tuple import numpy as np import pandas as pd import requests from bs4 import BeautifulSoup from lxml import etree from pytz import timezone from ratelimit import limits, sleep_and_retry from helpers import ref from src import wa_cacher """ Imperium Anglorum: This is adapted from proprietary InfoEurope code which in part does most of this already. Eg the proposal portions which translate, the locality adjustments, API reading, etc. There is also code in beta (not-in-production) which would have done this entirely, but I never got around to developing the VIEWS for that portion of the website. It seems much easier just to commit something like this given that all the code is already present. See ifly6.no-ip.org for more information. """ _headers = { 'User-Agent': 'WA parser (Auralia; Imperium Anglorum)' } def clean_chamber_input(chamber): """ Turns ambiguous chamber information into tuple (int, str) with chamber id and chamber name """ if type(chamber) == str: if chamber == '1': chamber = 1 elif chamber == '2': chamber = 2 elif chamber == 'GA': chamber = 1 elif chamber == 'SC': chamber = 2 chamber_name = 'GA' if chamber == 1 else \ 'SC' if chamber == 2 else '' return chamber, chamber_name def localised(dt: 'datetime', tz='US/Eastern'): return timezone(tz).localize(dt)
[ 2, 15069, 357, 66, 8, 12131, 611, 306, 21, 198, 11748, 27711, 198, 11748, 33245, 198, 11748, 302, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 1257, 310, 10141, 1330, 12940, 198, 6738, 19720, 1330, 309, 29291, 198, 198, 11748, ...
3.064961
508
import os from collections import OrderedDict, defaultdict from conans.model.ref import PackageReference from conans.util.files import save class Headers(object): _preferred_ordering = ['os', 'arch', 'compiler', 'build_type'] def row(self, n_rows=2): """ Retrieve list of headers as a single list (1-row) or as a list of tuples with settings organized by categories (2-row). Example output: 1-row: ['os', 'arch', 'compiler', 'compiler.version', 'compiler.libcxx', 'build_type'] 2-row: [('os', ['']), ('arch', ['']), ('compiler', ['', 'version', 'libcxx']),] """ headers = list(self.keys) if n_rows == 1: headers.extend(self.settings + self.options) if self.requires: headers.append('requires') return headers elif n_rows == 2: headers = [(it, ['']) for it in headers] settings = self._group_settings(self.settings) headers.extend(settings) headers.append(('options', self.options)) if self.requires: headers.append(('requires', [''])) return headers else: raise NotImplementedError("not yet")
[ 11748, 28686, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 11, 4277, 11600, 198, 198, 6738, 369, 504, 13, 19849, 13, 5420, 1330, 15717, 26687, 198, 6738, 369, 504, 13, 22602, 13, 16624, 1330, 3613, 628, 198, 198, 4871, 7123, 364, 7, ...
2.252688
558
from covid import Covid import json covid = Covid(source="worldometers") covid.get_data() iran_casses = covid.get_status_by_country_name("iran") confirmed = iran_casses['confirmed'] new_cases = iran_casses['new_cases'] deaths = iran_casses['deaths'] recovered = iran_casses['recovered'] active = iran_casses['active'] critical = iran_casses['critical'] new_deaths = iran_casses ['new_deaths'] total_tests = iran_casses['total_tests'] total_tests_per_million = int(iran_casses['total_tests_per_million']) total_cases_per_million = int(iran_casses['total_cases_per_million']) total_deaths_per_million = int(iran_casses['total_deaths_per_million']) population = int(iran_casses['population']) pr = json.dumps({ 'confirmed': confirmed, 'new_cases': new_cases, 'deaths': deaths, 'recovered': recovered, 'active': active, 'critical': critical, 'new_deaths': new_deaths, 'total_tests': total_tests, 'total_tests_per_million': total_tests_per_million, 'total_cases_per_million': total_cases_per_million, 'total_deaths_per_million': total_deaths_per_million, 'population': population }) print(pr)
[ 6738, 39849, 312, 1330, 39751, 312, 198, 11748, 33918, 198, 198, 66, 709, 312, 796, 39751, 312, 7, 10459, 2625, 6894, 40077, 4943, 198, 66, 709, 312, 13, 1136, 62, 7890, 3419, 198, 198, 343, 272, 62, 66, 13978, 796, 39849, 312, 13, ...
2.62069
435
# models/__init__.py from clcrypto import password_hash from psycopg2 import connect def delete(self, cursor): sql = "DELETE FROM Users WHERE id=%s" cursor.execute(sql, (self.__id,)) self.__id = -1 return True
[ 2, 4981, 14, 834, 15003, 834, 13, 9078, 198, 6738, 537, 29609, 78, 1330, 9206, 62, 17831, 198, 6738, 17331, 22163, 70, 17, 1330, 2018, 628, 628, 198, 220, 220, 220, 825, 12233, 7, 944, 11, 23493, 2599, 198, 220, 220, 220, 220, 220...
2.336449
107
from __future__ import division # LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1 # LIBTBX_PRE_DISPATCHER_INCLUDE_SH export BOOST_ADAPTBX_FPE_DEFAULT=1 import cStringIO from crys3d.wx_selection_editor import selection_editor_mixin import wx import libtbx.load_env import sys, os, time ######################################################################## # CLASSES AND METHODS FOR STANDALONE VIEWER # if __name__ == "__main__" : if "--test" in sys.argv : pdb_file = libtbx.env.find_in_repositories( relative_path="phenix_regression/pdb/1ywf.pdb", test=os.path.isfile) run([pdb_file, "--ss"]) else : run(sys.argv[1:])
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 2, 45651, 22737, 55, 62, 46437, 62, 26288, 47, 11417, 1137, 62, 1268, 5097, 52, 7206, 62, 9693, 10784, 9370, 1677, 10426, 62, 40156, 62, 1677, 53, 4663, 1340, 10979, 28, 16, 198, 2, 45651, 2...
2.474074
270
__revision__ = "$Id$" from io import BytesIO
[ 834, 260, 10178, 834, 796, 17971, 7390, 3, 1, 628, 628, 628, 198, 198, 6738, 33245, 1330, 2750, 4879, 9399, 198 ]
2.47619
21
from typing import Dict import numpy as np import tensorflow as tf import verres as V def factory(spec: dict) -> tf.optimizers.schedules.LearningRateSchedule: name = spec.pop("name", "default") if name.lower() in {"default", "constant"}: scheduler = ConstantSchedule(float(spec["learning_rate"])) else: scheduler_type = getattr(tf.optimizers.schedules, name, None) if scheduler_type is None: raise KeyError(f"No such scheduler: {name}") scheduler = scheduler_type(**spec) print(f" [Verres.schedule] - Factory built: {name}") return scheduler
[ 6738, 19720, 1330, 360, 713, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 11748, 3326, 411, 355, 569, 628, 628, 198, 4299, 8860, 7, 16684, 25, 8633, 8, 4613, 48700, 13, 40085, 11341, 13...
2.605932
236
import re import sys from itertools import izip as zip import argparse import requests # argparse definitions parser = argparse.ArgumentParser(description='Jira attack script') parser.add_argument('URL', type=str , help='the URL of the Jira instance... ex. https://jira.organization.com/') parser.add_argument('-u' ,'--usernames', dest='names', action='store_const', const=True, help='Print discovered usernames') parser.add_argument('-e' , '--emails', dest='emails',action='store_const', const=True, help='Print discovered email addresses') parser.add_argument('-a' ,'--all', dest='all',action='store_const',const=True,help='Print discovered email addresses and usernames') parser.add_argument('-eu' , dest='all',action='store_const',const=True,help=argparse.SUPPRESS) parser.add_argument('-ue' , dest='all',action='store_const',const=True,help=argparse.SUPPRESS) args = parser.parse_args() url = args.URL if args.URL[-1] != '/': args.URL = args.URL + "/" # Define URLs pickerURL = args.URL + "secure/popups/UserPickerBrowser.jspa?max=9999" filtersURL = args.URL + "secure/ManageFilters.jspa?filter=popular" #dashboardURL = args.URL + "secure/Dashboard.jspa" def extractPicker(response): ''' Takes in the response body for UserBrowserPicker and returns a dictionary containing usernames and email addresses. ''' userList = re.compile(r"-name\">(.*)</td>").findall(response.text) emailList = re.compile(r">(.*\@.*)</td>").findall(response.text) dictionary = dict(zip(userList , emailList)) return dictionary def extractFilters(response): ''' Takes in the response body for the manage filters page and returns a list containing usernames. ''' userList = re.compile(r"</span>.\((.*)\)").findall(response.text) return list(set(userList)) def validateURL(url): ''' Runs a stream of validation on a given URL and returns the response and a boolean value. ''' try: s = requests.Session() validateresponse = s.get(url , allow_redirects=False,timeout=5) except requests.exceptions.InvalidSchema: print "" print "[-] Invalid schema provided... Must follow format https://jira.organization.com/" print "" sys.exit(1) except requests.exceptions.MissingSchema: print "" print "[-] A supported schema was not provided. Please use http:// or https://" print "" sys.exit(1) except requests.exceptions.InvalidURL: print "[-] Invalid base URL was supplied... Please try again." sys.exit(1) except requests.exceptions.ConnectionError: print "" print "[-] Connection failed... Please check the URL and try again." print "" sys.exit(1) except requests.exceptions.RequestException: print "" print "[-] An unknown exception occurred... Please try again." print "" sys.exit(1) if validateresponse.status_code == 200: return validateresponse,True else: return "[-] The page is inaccessible",False if __name__ == "__main__": pickerResponse,pickerAccessible = validateURL(pickerURL) filterResponse,filterAccessible = validateURL(filtersURL) print "" print "" print "[+] Checking the User Picker page..." if pickerAccessible == True: users = extractPicker(pickerResponse) print "" print "[+] Success..." print "[+] Users: "+str(len(users)) print "[+] Emails: " + str(len(users)) print "" if (args.emails and args.names) or args.all: print '{:<20}{:<20}'.format("---Username---", "---------Email---------") for username, email in sorted(users.iteritems()): print '{:<20}{:<20}'.format(username,email) elif args.emails: for username,email in sorted(users.iteritems()): print email elif args.names: for username,email in sorted(users.iteritems()): print username print "" elif pickerAccessible == False: print pickerResponse print "" print "" print "[+] Checking the Manage Filters page..." if filterAccessible == True: filterUsers = extractFilters(filterResponse) if args.names or args.all: if len(filterUsers) == 0: print "[-] We could not find any anonymously accessible filters" print "" else: print "[+] The Manage Filters page is accessible and contains data..." print "" for username in filterUsers: print username print "" elif filterAccessible == False: print filterResponse
[ 11748, 302, 201, 198, 11748, 25064, 201, 198, 6738, 340, 861, 10141, 1330, 220, 528, 541, 355, 19974, 201, 198, 11748, 1822, 29572, 201, 198, 11748, 7007, 201, 198, 201, 198, 2, 1822, 29572, 17336, 201, 198, 48610, 796, 1822, 29572, 1...
2.479613
1,962
import json import string from datetime import datetime import deap import numpy as np import hmm from discriminator import Discriminator from ea import EA import random_search DEFAULT_PARAMS = { # Discriminator CNN model "model": "CNNModel3", # Algorithm Parameters "states": 5, "symbols": 5, "epochs": 10, "epoch_size": 500, "batch_size": 200, "seq_len": 20, "pop_size": 25, "gens": 50, "offspring_prop": 1.0, "cx_prob": 0.0, "mut_fn": "uniform", "mut_prob": 1.0, "mut_rate": None, # None - default to 1/N where N is number of genes # Implementation Parameters "_pool_size": 4, "_random_search": True, # Also run an elitist random search over #gens to compare performance } if __name__ == "__main__": main()
[ 11748, 33918, 198, 11748, 4731, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 390, 499, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 289, 3020, 198, 6738, 6534, 20900, 1330, 8444, 3036, 20900, 198, 6738, 304, 64, 133...
2.479876
323
#!/usr/bin/env python3 ''' This code traverses a directories of evaluation log files and record evaluation scores as well as plotting the results. ''' import os import argparse import json import copy from shutil import copyfile import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from utils import * MAX_ALIGN_STEPS = 75000 - 1 # This depends on the evaluation code used to generate the logs def generate_csv(log_dir, csv_file): ''' Traverse and read log files, and then output csv file from the eval data. - file to be generated: 'eval_scores.csv' - columns: state_machine_id, timesteps, rot_error ''' df = pd.DataFrame(columns=['state_machine_id', 'state_machine_name', 'timesteps', 'rot_error']) model_names = extract_model_names(log_dir) # Traverse all episodes and add each entry to data frame for state_machine_id, episode_idx, episode_dir in traverse_all_episodes(log_dir): json_util = JsonUtil(os.path.join(episode_dir, 'goal.json')) entry = { 'state_machine_id': state_machine_id, 'state_machine_name': model_names[state_machine_id], **json_util.load() } # Handling the timesteps==-1 case if entry['reachfinish'] == -1: entry['reachfinish'] = MAX_ALIGN_STEPS if entry['reachstart'] == -1: raise ValueError('\'reachstart\' in {episode_dir}/goal.json does not contain a valid value.') # Rename dict keys entry['timesteps'] = entry.pop('reachfinish') - entry.pop('reachstart') entry['rot_error'] = entry.pop('align_obj_error') entry['init_rot_error'] = entry.pop('init_align_obj_error', None) # Add a new entry entry['rot_error_diff'] = entry['init_rot_error'] - entry['rot_error'] df = df.append(entry, ignore_index=True) # df.append works differently from python since it is stupid df.to_csv(csv_file, index=False)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 7061, 6, 198, 1212, 2438, 33038, 274, 257, 29196, 286, 12660, 2604, 3696, 290, 198, 22105, 12660, 8198, 355, 880, 355, 29353, 262, 2482, 13, 198, 7061, 6, 198, 11748, 28686, 198, ...
2.6
755
#!/usr/bin/env python3 # NOTE: this file does not have the executable bit set. This tests that # Meson can automatically parse shebang lines. import sys template = '#define RET_VAL %s\n' output = template % (open(sys.argv[1]).readline().strip()) open(sys.argv[2], 'w').write(output)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 24550, 25, 428, 2393, 857, 407, 423, 262, 28883, 1643, 900, 13, 770, 5254, 326, 198, 2, 14937, 261, 460, 6338, 21136, 673, 36668, 3951, 13, 198, 198, 11748, 25064, 198, ...
3.010526
95
""" Test data""" stub_films = [{ "id": "12345", "title": "This is film one", },{ "id": "23456", "title": "This is film two", }] stub_poeple = [{ "name": "person 1", "films": ["url/12345", "url/23456"] },{ "name": "person 2", "films": ["url/23456"] },{ "name": "person 3", "films": ["url/12345"] },{ "name": "person 4", "films": ["url/12345"] }]
[ 37811, 6208, 1366, 37811, 198, 198, 301, 549, 62, 10379, 907, 796, 685, 90, 198, 220, 220, 220, 366, 312, 1298, 366, 10163, 2231, 1600, 198, 220, 220, 220, 366, 7839, 1298, 366, 1212, 318, 2646, 530, 1600, 198, 5512, 90, 198, 220, ...
2.005076
197
import sqlite3 from constants import DESTINATION_DB destination_connection = sqlite3.connect(DESTINATION_DB) destination_cursor = destination_connection.cursor() destination_cursor.execute('CREATE TABLE game(uuid, payload)')
[ 11748, 44161, 578, 18, 201, 198, 201, 198, 6738, 38491, 1330, 360, 6465, 1268, 6234, 62, 11012, 201, 198, 201, 198, 16520, 1883, 62, 38659, 796, 44161, 578, 18, 13, 8443, 7, 35, 6465, 1268, 6234, 62, 11012, 8, 201, 198, 16520, 1883,...
2.987342
79
# Copyright 2017 Google Inc. 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. """Tests for json_utils.""" import datetime import json from google.appengine.ext import ndb from common.testing import basetest from upvote.gae.datastore.models import santa from upvote.gae.shared.common import json_utils from upvote.shared import constants if __name__ == '__main__': basetest.main()
[ 2, 15069, 2177, 3012, 3457, 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, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.582677
254
from os import path from typing import Union from datetime import datetime from flask import Flask, request, redirect, render_template from flask_wtf import CSRFProtect from werkzeug.utils import secure_filename from data import db_session from data.posts import Posts from forms.edit_post_form import EditPostForm app = Flask(__name__) app.config['SECRET_KEY'] = 'SECRET_KEY' csrf_protect = CSRFProtect(app) UPLOAD_FOLDER = 'static/posts_img/' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER DATA_BASE = 'db/blog.sqlite' app.config['DATA_BASE'] = DATA_BASE def main(): db_session.global_init(app.config['DATA_BASE']) app.run('127.0.0.1', 8080) if __name__ == '__main__': main()
[ 6738, 28686, 1330, 3108, 198, 6738, 19720, 1330, 4479, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 18941, 11, 8543, 62, 28243, 198, 6738, 42903, 62, 86, 27110, 1330, 9429, 32754, 41426, 198...
2.711538
260
# ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems Inc. # 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. # ---------------------------------------------------------------------------- """ Neon backend wrapper for the NervanaGPU library. Most functions are thin wrappers around functions from the NervanaGPU class, the GPUTensor is taken directly from NervanaGPU as well. NervanaGPU is available at `<https://github.com/NervanaSystems/nervanagpu>` """ import logging from neon.backends.backend import Backend from nervanagpu import NervanaGPU from neon.diagnostics.timing_decorators import FlopsDecorator import pycuda.driver as drv import numpy as np logger = logging.getLogger(__name__)
[ 2, 16529, 10541, 198, 2, 15069, 1946, 399, 712, 2271, 11998, 3457, 13, 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, ...
3.949367
316
# -*- encoding: utf-8 -*- import os import pickle import sys import time import glob import unittest import unittest.mock import numpy as np import pandas as pd import sklearn.datasets from smac.scenario.scenario import Scenario from smac.facade.roar_facade import ROAR from autosklearn.util.backend import Backend from autosklearn.automl import AutoML import autosklearn.automl from autosklearn.data.xy_data_manager import XYDataManager from autosklearn.metrics import accuracy, log_loss, balanced_accuracy import autosklearn.pipeline.util as putil from autosklearn.util.logging_ import setup_logger, get_logger from autosklearn.constants import MULTICLASS_CLASSIFICATION, BINARY_CLASSIFICATION, REGRESSION from smac.tae.execute_ta_run import StatusType sys.path.append(os.path.dirname(__file__)) from base import Base # noqa (E402: module level import not at top of file) def test_fail_if_feat_type_on_pandas_input(self): """We do not support feat type when pandas is provided as an input """ backend_api = self._create_backend('test_fail_feat_pandas') automl = autosklearn.automl.AutoML( backend=backend_api, time_left_for_this_task=20, per_run_time_limit=5, metric=accuracy, ) X_train = pd.DataFrame({'a': [1, 1], 'c': [1, 2]}) y_train = [1, 0] with self.assertRaisesRegex(ValueError, "feat_type cannot be provided when using pandas"): automl.fit( X_train, y_train, task=BINARY_CLASSIFICATION, feat_type=['Categorical', 'Numerical'], ) self._tearDown(backend_api.temporary_directory) self._tearDown(backend_api.output_directory) def test_fail_if_dtype_changes_automl(self): """We do not support changes in the input type. Once a estimator is fitted, it should not change data type """ backend_api = self._create_backend('test_fail_feat_typechange') automl = autosklearn.automl.AutoML( backend=backend_api, time_left_for_this_task=20, per_run_time_limit=5, metric=accuracy, ) X_train = pd.DataFrame({'a': [1, 1], 'c': [1, 2]}) y_train = [1, 0] automl.InputValidator.validate(X_train, y_train, is_classification=True) with self.assertRaisesRegex(ValueError, "Auto-sklearn previously received features of type"): automl.fit( X_train.to_numpy(), y_train, task=BINARY_CLASSIFICATION, ) self._tearDown(backend_api.temporary_directory) self._tearDown(backend_api.output_directory) if __name__ == "__main__": unittest.main()
[ 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 15095, 198, 11748, 555, 715, 395, 198, 11748, 555, 715, 395, 13, 76, 735, 198, 198, ...
2.184841
1,293
""" This implements an abstrace base class Ring . Rationale: Goal is to separate the datatype specification from the algorithms and containers for the following reasons: 1) It allows to directly use the algorithms *without* overhead. E.g. calling mul(z.data, x.data, y.data) has much less overhead than z = x.__mul__(y). data is to be kept as close as possible to machine primitives. E.g. data is array or tuple of arrays. 2) Potential reuse of an algorithm in several datatypes. 3) Relatively easy to connect high performance algorithms with a very highlevel abstract description. For instance, most programming languages allow calling C-functions. Therefore, the algorithms should be given as void fcn(int A, double B, ...) For instance, the datatype is a truncated Taylor polynomial R[t]/<t^D> of the class Foo. The underlying container is a simple array of doubles. """ import numpy
[ 37811, 198, 1212, 23986, 281, 450, 2536, 558, 2779, 1398, 12569, 764, 198, 198, 49, 864, 68, 25, 198, 220, 220, 220, 220, 198, 220, 220, 220, 25376, 318, 284, 4553, 262, 4818, 265, 2981, 20855, 422, 262, 16113, 290, 16472, 329, 262,...
3.046012
326
""" Melhore o Desafio 061, perguntando para o usurio se ele quer mostrar mais alguns termos. O programa encerra quando ele disser que quer mostrar 0 termos. """ primeiro = int(input('Digite o termo: ')) razao = int(input('Digite a razo: ')) termo = primeiro cont = 1 total = 0 mais = 10 while mais != 0: total = total + mais while cont <= total: print('{} -> '.format(termo), end=' ') termo = termo + razao cont = cont + 1 print('Pausa') mais = int(input('Quantos termos voc quer mostrar a mais? ')) print('FIM')
[ 37811, 198, 21102, 71, 382, 267, 2935, 1878, 952, 657, 5333, 11, 583, 70, 2797, 25440, 31215, 267, 39954, 952, 384, 9766, 42517, 749, 20040, 285, 15152, 435, 44265, 3381, 418, 13, 198, 46, 1430, 64, 551, 2189, 430, 627, 25440, 9766, ...
2.446903
226
#################################### # author: Gonzalo Salazar # course: 2020 Complete Python Bootcamps: From Zero to Hero in Python # purpose: lecture notes # description: Section 15 - Web Scraping # other: N/A #################################### # RULES # 1. always try to get permission before scraping, otherwise I might be blocked # 2. check the laws of whatever country we are operating in (for legal issues) # LIMITATIONS # each website is unique -> so for each website there must exist a Python script # an update to a website might brake my script import requests import bs4 # Grabbing a title result = requests.get("http://example.com") type(result) result.text # bs with lxml tranforms the previous raw html into the following soup = bs4.BeautifulSoup(result.text,'lxml') soup # returns the tag we specified as a list (i.e., there might be more than one) soup.select('title') soup.select('title')[0].getText() soup.select('p') site_paragraphs = soup.select('p') type(site_paragraphs[0]) # not a string, instead is a specialized bs object, # which is why we can do something like call .getText() # Grabbing a class (from CSS) using soup.select() # 'div' : all elements with 'div' tag # '#some_id' : elements containing id='some_id' # '.some_class' : elements containing class='some_class' # 'div span' : any element named span within a div element # 'div > span' : any element named span directly within a div element, with # nothing in between res = requests.get("https://en.wikipedia.org/wiki/Jonas_Salk") soup = bs4.BeautifulSoup(res.text,'lxml') soup.select('.toctext')[0].text soup.select('.toctext')[0].getText() for item in soup.select('.toctext'): print(item.text) # Grabbing an image #soup.select('img') # can return more than what is needeed (it will depend on # the website) soup.select('.thumbimage') jonas_salk = soup.select('.thumbimage')[0] jonas_salk['src'] # we can treat it as a dictionary image_link = requests.get('http://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Roosevelt_OConnor.jpg/220px-Roosevelt_OConnor.jpg') #image_link.content # raw content of the image which is a binary file #make sure to use the same format that the image has f = open('my_image_image.jpg','wb') # wb means write binary f.write(image_link.content) f.close() # Multiple elements across multiple pages # GOAL: get title of every book with a 2 star rating #Check that this also work with page 1 #http://books.toscrape.com/catalogue/page-2.html base_url = 'http://books.toscrape.com/catalogue/page-{}.html' req = requests.get(base_url.format(1)) soup = bs4.BeautifulSoup(req.text,'lxml') products = soup.select(".product_pod") # always check the length, in this case should be 20 example = products[0] # one way (not useful everytime) 'star-rating Two' in str(example) # another way (checking for the presence of a class) example.select('.star-rating.Three') # if there is a space in a class we should add a dot example.select('.star-rating.Two') # nothing example.select('a')[1]['title'] two_star_titles = [] for n in range(1,51): scrape_url = base_url.format(n) req = requests.get(base_url.format(1)) soup = bs4.BeautifulSoup(req.text,'lxml') books = soup.select(".product_pod") for book in books: if len(book.select('.star-rating.Two')) != 0: two_star_titles.append(book.select('a')[1]['title']) two_star_titles
[ 29113, 4242, 198, 2, 1772, 25, 17109, 7335, 4849, 29413, 198, 2, 1781, 25, 12131, 13248, 11361, 18892, 66, 9430, 25, 3574, 12169, 284, 8757, 287, 11361, 198, 2, 4007, 25, 19143, 4710, 198, 2, 6764, 25, 7275, 1315, 532, 5313, 1446, 2...
2.869959
1,215
#!/usr/bin/env python3 import sys import os import re import json import traceback import pkg_resources import tarfile from collections import OrderedDict import anchore_engine.analyzers.utils, anchore_engine.utils analyzer_name = "package_list" try: config = anchore_engine.analyzers.utils.init_analyzer_cmdline(sys.argv, analyzer_name) except Exception as err: print(str(err)) sys.exit(1) imgname = config['imgid'] imgid = config['imgid_full'] outputdir = config['dirs']['outputdir'] unpackdir = config['dirs']['unpackdir'] squashtar = os.path.join(unpackdir, "squashed.tar") resultlist = {} version_found_map = {} binary_package_el = { 'name': None, 'version': None, 'location': None, 'type': 'binary', 'files': [], 'license': 'N/A', 'origin': 'N/A', 'metadata': json.dumps({}) } try: allfiles = {} if os.path.exists(unpackdir + "/anchore_allfiles.json"): with open(unpackdir + "/anchore_allfiles.json", 'r') as FH: allfiles = json.loads(FH.read()) else: fmap, allfiles = anchore_engine.analyzers.utils.get_files_from_squashtar(os.path.join(unpackdir, "squashed.tar")) with open(unpackdir + "/anchore_allfiles.json", 'w') as OFH: OFH.write(json.dumps(allfiles)) # read in previous analyzer output for helping to increase accuracy of findings fname = os.path.join(outputdir, 'pkgfiles.all') pkgfilesall = anchore_engine.analyzers.utils.read_kvfile_todict(fname) meta = anchore_engine.analyzers.utils.get_distro_from_squashtar(os.path.join(unpackdir, "squashed.tar"), unpackdir=unpackdir) distrodict = anchore_engine.analyzers.utils.get_distro_flavor(meta['DISTRO'], meta['DISTROVERS'], likedistro=meta['LIKEDISTRO']) # set up ordered dictionary structure for the runtimes and evidence types evidence = OrderedDict() for runtime in ['python', 'go', 'busybox']: evidence[runtime] = OrderedDict() for etype in ['binary', 'devel']: evidence[runtime][etype] = [] # Perform a per file routine to evaluate files for gathering binary package version evidence with tarfile.open(os.path.join(unpackdir, "squashed.tar"), mode='r', format=tarfile.PAX_FORMAT) as tfl: alltnames = tfl.getnames() alltfiles = {} for name in alltnames: alltfiles[name] = True memberhash = anchore_engine.analyzers.utils.get_memberhash(tfl) for member in list(memberhash.values()): try: get_python_evidence(tfl, member, memberhash, evidence) except Exception as err: print ("WARN: caught exception evaluating file ({}) for python runtime evidence: {}".format(member.name, str(err))) try: get_golang_evidence(tfl, member, memberhash, evidence) except Exception as err: print ("WARN: caught exception evaluating file ({}) for golang runtime evidence: {}".format(member.name, str(err))) try: get_busybox_evidence(tfl, member, memberhash, distrodict, evidence) except Exception as err: print ("WARN: caught exception evaluating file ({}) for busybox runtime evidence: {}".format(member.name, str(err))) resultlist = {} for runtime in evidence.keys(): #['python', 'go']: for e in evidence[runtime].keys(): #['binary', 'devel']: for t in evidence[runtime][e]: version = t.get('version') location = t.get('location') if location in pkgfilesall: print ("INFO: Skipping evidence {} - file is owned by OS package".format(location)) else: key = "{}-{}".format(runtime, version) if key not in version_found_map: result = {} result.update(binary_package_el) result.update(t) result['metadata'] = json.dumps({"evidence_type": e}) resultlist[location] = json.dumps(result) version_found_map[key] = True try: squashtar = os.path.join(unpackdir, "squashed.tar") hints = anchore_engine.analyzers.utils.get_hintsfile(unpackdir, squashtar) for pkg in hints.get('packages', []): pkg_type = pkg.get('type', "").lower() if pkg_type == 'binary': try: pkg_key, el = anchore_engine.analyzers.utils._hints_to_binary(pkg) try: resultlist[pkg_key] = json.dumps(el) except Exception as err: print ("WARN: unable to add binary package ({}) from hints - excpetion: {}".format(pkg_key, err)) except Exception as err: print ("WARN: bad hints record encountered - exception: {}".format(err)) except Exception as err: print ("WARN: problem honoring hints file - exception: {}".format(err)) except Exception as err: import traceback traceback.print_exc() print("WARN: analyzer unable to complete - exception: " + str(err)) if resultlist: ofile = os.path.join(outputdir, 'pkgs.binary') anchore_engine.analyzers.utils.write_kvfile_fromdict(ofile, resultlist) #print ("RESULT: {}".format(resultlist)) sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 33918, 198, 11748, 12854, 1891, 198, 11748, 279, 10025, 62, 37540, 198, 11748, 13422, 7753, 198, 6738, 17268, 1330, ...
2.22503
2,493
import pandas as pd import numpy as np import csv import urllib.request import json from datetime import datetime from datetime import timedelta from sklearn.preprocessing import MinMaxScaler import web_scrapers import os def wrangle_real_estate_headers(df): ''' run before joining dataframes so keys match df_sale_counts_by_zip_silicon_valley.columns = df_sale_counts_by_zip_silicon_valley.columns.str.replace('Sales Counts ', '') df_sale_counts_by_zip_silicon_valley = df_sale_counts_by_zip_silicon_valley.add_prefix('Sales Counts ') df_sale_counts_by_zip_silicon_valley.rename(columns = {'Sales Counts RegionName':'Zipcode'}, inplace=True) ''' df.columns = df.columns.str.replace('All Homes ', '') df = df.add_prefix('All Homes ') df.rename(columns={'All Homes RegionName': 'Zipcode'}, inplace=True) return df def create_zipcode_distances_dictionary(zipcodes, zip_list): ''' ***DONT RUN IF THESE ARE ALREADY CREATED*** currently stored as data/processed/zipcodes_within_radius.txt ''' print(len(zip_list)) for i in range(0, len(zip_list)): zipcodes[zip_list[i]] = calculate_distance_between_zips(zip_list[i], '0', '5'), calculate_distance_between_zips( zip_list[i], '5', '10') return zipcodes def create_text_file_from_dictionary(filename, dictionary): ''' with open('data/processed/zipcodes_within_radius.txt', 'w') as json_file: json.dump(zipcodes, json_file) ''' with open(filename, 'w') as json_file: json.dump(dictionary, json_file) return dictionary if __name__ == "__main__": print("we are wrangling data") #update_ipo_list(2019, 6, 7) main()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 21370, 198, 11748, 2956, 297, 571, 13, 25927, 198, 11748, 33918, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 4818, 8079, 1330, 28805, 12514, 1...
2.531664
679
from director.devel.plugin import GenericPlugin from director.fieldcontainer import FieldContainer from .lib import measurementpanel from PythonQt import QtCore
[ 6738, 3437, 13, 2934, 626, 13, 33803, 1330, 42044, 37233, 198, 6738, 3437, 13, 3245, 34924, 1330, 7663, 29869, 198, 198, 6738, 764, 8019, 1330, 15558, 35330, 198, 6738, 11361, 48, 83, 1330, 33734, 14055, 628 ]
4.527778
36
"""A small sphinx extension to let you configure a site with YAML metadata.""" from pathlib import Path # Transform a "Jupyter Book" YAML configuration file into a Sphinx configuration file. # This is so that we can choose more user-friendly words for things than Sphinx uses. # e.g., 'logo' instead of 'html_logo'. # Note that this should only be used for **top level** keys. PATH_YAML_DEFAULT = Path(__file__).parent.joinpath("default_config.yml") def yaml_to_sphinx(yaml): """Convert a Jupyter Book style config structure into a Sphinx config dict.""" sphinx_config = { "exclude_patterns": [ "_build", "Thumbs.db", ".DS_Store", "**.ipynb_checkpoints", ], } # Start with an empty options block theme_options = {} # Launch button configuration launch_buttons_config = yaml.get("launch_buttons", {}) repository_config = yaml.get("repository", {}) theme_options["launch_buttons"] = launch_buttons_config theme_options["path_to_docs"] = repository_config.get("path_to_book", "") theme_options["repository_url"] = repository_config.get("url", "") theme_options["repository_branch"] = repository_config.get("branch", "") # HTML html = yaml.get("html") if html: sphinx_config["html_favicon"] = html.get("favicon", "") sphinx_config["html_baseurl"] = html.get("baseurl", "") theme_options["google_analytics_id"] = html.get("google_analytics_id", "") # Deprecate navbar_footer_text after a release cycle theme_options["navbar_footer_text"] = html.get("navbar_footer_text", "") theme_options["extra_navbar"] = html.get("extra_navbar", "") theme_options["extra_footer"] = html.get("extra_footer", "") theme_options["home_page_in_toc"] = html.get("home_page_in_navbar") # Comments config sphinx_config["comments_config"] = html.get("comments", {}) # Pass through the buttons btns = ["use_repository_button", "use_edit_page_button", "use_issues_button"] use_buttons = {btn: html.get(btn) for btn in btns if html.get(btn) is not None} if any(use_buttons.values()): if not repository_config.get("url"): raise ValueError( "To use 'repository' buttons, you must specify the repository URL" ) # Update our config theme_options.update(use_buttons) # Update the theme options in the main config sphinx_config["html_theme_options"] = theme_options execute = yaml.get("execute") if execute: if execute.get("execute_notebooks") is False: # Special case because YAML treats `off` as "False". execute["execute_notebooks"] = "off" sphinx_config["jupyter_execute_notebooks"] = execute.get( "execute_notebooks", "auto" ) sphinx_config["execution_timeout"] = execute.get("timeout", 30) sphinx_config["jupyter_cache"] = execute.get("cache", "") _recursive_update( sphinx_config, {"execution_excludepatterns": execute.get("exclude_patterns", [])}, ) # LaTeX latex = yaml.get("latex") if latex: sphinx_config["latex_engine"] = latex.get("latex_engine", "pdflatex") # Extra extensions extra_extensions = yaml.get("sphinx", {}).get("extra_extensions") if extra_extensions: if not isinstance(extra_extensions, list): extra_extensions = [extra_extensions] extensions = sphinx_config.get("extensions", []) for extra in extra_extensions: extensions.append(extra) sphinx_config["extensions"] = extensions # Files that we wish to skip sphinx_config["exclude_patterns"].extend(yaml.get("exclude_patterns", [])) # Now do simple top-level translations YAML_TRANSLATIONS = { "logo": "html_logo", "title": "html_title", "execute_notebooks": "jupyter_execute_notebooks", "project": "project", "author": "author", "copyright": "copyright", } for key, newkey in YAML_TRANSLATIONS.items(): if key in yaml: val = yaml.get(key) if val is None: val = "" sphinx_config[newkey] = val return sphinx_config def _recursive_update(config, update): """Update the dict `config` with `update` recursively. This *updates* nested dicts / lists instead of replacing them. """ for key, val in update.items(): if isinstance(config.get(key), dict): config[key].update(val) elif isinstance(config.get(key), list): if isinstance(val, list): config[key].extend(val) else: config[key] = val else: config[key] = val
[ 37811, 32, 1402, 599, 20079, 87, 7552, 284, 1309, 345, 17425, 257, 2524, 351, 575, 2390, 43, 20150, 526, 15931, 198, 6738, 3108, 8019, 1330, 10644, 628, 198, 2, 26981, 257, 366, 41, 929, 88, 353, 4897, 1, 575, 2390, 43, 8398, 2393, ...
2.327743
2,087
__author__ = 'Tony Beltramelli - www.tonybeltramelli.com' # scripted agents taken from PySC2, credits to DeepMind # https://github.com/deepmind/pysc2/blob/master/pysc2/agents/scripted_agent.py import numpy as np import uuid from pysc2.agents import base_agent from pysc2.lib import actions from pysc2.lib import features _SCREEN_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index _SCREEN_SELECTED = features.SCREEN_FEATURES.selected.index _PLAYER_FRIENDLY = 1 _PLAYER_NEUTRAL = 3 _PLAYER_HOSTILE = 4 _NO_OP = actions.FUNCTIONS.no_op.id _MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id _ATTACK_SCREEN = actions.FUNCTIONS.Attack_screen.id _SELECT_ARMY = actions.FUNCTIONS.select_army.id _NOT_QUEUED = [0] _SELECT_ALL = [0]
[ 834, 9800, 834, 796, 705, 29387, 16734, 28073, 15516, 532, 7324, 13, 1122, 88, 37976, 28073, 15516, 13, 785, 6, 198, 2, 37341, 6554, 2077, 422, 9485, 6173, 17, 11, 10824, 284, 10766, 28478, 198, 2, 3740, 1378, 12567, 13, 785, 14, 22...
2.594406
286
import time import sys import dask from dask.distributed import ( wait, futures_of, Client, ) from tpch import loaddata, queries #from benchmarks import utils # Paths or URLs to the TPC-H tables. #table_paths = { # 'CUSTOMER': 'hdfs://bu-23-115:9000/tpch/customer.tbl', # 'LINEITEM': 'hdfs://bu-23-115:9000/tpch/lineitem.tbl', # 'NATION': 'hdfs://bu-23-115:9000/tpch/nation.tbl', # 'ORDERS': 'hdfs://bu-23-115:9000/tpch/orders.tbl', # 'PART': 'hdfs://bu-23-115:9000/tpch/part.tbl', # 'PARTSUPP': 'hdfs://bu-23-115:9000/tpch/partsupp.tbl', # 'REGION': 'hdfs://bu-23-115:9000/tpch/region.tbl', # 'SUPPLIER': 'hdfs://bu-23-115:9000/tpch/supplier.tbl', #} table_paths = { 'CUSTOMER': '/root/2g/customer.tbl', 'LINEITEM': '/root/2g/lineitem.tbl', 'NATION': '/root/2g/nation.tbl', 'ORDERS': '/root/2g/orders.tbl', 'PART': '/root/2g/part.tbl', 'PARTSUPP': '/root/2g/partsupp.tbl', 'REGION': '/root/2g/region.tbl', 'SUPPLIER': '/root/2g/supplier.tbl', } #table_paths = { # 'CUSTOMER': 'https://gochaudhstorage001.blob.core.windows.net/tpch/customer.tbl', # 'LINEITEM': 'https://gochaudhstorage001.blob.core.windows.net/tpch/lineitem.tbl', # 'NATION': 'https://gochaudhstorage001.blob.core.windows.net/tpch/nation.tbl', # 'ORDERS': 'https://gochaudhstorage001.blob.core.windows.net/tpch/orders.tbl', # 'PART': 'https://gochaudhstorage001.blob.core.windows.net/tpch/part.tbl', # 'PARTSUPP': 'https://gochaudhstorage001.blob.core.windows.net/tpch/partsupp.tbl', # 'REGION': 'https://gochaudhstorage001.blob.core.windows.net/tpch/region.tbl', # 'SUPPLIER': 'https://gochaudhstorage001.blob.core.windows.net/tpch/supplier.tbl', #} if __name__ == '__main__': main()
[ 11748, 640, 198, 11748, 25064, 198, 11748, 288, 2093, 198, 198, 6738, 288, 2093, 13, 17080, 6169, 1330, 357, 198, 220, 220, 220, 4043, 11, 198, 220, 220, 220, 25650, 62, 1659, 11, 198, 220, 220, 220, 20985, 11, 198, 8, 198, 198, 6...
2.080283
847
"""Use pika with the Tornado IOLoop """ import logging from tornado import ioloop from pika.adapters.utils import nbio_interface, selector_ioloop_adapter from pika.adapters import base_connection LOGGER = logging.getLogger(__name__)
[ 37811, 11041, 279, 9232, 351, 262, 48970, 314, 3535, 11224, 198, 198, 37811, 198, 11748, 18931, 198, 198, 6738, 33718, 1330, 1312, 349, 11224, 198, 198, 6738, 279, 9232, 13, 324, 12126, 13, 26791, 1330, 299, 65, 952, 62, 39994, 11, 31...
3.186667
75
from mock.mock import patch import os import pytest import ca_test_common import ceph_volume_simple_activate fake_cluster = 'ceph' fake_container_binary = 'podman' fake_container_image = 'quay.ceph.io/ceph/daemon:latest' fake_id = '42' fake_uuid = '0c4a7eca-0c2a-4c12-beff-08a80f064c52' fake_path = '/etc/ceph/osd/{}-{}.json'.format(fake_id, fake_uuid)
[ 6738, 15290, 13, 76, 735, 1330, 8529, 198, 11748, 28686, 198, 11748, 12972, 9288, 198, 11748, 1275, 62, 9288, 62, 11321, 198, 11748, 269, 27446, 62, 29048, 62, 36439, 62, 39022, 198, 198, 30706, 62, 565, 5819, 796, 705, 344, 746, 6, ...
2.320261
153
import setuptools setuptools.setup( name='mintermonitoring', version='1.0.0', packages=setuptools.find_packages(include=['mintermonitoring']) )
[ 11748, 900, 37623, 10141, 198, 198, 2617, 37623, 10141, 13, 40406, 7, 198, 220, 220, 1438, 11639, 1084, 353, 41143, 278, 3256, 198, 220, 220, 2196, 11639, 16, 13, 15, 13, 15, 3256, 198, 220, 220, 10392, 28, 2617, 37623, 10141, 13, 1...
2.655172
58
s = input() num = [0] * 26 for i in range(len(s)): num[ord(s[i])-97] += 1 for i in num: print(i, end = " ") if i == len(num)-1: print(i)
[ 82, 796, 5128, 3419, 198, 22510, 796, 685, 15, 60, 1635, 2608, 198, 1640, 1312, 287, 2837, 7, 11925, 7, 82, 8, 2599, 198, 220, 220, 220, 997, 58, 585, 7, 82, 58, 72, 12962, 12, 5607, 60, 15853, 352, 198, 198, 1640, 1312, 287, ...
1.837209
86
from enum import Enum from numpy import isin metric_names = [ "euclidean", "manhattan", "hamming", "l2", "l1" ]
[ 6738, 33829, 1330, 2039, 388, 198, 198, 6738, 299, 32152, 1330, 318, 259, 628, 198, 198, 4164, 1173, 62, 14933, 796, 685, 198, 220, 220, 220, 366, 12496, 565, 485, 272, 1600, 198, 220, 220, 220, 366, 805, 12904, 1600, 198, 220, 220,...
2.044776
67
import pandas as pd import os.path length_switch = True max_body_length = 50 process_candidates = os.path.exists('./datasets/candidates.output') x_train = open('./datasets/x_train').readlines() x_train = [x.rstrip('\n') for x in x_train] y_train = open('./datasets/y_train').readlines() y_train = [x.rstrip('\n') for x in y_train] x_valid = open('./datasets/x_valid').readlines() x_valid = [x.rstrip('\n') for x in x_valid] y_valid = open('./datasets/y_valid').readlines() y_valid = [x.rstrip('\n') for x in y_valid] bytecodes = open('./datasets/bytecode.output').readlines() bytecodes = [x.rstrip('\n') for x in bytecodes] references = open('./datasets/references.output').readlines() references = [x.rstrip('\n') for x in references] if (process_candidates): candidates = open('./datasets/candidates.output').readlines() candidates = [x.rstrip('\n') for x in candidates] df_pairs = pd.DataFrame({'source': bytecodes, 'target' : references, 'candidates': candidates }) else: df_pairs = pd.DataFrame({'source': bytecodes, 'target': references }) if (length_switch): mask = df_pairs['source'].apply(lambda x: len(x.split()) <= max_body_length) df_pairs = df_pairs.loc[mask] df_train = pd.DataFrame({'source': x_train + x_valid, 'target' : y_train + y_valid }) df_valid = df_pairs.merge(df_train, on='source', indicator=True, how='left')\ .query('_merge=="left_only"')\ .drop('_merge', axis=1)\ .drop('target_y', axis=1) # df_valid = df_valid.sample(frac=1).reset_index(drop=True).sample(50000) with open('./datasets/remaining_sources', 'w') as filehandle: filehandle.writelines("%s\n" % place for place in df_valid['source']) with open('./datasets/remaining_references', 'w') as filehandle: filehandle.writelines("%s\n" % place for place in df_valid['target_x']) if (process_candidates): with open('./datasets/remaining_candidates', 'w') as filehandle: filehandle.writelines("%s\n" % place for place in df_valid['candidates'])
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 13, 6978, 198, 198, 13664, 62, 31943, 796, 6407, 198, 9806, 62, 2618, 62, 13664, 796, 2026, 198, 14681, 62, 46188, 37051, 796, 28686, 13, 6978, 13, 1069, 1023, 7, 4458, 14, 19608, ...
2.555128
780
import System dataKey, _ = IN OUT = System.AppDomain.CurrentDomain.GetData("_Dyn_Wireless_%s" % dataKey)
[ 11748, 4482, 198, 198, 7890, 9218, 11, 4808, 796, 3268, 198, 12425, 796, 4482, 13, 4677, 43961, 13, 11297, 43961, 13, 3855, 6601, 7203, 62, 35, 2047, 62, 29451, 1203, 62, 4, 82, 1, 4064, 1366, 9218, 8 ]
2.763158
38
# %% [1189. *Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) # text'ballon' # collections.Counter
[ 2, 43313, 685, 1157, 4531, 13, 1635, 40541, 7913, 286, 6932, 13022, 16151, 5450, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 47033, 12, 17618, 12, 1659, 12, 1894, 13022, 34729, 198, 2, 2420, 6, 1894, 261, 6, 198, 2, 17268, ...
2.978261
46
from quiet_coms import find_quiet_ports from quiet import Quiet import time if 'EXIT_ON_FAIL' not in locals(): VERBOSE = True EXIT_ON_FAIL = True if __name__ == "__main__": q2c = QuietI2C(None, log_path='usb_log.txt') i2c_test(q2c) i2c_test_errors(q2c) i2c_test(q2c) print('All I2C Tests Passed')
[ 6738, 5897, 62, 785, 82, 1330, 1064, 62, 39624, 62, 3742, 198, 6738, 5897, 1330, 37355, 198, 11748, 640, 198, 198, 361, 705, 6369, 2043, 62, 1340, 62, 7708, 4146, 6, 407, 287, 17205, 33529, 198, 220, 220, 220, 33310, 33, 14058, 796,...
2.152866
157
# Source : https://leetcode.com/problems/binary-tree-tilt/description/ # Date : 2017-12-26 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
[ 2, 8090, 1058, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 39491, 12, 21048, 12, 83, 2326, 14, 11213, 14, 198, 198, 2, 7536, 220, 220, 1058, 2177, 12, 1065, 12, 2075, 198, 198, 2, 30396, 329, 257, 13934, 5509, 10139,...
2.303571
112
# Copyright 2019 The Keras Tuner 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 # # 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. """Utilities for Tuner class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import math from collections import defaultdict import numpy as np import time import random import hashlib import tensorflow as tf from tensorflow import keras from ..abstractions import display def generate_trial_id(): s = str(time.time()) + str(random.randint(1, 1e7)) return hashlib.sha256(s.encode('utf-8')).hexdigest()[:32] def format_execution_id(i, executions_per_trial): execution_id_length = math.ceil( math.log(executions_per_trial, 10)) execution_id_template = '%0' + str(execution_id_length) + 'd' execution_id = execution_id_template % i return execution_id
[ 2, 15069, 13130, 383, 17337, 292, 13932, 263, 46665, 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, ...
3.297101
414
__author__ = 'zieghailo' import matplotlib.pyplot as plt # plt.ion() if __name__ == "__main__": start_gui()
[ 834, 9800, 834, 796, 705, 49746, 456, 603, 78, 6, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 2, 458, 83, 13, 295, 3419, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298,...
2.288462
52
import warnings from typing import Callable, Optional, TypeVar, cast CallableType = TypeVar("CallableType", bound=Callable) def deprecation_wrapper(message: str, function_or_class: CallableType) -> CallableType: """Creates a wrapper for a deprecated function or class. Prints a warning the first time a function or class is called. Args: message (str): Warning message. function_or_class (CallableType): Function or class to wrap. Returns: CallableType: Wrapped function/class. """ warned = False return cast(CallableType, curried) def new_name_wrapper( old_name: str, new_name: str, function_or_class: CallableType ) -> CallableType: """Creates a wrapper for a renamed function or class. Prints a warning the first time a function or class is called with the old name. Args: old_name (str): Old name of function or class. Printed in warning. new_name (str): New name of function or class. Printed in warning. function_or_class (CallableType): Function or class to wrap. Returns: CallableType: Wrapped function/class. """ return deprecation_wrapper( f"{old_name} is deprecated! Use {new_name} instead.", function_or_class )
[ 11748, 14601, 198, 6738, 19720, 1330, 4889, 540, 11, 32233, 11, 5994, 19852, 11, 3350, 198, 198, 14134, 540, 6030, 796, 5994, 19852, 7203, 14134, 540, 6030, 1600, 5421, 28, 14134, 540, 8, 628, 198, 4299, 1207, 8344, 341, 62, 48553, 7,...
2.941589
428
import json data = { "users": [ {"Name": "Dominator", "skill": 100, "gold": 99999, "weapons": ['Sword', 'Atomic Laser']}, {"Name": "Looser", "skill": 1, "gold": -100000, "weapons": [None, None, None]}, ] } with open("example.json", "w") as f: s = json.dumps(data, indent=4) f.write(s)
[ 11748, 33918, 198, 198, 7890, 796, 1391, 198, 220, 220, 220, 366, 18417, 1298, 685, 198, 220, 220, 220, 220, 220, 220, 220, 19779, 5376, 1298, 366, 43417, 1352, 1600, 366, 42401, 1298, 1802, 11, 366, 24267, 1298, 860, 24214, 11, 366, ...
2.262411
141
from md_utils import * from py_utils import *
[ 6738, 45243, 62, 26791, 1330, 1635, 198, 6738, 12972, 62, 26791, 1330, 1635, 198 ]
3.285714
14
if __name__ == "__main__": data = raw_input().strip(',\n').split(' ') count = 0 total = 0 for pxl in data: pxl = pxl.split(',') mean = 0 for i in pxl: mean += int(i) mean /= 3 if mean < 70: count += 1 total += 1 if float(count) / total > 0.4: print 'night' else: print 'day'
[ 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1366, 796, 8246, 62, 15414, 22446, 36311, 7, 3256, 59, 77, 27691, 35312, 10786, 705, 8, 198, 220, 220, 220, 954, 796, 657, 198, 220, 220, 220, 2472, 796, ...
1.78341
217
import random as r # Sets up required variables running = True user_wins = 0 comp_wins = 0 answers = ["R", "P", "S"] win_combos = ["PR", "RS", "SP"] # Welcome message print("Welcome to Rock-Paper-Scissors. Please input one of the following:" "\n'R' - rock\n'P' - paper\n'S' - scissors\nto get started.") while running: # Running game of rock, paper, scissors if user_wins == 3 or comp_wins == 3: print(f"Game is over. The score was {user_wins}-{comp_wins}. Thanks for playing.") break user_guess = input("Guess:").upper() if user_guess.upper() not in answers: print("You didn't enter a valid letter.") break comp_guess = answers[r.randint(0, 2)] guess_join = user_guess + comp_guess if guess_join[0] == guess_join[1]: print(f"You both guessed {user_guess}!\nThe current score is {user_wins}-{comp_wins}.") else: # Checks to see if computer or user has won the round. if any(guess_join == elem in win_combos for elem in win_combos): user_wins += 1 print(f"You win! Score is {user_wins}-{comp_wins}.") else: comp_wins += 1 print(f"You lose! Score is {user_wins}-{comp_wins}.")
[ 11748, 4738, 355, 374, 628, 198, 2, 21394, 510, 2672, 9633, 198, 20270, 796, 6407, 198, 7220, 62, 86, 1040, 796, 657, 198, 5589, 62, 86, 1040, 796, 657, 198, 504, 86, 364, 796, 14631, 49, 1600, 366, 47, 1600, 366, 50, 8973, 198, ...
2.322642
530
from baselines import deepq
[ 6738, 1615, 20655, 1330, 2769, 80, 628 ]
4.142857
7
#!/usr/bin/python3 import requests import click from rich import inspect from rich.console import Console from url_normalize import url_normalize from urllib.parse import quote console = Console() if __name__ == "__main__": exploit()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 7007, 198, 11748, 3904, 198, 6738, 5527, 1330, 10104, 198, 6738, 5527, 13, 41947, 1330, 24371, 198, 6738, 19016, 62, 11265, 1096, 1330, 19016, 62, 11265, 1096, 198, 6738, 2956, ...
3.361111
72
# @copyright@ # Copyright (c) 2006 - 2019 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ # # @rocks@ # Copyright (c) 2000 - 2010 The Regents of the University of California # All rights reserved. Rocks(r) v5.4 www.rocksclusters.org # https://github.com/Teradata/stacki/blob/master/LICENSE-ROCKS.txt # @rocks@ import stack.commands
[ 2, 2488, 22163, 4766, 31, 198, 2, 15069, 357, 66, 8, 4793, 532, 13130, 3813, 14706, 198, 2, 1439, 2489, 10395, 13, 23881, 72, 7, 81, 8, 410, 20, 13, 87, 8931, 72, 13, 785, 198, 2, 3740, 1378, 12567, 13, 785, 14, 15156, 14706, ...
2.714286
154
import contextlib import torch from typing import List, Tuple last_executed_optimized_graph = torch._C._last_executed_optimized_graph def set_fusion_strategy(strategy: List[Tuple[str, int]]): """ Sets the type and number of specializations that can occur during fusion. Usage: provide a list of pairs (type, depth) where type is one of "STATIC" or "DYNAMIC" and depth is an integer. Behavior - static vs dynamic: In STATIC fusion, fused ops are compiled to have fixed input shapes. The shape is determined based on some initial profiling runs. In DYNAMIC fusion, fused ops are compiled to have variable input shapes, so that multiple shapes are possible. In both cases, we also recompile on new striding behavior, device, or dtype. Behavior - fallback functions & depth: When an input doesn't match the format required by the specialized compiled op, it will run a fallback function. Fallback functions are recursively be compiled and specialized based on the observed tensor shapes. Since compilation can be slow, the "depth" parameter is provided to limit the number of specializations that can be compiled, before giving up on recompiling and falling back to a completely un-fused, un-specialized implementation. The list of (type, depth) pairs controls the type of specializations and the number of specializations. For example: [("STATIC", 2), ("DYNAMIC", 2)] indicates that the first two specializations will use static fusions, the following two specializations will use dynamic fusion, and any inputs that satisfy none of the 4 options will run an unfused implementation. NB: in the future, if more as more fusion backends are added there may be more granular apis for specific fusers. """ return torch._C._jit_set_fusion_strategy(strategy)
[ 11748, 4732, 8019, 198, 198, 11748, 28034, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 628, 198, 12957, 62, 18558, 7241, 62, 40085, 1143, 62, 34960, 796, 28034, 13557, 34, 13557, 12957, 62, 18558, 7241, 62, 40085, 1143, 62, 34960, 198...
3.439201
551
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by pat on 5/8/18 """ .. currentmodule:: modlit.db.postgres .. moduleauthor:: Pat Daburu <pat@daburu.net> This module contains utilities for working directly with PostgreSQL. """ import json from pathlib import Path from urllib.parse import urlparse, ParseResult from addict import Dict import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT DEFAULT_ADMIN_DB = 'postgres' #: the default administrative database name DEFAULT_PG_PORT = 5432 #: the default PostgreSQL listener port # Load the Postgres phrasebook. # pylint: disable=invalid-name # pylint: disable=no-member sql_phrasebook = Dict( json.loads( ( Path(__file__).resolve().parent / 'postgres.json' ).read_text() )['sql'] ) def connect(url: str, dbname: str = None, autocommit: bool = False): """ Create a connection to a Postgres database. :param url: the Postgres instance URL :param dbname: the target database name (if it differs from the one specified in the URL) :param autocommit: Set the `autocommit` flag on the connection? :return: a psycopg2 connection """ # Parse the URL. (We'll need the pieces to construct an ogr2ogr connection # string.) dbp: ParseResult = urlparse(url) # Create a dictionary to hold the arguments for the connection. (We'll # unpack it later.) cnx_opt = { k: v for k, v in { 'host': dbp.hostname, 'port': int(dbp.port) if dbp.port is not None else DEFAULT_PG_PORT, 'database': dbname if dbname is not None else dbp.path[1:], 'user': dbp.username, 'password': dbp.password }.items() if v is not None } cnx = psycopg2.connect(**cnx_opt) # If the caller requested that the 'autocommit' flag be set... if autocommit: # ...do that now. cnx.autocommit = True return cnx def db_exists(url: str, dbname: str = None, admindb: str = DEFAULT_ADMIN_DB) -> bool: """ Does a given database on a Postgres instance exist? :param url: the Postgres instance URL :param dbname: the name of the database to test :param admindb: the name of an existing (presumably the main) database :return: `True` if the database exists, otherwise `False` """ # Let's see what we got for the database name. _dbname = dbname # If the caller didn't specify a database name... if not _dbname: # ...let's figure it out from the URL. db: ParseResult = urlparse(url) _dbname = db.path[1:] # Now, let's do this! with connect(url=url, dbname=admindb) as cnx: with cnx.cursor() as crs: # Execute the SQL query that counts the databases with a specified # name. crs.execute( sql_phrasebook.select_db_count.format(_dbname) ) # If the count isn't zero (0) the database exists. return crs.fetchone()[0] != 0 def create_db( url: str, dbname: str, admindb: str = DEFAULT_ADMIN_DB): """ Create a database on a Postgres instance. :param url: the Postgres instance URL :param dbname: the name of the database :param admindb: the name of an existing (presumably the main) database """ with connect(url=url, dbname=admindb) as cnx: cnx.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) with cnx.cursor() as crs: crs.execute(sql_phrasebook.create_db.format(dbname)) def touch_db( url: str, dbname: str = None, admindb: str = DEFAULT_ADMIN_DB): """ Create a database if it does not already exist. :param url: the Postgres instance URL :param dbname: the name of the database :param admindb: the name of an existing (presumably the main) database """ # If the database already exists, we don't need to do anything further. if db_exists(url=url, dbname=dbname, admindb=admindb): return # Let's see what we got for the database name. _dbname = dbname # If the caller didn't specify a database name... if not _dbname: # ...let's figure it out from the URL. db: ParseResult = urlparse(url) _dbname = db.path[1:] # Now we can create it. create_db(url=url, dbname=_dbname, admindb=admindb)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15622, 416, 1458, 319, 642, 14, 23, 14, 1507, 198, 37811, 198, 492, 1459, 21412, 3712, 953, 18250, 13, 9945, ...
2.433921
1,816
import logging import async_timeout import urllib.request import time import re from datetime import datetime, timedelta import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.util import Throttle from homeassistant.helpers.aiohttp_client import async_get_clientsession REQUIREMENTS = ['pyEstradasPT==1.0.2'] _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Powered by estradas.pt" CONF_CAMERA = 'camera' SCAN_INTERVAL = timedelta(minutes=5) DOMAIN = 'estradaspt' PLATFORM_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_CAMERA): vol.All(cv.ensure_list, [cv.string]) }) }, extra=vol.ALLOW_EXTRA) class CameraVideo(Entity): """Sensor that reads and stores the camera video.""" ICON = 'mdi:webcam' def __init__(self, name, file_name, url): """Initialize the component.""" self._name = name self._file_name = file_name self._url = url self._last_update = datetime.now()
[ 11748, 18931, 198, 11748, 30351, 62, 48678, 198, 11748, 2956, 297, 571, 13, 25927, 198, 11748, 640, 198, 11748, 302, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 11748, 2322, 37623, 5623, 355, 2322, 198, 198, 117...
2.69161
441
import lexer import ast
[ 11748, 31191, 263, 198, 11748, 6468, 198 ]
3.428571
7
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: terra/treasury/v1beta1/genesis.proto, terra/treasury/v1beta1/query.proto, terra/treasury/v1beta1/treasury.proto # plugin: python-betterproto from dataclasses import dataclass from typing import Dict, List import betterproto from betterproto.grpc.grpclib_server import ServiceBase import grpclib class QueryStub(betterproto.ServiceStub): class QueryBase(ServiceBase): from ....cosmos.base import v1beta1 as ___cosmos_base_v1_beta1__
[ 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 4237, 25, 1059, 430, 14, 33945, 11579, 14, 85, 16, 31361, 16, 14, 5235, 9339, 13, 1676, 1462, 11, 1059, 430, 14, 33945, 11579, 14, 85, 16, 31361, ...
2.865591
186
# ## Copyright (c) 2018, Bradley A. Minch ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## 2. Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. # import Tkinter as tk import usbservo if __name__=='__main__': gui = usbservogui() gui.root.mainloop()
[ 2, 201, 198, 2235, 15069, 357, 66, 8, 2864, 11, 16182, 317, 13, 1855, 354, 201, 198, 2235, 1439, 2489, 10395, 13, 201, 198, 2235, 201, 198, 2235, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 201, 198...
3.037109
512
try: from torch.hub import load_state_dict_from_url except ImportError: from torch.utils.model_zoo import load_url as load_state_dict_from_url
[ 28311, 25, 201, 198, 220, 220, 220, 422, 28034, 13, 40140, 1330, 3440, 62, 5219, 62, 11600, 62, 6738, 62, 6371, 201, 198, 16341, 17267, 12331, 25, 201, 198, 220, 220, 220, 422, 28034, 13, 26791, 13, 19849, 62, 89, 2238, 1330, 3440, ...
2.719298
57
""" This file contains the Zayo Service Inventory related API endpoints. References ---------- Docs http://54.149.224.75/wp-content/uploads/2020/02/Service-Inventory-Wiki.pdf """ # ----------------------------------------------------------------------------- # System Imports # ----------------------------------------------------------------------------- from typing import List, Dict # ----------------------------------------------------------------------------- # Public Imports # ----------------------------------------------------------------------------- from first import first # ----------------------------------------------------------------------------- # Private Imports # ----------------------------------------------------------------------------- from pyzayo.base_client import ZayoClientBase from pyzayo.consts import ZAYO_SM_ROUTE_SERVICES # ----------------------------------------------------------------------------- # Module Exports # ----------------------------------------------------------------------------- __all__ = ["ZayoServiceInventoryMixin"]
[ 37811, 198, 1212, 2393, 4909, 262, 1168, 323, 78, 4809, 35772, 3519, 7824, 886, 13033, 13, 198, 198, 19927, 198, 35937, 198, 220, 220, 220, 14432, 82, 198, 220, 220, 220, 2638, 1378, 4051, 13, 19442, 13, 24137, 13, 2425, 14, 24142, ...
5.793651
189
# =============================================================================== # Copyright 2011 Jake Ross # # 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. # =============================================================================== # =============enthought library imports======================= # =============standard library imports ======================== from __future__ import absolute_import import logging import os import shutil from logging.handlers import RotatingFileHandler from pychron.core.helpers.filetools import list_directory, unique_path2 from pychron.paths import paths NAME_WIDTH = 40 gFORMAT = '%(name)-{}s: %(asctime)s %(levelname)-9s (%(threadName)-10s) %(message)s'.format(NAME_WIDTH) gLEVEL = logging.DEBUG def tail(f, lines=20): """ http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail """ total_lines_wanted = lines BLOCK_SIZE = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting # from the end of the file while lines_to_go > 0 and block_end_byte > 0: if block_end_byte - BLOCK_SIZE > 0: # read the last block we haven't yet read f.seek(block_number * BLOCK_SIZE, 2) blocks.append(f.read(BLOCK_SIZE)) else: # file too small, start from begining f.seek(0, 0) # only read what was not read blocks.append(f.read(block_end_byte)) lines_found = blocks[-1].count(b'\n') lines_to_go -= lines_found block_end_byte -= BLOCK_SIZE block_number -= 1 all_read_text = b''.join(reversed(blocks)) return b'\n'.join(all_read_text.splitlines()[-total_lines_wanted:]).decode('utf-8') # def anomaly_setup(name): # ld = logging.Logger.manager.loggerDict # print 'anomaly setup ld={}'.format(ld) # if name not in ld: # bdir = paths.log_dir # name = add_extension(name, '.anomaly') # apath, _cnt = unique_path2(bdir, name, delimiter='-', extension='.log') # logger = logging.getLogger('anomalizer') # h = logging.FileHandler(apath) # logger.addHandler(h) def logging_setup(name, use_archiver=True, root=None, use_file=True, **kw): """ """ # set up deprecation warnings # import warnings # warnings.simplefilter('default') bdir = paths.log_dir if root is None else root # make sure we have a log directory # if not os.path.isdir(bdir): # os.mkdir(bdir) if use_archiver: # archive logs older than 1 month # lazy load Archive because of circular dependency from pychron.core.helpers.archiver import Archiver a = Archiver(archive_days=14, archive_months=1, root=bdir) a.clean() if use_file: # create a new logging file logname = '{}.current.log'.format(name) logpath = os.path.join(bdir, logname) if os.path.isfile(logpath): backup_logpath, _cnt = unique_path2(bdir, name, delimiter='-', extension='.log', width=5) shutil.copyfile(logpath, backup_logpath) os.remove(logpath) ps = list_directory(bdir, filtername=logname, remove_extension=False) for pi in ps: _h, t = os.path.splitext(pi) v = os.path.join(bdir, pi) shutil.copyfile(v, '{}{}'.format(backup_logpath, t)) os.remove(v) root = logging.getLogger() root.setLevel(gLEVEL) shandler = logging.StreamHandler() handlers = [shandler] if use_file: rhandler = RotatingFileHandler( logpath, maxBytes=1e7, backupCount=50) handlers.append(rhandler) fmt = logging.Formatter(gFORMAT) for hi in handlers: hi.setLevel(gLEVEL) hi.setFormatter(fmt) root.addHandler(hi) def wrap(items, width=40, indent=90, delimiter=','): """ wrap a list """ if isinstance(items, str): items = items.split(delimiter) gcols = iter(items) t = 0 rs = [] r = [] while 1: try: c = next(gcols) t += 1 + len(c) if t < width: r.append(c) else: rs.append(','.join(r)) r = [c] t = len(c) except StopIteration: rs.append(','.join(r)) break return ',\n{}'.format(' ' * indent).join(rs) # ============================== EOF ===================================
[ 2, 38093, 25609, 855, 198, 2, 15069, 2813, 14757, 9847, 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, ...
2.351449
2,208
import picmodels
[ 11748, 8301, 27530, 628, 628, 628, 628, 628 ]
3.25
8