id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3223122 | <reponame>Yosoyfr/tytus
import libs.ply.yacc as yacc
from Optimizador.lex2 import *
from controllers.error_controller import ErrorController
from Optimizador.clases3d import *
precedence = (
('nonassoc', 'LESS_THAN', 'LESS_EQUAL', 'GREATE_THAN',
'GREATE_EQUAL', 'EQUALS', 'EQUALS_EQUALS','NOT_EQUAL_LR', 'LEFT_... | StarcoderdataPython |
145392 | from typing import List
from collections import defaultdict
class Solution:
def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:
data = defaultdict(set)
uam = dict()
inverted_uam = {k:0 for k in range(1,k+1)}
solution = list()
for item in log... | StarcoderdataPython |
109737 | # coding=utf8
import numpy as np
class LabelSpreading:
def __init__(self, alpha=0.2, max_iter=30, tol=1e-3):
"""
:param alpha: clamping factor between (0,1)
:param max_iter: maximum number of iterations
:param tol: convergence tolerance
"""
self.alpha = alpha
... | StarcoderdataPython |
3249709 | <reponame>SteveMaverick/Python<filename>divide_and_conquer/quicksort.py
import sys
from typing import List
sys.setrecursionlimit(10 ** 5)
def partition(array: List, start: int, end: int) -> int:
"""
Helper function for quick_sort
Partitions array around a pivot
such that elements to the right of piv... | StarcoderdataPython |
1647116 | import os
import numpy as np
import pytest
from capreolus.benchmark.robust04 import Robust04Benchmark
from capreolus.collection import Collection
from capreolus.extractor.berttext import BertText
from capreolus.searcher.bm25 import BM25Grid
from capreolus.tests.common_fixtures import trec_index, dummy_collection_confi... | StarcoderdataPython |
4820611 | <filename>backend/initiatives/views/__init__.py
from .admin_views import *
from .views import *
| StarcoderdataPython |
1794795 | <reponame>acharal/tensorflow<gh_stars>0
import tensorflow as tf
from tensorflow.python.framework import function
ack = function.Declare("tak", [("x", tf.int32), ("y", tf.int32), ("z", tf.int32)], [("ret", tf.int32)])
@function.Defun(tf.int32, tf.int32, tf.int32, func_name="Tak", out_names=["ret"])
def TakImpl(x,y,z):... | StarcoderdataPython |
129957 | import string
size = 10
mid_line = '-'.join([string.ascii_letters[size - x] for x in range(1, size)] + [string.ascii_letters[x] for x in range(size)])
lines = []
for x in range(2,size+1):
main = ''.join(string.ascii_letters[size - x] for x in range(1, x))
*main_list,_ = list(main)
reverse = ''.join(x for x ... | StarcoderdataPython |
3284618 | <reponame>munniomer/Send-IT-Api-v1
"""User views contains Signup and login Resources"""
from app.api.v1.models.user_model import UserModel
from flask import Flask, request, make_response, json, jsonify
from flask_restful import Resource
from validators.validators import Validators
db = UserModel()
validate = Validator... | StarcoderdataPython |
1722891 | import argparse
import logging
from enum import Enum
from codigofacilito import unreleased, released, articles
from .config import DEBUG
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
class Items(str, Enum):
WORSHOPS = "workshops"
ARTI... | StarcoderdataPython |
21067 | <reponame>zhihou7/VCL<gh_stars>10-100
# --------------------------------------------------------
# Tensorflow VCL
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>, based on code from Transferable-Interactiveness-Network, <NAME>, <NAME> and <NAME>
# -----------------------------------------... | StarcoderdataPython |
30498 | class O(object): pass
class A(O): pass
class B(O): pass
class C(O): pass
class D(O): pass
class E(O): pass
class K1(A,B,C): pass
class K2(D,B,E): pass
class K3(D,A): pass
class Z(K1,K2,K3): pass
print K1.__mro__
print K2.__mro__
print K3.__mro__
print Z.__mro__
| StarcoderdataPython |
1625765 | """
balances simple
"""
import archon.broker.broker as broker
import archon.exchange.exchanges as exc
a = broker.Broker(setAuto=False)
a.set_keys_exchange_file(path_file_apikeys="./apikeys.toml")
client = a.afacade.get_client(exc.BINANCE)
bal = client.get_account()["balances"]
for x in bal:
f,l = float(x["free"]),fl... | StarcoderdataPython |
1718248 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
assert int('89') == 89
assert int('101', 2) == 5
assert int('0B101', 2) == 5
assert int('27', 8) == 23
assert int('027', 8) == 23
assert int('22', 16) == 34
assert int('0x22', 16) == 34
assert int('0X22', 16) == 34
| StarcoderdataPython |
114297 | <filename>piconumpy/test_cpython_capi.py
import numpy as np
from . import array
class Tests:
_array = array
def test_init_array(self):
a = self._array([1.0, 2.0])
assert a.size == 2
def test_init_array_numpy(self):
np_a = np.array([1.0, 2.0, 0.0, 0.0])
a = self._array(np... | StarcoderdataPython |
3360250 | def move(from_position, target_position):
print(f'Move disk from {from_position} to {target_position}')
def hanoi(disk_count, from_position, helper_position, target_position):
if not disk_count:
return
hanoi(disk_count - 1, from_position, helper_position, target_position)
move(from_position, t... | StarcoderdataPython |
64409 | <gh_stars>1-10
"""
Author: Benny
Date: Nov 2019
"""
from data_utils.ModelNetDataLoader import ModelNetDataLoader
import argparse
import numpy as np
import os
import torch
import datetime
import logging
from pathlib import Path
from tqdm import tqdm
import sys
import provider
import importlib
import shutil
BASE_DIR = o... | StarcoderdataPython |
3215666 | # -*- coding: utf-8 -*-
r"""
The set `\mathbb{P}^1(\QQ)` of cusps
EXAMPLES::
sage: Cusps
Set P^1(QQ) of all cusps
::
sage: Cusp(oo)
Infinity
"""
# ****************************************************************************
# Copyright (C) 2005 <NAME> <<EMAIL>>
#
# Distributed under the term... | StarcoderdataPython |
36201 | # -*- coding: utf-8 -*-
##############################################################################
# Author:QQ173782910
##############################################################################
import logging
from apscheduler.schedulers.background import BlockingScheduler
from RunUse import TradeRun
format ... | StarcoderdataPython |
3345664 | <reponame>cuappdev/archives<filename>tempo-api/src/app/base.py
from marshmallow_sqlalchemy import ModelSchema
from . import db
class Base(db.Model):
__abstract__ = True
created_at = db.Column(db.DateTime, default = db.func.current_timestamp())
updated_at = db.Column(db.DateTime, default = db.func.current_timesta... | StarcoderdataPython |
1782292 | import numpy as np
import matplotlib.pyplot as plt
from math import pi, cos
from scipy import loadtxt, optimize
import os
M = 1.41
plt.figure(figsize=(10,7), dpi=80)
ax = plt.axes()
dat = loadtxt("./particles/particles.tsv", skiprows=0, delimiter="\t")
t = dat.transpose()[0]
tracers = dat.transpose()[1:... | StarcoderdataPython |
3309142 | <reponame>Corleo/st_settings
import re
import sublime
import sublime_plugin
# for debugging
# sublime.log_commands(True)
# pattern = re.compile(r".*test.*") # match
# pattern = re.compile('(?!.*(?:test)).*') # don't match
class CustomBuildSystemCommand(sublime_plugin.WindowCommand):
def run(self, *args... | StarcoderdataPython |
4831196 | money=float(input('Quanto voce quer converter '))
dolar= money /3.91
print ('voce tem R$ {:.2f} reais ,convertido em dolar são $ {:.2f} dolares'.format(money,dolar))
| StarcoderdataPython |
178793 | from scrapy_scylla_proxies.random_proxy import RandomProxyMiddleware
| StarcoderdataPython |
155616 | ## @package AssociateJoint Association joint that used by gait recorder
## The class that has all the information about associations
class AssociateJoint:
## Constructor
# @param self Object pointer
# @param module Module name string
# @param node Node index
# @param corr Bool, correaltion: True for positive; Fal... | StarcoderdataPython |
1758335 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convert the *DECOW14X* corpus into a plain text file. Is used as pre-processing step for the
`word2vec <https://code.google.com/archive/p/word2vec/>`_ training.
To make this this more feasible (decow is a **huge** corpus), python's :mod:`multiprocessing` is used, s.t. every... | StarcoderdataPython |
120178 | <reponame>chulth/CRide
'''users app.'''
# Django
#from django.app import AppConfig
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
'''users app config.'''
name = 'cride.users'
verbose_name = 'Users'
| StarcoderdataPython |
141882 | <gh_stars>0
# Generated by Django 2.2.1 on 2019-05-26 03:44
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20190525_2338'),
]
operations = [
migrations.RenameField(
model_... | StarcoderdataPython |
3249885 | #!/usr/bin/env python
# Run the tests as below from the root folder of this python project:
# cd [THE_ROOT_FOLDER]
# python -m unittest discover -s tests
"""Tests for `epsg_constants` package."""
import unittest
from epsg_constants.epsg_number import EpsgNumber
class TestEpsg_constants(unittest.TestCase):
"""... | StarcoderdataPython |
1766044 | # Initial imports
import pandas as pd
import numpy as np
import datetime as dt
from pathlib import Path
%matplotlib inline
# Reading whale returns
# Rading the whale returs dataset using the pandas built in function read_csv and converting the Date column into datetime format.
df = pd.read_csv('./Resources/whale_retu... | StarcoderdataPython |
1769215 | <reponame>fish159753/python_projects<filename>coin_flip_runs.py
"""
File: coin_flip_runs.py
Name: <NAME>
-----------------------
This program should simulate coin flip(s)
with the number of runs input by users.
A 'run' is defined as consecutive results
on either 'H' or 'T'. For example, 'HHHHHTHTT'
is regarded as a 2-r... | StarcoderdataPython |
1665837 | """
Project.x
Author: <NAME>
"""
from __future__ import print_function, absolute_import
from six import iteritems
from six.moves import range
import ast
from types import ModuleType, FunctionType
# noinspection PyUnresolvedReferences
from six.moves import builtins
import math
import keyword
_builtins = dir(bui... | StarcoderdataPython |
3200521 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | StarcoderdataPython |
82687 | #!/usr/bin/env python3
"""Tools to generate a Snakemake-based BIDS app."""
import os
import pathlib
import subprocess
import argparse
import logging
import sys
import yaml
import bids
import snakemake
from snakemake.io import load_configfile
# We define Path here in addition to pathlib to put both variables in globa... | StarcoderdataPython |
169644 | # -*- coding: utf8 -*-
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'docato_proj.settings')
#app = Celery('docato_proj')
app = Celery('docato_proj',backend='rpc://') #,include=['test_celery.tasks'] # broker='... | StarcoderdataPython |
168253 | import pdb
from collections import namedtuple
from pathlib import Path
import z3
import sage.all
import helpers.vcommon as CM
from helpers.miscs import Miscs
import data.prog
import settings
DBG = pdb.set_trace
mlog = CM.getLogger(__name__, settings.logger_level)
class SymbsVals(namedtuple("SymbsVals", ("ss", "v... | StarcoderdataPython |
12510 | """
DB operations for Targets
"""
from api.models.base import DBModel
class TargetDB(DBModel):
'''DBModel for the targets table'''
tablename = 'targets'
| StarcoderdataPython |
1640472 | from django.db import models
from datetime import datetime as dt
# from polymorphic.manager import PolymorphicManager
from polymorphic.managers import PolymorphicManager
class ActividadQuerySet(models.QuerySet):
def en_espera(self):
return self.filter(estado='espera')
def rechazado(self):
ret... | StarcoderdataPython |
4823402 | <filename>src2/reader.py
# Reads cleans and parses data from wordle dictionaries.
class Reader:
def load_lists(solution_corpus_path, guess_corpus_path):
solution_corpus = Reader.get_word_list(solution_corpus_path)
guess_corpus = Reader.get_word_list(guess_corpus_path)
full_corpus = solution_corpus + gue... | StarcoderdataPython |
38313 | # graph
from datetime import date
import numpy as np
from bokeh.client import push_session
from bokeh.io import output_server, show, vform
from bokeh.palettes import RdYlBu3
from bokeh.plotting import figure, curdoc, vplot, output_server
from bokeh.models import ColumnDataSource
from bokeh.models.widgets im... | StarcoderdataPython |
4809778 | <gh_stars>100-1000
import os
import numpy as np
import zarr
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
from torch.utils.data import random_split
from tqdm import tqdm
def as_array(image):
return np.asarray(image).swapaxes(2, 0)
def convert_data_set(path, data_set, batc... | StarcoderdataPython |
1612332 | ## Copyright 2015-2019 <NAME>, <NAME>
## 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 i... | StarcoderdataPython |
3206009 | import requests
from faker import Faker
import random
fake = Faker()
Genres = [
"Action",
"Comedy",
"Drama",
"Fantasy",
"Horror",
"Mystery",
"Romance",
"Thriller",
"Western",
]
Book_Numbers = 51
for i in range(1, Book_Numbers):
# Book
requests.post(
"http://lo... | StarcoderdataPython |
1739438 | <reponame>benjyz/ape
from copy import deepcopy
from typing import Dict, List, Optional
from .abstract import (
FileMixin,
SerializableType,
update_dict_params,
update_list_params,
update_params,
)
from .contract import Compiler, ContractInstance, ContractType, Source
class PackageMeta(Serializabl... | StarcoderdataPython |
4803067 | <reponame>dewrin/img_scanner_en_django
from django.shortcuts import render, redirect
from django.views.generic import View
from django.core.files.storage import FileSystemStorage
from PIL import Image
from pytesseract import image_to_string
from django.shortcuts import render
from django.http import HttpResponse
impor... | StarcoderdataPython |
1784542 | #!/usr/bin/env python
"""Amalgamates all specified file references from a main source file into one large source file.
Searches through the main source file for a 'hotword:source_file' phrase.
Replaces this line with the full contents of the specified 'source_file'.
"""
__author__ = "<NAME>"
__copyright__ = "Copyrigh... | StarcoderdataPython |
130130 | <gh_stars>0
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..analysis import CoherenceAnalyzer
def test_CoherenceAnalyzer_inputs():
input_map = dict(
NFFT=dict(usedefault=True, ),
TR=dict(),
figure_type=dict(usedefault=True, ),
frequency_range=dict(usedefault=True, ),
... | StarcoderdataPython |
3311160 | <filename>tensorflow_federated/python/core/impl/test.py
# Copyright 2019, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... | StarcoderdataPython |
4802464 | <reponame>adamgreig/momobot
import feedparser
class Woot:
"""
Returns the current item on sale at Woot.com, according to the woot rss.
"""
def __init__(self, bot):
self.bot = bot
bot.register_command('woot', self.woot)
print "hello woot world"
self.bot.say('I exist')
... | StarcoderdataPython |
10825 | <gh_stars>0
from django.db import models
from django.db.models.deletion import CASCADE
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField
# Create your models here.
class Profile(models.Model):
"""Model for handling User Profile"""
user = models.OneToOneField(User, on_del... | StarcoderdataPython |
1793274 | <gh_stars>0
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFE... | StarcoderdataPython |
3343991 | """Library to access del.icio.us data via Python.
An introduction to the project is given in the README.
pydelicious is released under the FreeBSD License.
See license.txt for details and the copyright holders.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WA... | StarcoderdataPython |
1758704 | import traceback
from spikeforest2_utils import AutoRecordingExtractor
class Recording:
def __init__(self):
super().__init__()
self._recording = None
def javascript_state_changed(self, prev_state, state):
self._set_status('running', 'Running Recording')
if not self._recording:
... | StarcoderdataPython |
4834973 | <reponame>fabric-testbed/ActorBase
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including ... | StarcoderdataPython |
101605 | <reponame>pennucci/enterprise<filename>tests/test_gp_priors.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_gp_priors
----------------------------------
Tests for GP priors and bases.
"""
import unittest
import numpy as np
from tests.enterprise_test_data import datadir
from enterprise.pulsar import Pulsa... | StarcoderdataPython |
3326620 | <filename>data_wrangler.py
import csv
import json
import os
# Manages the retrieval and storage of CSV data
class DataManager:
CSVFiles = []
# Stores all of the csv file names
def __init__(self):
for filename in os.listdir("CSV"):
self.CSVFiles.append("CSV/" + filename)
... | StarcoderdataPython |
3355347 | <reponame>ubikpt/PyXtal
from structure import *
allpassed = True
for sg in range(1, 231):
print("Calculating spacegroup " + str(sg))
wyckoffs = get_wyckoffs(sg)
for index, wp in enumerate(wyckoffs):
v = np.random.random(3)
for i in range(3):
if np.random.random() < 0.5:
... | StarcoderdataPython |
4826647 | <reponame>rbirger/OxfordHCVNonSpatial
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# ###Description and preliminary code for Continuous-Time Markov Chain Model
#
# This model will test the importance of including a spatial component in the system. We will use ODEs to describe the dynamics of e... | StarcoderdataPython |
3232245 |
# Importing necessary packages for this project
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Setting seed for reproducibility
UBIT = 'damirtha'
np.random.seed(sum([ord(c) for c in UBIT]))
# Function to apply a mask on an image
def pointMask(image, mask):
img_list = []
for img_row in range... | StarcoderdataPython |
71166 | <gh_stars>0
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
3267403 | import random
def Partition(A):
if (len(A)==1):
return 0
v = len(A)-1
i = 0
j = len(A)-2
while (i <= j):
if ( (A[i] < A[v]) and (A[j] >= A[v]) ):
i += 1
j -= 1
if ( (A[i] >= A[v]) and (A[j] < A[v]) ):
A[i], A[j] = A[j], A[i]
... | StarcoderdataPython |
178527 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obt... | StarcoderdataPython |
4839199 | <gh_stars>100-1000
# -*- test-case-name: txdav.common.datastore.upgrade.sql.test -*-
##
# Copyright (c) 2011-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License ... | StarcoderdataPython |
178071 | <filename>magenta/models/nsynth/wavenet/eval.py
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE... | StarcoderdataPython |
3307301 | import numpy as np
import qpimage
from drymass import search
def test_basic():
size = 200
image = np.zeros((size, size), dtype=float)
x = np.arange(size).reshape(-1, 1)
y = np.arange(size).reshape(1, -1)
cx = 80
cy = 120
radius = 30
r = np.sqrt((x - cx)**2 + (y - cy)**2)
image[r <... | StarcoderdataPython |
4808122 | ###############################################################################
# TransientLogSpiralPotential: a transient spiral potential
###############################################################################
import numpy
from ..util import conversion
from .planarPotential import planarPotential
_degtorad=... | StarcoderdataPython |
3388374 | from pypower import idx_bus, idx_gen, idx_brch
import numpy as np
from cim2busbranch import ext_pypower
pytest_plugins = 'cim2busbranch.test.support'
def test_create(case, ppc):
res = ext_pypower.create(case)
assert res['version'] == ppc['version']
assert res['baseMVA'] == ppc['baseMVA']
assert (r... | StarcoderdataPython |
3231714 | import enum
import math
import numpy as np
from pylot.control.utils import get_angle
class BehaviorPlannerState(enum.Enum):
""" States in which the FSM behavior planner can be in."""
READY = 1
KEEP_LANE = 2
PREPARE_LANE_CHANGE_LEFT = 3
LANGE_CHANGE_LEFT = 4
PREPARE_LANE_CHANGE_RIGHT = 5
L... | StarcoderdataPython |
130042 | <filename>monitoring/monitorlib/locality.py
from enum import Enum
class Locality(str, Enum):
"""Operating locations and their respective regulation and technical variations."""
CHE = 'CHE'
"""Switzerland"""
@property
def is_uspace_applicable(self) -> bool:
return self in {Locality.CHE}
... | StarcoderdataPython |
1761864 | <reponame>athaun/Python-ai-assistant
import re
import time
import requests
import json
from jarvis.skills.skill import AssistantSkill
class LightSkills (AssistantSkill):
@classmethod
def toggle_light(cls, voice_transcript, skill, **kwargs):
"""
Toggles ceiling light on or off.
"""... | StarcoderdataPython |
130188 | <gh_stars>1-10
__author__ = 'Ivan'
import objectness_python
import tracker_python
from Dataset import VOT2015Dataset
import numpy as np
import matplotlib.pyplot as plt
import cv2
from matplotlib import gridspec
import re
import os
import time
import math
import copy
class ObjectnessVizualizer(object):
"""Class to ... | StarcoderdataPython |
121544 | <gh_stars>0
total = caros = cont = 0
barato = ''
print('==' * 20)
print(' <NAME> ')
print('==' * 20)
while True:
nome = str(input('Nome do Produto: ')).strip().title()
preco = float(input('Preço: R$ '))
op = ' '
while op not in 'SN':
op = str(input('Quer Continuar ? [S/N] ')).strip().upper()... | StarcoderdataPython |
3220643 | import boto3
def get_s3_object_last_modified(bucket_name, prefix):
"""
Get last modified S3 object in specified bucket_name with prefix
:param str bucket_name: Name of bucket to chewck for last modified object
:param str prefix: Prefix of object key
:return Object: AWS S3 Object
"""
# Bas... | StarcoderdataPython |
82994 | import json
import os
import threading
import time
import socket
import getpass
from datetime import datetime
from wandb import util
import wandb
METADATA_FNAME = 'wandb-metadata.json'
class Meta(object):
"""Used to store metadata during and after a run."""
HEARTBEAT_INTERVAL_SECONDS = 15
def __init__... | StarcoderdataPython |
3276205 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | StarcoderdataPython |
132028 | import pathlib
from setuptools import find_packages, setup
here = pathlib.Path(__file__).parent.resolve()
# Get the long description from the README file
long_description = (here / "README.md").read_text(encoding="utf-8")
# Arguments marked as "Required" below must be included for upload to PyPI.
# Fields marked a... | StarcoderdataPython |
3246886 | """
Copyright (C) Cortic Technology Corp. - All Rights Reserved
Written by <NAME> <<EMAIL>>, 2021
"""
from abc import abstractmethod
class BaseVisionProcessing:
def __init__(self, processor_type):
self.processor_type = processor_type
@abstractmethod
def config_worker(self, params):
pass... | StarcoderdataPython |
21466 | <filename>src/service/uri_generator.py
"""Generates pre-signed uri's for blob handling."""
from boto3 import client
import os
s3_client = client('s3')
def create_uri(repo_name, resource_oid, upload=False, expires_in=300):
"""Create a download uri for the given oid and repo."""
action = 'get_object'
if u... | StarcoderdataPython |
3376526 | <reponame>uint0/pylicy
from typing import Any, Dict, List
import pytest
from hypothesis import given
from hypothesis import strategies as st
from pylicy import models, rules
def test_load_rules_bad_version() -> None:
with pytest.raises(AttributeError):
rules.load({}, [])
with pytest.raises(NotImplem... | StarcoderdataPython |
1753475 | <filename>app.py
# This file is derived from this source: https://github.com/bhavaniravi/rasa-site-bot
# The original file is licensed under "the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or any later version."
# Hence this file is also licensed under GNU... | StarcoderdataPython |
1768740 | # Used to create html file from function open_movies_page
import fresh_tomatoes
# Used to get access to class Movies
import media
# This section is accessing the module media.py
toy_story = media.Movie(
"Toy Story",
"A story of a boy and his toys that come to life",
"https://upload.wikimedia.org/wi... | StarcoderdataPython |
163677 | import os
from newsapi import NewsApiClient
import datetime
# Init
api_key = os.environ.get('api_key')
newsapi = NewsApiClient(api_key=api_key)
#sources
sources = 'abc-news, al-jazeera-english,ars-technica,bbc-news,bbc-sport,bleacher-report,bloomberg,business-insider,buzzfeed,cnn,crypto-coins-news, entertainment-week... | StarcoderdataPython |
1694099 | from .constants import BASE_URL
from .api.stores import BestBuyStoresAPI
from .api.bulk import BestBuyBulkAPI
from .api.products import BestBuyProductsAPI
from .api.categories import BestBuyCategoryAPI
__version__ = "2.0.0"
class BestBuyAPI:
def __init__(self, api_key):
"""API's base class
:para... | StarcoderdataPython |
71694 | <gh_stars>1-10
#
"""
Unit tests for conv encoders.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
import texar.tf as tx
from texar.tf.modules.encoders.conv_encoders import Conv1DEncoder
... | StarcoderdataPython |
3360742 | <reponame>mail2nsrajesh/neutron-vpnaas
# Copyright (c) 2015 Canonical, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/l... | StarcoderdataPython |
190293 | <reponame>vishalbelsare/pysonDB
import json
import os
from typing import Any
from typing import Dict
from uuid import uuid4
from .errors import DataError
def verify_data(data: Dict[str, Any], db: Dict[str, Dict[str, Any]]) -> bool:
if db:
if sorted(list(db.values())[0]) == sorted(list(data)):
... | StarcoderdataPython |
160962 | <reponame>kipsang01/art-gallery
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.core.exceptions import ObjectDoesNotExist
from .models import Category, Image,Location
# Create your views here.
def home(request):
images = Image.objects.all()
categories = Category.o... | StarcoderdataPython |
1796009 | <reponame>WalkingMachine/sara_behaviors
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated aga... | StarcoderdataPython |
1647675 | import pytest
from ocdeployer.images import ImageImporter, import_images
@pytest.fixture
def mock_oc(mocker):
_mock_oc = mocker.patch("ocdeployer.images.oc")
mocker.patch("ocdeployer.images.get_json", return_value={})
yield _mock_oc
def _check_oc_calls(mocker, mock_oc):
assert mock_oc.call_count ==... | StarcoderdataPython |
3338868 | <filename>hatespeech_core/modules/pattern_classifier/PatternVectorizer.py
import regex
import pandas as pd
import numpy as np
class PatternVectorizer:
def __init__(self, patterns, binary=False):
self.binary = binary
vocabulary = pd.DataFrame()
vocabulary['patterns'] = patterns
vocabulary['regex... | StarcoderdataPython |
3347241 | from KLS_EDA import new_kls_df
from sklearn.model_selection import train_test_split
# Splitting the data into training data and test data
X = new_kls_df[1:4].to_numpy().reshape(new_kls_df[1:4].size//3, 3)
y = new_kls_df.loc['Karachi Electric'].to_numpy().reshape(-1)
others_blamed_train, others_blamed_test, ke_train, ... | StarcoderdataPython |
83310 | <gh_stars>1-10
import secrets
import string
def main():
''' Generates a password of the length specified by the user. '''
password_length = input("How many characters long should the password be?: ")
if password_length.isdecimal():
password_length = int(password_length)
# Generates pass... | StarcoderdataPython |
1756247 | from django.shortcuts import render,redirect
from .models import Profile,Project
from django.contrib.auth.decorators import login_required
from .forms import ProjectForm,VoteForm,EditProfile
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializer import ProjectSerializer,P... | StarcoderdataPython |
1653425 | from datetime import datetime
from app.core.config import STRFTIME
from app.db.db import database
from app.db.schemas import weights
from app.models.models import WeightDB
from app.models.models import WeightSchema
from loguru import logger
from sqlalchemy import desc
def _log_query(query: str, query_params: dict = ... | StarcoderdataPython |
3395778 | # Generated by Django 2.1.2 on 2018-10-10 10:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("pyazo_core", "0007_upload_mime_type"),
]
operations = [
migrations.AddField(
model_name="upload",
name="thumbnail",
... | StarcoderdataPython |
198087 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def move_dossier(apps, schema_editor):
Company = apps.get_model("core", "Company")
for c in Company.objects.all():
c.city_uk = c.city
c.street_uk = c.street
c.appt_uk = c.appt
c.w... | StarcoderdataPython |
3310093 | <gh_stars>0
from db import db
from flask_restful_swagger import swagger
@swagger.model
class CreatorModel(db.Model):
__tablename__ = 'creators'
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(80))
lastname = db.Column(db.String(80))
def __init__(self, las... | StarcoderdataPython |
3204651 | <reponame>daniel-keogh/graph-theory
#!/usr/bin/env python3
import unittest
# Enables executing this module directly.
# Ref: Remi - https://stackoverflow.com/a/9806045
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from match.regex import (
match,
InvalidR... | StarcoderdataPython |
167376 | <reponame>jamesreinhold/vigolend
from datetime import datetime
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from vigolend.users.models import User
from helpers.common.basemodel import BaseModel
from helpers.common.choices import ModelChoices
f... | StarcoderdataPython |
1688548 | import json
from typing import Any, ClassVar, Dict, Iterable, List, Tuple
import attr
from ...parameters import Parameter
from .converter import to_json_schema_recursive
@attr.s(slots=True, eq=False)
class OpenAPIParameter(Parameter):
"""A single Open API operation parameter."""
example_field: ClassVar[str... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.