id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3268576 | <filename>apps/greencheck/views.py
from datetime import date
from datetime import timedelta
from django.conf import settings
from google.cloud import storage
from django.views.generic.base import TemplateView
class GreenUrlsView(TemplateView):
template_name = "green_url.html"
def fetch_urls(self):
c... | StarcoderdataPython |
250688 | import argparse
import ntpath
import os
from shutil import copyfile
def list_diff(li1, li2):
"""returns a list with the difference of 2 lists"""
return list(list(set(li1) - set(li2)) + list(set(li2) - set(li1)))
def get_files_from(location, pattern):
"""returns the files from a folder
you can specif... | StarcoderdataPython |
8126296 | <gh_stars>0
#!/usr/bin/python3 -u
# Copyright 2018-present Facebook, 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 require... | StarcoderdataPython |
8084392 | # Modularização em python
'''VANTAGENS
* ORGANIZAÇÃO DO CÓDIGO
* FACILIDADE DE MANUTENÇÃO
* OCULTAÇÃO DE CÓDIGO DETALHADO
* REUTILIZAÇÃO EM OUTROS PROJETOS'''
'''Para se utilizar de modulos se cria um arquivo com as funções
e quando se quiser usar das mesmas se importa deste arquivo as funçoes para determindado
... | StarcoderdataPython |
11255818 | import typing as t
from werkzeug.datastructures import Headers
from werkzeug.wrappers import BaseResponse
_str_bytes = t.Union[str, bytes]
_data_type = t.Union[
_str_bytes,
BaseResponse,
t.Dict[str, t.Any],
t.Callable[
[t.Dict[str, t.Any], t.Callable[[str, t.List[t.Tuple[str, str]]], None]],
... | StarcoderdataPython |
3389903 | """
Name: <NAME>
CIS 41A Spring 2020
Unit E Take-Home Assignment
"""
# Second Script – Guessing Game
# Write a script that plays a simple guessing game.
# The script will generate a secret number from 1 to 100, inclusive, and the user will have to guess the number.
# After each guess, the script will tell the user ... | StarcoderdataPython |
6474025 | <gh_stars>0
# -*- codeing: utf-8 -*-
class Calculator(object):
def calculate(self, src):
if len (src) == 0:
return 0
else:
return self._parse_expression(src)
def _parse_expression(self, src):
num_left = self._parse_term(src)
result = num_left[0]
... | StarcoderdataPython |
6643149 | #!/usr/bin/python3
'''
OpenBLAS Relay Library Generator
Copyright (C) 2019 <NAME> <<EMAIL>>
License: MIT/Expat
Julia decided to mangle the symbols of the vendored copy of openblas
(INTERFACE64=1). I didn't read all the past discussions but in fact the symbol
mangling introduced difficulty in distribution packaging, an... | StarcoderdataPython |
3331392 | # -*- coding: utf-8 -*-
import os
class Constants():
time_to_leave_file = '/tmp/cosycar_will_leave_at.txt'
weather_storage_file = '/tmp/cosycar_weather.txt'
weather_interval = 15
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
cfg_file_path = '.config'
cfg_file_name = 'cosy... | StarcoderdataPython |
8047517 | # politician/urls.py
# Brought to you by <NAME>. Be good.
# -*- coding: UTF-8 -*-
from . import views_admin
from django.conf.urls import url
urlpatterns = [
url(r'^$', views_admin.politician_list_view, name='politician_list',),
url(r'^edit_process/$', views_admin.politician_edit_process_view, name='politicia... | StarcoderdataPython |
8149326 | import pyOcean_cpu as ocean
# Type casting applied to storage objects
s = ocean.asTensor([1,2,3]).storage
print(s)
t = ocean.int8(s)
print(t)
ocean.float(s, True)
print(s)
| StarcoderdataPython |
1801615 | # Tests in this file use an Org admin user provided by a Pytest fixture. The
# tests here should be a subset of the secretariat tests, since the CNA of last
# resort should always be able to perform any root CNA functionality in
# addition to functionality reserved for the CNA of last resort.
import json
import request... | StarcoderdataPython |
5114130 | import matplotlib.pyplot as plt
import numpy as np
import json
with open('../tokamaks.json') as f:
machines = json.load(f)
# by type of machine
plt.figure()
types_labels = ["Tokamaks", "Stellarators", "Inertial", "Others"]
types_machine = ["tokamak", "stellarator", "inertial", "alternate_concept"]
bottom = 0
cou... | StarcoderdataPython |
3219399 | import re
import math
import random
import json
import sys
from nalgene.node import *
SHIFT_WIDTH = 4
start_space = r'^( )*'
def count_indent(s):
indent = len(re.match(start_space, s).group(0))
return math.floor(indent / SHIFT_WIDTH)
def parse_string(base_dir, string):
lines = string.split('\n')
... | StarcoderdataPython |
11377668 | <reponame>jayanthyetukuri/CARLA
import itertools
import numpy as np
from .sampler import Sampler
def initialize_non_saturated_action_set(
scm,
dataset,
sampling_handle,
classifier,
factual_instance,
intervention_set,
num_samples=1,
epsilon=5e-2,
):
# default action_set
action... | StarcoderdataPython |
40768 | import pandas as pd
from nilearn.signal import clean
from nilearn.interfaces.fmriprep import load_confounds_strategy, load_confounds
from fmriprep_denoise.data.atlas import create_atlas_masker, get_atlas_dimensions
def generate_timeseries_per_dimension(atlas_name, output, benchmark_strategies,
... | StarcoderdataPython |
11378787 | from os import close, name
from broker import Broker
from config import AssetType, Config, SpreadMode
from sessional_spread import SessionalSpread
from typing import List, Dict
from datetime import timedelta
import pandas as pd
import numpy as np
import talib as ta
class Symbol:
def __init__(self,
broker: ... | StarcoderdataPython |
6595360 | import os
from redlib.api.system import is_linux, is_windows
from .bash_script_installer import BASHScriptInstaller
from .posh_script_installer import PoshScriptInstaller
from .shell_script_installer import ShellScriptInstallError
def get_shell_script_installer():
if is_linux():
shell = os.environ.get('SHELL', N... | StarcoderdataPython |
3567937 | <filename>markdown2pdf.py
# -*- coding: utf-8 -*-
import markdown
import ho.pisa as pisa
import StringIO
import os
import re
from Cheetah.Template import Template
from tempfile import NamedTemporaryFile
debug = False
def markdown2pdf(text, pdffile, cssfile='xhtml2pdf.css', src_dir='.',
fontfile='a... | StarcoderdataPython |
4904041 | <reponame>karaage0703/zero-deeplearning
import numpy as np
import matplotlib.pylab as plt
def sigmoid(x):
return 1/(1 + np.exp(-x))
x = np.arange(-5.0, 5.0 , 0.1)
y = sigmoid(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1)
plt.show()
| StarcoderdataPython |
11344672 | <reponame>Steap/SIXEcho<gh_stars>0
# coding=utf-8
from unittest import TestCase
from sixecho import Client
import sixecho
from time import sleep
class TestSixecho(TestCase):
def test_tokenize(self):
word = 'ในการเขียนโปรแกรมในภาษา Python โมดูล (Module) คือไฟล์ของโปรแกรมที่กำหนดตัวแปร ฟังก์ชัน หรือคลาสโดยแบ่... | StarcoderdataPython |
5165050 | <filename>tcvaemolgen/structures/mol_features.py
"""Molecule Feature Description
Unless otherwise noted, all work by:
******************************************************************
Title: PA-Graph-Transformer
Author: <NAME> (<EMAIL>)
Date: May 28, 2019
Code version: 4274301
Availability: https://github.com/benatorc... | StarcoderdataPython |
1808909 | from polyphony import testbench
from polyphony import pipelined
def nested06(x):
s = x
for i in pipelined(range(4)):
t = i
for j in range(4):
t += 1
for k in range(4):
s += 2
for l in range(4):
s += 3
s += t
... | StarcoderdataPython |
304478 | <reponame>quanshengwu/PyChemia
"""
Routines to read and write POSCAR file
"""
import os
import numpy as _np
import pychemia
def read_poscar(path='POSCAR'):
"""
Load a POSCAR file and return a pychemia structure object
:param path: (str) Filename of the POSCAR to read
:return:
"""
if os.path... | StarcoderdataPython |
3455021 | from rest_framework import status
from rest_framework.reverse import reverse
from tests.test_service_catalog.base_test_request import BaseTestRequest
from tests.utils import check_data_in_dict
class TestApiTowerServerPut(BaseTestRequest):
def setUp(self):
super(TestApiTowerServerPut, self).setUp()
... | StarcoderdataPython |
9767614 | #!/usr/bin/env python
from setuptools import setup, find_packages
import re
# get version from init file
with open('ginjinn/__init__.py', 'r') as f:
VERSION=re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]",
f.read(),
re.M
).group(1)
DESCRIPTION='Object detection pipeline ... | StarcoderdataPython |
141451 | <reponame>kubikvid/weather-this-day<filename>backend/main.py
# Copyright (c) 2019. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
# Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
# Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
# Proin dapibus... | StarcoderdataPython |
3390588 | <reponame>leakec/tfc<gh_stars>10-100
# This script solves Problem #6 of Chapter 1's exercises in the TFC book
####################################################################################################
# Create a constrained expression which begins at (-1,-1) and ends at (1,1).
# The constrained expression sho... | StarcoderdataPython |
1835243 | <reponame>Cent-Luc/University_Portal<filename>students/migrations/0002_auto_20191126_0241.py
# Generated by Django 2.2.7 on 2019-11-26 02:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('students', '0001_initial'),
]
operations = [
mi... | StarcoderdataPython |
65548 | from oso import Oso
from .auth import register_models
class SQLAlchemyOso(Oso):
"""The central object to manage application policy state, e.g.
the policy data, and verify requests when using Oso with SQLAlchemy.
Supports SQLAlchemy-specific functionality, including data filtering.
Accepts a SQLAlch... | StarcoderdataPython |
1653231 | <filename>api/tests/test_views.py<gh_stars>10-100
import pytest
from django.core.cache import cache
from django.shortcuts import reverse
from rest_framework.test import APIClient
from core.recipe import recipe_sites
client = APIClient()
@pytest.mark.django_db
def test_no_url_error():
response = client.post(reve... | StarcoderdataPython |
58036 | <reponame>RonaldKiprotich/Neighborhood
# Generated by Django 3.1.3 on 2020-12-02 09:55
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... | StarcoderdataPython |
1768050 | from __future__ import absolute_import
# getting all links example crawling jamescampbell.us
# author: <NAME>
# Date Created: 2015 05 22
# Date Updated: 2 July 2019
import argparse
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.item import Item, Fie... | StarcoderdataPython |
9661713 | import os
import pytest
from sqlalchemy import event
from sqlalchemy.orm import Session
from zeus import config
from zeus.storage.mock import FileStorageCache
@pytest.fixture(scope="session")
def session_config(request):
return {"db_name": "test_zeus"}
@pytest.fixture(scope="session")
def app(request, session... | StarcoderdataPython |
3368707 | <filename>Exfiltration/exfil.py
from Cryptodome.Cipher import AES, PKCS1_OAEP
from Cryptodome.PublicKey import RSA
from Cryptodome.Random import get_random_bytes
from io import BytesIO
import argparse
import base64
import ftplib
import getpass
import os
import random
import requests
import smtplib
import socket
impor... | StarcoderdataPython |
5120380 | import datetime
from dateutil import parser
from sklearn.feature_extraction.text import TfidfVectorizer
from tap_news_utils.mongodb_client import MongoDBClient
from tap_news_utils.cloudAMQP_client import CloudAMQPClient
from tap_news_utils.news_classifier_client import NewsClassifierClient
from config import DEDUPE_N... | StarcoderdataPython |
1849799 | import sys
import os
import re
import argparse
from sox import file_info
import json
import Levenshtein
import subprocess
import time
import signal
# poor-man's norm
def norm(txtin):
# remove things in parentheses
txtout = re.sub(r'\([^\)]+\)','',txtin)
# remove tags
txtout = re.sub(r'FILLEDPAUSE\_','', txt... | StarcoderdataPython |
6546459 | # -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
# Importations of the main packages and functions:
import numpy as np
import matplotlib.pyplot as plt
from functions import final_function, alpha_abrupt
# %%
# Representation of the variation of the interaction strength through time.
x = np.linspace(0, 59.9, 100)
N ... | StarcoderdataPython |
5057334 | <filename>ibeatles/step2/gui_handler.py
try:
import PyQt4
import PyQt4.QtCore as QtCore
import PyQt4.QtGui as QtGui
except:
import PyQt5
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import numpy as np
import pyqtgraph as pg
from pyqtgraph.dockarea import *
from ibeatles.utilities.... | StarcoderdataPython |
3482021 | <reponame>arjenroodselaar/skidl
from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
references = SchLib(tool=SKIDL).add_parts(*[
Part(name='CJ432',dest=TEMPLATE,tool=SKIDL,keywords='diode device shunt regulator',description='Shunt Regulator, SOT-23',ref_prefix='D',num_units=1,fpli... | StarcoderdataPython |
1663629 | <filename>python/test_servo_angles.py
"""
Demo moving the end link back and forth sinusoidally
"""
import time
import numpy as np
import ui
from robot import Robot
# Uncomment the following for simulation
#from robot import SimulatedRobot as Robot
with Robot.connect() as r, ui.basic(r) as gui:
while gui.open:
... | StarcoderdataPython |
8057506 | #
# This file is part of the GROMACS molecular simulation package.
#
# Copyright (c) 2019, by the GROMACS development team, led by
# <NAME>, <NAME>, <NAME>, and <NAME>,
# and including many others, as listed in the AUTHORS file in the
# top-level source directory and at http://www.gromacs.org.
#
# GROMACS is free softw... | StarcoderdataPython |
5192514 | # The great circle distance is the distance between
# two points on the surface of a sphere. Let (x1, y1) and (x2, y2) be the geographical
# latitude and longitude of two points. The great circle distance between the two
# points can be computed using the following formula:
# d = radius * arccos(sin(x 1 ) * sin(x 2 ) +... | StarcoderdataPython |
1655361 | <reponame>kswann-mck/udacity_drl_p3
"""
This script is the agent implementation of a Deep Deterministic Policy Gradient agent on the Unity Reacher environment. The base model, agent
and training function were taken from the solution here:
https://github.com/udacity/deep-reinforcement-learning/tree/master/ddpg-pendulum.... | StarcoderdataPython |
8138286 | <reponame>tophermckee/python_lca_data
import sys
sys.path.append("..")
from util.utilities import *
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%B-%d-%Y %H:%M:%S',
filename=f"../logs/{Path(__file__).stem}.log",
filemode='w'
)
de... | StarcoderdataPython |
1996227 | <reponame>ytyaru0/GitHub.Uploader.Pi3.Https.201802220700
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import os.path
import setting.Setting
# 抽象クラス
class DbInitializer(metaclass=ABCMeta):
def __init__(self):
self.__path_dir_root = os.path.abspath(os.path.dirname(os... | StarcoderdataPython |
3394786 | <filename>tests/load_context.py
def load_context():
"""
Add the src dir to sys.path so we can
import code in the test folder as expected
"""
import sys, os
current_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_path + '/../src')
| StarcoderdataPython |
9727268 | <gh_stars>0
from .collect_env import collect_env
from .logger import get_root_logger
from .statistictext import StatisticTextLoggerHook
from .print_log import print_defect_metrics, print_defect_loss
from .trainer_hooks import CheckRunstateHook, TrainerLogHook, TrainerCheckpointHook
__all__ = ['get_root_logger', 'colle... | StarcoderdataPython |
4887720 | import os
from sx.utils import get_package_root
from sx.stubs.settings import Settings
class Environment(object):
def __init__(self, location, constants={}):
self.__location = location
self.__constants = constants
self.__data = {}
def __add(self, key, value, prefix):
if prefix is not None:
key = '{}{}'.... | StarcoderdataPython |
1807312 | <reponame>kesavanvt/spark<gh_stars>1000+
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Vers... | StarcoderdataPython |
3490334 | from graphql.type import (
GraphQLField,
GraphQLFloat,
GraphQLInt,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLOutputType,
GraphQLSchema,
GraphQLString,
GraphQLUnionType,
)
from graphql.utilities import is_equal_type, is_type_sub_type_of
def... | StarcoderdataPython |
9766757 | import pandas as pd
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', required=True, nargs='+', type=str, dest="input")
parser.add_argument('-o', '--output', required=True, type=str, dest=... | StarcoderdataPython |
3221545 | from django.db.models import signals
from django.dispatch import receiver
from sales.models import ReceiptLine
# @receiver(signals.pre_delete,sender=ReceiptLine)
# def delete_status(sender,instance,*args,**kwargs):
# print ('deleting invoice status')
# inv=instance.invoice
# if inv.balance-instance.amount ... | StarcoderdataPython |
3541555 | <filename>Lib/site-packages/pyqt_units/MeasurementDatabase.py
#Created on 12 Aug 2014
#@author: neil.butcher
import os
from shutil import copyfile
root_filename = os.path.join(os.path.dirname(__file__) , 'measurements' ,'measurements_root.db')
filename = os.path.join(os.path.dirname(__file__) , 'measurements' , 'm... | StarcoderdataPython |
6489214 | from flask import jsonify
from flask_restful import Resource, request
from ..util.user import User
from ..util.dbutil import get_user,get_sensors,set_sensors,set_user
import json
class Profile(Resource):
def get(self):
#前端使用params传值
username = request.args.get("username")
print(str(username... | StarcoderdataPython |
6447620 | # SPDX-FileCopyrightText: Copyright (c) 2022 <NAME> for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`circuitpython_typing`
================================================================================
Types needed for type annotation that are not in `typing`
* Author(s): <NAME>, <NAME>, <NAME>
"""
_... | StarcoderdataPython |
1693630 | <reponame>frankmakesthecode/core
"""The Bravia TV component."""
import asyncio
from datetime import timedelta
import logging
from bravia_tv import BraviaRC
from bravia_tv.braviarc import NoIPControl
from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN
from homeassistant.components.remote im... | StarcoderdataPython |
6475687 | import LevelBuilder
from sprites import *
"""
### Creating builder ###
level: lb = LevelBuilder.LevelBuilder("level_34.plist")
### Adding sprites ###
Hero: lb.addObject(Hero.HeroSprite(x=20,y=10))
Rotor: lb.addObject(Rotor.RotorSprite(x=180,y=110,speed=5,torque=10000))
Bucket: lb.addObject(EnemyBucket... | StarcoderdataPython |
3375434 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | StarcoderdataPython |
6663805 | def check_command_succeeded(reply):
"""
Return true if command succeeded, print reason and return false if command
rejected
param reply: BinaryReply
return: boolean
"""
from zaber.serial import BinarySerial, BinaryDevice, BinaryCommand, BinaryReply
import time
if reply.co... | StarcoderdataPython |
4806084 | <reponame>faderani/mosse-object-tracking
from mosse import mosse
import argparse
parse = argparse.ArgumentParser()
parse.add_argument('--lr', type=float, default=0.125, help='the learning rate')
parse.add_argument('--sigma', type=float, default=100, help='the sigma')
parse.add_argument('--num_pretrain', type=int, defa... | StarcoderdataPython |
6540116 | <gh_stars>10-100
"""
Monkeypatches ``Project`` model to keep the size to 255 characters up from 63 since RTD 2.8.1.
RTD changed the name / slug length to 63 chars to fit DNS restrictions as they use the project
slug as third level domain (don't ask me why the restricted the name to the same length).
As we only use in... | StarcoderdataPython |
3454348 | from .grad_cam import GradCAM, GradCAMPlusPlus, XGradCAM
from .utils import overlay
| StarcoderdataPython |
1950883 | <filename>plums/plot/engine/utils.py
import PIL.ImageFont
import numpy as np
from plums.commons import Path
def get_text_color(background_color):
"""Select the appropriate text color (black or white) based on the luminance of the background color.
Arguments:
background_color (tuple): The record colo... | StarcoderdataPython |
3204220 |
def test_povgen():
import difflib
import urllib
import subprocess
import os
proteus_path = os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
povgen_path = os.path.join(proteus_path,'scripts','povgen.py')
urll... | StarcoderdataPython |
8033216 | <reponame>MohammedAljahdali/shrinkbench<gh_stars>100-1000
import pathlib
from torch.utils.data import Dataset
from torchvision.datasets import ImageFolder
# Data is here : http://places2.csail.mit.edu/download.html
# We assume directory structure from
# Small images (256 * 256) with easy directory structure
class... | StarcoderdataPython |
3427470 | """WizardKit: Tool Functions"""
# vim: sts=2 sw=2 ts=2
from datetime import datetime, timedelta
import logging
import pathlib
import platform
import requests
from wk.cfg.main import ARCHIVE_PASSWORD
from wk.cfg.sources import DOWNLOAD_FREQUENCY, SOURCES
from wk.exe import popen_program, run_program
from wk.std impor... | StarcoderdataPython |
1801221 | import re
import json
from typing import Tuple
MISSING_EMPTY_STR = re.compile(r'''
\s*
(
null
| false
| \-? 0 (\.0+)? ([eE] [\-\+]? [0-9]+)?
| \{ \s* \}
| \[ \s* \]
)
\s*
''', re.VERBOSE)
def test_regex_is_falsey(s: str) -> Tuple[bool, bool]:
"""
post: _[0] != _[1]
raises: json.JSONDecodeError... | StarcoderdataPython |
11260743 | <gh_stars>1-10
# run functions for merge
import os
import pytest
from merge_data import load_data, merge_data
from arrest_analysis import model_arrest, load_alldata, select_variables, save_output
@pytest.fixture
def alldata():
datadir = 'data'
demogdata, taskdata = load_data(datadir)
alldata = merge_data(d... | StarcoderdataPython |
9729019 | <gh_stars>10-100
import sys
sys.path.append('rchol/')
import numpy as np
from scipy.sparse import identity
from numpy.linalg import norm
from rchol import *
from util import *
# Initial problem: 3D-Poisson
n = 20
A = laplace_3d(n) # see ./rchol/util.py
# random RHS
N = A.shape[0]
b = np.random.rand(N)
print("Initia... | StarcoderdataPython |
1940300 | #!/usr/bin/ python
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 2 18:33:10 2016
Modified from https://stackoverflow.com/questions/38076682/how-to-add-colors-to-each-individual-face-of-a-cylinder-using-matplotlib
to add "end caps" and to undo fancy coloring.
@author: astrokeat
"""
import numpy as np
from matplotli... | StarcoderdataPython |
5028792 | #!/usr/bin/env python
import rospy
import numpy as np
import math
from math import pi
from geometry_msgs.msg import Twist, Point, Pose
from sensor_msgs.msg import LaserScan
from sensor_msgs.msg import Range
from std_msgs.msg import *
from nav_msgs.msg import Odometry
from std_srvs.srv import Empty
from tf.transformati... | StarcoderdataPython |
9705749 | <gh_stars>1-10
import pytest
from pathlib import Path
@pytest.fixture(scope="function")
def parser_check():
data = {"프룬_word" : "프룬",
"프룬_sentence": "프룬이 먹고 싶어",
"의창지_word" : "의창지",
"의창지_sentence" : "의창지를 먹고 싶어",
"금요일_word" : "금요일에 만나요",
"금요일_sentence" :... | StarcoderdataPython |
1884273 | # -*- coding: utf-8 -*-
"""
@author: <NAME>
@email: <EMAIL>
@time: 8/18/21 11:02 AM
"""
import time
import transforms3d as t3d
import copy
from helpers import *
from dataset import Reader
VOXEL_SIZE = 5
VOXEL_SIZE_FINE = 3
VISUALIZE = True
def main():
global_registrations = [get_teaser_solver]
global_regi... | StarcoderdataPython |
6472742 | <reponame>weleen/MGH.pytorch
# encoding: utf-8
"""
@author: liaoxingyu
@contact: <EMAIL>
"""
from torch.utils.data import Dataset
from fastreid.utils.misc import read_image
class CommDataset(Dataset):
"""compatible with un/semi-supervised learning"""
def __init__(self, datasets, transform=None, relabel=Tr... | StarcoderdataPython |
8118801 | #!/usr/bin/env python3
# The email checker script.
import os
import yaml
import logging
import email
#import bell_slap
from random import randint
from time import sleep
from imapclient import IMAPClient
# Store where we currently are in the filesystem.
__location__ = os.path.realpath(
os.path.join(os.getcwd(), o... | StarcoderdataPython |
8159099 | """
Piąty etap. Po wyodrebnieniu dobrze czasowo detekcji angażujemy do oceny detekcji modele ML (CNN, STD,baseline)
Finalnie oceniamy szanse % na to czy dany obraz jest sygnałem
"""
import os
from ML_function import preprocessData,CNN_classifier,STD_classifier,preprocesDataSTD,preprocesDataBL,BL_classifier,BaseTrigger
... | StarcoderdataPython |
207590 | import csv
import os
import glob
import argparse
import numpy as np
def merge_csv_files(src_dir, dst_dir):
'''
Takes a list of csv files (full file path) and merges them into a
single output.
'''
# Create a list of all the md files in the given directory
csv_list = glob.glob(os.path.join(src_d... | StarcoderdataPython |
9647549 | import subprocess
import os
class DiskInfo(object):
def __init__(self, devname):
self.name = devname
self.wwn = None
self.path = None
self.model = ''
self.size = 0
self.driver = None
self.mdcontainer = ''
devnode = '/dev/{0}'.format(devname)
q... | StarcoderdataPython |
6706616 | <reponame>disktnk/chainer-compiler<filename>elichika/tests/node/ndarray/Ceil.py
# coding: utf-8
import chainer
import numpy as np
import testtools
class A(chainer.Chain):
def __init__(self):
super(A, self).__init__()
def forward(self, x):
y1 = np.ceil(x)
return y1
# ===============... | StarcoderdataPython |
5166910 | <filename>tests/test_visualisation.py<gh_stars>0
"""The script to test visualisation"""
import cryptools.visualisation as vs
import pytest
def test_candle_1():
with pytest.raises(TypeError):
vs.candle([[0, 1, 1, 1]])
def test_candle_2():
with pytest.raises(TypeError):
vs.candle([0, 1, 1, 1]... | StarcoderdataPython |
75718 | <reponame>ihmeuw/cascade-at
import numpy as np
from scipy import stats
from cascade_at.dismod.constants import DensityEnum
from cascade_at.core.log import get_loggers
LOG = get_loggers(__name__)
def meas_bounds_to_stdev(df):
"""
Given data that includes a measurement upper bound and measurement lower
bo... | StarcoderdataPython |
1914739 | #! /usr/bin/env python3
import json
from flask import Flask, jsonify
from flask_restful import Resource, Api, reqparse, abort
from db import TopicList, Topic
from playhouse.shortcuts import model_to_dict
import logging
logger = logging.getLogger("peewee")
logger.addHandler(logging.StreamHandler())
logger.setLevel(lo... | StarcoderdataPython |
8058642 | from typing import *
from .. import tensor as T
from ..layers import is_jit_layer
from ..tensor import Tensor, Module, split, concat
from .core import *
__all__ = [
'SplitFlow', 'SplitFlow1d', 'SplitFlow2d', 'SplitFlow3d',
]
class SplitFlow(Flow):
"""
A flow which splits input `x` into halves, apply dif... | StarcoderdataPython |
11366393 | <reponame>hopper-maker/openxc-python<filename>openxc/sinks/notifier.py
"""A data sink implementation for the core listener notification service of
:class:`openxc.vehicle.Vehicle`.
"""
from threading import Thread
from collections import defaultdict
import logging
from openxc.measurements import Measurement, Unrecogniz... | StarcoderdataPython |
9789276 | # Generated by Django 2.0.1 on 2019-01-13 18:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app01', '0030_customerjavascript'),
]
operations = [
migrations.DeleteModel(
name='CustomerJavaScript',
),
]
... | StarcoderdataPython |
3397560 | <filename>2017.DigitalImageProcessing/FaceRecognition/crawler/crawler/spiders/imagespider.py
# -*- coding: utf-8 -*-
import os
import time
import scrapy
import twisted
from selenium import webdriver
from crawler.items import ImageItem
class BaiduImageSpider(scrapy.Spider):
name = "BaiduImageSpider"
allowed_d... | StarcoderdataPython |
25182 | <filename>helper.py
import requests
import pandas as pd
import tweepy #for twitter
import os
from bs4 import BeautifulSoup
import praw #for reddit
import requests
import requests.auth
def getTweets(search_terms=['counterfeit','amazonHelp']):
consumer_key = '6CM1Yqk0Qz6KUXsDQUS8xmahS'
consumer_secret = '<KEY>'
acc... | StarcoderdataPython |
1835929 | from utils import (number_to_digits,
digits_to_number,
is_palindrome,
capacity)
MAX_ITERATIONS_COUNT = 50
def lychrel(number: int) -> bool:
for _ in range(MAX_ITERATIONS_COUNT):
number += digits_to_number(reversed(list(number_to_digits(number))))
... | StarcoderdataPython |
4828173 | bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = f"My first bicycle was a {bicycles[0].title()}"
print (message)
| StarcoderdataPython |
3206168 | <reponame>aprilnovak/openmc<gh_stars>0
from openmc.examples import slab_mg
from tests.testing_harness import PyAPITestHarness
def test_mg_survival_biasing():
model = slab_mg()
model.settings.survival_biasing = True
harness = PyAPITestHarness('statepoint.10.h5', model)
harness.main()
| StarcoderdataPython |
8186244 | <reponame>Sebaestschjin/advent-of-code<filename>year2020/day22/reader.py
from pathlib import Path
def read(filename='in'):
file_path = Path(__file__).parent / filename
with file_path.open('r') as file:
return read_lines(file.readlines())
def read_lines(lines):
first, second = ''.join(lines).spli... | StarcoderdataPython |
12852477 | <filename>src/backend/hacker_gif_poll/graphql_api/tenor/queries/hacker_gif.py<gh_stars>0
# Base imports
from os import environ
# Third party imports
from graphene import Field, ObjectType, String, Int
# Project imports
from graphql_api.tenor.schemas.hacker_gif.result import Result
from graphql_api.tenor.resolvers.ha... | StarcoderdataPython |
1817616 | """
Prepare manifest files for speech recognition with OTS FRF_ASR001 dataset.
Author:
* <NAME>, 2022-01-24
"""
import os
import json
import csv
import logging
import random
from pathlib import Path
from speechbrain.utils.data_utils import get_all_files
from speechbrain.dataio.dataio import read_audio
logger = log... | StarcoderdataPython |
11232424 | import json
import logging
from ulauncher.api.client.Extension import Extension
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.event import KeywordQueryEvent
from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem
from ulauncher.api.shared.action.RenderResul... | StarcoderdataPython |
104696 | # -*- coding: utf-8 -*-
from torch.optim.optimizer import Optimizer
class Optimizers:
def __init__(self, *op: Optimizer):
self.optimizers = op
def zero_grad(self):
for op in self.optimizers:
op.zero_grad()
def step(self):
for op in self.optimizers:
... | StarcoderdataPython |
3572867 | <reponame>neuroticnerd/django-demo-app
from django.contrib import admin
from . import models
class ActionAdmin(admin.ModelAdmin):
list_display = (
'title', 'created_by', 'created_at', 'modified_by', 'modified_at'
)
list_filter = ('created_by', 'created_at')
fields = ('title', 'description')
... | StarcoderdataPython |
8182207 | """
Nextflow error handling and exit code tests.
The test suite runs ``nextflow run prep_riboviz.nf``.
"""
import os.path
import shutil
import tempfile
import yaml
import pytest
import riboviz.test
from riboviz import hisat2
from riboviz import params
from riboviz.test.nextflow import run_nextflow
@pytest.fixture(sc... | StarcoderdataPython |
4815374 | <gh_stars>0
from django.conf.urls import url
from app import views
from rest_framework import routers
from django.conf.urls import url, include
from app import views
router = routers.DefaultRouter()
router.register(r'users', views.UsersView)
# router.register(r'groups', views.GroupsView)
# router.register(r'permissi... | StarcoderdataPython |
12801436 | <filename>hs_formation/middleware/logger.py
from ..formation import (
_REQ_HTTP,
_RES_HTTP,
_CONTEXT,
_REQ_DURATION,
)
from toolz.curried import valfilter
def request_logger(logger):
no_nones = valfilter(lambda x: x)
def request_logger_middleware(ctx, next):
req = ctx[_REQ_HTTP]
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.