id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
33022 | import random
from torchvision.transforms import functional as F
from torchvision.transforms import transforms
from PIL import Image | StarcoderdataPython |
1624582 | import pytest
@pytest.fixture
def context():
class Context(object):
pass
return Context()
| StarcoderdataPython |
6552868 | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import io
import zipfile
import tempfile
import unittest
from six.moves import filterfalse
import fs.test
import fs.wrap
import fs.errors
import fs.memoryfs
import fs.archive.zipfs
from fs.path import relpath, j... | StarcoderdataPython |
6424725 | from typing import Callable
import requests
from .... import IGraphResponse, IGraphFilter, IGraphAction
from ...abstractions.ISharepointDocumentLibrary import ISharepointDocumentLibrary
from ...abstractions.ISharepointList import ISharepointList
from ...utilities.sharepoint_graph_client_base import SharepointGraphClie... | StarcoderdataPython |
6432684 | <reponame>i1caro/hotel
import logging
# import os
# create logger
logging.basicConfig(
filename='python.log',
level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S'
)
# logger = logging.getLogger('hotel')
# # create file handler which logs even info messages
# ... | StarcoderdataPython |
9635159 | # Generated by Django 3.0.7 on 2020-06-27 19:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coletaeapi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='collectionpoint',
name='address',
... | StarcoderdataPython |
248113 | #!/usr/bin/env python
# Author: <NAME>
# Core Python Pogramming - Homework 9
import os, imp
import string, random
def file_fliter(name): # 9-1
fhand = open(name)
for line in fhand:
if line[0] != '#':
print line,
fhand.close()
def read_file(): # 9-2
fhand = open(raw_input('Fil... | StarcoderdataPython |
3557120 | from .common import add_history_args, add_vehicle_args, format_duration_minutes, get_vehicle
from datetime import datetime
from tabulate import tabulate
help_text = 'Show charging statistics for your vehicle.'
def configure_parser(parser):
add_vehicle_args(parser)
add_history_args(parser)
parser.add_arg... | StarcoderdataPython |
1752280 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from solo.admin import SingletonModelAdmin
from events.models import Event, Profile, Team, Event, TeamMembership
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
pass
@admin.register(Event)
class E... | StarcoderdataPython |
5124520 | <filename>api/test/app/batch/test_db_data_exporter.py
"""
dc-test /usr/test/app/batch/test_db_data_exporter.py
"""
from unittest import mock
import pytest
from src.app.batch.db_data_exporter import DBDataExporter
from src.app.config.hard_constants import HardConstants
from src.app.models.comment import CommentDAO
fr... | StarcoderdataPython |
3219393 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 17:39:25 2020
@author: prachi
"""
import os
import sys
import numpy as np
import subprocess
import pickle
import argparse
#updating
def setup():
"""Get cmds and setup directories."""
cmdparser = argparse.ArgumentParser(description='con... | StarcoderdataPython |
3346685 | version = "0.90.20190728"
| StarcoderdataPython |
3291147 | import numpy as np
from spearmint.grids import sobol_grid
def evaluate(job_id, params):
x = params['X']
y = params['Y']
z = params['Z']
#print 'Evaluating at (%f, %f, %f)' % (x, y, z)
obj1 = float(x*np.power(16.0+np.power(z,2.0),0.5)+y*np.power(1.0+np.power(z,2.0),0.5)) + np.random.normal(0,0.00... | StarcoderdataPython |
12860471 | <gh_stars>0
import climate
import glob
import gzip
import io
import lmj.cubes
import logging
import numpy as np
import os
import pandas as pd
import pickle
import theanets
def compress(source, k, activation, **kwargs):
fns = sorted(glob.glob(os.path.join(source, '*', '*_jac.csv.gz')))
logging.info('%s: found ... | StarcoderdataPython |
1863279 | <gh_stars>0
from gitlabform.gitlab.core import GitLabCore
class GitLabServices(GitLabCore):
def get_service(self, project_and_group_name, service):
return self._make_requests_to_api("projects/%s/services/%s", (project_and_group_name, service))
def set_service(self, project_and_group_name, service, d... | StarcoderdataPython |
9631960 | <reponame>Superomeg4/SciDataTool<gh_stars>0
import numpy as np
from SciDataTool.Functions import NormError, UnitError, AxisError
from SciDataTool.Functions.conversions import convert as convert_unit, to_dB, to_dBA
from SciDataTool.Functions.derivation_integration import (
derivate,
integrate,
antiderivate,... | StarcoderdataPython |
3269920 | '''
Author: <NAME>
Email: <EMAIL>
Date created: 2020/1/6
Python Version: 3.6
'''
"""
Code to split the data into train and test dataset
"""
import configparser
import logging
import sys
import click
import ast
import pandas as pd
import os
sys.path.append('.')
from src.data.utils import read_raw_data... | StarcoderdataPython |
6665109 | <reponame>thequicksort/puddle
import networkx as nx
from puddle import mk_session, Droplet, project_path
min_volume = 1.0
max_volume = 4.0
def plan(low, high, target, epsilon=0.01):
graph = nx.DiGraph()
mid = (low + high) / 2
while abs(mid - target) > epsilon:
graph.add_edge(low, mid)
g... | StarcoderdataPython |
3380185 | <gh_stars>0
import connexion
import os
import project.app
orig_environ = dict(os.environ)
orig_environ["ALLOWED_API_KEYS"] = "test-api-key"
os.environ.update(orig_environ)
from flask_sqlalchemy import SQLAlchemy
from flask_testing import TestCase
from sqlalchemy.exc import SQLAlchemyError
from ge_core_shared import ... | StarcoderdataPython |
1744590 | # Under MIT License, see LICENSE.txt
from typing import Dict
from Util import Position
class Ball:
def __init__(self, position=Position()):
self._position = position
self._velocity = Position()
def update(self, new_dict: Dict):
self.position = new_dict['position']
self.velo... | StarcoderdataPython |
3448141 | <gh_stars>1-10
a=[]
b=[]
def multiples_of_3(n):
i=1
for i in range(n): # stops at 1 less than the value passed to `range`
m=i*3
if(m<n):
a.append(m)
def multiples_of_5(n):
j=1
for j in range(n): # could change to 201 and still work
k=j*5
if(k<n):
... | StarcoderdataPython |
8003973 | import random
import time
import sys
from pyparsems import *
def genNums(size):
nums = []
for i in range(size):
nums.append(random.randint(0, 10))
return nums
def sumList(nums):
res_sum = sum(nums)
if __name__ == '__main__':
if len(sys.argv) and sys.argv[1].isdigit():
n = int(sys.argv[1])
st ... | StarcoderdataPython |
3286239 | <reponame>kathryncrouch/eupathws
# -*- coding: utf-8 -*-
#
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2016 Genome Research Ltd
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission no... | StarcoderdataPython |
3494413 | class PyZbarError(Exception):
pass
| StarcoderdataPython |
3303954 | def fixformatting(data):
passports = []
currentPassport = {}
for line in data:
if line == "": # Stack Overflow code
passports.append(currentPassport)
currentPassport = {}
else:
for item in line.split(" "):
key, value = item.split(":")
... | StarcoderdataPython |
3457147 | <reponame>collinwright/nixpkgs
#!/usr/bin/python
import json
import sys
def process_section(name, section):
packages = set()
if "resolved" in section:
packages.add((name, section["resolved"]))
if "dependencies" in section:
for name in section["dependencies"]:
packages.add((n... | StarcoderdataPython |
1818342 | <gh_stars>1-10
from __future__ import absolute_import
from . import auth_providers
from .app import KnowledgeFlask
from .db_repo import DBSession
session_obj = DBSession()
db_repo_session = session_obj.session()
db_repo_engine = session_obj.engine()
| StarcoderdataPython |
5089414 | #!/usr/bin/env python
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxyActionClient
from lisa_interaction_msgs.msg import LisaUtterAction, LisaUtterGoal
class LisaUtterActionStateWithUserkey(EventState):
'''
An uttering action is performed with high priority (all running dialogue are d... | StarcoderdataPython |
11388238 | <reponame>dmontielg/smoking-microbiome
#!/usr/bin/env python
import os
import subprocess
import warnings
from collections import Counter
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelBinarizer
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import matthews_corrcoe... | StarcoderdataPython |
8025643 | <gh_stars>0
money = float(input())
sex = input()
years = int(input())
sport = input()
price = 0.0
if sex == "m":
if sport == "Gym":
price = 42
elif sport == "Boxing":
price = 41
elif sport == "Yoga":
price = 45
elif sport == "Zumba":
price = 34
elif sport == "Dances":... | StarcoderdataPython |
3318795 | <reponame>joshmaglione/ZetaFunctionSandbox
#
# Copyright 2019 <NAME>
#
# Distributed under MIT License
#
from sage.all import Matrix as _Matrix
from sage.all import Polyhedron as _Polyhedron
from sage.all import PolynomialRing as _PolynomialRing
from sage.all import QQ as _QQ
from sage.all import var as... | StarcoderdataPython |
3231065 | from .wrapped_dict import WrappedDict
class WorldState(WrappedDict):
"""A model of the world state"""
def __init__(self, *args, **kwargs):
self.turn_number = 0
super().__init__(*args, **kwargs)
def automatic_tick(self):
return
def execution_tick(self):
return
de... | StarcoderdataPython |
3349410 | print('1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);')
def prime(n):
i = 2
while n > i:
if n % i == 0:
return (n,'непростое число')
i += 1
if i == n:
return (n,'простое число')
print(prime(51))
print(prime(17))... | StarcoderdataPython |
9647745 | #coding:utf-8
# 作为库,下面的导入为 .tt 而不是 tt,
# 但是这样作为主程序启动就会报错,
# "ImportError: attempted relative import with no known parent package"
#
# 如果用.tt 作为主程序不会报错,但作为库使用会报错
# ImportError: No module named 'tt'
# 如果作为库,可以添加 -m
# python -m file_io.print_abspath (要从主文件夹启动)
# 不管从哪里输出,当前文件夹总是主程序文件夹
import os
from .tt im... | StarcoderdataPython |
6439368 | import numpy as np
from collections import deque
class CollisionDetector:
collision_resolution = 1
def __init__(self, env):
self.env = env
def isCollidedPoint(self, point):
return self.env[point[0],point[1],point[2]]
def isCollidedPath(self, start, end):
size = (start - end... | StarcoderdataPython |
3344475 | """An example of training PCL against OpenAI Gym Envs.
This script is an example of training a PCL agent against OpenAI Gym envs.
Both discrete and continuous action spaces are supported.
To solve CartPole-v0, run:
python train_pcl_gym.py
To solve InvertedPendulum-v1, run:
python train_pcl_gym.py --env Inver... | StarcoderdataPython |
3387044 | <reponame>PHIKN1GHT/secp_2020<gh_stars>0
from server import app, DBSession
from flask import Blueprint, request, session, send_file, make_response, jsonify
from utils import captcha, cmparePswd, invalid, invalidate
from flask_jwt_extended import jwt_required, jwt_optional, create_access_token, get_jwt_identity, get_ra... | StarcoderdataPython |
6626015 | <gh_stars>1-10
# 2019-11-11 16:07:35(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# from scipy.misc impo... | StarcoderdataPython |
390542 | import os
import ogr
from math import ceil
def rasttovecgrid(outputGridfn,xmin,xmax,ymin,ymax,gridHeight,gridWidth):
# convert sys.argv to float
xmin = float(xmin)
xmax = float(xmax)
ymin = float(ymin)
ymax = float(ymax)
gridWidth = float(gridWidth)
gridHeight = float(gridHeight)
# ge... | StarcoderdataPython |
5167299 | <filename>setup.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = his... | StarcoderdataPython |
11283648 | import torch as t
import torch.nn as nn
import torch.nn.functional as F
class AttentionLayer(nn.Module):
"""simple layer for attention-based convolution"""
def __init__(self, opt, in_channel, out_channel, alpha, concat=True):
super(AttentionLayer, self).__init__()
self.drop_out = opt.drop_out
... | StarcoderdataPython |
3498111 | #!flask/bin/python
from flask import Flask, request, logging
from KNX import *
import logging
app = Flask(__name__)
@app.route('/store/<int:floor_id>/<int:store_id>', methods=['POST'], strict_slashes=False)
def setStore(floor_id, store_id):
# Example values: 200 2 2 3/4/1
content = request.get_json()
valu... | StarcoderdataPython |
3394554 | from animation import Animation
import time
import numpy as np
import colorsys
from numpy import pi
import travellers
import standers
from utils import add_params
class Brendo(Animation):
layout_type = "Layout"
def __init__(self, layout,
shift_rate=0,
num_sections=10,
**kwargs
... | StarcoderdataPython |
8140480 | <filename>mailer/engine.py<gh_stars>0
from time import sleep
from models import Message, DontSendEntry, MessageLog
from django.core.mail import *
## configuration settings
# @@@ eventually move to settings.py
# when queue is empty, how long to wait (in seconds) before checking again
EMPTY_QUEUE_SLEEP = 300
def p... | StarcoderdataPython |
237642 | current_cycle = '2021-3'
pilatus_data_dir = "/exp_path/hdf"
| StarcoderdataPython |
143245 | <gh_stars>1-10
from typing import Any, List, Dict, Optional, Sequence
from scipy import sparse
import os
import sklearn
import numpy # NOTE numpy is used only to set types and nan values. FIXME with correct types from AF
# import arrayfire as af # FIXME uncommnet when line 300 is resolved
from numpy import ndarray ... | StarcoderdataPython |
12840405 | <reponame>cffbots/ESMValTool<filename>esmvaltool/cmorizers/obs/cmorize_obs_aphro_ma.py<gh_stars>100-1000
"""ESMValTool CMORizer for APHRODITE Monsoon Asia (APHRO-MA) data.
Tier
Tier 3: restricted dataset.
Source
http://aphrodite.st.hirosaki-u.ac.jp/download/
Last access
20200306
Download and processing ... | StarcoderdataPython |
5149056 | <filename>python_system.bzl
# Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | StarcoderdataPython |
5045047 | # Idea from
#<EMAIL>
def fiboSum(n):
if n==0: return [-1]
if n==1: return [1]
total = 0
fibo = [1]
f = 1
while f<=n:
fibo.append(f)
f+=fibo[len(fibo)-2]
fibo.pop(1)
index = len(fibo)-1
while sum(fibo)!=n:
if sum(fibo)-fibo[index] ==n:
fibo.pop(inde... | StarcoderdataPython |
46059 | <gh_stars>1-10
# Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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 |
8048029 | <filename>model/efficientnet.py
from efficientnet_pytorch import EfficientNet
import torch.nn.functional as F
import torch.nn as nn
class efficientnet(nn.Module):
def __init__(self, num_classes=1000):
super(efficientnet, self).__init__()
self.encoder = EfficientNet.from_pretrained('efficientnet-b1'... | StarcoderdataPython |
1678723 | import os
from flask import Flask, render_template, request, make_response, session, url_for, redirect, flash, abort
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.secret_key = 'wohohoho'
#upload
ALLOWED_EXTENSION = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] ='... | StarcoderdataPython |
4850104 | print('='*21)
print('Calculadora de média')
print('='*21)
n1 = float(input('Insira uma nota: '))
n2 = float(input('Insita a segunda nota: '))
print(f'A média de notas é igual a {(n1+n2)/2:.1f}.')
| StarcoderdataPython |
8072258 | import dash_html_components as html
from app import app
layout = html.Div(
'animations'
) | StarcoderdataPython |
11362659 | <reponame>curiousleo/wren
import re
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from pygments.lexer import RegexLexer
from pygments.token import *
class WrenLexer(RegexLexer):
name = 'Wren'
aliases = ['wren']
filenames = ['*.wren']
... | StarcoderdataPython |
1889385 | """
Server related classes (Daemon etc)
Pyro - Python Remote Objects. Copyright by <NAME> (<EMAIL>).
"""
import os
import sys
import uuid
import time
import socket
import collections
import threading
import logging
import inspect
import warnings
import serpent
from . import config, core, errors, serializers, socketu... | StarcoderdataPython |
3215090 | <gh_stars>0
from graphviz import Digraph, Source, render
from datetime import datetime
import sys
file = sys.argv[1]
system_time = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
if __name__ == "__main__":
for eng in ("dot", "neato", "twopi", "circo", "fdp", "sfdp"):
dot = Digraph(comment=system_time + '_' +... | StarcoderdataPython |
8098497 | <gh_stars>1-10
import os
import sys
import argparse
from core.config import conf
parser = argparse.ArgumentParser()
parser.add_argument("--develop", action="store_true", help="Run app on development mode.")
parser.add_argument("--log", type=int, help="Set log level", default=None)
parser.add_argument("-d", "--daemon",... | StarcoderdataPython |
1940213 | from django.conf.urls import patterns, url
urlpatterns = patterns(
'api.dc.template.views',
# /template - get
url(r'^$', 'dc_template_list', name='api_dc_template_list'),
# /template/<name> - get, create, delete
url(r'^(?P<name>[A-Za-z0-9\._-]+)/$', 'dc_template', name='api_dc_template'),
)
| StarcoderdataPython |
132267 | <gh_stars>1000+
# -*- coding: utf-8 -*-
# @Time : 2017/8/8 12:33
# @Author : play4fun
# @File : knn-find_nearest.py
# @Software: PyCharm
"""
knn-find_nearest.py:
http://www.bogotobogo.com/python/OpenCV_Python/python_opencv3_Machine_Learning_Classification_K-nearest_neighbors_k-NN.php
"""
import cv2
import nump... | StarcoderdataPython |
8059611 | <filename>reg.py
import re
import os
import os.path as osp
import gc
import argparse
from datetime import datetime
from typing import List
import numpy as np
from skimage.transform import AffineTransform, warp
import pandas as pd
import cv2 as cv
import tifffile as tif
import dask
from metadata_handling import genera... | StarcoderdataPython |
8002225 | """Test Hue migration logic."""
from unittest.mock import patch
from homeassistant.components import hue
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry
async def test_migrate_api_key(hass):
"""Test if username gets migrated to api_key."""
... | StarcoderdataPython |
8004290 | <gh_stars>0
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param n: An integer
@return: The head of linked list.
"""
def removeNthFrom... | StarcoderdataPython |
3384581 | <filename>tests/backup_test.py
import io
from fixtures import *
import tarfile
import gzip
def test_backing_up_config_dir():
compressed_tar_blob = manager.backup.config_dir()
tar = tarfile.open(fileobj=io.BytesIO(compressed_tar_blob), mode='r:*')
# The configuration directory has 9 files in it, plus the ... | StarcoderdataPython |
6664316 | """Test the variable meanings dictionary."""
import os
import os.path as op
import json
import sp_experiment
from sp_experiment.define_variable_meanings import (make_description_task_json,
make_events_json_dict,
mak... | StarcoderdataPython |
3488669 | <reponame>bharshbarger/python_toolbox
import subprocess
def tmux_execute(session_name, command):
proc = subprocess.Popen(['tmux', 'new-session', '-d', '-s', '{}'.format(session_name),\
'{}'.format(command)], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
| StarcoderdataPython |
206763 | # Tencent is pleased to support the open source community by making GNES available.
#
# Copyright (C) 2019 THL A29 Limited, a Tencent company. 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... | StarcoderdataPython |
3354120 | <reponame>Satanepigone/osr2mp4-app<gh_stars>100-1000
from PyQt5.QtWidgets import QLabel
class ParentTitle(QLabel):
def __init__(self, default_fontsize=1, color="white"):
super().__init__()
self.default_width = 1
self.default_height = 1
self.default_fontsize = default_fontsize
self.color = color
self.setS... | StarcoderdataPython |
5004514 | <gh_stars>1-10
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + "/../../")
import soundscapy.ssid.parameters as par
from pytest import raises
def test_surveyvar_dict():
for key, val in par.SURVEY_VARS.items():
if key in ["Traffic", "Other", "Human", "Natural... | StarcoderdataPython |
5046682 | <filename>src/py42/settings/debug.py
import logging
import sys
class _DebugSettings(object):
INFO = logging.INFO
DEBUG = logging.DEBUG
TRACE = logging.DEBUG
NONE = logging.NOTSET
def __init__(self):
self.logger = logging.getLogger("py42")
self.logger.addHandler(logging.StreamHandl... | StarcoderdataPython |
1659916 | #import helper
#import helper as h
from helper import validate_and_execute, user_input_message
user_input = ""
while user_input != "exit":
user_input = input(user_input_message)
days_and_unit = user_input.split(":")
days_and_unit_dict = {"days": days_and_unit[0], "unit": days_and_unit[1]}
validate_and_... | StarcoderdataPython |
5195958 | <filename>custom_components/ha-pyamdgpuinfo/const.py
""" The AMD GPU component."""
from homeassistant.components.sensor import (
DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
)
from homeassistant.const import (
CONF_RESOURCES,
DATA_MEBIBYTES,
PERCENTAGE,
TEMP_CELSIUS,... | StarcoderdataPython |
8137713 | <filename>python/package/open_waters/document/__init__.py<gh_stars>1-10
class Document:
__baseEndpoint = 'documents'
__client = None
def __init__(self, __client):
self.__client = __client
def upload(self, file_path: str) -> dict:
""" Upload document
:rtype: dict
:para... | StarcoderdataPython |
8198317 | # 763. Partition Labels
# Runtime: 40 ms, faster than 75.24% of Python3 online submissions for Partition Labels.
# Memory Usage: 14.4 MB, less than 24.03% of Python3 online submissions for Partition Labels.
class Solution:
# Greedy
def partitionLabels(self, s: str) -> list[int]:
last = {c: i for i, ... | StarcoderdataPython |
377194 | #!/usr/bin/env python
from django.apps import AppConfig
class DjangoMakeSuperUserConfig(AppConfig):
name = 'django_makesuperuser'
| StarcoderdataPython |
4915353 | import io
import json
import os
import copy
import os.path
from datetime import datetime
from io import BytesIO
import yaml
from PyPDF2 import PdfFileReader
from PyPDF2.generic import IndirectObject
from lxml import etree
from .flavors import xml_flavor
from .logger import logger
from .pdfwriter import FacturXPDFWrit... | StarcoderdataPython |
8102263 | import numpy
from scipy.ndimage import convolve
from skimage.data import camera
from skimage.util import random_noise
from dexp.processing.filters.fft_convolve import fft_convolve
from dexp.utils.backends import Backend, CupyBackend, NumpyBackend
def demo_fft_convolve_numpy():
with NumpyBackend():
_demo_... | StarcoderdataPython |
4932465 | from opensfm import dataset
from numpy import ndarray
from typing import Dict, Tuple
def get_all_track_observations(gcp_database, track_id: str) -> Dict[str, ndarray]:
print(f"Getting all observations of track {track_id}")
data = dataset.DataSet(gcp_database.path)
tracks_manager = data.load_tracks_manager... | StarcoderdataPython |
3420082 | from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/matchcoaches", methods=['POST'])
def hello():
return jsonify(coaches=[1,2,3], error=False)
| StarcoderdataPython |
8139808 | <gh_stars>0
import PIL
import torch
import numpy as np
from PIL import Image
class Transformer(object):
""""Transform"""
def __init__(self,):
pass
def __call__(self, img, bbox=None):
pass
class Compose(Transformer):
"""Compose transforms"""
def __init__(self, transforms=[]):
... | StarcoderdataPython |
1895495 | # -*- coding:utf-8 -*-
import os
import time
import functools
from PyQt5 import uic
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from utils import loadJson
from _rpc import _exec, _eval
class ControlPanel(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ControlPanel, self).__init__(par... | StarcoderdataPython |
8164315 | <filename>convlab2/laug/Word_Perturbation/multiwoz/types.py
from typing import TypeVar, NewType, Union, List, Dict
SampleType = TypeVar("SampleType")
StringType = str
WordType = TokenType = NewType("TokenType", str)
TokenListType = WordListType = List[TokenType]
SentenceType = Union[StringType, TokenListType]
... | StarcoderdataPython |
3214631 | """Public interface for TensorFlow GNN package.
All the public symbols, data types and functions are provided from this
top-level package. To use the library, you should use a single import statement,
like this:
import tensorflow_gnn as tfgnn
The various data types provided by the GNN library have corresponding ... | StarcoderdataPython |
12823183 | <reponame>liuyepiaoxiang/es6-learning
#!usr/bin/sh
# -*- coding:utf8 -*-
# this is a guess number game
import random
secretNumber = random.randint(1,20)
print('请猜一个0到20的数')
# ask the player to guess 6 times.
for guessTaken in range(1,7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:... | StarcoderdataPython |
11231552 | <reponame>zz-xx/robox86<filename>cogs/others/WebtoonsUpdates.py
from datetime import date
import discord
from discord.ext import commands
from x86 import helpers
class WebtoonsUpdates:
'''Reminds you when new chapter of your favorite webtoon is out'''
@commands.group(aliases=['Webtoons',... | StarcoderdataPython |
6419546 | """
TODO: Move to `godopy/contrib/scripts/` and allow installation from there
"""
from godot import bindings
from godot.nativescript import register_tool_class, register_method
from IPython.terminal.embed import InteractiveShellEmbed
POLL_INTERVAL = 0.05
class GodotPythonShell(InteractiveShellEmbed):
def init_... | StarcoderdataPython |
3209517 | <reponame>andrewdbell/downhill_skier
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('dodgerblue2')
FONT = pygame.font.Font(None, 32)
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = ... | StarcoderdataPython |
1845780 | # Task 2: Maximum Value calculation
def maximum(value_list):
# Initialize the maximum value with the first value in the list
max_value = value_list[0]
# Iterate through all values of the list
for value in value_list:
# If the current value in the list is higher than the actual max value ...
i... | StarcoderdataPython |
11229991 | <filename>v1.0.0.test/toontown/parties/DistributedPartyCannonActivityAI.py
from direct.directnotify import DirectNotifyGlobal
from toontown.parties.DistributedPartyActivityAI import DistributedPartyActivityAI
class DistributedPartyCannonActivityAI(DistributedPartyActivityAI):
notify = DirectNotifyGlobal.directNoti... | StarcoderdataPython |
1860168 | from random import *
import numpy as np
import time
import logging
import tkinter as tk
from PIL import Image, ImageTk
import pygame as pygame
#*************************************************************************
# Classe Paquet:
# Une carte est representé par sa valuer, sa figure et le fichier image
# le represa... | StarcoderdataPython |
9754363 | from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from . import forms
from .models import User
from django.contrib.sites.shortcuts import get_current_site
from django.utils.enco... | StarcoderdataPython |
6649877 | """
This file contains puller implementations for XRay
"""
import logging
from datetime import datetime
from typing import Optional, Any, List, Set
from samcli.lib.observability.observability_info_puller import ObservabilityEventConsumer
from samcli.lib.observability.xray_traces.xray_event_puller import AbstractXRayPu... | StarcoderdataPython |
3455697 | from __future__ import (absolute_import, division, print_function)
from odm2api.ODMconnection import SessionFactory
from odm2api.models import CVElevationDatum, setSchema
import pytest
__author__ = 'valentine'
dbs_readonly = [
['mysql:ODM@Localhost/', 'mysql', 'mysql+pymysql://ODM:odm@localhost/'],
['mysql... | StarcoderdataPython |
5178744 | import argparse
import os
import re
from django.apps import apps
from django.db import models
from django.conf import settings
from django.core.files import File
from django.core.management.base import BaseCommand
_ = lambda x: x
DB_PATTERN = re.compile(r'^\w+\.\w+/bytes/filename/mimetype$')
class Command(BaseCom... | StarcoderdataPython |
6645970 |
# This feature can be used to reduce the memory size consumed by the feature layer of the top MLP.
# Suppose we have n sparse features, each sparse features is represented by an embedding of size d,
# then, we can represent the sparse embeddings by a matrix X = (n, d). The dot product between sparse
# features is X(X^... | StarcoderdataPython |
9655874 | """
Early fusion scorer (i.e., object-centric model using language modeling).
@author: <NAME>
@author: <NAME>
"""
from nordlys.logic.fusion.fusion_scorer import FusionScorer
from nordlys.core.retrieval.elastic import Elastic
from nordlys.core.retrieval.retrieval_results import RetrievalResults
from collections import ... | StarcoderdataPython |
3572559 | <filename>tests/bamResample.py<gh_stars>10-100
#!/usr/bin/env python
import sys
import re
import pysam
import random
import os
from optparse import OptionParser
opts = OptionParser()
usage = "usage: %prog [options] [inputs] Software to process aligned bam files and generate the XB (Cell Barcode) tag"
opts = OptionPar... | StarcoderdataPython |
396341 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 3 13:20:01 2021
@author: mclea
"""
import field as f
import possion_matrix
import MG
import matplotlib.pyplot as plt
k = 7
n = 2**k+2
m = 2**k+2
x = f.new_field(n, m, top=10, bottom=-10, left=0, right=0, bc=0)
b = f.new_field(n, m, top=0, bottom=0, left=0, ... | StarcoderdataPython |
4962990 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import print_function
from __future__ import absolute_import
import numpy as np
import tensorflow as tf
from sandbox.rocky.tf.core.layers_powered import LayersPowered
from sandbox.rocky.tf.core.network import MLP
from sandbo... | StarcoderdataPython |
3347135 | <reponame>stungkit/Copycat-abstractive-opinion-summarizer
from nltk.util import ngrams as compute_ngrams
import numpy as np
from collections import OrderedDict
X_AND_X_PROP = 'x_and_x_prop'
X_AND_X_COUNT = 'x_and_x_count'
UN_SENT_PROP_PROP = 'un_sent_prop'
AVG_SEQ_LEN = 'avg_seq_len'
UN_SENTS = 'un_sents'
TOTAL_SENTS ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.