id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3325615
import json import sys import timeit from collections import Counter from dxtbx.model.experiment_list import ExperimentListFactory from libtbx import easy_mp from scitbx.array_family import flex def build_hist(nproc=1): # FIXME use proper optionparser here. This works for now if len(sys.argv) >= 2 and sys.ar...
StarcoderdataPython
122598
<gh_stars>1-10 from django.db import models from django.utils.translation import ugettext_lazy as _ from .utils import can_object_page_be_shown_to_pubilc PUBLISH_STATUS_LIST = ( (-1, 'NEVER Available'), (0, 'USE "Live as of Date"'), (1, 'ALWAYS Available') ) """ There are two different types of models tha...
StarcoderdataPython
3366606
import os from crossasr.utils import make_dir class ASR: def __init__(self, name): self.name = name self.transcription = "" def getName(self) : return self.name def setName(self, name:str): self.name = name def getTranscription(self): return self.transcription...
StarcoderdataPython
4825386
def update_from_ref(self, LUT_ref): """Update the equivalent circuit according to the LUT Parameters ---------- self : EEC_SCIM an EEC_SCIM object LUT_ref : LUTslip reference LUTslip object """ # Update skin effect to OP/T self.comp_skin_effect() self.comp_K21() ...
StarcoderdataPython
3212910
<filename>Clustering/K-means.py import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np import random import os from sklearn.cluster import KMeans from sklearn.datasets.samples_generator import make_blobs np.random.seed(0); X, y = make_blobs(n_samples=5000, centers=[[4,4], [-2, -1]...
StarcoderdataPython
1755679
import logging from spacel.model.aws import VALID_REGIONS, INSTANCE_TYPES logger = logging.getLogger('spacel.model.orbit') NAT_CONFIGURATIONS = { 'disabled', # No NAT, don't even try 'enabled', # Single NAT gateway for every AZ (default) 'per-az' # NAT gateway per AZ (suggested for production) } cla...
StarcoderdataPython
190414
#! /usr/bin/python from distutils.dir_util import copy_tree from pathlib import Path import os from .common import order_version, log_normal, log_info, mpk_lang lang_map = { "en": 2, "jp": 1, } def main(original_assets_path, cached_static_path): log_normal("Copy cached static data from majsoul-plus..."...
StarcoderdataPython
3366374
<gh_stars>10-100 from __future__ import absolute_import from collections import defaultdict from datetime import datetime from pytz import UTC from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_noop from django_countries.fields import CountryField ...
StarcoderdataPython
3374931
""" @Filename: test.py.py @Author: dulanj @Time: 2021-08-23 16.12 """ import torch from data_loader import get_test_loader from params import configs, DEVICE from pretrained_models import initialize_model def test(): # model = ClassificationModel(num_classes=configs["data"]["no_of_classes"]).to(DE...
StarcoderdataPython
1700091
<reponame>bellaz89/pyFEL ''' Implementation of the Hammersley low discrepancy sequence ''' import numba from numba import int64, objmode from numba.experimental import jitclass import numpy as np from scipy.special import erfcinv spec = [ ('base', int64), ('idx', int64) ] @jitclass(spec) class Hammersley...
StarcoderdataPython
3244361
<gh_stars>0 # Generated by Django 4.0 on 2021-12-13 09:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('src', '0001_initial'), ] operations = [ migrations.AlterField( model_name='product', name='name', ...
StarcoderdataPython
168772
from django.conf import settings URL_CDN_BASE = getattr(settings, 'SITETABLES_URL_CDN_BASE', '//cdn.datatables.net/')
StarcoderdataPython
1612591
<reponame>joshfriend/sqlalchemy-utils import sqlalchemy as sa from datetime import datetime, date, time import pytest from pytest import mark cryptography = None try: import cryptography except ImportError: pass from tests import TestCase from sqlalchemy_utils import EncryptedType, PhoneNumberType, ColorType f...
StarcoderdataPython
25461
from typing import Optional import requests from mstrio.connection import Connection from mstrio.utils.error_handlers import ErrorHandler @ErrorHandler(err_msg='Error while creating the package holder') def create_package_holder(connection: Connection, project_id: Optional[str] = None, err...
StarcoderdataPython
3363553
#abc209_d import sys, math, collections, itertools, heapq, functools, bisect input = sys.stdin.readline sys.setrecursionlimit(10**7) m = 10**9 + 7 def intm1(num): return int(num) - 1 intfunc = [int, intm1] def II(i=0): return intfunc[i](input()) def LII(i=0): return list(map(intfunc[i], input().spl...
StarcoderdataPython
3212319
<reponame>pablobsanchez/eq1fa2<gh_stars>0 """ Created on Tue Mar 1 09:55:26 2022 @author: po-po """ import cv2 import numpy as np import matplotlib.pyplot as plt import time import pandas as pd from simpleim2D import * # Create a VideoCapture object and read from input file # If the input is the camer...
StarcoderdataPython
92252
from .detector3d_template import Detector3DTemplate class PVSECONDFPNUNet(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset, nusc=False): super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset, nusc=nusc) self.module_list = self.build_networks() self...
StarcoderdataPython
1722893
import numpy as np def ask_sumxy(level): ask = level_sumxy(level) if ask: return [ '''Halle dos números enteros tales que la suma sea {} y la diferencia sea {}".'''.format(ask[2], ask[3]), [ask[0], ask[1]] ] def level_sumxy(level): min = 2 * level + 3 max = 5 * level + 15 return _sumxy(min, max) def ...
StarcoderdataPython
3273088
def test_layout(layout_from_family2): assert layout_from_family2 is not None def test_layout__intervals( layout_from_family2, individuals_intervals_from_family2): assert layout_from_family2[0]._intervals == \ individuals_intervals_from_family2 def test_layout_lines(layout_from_family2): ...
StarcoderdataPython
1794129
# Copyright 2020 The Bazel 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 la...
StarcoderdataPython
143605
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Initialization module for artellapipe-dccs-maya """ import os import logging.config # ================================================================================= PACKAGE = 'artellapipe.dccs.maya' # ============================================================...
StarcoderdataPython
3386399
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from lxml import html from config import getConfig from util import isWindow import os import codecs login_url = 'https://monocloud.net/login' if isWindow(): template = codecs.open('shadowsocks_win_tpl.bat', encoding='utf-8').read() else: templat...
StarcoderdataPython
3324454
import sched import time import pickle import socket def send_udp(s, packet): try: s.send(pickle.dumps(packet)) except ConnectionRefusedError: pass def send_packets(channel, *, send_rate=30, packet=lambda: None, send_func=lambda *args: None,...
StarcoderdataPython
105284
<reponame>ferrerinicolas/python_samples<filename>Variables/3.2.5.py string_variable = "Nicolas" int_variable = 24 print(string_variable) print(int_variable)
StarcoderdataPython
1729760
from collections import defaultdict from typing import Tuple class PoolConnections: def __init__(self): self._disconnected_till = defaultdict(int) def are_connected(self, ts: int, nodes: Tuple[str, str]): if nodes[0] == nodes[1]: return True nodes = self._sort_nodes(nodes)...
StarcoderdataPython
3323109
#!/usr/bin/env python3 from troposphere import Template, Sub, GetAtt, Ref from troposphere.s3 import Bucket from troposphere.codepipeline import Pipeline, ArtifactStore from awslambdacontinuousdelivery.tools.iam import createCodepipelineRole from awslambdacontinuousdelivery.source.codecommit import getCodeCommit from ...
StarcoderdataPython
1691676
import json import pytest from verity_sdk.utils import unpack_forward_message from verity_sdk.utils.Context import Context from verity_sdk.protocols.Protocol import Protocol from ..test_utils import get_test_config, cleanup @pytest.mark.asyncio async def test_get_message(): message = {'hello': 'world'} conte...
StarcoderdataPython
1711750
class ARGB: """ ARGB 色彩值。 """ _alpha: int _red: int _green: int _blue: int @property def alpha(self) -> int: """ Alpha 透明度通道。 """ return self._alpha @property def red(self) -> int: """ 红色通道。 """ return self....
StarcoderdataPython
3224933
<gh_stars>10-100 #coding:utf-8 ################################# #Copyright(c) 2014 dtysky ################################# import G2R class MovieSp(G2R.SpSyntax): def Show(self,Flag,Attrs,US,UT,Tmp,FS): sw='' name,Attrs=self.Check(Flag,Attrs,UT,FS) if name=='movie_StopMovie': sw+=' hide movie with Disso...
StarcoderdataPython
4840544
from infi import unittest from infi.eventlog import LocalEventLog class FacadeTestCase(unittest.TestCase): def test__open_system_channel(self): eventlog = LocalEventLog() with eventlog.open_channel_context("System"): pass def test__get_available_channels(self): eventlog = L...
StarcoderdataPython
1682859
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import os import re from datadog_checks.utils.common import get_docker_hostname CHECK_NAME = "couch" PORT = "5984" HOST = get_docker_hostname() URL = "http://{}:{}".format(HOST, PORT) USER = "dduser" PASSWORD ...
StarcoderdataPython
3351750
#!/usr/bin/env python from setuptools import setup, find_packages from ssdpy.version import VERSION with open("README.md", "r") as fh: long_description = fh.read() setup( name="ssdpy", version=VERSION, long_description=long_description, long_description_content_type="text/markdown", descripti...
StarcoderdataPython
3367050
<gh_stars>1-10 import abc from ... import utils class Loss(abc.ABC): @abc.abstractmethod def __call__(self, y_true, y_pred) -> float: """Returns the loss.""" @abc.abstractmethod def gradient(self, y_true, y_pred) -> float: """Returns the gradient with respect to ``y_pred``.""" cla...
StarcoderdataPython
3312489
<gh_stars>0 from django.shortcuts import render,redirect from products.models import Product from django.http import JsonResponse # Create your views here. from addresses.forms import AddressForm from addresses.models import Address from accounts.models import GuestEmail from billing.models import BillingProfile from a...
StarcoderdataPython
3269209
<reponame>NimbleStorage/container-examples import falcon import json import imprint import requests import mysql.connector import sys from os import environ from time import time class PingResource: def __init__(self): self.v = version() def on_get(self, req, resp, **kwargs): db = Ping() ...
StarcoderdataPython
1773484
# (C) Copyright 1996- ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernment...
StarcoderdataPython
40257
import torch import numpy as np import cv2 def tonumpyimg(img): """ Convert a normalized tensor image to unnormalized uint8 numpy image For single channel image, no unnormalization is done. :param img: torch, normalized, (3, H, W), (H, W) :return: numpy: (H, W, 3), (H, W). uint8 """ ...
StarcoderdataPython
4825947
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import numpy as np import os import re import sys from argparse import ArgumentParser from datetime import datetime, timedelta from itertools import product from scipy.interpolate import griddata from serial import Serial from time import sleep, time class Pr...
StarcoderdataPython
85688
<reponame>Moggs/Workbench from tkinter import * from tkinter.ttk import * from Moggs import * import win32print import os import sys class Printer(Toplevel): def __init__(self, parent, filelist=[], printer=None): Toplevel.__init__(self, parent) self.filelist=filelist ...
StarcoderdataPython
3214387
<filename>Kivy/Kivy/Bk_Interractive/sample/Chapter_06_code/10 - Search - query the TED Developer API/loaddialog.py # File name: loaddialog.py import kivy kivy.require('1.9.0') from kivy.uix.floatlayout import FloatLayout from kivy.properties import ObjectProperty from kivy.lang import Builder Builder.load_file('loadd...
StarcoderdataPython
44093
<reponame>wax911/anime-meta from .type_registries import CoreEntityCodec, CacheLogEntityCodec, SigningPolicyEntityCodec, \ IndexEntityCodec, AdBreakEntityCodec, EpisodeEntityCodec, SeasonEntityCodec, SeriesEntityCodec, \ ImageContainerEntityCodec, MoviePanelEntityCodec, SearchMetaEntityCodec, SeriesPanelEntityC...
StarcoderdataPython
3333498
import os import sys from os import listdir, makedirs from os.path import isfile, join import hashlib from typing import Counter from PIL import Image from send2trash import send2trash directory = "" def main(): # delete (send to trach) dublicates inside every subfolder of the current directory the .py ...
StarcoderdataPython
1786948
<reponame>uktrade/directory-forms-api<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-01-08 11:32 from __future__ import unicode_literals from django.db import migrations, models import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('submiss...
StarcoderdataPython
1738057
<reponame>MakerAsia/lvgl<filename>examples/libs/rlottie/lv_example_rlottie_1.py<gh_stars>1000+ #!/opt/bin/lv_micropython -i import lvgl as lv import display_driver # # Load a lottie animation from flash # from lv_example_rlottie_approve import lv_example_rlottie_approve lottie = lv.rlottie_create_from_raw(lv.scr_act()...
StarcoderdataPython
3304610
<filename>opyapi/http/errors/http_error.py from typing import Optional from opyapi import OpyapiError from opyapi.http import HttpResponse class HttpError(OpyapiError, HttpResponse): status_code: int = 500 http_message = "Internal Server Error" def __init__( self, http_message: Optional[str] = N...
StarcoderdataPython
157438
<reponame>vihaton/MBH<gh_stars>0 import torch from torchvision import datasets, transforms import numpy as np # ## MNIST data def get_dataset(data_name: str): if data_name == 'digit': return datasets.MNIST elif data_name == 'fashion': return datasets.FashionMNIST else: raise Value...
StarcoderdataPython
81677
import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_boston from sklearn.ensemble import StackingRegressor from sklearn.linear_model import LinearRegression, TheilSenRegressor from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn...
StarcoderdataPython
3213266
<reponame>tdeboer-ilmn/hail<filename>hail/python/hail/hail_logging.py import abc import logging class Logger(abc.ABC): @abc.abstractmethod def error(self, msg): pass @abc.abstractmethod def warning(self, msg): pass @abc.abstractmethod def info(self, msg): pass class...
StarcoderdataPython
1724763
#!/usr/bin/env python # -*- coding: utf-8 -*- """Parse some options to transpopy.""" from argparse import ArgumentParser def return_args(): """Return a parser object.""" _parser = ArgumentParser(add_help=True, description=( "Translate msgid's from a POT file with Google Translate API")) _parser....
StarcoderdataPython
4812227
""" Script to add the missing slot to the schimbaIntensitateMuzica intent The slot "nivel" was missing due to an error in the Chatito script corresponding to this intent (in scenarios 0,1,3) The default format for the input file is RASA """ import json FILES_TO_FIX = [ 'data/romanian_dataset/home_assistant/versi...
StarcoderdataPython
3240128
from django.db import models from multiselectfield import MultiSelectField # Create your models here. class Hero(models.Model): Attribute = ( ('Strength', 'Strength'), ('Agility', 'Agility'), ('Intelligence', 'Intelligence'), ) Role = ( ('Carry', 'Carry'), ('Mid', 'M...
StarcoderdataPython
1707690
<gh_stars>10-100 class Solution: def duplicateZeros(self, arr: List[int]) -> None: """ Do not return anything, modify arr in-place instead. """ possibleDups, arrLength = 0, len(arr) - 1 for i in range(arrLength + 1): if i > arrLength - possibleDups: ...
StarcoderdataPython
4810896
<gh_stars>1-10 try: import tweepy except ImportError: print("ENSURE YOU HAVE INSTALLED tweepy") try: from credentials import * except ImportError: print("ENSURE YOU HAVE CREATED credentials.py IN THE SAME FOLDER") try: from wordcloud import WordCloud, STOPWORDS except ImportError: print("ENSURE ...
StarcoderdataPython
3264261
import functools import logging from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Optional, Set from procrastinate import builtin_tasks, exceptions, jobs, migration from procrastinate import retry as retry_module from procrastinate import store, utils if TYPE_CHECKING: from procrastinate import tas...
StarcoderdataPython
1654687
<gh_stars>1-10 import graphene from wagtailcommerce.accounts.schema import UserQuery from wagtailcommerce.addresses.mutations import DeleteAddress, EditAddress from wagtailcommerce.carts.schema import CartQuery from wagtailcommerce.carts.mutations import AddToCart, ModifyCartLine, UpdateCartCoupon from wagtailcommerce...
StarcoderdataPython
1646722
from .models import ClientsID # Generates a unique id or checks its presence in cookies class PollMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.user.is_anonymous: ...
StarcoderdataPython
3217515
from typing import List from ..models import Brand, Car, Customer, User USER_TOKENS = [] BRANDS = [ Brand(1, "Acura"), Brand(2, "<NAME>"), Brand(3, "Bentley"), Brand(4, "BMW"), Brand(5, "Cadillac"), Brand(6, "Chevrolet"), Brand(7, "Dodge"), Brand(8, "Fiat"), Brand(9, "Ferrari"), ...
StarcoderdataPython
4825457
<reponame>TripSage/TeamFormationAssistant<gh_stars>1-10 # pylint: skip-file from __future__ import absolute_import import json import unittest import sys sys.path.append(".") from app.connection import connect from app import connection from app import app TEST_DATA = { "name": "XYZ", "hourlyrate": "40", ...
StarcoderdataPython
46384
<filename>python/prizes.py<gh_stars>1-10 import fnmatch import codecs import tablib import os import requests import urlparse import shutil import frontmatter import yaml import io class PrizeSpreadsheets(object): """ """ def __init__(self, dir_path): self.dir_path = dir_path def get_spreadsh...
StarcoderdataPython
1634627
<filename>tools/verify_transplant.py import caffe import surgery import numpy as np import os import setproctitle setproctitle.setproctitle(os.path.basename(os.getcwd())) from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list, get_output_dir base_weights = '../data/imagenet_models/VGG16.v2.fcn-surgery.caffem...
StarcoderdataPython
1611557
from gym import make import gym_workflow.envs import sys import csv import os import json import matplotlib.pyplot as plt def main(): env = make('Montage-v12') # Data Format # { # action: { # makespan: [], # overhead: [], # delay etc # } # } records = {} ...
StarcoderdataPython
4841936
<gh_stars>10-100 import os import cv2 from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import torch import torchvision from utils.data.structures.bounding_box import BoxList from utils.data.structures.segmentation_mask import SegmentationMask from utils.data.structures.hier import Hier min_hier_per...
StarcoderdataPython
1634040
<filename>isdhic/utils.py import os import time import tempfile import numpy as np from csb.bio import structure from .universe import Universe def randomwalk(n_steps, dim=3): """ Generate a random walk in n-dimensional space by making steps of fixed size (unit length) and uniformly chosen direction. ...
StarcoderdataPython
3224263
<reponame>kamilpz/haystack import os import sys import html import logging import pandas as pd from json import JSONDecodeError from pathlib import Path import streamlit as st from annotated_text import annotation from markdown import markdown from htbuilder import H # streamlit does not support any states out of the...
StarcoderdataPython
3332119
from collections import defaultdict, deque distances = {} def depth(edges, n): visited = [0] * (n + 1) distance = [0] * (n + 1) # queue to do BFS. Q = deque() distance[1] = 0 Q.append(1) visited[1] = True while Q: x = Q.popleft() for i in edges[x]: if vi...
StarcoderdataPython
103506
# Generated by Django 3.0.8 on 2020-09-13 14:43 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('site_settings', '0004_si...
StarcoderdataPython
1601129
<gh_stars>1-10 from aries_cloudagent.config.injection_context import InjectionContext from aries_cloudagent.config.provider import ClassProvider from aries_cloudagent.core.protocol_registry import ProtocolRegistry from aries_cloudagent.core.plugin_registry import PluginRegistry from .v1_0.message_types import MESSAGE_...
StarcoderdataPython
3240614
<filename>Exercices/Secao05/exercicio08.py print('Digite duas notas de um aluno') n1 = float(input('Nota 1: ')) n2 = float(input('Nota 2: ')) if n1 >= 0 and n2 < 11 : media = (n1 + n2) / 2 print(f'A média do aluno foi: {media}') else: print(f'Nota inválida')
StarcoderdataPython
19771
"""Loads the config.json file and store key value pairs into variables""" import json with open('config.json', 'r', encoding='utf-8') as f: config = json.load(f) config_location_type = config['location_type'] config_location = config['location'] country = config['country'] config_covid_terms = config['...
StarcoderdataPython
176540
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """password_recovery.py: A CGI endpoint for handling password recovery""" import json import os import sys import sqlite3 import auth import groups import sendemail from httperror import HTTPError RETURN_HEADERS = [] def __do_get(): raise HTTPError("This script i...
StarcoderdataPython
8094
""" A base node that provides several output tensors. """ from ....layers.algebra import Idx from .base import SingleNode, Node from .. import _debprint from ...indextypes import IdxType class IndexNode(SingleNode): _input_names = ("parent",) def __init__(self, name, parents, index, index_state=None): ...
StarcoderdataPython
1710838
<reponame>zamazaljiri/django-pyston<filename>pyston/__init__.py # Apply patch only if django is installed try: from django.core.exceptions import ImproperlyConfigured try: from django.db import models # NOQA from pyston.patch import * # NOQA from pyston.filters.default_filters import *...
StarcoderdataPython
24367
<reponame>alexzanderr/metro.digital<filename>src/app/todos/routes.py """ # type: ignore type ignore is to tell LSP-pyright to ignore the line because something it thinks that there are errors, but actually at runtime there are not """ from .validation import validate_password_check from .validation import ...
StarcoderdataPython
1736203
<reponame>luisornelasch/melp<filename>migration.py import pandas from app.database.database import engine from app.models.models import Post file_name = "restaurantes.csv" data_frame = pandas.read_csv(file_name) data_frame.to_sql(con=engine, name=Post.__tablename__, if_exists='append', index=False) ...
StarcoderdataPython
3381760
import os import random import argparse import numpy as np import pandas as pd import torch from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler from torchtext.data import Field, LabelField, BucketIterator class Data_Prepper: def __init__(self, name, train_batch_size, n_pa...
StarcoderdataPython
3285915
# Modify from https://github.com/NVIDIA/Megatron-LM/blob/main/tasks/zeroshot_gpt/evaluate.py # coding=utf-8 # Copyright (c) 2020, 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 obt...
StarcoderdataPython
3229030
# -*- coding: utf-8 -*- from __future__ import absolute_import from colour.utilities import CaseInsensitiveMapping from .aces import (ACES_2065_1_COLOURSPACE, ACES_CC_COLOURSPACE, ACES_CCT_COLOURSPACE, ACES_CG_COLOURSPACE, ACES_PROXY_COLOURSPACE) from .aces_it import ACES_RICD fr...
StarcoderdataPython
3375978
import asyncio from .engine.fanhuaji import FanhuajiEngine from .engine.opencc import OpenCC as OpenCCEngine class Converter(): def __init__(self, engine, converter): self.engine = engine self.converter = converter def convert(self, content: str) -> str: """轉換 epub 內文 Args:...
StarcoderdataPython
1683287
<gh_stars>0 import jwt # TODO : move to environment variable JWT_SECRET_KEY = '<KEY>' def jwt_encode(data, expire_timestamp=None): if expire_timestamp is not None: data['exp'] = expire_timestamp return jwt.encode(data, JWT_SECRET_KEY, algorithm='HS512') def jwt_decode(token): return jwt.decode(to...
StarcoderdataPython
20800
""" Implements the base Parser as a Context Manager. """ from abc import ABCMeta, abstractmethod class Parser: """ Base abstract class for a parser. Further parsers should inherit from this and override the abstract parse() method. """ __metaclass__ = ABCMeta def __init__(self, filename)...
StarcoderdataPython
107474
<reponame>amachefe/XAc # Experiments going on here from bitcoinrpc.authproxy import AuthServiceProxy import json access = AuthServiceProxy("http://rpcusername:rpcpassword@127.0.0.1:8332") def reconcile_transaction(txid, amount, type): raw_transaction = access.getrawtransaction(txid, 1) vector_out = raw_trans...
StarcoderdataPython
1657500
<reponame>danielboloc/postgap<filename>postgap_html_report.py<gh_stars>1-10 #! /usr/bin/env python """ Copyright [1999-2019] EMBL-European Bioinformatics Institute 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 ...
StarcoderdataPython
1640889
#!/usr/bin/python import os import base64 import json import sys import logging import logging.handlers import subprocess import time import re import argparse operation = "keyvault_helper_module" script_path = os.path.realpath(__file__) script_directory = os.path.dirname(script_path) log_path = os.path.join(script_d...
StarcoderdataPython
3357242
<filename>bin/intensity_normalization/normalize/__init__.py from . import fcm, gmm, kde, lsq, nyul, whitestripe, zscore
StarcoderdataPython
3376553
<reponame>YuanMaSa/aws-well-architected-framework<gh_stars>10-100 """ This module is the main script to add EMR step """ import os import json import logging import time import boto3 from botocore.exceptions import ClientError msg_format = '%(asctime)s %(levelname)s %(name)s: %(message)s' logging.basicConfig(format=ms...
StarcoderdataPython
1787976
<reponame>gpauloski/ProxyStore<gh_stars>1-10 """MapReduce with FuncX and ProxyStore example""" import argparse import numpy as np import proxystore as ps import time from funcx.sdk.client import FuncXClient from typing import List def app_double(x: np.ndarray) -> np.ndarray: """Doubles input array""" return ...
StarcoderdataPython
1788913
from .task import * from .pymp_mapper import * from .pymp_iterator import * from .ray_backend import * from .ray_mapper import * from .ray_iterator import * # from .ray_dataloader import * from ._version import get_versions __version__ = get_versions()['version'] version = __version__ del get_versions def init_backe...
StarcoderdataPython
29899
<reponame>openlobby/openlobby-server from datetime import datetime def strip_value(data, *path): element = path[0] value = data.get(element) if len(path) == 1: data[element] = "__STRIPPED__" return value else: if isinstance(value, dict): return strip_value(value, *p...
StarcoderdataPython
3374458
""" This function will submit a specified number of sbatch jobs. Each sbatch job (I call them applyFunctionDaemons) will traverse the directory tree which starts from root. While traversing the directory tree, a daemon will look for a certain condition that indicates it is in the proper place to apply a function. Once...
StarcoderdataPython
3396825
<reponame>wcooley/python-gryaml<filename>tests/test__py2neo.py #!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for :mod:`gryaml._py2neo`.""" from __future__ import print_function, absolute_import import pytest # noqa @pytest.mark.integration def test_connect(graphdb): """Test :func:`~py2neo_compat.conn...
StarcoderdataPython
1609136
from setuptools import setup with open("README.md", "r", encoding="utf8") as rm: readme = rm.read() with open("requirements.txt") as rq: requirements = rq.read().split('\n') setup( name="lshashing", version="1.0.0", description="Nearest neighbors search using locality-sensitive hashing...
StarcoderdataPython
1611155
import json from django.conf.urls import url from django.http import HttpResponse from ecs.docstash.decorators import with_docstash @with_docstash() def simple_post_view(request): if request.method == 'POST': request.docstash.value = request.POST.dict() request.docstash.save() return HttpResp...
StarcoderdataPython
172156
<reponame>joshuagryphon/plastid #!/usr/bin/env python """Estimate :term:`sub-codon phasing` in a :term:`ribosome profiling` dataset, stratified by read length. Because ribosomes step three nucleotides in each cycle of translation elongation, in many :term:`ribosome profiling` datasets a triplet periodicity is observab...
StarcoderdataPython
58019
<gh_stars>100-1000 import click import json, cPickle import requests, zipfile import os, glob from music21 import analysis, converter, corpus, meter from music21.note import Note from constants import * @click.group() def datasets(): """Constructs various datasets.""" pass @click.command() @click.option('-...
StarcoderdataPython
189655
from chef.base import ChefObject class Environment(ChefObject): """A Chef environment object. .. versionadded:: 0.2 """ url = '/environments' api_version = '0.10' attributes = { 'description': str, 'cookbook_versions': dict, 'default_attributes': dict, 'o...
StarcoderdataPython
1763388
<reponame>rikiesxiao/android_testing_with_python #coding=utf-8 import re import time import subprocess import log class AdbException(Exception): def __init__(self, message): Exception.__init__(self, message+'\n') RETRY_CONNECTION_TIMES = 5 RETRY_CONNECTION_BETWEEN = 10 class ADB(object): def __init__...
StarcoderdataPython
65301
import sys from app import app from app import get_attempts_data as presenter from app import topic_hlr_train as model_functions from app import kafka_config import json from kafka import KafkaConsumer from kafka.structs import OffsetAndMetadata, TopicPartition from datetime import datetime, time, timedelta from collec...
StarcoderdataPython
132496
<reponame>paulondc/ushotgun import os import json import shotgun_api3 class SessionConfigError(Exception): """ Session Config Error. """ class Session(object): """ Singleton shotgun session. """ __sessionSingleton = None __sessionConfigEnv = 'USHOTGUN_SESSION_CONFIG_PATH' __shotgu...
StarcoderdataPython
87247
<gh_stars>0 #! /usr/bin/python # -*- coding: utf-8 -*- import re; import urllib; import urllib2; import sys; import os; def write_xml_tocache(xml, path): afile = open(path, 'w'); afile.write(xml); afile.close(); def crawl_xml_incache(word): qw = fix_query_string(word.lower()); swi_path = "/home/lizh...
StarcoderdataPython
56707
""" This file contains code to measure the performance of the system (c) 2015 Massachusetts Institute of Technology """ # Native import logging LOGGER = logging.getLogger(__name__) import time import re # CATAN import catan.db import catan.globals as G def log_database_counts(node_dict): """ ...
StarcoderdataPython