id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1799376 | <filename>dao/user/user_status_dao.py
# coding=utf-8
from dao.base.base_dao import BaseDao
from support.db.mysql_db import doctor_user_conn
class UserStatusDao(BaseDao):
db_name = "doctor_user"
table_name = "user_status"
@classmethod
def insert(cls, user_id, cuid, longitude, latitude, open_push, ip, ... | StarcoderdataPython |
69544 | <gh_stars>1-10
from datetime import datetime
from scrapy import signals
class MonitorExtension(object):
"""
采集并上报监控指标,如scrapy状态或需要的业务指标
"""
def __init__(self, stats):
self.stats = stats
self.spider = None
@classmethod
def from_crawler(cls, crawler):
ext = cls(crawler... | StarcoderdataPython |
1642942 | # Generated by Django 2.2.8 on 2020-01-18 16:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hoodapp', '0007_neighbourhood_image'),
]
operations = [
migrations.AddField(
model_name='health',
name='image',
... | StarcoderdataPython |
4840158 | import sys
sys.path.append("../../src")
from pulumi_gcp_network.subnets import Subnets # noqa
project_id = "demo-project"
network_name = "example-vpc"
subnets = [
{
"subnet_name": "subnet-01",
"subnet_ip": "10.10.10.0/24",
"subnet_region": "us-west1",
},
{
"subnet_name": ... | StarcoderdataPython |
1677861 | from .action import Action
class EnvInterface:
"""The interface defines the methods which each environment class needs to implement"""
def reset(self) -> object:
"""Resets the environment
Returns
state (list[float]): The state of the environment"""
pass
def step(self... | StarcoderdataPython |
3273995 | """fobject
Retrieve id of tile at given position.
Retrieve the internal id of a tile at a certain position. The internal id corresponds to the id you see when hovering over a tile in LDTK.
in:
- Numeric: id of the layer
- Numeric: x position
- Numeric: y position
out:
- Numeric: internal id of the tile
"""
class ... | StarcoderdataPython |
59058 | <filename>Questions/Chief in Chains/solution.py<gh_stars>1-10
class Solution(object):
def reconstructQueue(self, people):
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
m = int(input())
k = Solution()
a... | StarcoderdataPython |
1799481 | <reponame>AndyChiangSH/1102_Web-based-systems<filename>midterm3/s4108056005/restaurant/migrations/0003_auto_20220524_2246.py
# Generated by Django 3.1.2 on 2022-05-24 14:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('restaurant', '0002_user'),
]
op... | StarcoderdataPython |
3226338 | """Contains common tensor operations."""
from typing import Sequence, Union
import torch
import numpy as np
def collate_tensors(
tensors: Sequence[torch.Tensor], pad_value: Union[int, float, bool, str] = 0
):
dtype = tensors[0].dtype
device = tensors[0].device
batch_size = len(tensors)
shape = (b... | StarcoderdataPython |
157762 | <gh_stars>1-10
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def taskflow_repository():
maybe(
http_archive,
name = "taskflow",
urls = [
"https://github.com/taskflow/taskflow/archive/refs/tags/... | StarcoderdataPython |
4838679 | <gh_stars>0
import turtle as t
t.penup() #move pen without writing
t.ht()
## Change turtle to a square here.
t.shape('square')
STAMP_ID = 0
STAMP_IDs = []
def stamp_block():
'''
Places a block in the center of the canvas.
'''
## HINT
global STAMP_ID
STAMP_ID = t.stamp()
def erase_block():
... | StarcoderdataPython |
3351914 | <gh_stars>0
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype("float32")
y_data = x_data * 0.1 + 0.3
W = tf.Variable(tf.random_uniform([1],-1.0,1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimize... | StarcoderdataPython |
193496 | from __future__ import division
import os
import numpy as np
import pprint
import tensorflow as tf
import tensorflow.contrib.slim as slim
import pickle, csv
from utils import *
from model import UNet3D, SurvivalVAE
flags = tf.app.flags
flags.DEFINE_integer("epoch", 4, "Epoch to train [4]")
flags.DEFINE_string("train_... | StarcoderdataPython |
1786435 | # Generated by Django 3.1.2 on 2020-10-11 22:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='location',
field=... | StarcoderdataPython |
1693076 | from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
db = SQLAlchemy()
ma = Marshmallow()
class CarCount(db.Model):
id = db.Column(db.Integer, primary_key=True)
date_time = db.Column(db.DateTime)
number = db.Column(db.Integer)
class AirParameters(db.Model):
id = db.Col... | StarcoderdataPython |
3205709 | <gh_stars>0
def escriu_capçelera(nom_fitxer):
with open(nom_fitxer, mode='w') as imatge:
imatge.write('P1\n')
imatge.write('3 3\n')
if __name__ == '__main__':
escriu_capçelera('imatge.pbm') | StarcoderdataPython |
1755219 | <filename>src/data_loaders/data_loader.py
import pickle
import re
import constants
class Data(object):
def __init__(self, inputs=None, outputs=None):
self.inputs = inputs # list of input sequences e.g. chars, words
self.outputs = outputs # list of output sequences (label sequences)
class Rest... | StarcoderdataPython |
3323431 | <gh_stars>10-100
from kratos import *
from lake.attributes.config_reg_attr import ConfigRegAttr
class ConfigReg(Generator):
def __init__(self,
name,
data_width,
init_val):
super().__init__(f"config_reg_{name}_{data_width}")
self.add_attribute(Con... | StarcoderdataPython |
186525 | #!/usr/bin/env python3
import random
def main():
"""Terminal上でポーカーを再現。ダブルアップはなし。
"""
poker = Poker()
# test()
"""
標準入出力を利用して、ゲームを行う
ループで回せばいい
終了の文字も指定する
ゲームの流れは、
スタート->dealされた札が5枚表示される->holdする札を選択する->
->再びdealする->役を判定->ゲームの結果処理->スタートに戻る
ユーザーができることは、
holdする札を選ぶ。結果表示後... | StarcoderdataPython |
1729008 | <reponame>cccccccccccccc/Myleetcode<filename>449/serializeanddeserialize BST.py
# Definition for a binary tree node.
"""
timecomplexity = O(n) spacecomplexity = O(n)
BST could be constructed by preorder or postorder travesal only.
That means that BST structure is already encoded in the preorder or postorder traversal a... | StarcoderdataPython |
1606890 | from setuptools import setup
setup(
name='pynkpandas',
packages=['pynkpandas'],
description='pynkpandas is a plugin for pynk. It does support data analysis.',
version='0.0.1',
url='https://gitlab.esa.int/mustlink-dev/pynkpandas',
author='esa/esoc/ops-os',
install_requires=["pandas"],
py... | StarcoderdataPython |
1633883 | <reponame>KJoke70/deep-visualization-toolbox
# basic network configuration
base_folder = '%DVT_ROOT%/'
caffevis_deploy_prototxt = base_folder + './models/vgg/vgg16.prototxt'
caffevis_network_weights = base_folder + './models/vgg/vgg16.caffemodel'
caffevis_data_mean = (103.939, 116.779, 123.68)
# input images
st... | StarcoderdataPython |
3241572 | import random
# Duplicando a sequência
def duplicacao_sequencia(seq_dna):
return 2*seq_dna
# Probabilidade de mundança - Randomizado
# A função especifica se a cada base nitrogenada muta ou não muta
def probabilidade_mutacao(lista_probabilidade,prob):
lista_armazenar = []
# Armazenar os valores rando... | StarcoderdataPython |
94824 | from django.test import TestCase
from dojo.tools.blackduck_component_risk.parser import BlackduckHubParser
from dojo.models import Test
from pathlib import Path
class TestBlackduckHubCRParser(TestCase):
def test_blackduck_enhanced_zip_upload(self):
testfile = Path("dojo/unittests/scans/blackduck_component... | StarcoderdataPython |
79720 | import sys, os
import subprocess
from git_tools import git_tools
import matplotlib.pylab as pylab
current_dir = os.getcwd()
authors_data = {}
def commit_analysis(commit_hash, initial_date):
# print("commit: " + commit_hash)
author_name_cmd = "git log -1 --pretty=format:'%an' " + commit_hash
author_name_... | StarcoderdataPython |
1653858 | <filename>tests/test_experiment.py
import os
def test_model_creation():
assert os.path.exists("data/model.pickle")
def test_metrics_creation():
assert os.path.exists("data/metrics.json")
def test_dataset_availability():
assert os.path.exists("data/creditcard.csv")
| StarcoderdataPython |
1662245 | import os
import datetime
from hashkernel.bakery import (
NotAuthorizedError, CredentialsError, Cake, CakeRack,
CakePath, CakeType, CakeRole, PatchAction, Content)
from hashkernel import reraise_with_msg, utf8_reader
from hashstore.utils import tuple_mapper
from hashkernel.file_types import (BINARY, guess_name,... | StarcoderdataPython |
3317391 | # Generated by Django 2.1.2 on 2019-01-30 12:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mrp_system', '0066_auto_20190130_1148'),
]
operations = [
migrations.AddField(
model_name='vendor',
name='address',
... | StarcoderdataPython |
153338 | import argparse
import os
import pdb
import shutil
from timeit import default_timer as timer
import numpy as np
import pandas as pd
from tqdm import tqdm
from evaluation import write_submission
def iters_ensemble(args):
'''
Ensemble on different iterations and generate ensembled files in fusioned folder
... | StarcoderdataPython |
3229415 | <reponame>benjolitz/instruct
import pytest
from enum import Enum
from instruct.typedef import (
parse_typedef,
make_custom_typecheck,
has_collect_class,
find_class_in_definition,
)
from instruct import Base, Atomic
from typing import List, Union, AnyStr, Any, Optional, Generic, TypeVar, Tuple, FrozenSet... | StarcoderdataPython |
1617777 | from enum import Enum
class LogType(Enum):
Info = 0
Success = 1
Fail = 2
Error = 3
Subtle = 4
Process = 5 | StarcoderdataPython |
3392860 | <filename>041.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
41. 係り受け解析結果の読み込み(文節・係り受け)
文節を表すクラスChunkを実装せよ.このクラスは形態素(Morphオブジェクト)の
リスト(morphs),係り先文節インデックス番号(dst),
係り元文節インデックス番号のリスト(srcs)をメンバ変数に持つこととする.
さらに,入力テキストのCaboChaの解析結果を読み込み,1文を
Chunkオブジェクトのリストとして表現し,8文目の文節の文字列と係り先を
表示せよ.
"""
import sys
from itertools im... | StarcoderdataPython |
3237898 | <filename>src/scs_core/gas/pid/pid_calib.py
"""
Created on 24 Sep 2016
@author: <NAME> (<EMAIL>)
"""
from collections import OrderedDict
from scs_core.data.datum import Datum
from scs_core.gas.sensor_calib import SensorCalib
# ----------------------------------------------------------------------------------------... | StarcoderdataPython |
3386770 | <reponame>khunfloat/Pointlib
__version__ = '4.62.2'
| StarcoderdataPython |
1791815 | # Finds recursively files with given extension in the given directory
# IMPORTS
from os import listdir
from os.path import join, isdir
# FUNCTIONS
def find(parent_dir, extension):
for file in listdir(parent_dir):
child = join(parent_dir, file)
if isdir(child):
find(child, extension)
... | StarcoderdataPython |
4805475 | import fastai
from fastai.vision import *
from fastai.callbacks import *
class KnowledgeDistillation(LearnerCallback):
def __init__(self, learn:Learner, teacher:Learner, T:float=20., α:float=0.7):
super().__init__(learn)
self.teacher = teacher
self.T, self.α = T, α
def on_backward... | StarcoderdataPython |
1622952 | <gh_stars>0
import unittest
from app.models import Case, Client, Comment
class TestCase(unittest.TestCase):
def setUp(self):
self.client_Stephen = Client(full_name = "<NAME>",
username = "remmi_m",
password = "<PASSWORD>",
... | StarcoderdataPython |
1707261 | import tensorflow as tf
from easy_rec.python.core.metrics import metric_learning_average_precision_at_k
from easy_rec.python.core.metrics import metric_learning_recall_at_k
from easy_rec.python.layers import dnn
from easy_rec.python.layers.common_layers import gelu
from easy_rec.python.layers.common_layers import high... | StarcoderdataPython |
1758133 | import torch.nn as nn
import torch # pytorch 0.4.0! fft
import numpy as np
import cv2
def complex_mul(x, z):
out_real = x[..., 0] * z[..., 0] - x[..., 1] * z[..., 1]
out_imag = x[..., 0] * z[..., 1] + x[..., 1] * z[..., 0]
return torch.stack((out_real, out_imag), -1)
def complex_mulconj(x, z):
out_... | StarcoderdataPython |
1678216 | """
.. module:: COptimizerPGDExp
:synopsis: Optimizer using Projected Gradient Descent with Exponential Line Search.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import numpy as np
from secml.array import CArray
from secml.optim.optimizers import COptimizerPGDLS
from secml.optim.optimizers.line_search import CLineSearc... | StarcoderdataPython |
3377775 | <gh_stars>1-10
# Copyright 2015 - Mirantis, 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 ... | StarcoderdataPython |
3274237 | <reponame>JaDogg/sbx
"""
Core Study Box classes
.. include:: ../../docs/EXAMPLES.md
.. include:: ../../docs/FILE_FORMAT.md
"""
| StarcoderdataPython |
69216 | # Start of memory.py.
import ctypes as ct
def addressOffset(x, offset, bt):
return ct.cast(ct.addressof(x.contents)+int(offset), ct.POINTER(bt))
def allocateMem(size):
return ct.cast((ct.c_byte * max(0,size))(), ct.POINTER(ct.c_byte))
# Copy an array if its is not-None. This is important for treating
# Numpy a... | StarcoderdataPython |
1765370 | <reponame>samkaufman/morello
import contextvars
import dataclasses
import functools
import sys
from collections.abc import Iterable, Sequence
from typing import Any, Callable, Optional
import morello.impl.actions
import morello.impl.base
from .. import cost, pruning, specs, system_config
prune_column_major: contextv... | StarcoderdataPython |
1687516 | <reponame>effrenus/connect-reports-core
# Copyright © 2021 CloudBlue. All rights reserved.
| StarcoderdataPython |
46184 | <reponame>uc-cdis/cwl
'''update postgres metrics'''
import postgres.mixins
import postgres.utils
class GenomelIndividualMetrics(postgres.mixins.IndMetricsTypeMixin, postgres.utils.Base):
__tablename__ = 'genomel_individual_workflow_metrics'
def add_metrics(engine, table, data):
""" add provided metrics to da... | StarcoderdataPython |
140571 | <reponame>akubera/stumpy
#
# stumpy/utils.py
#
"""
Utility methods
"""
from enum import Enum
class ROOT_TO_NUMPY_DTYPE(Enum):
C = 'i1'
S = 'i2'
I = 'i4'
F = 'f4'
D = 'f8'
def iter_tobject(tobj, pattern=None):
from ROOT import TDirectory, TCollection
from fnmatch import fnmatch
impo... | StarcoderdataPython |
3265238 | """
Update timestamps of eLife annotations imported from Disqus.
The annotations were initially created with the `POST /api/annotations`
endpoint, which does not allow the `created` and `updated` timestamps to be
specified.
This migration restores the original timestamps from the corresponding Disqus
comments.
Revis... | StarcoderdataPython |
1625198 | #!/usr/bin/python3
"""
Assembler produces A64 ELF executables
"""
import argparse
import os
import stat
import sys
from typing import Dict, Any
from CpuA64 import assembler as asm
def lint(input):
src = sys.stdin if input == "-" else open(input)
print("UNIT", asm.UnitParse(src, False))
def assemble_common... | StarcoderdataPython |
3363440 | <gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# Dataset:
# O conjunto de dados para este projeto é originário do Repositório de A prendizado de Máquina da UCI
# (https://archive.ics.uci.edu/ml/datasets/Adult)
# Importando os módulos
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection i... | StarcoderdataPython |
118016 | NEW_FEATURES = [3, 5, 6, 7]
FEATURES = [
1, # L
2, # S
4, # B
8, # A
3, # LS
5, # LB
6, # SB
9, # LA
9, # LA
9, # LA
9, # LA
9, # LA
10, # SA
10, # SA
10, # SA
10, # SA
10, # SA
12, # BA
12, # BA
12, # BA
12, # BA
... | StarcoderdataPython |
1628780 | <filename>src/sendkeyboardinput/sk.py<gh_stars>1-10
# we would need to scope it to a certain window
# could we eliminate the keystroke so it is silent
# run in a background
import pyautogui
import time
pyautogui.FAILSAFE = True
time.sleep(5)
f = open("/usr/share/wordlists/rockyou.txt", 'r')
for word in f:
pyautogu... | StarcoderdataPython |
1617246 | __all__ = ('test_validator', 'test_models')
| StarcoderdataPython |
3233870 | # 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 applica... | StarcoderdataPython |
58267 | """ Contains TaskState class """
from tasksupervisor.endpoint.fiware_orion.entities.entity import FiwareEntity
from tasksupervisor.endpoint.fiware_orion.entities.task import Task
class TaskState(FiwareEntity):
""" Represents the current state of the Task """
def __init__(self, _task):
if not isinstanc... | StarcoderdataPython |
118901 | <gh_stars>10-100
"""Module contains objects used for factor rotation
Currently contains these rotations:
- Varimax (numpy backend)
- Quartimax (numpy backend)
- Pseudo-Varimax (using Tensorflow backend, in rotation_tf module)
- Pseudo-Quartimax (using Tensorflow backend, in rotation_tf module)
The reason that some ar... | StarcoderdataPython |
3261438 | """
Author: <NAME>
Organization: terrestris GmbH & Co. KG
Contact: <EMAIL>
Created on: 10.11.20
"""
def runs_as_async_task() -> bool:
"""Check if a method is currently running in a worker.
This method can be called in any method to check if this method
was called from an async celery worker.
Code ta... | StarcoderdataPython |
189942 | import logging
from db_access import db_ops
from db_access import db_troop_class
from db_access import db_skin
from db_access import db_troop_modifier
from db_access import db_loadout
from db_access import db_modifier
from misc import timing
from model import troop
troop_cache = {}
@timing.timing
def get_by_id(tro... | StarcoderdataPython |
154132 | import matplotlib
from matplotlib import pyplot as plt
import tensorflow as tf
# tf.enable_eager_execution()
import tensorflow_probability as tfp
import numpy as np
def session_options(enable_gpu_ram_resizing=True):
"""Convenience function which sets common `tf.Session` options."""
config = tf.ConfigProto()
... | StarcoderdataPython |
58052 | <reponame>kiancross/pixys<gh_stars>1-10
#
# Copyright (c) 2020 <NAME>
#
from pixy.escape_sequence import EscapeSequence
reset = EscapeSequence(0)
def pring(text: str, style: EscapeSequence = EscapeSequence()) -> str:
if not isinstance(text, str):
raise ValueError("text must be of type str")
if no... | StarcoderdataPython |
3396795 | <filename>main.py<gh_stars>0
print('Welcome to the MineCraft CommandConsole, Press /help for a list of commands.')
while True:
x = input('/')
if x=='lol':
print('lol')
else:
print('Unknown Command ' + x)
| StarcoderdataPython |
1772332 | <reponame>Kev-in123/ICS2O7<gh_stars>1-10
vowels = "aeiouAEIOU"
word = input("Enter a word: ")
for i in range(len(word)):
if vowels.find(word[i]) != -1:
for j in range(len(vowels)):
if vowels[j] == word[i]:
if j + 1 < 5 or j + 1 > 5 and j + 1 <= 9:
pri... | StarcoderdataPython |
1795952 | # import libraries
import numpy as np
from flask import Flask, request, render_template
import pickle
import os
import pandas as pd
from collections import OrderedDict
# app name
app = Flask(__name__)
# load the saved model
def load_model():
return pickle.load(open('models\\loan_xgc_model.pkl','rb'))
# home page... | StarcoderdataPython |
186070 | <gh_stars>0
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
from cc_plugin_eustace import __version__
def readme():
with open('README.md') as f:
return f.read()
reqs = [line.strip() for line in open('requirements.txt')]
setup(name = "cc-plugi... | StarcoderdataPython |
1647340 | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework import status
from rest_framework.authentication import TokenAuthentication
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from res... | StarcoderdataPython |
1644341 | import pymongo
class MongoConfig():
def __init__(self, database_name, collection_name, use_localhost=False):
self.host = '172.16.31.10'
self.port_1 = 37017
self.port_2 = 47017
self.port_3 = 57017
self.database_name = database_name
self.collection_name = collection_na... | StarcoderdataPython |
3258172 | from pynput.keyboard import Listener, Controller, Key
import time
import threading
class ComboListener:
def __init__(self):
self.cur_keys = []
self.keymap = {
'aaa': 'aster',
'bbb': 'good boy'
}
self._run()
def _on_press(self, key):
try:
... | StarcoderdataPython |
1735474 | <gh_stars>0
import random
import unittest
import copy
from norm_behaviour_old import *
from aamas_experiments import sum_entry,average_entries
from priorityqueue import PriorityQueue
from norm_identification2 import *
from __builtin__ import str
class TestNormBehaviour(unittest.TestCase):
def setUp(self):
... | StarcoderdataPython |
3376654 | <filename>EdApi/bot.py<gh_stars>1-10
import json
from requests import request as r
from EdApi.common.exceptions import LoginException
class EdBot:
"""
A bot to connect to the EcoleDirecte Api with requests
"""
def __init__(self, username, password, proxy_address=None, proxy_port=None):
... | StarcoderdataPython |
1745022 | <reponame>Deepanjalli/job_portal6<gh_stars>0
# Generated by Django 2.1.2 on 2019-01-05 13:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Photo',
fields... | StarcoderdataPython |
3311574 | #!/usr/bin/python
# Not really an issue. It works as it is supposed to, I'd like to know if there's any possibility to add a ks_option to allow such
# output
# Github issue: #267
# Author: krystalgamer
from keystone import *
import regress
class TestX86(regress.RegressTest):
def runTest(self):
# Initia... | StarcoderdataPython |
3379436 | import logging
from Pyro5.compatibility import Pyro4
try:
import queue
except ImportError:
import Queue as queue
import sys
import threading
import time
import uuid
import zmq
#from ..pyro4_server import config
#from ..util import PausableThread, iterative_run
from ..threading_util import PausableThread
from ... | StarcoderdataPython |
1605995 | <gh_stars>10-100
import boto3
import cloudpickle
import io
import logging
import os
import pandas as pd
from botocore.client import ClientError
from flask import Flask
from flask import jsonify
from flask import request
from marshmallow import fields, Schema
app = Flask(__name__)
logger = logging.getLogger()
logging... | StarcoderdataPython |
1769823 | from petaldata.datasets.stripe.reports.customer_lists.abstract_mom_diff import AbstractMoMDiff
from petaldata.datasets.stripe.reports.customer_lists.new import New
from petaldata.datasets.stripe.reports.customer_lists.expansion_contraction import ExpansionContraction
from petaldata.datasets.stripe.reports.customer_lis... | StarcoderdataPython |
3247699 | <reponame>taqtiqa-mark/pymarket
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
def plot_trades_as_graph(
bids: pd.DataFrame,
transactions: pd.DataFrame,
ax=None):
"""Plots all the bids as a bipartit graph
with buyers and trades and an edge between
each pa... | StarcoderdataPython |
28479 | import argparse
import gym
import gym_module_select
from stable_baselines.common.vec_env import DummyVecEnv
def init_parse_argument():
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--num-exp', help='num experiment episode', type=int, default=10)
args = parser.parse_args()
return args
... | StarcoderdataPython |
123761 | <gh_stars>100-1000
import cffi
import faulthandler
import os
import sys
from cffi_util import read_stripped_header
SELF_DIR = os.path.dirname(os.path.abspath(__file__))
TOPLEVEL = os.path.abspath(SELF_DIR + "/../") + "/"
# The reference implementation is at the top level.
sys.path.append(TOPLEVEL)
HEADERS = [
"... | StarcoderdataPython |
1697006 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | StarcoderdataPython |
162383 | #coding: utf-8
""" Tests for Oracle Api.
"""
import unittest
| StarcoderdataPython |
97629 | <reponame>bkushigian/PokerNowPy
'''
game.py
Created by <NAME> on 5/27/20.
Adapted to Python by <NAME> on 8/7/2021
Copyright © 2020 Say Goodnight Software. All rights reserved.
'''
from typing import List, Optional, Dict
from util import nil_guard, first, last, hash_str_as_id
from datetime import datetime, timezone
f... | StarcoderdataPython |
3221301 | # Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - <NAME>, <<EMAIL>>, 20... | StarcoderdataPython |
40823 | <gh_stars>1-10
from django.contrib import admin
# Register your models here.
from django.contrib.auth.admin import UserAdmin
# Register your models here.
from api.models import CustomUser,Company
class UserModel(UserAdmin):
pass
admin.site.register(CustomUser,UserModel)
admin.site.register(Company)
| StarcoderdataPython |
1708977 | # You are to write scripts as requested below using the for loops:
# ask the user to enter 5 numbers and print the total at the end.
total = 0
for count in range(5):
num = input('Enter a number: ')
total += int(num)
print('Total is', total)
# print out the the shape below
# *
# **
# ***
# ****
# *****
# **... | StarcoderdataPython |
1677856 | from .base_testcase import BaseTestCase
import json
import os
import tempfile
import subprocess
from .test_office_hours_queue import enableQueue
class TestAccessibility(BaseTestCase):
"""
Test cases revolving around the logging in functionality of the site
"""
def __init__(self, testname):
s... | StarcoderdataPython |
3322615 | <filename>playfair.py
#!/usr/bin/env python
"""
Caesar Cipher Brute force Decryption
Author: <NAME>-<NAME>
E-Mail: <EMAIL>
Created: 2017-03-17
Python: 2.7
License: MIT
"""
import sys
def usage():
print "Usage: playfair < e | d > <KEY> <PLAINTEXT>"
def prepare_matrix(key):
return
def... | StarcoderdataPython |
3309604 | from random import choice
class RandomForest:
FORESTS = []
def __init__(self):
if self.FORESTS:
return
with open("forests") as f:
self.FORESTS = f.read().splitlines()
def get(self):
return choice(self.FORESTS)
| StarcoderdataPython |
1769822 | <reponame>rudyn2/tsad
import argparse
import numpy as np
import torch
import wandb
from gym_carla.envs.carla_pid_env import CarlaPidEnv
from torch.utils.data import DataLoader
from train_bc import BCTrainer
from models.carlaAffordancesDataset import AffordancesDataset, HLCAffordanceDataset
from agent import BCStocha... | StarcoderdataPython |
1750880 | import heapq
class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
total_area = n * m
dp = [0] * (total_area + 1)
for i in range(1, total_area):
dp[i] = 1 + min(dp[i - k * k] for k in range(1, int(i ** 0.5) + 1))
height = [0] * m
pq = []
for i... | StarcoderdataPython |
4839893 | <gh_stars>0
# -*- coding: utf-8 -*-
import pywinauto
def search_child_byclassname_1(class_name, uiaElementInfo, target_all = False):
target = []
# 全ての子要素検索
for childElement in uiaElementInfo.children():
#一覧確認--------------------------------------
#print(childElement)
#p... | StarcoderdataPython |
4823058 | <reponame>hocineabdellatif/genetic-py
from typing import List, Union, Dict, Tuple, Set, Any, Literal
from functools import reduce
from json import dumps
from random import randint
from math import floor, sqrt
def to_terminal(
line_type: Union[Literal['warning', 'error', 'info', ''], None],
msg_type: U... | StarcoderdataPython |
1783422 | """
Plotting Tools for persistence diagrams and cocycles
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def plotDGM(dgm, color = 'b', sz = 20, label = 'dgm', axcolor = np.array([0.0, 0.0, 0.0]), marker = None):
if dgm.size == 0:
return
# Create Lists
#... | StarcoderdataPython |
19874 | <filename>python/src/pdef/version.py<gh_stars>1-10
# encoding: utf-8
'''Pdef version in a separate module to simplify setup.py.'''
__version__ = '1.2.0'
| StarcoderdataPython |
60628 | import os
import numpy as np
import random
import numbers
import skimage
from skimage import io, color
import torch
# read uint8 image from path
def imread_uint8(imgpath, mode='RGB'):
'''
mode: 'RGB', 'gray', 'Y', 'L'.
'Y' and 'L' mean the Y channel of YCbCr.
'''
if mode == 'RGB':
img = io.... | StarcoderdataPython |
1737049 | # Copyright 2015 Cloudera 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, so... | StarcoderdataPython |
103990 | <gh_stars>0
from madlib import print_intro
def test_index_one():
expected = "**************************************"
"** Welcome to Madlibs! **"
"**************************************"
"** You will be prompted for a list **"
"** of words to substitute **"
"** for b... | StarcoderdataPython |
1792268 | <gh_stars>0
'''
.. versionadded:: 2.30
'''
from collections import OrderedDict
import functools as ft
import logging
from asyncio_helpers import sync
from markdown2pango import markdown2pango
from pygtkhelpers.forms import FormView
from pygtkhelpers.gthreads import gtk_threadsafe
from pygtkhelpers.schema import (get_f... | StarcoderdataPython |
3273497 | # Copyright 2014 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 telemetry import test
from measurements import chrome_proxy
import page_sets
class ChromeProxyLatency(test.Test):
tag = 'latency'
test = chrome_p... | StarcoderdataPython |
3247186 | <reponame>alexgolec/interview-problems
# Level 4: A linear-time, constant space solution based on dynamic programming.
from neighbors import neighbors
def count_sequences(start_position, num_hops):
prior_case = [1] * 10
current_case = [0] * 10
current_num_hops = 1
while current_num_hops <= num_hops:
... | StarcoderdataPython |
130758 | """Semantic Role Labeling related modeling class"""
from copy import deepcopy
from typing import List, Optional
from pororo.tasks.utils.base import PororoFactoryBase, PororoSimpleBase
class PororoSrlFactory(PororoFactoryBase):
"""
Conduct semantic role labeling
Korean (`charbert.base.ko.srl`)
... | StarcoderdataPython |
3200425 | <reponame>Ozanaydinn/Ozanaydinn.github.io
from flask import Flask, jsonify
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_cors import CORS
import os
from datetime import timedelta
import controllers.AuthController as AuthController
import cont... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.