content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from fastapi import FastAPI, Request, Response from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from utils import get_page_data, process_initial import uvicorn app = FastAPI() templates = Jinja2Templates(directory="templates") app.mount("/static", StaticFiles(directory="static"), name="static") if __name__ == "__main__": uvicorn.run("main:app", host="127.0.0.1", port=8050, log_level="info")
[ 6738, 3049, 15042, 1330, 12549, 17614, 11, 19390, 11, 18261, 198, 6738, 3049, 15042, 13, 16733, 274, 1330, 11532, 31077, 198, 6738, 3049, 15042, 13, 12708, 16624, 1330, 36125, 25876, 198, 6738, 3049, 15042, 13, 11498, 489, 803, 1330, 1729...
3.189542
153
# # Python script using OME API to create a new static group # # _author_ = Raajeev Kalyanaraman <Raajeev.Kalyanaraman@Dell.com> # _version_ = 0.1 # # Copyright (c) 2020 Dell EMC Corporation # # 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. # """ SYNOPSIS: Script to create a new static group DESCRIPTION: This script exercises the OME REST API to create a new static group. The user is responsible for adding devices to the group once the group has been successfully created. For authentication X-Auth is used over Basic Authentication Note that the credentials entered are not stored to disk. EXAMPLE: python create_static_group.py --ip <xx> --user <username> --password <pwd> --groupname "Random Test Group" """ import json import argparse from argparse import RawTextHelpFormatter import urllib3 import requests def create_static_group(ip_address, user_name, password, group_name): """ Authenticate with OME and enumerate groups """ try: session_url = 'https://%s/api/SessionService/Sessions' % ip_address group_url = "https://%s/api/GroupService/Groups?$filter=Name eq 'Static Groups'" % ip_address headers = {'content-type': 'application/json'} user_details = {'UserName': user_name, 'Password': password, 'SessionType': 'API'} session_info = requests.post(session_url, verify=False, data=json.dumps(user_details), headers=headers) if session_info.status_code == 201: headers['X-Auth-Token'] = session_info.headers['X-Auth-Token'] response = requests.get(group_url, headers=headers, verify=False) if response.status_code == 200: json_data = response.json() if json_data['@odata.count'] > 0: # Technically there should be only one result in the filter group_id = json_data['value'][0]['Id'] group_payload = {"GroupModel": { "Name": group_name, "Description": "", "MembershipTypeId": 12, "ParentId": int(group_id)} } create_url = 'https://%s/api/GroupService/Actions/GroupService.CreateGroup' % ip_address create_resp = requests.post(create_url, headers=headers, verify=False, data=json.dumps(group_payload)) if create_resp.status_code == 200: print("New group created : ID =", create_resp.text) elif create_resp.status_code == 400: print("Failed group creation ...See error info below") print(json.dumps(create_resp.json(), indent=4, sort_keys=False)) else: print("Unable to retrieve group list from %s" % ip_address) else: print("Unable to create a session with appliance %s" % ip_address) except Exception as error: print("Unexpected error:", str(error)) if __name__ == '__main__': urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) parser = argparse.ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter) parser.add_argument("--ip", "-i", required=True, help="OME Appliance IP") parser.add_argument("--user", "-u", required=False, help="Username for OME Appliance", default="admin") parser.add_argument("--password", "-p", required=True, help="Password for OME Appliance") parser.add_argument("--groupname", "-g", required=True, help="A valid name for the group") args = parser.parse_args() create_static_group(args.ip, args.user, args.password, args.groupname)
[ 2, 198, 2, 11361, 4226, 1262, 440, 11682, 7824, 284, 2251, 257, 649, 9037, 1448, 198, 2, 198, 2, 4808, 9800, 62, 796, 7567, 1228, 1453, 85, 509, 3400, 272, 283, 10546, 1279, 21762, 1228, 1453, 85, 13, 42, 3400, 272, 283, 10546, 31...
2.309463
1,955
from typing import Callable, Optional, Tuple, Union import numpy as np from torch.utils.data import DataLoader, Sampler from torch.utils.data.dataset import Subset, ConcatDataset import torch.utils.data.distributed as data_dist from dataflow.datasets import get_train_dataset, get_val_dataset, TransformedDataset, get_train_noval_sbdataset
[ 6738, 19720, 1330, 4889, 540, 11, 32233, 11, 309, 29291, 11, 4479, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 11, 3409, 20053, 198, 6738, 28034, 13, 26791, 13, 7890, 13, 196...
3.053097
113
from datetime import datetime, timedelta from typing import Any, Dict, Optional import graphene import jwt from django.conf import settings from django.core.handlers.wsgi import WSGIRequest from ..account.models import User from ..app.models import App from .permissions import ( get_permission_names, get_permissions_from_codenames, get_permissions_from_names, ) JWT_ALGORITHM = "HS256" SALEOR_AUTH_HEADER = "HTTP_AUTHORIZATION_BEARER" DEFAULT_AUTH_HEADER = "HTTP_AUTHORIZATION" AUTH_HEADER_PREFIXES = ["JWT", "BEARER"] JWT_ACCESS_TYPE = "access" JWT_REFRESH_TYPE = "refresh" JWT_THIRDPARTY_ACCESS_TYPE = "thirdparty" JWT_REFRESH_TOKEN_COOKIE_NAME = "refreshToken" PERMISSIONS_FIELD = "permissions" JWT_SALEOR_OWNER_NAME = "saleor" JWT_OWNER_FIELD = "owner" def is_saleor_token(token: str) -> bool: """Confirm that token was generated by Saleor not by plugin.""" try: payload = jwt.decode(token, options={"verify_signature": False}) except jwt.PyJWTError: return False owner = payload.get(JWT_OWNER_FIELD) if not owner or owner != JWT_SALEOR_OWNER_NAME: return False return True def create_access_token_for_app(app: "App", user: "User"): """Create access token for app. App can use user jwt token to proceed given operation on the Saleor side. The token which can be used by App has additional field defining the permissions assigned to it. The permissions set is the intersection of user permissions and app permissions. """ app_permissions = app.permissions.all() app_permission_enums = get_permission_names(app_permissions) permissions = user.effective_permissions user_permission_enums = get_permission_names(permissions) app_id = graphene.Node.to_global_id("App", app.id) additional_payload = { "app": app_id, PERMISSIONS_FIELD: list(app_permission_enums & user_permission_enums), } payload = jwt_user_payload( user, JWT_THIRDPARTY_ACCESS_TYPE, exp_delta=settings.JWT_TTL_APP_ACCESS, additional_payload=additional_payload, ) return jwt_encode(payload)
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 32233, 198, 198, 11748, 42463, 198, 11748, 474, 46569, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 72...
2.570406
838
import os, json, logging, jsonpath_rw_ext, jsonpath_rw from jsonpath_rw import jsonpath, parse from . import events from ast import literal_eval from flask import make_response logger = logging.getLogger(__name__) CONFIG_PATH = '/tests/settings/config.json'
[ 11748, 28686, 11, 33918, 11, 18931, 11, 33918, 6978, 62, 31653, 62, 2302, 11, 33918, 6978, 62, 31653, 198, 6738, 33918, 6978, 62, 31653, 1330, 33918, 6978, 11, 21136, 198, 6738, 764, 1330, 2995, 198, 6738, 6468, 1330, 18875, 62, 18206, ...
3.291139
79
# Generated by Django 2.2.4 on 2019-11-14 16:48 import django.contrib.postgres.fields.jsonb from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 19, 319, 13130, 12, 1157, 12, 1415, 1467, 25, 2780, 198, 198, 11748, 42625, 14208, 13, 3642, 822, 13, 7353, 34239, 13, 25747, 13, 17752, 65, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, ...
2.822222
45
from json import JSONEncoder from time import time
[ 6738, 33918, 1330, 19449, 27195, 12342, 198, 6738, 640, 1330, 640, 198 ]
4.25
12
"""Compute pi.""" from decimal import Decimal, getcontext import argparse import itertools if __name__ == '__main__': parser = argparse.ArgumentParser(description='Calculates pi.') parser.add_argument('--precision', type=int, default=100, help='The desired precision of pi (default: 100 digits)') args = parser.parse_args() pi_computer = ComputePi() print(pi_computer.machin_euler(args.precision))
[ 37811, 7293, 1133, 31028, 526, 15931, 198, 6738, 32465, 1330, 4280, 4402, 11, 651, 22866, 198, 11748, 1822, 29572, 198, 11748, 340, 861, 10141, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220,...
2.715152
165
#!/usr/bin/python3 import time from brownie import ( DataTypes, TransparentUpgradeableProxy, ProxyAdmin, config, network, Contract, ) from scripts.helpful_scripts import get_account, encode_function_data
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 11748, 640, 198, 6738, 7586, 494, 1330, 357, 198, 220, 220, 220, 6060, 31431, 11, 198, 220, 220, 220, 3602, 8000, 44948, 540, 44148, 11, 198, 220, 220, 220, 38027, 46787, 11, 198, 220, ...
2.8625
80
import torch.nn as nn
[ 11748, 28034, 13, 20471, 355, 299, 77, 198 ]
2.75
8
# written by Jaekwang Cha # version 0.1 # ================== IMPORT CUSTOM LEARNING LIBRARIES ===================== # from customs.train import train, test from customs.dataset import load_dataset from customs.model import load_model # ================== TRAINING SETTINGS ================== # import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--train_method', default='supervised', type=str, help='type of training: supervised(default), unsupervised, reinforce') parser.add_argument('--task', default='classification', type=str, help='task of training: classification(default), regression') parser.add_argument('--dataset', default='mnist', type=str, help='dataset to use') parser.add_argument('--model', default='CNN', type=str, help='model to use') parser.add_argument('--seed', default=42, type=int, help='random seed (default: 42)') parser.add_argument('--num_worker', default=1, type=int, help='number of dataloader worker') parser.add_argument('--no_cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--gpu', default=0, type=str, help='GPU-id for GPU to use') parser.add_argument('--multi_gpu', default=0, type=str, help='GPU-ids for multi-GPU usage') parser.add_argument('--pin_memory', default=True, type=bool, help='pin memory option selector') parser.add_argument('--save_model', action='store_true', default=False, help='For Saving the current Model') parser.add_argument('--save_path', default=os.getcwd()+'/weights', type=str, help='Where to save weights') parser.add_argument('--log_path', default=os.getcwd()+'/Logs', type=str, help='Where to save Logs') # data setting parser.add_argument('--val_rate', default=0.2, type=float, help='split rate for the validation data') parser.add_argument('--transform', default='default', type=str, help='choose the data transform type') # training parameter setting parser.add_argument('--n_epoch', default=10, type=int, help='number of total training iteration') parser.add_argument('--batch_size', default=32, type=int, help='size of minibatch') parser.add_argument('--test_batch_size', default=32, type=int, help='size of test-minibatch') # optimizer & scheduler setting parser.add_argument('--lr', default=0.03, type=float, help='training learning rate') parser.add_argument('--optimizer', default='adam', type=str, help='optimizer select') parser.add_argument('--scheduler', default='steplr', type=str, help='scheduler select') opt = parser.parse_args() # ===================== IMPORT PYTORCH LIBRARIES ================== # import torch from torch.utils.data import DataLoader torch.manual_seed(opt.seed) # ================== GPU SETTINGS ================== # # ======================= MAIN SCRIPT ============================= # if __name__ == '__main__': main(opt)
[ 2, 3194, 416, 13790, 988, 47562, 20703, 201, 198, 2, 2196, 657, 13, 16, 201, 198, 201, 198, 2, 36658, 28, 30023, 9863, 327, 7759, 2662, 12509, 1503, 15871, 45651, 49, 1503, 11015, 36658, 1421, 1303, 201, 198, 6738, 17112, 13, 27432, ...
2.358076
1,455
#!/usr/bin/env python3 import logging import sys import subprocess from pathlib import Path from datetime import datetime from Pegasus.api import * logging.basicConfig(level=logging.DEBUG) # --- Work Dir Setup ----------------------------------------------------------- RUN_ID = "024-sc4-gridftp-http-" + datetime.now().strftime("%s") TOP_DIR = Path.cwd() WORK_DIR = TOP_DIR / "work" try: Path.mkdir(WORK_DIR) except FileExistsError: pass # --- Configuration ------------------------------------------------------------ print("Generating pegasus.properties at: {}".format(TOP_DIR / "pegasus.properties")) props = Properties() props["pegasus.dir.useTimestamp"] = "true" props["pegasus.dir.storage.deep"] = "false" props["pegasus.data.configuration"] = "nonsharedfs" with (TOP_DIR / "pegasus.properties").open(mode="w") as f: props.write(f) # --- Sites -------------------------------------------------------------------- print("Generating site catalog at: sites.yml") LOCAL = "local" CONDOR_POOL = "condorpool" STAGING_SITE = "staging_site" try: pegasus_config = subprocess.run( ["pegasus-config", "--bin"], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) except FileNotFoundError as e: print("Unable to find pegasus-config") assert pegasus_config.returncode == 0 PEGASUS_BIN_DIR = pegasus_config.stdout.decode().strip() sites = """ pegasus: "5.0" sites: - name: "condor_pool" arch: "x86_64" os.type: "linux" profiles: condor: universe: "vanilla" pegasus: style: "condor" - name: "staging_site" arch: "x86_64" os.type: "linux" directories: - type: "sharedScratch" path: "/lizard/scratch-90-days/http-scratch/ptesting" fileServers: - operation: "get" url: "http://workflow.isi.edu/shared-scratch/ptesting" - operation: "put" url: "gsiftp://workflow.isi.edu/lizard/scratch-90-days/http-scratch/ptesting" - name: "local" arch: "x86_64" os.type: "linux" os.release: "rhel" os.version: "7" directories: - type: "sharedScratch" path: "{work_dir}/scratch" fileServers: - operation: "all" url: "file://{work_dir}/scratch" - type: "localStorage" path: "{work_dir}/outputs" fileServers: - operation: "all" url: "file://{work_dir}/outputs" profiles: env: PEGASUS_BIN_DIR: "{pegasus_bin_dir}" """.format( work_dir=str(WORK_DIR), pegasus_bin_dir=PEGASUS_BIN_DIR ) with (TOP_DIR / "sites.yml").open(mode="w") as f: f.write(sites) # --- Transformations ---------------------------------------------------------- rosetta_exe = Transformation( "rosetta.exe", arch=Arch.X86_64, os_type=OS.LINUX, site="local", pfn="file://" + str(TOP_DIR / "rosetta.exe"), is_stageable=True, ).add_pegasus_profile(clusters_size=3) tc = TransformationCatalog().add_transformations(rosetta_exe) # --- Replicas & Workflow ------------------------------------------------------ rc = ReplicaCatalog() # add all files in minirosetta_database inputs = list() get_files(Path("minirosetta_database")) f1 = File("design.resfile") inputs.append(f1) rc.add_replica(LOCAL, f1, str(Path("design.resfile").resolve())) f2 = File("repack.resfile") inputs.append(f2) rc.add_replica(LOCAL, f2, str(Path("repack.resfile").resolve())) wf = Workflow("rosetta") pdb_files = list(Path("pdbs").iterdir()) for i in range(10): current_file = pdb_files[i] if current_file.is_file(): job = ( Job(rosetta_exe, _id=current_file.name.replace(".pdb", "")) .add_inputs(File(current_file.name), *inputs) .add_outputs(File(current_file.name + ".score.sc"), register_replica=True) .add_args( "-in:file:s", current_file.name, "-out:prefix " + current_file.name + ".", "-database ./minirosetta_database", "-linmem_ig 10", "-nstruct 1", "-pert_num 2", "-inner_num 1", "-jd2::ntrials 1", ) ) rc.add_replica("local", current_file.name, str(current_file.resolve())) wf.add_jobs(job) # write rc to separate file for registration jobs with (TOP_DIR / "replicas.yml").open("w") as f: rc.write(f) wf.add_transformation_catalog(tc) try: wf.plan( dir=str(WORK_DIR), verbose=5, sites=[CONDOR_POOL], staging_sites={CONDOR_POOL: STAGING_SITE}, ) except PegasusClientError as e: print(e.output)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 18931, 198, 11748, 25064, 198, 11748, 850, 14681, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 48188, 13, 15042, 1330, 163...
2.320812
1,970
import torch from ceem.opt_criteria import * from ceem.systems import LorenzAttractor from ceem.dynamics import * from ceem.smoother import * from ceem import utils if __name__ == '__main__': test_smoother()
[ 11748, 28034, 198, 198, 6738, 2906, 368, 13, 8738, 62, 22213, 5142, 1330, 1635, 198, 6738, 2906, 368, 13, 10057, 82, 1330, 15639, 27305, 8086, 40450, 198, 6738, 2906, 368, 13, 67, 4989, 873, 1330, 1635, 198, 6738, 2906, 368, 13, 5796,...
2.905405
74
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """A collection of backend information formatted to generate drawing data. This instance will be provided to generator functions. The module provides an abstract class :py:class:``DrawerBackendInfo`` with necessary methods to generate drawing objects. Because the data structure of backend class may depend on providers, this abstract class has an abstract factory method `create_from_backend`. Each subclass should provide the factory method which conforms to the associated provider. By default we provide :py:class:``OpenPulseBackendInfo`` class that has the factory method taking backends satisfying OpenPulse specification [1]. This class can be also initialized without the factory method by manually specifying required information. This may be convenient for visualizing a pulse program for simulator backend that only has a device Hamiltonian information. This requires two mapping objects for channel/qubit and channel/frequency along with the system cycle time. If those information are not provided, this class will be initialized with a set of empty data and the drawer illustrates a pulse program without any specific information. Reference: - [1] Qiskit Backend Specifications for OpenQASM and OpenPulse Experiments, https://arxiv.org/abs/1809.03452 """ from abc import ABC, abstractmethod from collections import defaultdict from typing import Dict, List, Union, Optional from qiskit import pulse from qiskit.providers import BaseBackend, BackendConfigurationError def get_channel_frequency(self, chan: pulse.channels.Channel) -> Union[float, None]: """Get frequency of given channel object.""" return self._chan_freq_map.get(chan, None) class OpenPulseBackendInfo(DrawerBackendInfo): """Drawing information of backend that conforms to OpenPulse specification."""
[ 2, 770, 2438, 318, 636, 286, 1195, 1984, 270, 13, 198, 2, 198, 2, 357, 34, 8, 15069, 19764, 12131, 13, 198, 2, 198, 2, 770, 2438, 318, 11971, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 13, 921, 743, 198, 2, 7330, 257, 486...
3.981197
585
# Create your views here. from .models import Mfund import plotly.graph_objects as go from plotly.offline import plot from plotly.tools import make_subplots from django.db.models import Q from django.conf import settings from django.shortcuts import redirect from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic.list import ListView from django.views import View from django.db.models import OuterRef, Subquery, Count, Sum, Max, Min from django.db.models.functions import Trim, Lower, Round import pandas as pd import csv, io import openpyxl from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect from django_gotolong.lastrefd.models import Lastrefd, lastrefd_update from django_gotolong.broker.icidir.imf.models import BrokerIcidirMf
[ 2, 13610, 534, 5009, 994, 13, 198, 198, 6738, 764, 27530, 1330, 337, 10990, 198, 198, 11748, 7110, 306, 13, 34960, 62, 48205, 355, 467, 198, 6738, 7110, 306, 13, 2364, 1370, 1330, 7110, 198, 6738, 7110, 306, 13, 31391, 1330, 787, 62...
3.173759
282
#coding: utf-8 from gevent import monkey monkey.patch_all() from gevent.pool import Pool import gevent import requests import urllib import os import time import re import ssl if __name__ == '__main__': downloader = Downloader(5) downloader.run('https://www.xiaodianying.com/filets/2069/dp.m3u8', './video',True)
[ 2, 66, 7656, 25, 3384, 69, 12, 23, 198, 198, 6738, 4903, 1151, 1330, 21657, 198, 49572, 13, 17147, 62, 439, 3419, 198, 6738, 4903, 1151, 13, 7742, 1330, 19850, 198, 11748, 4903, 1151, 198, 11748, 7007, 198, 11748, 2956, 297, 571, 19...
2.714286
119
# Generated by Django 3.2.9 on 2021-12-06 10:02 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 24, 319, 33448, 12, 1065, 12, 3312, 838, 25, 2999, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
#!/usr/bin/env python3 import os import contextlib from PyQt5 import QtCore, QtWidgets from dsrlib.settings import Settings def getSaveFilename(parent, domain, extension): with Settings().grouped('Paths') as settings: path = QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.DocumentsLocation) sname = 'save_%s' % domain if settings.contains(sname): path = settings.value(sname) while True: name, dummy = QtWidgets.QFileDialog.getSaveFileName(parent, _('Save'), path, '*.%s' % extension, options=QtWidgets.QFileDialog.DontConfirmOverwrite) if not name: return None if not name.endswith('.%s' % extension): name = '%s.%s' % (name, extension) if os.path.exists(name): resp = QtWidgets.QMessageBox.question(parent, _('Overwrite file?'), _('This file already exists. Overwrite?'), QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No|QtWidgets.QMessageBox.Cancel) if resp == QtWidgets.QMessageBox.Yes: settings.setValue(sname, os.path.dirname(name)) return name if resp == QtWidgets.QMessageBox.No: continue return None settings.setValue(sname, os.path.dirname(name)) return name def getOpenFilename(parent, domain, extension): with Settings().grouped('Paths') as settings: path = QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.DocumentsLocation) sname = 'open_%s' % domain if settings.contains(sname): path = settings.value(sname) name, dummy = QtWidgets.QFileDialog.getOpenFileName(parent, _('Open file'), path, '*.%s' % extension if extension else '') if name: settings.setValue(sname, os.path.dirname(name)) return name return None class EnumComboBox(QtWidgets.QComboBox): valueChanged = QtCore.pyqtSignal(object)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 198, 11748, 4732, 8019, 198, 198, 6738, 9485, 48, 83, 20, 1330, 33734, 14055, 11, 33734, 54, 312, 11407, 198, 198, 6738, 288, 27891, 8019, 13, 33692, 1330, 16163...
2.036449
1,070
#!/usr/bin/env python3 # # Copyright 2017-2020 GridGain Systems. # # 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. from .tidenpluginmanager import PluginManager from .report.steps import step, InnerReportConfig, Step, add_attachment, AttachmentType from .util import log_print, unix_path, call_method, create_case, kill_stalled_java, exec_time from .result import Result from .util import write_yaml_file, should_be_skipped from .logger import * from .runner import get_test_modules, get_long_path_len, get_class_from_module, known_issue_str from .priority_decorator import get_priority_key from .sshpool import SshPool from uuid import uuid4 from traceback import format_exc from .runner import set_configuration_options, get_configuration_representation, get_actual_configuration from importlib import import_module from os import path, mkdir from time import time from shutil import copyfile from os.path import join, basename from glob import glob import traceback
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 15069, 2177, 12, 42334, 24846, 38, 391, 11998, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, ...
3.615764
406
import logging import os import re import uuid from pathlib import Path from ludwig.constants import CHECKSUM, META, TEST, TRAINING, VALIDATION from ludwig.data.cache.util import calculate_checksum from ludwig.utils import data_utils from ludwig.utils.fs_utils import delete, path_exists logger = logging.getLogger(__name__) def alphanum(v): """Filters a string to only its alphanumeric characters.""" return re.sub(r"\W+", "", v)
[ 11748, 18931, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 334, 27112, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 300, 463, 28033, 13, 9979, 1187, 1330, 5870, 25171, 50, 5883, 11, 337, 20892, 11, 43001, 11, 29125, 1268, 2751...
2.908497
153
import pprint from FactorioCalcBase.data.binary import sorted_recipe_list, production_machine_category_list_dict from FactorioCalcBase.recipe import Recipe from FactorioCalcBase.calculator_base import CalculatorBase from FactorioCalcBase.dependency_dict_common_function import dict_add_number import time
[ 11748, 279, 4798, 198, 6738, 27929, 952, 9771, 66, 14881, 13, 7890, 13, 39491, 1330, 23243, 62, 29102, 431, 62, 4868, 11, 3227, 62, 30243, 62, 22872, 62, 4868, 62, 11600, 198, 6738, 27929, 952, 9771, 66, 14881, 13, 29102, 431, 1330, ...
3.551724
87
# Copyright (c) 2006- Facebook # Distributed under the Thrift Software License # # See accompanying file LICENSE or visit the Thrift site at: # http://developers.facebook.com/thrift/
[ 2, 15069, 357, 66, 8, 4793, 12, 3203, 198, 2, 4307, 6169, 739, 262, 16283, 2135, 10442, 13789, 198, 2, 198, 2, 4091, 19249, 2393, 38559, 24290, 393, 3187, 262, 16283, 2135, 2524, 379, 25, 198, 2, 2638, 1378, 16244, 364, 13, 19024, ...
3.66
50
# # Copyright 2018 Picovoice 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. # import os from collections import namedtuple from enum import Enum import numpy as np from pocketsphinx import get_model_path from pocketsphinx.pocketsphinx import Decoder from engines import Porcupine from engines import snowboydetect from engines import AudioRecognition, FeatureExtractor SensitivityInfo = namedtuple('SensitivityInfo', 'min, max, step')
[ 2, 198, 2, 15069, 2864, 15085, 709, 2942, 3457, 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, 13,...
3.743083
253
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 20 22:18:58 2020 @author: https://stackoverflow.com/questions/293431/python-object-deleting-itself @editor: thirschbuechler this is probably overkill to alternatively exit a with-context, rather than by exception, but hey, maybe it will be needed, or related to getting rid of the visa-handle within thvisa # for some reason, __enter__ does not work in the with-context """ # NOTE: This is Python 3 code, it should work with python 2, but I haven't tested it. import weakref #https://docs.python.org/3/library/weakref.html if __name__ == '__main__': # test if called as executable, not as library instance = InsaneClass() instance.__enter__() instance.commit_suicide() #print(instance) print(InsaneClass) # pointer print(InsaneClass().__enter__()) # an object print("now, something completely different!") with InsaneClass() as i: i.commit_suicide() print(i)
[ 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, 2892, 2365, 1160, 2534, 25, 1507, 25, 3365, 12131, 198, 198, 31, 9800, 25, 3740, 1378, 25...
2.868195
349
#!/usr/bin/env python # -*- coding: utf-8 -*- """A module containing an algorithm for hand gesture recognition""" import numpy as np import cv2 from typing import Tuple __author__ = "Michael Beyeler" __license__ = "GNU GPL 3.0 or later" def recognize(img_gray): """Recognizes hand gesture in a single-channel depth image This method estimates the number of extended fingers based on a single-channel depth image showing a hand and arm region. :param img_gray: single-channel depth image :returns: (num_fingers, img_draw) The estimated number of extended fingers and an annotated RGB image """ # segment arm region segment = segment_arm(img_gray) # find the hull of the segmented area, and based on that find the # convexity defects (contour, defects) = find_hull_defects(segment) # detect the number of fingers depending on the contours and convexity # defects, then draw defects that belong to fingers green, others red img_draw = cv2.cvtColor(segment, cv2.COLOR_GRAY2RGB) (num_fingers, img_draw) = detect_num_fingers(contour, defects, img_draw) return (num_fingers, img_draw) def segment_arm(frame: np.ndarray, abs_depth_dev: int = 14) -> np.ndarray: """Segments arm region This method accepts a single-channel depth image of an arm and hand region and extracts the segmented arm region. It is assumed that the hand is placed in the center of the image. :param frame: single-channel depth image :returns: binary image (mask) of segmented arm region, where arm=255, else=0 """ height, width = frame.shape # find center (21x21 pixel) region of imageheight frame center_half = 10 # half-width of 21 is 21/2-1 center = frame[height // 2 - center_half:height // 2 + center_half, width // 2 - center_half:width // 2 + center_half] # find median depth value of center region med_val = np.median(center) # try this instead: frame = np.where(abs(frame - med_val) <= abs_depth_dev, 128, 0).astype(np.uint8) # morphological kernel = np.ones((3, 3), np.uint8) frame = cv2.morphologyEx(frame, cv2.MORPH_CLOSE, kernel) # connected component small_kernel = 3 frame[height // 2 - small_kernel:height // 2 + small_kernel, width // 2 - small_kernel:width // 2 + small_kernel] = 128 mask = np.zeros((height + 2, width + 2), np.uint8) flood = frame.copy() cv2.floodFill(flood, mask, (width // 2, height // 2), 255, flags=4 | (255 << 8)) ret, flooded = cv2.threshold(flood, 129, 255, cv2.THRESH_BINARY) return flooded def find_hull_defects(segment: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Find hull defects This method finds all defects in the hull of a segmented arm region. :param segment: a binary image (mask) of a segmented arm region, where arm=255, else=0 :returns: (max_contour, defects) the largest contour in the image and all corresponding defects """ contours, hierarchy = cv2.findContours(segment, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # find largest area contour max_contour = max(contours, key=cv2.contourArea) epsilon = 0.01 * cv2.arcLength(max_contour, True) max_contour = cv2.approxPolyDP(max_contour, epsilon, True) # find convexity hull and defects hull = cv2.convexHull(max_contour, returnPoints=False) defects = cv2.convexityDefects(max_contour, hull) return max_contour, defects def detect_num_fingers(contour: np.ndarray, defects: np.ndarray, img_draw: np.ndarray, thresh_deg: float = 80.0) -> Tuple[int, np.ndarray]: """Detects the number of extended fingers This method determines the number of extended fingers based on a contour and convexity defects. It will annotate an RGB color image of the segmented arm region with all relevant defect points and the hull. :param contours: a list of contours :param defects: a list of convexity defects :param img_draw: an RGB color image to be annotated :returns: (num_fingers, img_draw) the estimated number of extended fingers and an annotated RGB color image """ # if there are no convexity defects, possibly no hull found or no # fingers extended if defects is None: return [0, img_draw] # we assume the wrist will generate two convexity defects (one on each # side), so if there are no additional defect points, there are no # fingers extended if len(defects) <= 2: return [0, img_draw] # if there is a sufficient amount of convexity defects, we will find a # defect point between two fingers so to get the number of fingers, # start counting at 1 num_fingers = 1 # Defects are of shape (num_defects,1,4) for defect in defects[:, 0, :]: # Each defect is an array of four integers. # First three indexes of start, end and the furthest # points respectively # contour is of shape (num_points,1,2) - 2 for point coordinates start, end, far = [contour[i][0] for i in defect[:3]] # draw the hull cv2.line(img_draw, tuple(start), tuple(end), (0, 255, 0), 2) # if angle is below a threshold, defect point belongs to two # extended fingers if angle_rad(start - far, end - far) < deg2rad(thresh_deg): # increment number of fingers num_fingers += 1 # draw point as green cv2.circle(img_draw, tuple(far), 5, (0, 255, 0), -1) else: # draw point as red cv2.circle(img_draw, tuple(far), 5, (0, 0, 255), -1) # make sure we cap the number of fingers return min(5, num_fingers), img_draw def angle_rad(v1, v2): """Angle in radians between two vectors This method returns the angle (in radians) between two array-like vectors using the cross-product method, which is more accurate for small angles than the dot-product-acos method. """ return np.arctan2(np.linalg.norm(np.cross(v1, v2)), np.dot(v1, v2)) def deg2rad(angle_deg): """Convert degrees to radians This method converts an angle in radians e[0,2*np.pi) into degrees e[0,360) """ return angle_deg / 180.0 * np.pi
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 32, 8265, 7268, 281, 11862, 329, 1021, 18342, 9465, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11...
2.491686
2,646
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' // Copyright (c) 2015 Intel Corporation // // 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. ''' """ PanicLogger RAM-tracing """ import sys import time from logger import Logger
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 1003, 15069, 357, 66, 8, 1853, 8180, 10501, 198, 1003, 198, 1003, 49962, 739, 262, 24843, 13789, 11, 10...
3.565217
207
import sys import os from . import filesys MAIN_USAGE_MESSAGE = """ usage: xlab command ... Options: positional arguments: command project """
[ 11748, 25064, 198, 11748, 28686, 198, 198, 6738, 764, 1330, 3696, 893, 198, 198, 5673, 1268, 62, 2937, 11879, 62, 44, 1546, 4090, 8264, 796, 37227, 198, 26060, 25, 2124, 23912, 3141, 2644, 198, 198, 29046, 25, 198, 198, 1930, 1859, 71...
2.833333
54
# Copyright (c) 2021 PaddlePaddle Authors. 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. from .optimizer import Optimizer from .adam import Adam from ..fluid import core from ..fluid import framework from ..fluid.framework import Variable from ..fluid.dygraph import base as imperative_base from collections import Callable import paddle _C_ops = core.ops __all__ = []
[ 2, 15069, 357, 66, 8, 33448, 350, 37382, 47, 37382, 46665, 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...
3.756303
238
from api import app from unittest import TestCase
[ 6738, 40391, 1330, 598, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 628 ]
3.923077
13
# install BeautifulSoup4 before running # # prints out historical data in csv format: # # [date, open, high, low, close, volume] # import re, csv, sys, urllib2 from bs4 import BeautifulSoup # If start date and end date is the same only one value will be returned and # if not the multiple values which can be used to make calculations # # ticker (company symbol) # interval (d (daily), m (monthly), q (quarterly), y (yearly)) # start_date (YYYYMMDD) # end_date (YYYYMMDD) if __name__ == '__main__': main()
[ 2, 2721, 23762, 50, 10486, 19, 878, 2491, 198, 2, 198, 2, 20842, 503, 6754, 1366, 287, 269, 21370, 5794, 25, 198, 2, 198, 2, 685, 4475, 11, 1280, 11, 1029, 11, 1877, 11, 1969, 11, 6115, 60, 198, 2, 198, 11748, 302, 11, 269, 21...
3.029586
169
import sys import io from collections import defaultdict import struct from time import sleep import queue import threading import serial from serial import SerialException RUN_LABELS = ('Time left', 'Temp 1', 'Temp 2', 'Off Goal', 'Temp Change', 'Duty cycle (/30)', 'Heating', 'Cycle', 'Total time', 'Goal temp') MSG_RUN_STATUS = 1 MSG_CONFIG = 2 MSG_STATUS = 3 MSG_LENGTHS = {MSG_RUN_STATUS: 20, MSG_CONFIG: 9, MSG_STATUS: 5} STATE_START = 1 STATE_ACTIVE = 2 STATE_READY = 3 STATE_BOOT = 4 STATE_INIT = 5 STATE_DISCONNECTED = 127 # can't connect to serial HB_CYCLE = 30 def check_connection(fun): return inner
[ 11748, 25064, 198, 11748, 33245, 198, 6738, 17268, 1330, 4277, 11600, 198, 11748, 2878, 198, 6738, 640, 1330, 3993, 198, 11748, 16834, 198, 11748, 4704, 278, 198, 198, 11748, 11389, 198, 6738, 11389, 1330, 23283, 16922, 198, 198, 49, 4944...
2.756637
226
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test that a node receiving many (potentially out of order) blocks exits initial block download (IBD; this occurs once it has passed minimumchainwork) and continues to sync without seizing. """ import random from test_framework.blocktools import create_block, create_coinbase from test_framework.mininode import (CBlockHeader, network_thread_start, P2PInterface, msg_block, msg_headers) from test_framework.test_framework import BitcoinTestFramework from test_framework.util import wait_until, p2p_port NUM_IBD_BLOCKS = 50 if __name__ == '__main__': SyncChainTest().main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 2864, 383, 6185, 6505, 198, 2, 4307, 6169, 739, 262, 17168, 3788, 5964, 11, 766, 262, 19249, 198, 2, 2393, 27975, 45761, 393, 2638, 1378, 2503, 13, 44813, ...
2.516043
374
from django.db import models from djangostagram.users import models as user_model # Create your models here. # This class is used in other models as an inheritance. # An often-used pattern
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 648, 455, 6713, 13, 18417, 1330, 4981, 355, 2836, 62, 19849, 198, 198, 2, 13610, 534, 4981, 994, 13, 198, 198, 2, 770, 1398, 318, 973, 287, 584, 4981, 355, 281, 24155, 13, ...
3.660377
53
from guillotina.contrib.workflows.interfaces import IWorkflowChangedEvent from guillotina.events import ObjectEvent from zope.interface import implementer
[ 6738, 915, 359, 313, 1437, 13, 3642, 822, 13, 1818, 44041, 13, 3849, 32186, 1330, 314, 12468, 11125, 31813, 9237, 198, 6738, 915, 359, 313, 1437, 13, 31534, 1330, 9515, 9237, 198, 6738, 1976, 3008, 13, 39994, 1330, 3494, 263, 628 ]
3.804878
41
""" Suppress COVID EHR vaccine concepts. Original Issues: DC-1692 """ # Python imports import logging # Project imports from cdr_cleaner.cleaning_rules.deid.concept_suppression import AbstractBqLookupTableConceptSuppression from constants.cdr_cleaner import clean_cdr as cdr_consts from common import JINJA_ENV, CDM_TABLES from utils import pipeline_logging # Third party imports from google.cloud.exceptions import GoogleCloudError LOGGER = logging.getLogger(__name__) SUPPRESSION_RULE_CONCEPT_TABLE = 'covid_vaccine_concepts' COVID_VACCINE_CONCEPT_QUERY = JINJA_ENV.from_string(""" CREATE OR REPLACE TABLE `{{project_id}}.{{sandbox_id}}.{{concept_suppression_lookup_table}}` AS with covid_vacc as ( SELECT * FROM `{{project_id}}.{{dataset_id}}.concept` WHERE ( -- done by name and vocab -- REGEXP_CONTAINS(concept_name, r'(?i)(COVID)') AND REGEXP_CONTAINS(concept_name, r'(?i)(VAC)') AND vocabulary_id not in ('PPI') ) OR ( -- done by code and vocab -- REGEXP_CONTAINS(concept_code, r'(207)|(208)|(210)|(211)|(212)') and vocabulary_id = 'CVX' ) OR ( -- done by code and vocab -- REGEXP_CONTAINS(concept_code, r'(91300)|(91301)|(91302)|(91303)|(91304)') and vocabulary_id = 'CPT4' ) ), concepts_via_cr as ( select distinct c.* from `{{project_id}}.{{dataset_id}}.concept`as c left join `{{project_id}}.{{dataset_id}}.concept_relationship` on c.concept_id = concept_id_1 where concept_id_2 in (select concept_id from covid_vacc) # and concept_id_1 not in (select concept_id from covid_vacc) and ( relationship_id not in ('Subsumes', 'RxNorm dose form of', 'Dose form group of', 'RxNorm - SPL') OR (relationship_id = 'RxNorm - SPL' and REGEXP_CONTAINS(concept_name, r'(?i)(COVID)')) ) ), concepts_via_ca as ( select c.* from `{{project_id}}.{{dataset_id}}.concept`as c left join `{{project_id}}.{{dataset_id}}.concept_ancestor` as ca on c.concept_id = ca.descendant_concept_id where ca.ancestor_concept_id in (select concept_id from covid_vacc) ) select distinct * from covid_vacc union distinct select distinct * from concepts_via_ca union distinct select distinct * from concepts_via_cr """) if __name__ == '__main__': import cdr_cleaner.args_parser as parser import cdr_cleaner.clean_cdr_engine as clean_engine ARGS = parser.parse_args() pipeline_logging.configure(level=logging.DEBUG, add_console_handler=True) if ARGS.list_queries: clean_engine.add_console_logging() query_list = clean_engine.get_query_list( ARGS.project_id, ARGS.dataset_id, ARGS.sandbox_dataset_id, [(CovidEHRVaccineConceptSuppression,)]) for query in query_list: LOGGER.info(query) else: clean_engine.add_console_logging(ARGS.console_log) clean_engine.clean_dataset(ARGS.project_id, ARGS.dataset_id, ARGS.sandbox_dataset_id, [(CovidEHRVaccineConceptSuppression,)])
[ 37811, 198, 15979, 601, 7375, 11008, 412, 17184, 12319, 10838, 13, 198, 198, 20556, 22852, 25, 6257, 12, 1433, 5892, 198, 37811, 198, 198, 2, 11361, 17944, 198, 11748, 18931, 198, 198, 2, 4935, 17944, 198, 6738, 269, 7109, 62, 27773, ...
2.341705
1,314
import pydbhub from typing import Any, Dict, List, Tuple from json.decoder import JSONDecodeError import requests import io def send_request_json(query_url: str, data: Dict[str, Any]) -> Tuple[List[Any], str]: """ send_request_json sends a request to DBHub.io, formatting the returned result as JSON Parameters ---------- query_url : str url of the API endpoint data : Dict[str, Any] data to be processed to the server. Returns ------- Tuple[List[Any], str] The returned data is - a list of JSON object. - a string describe error if occurs """ try: headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'} response = requests.post(query_url, data=data, headers=headers) response.raise_for_status() return response.json(), None except JSONDecodeError as e: return None, e.args[0] except TypeError as e: return None, e.args[0] except requests.exceptions.HTTPError as e: try: return response.json(), e.args[0] except JSONDecodeError: return None, e.args[0] except requests.exceptions.RequestException as e: cause = e.args(0) return None, str(cause.args[0]) def send_request(query_url: str, data: Dict[str, Any]) -> Tuple[List[bytes], str]: """ send_request sends a request to DBHub.io. Parameters ---- query_url : str url of the API endpoint data : Dict[str, Any] data to be processed to the server.------ Returns ------- List[bytes] database file is returned as a list of bytes """ try: headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'} response = requests.post(query_url, data=data, headers=headers) response.raise_for_status() return response.content, None except requests.exceptions.HTTPError as e: return None, e.args[0] except requests.exceptions.RequestException as e: cause = e.args(0) return None, str(cause.args[0]) def send_upload(query_url: str, data: Dict[str, Any], db_bytes: io.BufferedReader) -> Tuple[List[Any], str]: """ send_upload uploads a database to DBHub.io. Parameters ---------- query_url : str url of the API endpoint. data : Dict[str, Any] data to be processed to the server. db_bytes : io.BufferedReader A buffered binary stream of the database file. Returns ------- Tuple[List[Any], str] The returned data is - a list of JSON object. - a string describe error if occurs """ try: headers = {'User-Agent': f'pydbhub v{pydbhub.__version__}'} files = {"file": db_bytes} response = requests.post(query_url, data=data, headers=headers, files=files) response.raise_for_status() if response.status_code != 201: # The returned status code indicates something went wrong try: return response.json(), str(response.status_code) except JSONDecodeError: return None, str(response.status_code) return response.json(), None except requests.exceptions.HTTPError as e: try: return response.json(), e.args[0] except JSONDecodeError: return None, e.args[0] except requests.exceptions.RequestException as e: cause = e.args(0) return None, str(cause.args[0])
[ 11748, 279, 5173, 34369, 549, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 7343, 11, 309, 29291, 198, 6738, 33918, 13, 12501, 12342, 1330, 19449, 10707, 1098, 12331, 198, 11748, 7007, 198, 11748, 33245, 628, 198, 4299, 3758, 62, 2592...
2.412983
1,448
import pytest from calcscore import round_score # you'll be picking what teams make it to the next round # - so picking 32, then 16, then 8, 4, 2, 1...i.e. round 1-6 winners # teams will have a name & a seed # seed doesn't change, so maybe make that not passed around w/ results
[ 11748, 12972, 9288, 198, 6738, 42302, 26675, 1330, 2835, 62, 26675, 198, 198, 2, 345, 1183, 307, 10868, 644, 3466, 787, 340, 284, 262, 1306, 2835, 198, 2, 220, 220, 532, 523, 10868, 3933, 11, 788, 1467, 11, 788, 807, 11, 604, 11, ...
3.357143
84
import unittest from operator import attrgetter import obonet from pyobo import SynonymTypeDef, get from pyobo.struct import Reference from pyobo.struct.struct import ( iterate_graph_synonym_typedefs, iterate_graph_typedefs, iterate_node_parents, iterate_node_properties, iterate_node_relationships, iterate_node_synonyms, iterate_node_xrefs, ) from tests.constants import TEST_CHEBI_OBO_PATH
[ 11748, 555, 715, 395, 198, 6738, 10088, 1330, 708, 81, 1136, 353, 198, 198, 11748, 909, 36823, 198, 198, 6738, 12972, 20391, 1330, 16065, 5177, 6030, 7469, 11, 651, 198, 6738, 12972, 20391, 13, 7249, 1330, 20984, 198, 6738, 12972, 20391...
2.934783
138
# -*- coding: utf-8 -*- # + ## Utilidades comunes entre places y OSM. # + import csv import ast import codecs from math import cos, asin, sqrt # + # - import pandas as pd def distance(lat1, lon1, lat2, lon2): """ El resultado de la medicin de distancia esta en kilometros. """ p = 0.017453292519943295 #Pi/180 a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2 return 12742 * asin(sqrt(a)) """ El proceso es muy pesado y no es posible hacer el ananlisis con toda la data de bogot, el nmero de registros es demasiado grande para caber en memoria. El uso correcto es filtrar los datos antes de hacer el cross join. """
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 1343, 198, 2235, 7273, 346, 312, 2367, 401, 4015, 920, 260, 4113, 331, 7294, 44, 13, 198, 198, 2, 1343, 198, 11748, 269, 21370, 198, 11748, 6468, 198, 11748, 40481,...
2.367893
299
#This script Imports Game Data from ESPN, and Odds from the ODDS-API, and then imports them into a MySQL table, example in workbench here https://puu.sh/HOKCj/ce199eec8e.png import mysql.connector import requests import json import datetime import time #Connection to the MYSQL Server. mydb = mysql.connector.connect( host="", user="", password="", database="basketbet_data" ) mycursor = mydb.cursor() #Games List. allGames=[] #Gets the game Data from ESPN API given the link. #Gets the Odds from the ODDS-API. #Block to keep the script running then sleep for time 300 with counter set at 72 for Games every 5min | Odds every 6hr. counter=72 startTime = time.time() while True: #Today, Yesterday and Tomorrow. today = datetime.date.today() yesterday = today + datetime.timedelta(days=-1) tomorrow = today + datetime.timedelta(days=1) #Removing the - from the dates for the URLs, then making the URLs. todayShort = str(today).replace('-', '') yesterdayShort = str(yesterday).replace('-', '') tomorrowShort = str(tomorrow).replace('-', '') yesterdayUrl = "http://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard?dates=" + yesterdayShort + '-' + yesterdayShort todayUrl = "http://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard?dates=" + todayShort + '-' + todayShort tomorrowUrl = "http://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard?dates=" + tomorrowShort + '-' + tomorrowShort newGetter(yesterdayUrl) newGetter(todayUrl) newGetter(tomorrowUrl) #Inserting or updating the table in MYSQL with the games. c=0 updateCount=0 newGameCount=0 while c < len(allGames): query_string = 'SELECT * FROM basketbet_data.all_games WHERE Game_ID = %s' gameID = (str(allGames[c][0]),) mycursor.execute(query_string, gameID) if mycursor.fetchone(): updateCount+=1 query_list = [allGames[c][1], allGames[c][2], allGames[c][4], allGames[c][5], allGames[c][3], allGames[c][6], allGames[c][7], allGames[c][8], allGames[c][9], allGames[c][0]] query_string = 'UPDATE all_games SET Game_Name = %s, Home_Team = %s, Away_Team = %s, Away_Score = %s, Home_Score = %s, Game_Date = %s, Game_Time = %s, Game_Period = %s, Game_Status = %s WHERE (Game_ID = %s)' mycursor.execute(query_string, query_list) mydb.commit() else: newGameCount+=1 query_string = "INSERT INTO basketbet_data.all_games (Game_ID, Game_Name, Home_Team, Home_Odds, Home_Score, Away_Team, Away_Odds, Away_Score, Game_Date, Game_Time, Game_Period, Game_Status) VALUES (%s, %s, %s, 0, %s, %s, 0, %s, %s, %s, %s, %s)" mycursor.execute(query_string, allGames[c]) mydb.commit() c+=1 #Prints to console what games were updated and what new games were inserted. print('----------------------------------------') print(str(updateCount) + ' GAMES UPDATED, and ' + str(newGameCount) + ' NEW GAMES inserted.') print('----------------------------------------') allGames=[] #Counter for the Odds script. if counter==72: oddsGetter() counter=0 else: counter+=1 print('\n') time.sleep(300 - ((time.time() - startTime) % 300))
[ 2, 1212, 4226, 1846, 3742, 3776, 6060, 422, 10409, 11, 290, 20664, 82, 422, 262, 31245, 5258, 12, 17614, 11, 290, 788, 17944, 606, 656, 257, 33476, 3084, 11, 1672, 287, 670, 26968, 994, 3740, 1378, 79, 12303, 13, 1477, 14, 39, 11380...
2.405726
1,432
"""Tests for neurodocker.main""" # Author: Jakub Kaczmarzyk <jakubk@mit.edu> from __future__ import absolute_import, unicode_literals import sys import pytest from neurodocker.neurodocker import create_parser, parse_args, main
[ 37811, 51, 3558, 329, 7669, 45986, 13, 12417, 37811, 198, 2, 6434, 25, 25845, 549, 509, 330, 89, 3876, 46355, 1279, 73, 461, 549, 74, 31, 2781, 13, 15532, 29, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 28000, 1098...
3.064935
77
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2020 The Project U-Ray Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC ''' FDCE Primitive: D Flip-Flop with Clock Enable and Asynchronous Clear FDPE Primitive: D Flip-Flop with Clock Enable and Asynchronous Preset FDRE Primitive: D Flip-Flop with Clock Enable and Synchronous Reset FDSE Primitive: D Flip-Flop with Clock Enable and Synchronous Set LDCE Primitive: Transparent Data Latch with Asynchronous Clear and Gate Enable LDPE Primitive: Transparent Data Latch with Asynchronous Preset and Gate Enable ''' from prims import isff, isl from utils.segmaker import Segmaker segmk = Segmaker("design.bits", bits_per_word=16) def loadtop(): ''' i,prim,loc,bel 0,FDPE,SLICE_X12Y100,C5FF 1,FDPE,SLICE_X15Y100,A5FF 2,FDPE_1,SLICE_X16Y100,B5FF 3,LDCE_1,SLICE_X17Y100,BFF ''' f = open('top.txt', 'r') f.readline() ret = {} for l in f: i, prim, loc, bel, init = l.split(",") i = int(i) init = int(init) ret[loc] = (i, prim, loc, bel, init) return ret top = loadtop() print("Loading tags from design.txt") with open("design.txt", "r") as f: for line in f: ''' puts $fp "$type $tile $grid_x $grid_y $ff $bel_type $used $usedstr" CLEM CLEM_X10Y137 30 13 SLICE_X13Y137/AFF REG_INIT 1 FDRE CLEM CLEM_X10Y137 30 13 SLICE_X12Y137/D2FF FF_INIT 0 ''' line = line.split() tile_type = line[0] tile_name = line[1] grid_x = line[2] grid_y = line[3] # Other code uses BEL name # SLICE_X12Y137/D2FF site_ff_name = line[4] site, ff_name = site_ff_name.split('/') ff_type = line[5] used = int(line[6]) cel_prim = None cel_name = None if used: cel_name = line[7] cel_prim = line[8] cinv = int(line[9]) init = vs2i(line[10]) # A B C D E F G H which = ff_name[0] # LUT6 vs LUT5 FF is2 = '2' in ff_name if used: segmk.add_site_tag(site, "%s.ZINI" % ff_name, 1 ^ init) ''' On name: The primitives you listed have a control input to set the FF value to zero (clear/reset), the other three primitives have a control input that sets the FF value to one. Z => inversion ''' segmk.add_site_tag(site, "%s.ZRST" % ff_name, cel_prim in ('FDRE', 'FDCE', 'LDCE')) segmk.compile() segmk.write()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 12131, 220, 383, 4935, 471, 12, 19591, 46665, 13, 198, 2, 198, 2, 5765, 286, 42...
2.075342
1,314
from typing import Callable import numpy as np from hmc.integrators.states.leapfrog_state import LeapfrogState from hmc.integrators.fields import riemannian from hmc.linalg import solve_psd
[ 6738, 19720, 1330, 4889, 540, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 289, 23209, 13, 18908, 18942, 13, 27219, 13, 293, 499, 49956, 62, 5219, 1330, 33927, 49956, 9012, 198, 6738, 289, 23209, 13, 18908, 18942, 13, 25747,...
3.216667
60
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 2017 Bitcraze AB # # Crazyflie Python Library # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """ Example scipts that allows a user to "push" the Crazyflie 2.0 around using your hands while it's hovering. This examples uses the Flow and Multi-ranger decks to measure distances in all directions and tries to keep away from anything that comes closer than 0.2m by setting a velocity in the opposite direction. The demo is ended by either pressing Ctrl-C or by holding your hand above the Crazyflie. For the example to run the following hardware is needed: * Crazyflie 2.0 * Crazyradio PA * Flow deck * Multiranger deck """ import logging import sys import time import cflib.crtp from cflib.crazyflie import Crazyflie from cflib.crazyflie.syncCrazyflie import SyncCrazyflie from cflib.positioning.motion_commander import MotionCommander from cflib.utils.multiranger import Multiranger import matplotlib.pyplot as plt from matplotlib.pyplot import figure import matplotlib.patches as patches URI = 'radio://0/80/2M' if len(sys.argv) > 1: URI = sys.argv[1] # Only output errors from the logging framework logging.basicConfig(level=logging.ERROR) if __name__ == '__main__': # Initialize the low-level drivers (don't list the debug drivers) cflib.crtp.init_drivers(enable_debug_driver=False) rangeArray = [] cf = Crazyflie(rw_cache='./cache') with SyncCrazyflie(URI, cf=cf) as scf: with MotionCommander(scf) as motion_commander: with Multiranger(scf) as multiranger: motion_commander.start_turn_left(90) rangeArray.append(multiranger.front) time.sleep(0.05) plt.plot(rangeArray)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 220, 220, 220, 8614, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1427, 220, 4808, 11593, ...
2.78882
966
from django.utils.translation import ugettext_lazy as _ USER_TYPE_STAFF = 'STAFF' USER_TYPE_ADMIN = 'ADMIN' USER_TYPE_BARBER = 'BARBER' USER_TYPE_CHOICES = ( (USER_TYPE_STAFF, _('Dev')), (USER_TYPE_ADMIN, _('Admin')), (USER_TYPE_BARBER, _('Barber')), )
[ 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 628, 198, 29904, 62, 25216, 62, 2257, 32, 5777, 796, 705, 2257, 32, 5777, 6, 198, 29904, 62, 25216, 62, 2885, 23678, 796, 705, 2885, 23678, 6...
2.180328
122
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from common.chrome_proxy_shared_page_state import ChromeProxySharedPageState from telemetry.page import page as page_module from telemetry import story
[ 2, 15069, 1584, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 6738,...
3.91358
81
""" in this example we want to create a user credentials database with: user_id & password logger showing connection logs, DB version, errors during fetching & executing """ import sqlite3 from lessons.sqlite_example.log import create as create_logger if "__main__" == __name__: import os log_file = os.path.dirname(os.path.abspath(__file__)) + '\\log.txt' db_file = os.path.dirname(os.path.abspath(__file__)) + '\\db.db' log = create_logger(log_file=log_file) database = DataBaseExtention(db_file, log) # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # database.execute(database.command.drop_table.format('users')) # database.execute(database.command.create_users_table) # database.execute(database.command.add_user.format('cs0008', '123123a')) # database.execute(database.command.add_user.format('af0006', '123123a')) # database.execute(database.command.add_user.format('jh0003', '123123a')) # database.execute(database.command.add_user.format('kb0004', '123123a')) # database.execute(database.command.add_user.format('op0001', '123123a')) # database.execute(database.command.add_user.format('gv0001', '123123a')) # database.execute(database.command.add_user.format('pm0001', '123123a')) # database.execute(database.command.add_user.format('ps0001', '123123a')) # database.execute(database.command.add_user.format('qa0000', '123123a')) # user_credentials = database.get_user_credentials(id='14') # database.connection.commit() # database.connection.close() # print(user_credentials) # create a simple database with websites table that includes ( # url: varchar(1024), # popularity_score: integer, # monthly_visitations: integer # ) # database.command.create_websites_table = ''' # CREATE TABLE IF NOT EXISTS websites ( # id INTEGER PRIMARY KEY AUTOINCREMENT, # url TEXT, # popularity_score INTEGER, # monthly_visitations INTEGER # ) # ''' # database.command.add_website = 'INSERT INTO websites (url, popularity_score, monthly_visitations) VALUES (\'{}\', \'{}\', \'{}\');' # database.execute(database.command.create_websites_table) # database.execute(database.command.add_website.format('https://www.google.com', 5, 4000000000)) # database.execute(database.command.add_website.format('https://www.ynet.com', 3, 5000000)) # database.execute(database.command.add_website.format('https://www.youtube.com', 6, 1300000000)) # database.execute(database.command.add_website.format('https://www.python.org', 5, 1000000)) # database.command.get_site = 'SELECT url, popularity_score, monthly_visitations FROM websites WHERE url = \'{}\';' # url, popularity, visitations = database.fetch(database.command.get_site.format('https://www.python.org'))[0] # # print(url, popularity, visitations) database.export_from_table_to_file( table='websites', file_name='exported.csv', titles=('id', 'url', 'popularity_score', 'monthly_visitations') ) # database.connection.commit() database.connection.close()
[ 37811, 198, 259, 428, 1672, 356, 765, 284, 2251, 257, 2836, 18031, 6831, 351, 25, 198, 7220, 62, 312, 1222, 9206, 198, 6404, 1362, 4478, 4637, 17259, 11, 20137, 2196, 11, 8563, 1141, 21207, 278, 1222, 23710, 198, 37811, 198, 198, 1174...
2.731201
1,157
from django.urls import re_path from projectx.consumers import UserWebSocketConsumer from .consumers import UserWebSocketConsumer websocket_urlpatterns = [ re_path(r"^ws/$", UserWebSocketConsumer.as_asgi()), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 302, 62, 6978, 198, 198, 6738, 1628, 87, 13, 5936, 31260, 1330, 11787, 13908, 39105, 49106, 198, 198, 6738, 764, 5936, 31260, 1330, 11787, 13908, 39105, 49106, 198, 198, 732, 1443, 5459, 62, 6371,...
2.972603
73
from django.utils.translation import ugettext_lazy as _ from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from .conf import settings if settings.ALDRYN_SEARCH_REGISTER_APPHOOK: apphook_pool.register(AldrynSearchApphook)
[ 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 198, 198, 6738, 269, 907, 13, 1324, 62, 8692, 1330, 16477, 4090, 381, 198, 6738, 269, 907, 13, 1324, 25480, 62, 7742, 1330, 598, 25480, 62, 7...
2.842697
89
import pandas as pd from openpyxl import Workbook from openpyxl.chart import BarChart, Reference wb = Workbook() ws = wb.active df = pd.read_csv('population.csv') ws.append(df.columns.tolist()) for row in df.values: ws.append(list(row)) row_length = 1 + len(df.values) values = Reference(ws, min_col=2, max_col=2, min_row=1, max_row=row_length) categories = Reference(ws, min_col=1, min_row=2, max_row=row_length) chart = BarChart() chart.type = 'bar' chart.style = 11 chart.shape = 4 chart.title = '' chart.x_axis.title = '' chart.y_axis.title = '' chart.add_data(values, titles_from_data=True) chart.set_categories(categories) ws.add_chart(chart, 'A9') wb.save('population_horizontal.xlsx')
[ 11748, 19798, 292, 355, 279, 67, 201, 198, 6738, 1280, 9078, 87, 75, 1330, 5521, 2070, 201, 198, 6738, 1280, 9078, 87, 75, 13, 40926, 1330, 2409, 45488, 11, 20984, 201, 198, 201, 198, 39346, 796, 5521, 2070, 3419, 201, 198, 18504, 7...
2.393443
305
from changes.api.serializer import Serializer, register from changes.models.log import LogSource
[ 6738, 2458, 13, 15042, 13, 46911, 7509, 1330, 23283, 7509, 11, 7881, 198, 6738, 2458, 13, 27530, 13, 6404, 1330, 5972, 7416, 628 ]
4.26087
23
# Copyright (c) 2021-2022, NVIDIA CORPORATION. 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. import argparse import nibabel as nib import nrrd import numpy as np parser = argparse.ArgumentParser("Convert nrrd label to nifti with reference image file for affine") parser.add_argument("--input_path", help="Input nrrd path", type=str) parser.add_argument("--reference_path", help="Reference image path", type=str) parser.add_argument("--output_path", help="Output nifti path", type=str) args = parser.parse_args() img = nib.load(args.reference_path) img_affine = img.affine nrrd = nrrd.read(args.input_path) data = np.flip(nrrd[0], axis=1) nft_img = nib.Nifti1Image(data, img_affine) nib.save(nft_img, args.output_path)
[ 2, 15069, 357, 66, 8, 33448, 12, 1238, 1828, 11, 15127, 23929, 44680, 6234, 13, 220, 1439, 2489, 10395, 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...
3.186701
391
from setuptools import setup import io import os import re version_re = re.compile(r'^__version__ = "([^"]*)"$') # Find the version number. with open('rst2ctags.py', 'r') as f: for line in f: line = line.rstrip() m = version_re.match(line) if m: version = m.group(1) break else: raise RuntimeError("Couldn't find version string in rst2ctags.py") # Load the description. readme_path = os.path.join(os.path.dirname(__file__), 'README.rst') with io.open(readme_path, encoding='utf-8') as f: long_description = f.read() setup( name='rst2ctags', description='Generates ctags-compatible output for the sections of a ' 'reStructuredText document.', long_description=long_description, license='BSD', author='John Szakmeister', author_email='john@szakmeister.net', url='https://github.com/jszakmeister/rst2ctags', version=version, py_modules=['rst2ctags'], zip_safe=True, entry_points={ 'console_scripts': [ 'rst2ctags = rst2ctags:cli_main', ], }, classifiers=[ 'License :: OSI Approved :: BSD License', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development', 'Topic :: Text Processing', 'Topic :: Text Processing :: Indexing', 'Topic :: Utilities', ] )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 11748, 33245, 198, 11748, 28686, 198, 11748, 302, 628, 198, 9641, 62, 260, 796, 302, 13, 5589, 576, 7, 81, 6, 61, 834, 9641, 834, 796, 366, 26933, 61, 8973, 9, 16725, 3, 11537, 628, 1...
2.360902
665
#!/usr/bin/env python # Copyright (C) 2018 rerobots, 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 # # 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. """Command-line interface """ import argparse import json import logging import logging.handlers import os import os.path import subprocess import sys import uuid import yaml from aiohttp.client_exceptions import ClientConnectorError as ConnectionError from .core import WorkspaceInstance from .mgmt import get_local_config, add_key, add_ssh_path, list_local_keys from .mgmt import find_wd, modify_local, rm_wd from .api import HSAPIClient from .err import Error as HSError from .addons import camera_main, stop_cameras from .addons import add_cmdsh, rm_cmdsh, add_vnc, rm_vnc, add_mistyproxy, rm_mistyproxy if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 34, 8, 2864, 302, 22609, 1747, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, ...
3.330729
384
"""Realty Info""" import os import requests from dotenv import load_dotenv from fastapi import APIRouter, Depends import sqlalchemy from pydantic import BaseModel, SecretStr from app import config from app.walk_score import * load_dotenv() router = APIRouter() headers = {'x-rapidapi-key': os.getenv('api_key'), 'x-rapidapi-host': os.getenv('host') }
[ 37811, 15633, 774, 14151, 37811, 198, 198, 11748, 28686, 198, 11748, 7007, 198, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 6738, 3049, 15042, 1330, 3486, 4663, 39605, 11, 2129, 2412, 198, 11748, 44161, 282, 26599, 198, 67...
2.751825
137
from __future__ import print_function import time import weeutil.weeutil import weewx.manager import weewx.xtypes archive_sqlite = {'database_name': '/home/weewx/archive/weepwr.sdb', 'driver': 'weedb.sqlite'} archive_mysql = {'database_name': 'weewx', 'user': 'weewx', 'password': 'weewx', 'driver': 'weedb.mysql'} sql_str = "SELECT %s(%s), MIN(usUnits), MAX(usUnits) FROM %s " \ "WHERE dateTime > ? AND dateTime <= ?" % ('avg', 'outTemp', 'archive') timespan = weeutil.weeutil.TimeSpan(1573245000, 1573246800) timespan = weeutil.weeutil.TimeSpan(1573245000, 1573245000 + 600) print('timespan=', timespan) with weewx.manager.Manager.open(archive_sqlite) as db_manager: interpolate_dict = { 'aggregate_type': 'diff', 'obs_type': 'ch8_a_energy2', 'table_name': db_manager.table_name, 'start': timespan.start, 'stop': timespan.stop, } SQL_TEMPLATE = "SELECT (ch8_a_energy2 - (SELECT ch8_a_energy2 FROM archive WHERE dateTime=%(start)s)) / (%(stop)s - %(start)s) FROM archive WHERE dateTime=%(stop)s;" SQL_TEMPLATE = """Select a.dateTime as StartTime , b.dateTime as EndTime , b.dateTime-a.dateTime as TimeChange , b.ch8_a_energy2-a.ch8_a_energy2 as ValueChange FROM archive a Inner Join archive b ON b.dateTime>=1573245000 AND b.dateTime<=(1573245000 + 600)""" SQL_TEMPLATE = """Select a.dateTime as StartTime, b.datetime as EndTime, b.dateTime-a.dateTime as TimeChange, b.ch8_a_energy2-a.ch8_a_energy2 as ValueChange FROM archive a, archive b WHERE b.dateTime = (Select MAX(c.dateTime) FROM archive c WHERE c.dateTime<=(1573245000+600)) AND a.dateTime = (SELECT MIN(dateTime) FROM archive WHERE dateTime>=1573245000);""" SQL_TEMPLATE = """Select a.dateTime as StartTime, b.datetime as EndTime, b.dateTime-a.dateTime as TimeChange, b.ch8_a_energy2-a.ch8_a_energy2 as ValueChange FROM archive a, archive b WHERE b.dateTime = (Select MAX(dateTime) FROM archive WHERE dateTime<=(1573245000+600)) AND a.dateTime = (SELECT MIN(dateTime) FROM archive WHERE dateTime>=1573245000);""" SQL_TEMPLATE = "SELECT (b.%(obs_type)s - a.%(obs_type)s) / (b.dateTime-a.dateTime) "\ "FROM archive a, archive b "\ "WHERE b.dateTime = (SELECT MAX(dateTime) FROM archive WHERE dateTime <= %(stop)s) "\ "AND a.dateTime = (SELECT MIN(dateTime) FROM archive WHERE dateTime >= %(start)s);" sql_stmt = SQL_TEMPLATE % interpolate_dict print(sql_stmt) # Get the number of records with db_manager.connection.cursor() as cursor: for row in cursor.execute(sql_stmt): print(row)
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 640, 198, 198, 11748, 43671, 22602, 13, 732, 68, 22602, 198, 11748, 356, 413, 87, 13, 37153, 198, 11748, 356, 413, 87, 13, 742, 9497, 198, 198, 17474, 62, 25410, 578, 796, 1...
2.44506
1,083
#!/usr/bin/env pytest-3 from fastapi.testclient import TestClient from fast_lemon_api import app client = TestClient(app) neworder = { "isin": "blablablabla", "limit_price": 0.2, "side": "buy", "quantity": 1, "valid_until": 1996943663, "status": "open" } order_id = None
[ 2, 48443, 14629, 14, 8800, 14, 24330, 12972, 9288, 12, 18, 198, 198, 6738, 3049, 15042, 13, 9288, 16366, 1330, 6208, 11792, 198, 198, 6738, 3049, 62, 293, 2144, 62, 15042, 1330, 598, 198, 198, 16366, 796, 6208, 11792, 7, 1324, 8, 62...
2.313433
134
#!/bin/python2 import collections import re import subprocess import sys PUC = "../pamu2fcfg/pamu2fcfg" resident = ["", "-r"] presence = ["", "-P"] pin = ["", "-N"] verification = ["", "-V"] Credential = collections.namedtuple("Credential", "keyhandle pubkey attributes oldformat") sshformat = 0 # Single credentials print >> sys.stderr, "Generating single credentials" for r in resident: for p in presence: for n in pin: for v in verification: filename = "credentials/new_" + r + p + v + n print >> sys.stderr, "Generating " + filename + ".templ" line = subprocess.check_output([PUC, "-u@USERNAME@", r, p, v, n]) matches = re.match(r'^.*?:(.*?),(.*?),es256,(.*)', line, re.M) with open(filename + ".templ", "w") as outfile: outfile.write(line) credentials = [Credential(keyhandle = matches.group(1), pubkey = matches.group(2), attributes = matches.group(3), oldformat = 0)] print_test_case(filename + ".cred", sshformat, credentials) # Double credentials print >> sys.stderr, "Generating double credentials" for r in resident: for p in presence: for n in pin: for v in verification: filename = "credentials/new_double_" + r + p + v + n print >> sys.stderr, "Generating " + filename + ".templ" line = subprocess.check_output([PUC, "-u@USERNAME@", r, p, v, n]) matches = re.match(r'^.*?:(.*?),(.*?),es256,(.*)', line, re.M) with open(filename + ".templ", "w") as outfile: outfile.write(line) credentials = [Credential(keyhandle = matches.group(1), pubkey = matches.group(2), attributes = matches.group(3), oldformat = 0)] line = subprocess.check_output([PUC, "-n", r, p, v, n]) matches = re.match(r'^.*?:(.*?),(.*?),es256,(.*)', line, re.M) with open(filename + ".templ", "a") as outfile: outfile.write(line) credentials += [Credential(keyhandle = matches.group(1), pubkey = matches.group(2), attributes = matches.group(3), oldformat = 0)] print_test_case(filename + ".cred", sshformat, credentials) # Mixed credentials print >> sys.stderr, "Mixed double credentials" options = [("", ""), ("", "-P"), ("-P", ""), ("-P", "-P")] for p1, p2 in options: filename = "credentials/new_mixed_" + p1 +"1" + p2 + "2" print >> sys.stderr, "Generating " + filename + ".templ" line = subprocess.check_output([PUC, "-u@USERNAME@", p1]) matches = re.match(r'^.*?:(.*?),(.*?),es256,(.*)', line, re.M) with open(filename + ".templ", "w") as outfile: outfile.write(line) credentials = [Credential(keyhandle = matches.group(1), pubkey = matches.group(2), attributes = matches.group(3), oldformat = 0)] line = subprocess.check_output([PUC, "-n", p2]) matches = re.match(r'^.*?:(.*?),(.*?),es256,(.*)', line, re.M) with open(filename + ".templ", "a") as outfile: outfile.write(line) credentials += [Credential(keyhandle = matches.group(1), pubkey = matches.group(2), attributes = matches.group(3), oldformat = 0)] print_test_case(filename + ".cred", sshformat, credentials)
[ 2, 48443, 8800, 14, 29412, 17, 198, 198, 11748, 17268, 198, 11748, 302, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 198, 5105, 34, 796, 366, 40720, 79, 321, 84, 17, 69, 37581, 14, 79, 321, 84, 17, 69, 37581, 1, 198, 198, 8154,...
1.936721
2,007
# Copyright 2016 The TensorFlow Authors. 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. # ============================================================================== """Affine Scalar Tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.distributions.python.ops.bijectors.affine_scalar import AffineScalar from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops.distributions.bijector_test_util import assert_scalar_congruency from tensorflow.python.platform import test if __name__ == "__main__": test.main()
[ 2, 15069, 1584, 383, 309, 22854, 37535, 46665, 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, ...
3.757764
322
import os import subprocess import json import urllib.request from mule.util import os_util from mule.util import file_util from mule.util import time_util from mule.util import s3_util from mule.util import semver_util import platform def install_node(data_dir, bin_dir, channel, node_package_version='latest'): """ Download and install algod. """ node_package_dir = file_util.ensure_folder(f"/tmp/algod-pkg-{time_util.get_timestamp()}") data_dir = file_util.ensure_folder(data_dir) bin_dir = file_util.ensure_folder(bin_dir) os_type = os_util.get_os_type() cpu_arch_type = os_util.get_cpu_arch_type() if node_package_version == 'latest': if channel == 'test': node_package_version = get_latest_package_version('node', 'stable', os_type, cpu_arch_type) else: node_package_version = get_latest_package_version('node', channel, os_type, cpu_arch_type) print(f"Installing {channel} node package version {node_package_version} to:\n\tbin_dir: {bin_dir}\n\tdata_dir: {data_dir}") node_package_url = build_algo_release_url('node', channel, os_type, cpu_arch_type, node_package_version) if channel == 'test': node_package_url = build_algo_release_url('node', 'stable', os_type, cpu_arch_type, node_package_version) node_package_tar_path = f"{node_package_dir}/node_package.tar.gz" _ = urllib.request.urlretrieve(node_package_url, node_package_tar_path) file_util.decompressTarfile(node_package_tar_path, f"{node_package_dir}") file_util.mv_folder_contents(f"{node_package_dir}/data", data_dir) file_util.mv_folder_contents(f"{node_package_dir}/bin", bin_dir) if channel == 'stable': file_util.copy_file( os.path.join(node_package_dir, "genesis/mainnet/genesis.json"), os.path.join(data_dir, 'genesis.json') ) else: file_util.copy_file( os.path.join(node_package_dir, f"genesis/{channel}net/genesis.json"), os.path.join(data_dir, 'genesis.json') )
[ 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 33918, 198, 11748, 2956, 297, 571, 13, 25927, 198, 6738, 285, 2261, 13, 22602, 1330, 28686, 62, 22602, 198, 6738, 285, 2261, 13, 22602, 1330, 2393, 62, 22602, 198, 6738, 285, 2261, 13, ...
2.397196
856
""" The ``ui.ScrollPanel`` class implements a panel that scrolls its contents. If you want the scroll bars to be always visible, call ``setAlwaysShowScrollBars(True)``. You can also change the current scrolling position programmatically by calling ``setScrollPosition(vPos)`` and ``setScrollHorizontalPosition(hPos)`` to change the horizontal and vertical scrolling position, respectively. It is in the nature of a scrollpanel that if you give it a relative size, it will not work. This makes it tricky to use it where you want it to fill out a parent widget of unknown size. To avoid this problem you will have to wrap its content in a SimplePanel and then use css/oveflow to control its behaviour as shown in the second example: "container" represents the parent widget that could be any absolute or relative size and the superscrollpanel will fill it out and apply vertical scrollbars if needed. """ from pyjamas.ui.SimplePanel import SimplePanel from pyjamas.ui.ScrollPanel import ScrollPanel from pyjamas.ui.HTML import HTML from pyjamas.ui.VerticalPanel import VerticalPanel
[ 37811, 198, 464, 7559, 9019, 13, 29261, 26639, 15506, 1398, 23986, 257, 6103, 326, 32138, 663, 10154, 13, 198, 198, 1532, 345, 765, 262, 10743, 9210, 284, 307, 1464, 7424, 11, 869, 198, 15506, 2617, 30374, 15307, 29261, 33, 945, 7, 17...
4.067416
267
#!/usr/bin/env python3 # May you recognize your weaknesses and share your strengths. # May you share freely, never taking more than you give. # May you find love and love everyone you find. import re import time import whois phone_spellable = re.compile(r'^[filoqrsuwxy]+$') candidate_words = [] with open('/usr/share/dict/words') as f: for word in f: word = word.strip() if phone_spellable.match(word): candidate_words.append((len(word), word)) candidate_words.sort() for word in candidate_words: query = False while query is False: try: query = whois.query('%s.com' % word[1]) except: print("Sleeping five seconds...") time.sleep(5) if not query: print(word)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 1737, 345, 7564, 534, 20256, 290, 2648, 534, 18929, 13, 198, 2, 1737, 345, 2648, 12748, 11, 1239, 2263, 517, 621, 345, 1577, 13, 198, 2, 1737, 345, 1064, 1842, 290, 184...
2.427673
318
''' * @file ElevatorTestCaseList.py * @author Armin Zare Zadeh * @date 30 July 2020 * @version 0.1 * @brief Implements a class to hold all the test cases during the program life cycle. ''' #!/usr/bin/env python3 import sys import ctypes import ElevatorConfig as cfg import ElevatorMsgProtocol as msgProto
[ 7061, 6, 198, 1635, 2488, 7753, 220, 220, 37881, 1352, 14402, 20448, 8053, 13, 9078, 198, 1635, 2488, 9800, 943, 1084, 1168, 533, 1168, 671, 71, 198, 1635, 2488, 4475, 220, 220, 1542, 2901, 12131, 198, 1635, 2488, 9641, 657, 13, 16, ...
2.953704
108
from django.utils.translation import ugettext from django.views.decorators.http import require_POST from django.http import JsonResponse from django.shortcuts import render from django.core.exceptions import ValidationError from django.views.decorators.csrf import csrf_exempt from cart.lib import get_cart from cart.forms import SelectProductForm, SetQtyForm
[ 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 198, 6738, 42625, 14208, 13, 33571, 13, 12501, 273, 2024, 13, 4023, 1330, 2421, 62, 32782, 198, 6738, 42625, 14208, 13, 4023, 1330, 449, 1559, 31077, 198, 6738, 42625...
3.462264
106
#------ game constants -----# #players WHITE = 0 BLACK = 1 BOTH = 2 #color for onTurnLabel PLAYER_COLOR = ["white", "black"] #figures PAWN = 1 KNIGHT = 2 BISHOP = 3 ROOK = 4 QUEEN = 5 KING = 6 FIGURE_NAME = [ "", "pawn", "knight", "bishop", "rook", "queen", "king" ] #used in move 32bit for promotion figure prom_figure = figure-2 PROM_KNIGHT = 0 PROM_BISHOP = 1 PROM_ROOK = 2 PROM_QUEEN = 3 #all lines A, B, C, D, E, F, G, H = range(8) #all squares A1, B1, C1, D1, E1, F1, G1, H1, \ A2, B2, C2, D2, E2, F2, G2, H2, \ A3, B3, C3, D3, E3, F3, G3, H3, \ A4, B4, C4, D4, E4, F4, G4, H4, \ A5, B5, C5, D5, E5, F5, G5, H5, \ A6, B6, C6, D6, E6, F6, G6, H6, \ A7, B7, C7, D7, E7, F7, G7, H7, \ A8, B8, C8, D8, E8, F8, G8, H8 = range(64) #----- game display constants -----# DEFAULTBORDERWIDTH = 20 DEFAULTTILEWIDTH = 45 DEFAULTFONTSIZE = (7, 15) COLORS = { "bg":"#EDC08C", "border":"#B55602", "tiles":("#FC9235", "#FFB87A") } #----- move types -----# NORMAL_MOVE, CAPTURE, PROMOTION, DOUBLE_STEP, ENPASSANT_CAPTURE, CASTLING, KING_CAPTURE = range(7) #----- move 32bit reservation -----# # a single move is stored in 32 bit as follows # xxxxxxxx xx x xxx xxx xxxxxx xxxxxx xxx # G F E D C B A # # A: move type (0-6) # B: start sq (0-63) # C: destination sq (0-63) # D: start figure (1-6) # E: captured figure (1-6) # F: color of moved piece (0-1) # G: promotion figure (0-3) #NAME = (start_bit, lenght) MOVE_TYPE = (0, 3) MOVE_START = (3, 6) MOVE_DEST = (9, 6) MOVE_FIG_START = (15, 3) MOVE_FIG_CAPTURE = (18, 3) MOVE_COLOR = (21, 1) MOVE_PROM = (22, 2) #----- castling -----# CASTLING_LEFT = 0 CASTLING_RIGHT = 1 #----- player status -----# IDELING = 0 PICKING = 1 INF = 1000000 ASCII_FIG = [[],[]] ASCII_FIG[WHITE] = [ 'x', chr(9817), chr(9816), chr(9815), chr(9814), chr(9813), chr(9812)] ASCII_FIG[BLACK] = [ 'x', chr(9823), chr(9822), chr(9821), chr(9820), chr(9819), chr(9818)] #AI constants CASTLING_RIGHT_LOSS_PENALTY = -40
[ 201, 198, 2, 23031, 983, 38491, 37404, 2, 201, 198, 2, 32399, 201, 198, 12418, 12709, 796, 657, 201, 198, 9148, 8120, 796, 352, 201, 198, 33, 26946, 796, 362, 201, 198, 201, 198, 2, 8043, 329, 319, 17278, 33986, 201, 198, 31519, 1...
1.878597
1,112
import gym import gym_pokemon import random if __name__ == "__main__": env = gym.make("Pokemon-v0") total_reward = 0.0 total_steps = 0 obs = env.reset() while True: action = random.randint(-1,8) obs, reward, done, _ = env.step(action) total_reward += reward total_steps += 1 print("Currently %d steps, total reward of %.2f" % (total_steps, total_reward)) if done: break
[ 11748, 11550, 198, 11748, 11550, 62, 79, 12717, 198, 11748, 4738, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 197, 24330, 796, 11550, 13, 15883, 7203, 48034, 12, 85, 15, 4943, 198, 197, 23350, 62, 260, 904,...
2.529032
155
num1 = int(input('Digite o 1 nmero: ')) num2 = int(input('Digite o 2 nmero: ')) if num1 > num2: print('O {} maior que {}'.format(num1, num2)) elif num1 < num2: print('O {} maior que4 {}'.format(num2, num1)) else: print('Os nmeros so iguais')
[ 22510, 16, 796, 493, 7, 15414, 10786, 19511, 578, 267, 352, 299, 647, 78, 25, 705, 4008, 198, 22510, 17, 796, 493, 7, 15414, 10786, 19511, 578, 267, 362, 299, 647, 78, 25, 705, 4008, 198, 361, 997, 16, 1875, 997, 17, 25, 198, 22...
2.206897
116
#!/usr/bin/env python import os from setuptools import setup, find_packages def read(fname): """Open files relative to package.""" return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='ipyfilechooser', version='0.3.1', author='Thomas Bouve (@crahan)', author_email='crahan@n00.be', description=( 'Python file chooser widget for use in ' 'Jupyter/IPython in conjunction with ipywidgets' ), long_description=read('README.md'), long_description_content_type='text/markdown', url='https://github.com/crahan/ipyfilechooser', license='MIT', packages=find_packages(), classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', ], install_requires=[ 'ipywidgets' ] )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 28686, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 628, 198, 4299, 1100, 7, 69, 3672, 2599, 198, 220, 220, 220, 37227, 11505, 3696, 3585, 284, 5301, 526, 1593...
2.52356
382
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import appengine_config import datetime import json import logging import os.path import pickle import sys import urllib sys.path.append( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'third_party')) from google.appengine.ext import blobstore from google.appengine.ext import db from google.appengine.ext import deferred from google.appengine.ext import webapp from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app import cloudstorage import app import gtest_parser # pylint: disable=pointless-string-statement """When displaying a list of results, how many to display on one page.""" PAGE_SIZE = 100 def _clean_int(value, default): """Convert a value to an int, or the default value if conversion fails.""" try: return int(value) except (TypeError, ValueError), _: return default application = webapp.WSGIApplication( [('/', MainAction), ('/gtest_query', GTestQueryAction), ('/suppression_query', SuppressionQueryAction), ('/suppression_summary', SuppressionSummaryAction), ('/unused_suppressions', UnusedSuppressionsAction), ('/list', ListAction), ('/build_step_json', BuildStepJSONAction), ('/status_receiver', StatusReceiverAction), ('/tasks/fetch_builders', FetchBuildersAction), ('/tasks/fetch_steps', FetchStepsAction), ('/tasks/update_parsed_data', UpdateParsedDataAction), ('/viewlog/raw/(.*)', ViewRawLogAction)]) if __name__ == '__main__': main()
[ 2, 15069, 357, 66, 8, 2813, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 1...
3.069272
563
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest from hypothesis import given import numpy as np from caffe2.proto import caffe2_pb2 from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu import caffe2.python.serialized_test.serialized_test_util as serial # TODO(jiayq): make them hypothesis tests for better coverage. if __name__ == "__main__": unittest.main()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 555, 715, 39...
3.374194
155
# Copyright (c) 2017 StackHPC Ltd. # # 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. import unittest import cliff.app import cliff.commandmanager import mock from kayobe.cli import commands from kayobe import utils
[ 2, 15069, 357, 66, 8, 2177, 23881, 39, 5662, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789,...
3.715026
193
############################################################################### # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. ############################################################################### import os import tensorflow as _tf from distutils.version import StrictVersion is_tf2 = StrictVersion(_tf.__version__.split('-')[0]) >= StrictVersion('2.0.0') if is_tf2: tensorflow = _tf.compat.v1 def is_subclassed(layer): """Returns True if the object is a subclassed layer or subclassed model.""" return (layer.__module__.find('keras.engine') == -1 and layer.__module__.find('keras.layers') == -1) else: tensorflow = _tf
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321, 13, 198, 29113, 29...
3.27686
242
""" HTTP MultiServer/MultiClient for the ByteBlower Python API. All examples are guaranteed to work with Python 2.7 and above Copyright 2018, Excentis N.V. """ # Needed for python2 / python3 print function compatibility from __future__ import print_function # import the ByteBlower module import byteblowerll.byteblower as byteblower import time configuration = { # Address (IP or FQDN) of the ByteBlower server to use 'server_address': 'byteblower-tp-1300.lab.byteblower.excentis.com', # Configuration for the first ByteBlower port. # Will be used as HTTP server. 'port_1_config': { 'interface': 'trunk-1-13', 'mac': '00:bb:01:00:00:01', # IP configuration for the ByteBlower Port. # Options are 'DHCPv4', 'DHCPv6', 'SLAAC', 'static' # if DHCPv4, use "dhcpv4" 'ip': 'dhcpv4', # if DHCPv6, use "dhcpv6" # 'ip': 'dhcpv6', # if SLAAC, use "slaac" # 'ip': 'slaac', # if staticv4, use ["ipaddress", netmask, gateway] # 'ip': ['192.168.0.2', "255.255.255.0", "192.168.0.1"], # if staticv6, use ["ipaddress", prefixlength] # 'ip': ['3000:3128::24', '64'], # TCP port number to be used by the HTTP connection. # On the HTTP server, this will be the port on which the server # listens. 'tcp_port': 4096 }, # Configuration for the second ByteBlower port. # Will be used as HTTP client. 'port_2_config': { 'interface': 'trunk-1-25', 'mac': '00:bb:01:00:00:02', # IP configuration for the ByteBlower Port. # Options are 'DHCPv4', 'DHCPv6', 'SLAAC', 'static' # if DHCPv4, use "dhcpv4" 'ip': 'dhcpv4', # if DHCPv6, use "dhcpv6" # ip': 'dhcpv6', # if SLAAC, use "slaac" # 'ip': 'slaac', # if staticv4, use ["ipaddress", netmask, gateway] # 'ip': ['192.168.0.2', "255.255.255.0", "192.168.0.1"], # if staticv6, use ["ipaddress", prefixlength] # 'ip': ['3000:3128::24', '64'], # TCP port range the HTTP Clients will use to connect with # the HTTP server 'tcp_port_min': 32000, 'tcp_port_max': 50000 }, # HTTP Method # HTTP Method can be GET or PUT # - GET: Standard HTTP download, we retrieve data from the web server # - PUT: Standard HTTP upload, the wireless endpoint will push data to the # webserver 'http_method': 'GET', # 'http_method': 'PUT', # total duration, in nanoseconds. # This is the duration of the flow. When this duration expires, # all sessions will be stopped. 'duration': 10000000000, # session duration, in nanoseconds # Duration of the individual sessions # 'session_duration': 1500000000, 'session_duration': None, # session size, in bytes # The number of bytes transmitted by a session 'session_size': 1 * 1000 * 1000, # 'session_size': None, # max concurrent sessions # Maximum number of sessions that will be running simultaneously 'max_concurrent_sessions': 100, # maximum number of sessions # No more than this number of sessions will be created # 0 means no limit 'max_total_sessions': 0, # TOS value to use on the HTTP client (and server) 'tos': 0 } # When this python module is called stand-alone, the run-function must be # called. This approach makes it possible to include it in a series of # examples. if __name__ == "__main__": example = Example(**configuration) try: example.run() finally: example.cleanup()
[ 37811, 198, 40717, 15237, 10697, 14, 29800, 11792, 329, 262, 30589, 3629, 789, 11361, 7824, 13, 198, 3237, 6096, 389, 11462, 284, 670, 351, 11361, 362, 13, 22, 290, 2029, 198, 198, 15269, 2864, 11, 1475, 1087, 271, 399, 13, 53, 13, ...
2.466667
1,470
#!/usr/bin/env python # Converts a PoD XML file to a GeoJSON file. # # With the --javascript parameter, the generated file is a javascript # file defining a variable 'basePodSpec'. # # Get the PoD XML file from http://dev.24-timmars.nu/PoD/xmlapi_app.php. import xml.etree.ElementTree as etree import argparse import re import json import io import sys import os.path import datetime if sys.version < '3': import codecs # points number 9000 and above are not real points; they are used to mark # area borders MAXPOINT=8999 if __name__ == '__main__': run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 1482, 24040, 257, 7695, 35, 23735, 2393, 284, 257, 32960, 40386, 2393, 13, 198, 2, 198, 2, 2080, 262, 1377, 37495, 11507, 11, 262, 7560, 2393, 318, 257, 44575, 198, 2, 2393, ...
3.053763
186
import os import json import importlib from pluginbase import PluginBase import rastervision as rv from rastervision.protos.plugin_pb2 import PluginConfig as PluginConfigMsg from rastervision.utils.files import download_if_needed def load_conf_list(s): """Loads a list of items from the config. Lists should be comma separated. This takes into account that previous versions of Raster Vision allowed for a `[ "module" ]` like syntax, even though that didn't work for multi-value lists. """ try: # A comma separated list of values will be transformed to # having a list-like string, with ' instead of ". Replacing # single quotes with double quotes lets us parse it as a JSON list. return json.loads(s.replace("'", '"')) except json.JSONDecodeError: return list(map(lambda x: x.strip(), s.split(',')))
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 1330, 8019, 198, 198, 6738, 13877, 8692, 1330, 42636, 14881, 198, 198, 11748, 374, 1603, 10178, 355, 374, 85, 198, 6738, 374, 1603, 10178, 13, 11235, 418, 13, 33803, 62, 40842, 17, 1330, 4263...
3.113074
283
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags import os import os.path as osp import numpy as np import torch import torchvision import torch.nn as nn from torch.autograd import Variable import functools from . import net_blocks as nb import pdb
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 6738, 2352, 75, 1330, 598, 198, 6738, 2352, 75, 1330, 9701, 198, 11748, 28686, 198, ...
3.57
100
#!/usr/bin/env python # Copyright (c) 2018, DIANA-HEP # 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. import math import numbers import operator import awkward import awkward.util class ArrayMethods(Common): def cosdelta(self, other): denom = self.mag2 * other.mag2 mask = (denom > 0) denom = denom[mask] denom[:] = awkward.util.numpy.sqrt(denom) out = self.dot(other) out[mask] /= denom mask = awkward.util.numpy.logical_not(mask) out[mask] = 1 return awkward.util.numpy.clip(out, -1, 1) def angle(self, other, normal=None, degrees=False): out = awkward.util.numpy.arccos(self.cosdelta(other)) if normal is not None: a = self.unit b = other.unit out = out * awkward.util.numpy.sign(normal.dot(a.cross(b))) if degrees: out = awkward.util.numpy.multiply(out, 180.0/awkward.util.numpy.pi) return out def isopposite(self, other, tolerance=1e-10): tmp = self + other tmp.x = awkward.util.numpy.absolute(tmp.x) tmp.y = awkward.util.numpy.absolute(tmp.y) tmp.z = awkward.util.numpy.absolute(tmp.z) out = (tmp.x < tolerance) out = awkward.util.numpy.bitwise_and(out, tmp.y < tolerance) out = awkward.util.numpy.bitwise_and(out, tmp.z < tolerance) return out def isperpendicular(self, other, tolerance=1e-10): tmp = self.dot(other) tmp.x = awkward.util.numpy.absolute(tmp.x) tmp.y = awkward.util.numpy.absolute(tmp.y) tmp.z = awkward.util.numpy.absolute(tmp.z) out = (tmp.x < tolerance) out = awkward.util.numpy.bitwise_and(out, tmp.y < tolerance) out = awkward.util.numpy.bitwise_and(out, tmp.z < tolerance) return out class Methods(Common): def cosdelta(self, other): m1 = self.mag2 m2 = other.mag2 if m1 == 0 or m2 == 0: return 1.0 r = self.dot(other) / math.sqrt(m1 * m2) return max(-1.0, min(1.0, r)) def angle(self, other, degrees=False): out = math.acos(self.cosdelta(other)) if degrees: out = out * 180.0/math.pi return out def isopposite(self, other, tolerance=1e-10): tmp = self + other return abs(tmp.x) < tolerance and abs(tmp.y) < tolerance and abs(tmp.z) < tolerance def isperpendicular(self, other, tolerance=1e-10): tmp = self.dot(other) return abs(tmp.x) < tolerance and abs(tmp.y) < tolerance and abs(tmp.z) < tolerance def __add__(self, other): return self._vector(operator.add, other) def __radd__(self, other): return self._vector(operator.add, other, True) def __sub__(self, other): return self._vector(operator.sub, other) def __rsub__(self, other): return self._vector(operator.sub, other, True) def __mul__(self, other): return self._scalar(operator.mul, other) def __rmul__(self, other): return self._scalar(operator.mul, other, True) def __div__(self, other): return self._scalar(operator.div, other) def __rdiv__(self, other): return self._scalar(operator.div, other, True) def __truediv__(self, other): return self._scalar(operator.truediv, other) def __rtruediv__(self, other): return self._scalar(operator.truediv, other, True) def __floordiv__(self, other): return self._scalar(operator.floordiv, other) def __rfloordiv__(self, other): return self._scalar(operator.floordiv, other, True) def __mod__(self, other): return self._scalar(operator.mod, other) def __rmod__(self, other): return self._scalar(operator.mod, other, True) def __divmod__(self, other): return self._scalar(operator.divmod, other) def __rdivmod__(self, other): return self._scalar(operator.divmod, other, True) def __pow__(self, other): if isinstance(other, (numbers.Number, awkward.util.numpy.number)): if other == 2: return self.mag2 else: return self.mag2**(0.5*other) else: self._scalar(operator.pow, other) # no __rpow__
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 357, 66, 8, 2864, 11, 14766, 31574, 12, 39, 8905, 198, 2, 1439, 2489, 10395, 13, 198, 2, 220, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 3...
2.437925
2,352
""" Implements a non interactive controller to controt non-interactive visualizers. (i.e. those that are used for converting TPP souce code into another format) """ from tpp.FileParser import FileParser from tpp.controller.TPPController import TPPController
[ 37811, 198, 3546, 1154, 902, 257, 1729, 14333, 10444, 284, 1246, 83, 1729, 12, 3849, 5275, 5874, 11341, 13, 198, 198, 7, 72, 13, 68, 13, 883, 326, 389, 973, 329, 23202, 24322, 24049, 344, 2438, 656, 1194, 5794, 8, 198, 37811, 198, ...
4
65
from bs4 import BeautifulSoup from datetime import date from lxml import html import requests import re import json if __name__ == '__main__': cs = CovidScraper() results = cs.scrape_data() print(results)
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 300, 19875, 1330, 27711, 198, 198, 11748, 7007, 198, 11748, 302, 198, 11748, 33918, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, ...
2.92
75
#!/usr/bin/python2.7 import os from PIL import Image DATEI_WEB_GROSSE = 700 if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 22, 198, 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 35, 6158, 40, 62, 8845, 33, 62, 10761, 2640, 5188, 796, 13037, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, ...
2.285714
49
import discord from discord.ext import commands
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 628, 198 ]
4.545455
11
import pytest from privacy_evaluator.attacks.sample_attack import Sample_Attack """ This test only test if no error is thrown when calling the function, can be removed in the future """
[ 11748, 12972, 9288, 198, 198, 6738, 6782, 62, 18206, 84, 1352, 13, 38458, 13, 39873, 62, 20358, 1330, 27565, 62, 27732, 198, 198, 37811, 198, 1212, 1332, 691, 1332, 611, 645, 4049, 318, 8754, 618, 4585, 262, 2163, 11, 460, 307, 4615, ...
3.916667
48
# 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. import ast import re from setuptools import setup import textwrap _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('prestodb/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) setup( name='presto-python-client', author='Presto Team', author_email='presto-users@googlegroups.com', version=version, url='https://github.com/prestodb/presto-python-client', packages=['prestodb'], package_data={'': ['LICENSE', 'README.md']}, description='Client for the Presto distributed SQL Engine', long_description=textwrap.dedent(""" Client for Presto (https://prestodb.io), a distributed SQL engine for interactive and batch big data processing. Provides a low-level client and a DBAPI 2.0 implementation. """), license='Apache 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database :: Front-Ends', ], install_requires=[ 'click', 'future', 'ipaddress', 'requests', 'requests_kerberos', 'six', 'typing', ], extras_require={'tests':[ 'httpretty', 'pytest', 'pytest-runner', ]} )
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330, 257, 4866, 286, 262, 13789, 379, 198, 2,...
2.710112
890
import matplotlib.pyplot as graph subject = ["Probability", "Calculas", "Discrete Mathematics", "Adv Engineering Mathematics", "Linear Algebra", "Cryptography"] weightage = [250,900,850,1200,290,345] seperator = [0.05,0,0,0,0.05,0.05] graph.title("Mathematics Topic Weightage") graph.pie(weightage,labels=subject,autopct="%0.1f%%", explode=seperator) graph.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 4823, 198, 198, 32796, 796, 14631, 2964, 65, 1799, 1600, 366, 9771, 3129, 292, 1600, 366, 15642, 8374, 39448, 1600, 366, 22856, 14044, 39448, 1600, 220, 198, 1, 14993, 451, 978, 29230, 160...
2.705882
136
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.utils import split_train_test from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression from sklearn.linear_model import Lasso from utils import * import plotnine as gg def select_polynomial_degree(n_samples: int = 100, noise: float = 5): """ Simulate data from a polynomial model and use cross-validation to select the best fitting degree Parameters ---------- n_samples: int, default=100 Number of samples to generate noise: float, default = 5 Noise level to simulate in responses """ # Question 1 - Generate dataset for model f(x)=(x+3)(x+2)(x+1)(x-1)(x-2) + eps for eps Gaussian noise # and split into training- and testing portions X = np.linspace(-1.2, 2, n_samples) y = f(X) + np.random.normal(0, noise, n_samples) train_X, train_y, test_X, test_y = split_train_test(pd.DataFrame(X), pd.Series(y), train_proportion=(2 / 3)) df_train = pd.DataFrame({"x": train_X.squeeze(), "y": train_y, "type": "Train"}) df_test = pd.DataFrame({"x": test_X.squeeze(), "y": test_y, "type": "test"}) x_stat = np.linspace(-1.4, 2, 100) df_stat = pd.DataFrame({"x": x_stat, "y": f(x_stat), "type": "Model"}) df = pd.concat([df_test, df_train]) title = f"f(x) = (x+3)(x+2)(x+1)(x-1)(x-2) + Gaussian noise ~ N(0,{noise})" p = gg.ggplot() + \ gg.geom_point(df, gg.aes("x", "y", color="type")) + \ gg.geom_line(df_stat, gg.aes("x", "y")) + \ gg.theme_bw() + \ gg.ggtitle(title) # print(p) gg.ggsave(filename=f'../../IML/ex5/plots/{title}.png', plot=p, verbose=False) # Question 2 - Perform CV for polynomial fitting with degrees 0,1,...,10 train_err = [] validation_err = [] for k in range(11): pf = PolynomialFitting(k) train_score, validation_score = cross_validate(pf, train_X.to_numpy(), train_y.to_numpy(), mean_square_error) train_err.append(train_score) validation_err.append(validation_score) df1 = pd.DataFrame({"k": range(11), "avg error": train_err, "type": "train error"}) df2 = pd.DataFrame({"k": range(11), "avg error": validation_err, "type": "validation error"}) df = pd.concat([df1, df2]) title = f" Cross Validation for Polynomial Fitting Over Different Degrees k" p = gg.ggplot(df, gg.aes("k", "avg error", color="type")) + \ gg.geom_point() + \ gg.theme_bw() + gg.scale_x_continuous(breaks=range(11)) + \ gg.labs(y="Average training and validation errors", title=f"{title} \nWith Noise: {noise}, Num of samples: {n_samples}") gg.ggsave(filename=f'../../IML/ex5/plots/{title} {noise} {n_samples}.png', plot=p, verbose=False) # Question 3 - Using best value of k, fit a k-degree polynomial model and report test error best_k = np.argmin(np.array(validation_err)) pf = PolynomialFitting(int(best_k)) pf.fit(train_X.to_numpy(), train_y.to_numpy()) y_pred = pf.predict(test_X.to_numpy()) print("best k =", best_k) print("Test = ", round(mean_square_error(test_y.to_numpy(), y_pred), 2)) print("Validation = ", round(validation_err[best_k], 2)) def select_regularization_parameter(n_samples: int = 50, n_evaluations: int = 500): """ Using sklearn's diabetes dataset use cross-validation to select the best fitting regularization parameter values for Ridge and Lasso regressions Parameters ---------- n_samples: int, default=50 Number of samples to generate n_evaluations: int, default = 500 Number of regularization parameter values to evaluate for each of the algorithms """ # Question 6 - Load diabetes dataset and split into training and testing portions X, y = datasets.load_diabetes(return_X_y=True, as_frame=True) train_X, train_y, test_X, test_y = X.iloc[:50, :], y[:50], X.iloc[50:, ], y[50:] # Question 7 - Perform CV for different values of the regularization parameter for Ridge and Lasso regressions for name, learner, ran in [("Ridge", RidgeRegression, np.linspace(0.001, 0.05, 500)), ("Lasso", Lasso, np.linspace(0.001, 0.5, 500))]: train_err = [] validation_err = [] for lam in ran: rg = learner(lam) train_score, validation_score = cross_validate(rg, train_X.to_numpy(), train_y.to_numpy(), mean_square_error) train_err.append(train_score) validation_err.append(validation_score) df1 = pd.DataFrame({"lambda": ran, "avg error": train_err, "type": "train error"}) df2 = pd.DataFrame({"lambda": ran, "avg error": validation_err, "type": "validation error"}) df = pd.concat([df1, df2]) title = f"{name} Regularization Cross Validate Over Different Lambda" p = gg.ggplot(df, gg.aes("lambda", "avg error", color="type")) + \ gg.geom_line() + \ gg.theme_bw() + gg.labs(y="Average training and validation errors", title=title) gg.ggsave(filename=f'../../IML/ex5/plots/{title}.png', plot=p, verbose=False) # Question 8 - Compare best Ridge model, best Lasso model and Least Squares model best_lam = np.argmin(np.array(validation_err)) rg = learner(ran[best_lam]) rg.fit(train_X.to_numpy(), train_y.to_numpy()) y_pred = rg.predict(test_X.to_numpy()) print(f"best lambda {name} = {round(ran[best_lam], 3)}") print(f"Test MSE {name} = {round(mean_square_error(test_y.to_numpy(), y_pred), 2)}") lr = LinearRegression() lr.fit(train_X.to_numpy(), train_y.to_numpy()) print("Linear Regression Loss = ", lr.loss(test_X.to_numpy(), test_y.to_numpy())) if __name__ == '__main__': np.random.seed(0) select_polynomial_degree() select_polynomial_degree(noise=0) select_polynomial_degree(n_samples=1500, noise=10) select_regularization_parameter()
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 1330, 40522, 198, 6738, 314, 5805, 451, 77, 13, 4164, 10466, 1330, 1612, 62, 23415, 62, 18224, 198, ...
2.347529
2,630
import re import copy def parse_media(media, content_version, project_chapters): """ Converts a media object into formats usable in the catalog :param media: the media object :type media: dict :param content_version: the current version of the source content :type content_version: string :param project_chapters: a dictionary of project chapters :type project_chapters: dict :return: resource_formats, project_formats a list of resource formats and dictionary of project formats """ resource_formats = [] project_formats = {} if 'resource' in media: resource_formats = _parse_resource(media['resource'], content_version) if 'projects' in media: for project in media['projects']: project_id = project['identifier'] chapters = [] if project_id == 'obs': # TRICKY: obs projects always have 50 chapters # This allows empty projects to still publish media. for x in range(1, 51): # chapters 1..50 chapters.append(str(x).zfill(2)) if project_id in project_chapters: chapters = project_chapters[project_id] project_formats[project_id] = _parse_project(project, content_version, chapters) return resource_formats, project_formats def _parse_resource(resource, content_version): """ Converts a resource media object into formats usable in the catalog :param resource: the media object :type resource: dict :param content_version: the current version of the source content :type content_version: string :return: a list of formats """ source_version = _expand_keys(resource['version'], {'latest': content_version}) formats = [] if 'media' in resource: for media in resource['media']: media_version = _expand_keys(media['version'], {'latest': content_version}) expansion_vars = _make_expansion_variables(media, content_version) if 'quality' in media and len(media['quality']) > 0: # build format for each quality for quality in media['quality']: expansion_vars['quality'] = quality format = _make_format(source_version=source_version, media_version=media_version, quality=quality, media=media, expansion_vars=expansion_vars) formats.append(format) else: # build a single format format = _make_format(source_version=source_version, media_version=media_version, quality=None, media=media, expansion_vars=expansion_vars) formats.append(format) return formats def _parse_project(project, content_version, chapters_ids): """ Converts a project media object into formats usable in the catalog :param project: the media object :type project: dict :param content_version: the current version of the source content :type content_version: string :param chapters_ids: a list of chapter identifiers in the project :type chapters_ids: list :return: a list of formats """ source_version = _expand_keys(project['version'], {'latest': content_version}) formats = [] if 'media' in project: for media in project['media']: media_version = _expand_keys(media['version'], {'latest': content_version}) expansion_vars = _make_expansion_variables(media, content_version) if 'quality' in media and len(media['quality']) > 0: # build format for each quality for quality in media['quality']: expansion_vars['quality'] = quality format = _make_format(source_version=source_version, media_version=media_version, quality=quality, media=media, expansion_vars=expansion_vars) chapters = _prepare_chapter_formats(media, chapters_ids, expansion_vars) if chapters: format['chapters'] = chapters formats.append(format) else: # build single format format = _make_format(source_version=source_version, media_version=media_version, quality=None, media=media, expansion_vars=expansion_vars) chapters = _prepare_chapter_formats(media, chapters_ids, expansion_vars) if chapters: format['chapters'] = chapters formats.append(format) return formats def _prepare_chapter_formats(media, chapters, expansion_vars): """ This is a wrapper around the method `_parse_project_chapter`. Since we routinely conditionally prepare chapters in multiple places this handles it in one place :param media: the media object to inspect :param chapters: a list of chapter ids :param expansion_vars: a dictionary of variables that may be expanded in the chapter url :return: """ if 'chapter_url' in media: chapter_url = _expand_keys(media['chapter_url'], expansion_vars) chapters = _parse_project_chapter(chapter_url, chapters) if chapters: return chapters return None def _parse_project_chapter(chapter_url, chapters): """ Generates chapter formats for use in the catalog :param chapter_url: the url template that will be used in the formats :param chapters: a list of chapter ids :type chapters: list :return: """ # TODO: this requires that we give a well formatted list of chapter ids and check if the Rc is a book # only book RCs can have chapter formats formats = [] for chapter_id in chapters: format = { 'size': 0, 'length': 0, 'modified': '', 'identifier': chapter_id, 'url': _expand_keys(chapter_url, {'chapter': chapter_id}), 'signature': '', 'build_rules': [ 'signing.sign_given_url' ] } formats.append(format) return formats def _make_expansion_variables(media_block, content_version): """ Creates a dictionary of expansion variables for media items. :param self: :param media_block: :param content_version: :return: """ vars = copy.copy(media_block) # strip black listed keys black_list = ['url', 'chapter_url'] for key in black_list: if key in vars: del vars[key] # TRICKY: using `latest` as an expansion variable in urls is not explicitly stated in the spec, # but it's a common misunderstanding so we allow it. vars['latest'] = '{}'.format(content_version) return vars def _expand_keys(target, replacements): """ Replaces all the dict keys found in the string with the dict values. Keys in the string must be delimited by brackets {} :param target: :param replacements: :return: """ if isinstance(target, basestring) or isinstance(target, str): result = target if not isinstance(replacements, dict): raise Exception('Expected dictionary of replacements but received {}'.format(type(replacements))) for key in replacements: if not isinstance(replacements[key], list): result = re.sub(r'{\s*' + key + '\s*}', '{}'.format(replacements[key]), result) return result elif isinstance(target, int): return target else: raise Exception('Invalid replacement target "{}". Expected string but received {}'.format(target, type(target)))
[ 11748, 302, 198, 11748, 4866, 198, 198, 4299, 21136, 62, 11431, 7, 11431, 11, 2695, 62, 9641, 11, 1628, 62, 354, 12126, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1482, 24040, 257, 2056, 2134, 656, 17519, 24284, 287, 262, ...
2.21408
3,821
# -*- coding:utf-8 -*- # create_time: 2019/8/5 16:02 # __author__ = 'brad' from . import utils from .tasks.base import WaitingTask, BaseTask
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 2251, 62, 2435, 25, 13130, 14, 23, 14, 20, 1467, 25, 2999, 198, 2, 11593, 9800, 834, 796, 705, 1671, 324, 6, 198, 6738, 764, 1330, 3384, 4487, 198, 6738, 764, 83, ...
2.535714
56
from django.db.models.fields.files import (FieldFile, ImageField, ImageFileDescriptor) from django.utils.translation import ugettext as _ from .backends import get_backend_class from .files import VideoFile
[ 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 25747, 13, 16624, 1330, 357, 15878, 8979, 11, 7412, 15878, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 22...
2.442308
104
from flaky import flaky from slm_lab.experiment.control import Trial from slm_lab.experiment.monitor import InfoSpace from slm_lab.lib import util from slm_lab.spec import spec_util import os import pandas as pd import pytest import sys # helper method to run all tests in test_spec
[ 6738, 781, 15492, 1330, 781, 15492, 198, 6738, 1017, 76, 62, 23912, 13, 23100, 3681, 13, 13716, 1330, 21960, 198, 6738, 1017, 76, 62, 23912, 13, 23100, 3681, 13, 41143, 1330, 14151, 14106, 198, 6738, 1017, 76, 62, 23912, 13, 8019, 133...
3.2
95
from model.group import Group
[ 6738, 2746, 13, 8094, 1330, 4912, 628, 628, 628, 198 ]
3.6
10
import io import time import datetime from readme_metrics.Metrics import Metrics from readme_metrics.MetricsApiConfig import MetricsApiConfig from readme_metrics.ResponseInfoWrapper import ResponseInfoWrapper from werkzeug import Request
[ 11748, 33245, 198, 11748, 640, 198, 11748, 4818, 8079, 198, 198, 6738, 1100, 1326, 62, 4164, 10466, 13, 9171, 10466, 1330, 3395, 10466, 198, 6738, 1100, 1326, 62, 4164, 10466, 13, 9171, 10466, 32, 14415, 16934, 1330, 3395, 10466, 32, 14...
3.529412
68
import numpy as np import gym from sklearn.neighbors import NearestNeighbors import matplotlib.pyplot as plt import argparse parser = argparse.ArgumentParser(description='KBRL with KNN') parser.add_argument('--episodes', nargs='?', type=int, default=500) parser.add_argument('--max_timesteps', nargs='?', type=int, default=200) parser.add_argument('environment') args = parser.parse_args() env = gym.make(args.environment).env action_space = env.action_space # hyperparameters: epsilon = 1.0 exploration_decay = 0.98 k = 500 # number of nearest neighbors minimum_num_iters = 500 # number of iterations used for training num_iter = 0 max_iters = 0 gamma = 0.95 max_state_size = 15000 # because we don't know the state space size in continuous environments # learning-related variables states = None actions = {} rewards = {} values = {} # episode-related variables episode_beginning = 0 # Ignore sklearn warnings import warnings warnings.warn = warn reward = 0 episode_reward = 0 done = False cumulative_reward_list = [] for i in range(args.episodes): observation = env.reset() sum_reward = 0 for j in range(args.max_timesteps): env.render() action = make_move(observation, reward, done) observation, reward, done, _ = env.step(action) sum_reward += reward if done: break episode_reward = episode_reward * 0.95 + sum_reward * 0.05 print('Reward for episode '+ str(i)+' : '+str(episode_reward)) cumulative_reward_list.append(episode_reward) # env.render() plt.plot(range(0,500), cumulative_reward_list, linewidth=2) plt.xlabel("Episodes") plt.ylabel("Cumulative Reward") plt.title("Performance") plt.show() plt.close()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 11550, 198, 6738, 1341, 35720, 13, 710, 394, 32289, 1330, 3169, 12423, 46445, 32289, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 1822, 29572, 198, 198, 48610, 796, ...
2.796721
610
import elasticsearch from elasticsearch import Elasticsearch from elasticsearch import helpers import time, json, datetime, os
[ 11748, 27468, 12947, 198, 6738, 27468, 12947, 1330, 48567, 12947, 198, 6738, 27468, 12947, 1330, 49385, 198, 198, 11748, 640, 11, 33918, 11, 4818, 8079, 11, 28686, 198 ]
4.571429
28
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from util import clean_phone_number, clean_outgoing_sms_text from django.test import TestCase
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 43907, 25, 257, 72, 40379, 28, 19, 39747, 28, 19, 2123, 1509, 28, 19, 21004, 28, 40477, 12, 23, 198, 198, 6738, 7736, 1330, 3424, 62, 4862, 62, 17618, 11, 3424, 62, 448, 5146, ...
2.59375
64
__author__ = "Joseph Gomes" __copyright__ = "Copyright 2017, Stanford University" __license__ = "MIT" import sys from deepchem.models import KerasModel from deepchem.models.layers import AtomicConvolution from deepchem.models.losses import L2Loss from tensorflow.keras.layers import Input, Layer import numpy as np import tensorflow as tf import itertools def initializeWeightsBiases(prev_layer_size, size, weights=None, biases=None, name=None): """Initializes weights and biases to be used in a fully-connected layer. Parameters ---------- prev_layer_size: int Number of features in previous layer. size: int Number of nodes in this layer. weights: tf.Tensor, optional (Default None) Weight tensor. biases: tf.Tensor, optional (Default None) Bias tensor. name: str Name for this op, optional (Defaults to 'fully_connected' if None) Returns ------- weights: tf.Variable Initialized weights. biases: tf.Variable Initialized biases. """ if weights is None: weights = tf.random.truncated_normal([prev_layer_size, size], stddev=0.01) if biases is None: biases = tf.zeros([size]) w = tf.Variable(weights, name='w') b = tf.Variable(biases, name='b') return w, b
[ 834, 9800, 834, 796, 366, 29458, 402, 2586, 1, 198, 834, 22163, 4766, 834, 796, 366, 15269, 2177, 11, 13863, 2059, 1, 198, 834, 43085, 834, 796, 366, 36393, 1, 198, 198, 11748, 25064, 198, 198, 6738, 2769, 15245, 13, 27530, 1330, 17...
2.620155
516
""" Copyright (c) 2020 COTOBA DESIGN, Inc. 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. """ import unittest from programy.config.file.yaml_file import YamlConfigurationFile from programy.config.brain.oob import BrainOOBConfiguration from programy.clients.events.console.config import ConsoleConfiguration
[ 37811, 198, 15269, 357, 66, 8, 12131, 327, 26631, 4339, 22196, 16284, 11, 3457, 13, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 3788, 290, 3917, 198, 22897, 341, 3696, ...
3.944785
326
import abc from ...orb_attribute import OrbAttribute # Interface for active skills that create specific orb types (whether board change, orb change, orb spawn, etc)
[ 11748, 450, 66, 198, 6738, 2644, 27688, 62, 42348, 1330, 15839, 33682, 628, 198, 2, 26491, 329, 4075, 4678, 326, 2251, 2176, 15769, 3858, 357, 25356, 3096, 1487, 11, 15769, 1487, 11, 15769, 10922, 11, 3503, 8 ]
4.486486
37
""" Core business logic for `mystery`. This code will run when the package is being built and installed. """ import json import pathlib import random import tempfile import urllib.request import typing import setuptools from setuptools.command.sdist import sdist # Load the configuration file. CONFIG_PATH = pathlib.Path('config.json') CONFIG = json.load(CONFIG_PATH.open('r')) def _get_lockfile_path() -> pathlib.Path: """ Assemble the lockfile's path. :return: lockfile path. :rtype: pathlib.Path """ return pathlib.Path(tempfile.gettempdir()).joinpath(CONFIG['lockfile_name']) def _get_package_list() -> typing.List[str]: """ Get a list of possible packages. :return: list of package names. :rtype: typing.List[str] """ try: # Get the top PyPI packages and use one of them. response = urllib.request.urlopen(CONFIG['top_pypi_packages_link']) possible_packages_raw = response.read() except urllib.request.URLError: # Use the offline backup file. with open(CONFIG['top_pypi_packages_offline_backup'], 'r') as backup_file: possible_packages_raw = backup_file.read() return json.loads(possible_packages_raw)['rows'][: CONFIG['top_x_packages']] def _choose_mystery_package() -> str: """ Choose the underlying mysterious package and handle the lockfile's state. :return: mystery package name. :rtype: str """ # To keep the chosen dependency consistent in between setup.py runs, 'mystery' uses a temporary lockfile. dep_lock_path = _get_lockfile_path() if dep_lock_path.exists(): # Use the locked package and unlink the lockfile. chosen_package = dep_lock_path.read_text().strip() dep_lock_path.unlink() else: # Choose a package and create the lockfile. possible_packages = _get_package_list() chosen_package = random.choice( [package['project'] for package in possible_packages] ) dep_lock_path.write_text(chosen_package) # Lock the chosen package of course. return chosen_package def _fix_package_name(package_name: str) -> str: """ Fix the package name so it could be placed in the __init__.py file. :param package_name: mystery package name. :type package_name: str :return: fixed mystery package name. :rtype: str """ # Transform to eligible package name. fixed_package_name = package_name.replace('-', '_') # Special case for the 'backports' modules. if fixed_package_name.startswith('backports_'): fixed_package_name.replace('_', '.', 1) return fixed_package_name def _write_init_py(package_name: str) -> None: """ Dynamically write the __init__.py for the package using the chosen package. :param chosen_package: mystery package name. :type chosen_package: str :rtype: None """ package_name = _fix_package_name(package_name) init_py_path = pathlib.Path('mystery') init_py_path.mkdir(exist_ok=True) init_py_path = init_py_path / '__init__.py' init_py_path.write_text( f''' # Here we're trying to import the mystery package (it's "{package_name}" this time). # If it exists, overwrite 'mystery' in 'sys.modules'. Else, print there was an error. import sys try: import {package_name} except ImportError as error: print('Internal error:', error) print("The mystery package wasn't playing nice. Sorry!") print('Hint: you can always try to reinstall mystery and get a different package!') sorry = 'try reinstalling mystery and get a different package!' else: sys.modules['mystery'] = {package_name} sys.modules['mystery'].__mystery_init_py__ = __file__ sys.modules['mystery'].__mystery_package_name__ = '{package_name}' del sys # We care about this only when mystery fails (and even that's inconsequential). ''' ) def _get_long_description_data() -> typing.Tuple[str, str]: """ Get data regarding the long description of the package. :return: tuple of the README.md text and the long_description type. :rtype: typing.Tuple[str, str] """ with open('README.md', 'r') as readme: return (readme.read(), 'text/markdown') CHOSEN_PACKAGE = _choose_mystery_package() _write_init_py(CHOSEN_PACKAGE) LONG_DESCRIPTION, LONG_DESCRIPTION_CONTENT_TYPE = _get_long_description_data() setuptools.setup( name='mystery', version='1.0.2', description='It is a riddle, wrapped in a mystery, inside an enigma.', url='https://github.com/DivoK/mystery', author='Divo Kaplan', author_email='divokaplan@gmail.com', packages=setuptools.find_packages(), install_requires=[CHOSEN_PACKAGE], cmdclass={'sdist': SDistCommand}, python_requires='>=3.6', include_package_data=True, long_description=LONG_DESCRIPTION, long_description_content_type=LONG_DESCRIPTION_CONTENT_TYPE, keywords='mystery setuptools fun python-packages random', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Intended Audience :: Other Audience', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
[ 37811, 198, 14055, 1597, 9156, 329, 4600, 1820, 41991, 44646, 198, 1212, 2438, 481, 1057, 618, 262, 5301, 318, 852, 3170, 290, 6589, 13, 198, 37811, 198, 198, 11748, 33918, 198, 11748, 3108, 8019, 198, 11748, 4738, 198, 11748, 20218, 77...
2.741528
1,977
#!/usr/bin/env python # -*- coding: utf-8 -*- # ======================================= # File Name: ADMM_primal.py # Purpose : implementation for ADMM method # for solving primal problem # ======================================= from utils import get_params import numpy as np import sys def ADMM_primal(mu, nu, c, iters=10000, rho=1024, alpha=1.618): """ADMM_primal """ # initialize m, n = c.shape pi = np.zeros((m, n)) pi_dag = np.zeros((m, n)) w = np.zeros((m, n)) u = np.zeros(m) v = np.zeros(n) rho_tilde = rho * 32 while rho_tilde >= rho: for _ in range(iters): r = ((-w + u.reshape((m, 1)) + v.reshape((1, n)) - c) / rho + mu.reshape((m, 1)) + nu.reshape((1, n)) + pi_dag) pi = (r - ((r.sum(axis=1) - r.sum() / (m + n + 1)) / (n + 1)).reshape((m, 1)) - ((r.sum(axis=0) - r.sum() / (m + n + 1)) / (m + 1)).reshape((1, n))) pi_dag = np.maximum(pi + w / rho, 0.0) u = u + alpha * rho * (mu - pi.sum(axis=1)) v = v + alpha * rho * (nu - pi.sum(axis=0)) w = w + alpha * rho * (pi - pi_dag) rho_tilde = rho_tilde / 2 print('error_mu = %.5e' % np.linalg.norm(pi_dag.sum(axis = 1) - mu, 1)) print('error_nu = %.5e' % np.linalg.norm(pi_dag.sum(axis = 0) - nu, 1)) print('fvall = %.5e' % (c * pi_dag).sum()) if __name__ == '__main__': try: print("Test...") _mu, _nu, _c = get_params(64, 'random') ADMM_primal(_mu, _nu, _c) except KeyboardInterrupt: print (" Ctrl+C pressed...") sys.exit(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 46111, 50155, 198, 2, 9220, 6530, 25, 5984, 12038, 62, 1050, 4402, 13, 9078, 198, 2, 32039, 220, 1058, 7822, 329, ...
1.940559
858
#!/usr/bin/python import os import sys import pprint import argparse parser = argparse.ArgumentParser(description='Clean up the data for a given parameter') parser.add_argument('--infile', help="Path to the VCF file", default='test.vcf') parser.add_argument('--outfile', help="Path to the new VCF file", default='test.out.vcf') parser.add_argument('--param', help="Parameter to clean", default='PL') args = parser.parse_args() fi = open(args.infile, 'r') #fo = open('Spombe.2013-01-02.filt3c.nr57-final.snps.anno-snpeff3.cleaned3.AB325691.vcf', 'w') fo = open(args.outfile, 'w') for line in fi: if len(line) == 0: continue if line[0] == '#': fo.write(line) continue line = line.rstrip() v = line.split('\t'); params = v[8].split(':') out = v[0:8] try: paramIndex = params.index(args.param) del params[paramIndex] out.append(':'.join(params)) for d in v[9:]: dv = d.split(':') del dv[paramIndex] out.append(':'.join(dv)) except ValueError: out.append(':'.join(params)) out += v[9:] fo.write("\t".join(out) + "\n") fi.close() fo.close()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 279, 4798, 198, 11748, 1822, 29572, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 11639, 32657, 510, 262, 1366, 329, 257...
2.417749
462