id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
17263 | from distutils.version import LooseVersion
import requests
import os
import shutil
import threading
import webbrowser
from zipfile import ZipFile
from pathlib import Path
import traceback
import tempfile
# import concurrent.futures
from flask import Flask, url_for, make_response
from flask.json import dumps
from flask_... | StarcoderdataPython |
1783134 | """
Multilayer VAE + Pixel CNN
<NAME>
"""
import os, sys
if 'ISHAAN_NN_LIB' in os.environ:
sys.path.append(os.environ['ISHAAN_NN_LIB'])
else:
sys.path.append(os.getcwd())
N_GPUS = 1
try: # This only matters on Ishaan's computer
import experiment_tools
experiment_tools.wait_for_gpu(tf=True, n_gpus=N_G... | StarcoderdataPython |
134842 | import torch
import torch.nn as nn
from torchvision import models
from torch.nn.functional import sigmoid as sigmoid
from torch.autograd import Variable
#This file contains all of the Residual-U-Net variants, including Gaussian Dropout
#Gaussian Dropout is taken from https://github.com/j-min/Dropouts/blob/maste... | StarcoderdataPython |
3315041 | <reponame>Helyosis/web_prik
from enigma_machine.rotor import Rotor
class Machine:
def __init__(self, size=256, nbRotors=3, config=None):
if config is not None:
self.set_config(config)
return
self.size = size
self.nbRotors = nbRotors
self.child = Rotor(self... | StarcoderdataPython |
1621516 | <reponame>DX-MON/OpenPICle
# SPDX-License-Identifier: BSD-3-Clause
from amaranth import Elaboratable, Module, Signal, unsigned
from .types import Opcodes, ArithOpcode, LogicOpcode, BitOpcode
from .busses import *
__all__ = ["PIC16"]
class PIC16(Elaboratable):
def __init__(self):
self.iBus = InstructionBus()
self... | StarcoderdataPython |
1626894 | <filename>setup.py<gh_stars>0
from setuptools import setup
setup(name='shelvery', version='0.9.1', author='Base2Services R&D',
author_email='<EMAIL>',
url='http://github.com/base2Services/shelvery-aws-backups',
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language... | StarcoderdataPython |
139632 | <filename>jack_sparrow.py
cu,cd = map(int,raw_input().split())
a = map(int,raw_input().split(' '))
eff = cu-cd
count = 0
total = 0
for i in a:
t=i/eff
if((i-cu)%eff==0):
t=(i-cu)/eff
if((i%eff)>0):
t+=1
total+=t
print total
| StarcoderdataPython |
4818519 | <filename>our_scripts/dev_tests/run_all_local.py
# run_all_local.py: way to test on local system with restructured helper functions
# target system: local
# authors: <NAME>
# email: <EMAIL>
# created: June 14, 2021
import os
import prescient_helpers.run_helpers as rh
path_template = "./scenario_"
solar_path = "./sola... | StarcoderdataPython |
1760557 | <filename>doorbot/core/service.py
# -*- coding: utf-8 -*-
class Service(object):
def __init__(self, services=None, database=None, account=None):
self.services = services
self.database = database
self.account = account
| StarcoderdataPython |
1749162 | <reponame>RuiShu/deep-generative-models
import os
import sys
import argparse
from codebase import args as codebase_args
from pprint import pprint
import tensorflow as tf
# Settings
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--src', type=str, defau... | StarcoderdataPython |
3324475 | import logging
import discord.ext.tasks
logger = logging.getLogger(__package__)
def safe_coro(func):
async def wrapped(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
logger.error(e)
return wrapped
def safe_loop(*args, **kwargs):
... | StarcoderdataPython |
25994 | from tletools import TLE
import matplotlib.pyplot as plt
import numpy as np
import math
from math import *
import sys
import datetime as dt
import tleToKeplerianElements as ttke
# uses TLE to return the current distance of the satellite to the focus
def distanceToCentralBody(tle, curr_trueA):
lan, argp, inc, ecc,... | StarcoderdataPython |
92601 | from django.conf.urls import url, include
urlpatterns = [
url(r'^inventory/', include('tsadmapi.inventory.urls', namespace='inventory')),
url(r'^slave/', include('tsadmapi.slave.urls', namespace='slave')),
]
| StarcoderdataPython |
3345460 | # coding: utf8
from zeit.cms.i18n import MessageFactory as _
import PIL.Image
import six
import zc.form.field
import zc.form.interfaces
import zc.sourcefactory.contextual
import zeit.cms.content.contentsource
import zeit.cms.content.interfaces
import zeit.cms.content.sources
import zeit.cms.interfaces
import zeit.cms.r... | StarcoderdataPython |
36801 | """
USFM References Tools
"""
import re
__version__ = '1.1.0'
ANY_REF = re.compile(r'^[1-9A-Z]{3}\.([0-9]{1,3}(_[0-9]+)?(\.[0-9]{1,3})?|INTRO\d+)$')
CHAPTER = re.compile(r'^[1-6A-Z]{3}\.[0-9]{1,3}(_[0-9]+)?$')
CHAPTER_OR_INTRO = re.compile(r'^[1-9A-Z]{3}\.([0-9]{1,3}(_[0-9]+)?|INTRO\d+)$')
SINGLE_CHAPTER_OR_VERSE = r... | StarcoderdataPython |
3241892 | <reponame>jaydeetay/pxt
a = 1
for i in range(10):
a += 1
continue
print(a)
b = 1
for j in range(10):
b += 1
break
print(b) | StarcoderdataPython |
111001 | <reponame>barajus/netsim-tools<gh_stars>0
#
# netlab config command
#
# Deploy custom configuration template to network devices
#
import typing
import argparse
import os
import glob
import subprocess
from pathlib import Path
from .. import common
#
# CLI parser for 'netlab install' command
#
def install_parse(args: t... | StarcoderdataPython |
4831533 | # Least Common Multiple
# Author: jerrybelmonte
# Input: Two integers a and b seperated by a space.
# Output: Least common multiple of a and b.
# Uses the Euclidean algorithm of the greatest common divisor
# to compute the least common multiple.
def lcm(a, b):
# greatest common divisor helper function
def gcd... | StarcoderdataPython |
1793672 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: jsuter
Project: STIMPY - Sentence Transformative Infernece Mapping for Python
<NAME>, 2019
---
EVALUATE_dev_samples.py
- Load development samples
- Evaluate samples
- Print performance results
"""
# Import statements
import copy
import sys
import time
impor... | StarcoderdataPython |
3394369 | <filename>day_1.py
from __future__ import division, print_function
import os
from my_utils.tests import test_function
def solve_capcha(capcha_str):
"""Function which calculates the solution to part 1
Arguments
---------
capcha_str : str, a string of numbers
Returns
-------
total ... | StarcoderdataPython |
4808624 | <reponame>terra-money/terra.py
import asyncio
import base64
from pathlib import Path
from terra_sdk.client.lcd import LCDClient
from terra_sdk.core import Coins
from terra_sdk.core.bank import MsgSend
from terra_sdk.util.contract import get_code_id
def main():
terra = LCDClient(
url="https://pisco-lcd.te... | StarcoderdataPython |
3246623 | string= input("Enter a string: ")
string=string.upper()
freq: dict={}
st: set={*string}
for c in string:
if c in freq:
freq[c]+=1
else:
freq[c]=1
for c in st:
print(f'{c} {freq[c]}')
| StarcoderdataPython |
1602945 | from torchdistill.common.main_util import load_ckpt
from torchdistill.models.official import get_object_detection_model
from torchdistill.models.registry import get_model
from torchdistill.models.registry import register_model_class, register_model_func
from sc2bench.models.detection.base import check_if_updatable_det... | StarcoderdataPython |
3390761 | import copy
import logging
import numpy as np
import time
import torch
from typing import Union, Callable, Any
from .worker import Worker, ByzantineWorker
from .server import TorchServer
from .utils import vectorize_model, unstack_vectorized_model
class _SimulatorBase(object):
"""Simulate distributed programs wi... | StarcoderdataPython |
1695569 | def pick_best(name, api, data):
if api.name == "hummingbirdv1":
done = False
maxb = 3
best = data[0]
if not(best['title'].lower() == name.lower() or best['title'] == name.lower()):
for e in data:
if not e['alternate_title']:
e['alternat... | StarcoderdataPython |
173588 | import numpy as np
import cv2
import os
import sys
sys.path.insert(0, os.getcwd())
import os.path as osp
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Circle
from tools.auto_anno_movie import AnnoationBase, AnnoationSub, get_landmark_annotation, get_face_annotation, LANDMARKS
from easydict i... | StarcoderdataPython |
130459 | # Lint as: python2, python3
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | StarcoderdataPython |
142081 | <filename>Tugas ETS/program/soal1.py
from multiprocessing import Process, Pipe
from random import randint
import time
import random
DataSensor = [[500,400,300,200,100],[500,400,300,200,100],[600,500,400,300,200],[500,400,300,200,100],[40,30,20,10,5],[60,40,30,20,10],[500,400,300,200,100],["Merah","Kuning","Hijau"]]
L ... | StarcoderdataPython |
1687456 | <filename>TOOL/mod_datacleaning/data_cleaning.py
import pandas as pd
import numpy as np
def fix_missing(file, fix_option):
# file.rename(columns=lambda x: x.strip(), inplace=True)
if fix_option == 'skip':
print (fix_option)
file.dropna(axis=0,inplace=True)
elif fix_option == 'mean':
... | StarcoderdataPython |
1775792 | import os
import json
from framework._utils import AnalyserHook
class GitHubAnalyseCompatibility(AnalyserHook):
''' analyse compatibility over language versions. '''
@staticmethod
def analyse(data):
import time
from framework.github._helper import iter_repos
ymd = lambda epoch: t... | StarcoderdataPython |
3252364 | import tensorflow as tf
def generate_guided_attention(
mel_lengths, input_lengths, reduction_factor=1, g=0.2
):
mel_len = mel_lengths // reduction_factor
char_len = input_lengths
xv, yv = tf.meshgrid(tf.range(char_len), tf.range(mel_len), indexing='ij')
f32_matrix = tf.cast(yv / mel_len - xv / cha... | StarcoderdataPython |
1773337 | import wx
class Form1( wx.Panel ):
def __init__( self, parent, id ):
wx.Panel.__init__( self, parent, id )
self.quote = wx.StaticText( self, -1, "Your quote is",
wx.Point( 20, 30 ) )
self.logger = wx.TextCtrl( self, 5, "", wx.Point(300, 20),
... | StarcoderdataPython |
181478 | from dataspot.network.node_networker import NodeNetworker
class NodeListNetworker(NodeNetworker):
def __init__(self):
self.__nodes = None
def set_node(self, graph):
nodes = list()
for i in graph.nodes:
nodes.append(i.strip())
nodes = list(set(nodes))
self... | StarcoderdataPython |
1635296 | import voluptuous as vol
from pi4home.automation import ACTION_REGISTRY
from pi4home.components import text_sensor
from pi4home.components.text_sensor import TextSensorPublishAction
import pi4home.config_validation as cv
from pi4home.const import CONF_ID, CONF_LAMBDA, CONF_NAME, CONF_STATE, CONF_UPDATE_INTERVAL
from p... | StarcoderdataPython |
1620262 | <filename>Week 1/id_385/LeetCode_21_385.py
# -*- encoding: utf-8 -*-
"""
package.module
~~~~~~~~~~~~~~
LeetCode ็ฌฌ21้ข: ๅๅนถไธคไธชๆๅบ้พ่กจ
:copyright: (c) 2019-10-17 by liuyajing.
:license: OPS, see LICENSE_FILE for more details.
"""
# ๅฐไธคไธชๆๅบ้พ่กจๅๅนถไธบไธไธชๆฐ็ๆๅบ้พ่กจๅนถ่ฟๅใๆฐ้พ่กจๆฏ้่ฟๆผๆฅ็ปๅฎ็ไธคไธช้พ่กจ็ๆๆ่็น็ปๆ็ใ
#
# ็คบไพ๏ผ
#
# ่พๅ
ฅ๏ผ1->2->4, 1... | StarcoderdataPython |
3213225 | import json
import os
import sys
from os import environ
from pathlib import Path
from typing import Dict, Iterable
import boto3
import pytest
from _pytest.monkeypatch import MonkeyPatch
from moto import mock_ec2
from mypy_boto3_ec2.client import EC2Client
from pytest_cases import fixture
from .manage_ec2 import creat... | StarcoderdataPython |
93191 | <reponame>riteshreddyr/bhajanpresentationmaker
__author__ = 'RiteshReddy'
from controllers.BhajanManager import *
from controllers.PresentationManager import *
def error_handler(e):
return render_template("generic_error.html")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=80, debug=True)
| StarcoderdataPython |
3355425 | <filename>sift_pyx12/error_999.py
######################################################################
# Copyright
# <NAME> <<EMAIL>>
# All rights reserved.
#
# This software is licensed as described in the file LICENSE.txt, which
# you should have received as part of this distribution.
#
#########################... | StarcoderdataPython |
186149 | <gh_stars>0
import random
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
def limit_content_type_choices():
problem_subclasses = Problem.__subclasses__()
content_types = ContentType.objects.get_for_models(*problem_subc... | StarcoderdataPython |
4804916 | import numpy as np
def binary_classification_metrics(prediction, ground_truth):
'''
Computes metrics for binary classification
Arguments:
prediction, np array of bool (num_samples) - model predictions
ground_truth, np array of bool (num_samples) - true labels
Returns:
precision, recall, f... | StarcoderdataPython |
143248 | import colorsys
import json
import socket
import logging
from enum import Enum
from .decorator import decorator
from .flow import Flow
MUSIC_PORT = 37657
_LOGGER = logging.getLogger(__name__)
@decorator
def _command(f, *args, **kw):
"""
A decorator that wraps a function and enables effects.
"""
self... | StarcoderdataPython |
4838772 | #!/usr/bin/env python
import time
import wx
import wx.lib.scrolledpanel as sp
#----------------------------------------------------------------------
header = """\
This demo shows the various ways that wx.Timers can be used in your code. Just
select one of the buttons in the left column to start a timer in the ... | StarcoderdataPython |
3316263 | power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | StarcoderdataPython |
3241908 | <reponame>jkwening/bus_wmata
import requests
class WmataApi:
"""WMATA API class."""
bus_routes_url = 'https://api.wmata.com/Bus.svc/json/jRoutes'
bus_pos_url = 'https://api.wmata.com/Bus.svc/json/jBusPositions'
bus_path_url = 'https://api.wmata.com/Bus.svc/json/jRouteDetails'
bus_schedule_url = 'h... | StarcoderdataPython |
3359796 | <gh_stars>0
#
# @lc app=leetcode id=146 lang=python3
#
# [146] LRU Cache
#
# https://leetcode.com/problems/lru-cache/description/
#
# algorithms
# Medium (35.48%)
# Likes: 7833
# Dislikes: 320
# Total Accepted: 707.2K
# Total Submissions: 2M
# Testcase Example: '["LRUCache","put","put","get","put","get","put","g... | StarcoderdataPython |
3260140 | """Build the desired software environment"""
import sys
import os
import os.path
from azureml.core import Environment
from azureml.core.conda_dependencies import CondaDependencies
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '../..')))
from scripts.authentication.service_principal import ws... | StarcoderdataPython |
3387408 | <gh_stars>0
def kmp(text, pattern):
pattern = list(pattern)
#Partial match" table
t = kmp_partial_match_table(pattern)
def kmp_shift_table(pattern):
shifts = [None] * (len(pattern) + 1)
shift = 1
for pos in range(len(pattern) + 1):
while shift < pos and pattern[pos - 1] != pattern[po... | StarcoderdataPython |
1781922 | <filename>voyager/resources/exoplanet/exoplanetalias.py
from typing import Union
_ATTRS = {
'name',
'2mass',
'cd',
'cpd',
'gj',
'hd',
'hip',
'hr',
'iras',
'sao',
'tyc',
'wise',
}
class ExoplanetAlias(object):
__slots__ = [
'_data',
]
_cache = {}
... | StarcoderdataPython |
3272303 | import argparse
import logging
import time
import cv2
import numpy as np
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
logger = logging.getLogger('TfPoseEstimator-WebCam')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
form... | StarcoderdataPython |
3290567 | import os
from typing import List, Tuple, Union
import nibabel as nib
import numpy as np
from deepreg.dataset.loader.interface import FileLoader
from deepreg.dataset.util import get_sorted_file_paths_in_dir_with_suffix
from deepreg.registry import REGISTRY
DATA_FILE_SUFFIX = ["nii.gz", "nii"]
def load_nifti_file(f... | StarcoderdataPython |
3256495 | import dlxapi
from dlxapi.constants import base_url
from dlxapi.access_token import get_access_token
from dlxapi import Configuration
def dlx_api():
configuration = Configuration()
configuration.access_token = get_access_token()
configuration.host = base_url
api_instance = dlxapi.PortfoliosApi(dlxapi... | StarcoderdataPython |
1787505 | """
For the new versions of linear search: if there are duplicate values, which do they find?
"""
"""
Answer: The second one in the list
""" | StarcoderdataPython |
1724079 | from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import db, Comment
from flask_login import login_required
from app.forms import NewCommentForm
from app.utils import validation_errors_to_error_messages
comment_routes = Blueprint('comments', __name__)
@comment_rout... | StarcoderdataPython |
4816179 | import os
import numpy as np
import h5py
import fnmatch
from .lh5_utils import *
from .scalar import Scalar
from .struct import Struct
from .table import Table
from .array import Array
from .fixedsizearray import FixedSizeArray
from .arrayofequalsizedarrays import ArrayOfEqualSizedArrays
from .vectorofvectors import V... | StarcoderdataPython |
157428 | <reponame>vkvam/fpipe<filename>fpipe/meta/__init__.py
from .blocksize import BlockSize # noqa:F401
from .bucket import Bucket # noqa:F401
from .checksum import MD5 # noqa:F401
from .host import Host # noqa:F401
from .mime import Mime # noqa:F401
from .modified import Modified # noqa:F401
from .password import Pas... | StarcoderdataPython |
46899 | from interfaces.interface import Publisher, stock_list
from utils.notifier import NotificationUtils
from service.loader import LoadStock
from utils import cache_util, common_constants
class WatchTower(Publisher):
state = 0
observser_list = list()
def __init__(self, stock_val):
self.stock_val = st... | StarcoderdataPython |
1610496 | <gh_stars>10-100
import traceback
from typing import Callable
def pretty_loop(worker_id: int, loop_fn: Callable[[], None]) -> None:
try:
loop_fn()
except KeyboardInterrupt:
print(f"Worker {worker_id} ended by KeyboardInterruption.")
except Exception as e:
traceback.print_exc()
... | StarcoderdataPython |
103479 | class World(object):
pass
class Field(object):
pass
from typing import Union
import numpy as np
import random
import math
from tocenv.env import TOCEnv
import tocenv.components.item as items
import tocenv.components.agent as agent
import tocenv.components.skill as skills
import tocenv.components.block as... | StarcoderdataPython |
3280240 | import sqlite3
def conectar():
SQL = "CREATE TABLE IF NOT EXISTS planeta " \
"(id INTEGER PRIMARY KEY AUTOINCREMENT ," \
"nome TEXT NOT NULL," \
"clima TEXT NOT NULL," \
"terreno TEXT NOT NULL," \
"aparicoes NUMERIC)"
try:
conexao = sqlite3.connect('... | StarcoderdataPython |
3309828 | <reponame>lendlsmith/wagtail-cookiecutter-foundation
# Create your views here.
from django.shortcuts import render
def error_500(request):
return render(request, '500.html')
def check():
pass
| StarcoderdataPython |
63993 | # ===================== ่ทฏๅพ้
็ฝฎ ============================
folder_path = "folder/path/"
tex_raw_path = folder_path + "raw.tex"
tex_out_path = folder_path + "out.tex"
# ================== ๅฎ้ชๆฅๅ่กจๅคดไฟกๆฏ ============================
stid = "173530xx"
major = "็ฉ็ๅญฆ"
grade = "17็บง"
name = "ๆจไธ"
# ================== tex ๅฏผ่จๅบ่ฎพ็ฝฎ =... | StarcoderdataPython |
53200 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from xcube_hub.models.base_model_ import Model
from xcube_hub import util
class CubegenConfigCodeConfigFileSet(Model):
"""NOTE: This class is auto generated by Op... | StarcoderdataPython |
113938 | <reponame>leetcode-notes/daily-algorithms-practice<filename>leetcode/1094_car_pooling.py
from collections import defaultdict
class Solution:
def carPooling(self, trips, capacity: int) -> bool:
points = set()
pickup, dropoff = defaultdict(int), defaultdict(int)
for p, s, e in trips:
... | StarcoderdataPython |
3211818 | """
Pretty table generation.
"""
from itertools import cycle
from string import capwords
from fabric.colors import red, green, blue, magenta, white, yellow
class ColorRow(dict):
"""
Ordered collection of column values.
"""
def __init__(self, table, **kwargs):
super(ColorRow, self).__init__(sel... | StarcoderdataPython |
190199 | # occiput
# <NAME>
# Harvard University, Martinos Center for Biomedical Imaging
# Apr. 2014, Boston, MA
from __future__ import absolute_import
from .ilang_models import SSD_ilang
from .registration import Registration_Two_Images, Registration_Longitudinal, Registration_N_Images
| StarcoderdataPython |
3336817 | <reponame>wilson1745/twstock<filename>twstock/cli/stock.py
# -*- coding: utf-8 -*-
import twstock
def run(argv):
for sid in argv:
s = twstock.Stock(sid)
print('-------------- %s ---------------- ' % sid)
print('high : {:>5} {:>5} {:>5} {:>5} {:>5}'.format(*s.high[-5:]))
print('low... | StarcoderdataPython |
39547 | from .util import md5sum_from_filepath
from .datasetingestionhistorysolr import DatasetIngestionHistorySolr
from .datasetingestionhistoryfile import DatasetIngestionHistoryFile
| StarcoderdataPython |
3287793 | <gh_stars>1000+
import abc
import copy
import datetime
import json
from dataclasses import dataclass, field
from io import BytesIO
from typing import Any, Dict, Optional, Tuple, Union
import ijson
import requests
import requests.exceptions
from anchore_engine.clients.grype_wrapper import GrypeWrapperSingleton
from an... | StarcoderdataPython |
3286399 | # coding=utf-8
"""
# @Time : 8/22/19 11:46 AM
# @Author : F0rGeEk@root
# @Email : <EMAIL>
# @File : crack.py
# @Software: PyCharm
***********************************************************
โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโ
โโโ... | StarcoderdataPython |
176041 | <filename>libextract/api.py<gh_stars>100-1000
from functools import partial
from ._compat import BytesIO
from .core import parse_html, pipeline, select, measure, rank, finalise
def extract(document, encoding='utf-8', count=None):
if isinstance(document, bytes):
document = BytesIO(document)
crank ... | StarcoderdataPython |
1645156 | from train.utils import get_encoder
def test_get_encoder():
"""
Just test that the functions returns something and doesn't crash
"""
assert get_encoder()
| StarcoderdataPython |
81793 | <reponame>Akhadafi/WEB-Framework
from django.views.generic.base import TemplateView
# inheritence dari TemplateResponseMixin
# ContexMixin
# View
class IndexView(TemplateView):
pass
class ParameterView(TemplateView):
template_name = "parameter.html"
def get_context_data(self, *args, **kwargs):
... | StarcoderdataPython |
1666868 | # you can write to stdout for debugging purposes, e.g.
# print "this is a debug message"
def solution(A, B, M, X, Y):
# write your code in Python 2.7
"""
floors = [0 to M ]
elevator:
max capacity of X people
weight limit of Y lbs
N people gathered in floor[0] standing in a queue()
... | StarcoderdataPython |
155575 | <gh_stars>0
import re
import datetime
import requests
import lxml.html
from .kvucol import Collection
from .kvuconst import BASEURL
class Book:
def __init__(
self,
session:requests.Session,
url:str) -> None:
if url.startswith('http'):
# absolute link
... | StarcoderdataPython |
4818744 | # Generated by Django 2.2.5 on 2019-12-02 16:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('openbook_posts', '0066_auto_20191129_1630'),
('openbook_posts', '0066_trendingpost'),
]
operations = [
]
| StarcoderdataPython |
3326671 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = '<NAME>'
#
# Done by <NAME>
#
# Licensed under the Apache License, Version 2.0, that can be viewed at:
# http://www.apache.org/licenses/LICENSE-2.0
| StarcoderdataPython |
194639 | # ใคใณในใใผใซใใ discord.py ใ่ชญใฟ่พผใ
import discord
# ่ชๅใฎBotใฎใขใฏใปในใใผใฏใณใซ็ฝฎใๆใใฆใใ ใใ
TOKEN
# ๆฅ็ถใซๅฟ
่ฆใชใชใใธใงใฏใใ็ๆ
client = discord.Client()
# ่ตทๅๆใซๅไฝใใๅฆ็
@client.event
async def on_ready():
# ่ตทๅใใใใฟใผใใใซใซใญใฐใคใณ้็ฅใ่กจ็คบใใใ
print('ใญใฐใคใณใใพใใ')
# ใกใใปใผใธๅไฟกๆใซๅไฝใใๅฆ็
@client.event
async def on_message(message):
# ใกใใปใผใธ้ไฟก่
ใBotใ ใฃใๅ ดๅใฏ็ก่ฆใใ
... | StarcoderdataPython |
1711888 | <gh_stars>0
from satsim import Service
class Logger(Service):
INFORMATION = "INFORMATION"
EVENT = "EVENT"
WARNING = "WARNING"
ERROR = "ERROR"
DEBUG = "DEBUG"
def __init__(self, simulator):
self._simulator = simulator
def log(self, sender, message, kind=None):
print("{} |... | StarcoderdataPython |
1775060 | def doDivision
a=10
b=5
c=a/b
print(c)
doDivision()#division of two numbers
| StarcoderdataPython |
154700 | from flask import (
blueprints,
current_app,
flash,
jsonify,
redirect,
request,
url_for
)
from sqlalchemy.exc import IntegrityError
from patchserver.exc import (
InvalidPatchDefinitionError,
InvalidWebhook,
PatchArchiveRestoreFailure,
SoftwareTitleNotFound,
Unauthorized
... | StarcoderdataPython |
1752300 | <filename>pdp/utility/filetemplate.py
from string import Template
class FileTemplate:
def __init__(self, template_string):
self.template_string = template_string
def replace(self, template_key, value):
template = Template(self.template_string)
replacement = {template_key: value}
... | StarcoderdataPython |
3369065 | <reponame>HoneyTheYellowBear123/bababot
"""
Bababooey bot
"""
import logging
import os
import random
from itertools import product
import discord
from dotenv import load_dotenv
# Create a custom logger that logs to file and to stream
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create separ... | StarcoderdataPython |
3257655 | import screenpoint
import cv2
# Load input images.
screen = cv2.imread('example/screen.png', 0)
view = cv2.imread('example/view.jpg', 0)
# Project centroid.
x, y, img_debug = screenpoint.project(view, screen, True)
# Write debug image.
cv2.imwrite('example/match_debug.png', img_debug) | StarcoderdataPython |
1668845 | <reponame>utlive/VIDMAP
import skimage.io
import skvideo.io
import os
import h5py
from sklearn.externals import joblib
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import f1_score
import scipy.misc
import scipy.signal
import numpy as np
from s... | StarcoderdataPython |
136593 | # -*- coding: utf-8 -*-
"""
This module contains tests for the ACSpy package.
"""
from __future__ import division, print_function
from acspy import acsc, control
import time
def test_write_real():
print("Testing acsc.writeReal")
hc = acsc.openCommDirect()
varname = "SLLIMIT1"
val = 3.14
acsc.write... | StarcoderdataPython |
3326806 | <filename>tmdb/parsers/episodes.py
"""Parsers of episode objects."""
from datetime import datetime, date
from tmdb.parsers.mixins import ImageParserMixin, ImageSize
from ..datatypes import Episode
from .base import Parser
from typing import Optional
class EpisodeParser(ImageParserMixin, Parser[Episode]):
"""Pars... | StarcoderdataPython |
14908 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import boto3
import botocore
import os
import logging
import time
import json
import datetime
log = logging.getLogger()
log.setLevel('INFO')
bucket = os.environ['BUCKET']
region = os.environ['AWS_REGION']
solu... | StarcoderdataPython |
84139 | <gh_stars>100-1000
from rest_framework import serializers
from baserow.contrib.database.views.models import GridViewFieldOptions
class GridViewFieldOptionsSerializer(serializers.ModelSerializer):
class Meta:
model = GridViewFieldOptions
fields = ("width", "hidden", "order")
class GridViewFilter... | StarcoderdataPython |
163424 | <filename>FORTH.py
from metaL import *
class thisModule(cppModule):
def __init__(self, V=None):
super().__init__(V)
mod = thisModule()
mod.TITLE = 'primitive CLI/script engine'
mod.ABOUT = """
"""
vm = cFile('vm')
mod.d.src // vm
compiler = cppFile('compiler')
mod.d.src // compiler
lex = lexFile('le... | StarcoderdataPython |
3377800 | <filename>tpotMalwareArchiver.py
import yaml
from os import path
from libTpotMalwareArchiver import malwareArchiver
if __name__ == '__main__':
# Read yaml config file
YAMLFILE = "./tpotMalwareArchiverSettings.yaml" # System Configuration and Variables
if (path.exists(YAMLFILE)):
# -- Loads Confi... | StarcoderdataPython |
1642753 | N = int(input())
mod = 10 ** 9 + 7
A = [int(x) for x in input().split()]
ans = 0
for i in range(60):
cnt = 0
for a in A:
cnt += a >> i & 1
ans += cnt * (N - cnt) * (1 << i)
print(ans % mod)
| StarcoderdataPython |
1607704 | import praw
import discord
import random
from discord.ext import commands
from discord.ext.commands import BucketType
import json
# getting API key and acc details from json file
secret = json.load(open('../Bot/configs/secret.json'))
r = praw.Reddit(client_id=secret['reddit']['client_id'],
client_se... | StarcoderdataPython |
106744 | <reponame>jielyugt/calibration
#Code base from https://github.com/aravindsiv/dan_qa
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
import pickle as pkl
import numpy as np
class PreProcessor:
def __init__(self,INPUT_FILE,WE... | StarcoderdataPython |
1612966 | <reponame>saxix/django-mb
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import pytest
from pika import PlainCredentials
from pika.exceptions import ProbableAuthenticationError
from demoproject.models import DemoModel1
from django_mb.config import NOTIFY_CREATE, NOTIFY_DELETE, NOTIFY_... | StarcoderdataPython |
103612 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | StarcoderdataPython |
3220345 | <reponame>himanshu-setia/myKeystone
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | StarcoderdataPython |
1732583 | # Copyright (C) 2017 <NAME>
#
# See 'py_scrabble.pyw' for more info on copyright
import threading, re, os, pickle, queue, sys
from tkinter import *
from tkinter.messagebox import askyesno, showwarning, showinfo
from tkinter.simpledialog import askstring
from tkinter.filedialog import asksaveasfilename
import lib.la... | StarcoderdataPython |
3341731 | <reponame>CESNET/exafs<gh_stars>1-10
import pytest
import flowapp.validators
def test_port_string_len_raises(field):
port = flowapp.validators.PortString()
field.data = "1;2;3;4;5;6;7;8"
with pytest.raises(flowapp.validators.ValidationError):
port(None, field)
@pytest.mark.parametrize("a... | StarcoderdataPython |
162846 | <reponame>hixio-mh/taskcat
# flake8: noqa
import json
if __name__ == "__main__":
schema = json.load(open("./taskcat/cfg/config_schema.json", "r"))
def resolve_ref(props):
if "$ref" in props:
ref = props["$ref"].split("/")[-1]
del props["$ref"]
props.update(schema["... | StarcoderdataPython |
3242593 | <reponame>ribal-aladeeb/reinforcement-learning-2048<gh_stars>1-10
from typing import Callable
import numpy as np
import torch
from board import Board2048
from collections import deque
import copy
def board_as_4d_tensor(board: Board2048, device: str) -> torch.tensor:
return board.log_scale().state_as_4d_tensor().to... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.