id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6495548 | import codecs
import copy
import pickle
import numpy as np
import console
import constants
import regression
np.random.seed(11)
# This is to pickle all foods in sorted order
def pickle_top_foods_for_each_nutrient(pickle_all_foods=True):
with open(constants.NUTRIENT_DETAILS_FILE, 'r', encoding='ISO-8859-1') \
... | StarcoderdataPython |
6700735 | <gh_stars>0
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, DATETIME
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
from datetime import datetime
import time
# TODO: db_uri
# dialect+driver://username:password@host:port/... | StarcoderdataPython |
6492641 | <reponame>NateThom/contrastive_learning
import torch
import torchvision.transforms.functional as TF
import torchvision.transforms as T
class MyRandomColorJitter(object):
"""Crop randomly the image and masks in a sample
output_size (tuple or int): Desired output size. If int, square crop
... | StarcoderdataPython |
5184818 | <reponame>harshal306/radiometric_normalization
'''
Copyright 2015 Planet Labs, 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... | StarcoderdataPython |
40784 | """doufo.convert
abstract class of `dataType` converters.
Example:
Todo:
Author:
"""
from .function import func
from functools import wraps, cmp_to_key
from multipledispatch import Dispatcher
from typing import Callable, TypeVar
__all__ = ['converters', 'convert_to', 'convert']
T = TypeVar('T')
B = TypeVa... | StarcoderdataPython |
1953455 | <filename>Conversor de bases numericas.py
num = int(input('Informe um número para a conversão: '))
print('Digite 1 para BINÁRIO')
print('Digite 2 para OCTAL')
print('Digite 3 para HEXADECIMAL')
base = int(input('Escolha a base numérica: '))
if base == 1:
print('{} em BINÁRIO é igual a {}'.format(num, bin(num)[2:]))... | StarcoderdataPython |
4955390 | <filename>improver/utilities/temporal.py
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted... | StarcoderdataPython |
3372793 | <gh_stars>0
import json
from logzio.handler import LogzioHandler
class ExtensionLogHandler(LogzioHandler):
def __init__(self, *args, **kwargs):
self.default_extra_fields = kwargs.pop('default_extra_fields')
super().__init__(*args, **kwargs)
def extra_fields(self, message):
extra_fiel... | StarcoderdataPython |
6624677 | <filename>src/pyast_utils.py
# Copyright (c) 2019, IBM Research.
#
# Author: <NAME> <<EMAIL>>
#
# vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4:
import itertools
import copy
import ast as pyast
class StructureTupleYields(pyast.NodeTransformer):
""" AST transformer for "structuring" yielded tuples
... | StarcoderdataPython |
6452724 | """Directory structure and paths."""
import platform
from pathlib import Path
URL = {
0: 'http://s3.eu-central-1.amazonaws.com/boo2012/data_reference.rar',
2012: 'http://www.gks.ru/opendata/storage/7708234640-bdboo2012/data-20181029t000000-structure-20121231t000000.csv',
2013: 'http://www.gks.r... | StarcoderdataPython |
3558448 | from argparse import ArgumentParser
from sys import stdin
from mlmorph import Generator, Analyser
def main():
"""Invoke a simple CLI analyser or generator."""
a = ArgumentParser()
a.add_argument('-i', '--input', metavar="INFILE", type=open,
dest="infile", help="source of analysis data")... | StarcoderdataPython |
3305205 | import pygame
from sys import exit
#from KinectTools import PyKinectRuntime
#from KinectTools import PyKinectV2
import ctypes
from Stamina.stamina import stamina
from faceRecognition.Login import login
from faceRecognition.Signup import signup
from utils.utils import scale
from utils.utils import choose,click
clas... | StarcoderdataPython |
8048704 | __all__ = [
'InfrastructureApi',
]
class InfrastructureApi(object):
def search(self, query):
"""
Search datadog for hosts and metrics by name. The search *query* can be
faceted to limit the results (e.g. ``"hosts:foo"``, or ``"metrics:bar"``)
or un-faceted, which will return res... | StarcoderdataPython |
4848827 | <gh_stars>1-10
import web, datetime
db = web.database(dbn='mysql', db='webpy_demo', user='dbuser',pw="<PASSWORD>")
def get_posts():
return db.select('entries', order='id DESC')
def get_post(id):
try:
return db.select('entries', where='id=$id', vars=locals())[0]
except IndexError:
return N... | StarcoderdataPython |
6581038 | <reponame>3dimaging/DeepLearningCamelyon_II
#!/home/wli/env python3
# -*- coding: utf-8 -*-
"""
Title: convert XML to binary mask
=================================
Created: 10-31-2019
Python-Version: 3.5, 3.6
Description:
------------
This module is used to generate binary mask files from the annotations (XML files).... | StarcoderdataPython |
12801785 | import os
import shutil
from pathlib import Path
import dash
from dash import html
from dash import dcc
class DashboardObject:
def __init__(self, title, description = "", dependencies = [], meta = None):
self.title = title
self.description = description
self.dependencies = dependencies
... | StarcoderdataPython |
1846763 | <reponame>nilsreichert/core
"""The RegisterController Module."""
from config import auth
from masonite.auth import Auth
from masonite.helpers import password as bcrypt_password
from masonite.request import Request
from masonite.view import View
from masonite.auth import MustVerifyEmail
from masonite.managers import Ma... | StarcoderdataPython |
8164010 | <gh_stars>0
#!/usr/bin/env python
# Title: UAV client
# Description: Randomly generates peoples poses and sends them to the RabbitMQ server
# Engineer: <NAME>
# Email: <EMAIL>
# Lab: Autonomous Controls Lab, The University of Texas at San Antonio
######### Libraries ###################
import numpy... | StarcoderdataPython |
60253 | #!/usr/bin/python
import sqlite3
uId = 4
con = sqlite3.connect('ydb.db')
with con:
cur = con.cursor()
cur.execute("SELECT name, price FROM cars WHERE Id=:Id", {"Id": uId})
row = cur.fetchone()
print(f"{row[0]}, {row[1]}")
| StarcoderdataPython |
3503554 | <filename>tests/test_dynamic_models.py
"""Trial runs on DynamicBot with the TestData Dataset."""
import time
import logging
import unittest
import numpy as np
import tensorflow as tf
import pydoc
from pydoc import locate
import data
import chatbot
from utils import io_utils, bot_freezer
from tests.utils import *
c... | StarcoderdataPython |
8054022 | #!/usr/bin/env python
"""
Cacheability checking function.
"""
from redbot.formatter import relative_time, f_num
from redbot.message import HttpRequest, HttpResponse
from redbot.speak import Note, categories, levels
### configuration
cacheable_methods = ['GET']
heuristic_cacheable_status = ['200', '203', '206', '300'... | StarcoderdataPython |
11235037 | <reponame>study-abacus/admin-site
from django.contrib import admin
from .models import Student, Course, Fee, Achievement, CI
# Register your models here.
admin.site.register(Student)
admin.site.register(Course)
admin.site.register(Fee)
admin.site.register(Achievement)
admin.site.register(CI) | StarcoderdataPython |
9786662 | # -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.5
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# %% [markdown]
# # 📝 Exercise M4.05
# In the prev... | StarcoderdataPython |
317743 | from werkzeug.serving import run_simple
from webapp import create_app
import sys
from os import path
if __name__ == '__main__':
project_dp = path.dirname(path.dirname(path.realpath(__file__)))
sys.path.append(path.join(project_dp)) # to find any local resolvers
app = create_app(config_file_path='/opt/lor... | StarcoderdataPython |
3290371 | """TODO"""
import pandas
import nltk
nltk.download('punkt') # skip if already downloaded
from sklearn.cross_validation import train_test_split
from textblob.classifiers import NaiveBayesClassifier
from arcode import anycode, clean_str
class XcLassify(object):
"""TODO"""
def __init__(self):
self.__cl = ... | StarcoderdataPython |
8067997 | import unittest
from unittest import mock
from collections import defaultdict
import pandas as pd
from data_profiler.profilers.unstructured_data_labeler_column_profile import UnstructuredDataLabelerProfile
class TestUnstructuredDataLabelerProfile(unittest.TestCase):
def test_char_level_counts(self):
# ... | StarcoderdataPython |
6555466 | import numpy as np
import pandas as pd
from pydantic import ValidationError
from regression_model.config.core import config
from regression_model.processing.schemas import MultipleHouseDataInputs
def drop_na_inputs(*, input_data: pd.DataFrame) -> pd.DataFrame:
"""Check model inputs for na values and filter."""
... | StarcoderdataPython |
12836019 | # Copyright 2017 Tensorflow. All Rights Reserved.
# Modifications copyright 2018 <NAME>/<NAME> & <NAME>
# We follow the object detection API of Tensorflow
#
# 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... | StarcoderdataPython |
6618062 | <reponame>heylenz/python27<gh_stars>10-100
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2004-2005 Trolltech AS. All rights reserved.
##
## This file is part of the example classes of the Qt Toolkit.
##
## This file may be used under the terms o... | StarcoderdataPython |
9632252 | <gh_stars>0
#!/usr/bin/env python3
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def re... | StarcoderdataPython |
1625224 | import sqlite3
# establish a connection with the desired database
conn = sqlite3.connect('rpg_db.sqlite3')
conn # (optional) test the output
# create a cursor -> curs = conn.cursor() -> see loop below
# query for the total number of characters
query = 'SELECT COUNT(DISTINCT character_id) FROM charactercreator_chara... | StarcoderdataPython |
195106 | <reponame>tatuanb/monai_V1
# Copyright 2020 - 2021 MONAI Consortium
# 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 |
6412617 | N = int(input())
D, X = map(int, input().split())
A = [int(input()) for _ in range(N)]
ans = X
for a in A:
if D % a == 0:
ans -= 1
ans += 1 + D // a
print(ans)
| StarcoderdataPython |
3447504 | """ Enhanced functions for list. This enhanced list is
strictly typed """
from typing import Generic, TypeVar, Iterable, List
# generics datatype
Type = TypeVar("T")
class EnhancedList(list, Generic[Type]):
""" extends list of a gerneric type """
def __init__(self, *args: Iterable[Type]):
... | StarcoderdataPython |
17806 | """
A fixed-capacity queue implemented as circular queue.
Queue can become full.
* enqueue is O(1)
* dequeue is O(1)
"""
class Queue:
"""
Implementation of a Queue using a circular buffer.
"""
def __init__(self, size):
self.size = size
self.storage = [None] * size
self.first =... | StarcoderdataPython |
6620245 | """ EfficientNet, MobileNetV3, etc Blocks
Hacked together by / Copyright 2020 <NAME>
"""
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
from .layers import create_conv2d, drop_path, get_act_layer
from .layers.activations import sigmoid
# Defaults used for Google/Tensorflow traini... | StarcoderdataPython |
319326 | from indexor.indexor import Indexor
| StarcoderdataPython |
171076 | # -*- coding: utf-8 -*-
"""Miscellaneous utilities."""
import gzip
import os
from subprocess import check_output # noqa:S404
__all__ = [
"obo_to_obograph",
"obo_to_owl",
]
def obo_to_obograph(obo_path, obograph_path) -> None:
"""Convert an OBO file to OBO Graph file with pronto."""
import pronto
... | StarcoderdataPython |
6706028 | <reponame>Jie-Yuan/1_DataMining
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : iWork.
# @File : DateTimeFeat
# @Time : 2019-06-13 23:16
# @Author : yuanjie
# @Email : <EMAIL>
# @Software : PyCharm
# @Description :
import pandas as pd
from tqdm import tqdm
from datetim... | StarcoderdataPython |
1692247 | #!/bin/env python3
import time
import signal
from gi.repository import GLib
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
from setproctitle import setproctitle, setthreadtitle
from typing import List
from .clipboard import Clipboard
from .keepass import KeepassPasswords
BUS_NAME = "de.naglfar.kru... | StarcoderdataPython |
1917257 | <gh_stars>1-10
import os
import time
import numpy as np
from dataset_loaders.parallel_loader import ThreadedDataset
floatX = 'float32'
class Polyps912Dataset(ThreadedDataset):
'''The Endoluminal Scene Segmentation (EndoScene) of Colonoscopy Images
benchmark
The EndoScene dataset [1]_ consists of 912 f... | StarcoderdataPython |
1984198 | <filename>hamming2.py
# код (n, k) n -- символов в код. слове, k -- символов в сообщении
# пор. мат. G размера k×n
# пров. мат. H размер (n-k)×n
G = [
[1, 0, 0, 0, 1, 1, 0],
[0, 1, 0, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 1, 1],
] # (7, 4)
import numpy as np
G = np.array(G)
print(G.T)
#... | StarcoderdataPython |
265834 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-12-08 06:13
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bicycleparking', '0002_auto_20171129_0126'),
('bicycleparking', '0002_auto_20171129_0128'),
... | StarcoderdataPython |
11352168 | from pathlib import Path
DATA_DIR = Path(__file__).resolve().parent | StarcoderdataPython |
9755674 | import logging
import os
import shutil
from oslo_config import cfg
LOG = logging.getLogger(__name__)
def execute(filename, formatted_name):
"""Renames a file based on the name generated using metadata.
:param str filename: absolute path and filename of original file
:param str formatted_name: absolute ... | StarcoderdataPython |
8147422 | <reponame>hhucn/dbas<filename>api/tests/test_exports.py
import arrow
from webtest.response import TestResponse
from api.exports import import_aif
from api.tests.test_views import create_request_with_token_header
from dbas.database.discussion_model import Issue
from dbas.tests.utils import TestCaseWithConfig, test_app
... | StarcoderdataPython |
6631991 | <filename>url_manager/views.py
#coding: utf-8
import re
import urllib
from models import WrongURL, LongURL, ShortURL
BASE62 = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
nBASE62 = len(BASE62)
PATTERN = r'http://[^/^\s]+[.]\w{2,4}\S/?'
def get_short_id(url):
u'''긴 URL을 받아서 짧은 URL의 id를 반환'''... | StarcoderdataPython |
167432 | from numpy import pi, isclose
from pyroll.core import CircularOvalGroove
def test_circular_oval():
g = CircularOvalGroove(depth=5.05, r1=7, r2=33)
assert isclose(g.usable_width, 17.63799973 * 2)
assert isclose(g.alpha1, 29.102618 / 180 * pi)
assert isclose(g.alpha2, 29.102618 / 180 * pi)
assert ... | StarcoderdataPython |
12854487 | <filename>test/demo-random.py
import snap
G = snap.GenFull(snap.PNEANet, 100)
# get a new random generator, provide the seed value
Rnd = snap.TRnd(42)
# randomize the generator, every execution will produce a different sequence.
# Comment out the line to get the same sequence on every execution.
Rnd.Randomize()
for... | StarcoderdataPython |
4908163 | <filename>core/tests/test_polypod/test_main/test_main_env_vars.py
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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.... | StarcoderdataPython |
6564418 | <filename>ansible/tests/DepreciatedStatementUsage.py<gh_stars>1-10
from ansiblelint.rules import RulesCollection
from ansiblelint.runner import Runner
from ansiblelints.stage.DepreciatedStatementUsage import DepreciatedStatementUsage
class TestDepreciatedStatementUsage:
def test_file(self):
collection =... | StarcoderdataPython |
1647207 | <reponame>pitchin/sentry<filename>src/sentry/models/projectownership.py
from __future__ import absolute_import
from jsonfield import JSONField
from django.db import models
from django.utils import timezone
from sentry.db.models import Model, sane_repr
from sentry.db.models.fields import FlexibleForeignKey
from sentr... | StarcoderdataPython |
1848726 | <reponame>pbs/django-cropduster
import datetime
import unittest
import os
import hashlib
import shutil
import uuid
from django.conf import settings
PATH = os.path.split(__file__)[0]
from django.db import models
from django.core.files.base import ContentFile
from django.core.exceptions import ObjectDoesNotExist as DNE... | StarcoderdataPython |
9699812 | <reponame>mdmintz/seleniumspot
from behave import step
@step("Open the Calculator App")
def go_to_calculator(context):
context.sb.open("https://seleniumbase.io/apps/calculator")
@step("Press C")
def press_c(context):
context.sb.click("button#clear")
@step("Press (")
def press_open_paren(context):
cont... | StarcoderdataPython |
6462342 | from math import *
#Primero, pedimos la temperatura original del huevo.
t0 = float(raw_input("Ingrese la temperatura original del huevo: "))
#Ahora, establezcamos los datos.
M = 63 #Masa. Asumiremos un huevo grande
c = 3.7 #Capacidad calorifica especifica
ro = 1.038 #Densidad
K = 0.0054 #Conductividad termica
tw = 10... | StarcoderdataPython |
8080876 | import matplotlib.pyplot as plt
import gym
import time
from csv import writer
from stable_baselines3.common.type_aliases import GymObs, GymStepReturn
from typing import Union
import numpy as np
import os
from typing import Optional
from autoencoder import load_ae
import gym.wrappers
class AutoEncoderWrapper(gym.Wra... | StarcoderdataPython |
120908 | #!/usr/bin/python3
#
# Copyright © 2017 jared <<EMAIL>>
#
from pydub import AudioSegment, scipy_effects, effects
import os
import settings, util
# combine two audio samples with a crossfade
def combine_samples(acc, file2, CROSSFADE_DUR=100):
util.debug_print('combining ' + file2)
sample2 = AudioSegment.from_w... | StarcoderdataPython |
3338597 | <reponame>risteon/nimble
from __future__ import print_function
import sys
from nimble.sources import KittiOdometrySource
from nimble.sinks import ImageDisplaySink
def main():
if len(sys.argv) < 2:
print("Specify the Kitti dataset root folder as argument")
return
kitti_data = KittiOdometryS... | StarcoderdataPython |
5008070 | import os
import argparse
from shutil import move
import cv2
import shutil
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--inputdir", help="full directory path which hold images/data", type=str)
args = parser.parse_args()
new_dir = os.path.join (os.path.dirname(args.inputdir), "resized_s... | StarcoderdataPython |
9638461 | """This module contains a type to store calculate distances between the player and walls/objects"""
from pygame.math import Vector2
import settings
from side import Side
class Plotter:
"""This type calculates sizes, distances and directions of in game objects in relation to the player"""
def _avoid_zero(se... | StarcoderdataPython |
1621301 | <filename>src/xbot/nlu/intent/intent_with_bert.py
import os
import json
from typing import Any
from src.xbot.util.nlu_util import NLU
from src.xbot.constants import DEFAULT_MODEL_PATH
from src.xbot.util.path import get_root_path, get_config_path, get_data_path
from src.xbot.util.download import download_from_url
from ... | StarcoderdataPython |
4970387 | <reponame>stcz/qfieldcloud<filename>docker-app/qfieldcloud/core/utils2/jobs.py
import logging
from typing import List, Optional
import qfieldcloud.core.models as models
from django.db.models import Q
from qfieldcloud.core import exceptions
logger = logging.getLogger(__name__)
def apply_deltas(
project: "models.... | StarcoderdataPython |
6662594 | <filename>scripts/cji_scripts/migrate_trino.py
#! /usr/bin/env python3.8
import logging
import os
import trino
logging.basicConfig(format="%(asctime)s: %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p", level=logging.INFO)
PRESTO_HOST = os.environ.get("PRESTO_HOST", "localhost")
PRESTO_USER = os.environ.get("PRESTO_USER",... | StarcoderdataPython |
1702749 | from openface.openface_model import create_model
from openface.preprocess_face_data import load_metadata
from openface.align import AlignDlib
import numpy as np
import cv2
import config
import os
from datetime import datetime
# using pre-trained model
print('load_model')
nn4_small2_pretrained = create_model()
nn4_smal... | StarcoderdataPython |
304071 | <filename>compare_methods.py
import sem_utils
import numpy as np
import pandas as pd
np.random.seed(4578347)
##setup search parameters:
timeseries_lengths = np.array([30,100,300,1000,3000,10000])
timeseries_rhos = np.array([0.1, 0.3, 0.5, 0.7, 0.9, 0.99])
numrpts = 100
##setup names and estimation functions
metho... | StarcoderdataPython |
354403 | <filename>Warm-Up Challenges/CountingValleys.py
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
UD = {'U': 1, 'D': -1}
sea_level = 0
valley = 0
for step in s:
sea_level = sea_level +... | StarcoderdataPython |
266052 | <gh_stars>100-1000
from __future__ import print_function, division
import sys,os
quspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,quspin_path)
from quspin.operators import hamiltonian
from quspin.basis import spin_basis_general, boson_basis_general, spinless_fermion_basis_general, spinful_fermion_basis... | StarcoderdataPython |
9697800 | s = str(input('Qual é o seu sexo? [M/F] ')).strip().upper()[0] # [0] só pega a primeira letra
while s not in 'FM':
s = str(input('Sexo inválido! Digite novamente: [M/F] ')).strip().upper()[0]
print('Sexo {} registrado com sucesso!'.format(s))
| StarcoderdataPython |
5029368 | <filename>fine-tune/model/layers.py<gh_stars>100-1000
import torch
from torch.autograd import Variable
from torch import nn
from torch.nn import functional as F
from .basic_layers import sort_batch, ConvNorm, LinearNorm, Attention, tile
from .utils import get_mask_from_lengths
from .beam import Beam, GNMTGlobalScorer
... | StarcoderdataPython |
12818784 | #!/usr/bin/env python
import sys
f1 = open(sys.argv[1])
f2 = open(sys.argv[2])
res = 0
for l1, l2 in zip(f1, f2):
v1 = float(l1.strip())
v2 = float(l2.strip())
rel_diff = abs(v1 - v2) / abs(v1)
if rel_diff > 10 ** -4:
print "Difference: {} vs {}".format(v1, v2)
res = 1
sys.exit(res)
| StarcoderdataPython |
11344288 | <gh_stars>0
from timemachines.skaters.dlm.dlmunivariate import dlm_univariate_a, dlm_univariate_r3
from timemachines.skatertools.evaluation.evaluators import hospital_mean_square_error
def test_dlm_auto_univariate():
print(hospital_mean_square_error(f=dlm_univariate_a, k=3, n=150, n_burn=44))
print(hospital_m... | StarcoderdataPython |
3285222 | <filename>saliency/Saliency_other_models/models/SAM_RESNET/config.py
#########################################################################
# MODEL PARAMETERS #
#########################################################################
# version (0 for SAM-VGG and 1 for SAM-ResNet)
version = 1
# batch si... | StarcoderdataPython |
1767827 | def find_bucket_key(s3_path):
"""
This is a helper function that given an s3 path such that the path is of
the form: bucket/key
It will return the bucket and the key represented by the s3 path
"""
s3_components = s3_path.split("/")
bucket = s3_components[0]
s3_key = ""
if len(s3_comp... | StarcoderdataPython |
5059767 | '''
Classes from the 'AGXMetalA10' framework.
'''
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
AGXA10FamilyIndirectRenderCommandEncoder = _Class('AG... | StarcoderdataPython |
9623295 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='OnedenAliment',
fields=[
('id', models.AutoFiel... | StarcoderdataPython |
6495010 | import torch
import torch.nn as nn
import torch.nn.functional as F
from mflow.models.basic import GraphLinear, GraphConv, ActNorm, ActNorm2D
# class AffineCoupling(nn.Module):
# def __init__(self, in_channel, hidden_channels, affine=True): # filter_size=512, --> hidden_channels =(512, 512)
# super(Affin... | StarcoderdataPython |
11316282 | import minishogilib
import numpy as np
import os
from optparse import OptionParser
import sys
import tensorflow as tf
import threading
import mcts
import network
class USI:
def __init__(self, weight_file):
self.weight_file = weight_file
self.nn = None
self.search = None
self.opti... | StarcoderdataPython |
5167400 | def aVeryBigSum(ar):
# Write your code here
for x in ar:
x = sum(ar)
return x
ar = [1000000001, 1000000002, 1000000003, 1000000004, 1000000005]
print(aVeryBigSum(ar))
# print(ar) | StarcoderdataPython |
3425576 | # -*- coding: utf-8 -*-
from crosspm.helpers.locker import Locker
class Usedby(Locker):
def __init__(self, config, do_load, recursive):
# Ignore do_load flag
super(Usedby, self).__init__(config, False, recursive)
def usedby_packages(self, deps_file_path=None, depslock_file_path=None, package... | StarcoderdataPython |
132828 | # -*- coding: utf-8 -*-
from ..vendor import Qt
from ..vendor.Qt import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(556, 258)
Form.setMinimumSize(QtCore.QSize(0, 0))
self.gridLayout = QtWidgets.QGridLayout(Form)
... | StarcoderdataPython |
1853424 | <reponame>hzy001/xgboost-serving-1<filename>tensorflow_serving/example/xgboost_client.py
# 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
#
# ... | StarcoderdataPython |
6416308 | <reponame>iandtek/realtor-deals-analyzer<filename>app.py
from flask import Flask
import json
app = Flask(__name__)
@app.route("/properties")
def properties():
return {'properties': json.load(open('properties.json'))}
if __name__ == "__main__":
app.run() | StarcoderdataPython |
4801259 | <filename>tests/test_cookie.py
#!/usr/bin/python3
"""
Testing the supposedly beautiful command line parsing
@author chairs
"""
import unittest
from cookie.cookie import Cookie
app = Cookie(__name__, notes=('simple', 'test'))
class TestCookie (unittest.TestCase):
def test_notes (self):
"""
Ensure that the note... | StarcoderdataPython |
9666464 | <filename>ovl/target_filters/contour_filters.py
from typing import Tuple
import math
import cv2
from ..math.contours import contour_center
from ..math.geometry import distance_between_points
from ..math.image import distance_from_frame
from .contour_filter import contour_filter
from ..utils.types import RangedNumber
f... | StarcoderdataPython |
4859608 | import socket
import telnetlib
import struct
from hexdump import hexdump
def q(a):
return struct.pack("I", a)
def interact():
t = telnetlib.Telnet()
t.sock = s
t.interact()
def r_until(st):
ret = ""
while st not in ret:
ret += s.recv(8192)
return ret
s = socket.create_connection(("localhost", ... | StarcoderdataPython |
238249 | import unittest
from hamcrest import assert_that, equal_to
from lxslt import MatchName, DeepDive
class DeepDiveTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.diver = DeepDive(MatchName('child'))
def test_find_on_first_level(self):
tree = ['root', ['child']]
back ... | StarcoderdataPython |
6494235 | <gh_stars>0
from threading import Thread
from . import test_cipher
from . import test_digest
class ThreadedTester(Thread):
failed = False
def run(self):
try:
test_digest.test_digest()
test_cipher.test_cipher(['a' * 1000, 'd' * 1000])
# test_evp.test_rand()
... | StarcoderdataPython |
1890866 | <gh_stars>1-10
loot = input().split("|")
cmd = input()
class Treasure:
def __init__(self, loot):
self.loot = loot
def loot_items(self, found_treasure):
for item in found_treasure:
if item not in self.loot:
self.loot.insert(0, item)
def drop(self, idx):
... | StarcoderdataPython |
263044 | <reponame>fabiangunzinger/python_pottering
import turtle
def koch(t, n):
"""Draw a Koch curve of length n."""
if n < 25:
t.fd(n)
return
koch(t, n/3)
t.lt(60)
koch(t, n/3)
t.rt(120)
koch(t, n/3)
t.lt(60)
koch(t, n/3)
def snowflake(t, n):
"""Draw a Koch snowflake... | StarcoderdataPython |
5125951 | import re
from distutils.command.build import build
from setuptools import setup
from setuptools.command.install import install as _install
VERSION = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]",
open('aws_ir/_version.py', 'r').read(),
re.MULTILINE
).group(1)
class install(_install):
def run(self)... | StarcoderdataPython |
1991086 | from ..contrib.auth.signals import *
| StarcoderdataPython |
6429499 | # This problem was asked by Google.
# Given an array of integers, return a new array where each element in the new array
# is the number of smaller elements to the right of that element in the original input array.
# For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0], since:
# • There is 1 smaller ele... | StarcoderdataPython |
5087795 | import numpy as np
import pandas as pds
from keras.models import Sequential
from keras.layers import Input, Dense, Dropout, BatchNormalization
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.model_se... | StarcoderdataPython |
6456185 | <reponame>tejpratap545/E-Commerce-Application
from backend.users.models import User
from factory import post_generation
from factory.django import DjangoModelFactory
from faker import Faker
from oauth2_provider.models import Application
from typing import Any, Sequence
import factory
fake = Faker()
class UserFacto... | StarcoderdataPython |
1728939 | <gh_stars>1-10
import mechanize
import http.cookiejar
from bs4 import BeautifulSoup as bs
import json
import pandas as pd
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = http.cookiejar.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect... | StarcoderdataPython |
1658779 | #!/usr/bin/python3
from random import randint
def randhex():
i = randint(0,255)
return bytes([i])
def divider1(fname):
divisor = 2
fp1 = open(fname, 'rb')
fp2 = open(fname+'.out1', 'wb')
fp3 = open(fname+'.out2', 'wb')
i = 0
c = fp1.read(1)
while c:
if(i%divisor... | StarcoderdataPython |
8174856 | <gh_stars>1-10
import cv2
from cv2 import aruco
import numpy as np
import matplotlib.pyplot as plt
images=[
"board/0.jpg",
"board/1.jpg",
"board/2.jpg",
"board/3.jpg",
"board/4.jpg",
"board/5.jpg",
"board/6.jpg",
"board/7.jpg",
"board/8.jpg",
"board/9.jpg",
"board/10.jpg",
"board/11.jpg",
"board/12.jpg",
... | StarcoderdataPython |
6450881 |
class BiosModelReaction:
def __init__(self, json, api=None, uid=None, id=None, model=None):
self.json_data = json
self.api = api
#self.database = database
@property
def id(self):
return self.json_data['id']
@property
def uid(self):
return self.json_da... | StarcoderdataPython |
8192625 | <reponame>rputh055/crawlzerotest
from django.conf.urls import url
from crawlzero import views
# SET THE NAMESPACE!
app_name = 'crawlzero'
# Be careful setting the name to just /login use userlogin instead!
urlpatterns=[
url(r'^register/$',views.register,name='register'),
url(r'^user_login/$',views.user_login,na... | StarcoderdataPython |
6579616 | from datetime import time
from typing import List, Optional
class Arduino:
def __init__(self, id: int, name: str, template_id: int):
self.__id = id
self.name = name
self.template_id = template_id
@property
def id(self) -> int:
return self.__id
class Template:
def __i... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.