id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1621876 | <filename>hello_world/test_main.py
"""Tests main.py."""
from hello_world.main import message
def test_message() -> None:
"""Tests hello message."""
assert message() == "Hi world"
| StarcoderdataPython |
1627928 | #!/usr/bin/python
import cookielib
import urllib
import urllib2
import urllib3
import time
import json
import sys
import traceback
from atlas import measure_baseclass
login_url = 'https://access.ripe.net'
udm_url = 'https://atlas.ripe.net/atlas/udm.html'
data_url = 'https://atlas.ripe.net/atlas/udmgrid.json'
cookie_fi... | StarcoderdataPython |
116853 | from rest_framework import viewsets, permissions, status
from rest_framework.response import Response
class HealthViewSet(viewsets.ViewSet):
# uncomment this to make the endpoint require authentication
# permission_classes = [permissions.IsAuthenticated]
def list(self, request, *args, **kwargs):
... | StarcoderdataPython |
1730975 | #!/usr/bin/env python
"""Contains the Data Model for the MAC Address(es) Resource.
Represents the data model for the IEEE MA-L Public Assignments
Listing data. The three-octet MA-L can be used as a lookup
to help identify a provided Organizationally Unique Identifier
(OUI) which identifies a vendor, manufacturer or o... | StarcoderdataPython |
3334053 | import zerorpc
import pandas as pd
import logging
import numpy as np
logging.basicConfig()
def rand_weights(n):
k = np.random.rand(n)
return k / sum(k)
def calcMuSigma(returns):
p = np.asmatrix(np.mean(returns, axis=1))
w = np.asmatrix(rand_weights(len(returns)))
C = np.asmatrix(np.cov(returns))
... | StarcoderdataPython |
3318536 | from .action import default_kwargs, plot_action, generate_arg_and_kwags, get_value, get_subset
from .action import DataSource, AxPlot
def _hist_plotter(df: DataSource, y, *arg, **kwargs):
_y = get_subset()(df, y)
def plot(ax):
ax.hist(_y, **kwargs)
return ax
return plot
def hist(**prese... | StarcoderdataPython |
1743858 | from rx.core import Observer, ObservableBase, Disposable
from rx.subjects import Subject
from rx.disposables import AnonymousDisposable
from rx.concurrency import current_thread_scheduler
from rx.core.notification import OnCompleted, OnError, OnNext
class ControlledSubject(ObservableBase, Observer):
def __init__(... | StarcoderdataPython |
1669095 | <filename>courses/migrations/0004_auto_20190414_2045.py<gh_stars>0
# Generated by Django 2.2 on 2019-04-14 19:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('courses', '0003_auto_20190414_1910'),
]
operations... | StarcoderdataPython |
1743512 | <reponame>hritools/faceR<filename>faceR/tracking/dlib_tracking.py<gh_stars>0
"""
A stateful tracker of arbitrary objects
"""
import logging
import dlib
from multiprocessing import Pool
name_list = list()
d_trackers = list()
class ReusablePool:
"""
Manage reusable tracker objects for use by client.
"""
... | StarcoderdataPython |
3349681 | import distutils.util
import cv2
import numpy as np
import paddle
from tqdm import tqdm
def print_arguments(args):
print("----------- Configuration Arguments -----------")
for arg, value in sorted(vars(args).items()):
print("%s: %s" % (arg, value))
print("----------------------------------------... | StarcoderdataPython |
72882 | from textbox.data.dataloader.abstract_dataloader import AbstractDataLoader
from textbox.data.dataloader.single_sent_dataloader import SingleSentenceDataLoader
from textbox.data.dataloader.paired_sent_dataloader import PairedSentenceDataLoader
from textbox.data.dataloader.attr_sent_dataloader import AttributedSentenceDa... | StarcoderdataPython |
4841815 | <gh_stars>1-10
City = [
{
"热门城市": [
{
"name": "北京",
"key": "热门"
},
{
"name": "上海",
"key": "热门"
},
{
"name": "广州",
"key": "热门"
},
{
"name": "深圳",
"key": "热门"
},
{
"name": "成都",
"key": "热门"
},
{
"name": "重庆",
"key": "热门"
},
{
"name": "天津",
"key": "热门"
},
{
"name": "杭州",
"key": "热门"
},
... | StarcoderdataPython |
47755 | from pathlib import Path
from shutil import copyfile
import logging
def move_files(dir_from: Path, dir_to: Path):
logging.info(f"Moving files from '{dir_from}' to '{dir_to}'")
p = dir_from.glob("**/*")
input_paths = [x for x in p if x.is_file()]
for input_path in input_paths:
filename = input_... | StarcoderdataPython |
191032 | """add sol associated wallet
Revision ID: f64a484f1496
Revises: <PASSWORD>
Create Date: 2021-07-21 15:58:05.108372
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "f64a484f1496"
down_revision = "<PASSWORD>"
branch_label... | StarcoderdataPython |
3397564 | import numba
import numpy as np
from math import sqrt, sin, cos, acos, atan2
@numba.njit
def residual(t, yin, yp, R, L1, L2, H, Ct, Cdv, Cd, St, Sv, rho, Ma, Mv, Iv, theta):
"""Calculates the residual of the system of equations G(t, y, yp) == 0."""
x,y,p,x1,y1,p1 = yin
x2,y2,p2 = yp[3:6]
t1,dt1,ddt1,t2... | StarcoderdataPython |
3291866 | <filename>examples/mnist.py
from __future__ import absolute_import, division, print_function
import os
import time
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow import keras
from odin.training import Trainer
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['TF_FORC... | StarcoderdataPython |
1726388 | <reponame>zauberzeug/rosys
from .communication import Communication
from .communication_factory import CommunicationFactory
from .serial_communication import SerialCommunication
from .web_communication import WebCommunication
| StarcoderdataPython |
1733198 |
if __name__ == "__main__":
final_answer = 0
lookup_values = {')':3,']':57,'}':1197,'>':25137}
lookup_opens = {')':'(',']':'[','}':'{','>':'<'}
with open("10input.txt") as f:
lines = f.readlines()
for line in lines:
stripped_line = list(line.rstrip("\n"))
# The entries here r... | StarcoderdataPython |
1728056 | <filename>flowserv/controller/worker/manager.py<gh_stars>1-10
# This file is part of the Reproducible and Reusable Data Analysis Workflow
# Server (flowServ).
#
# Copyright (C) 2019-2021 NYU.
#
# flowServ is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file f... | StarcoderdataPython |
1724326 | <filename>tests/detections/test_detections.py
'''
Test that computes detections for all entries in the database that do not have
a `labels_path` column populated. The column is populated with the path to the
labels on disk.
Copyright 2020 Voxel51, Inc.
voxel51.com
'''
import pandemic51.core.detections as pand
pand.d... | StarcoderdataPython |
180663 | <reponame>DanSava/showmewhatyougot<gh_stars>0
import requests
import re
import json
import sched
import time
from email.mime.text import MIMEText
import smtplib
import logging
import os
class Scraper(object):
def __init__(self):
self.logger = logging.getLogger('croller')
self.processed_urls = []
... | StarcoderdataPython |
1711931 | from portality import models
# these are the ids of the journal and the issn of the erroneous continuation
id = "d241030fda0b419f9aaaf542d57a61af"
issn = "0049-3449"
# details to create the new journal record
name = "<NAME>"
email = "<EMAIL>"
owner = "00493449"
# get the journal and the other journal's bibjson from ... | StarcoderdataPython |
1629406 | <filename>Arithmetic Formatter/arithmetic_arranger.py
def arithmetic_arranger(problems, print_ans = False):
count = 1
if len(problems)>5:
return "Error: Too many problems."
line_1 = ""
line_2 = ""
dash_line = ""
ans_line = ""
for problem in problems:
chars = problem.split()
try :
... | StarcoderdataPython |
1638421 | """File IO for Flickr 30K images and text captions.
Author: <NAME>
Contact: <EMAIL>
Date: September 2019
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import logging
import numpy as np
def load_flickr30k_splits(splits_dir... | StarcoderdataPython |
1704261 | <reponame>indigo-dc/dogs_breed_det<filename>dogs_breed_det/config.py
# -*- coding: utf-8 -*-
"""
Module to define CONSTANTS used across the project
"""
import os
from webargs import fields
from marshmallow import Schema, INCLUDE
# identify basedir for the package
BASE_DIR = os.path.dirname(os.path.normpath(os.path.... | StarcoderdataPython |
1603549 | """Compare Pulsar and HabCat coordinates"""
import csv
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from astropy import coordinates as coord
def flipra(coordinate):
"""Flips RA coordinates by 180 degrees"""
coordinate = coordinate + 180
if coordinate > 360:
coordin... | StarcoderdataPython |
3284562 | <filename>scripts/backup-tool.py
#! /usr/bin/python
"""Create a backup.
"""
import archive.bt
archive.bt.backup_tool()
| StarcoderdataPython |
1701740 | <reponame>datavaluepeople/tentaclio
"""HTTP Stream client."""
import io
from typing import Optional
from urllib import parse
import requests
from tentaclio import protocols
from . import base_client, decorators, exceptions
__all__ = ["HTTPClient"]
DEFAULT_TIMEOUT = 10.0
DEFAULT_HEADERS = {"Accept": "application... | StarcoderdataPython |
77578 | # small helper script to check results
import fnmatch
import os
import shutil
import time
import json
import sys
liste = []
CHECKFOLDER = sys.argv[1]
"""
# we do not need the pickle files here
for root, dirnames, filenames in os.walk(CHECKFOLDER):
for filename in fnmatch.filter(filenames, 'scenario.pickle'):
... | StarcoderdataPython |
1740190 | <reponame>UCLCheminformatics/ScaffoldGraph
"""
scaffoldgraph tests.vis.test_vis_utils
"""
import scaffoldgraph.vis.utils as vis_utils
import matplotlib.pyplot as plt
import random
import pytest
import re
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit import Chem
from scaffoldgraph.utils import suppress_rdlogger
... | StarcoderdataPython |
3278382 | <reponame>wilkeraziz/smtutils
"""
Extracts minimal phrases from symmetrized word alignments
"""
from collections import defaultdict, deque
def as_words(phrase, id2word):
return tuple(id2word[i] for i in phrase)
def try_expand(f, f2e, f_min, f_max, e_min, e_max):
"""
Try to expand the boundaries of a p... | StarcoderdataPython |
4804265 | import humanize
import pathlib
from typing import Coroutine
async def async_progress(path: pathlib.Path, reader: Coroutine) -> bytes:
def progress(loaded, total, bar_len=30):
filled_len = int(round(bar_len * loaded / total))
empty_len = bar_len - filled_len
loaded = humanize.naturalsize(... | StarcoderdataPython |
105817 | # Copyright 2015 Palo Alto Networks, 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 agre... | StarcoderdataPython |
3254930 |
from api import celery as celery_app
from api.models import Device as DeviceModel
from api.async.base import DeviceTask
from api.async import celery_logger
from api import device_refresh_redis_conection
import orangengine
REDIS_DEV_REF_INTV_COUNT_PREFIX = 'dev:refresh:interval:count:'
CELERY_BEAT_INTERVAL = 5
@cel... | StarcoderdataPython |
196336 | # Copyright 2016 NTT DATA.
# 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 app... | StarcoderdataPython |
117137 | from django import forms
from sysrev.api import PubMed
from sysrev.models import *
from widgets import *
class ProfileForm(forms.ModelForm):
class Meta:
model = User
fields = ("email",)
def clean_email(self):
email = self.cleaned_data.get('email')
if self.instance and self.i... | StarcoderdataPython |
1606408 | from ..titanic import digital
from ..titanic import gmpmath
from ..titanic.ops import OP
class MPNum(digital.Digital):
# must be implemented in subclasses
@classmethod
def _select_context(cls, *args, ctx=None):
raise ValueError('virtual method: unimplemented')
@classmethod
def _round_to_... | StarcoderdataPython |
186048 | <reponame>vhn0912/python-snippets<filename>notebook/pypdf2_split.py
import PyPDF2
merger = PyPDF2.PdfFileMerger()
merger.append('data/src/pdf/sample1.pdf', pages=PyPDF2.pagerange.PageRange(':2'))
merger.write('data/temp/sample_split1.pdf')
merger.close()
merger = PyPDF2.PdfFileMerger()
merger.append('data/src/pdf/... | StarcoderdataPython |
3320312 | <reponame>zStartKiller/BotDiscordPython<filename>main.py
# Importações
import discord
import os
import asyncio
import datetime
from discord.ext import commands
from config import settings
intents=intents=discord.Intents.all()
intents.members = True
bot = commands.Bot(intents=intents, command_prefix =co... | StarcoderdataPython |
1760036 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from functools import partial
import time
__all__ = ['ResNeXt', 'resnet50', 'resnet101']
def conv3x3x3(in_planes, out_planes, stride=1):
# 3x3x3 convolution with padding
return nn.Conv3d(
... | StarcoderdataPython |
3291757 | <reponame>adeutscher/core-tools
#!/usr/bin/env python
from __future__ import print_function
import csv, getopt, json, os, sys
format_name = "YAML"
#
# Common Colours and Message Functions
###
def _print_message(header_colour, header_text, message, stderr=False):
f=sys.stdout
if stderr:
f=sys.stderr
... | StarcoderdataPython |
1736118 | <reponame>minhongqi/federated
# Copyright 2018, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | StarcoderdataPython |
40444 | # This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that ... | StarcoderdataPython |
3223084 | <gh_stars>1-10
import re
import enchant
from wb_nlp import dir_manager
en_dict = enchant.Dict("en_US")
VALID_TOKEN_PAT = re.compile('^[a-z]+$')
with open(dir_manager.get_data_dir("whitelists", "whitelists", "wordfreq-enwiki-latest-pages-articles.xml.bz2.txt")) as fl:
with open(dir_manager.get_data_dir("whitelists"... | StarcoderdataPython |
4817939 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 03 11:30:20 2017
@author: <NAME>
Index forward/backward neighbors and admissibility for monotone sets.
"""
import numpy as np
def admissible_neighbors(index, index_set):
"""Given an index and a monotone index set, find admissible neighboring
indices"""
for... | StarcoderdataPython |
3382441 | <reponame>InterstellarLabs/dca<filename>dca/templates/view.py
"""
DCA view template.
It's used to generate views for a model.
"""
# App imports.
from dca.utils import default | StarcoderdataPython |
102516 | """
TODO: doc for init
"""
__version__ = '1.0.0'
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 <NAME>'
from .timeline import Timeline
from .schemas import DocumentError
| StarcoderdataPython |
1650991 | from enum import Enum, unique
from .color import Color
@unique
class BrightColor(Enum):
"""Options for bright colors."""
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
MAGENTA = "\033[95m"
BLUE = "\033[94m"
CYAN = "\033[96m"
WHITE = "\033[97m"
BLACK = "\033[90m"
DEFA... | StarcoderdataPython |
36630 | """
Compartmentalize:
[ ascii art input ]
---------------
| maybe some |
| sort of auxillary |
| drawing program |
|
|
\ /
v
[ lex/parser ] --> [ translater ]
--------- ----------
| grammar | | notes literals|
| to numerical |
... | StarcoderdataPython |
1751340 | import enum
import construct
from construct import Struct, Int32ub, Switch, Float32b, Byte, PrefixedArray, Int64ub
from retro_data_structures.adapters.enum_adapter import EnumAdapter
from retro_data_structures.common_types import String, AssetId64, AssetId32
class MetaAnimationType(enum.IntEnum):
Play = 0
B... | StarcoderdataPython |
1667500 | """Data module."""
import math
import os
from typing import Collection, Dict, Iterable, List
import numpy as np
import pandas as pd
import torch
from gsea_api.molecular_signatures_db import (
GeneSet,
GeneSets,
MolecularSignaturesDatabase,
)
from spexlvm import config
# logging stuff
logger = config.logg... | StarcoderdataPython |
11285 | <filename>src/algoritmia/problems/binpacking/firstfitbinpacker.py<gh_stars>1-10
from algoritmia.problems.binpacking.nextfitbinpacker import NextFitBinPacker
class FirstFitBinPacker(NextFitBinPacker):#[full
def pack(self, w: "IList<Real>", C: "Real") -> "IList<int>":
x = [None] * len(w)
free = ... | StarcoderdataPython |
3292716 | <reponame>pasta96/django-drf-react-example
from django.contrib.auth import get_user_model
from rest_framework import serializers
from . import models
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('id', get_user_model().USERNAME_FIELD)
class P... | StarcoderdataPython |
17542 | '''
' Python Regular Expression 正则表达式
'
'''
import re
def test_match():
s = 'hello python Hello'
p = 'hello'
o = re.match(p, s)
print(o)
print(dir(o))
print(o.group()) # 返回匹配的字符串
print(o.span()) # 范围
print(o.start()) # 开始处
print('*' * 30, 'flags参数的使用')
o2 = re.match(p, s, re.L)
print(o2.grou... | StarcoderdataPython |
1627053 | import FWCore.ParameterSet.Config as cms
fftjetVertexAdder = cms.EDProducer(
"FFTJetVertexAdder",
#
# Label for the beam spot info
beamSpotLabel = cms.InputTag("offlineBeamSpot"),
#
# Label for an existing collection of primary vertices
existingVerticesLabel = cms.InputTag("offlinePrimaryVe... | StarcoderdataPython |
3284037 | <reponame>ResonantGeoData/ResonantGeoData
# Generated by Django 3.2.5 on 2021-07-13 10:17
import django.contrib.postgres.fields.ranges
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rgd_imagery', '0001_initial'),
]
operations = [
migrations.Ad... | StarcoderdataPython |
3273438 | import os
import random
from typing import Any, Dict
import numpy as np
# from mmcls.models.losses import accuracy, f1_score, precision, recall
# from mmcls.models.losses.eval_metrics import class_accuracy
from .base_dataset import BaseDataset
from .builder import DATASETS
# 0 1 2 ... | StarcoderdataPython |
1645592 | <reponame>govind794/all-programming<filename>python/String/add_string.py<gh_stars>0
# Write a python program to add 'ing' at the end of a givan string(length should be at least 3).
# if the givan string already ends with 'ing' then add 'ly' instead if the string length of the givan string
# is less then 3, leave it unc... | StarcoderdataPython |
1710270 | <filename>tests/test_00_dxf_low_level_structs/test_016_encoding.py
# Created: 26.03.2016
# Copyright (C) 2016-2019, <NAME>
# License: MIT License
import pytest
import codecs
from ezdxf.lldxf.encoding import dxf_backslash_replace
codecs.register_error('dxfreplace', dxf_backslash_replace) # setup DXF unicode encoder -... | StarcoderdataPython |
1645003 | # AUTHOR: whisperain (https://github.com/memset0)
from my_array import Array
STEP = 1.5
class List:
def __len__(self):
return self.len
def __getitem__(self, index):
return self.arr[index if index >= 0 else index + self.len]
def __setitem__(self, index, value):
self.arr[index if ... | StarcoderdataPython |
3389664 | import re
daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ScheduleType = {
"Понедельник": daysOfWeek[0],
"Вторник": daysOfWeek[1],
"Среда": daysOfWeek[2],
"Четверг": daysOfWeek[3],
"Пятница": daysOfWeek[4],
"Суббота": daysOfWeek[5],
"Воскресенье"... | StarcoderdataPython |
93624 | <reponame>Steinbeck-Lab/RanDepict
import os
import pathlib
import numpy as np
import io
from skimage import io as sk_io
from skimage.color import rgba2rgb, rgb2gray
from skimage.util import img_as_ubyte, img_as_float
from PIL import Image, ImageFont, ImageDraw, ImageStat
from multiprocessing import set_start_method, ge... | StarcoderdataPython |
3326976 | <filename>SRT/reservation.py
from .constants import *
class SRTTicket:
SEAT_TYPE = {"1": "일반실", "2": "특실"}
PASSENGER_TYPE = {
"1": "어른/청소년",
"2": "장애 1~3급",
"3": "장애 4~6급",
"4": "경로",
"5": "어린이",
}
def __init__(self, data):
self.car = data["scarNo"]
... | StarcoderdataPython |
4814702 | <gh_stars>0
#!/usr/bin/env python
import math
n = 325489
square = n
while True:
root = math.sqrt(square)
if root%1 == 0 and root%2 == 1:
break
square = square + 1
diff = (square - n)%root
middle = root//2
ans = abs(diff - middle) + (root//2)
| StarcoderdataPython |
111044 | <gh_stars>1-10
"""
Tools for working with files and file systems
"""
import os
import re
import itertools
import functools
import calendar
import contextlib
import logging
import datetime
import glob
import tempfile
import platform
import ctypes
import importlib
import pathlib
from typing import Dict, Union
from sing... | StarcoderdataPython |
4807547 | <filename>tests/bot/test_handle_message.py
"""Test handle_message."""
import pytest
from phial import Message, Phial
from phial.errors import ArgumentValidationError
def test_handle_message_handles_none_correctly() -> None:
"""Test handle_message handle None correctly."""
def command() -> None:
rais... | StarcoderdataPython |
1784413 | <filename>refla/db.py<gh_stars>0
from copy import copy
data = [
{
'id': 1,
'title': u'Discuss report with John',
'done': False
},
{
'id': 2,
'title': u'Get a haircut',
'done': True
},
{
'id': 3,
'title': u'Pay electricity bill',
... | StarcoderdataPython |
1665032 | from auth.validate import validade
client = validade()
def status_update(tweet):
updateStatusRequest = client.request(
f'https://api.twitter.com/1.1/statuses/update.json?status={tweet}',
method='POST'
)
return updateStatusRequest
def home_timeline():
homeTimelineRequest = client.r... | StarcoderdataPython |
3309628 | <reponame>PureFunctor/amalgam-lisp
from __future__ import annotations
from contextlib import contextmanager
from typing import (
cast,
Dict,
Iterable,
Mapping,
Optional,
TYPE_CHECKING,
)
if TYPE_CHECKING: # pragma: no cover
from amalgam.amalgams import Amalgam
from amalgam.engine imp... | StarcoderdataPython |
1773029 | """
Author: <NAME>
Date: Nov 25, 2020
Retrieve datasets from a URL, file of URLs, or GitHub directory URL
Usage: get_datasets.py -i=<input> -o=<output> [-u] [-f] [-g] [-v]
Options:
-i <input>, --input <input> Input URL
-o <output>, --output <output> The local output location to transfer the datasets
[-u] ... | StarcoderdataPython |
4800490 | <gh_stars>1-10
from unittest.mock import Mock
from dagster import build_init_resource_context, ResourceDefinition
from hca_orchestration.contrib.data_repo.data_repo_service import DataRepoService
from hca_orchestration.resources.config.datasets import find_or_create_project_dataset
from hca_orchestration.models.hca_d... | StarcoderdataPython |
187875 | <gh_stars>1-10
# coding=utf-8
# Copyright 2011 Foursquare Labs Inc. All Rights Reserved
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import unittest
from foursquare.source_code_analysis.scala.scala_import_sorte... | StarcoderdataPython |
1682583 | #!/usr/bin/env python2
import string
import sys
_KEYWORDS = dict([ (j, i) for i, j in enumerate([
'for', 'while', 'until',
'if', 'unless', 'elif', 'else',
'switch', 'case',
'{', '}', '(', ')',
';', ',', '.', '='
]
)])
def keywords_substitution(tokens):
"""
Transf... | StarcoderdataPython |
3210676 | """test_extensions.py."""
# Import a minimal text loader class, the functions for scrubber pipelines,
# and the scrubber function registry
from lexos.io.basic import Loader
from lexos.tokenizer import extensions, make_doc
# Load a text
data = ["tests/test_data/Austen_Pride.txt"]
loader = Loader()
loader.load(data)
#... | StarcoderdataPython |
1717794 | <reponame>ankitsumitg/python-projects<filename>gas_mileage/test_milesPerGallon.py<gh_stars>1-10
"""
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import gas_mileage
class TestMilesPerGallon(unittest.TestCase):
def test001_milesPerGallonExists(self):
se... | StarcoderdataPython |
1756221 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-25 18:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... | StarcoderdataPython |
165886 | <reponame>INDElab/conversationkg
# -*- coding: utf-8 -*-
import pickle
from urllib.parse import urlparse
from process_emails import extract_meta, parse_header, url_pattern,\
email_address_pattern, group_into_convos
class Ledger(dict):
def __init__(self):
super().__init__(self... | StarcoderdataPython |
3250544 | <reponame>rsdoherty/azure-sdk-for-python
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import HttpResponseError
from azure.digit... | StarcoderdataPython |
3352476 | <reponame>kyawmyomin/nornir
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Set,
Union,
KeysView,
ValuesView,
ItemsView,
Iterator,
TypeVar,
)
from nornir.core.configuration import Config
from nornir.core.plugins.connections import (
ConnectionPlugin,
Co... | StarcoderdataPython |
3350282 | <reponame>wearpants/scrapi
import logging
import functools
from itertools import islice
from datetime import date, timedelta
from celery import Celery
from scrapi import util
from scrapi import events
from scrapi import settings
from scrapi import registry
from scrapi import processing
from scrapi.util import timesta... | StarcoderdataPython |
1675232 | import re
import sqlite3
from json import load, loads
from django.db import models
# Create your models here.
class ChoiceQuestions(models.Model):
def __init__(self, data):
self.data = str(data)
def _remove_non_alphanum_char(self, string):
return re.sub(r'\W+', ' ', string)
... | StarcoderdataPython |
1663169 | <reponame>blurks/wold2
# coding=utf-8
"""fix poly word
Revision ID: 28959d50de6
Revises: 207db8b425a8
Create Date: 2015-08-04 12:39:04.468959
"""
# revision identifiers, used by Alembic.
revision = '28959d50de6'
down_revision = '207db8b425a8'
import datetime
from alembic import op
import sqlalchemy as sa
def upg... | StarcoderdataPython |
62102 | <reponame>Kanavoy/UODS
# filepaths, except with dots instead of slashes and no file extension
from Algorithms.Update.relative_agreement import perform_update as wrapped_update
from Algorithms.Intervention.degree import intervene as wrapped_intervene
# make sure you set opts.intervention.numb to 0, otherwise
# it'll ex... | StarcoderdataPython |
116314 | import sympy as sp
x, y, z = sp.symbols('x y z')
sp.init_printing()
# Here we simply give the input needed as The Following:
# ( X0 ) & ( X1 ) & ( X2 )
# ( Fx ) is the equation of the function
# ( n ) is the number of Iterations needed
x0 = 4.5
x1 = 5.5
x2 = 5
Fx = x**3 - 13*x - 12
n = 3
print("________________... | StarcoderdataPython |
1717243 | import json
import os
from distutils.dir_util import copy_tree
from unittest import TestCase
from osbot_aws.apis.Secrets import Secrets
from osbot_gsuite.apis.GDrive import GDrive
from osbot_gsuite.apis.GSheets import GSheets
from osbot_gsuite.apis.GSuite_Setup import GSuite_Setup
from osbot_utils.utils.Dev import Dev
... | StarcoderdataPython |
1638011 | from scapy.all import sniff
from threading import Thread, Event
class Sniffer(Thread):
''' Thread for incommig dns requests '''
def __init__(self, interface, sniff_filter, packet_handler, fin_action):
super().__init__()
self.interface = interface
self.SNIFF_FILTER = sniff_filte... | StarcoderdataPython |
3354476 | <reponame>dmccloskey/SBaaS_quantification<filename>SBaaS_quantification/stage01_quantification_MQResultsTable_io.py
#system
import json
#SBaaS
from .stage01_quantification_MQResultsTable_query import stage01_quantification_MQResultsTable_query
#from .stage01_quantification_analysis_query import stage01_quantification_... | StarcoderdataPython |
4831133 | # Generated by Django 3.1.6 on 2021-03-27 20:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('information_sharing', '0004_auto_20210327_2105'),
]
operations = [
migrations.CreateModel(
name='Discoverymethod',
f... | StarcoderdataPython |
3320314 | """
Script to get fragment size distribution
@author: <NAME>
"""
##### IMPORT MODULES #####
# import necessary for python
import os
#import matplotlib as mpl
#mpl.use('PS')
import matplotlib.pyplot as plt
from pyatac.fragmentsizes import FragmentSizes
from pyatac.chunk import ChunkList
def get_sizes(args):
"""fu... | StarcoderdataPython |
1788714 | <reponame>djfkahn/MemberHubDirectoryTools
import unittest
from unittest.mock import patch
import os
import family
import hub_map_tools
import roster
import person
data_file_path = os.path.abspath("./family_tests/")
hub_file_name = data_file_path + "/hub_map.csv"
common_hub_map = hub_map_tools.ReadHubMapFromFile(hub_f... | StarcoderdataPython |
3354940 | import datetime
import great_expectations as ge
import great_expectations.jupyter_ux
from great_expectations.checkpoint import LegacyCheckpoint
from great_expectations.data_context.types.resource_identifiers import ValidationResultIdentifier
context = ge.data_context.DataContext()
# Feel free to change the name of yo... | StarcoderdataPython |
3202311 | <filename>research/multi_representation_adversary/multi_representation_adversary/trainer.py
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apa... | StarcoderdataPython |
3349706 | import nextcord
async def option_management(game, player_list):
def check(msg):
return msg.author == game.mj
while True:
em = nextcord.Embed(title="Option", description="```diff\noption:\n{}```".format(
"\n".join("{} {} : {}".format('+' if j else '-', i, repr(j))
for i, ... | StarcoderdataPython |
1632015 | <filename>server.py<gh_stars>0
from object import Object
OK = 1
NOK = 0
class Server():
def __init__(self, name):
self.name = name
self.counter = 0
self.objects = []
def sync_to_client(self, counter):
objects = [o for o in self.objects if o.lastupdate_cou... | StarcoderdataPython |
3249565 | <filename>quadpy/sphere/stroud.py
# -*- coding: utf-8 -*-
#
import numpy
import sympy
from .helpers import cartesian_to_spherical
from .albrecht_collatz import AlbrechtCollatz
from .mclaren import McLaren
from ..nsphere.stroud1969 import Stroud1969
class Stroud(object):
"""
<NAME>,
Approximate Calculati... | StarcoderdataPython |
1686014 | <filename>callnumber_app/tests.py
# -*- coding: utf-8 -*-
import logging, pprint
from django.test import TestCase
log = logging.getLogger(__name__)
TestCase.maxDiff = None
class ClientTest( TestCase ):
""" Tests views via Client. """
def test_callnumber_response(self):
""" Checks two submitted cal... | StarcoderdataPython |
1767547 | <reponame>FarmVivi/kodihikvision
import xbmcaddon
def getSettingString(setting_id):
return xbmcaddon.Addon(id='plugin.farmvivi.hikvision').getSettingString(setting_id)
def getSettingInt(setting_id):
return xbmcaddon.Addon(id='plugin.farmvivi.hikvision').getSettingInt(setting_id)
| StarcoderdataPython |
6619 | #!/usr/bin/python
"""
Firewall for munkireport.
By Tuxudo
Will return all details about how the firewall is configured
"""
import subprocess
import os
import sys
import platform
import re
import plistlib
import json
sys.path.insert(0,'/usr/local/munki')
sys.path.insert(0, '/usr/local/munkireport')
from munkilib impo... | StarcoderdataPython |
3256977 | <filename>app/models.py
from . import login_manager
from . import database
from .exceptions import ValidationError
from datetime import datetime, timezone
from itsdangerous import BadHeader, SignatureExpired
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from sqlalchemy.ext.hybrid import hybrid_... | StarcoderdataPython |
3309450 | <reponame>th2-net/th2-common-py<gh_stars>0
# Copyright 2020-2021 Exactpro (Exactpro Systems Limited)
#
# 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/li... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.