id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3399174 | <reponame>jmstevens/aesopbot<filename>src/features/genius/song_structure.py
"""From dlarsen5's PyRap song structure script.
https://github.com/dlarsen5/PyRap/blob/master/Song_Structure.py
"""
import itertools
import os
import pickle
import re
import json
# from nltk.corpus import stopwords
artists = ['<NAME>','Drake'... | StarcoderdataPython |
1795958 | <filename>cnn_training/vgg2_2_tfrecords.py
#!/usr/bin/env python
# coding: utf-8
"""
Trains some face recognition baselines using ARC based models
Usage:
vgg2_2_tfrecords.py <vgg-path> <output-path>
vgg2_2_tfrecords.py -h | --help
Options:
-h --help Show this screen.
"""
from docopt impor... | StarcoderdataPython |
3219847 | <reponame>Phill240/chrome-remote-interface-py
"""This is an auto-generated file. Modify at your own risk"""
from typing import Awaitable, Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from cripy import ConnectionType, SessionType
__all__ = ["Fetch"]
class Fetch:
"""
A domai... | StarcoderdataPython |
1784558 | <filename>code/python/lib/mayavi_utils.py
#
# For licensing see accompanying LICENSE.txt file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
from pylab import *
import mayavi.mlab
def points3d_color_by_scalar(positions, scalars, sizes=None, mode="sphere", scale_factor=1.0, colormap="jet", opacity=1.0):
... | StarcoderdataPython |
1716305 | from job_board.users.forms import BaseSignupForm
from django import forms
from django.utils.translation import gettext_lazy as _
class EmployerSignupForm(BaseSignupForm):
employer_name = forms.CharField(required=True, label=_("Employer Name"), widget=forms.TextInput(
attrs={"placeholder": _("Employer ... | StarcoderdataPython |
3288958 | #!/usr/bin/python
# coding: utf-8
"""Visual keyboard for Pygame engine. Aims to be easy to use as highly customizable as well.
``VKeyboard`` only require a pygame surface to be displayed on and a text consumer function, as in the following example :
```python
from pygame_vkeyboard import *
# Initializes your window... | StarcoderdataPython |
1655748 | <reponame>z687wang/Hikari
from .serializers import MyTokenObtainPairSerializer
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.views import TokenObtainPairView
from django.contrib.auth.models import User
from .serializers import RegisterSerializer
from rest_framework import generics
from r... | StarcoderdataPython |
198664 | from typing import Iterable
class InfiniteIterator:
"""Infinitely repeat the iterable."""
def __init__(self, iterable: Iterable):
self._iterable = iterable
self.iterator = iter(self._iterable)
def __iter__(self):
return self
def __next__(self):
for _ in range(2):
... | StarcoderdataPython |
1602251 | import unittest
# On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
# Once you pay the cost, you can either climb one or two steps.
# You need to find minimum cost to reach the top of the floor,
# and you can either start from the step with index 0, or the step with index 1.
inpu... | StarcoderdataPython |
3275138 | <reponame>diefans/python-arangodb
"""Some classes to easy work with arangodb."""
from . import meta, util, query
import logging
LOG = logging.getLogger(__name__)
class QueryMixin(object):
# pylint: disable=E0213
@util.classproperty
def alias(cls):
"""A query alias for this collection."""
... | StarcoderdataPython |
1736516 | from .hover.processor import HoverNetPostProcessor
from .cellpose.processor import CellposePostProcessor
from .drfns.processor import DRFNSPostProcessor
from .dcan.processor import DCANPostProcessor
from .dran.processor import DRANPostProcessor
from .basic.processor import BasicPostProcessor
from .thresholding import ... | StarcoderdataPython |
185625 | <filename>paddleseg3d/datasets/preprocess_utils/geometry.py
# Copyright (c) 2022 PaddlePaddle 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.a... | StarcoderdataPython |
3386694 | <filename>tcx_set_timings.py
#!/usr/bin/env python3
""" Add new timestamps to trackpoints in a TCX file, with an equal amount between each trackpoint """
import argparse
from lxml import etree
import datetime
import math
parser = argparse.ArgumentParser()
parser.add_argument('input')
parser.add_argument('output')
pa... | StarcoderdataPython |
191193 | import os, time, json
import numpy as np
from scellseg import models, io, metrics
from scellseg.contrast_learning.dataset import DatasetPairEval
from scellseg.dataset import DatasetShot, DatasetQuery
from torch.utils.data import DataLoader
from scellseg.utils import set_manual_seed, make_folder, process_different_mode... | StarcoderdataPython |
1707034 | <reponame>tedunderwood/fiction
# select_random_corpus.py
#
# This module imports metadata about volumes
# in a given set of genre(s), as well as a
# given random set, and then helps the user
# select more volumes to balance the sets.
#
# It is loosely based on
#
# /Users/tunder/Dropbox/GenreProject/python/reception/sel... | StarcoderdataPython |
1665808 | <reponame>drednout/locust_on_meetup
from locust import HttpLocust, TaskSet, task
class HttpPingTasks(TaskSet):
@task
def ping(self):
self.client.get("/")
class HttpPingLocust(HttpLocust):
task_set = HttpPingTasks
min_wait = 100
max_wait = 500
| StarcoderdataPython |
80298 | import pytest
from ..encryptor import Encryptor, Decryptor
from secrets import token_bytes, randbelow
@pytest.fixture
def private_key_bytes():
private_key_bytes = Decryptor.generate_private_key(
password=None
)
yield private_key_bytes
@pytest.fixture
def decryptor(private_key_bytes):
decryptor = Decrypt... | StarcoderdataPython |
3248269 | """
Parametric spline interpolator
Useful when you need to interpolate a curve of values, like points along a flux surface or a chord
"""
import warnings
import numpy as np
from scipy.interpolate import splprep, splev
class ParametricSpline:
"""
A wrapper class around slprep and splev from scipy.interpolate
... | StarcoderdataPython |
96632 | <gh_stars>1-10
import os
bot_token = '<KEY>'
bot_user_name = 'xxx_bot'
URL = "https://cf45064e05ed.ngrok.io"
| StarcoderdataPython |
3377452 | from nxos_ebay import NexusOSNetConfDriver
| StarcoderdataPython |
1751184 | <gh_stars>1-10
from sklearn.metrics import recall_score
from metrics.metric import Metric
class Recall(Metric):
name = 'recall'
def apply(self,y_true, y_pred):
recall_labels = recall_score(y_true, y_pred, average=None, zero_division=1)
macro = recall_score(y_true, y_pred, average='macro',... | StarcoderdataPython |
1738125 | <gh_stars>10-100
"""
Example demonstrating how to add DID with the role of Trust Anchor to ledger.
Uses seed to obtain Steward's DID which already exists on the ledger.
Then it generates new DID/Verkey pair for Trust Anchor.
Using Steward's DID, NYM transaction request is built to add Trust Anchor's DID and Verkey
on t... | StarcoderdataPython |
1728909 | <reponame>marsggbo/hyperbox
from .constants import NONE, SKIP_CONNECT, CONV_1X1, CONV_3X3, AVG_POOL_3X3, PRIMITIVES
from .model import Nb201TrialStats, Nb201IntermediateStats, Nb201TrialConfig
from .query import query_nb201_trial_stats
| StarcoderdataPython |
3236693 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | StarcoderdataPython |
123505 | #!/usr/bin/env python
# This is largely adopted from https://github.com/enode-engineering/tesla-oauth2
import base64
import hashlib
import os
import sys
import re
import random
import time
import argparse
import json
from urllib.parse import parse_qs
import requests
MAX_ATTEMPTS = 7
CLIENT_ID = "81527cff06843c8634fd... | StarcoderdataPython |
3300283 | import maya.cmds as cmds
import maya.mel as mel
import os
import ART_rigUtils as utils
reload(utils)
#----------------------------------------------------------------------------------------
# Currently this script is written to work with multiple twists, but if you have more than one the last one is the... | StarcoderdataPython |
1600893 | from sys import stdout, stderr
from core.error import print_error, Errors
from core.parser import TokenType
class Interpreter:
def __init__(
self,
tree,
cell_array_size: int,
filepath: str = None,
silent: bool = False,
print_to_string: bool = False,
exit_on_... | StarcoderdataPython |
118675 | # from fit import FitCLI, fit, fit_sat
# from . import fit # works weirdly
from .fit import FitCLI, fit, fit_sat
__all__ = ["FitCLI", "fit", "fit_sat"]
| StarcoderdataPython |
3283701 | <gh_stars>10-100
# Copyright 2021 The MLX Contributors
#
# SPDX-License-Identifier: Apache-2.0
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server.m... | StarcoderdataPython |
151055 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import subprocess
import time
import requests
import hcl
import distutils.spawn
from unittest import SkipTest
from tests.utils import get_config_file_path, load_config_file, create_client
logger = logging.getLogger(__name__)
class ServerManager(... | StarcoderdataPython |
1610119 | <gh_stars>1-10
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
from collections import defaultdict
import copy
from typing import Dict, List, Tuple
import networkx as nx
import warnings
import sympy
from dace.transformation import transformation as xf
from dace import (data, dtypes, nodes,... | StarcoderdataPython |
191833 | <reponame>vindula/collective.ckeditor<filename>collective/ckeditor/tests/__init__.py
# Other packages may find this useful
from collective.ckeditor.tests.base import CKEditorTestCase
| StarcoderdataPython |
1730352 | # -*- coding: utf-8 -*- äöü vim: ts=8 sts=4 sw=4 si et tw=79
"""\
Tools for "brains"
"""
# Python compatibility:
from __future__ import absolute_import
from six import string_types as six_string_types
from six.moves import map
__author__ = "<NAME> <<EMAIL>>"
VERSION = (0,
6, # aufgeräumt
)
__v... | StarcoderdataPython |
191290 | import os
import urllib.parse as up
from werkzeug.middleware.proxy_fix import ProxyFix
from flask import url_for, render_template
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from src import api, db, ma, create_app, Config, bp, bcrypt, jwt, admin, login_manager
# config = confi... | StarcoderdataPython |
3343269 | <filename>tests/test_sdk1.py
from client_sdk_python import Web3, HTTPProvider
from client_sdk_python.eth import PlatON
from hexbytes import HexBytes
# get blockNumber
w3 = Web3(HTTPProvider("http://localhost:6789"))
platon = PlatON(w3)
block_number = platon.blockNumber
print(block_number)
# get Balance
address = '0x4... | StarcoderdataPython |
1788140 | <gh_stars>0
import re
def increment_string(string):
num = re.findall('\d+', string)
plain_string = re.findall('\D+', string)
new_num = increment_and_diff(num)[0]
length_diff = increment_and_diff(num)[1]
new_num_string = str(new_num).rjust(length_diff + 1, '0')
if len(plain_string) > 0:
... | StarcoderdataPython |
3255966 | <reponame>jfuruness/lib_secure_monitoring_service<filename>lib_secure_monitoring_service/__main__.py
from lib_bgp_simulator import Simulator, BGPAS, Graph
from lib_rovpp import ROVPPV1SimpleAS
from lib_secure_monitoring_service.engine_inputs import V4SubprefixHijack
from lib_secure_monitoring_service.rov_sms import R... | StarcoderdataPython |
1798458 | <reponame>Asperger/PCRD-DiscordBot
from pickle import load, dump
from os.path import exists, dirname, join
from threading import Thread, RLock
from datetime import datetime
from utils.log import FileLogger
from utils.timer import get_settlement_time_object
from googleapiclient.discovery import build
from google_auth_oa... | StarcoderdataPython |
3307164 | # ex-072 - Números por Extenso
lista = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco',
'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze',
'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezesseis',
'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
while True:
while True:
num = int(input('D... | StarcoderdataPython |
1647770 | """
Faz a representação de um elemento na lista ligada.
Cada elemento (aqui chamado de nó) terá seu valor representado como inteiro e um apontamento para o próximo elemento da lista.
Keyword arguments:
value -- valor do elemento
"""
class Node:
def __init__(self, value):
self.value = value... | StarcoderdataPython |
101888 | <reponame>sn0b4ll/Incident-Playbook<gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software F... | StarcoderdataPython |
1747672 | <filename>rpiRobot/src/vision/domain/iCamera.py
from abc import ABC, abstractmethod
from vision.domain.image import Image
class ICamera(ABC):
@abstractmethod
def take_picture(self) -> Image:
pass
| StarcoderdataPython |
151501 | n=int(input("enter a number"))
m=int(input("enter a number"))
if n%m==0:
print(n,"is dividible by",m)
else:
print(n,"is not divisible by",m)
if n%2==0:
print(n,"is even")
else:
print(n,"is odd")
| StarcoderdataPython |
69031 | class HistoryStatement:
def __init__(self, hashPrev, hashUploaded, username, comment=""):
self.hashPrev = hashPrev
self.hashUploaded = hashUploaded
self.username = username
self.comment = comment
def to_bytes(self):
buf = bytearray()
buf.extend(self.hashPrev)
buf.extend(self.hashUploaded)
... | StarcoderdataPython |
1627764 | """
With these settings, tests run faster.
"""
import logging.config
import os
import re
from django.conf import settings
DEBUG = False
from django.utils.log import DEFAULT_LOGGING
from .base import *
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
# GENERAL
# -------------------------------------------------------------... | StarcoderdataPython |
1732649 | #Assignment 8.5
#file name = mbox-short.txt
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
line = line.rstrip()
if not line.startswith('From '): #To check if the line staty with 'From '
continue #Note that there is a sp... | StarcoderdataPython |
3207729 | <gh_stars>0
from multiprocessing import Queue, Lock, Process, current_process
import queue, time
'''
where we are adding tasks to the queue, then creating processes and starting them, then using join() to complete the processes. Finally we are printing the log from the second queue
'''
def doJob(task_to_complete... | StarcoderdataPython |
158576 | #!/usr/bin/env python
# Usage:
# python parse_taxonomy_for_clustered_subset.py X Y Z
# where X is the fasta file to read target labels from, Y is the taxonomy mapping file starting with a superset of labels from X, and Z is the output taxonomy mapping file.
from cogent.parse.fasta import MinimalFastaParser
from sys ... | StarcoderdataPython |
3218322 | from pyfluminus.api import name, modules, get_announcements, current_term
from pyfluminus.structs import Module
from pyfluminus.fluminus import get_links_for_module
from app import db
from app.models import User, User_Mods
from app.extra_api import get_class_grps
from datetime import datetime
def get_active_mods(auth... | StarcoderdataPython |
3338638 | <filename>esmvalcore/cmor/_fixes/obs4mips/airs_2_1.py
"""Fixes for obs4MIPs dataset AIRS-2-1."""
from iris.exceptions import CoordinateNotFoundError
from ..fix import Fix
class AllVars(Fix):
"""Common fixes to all vars."""
def fix_metadata(self, cubes):
"""
Fix metadata.
Change unit... | StarcoderdataPython |
48657 | <reponame>nickswalker/counterpoint-reinforcement-learning
from typing import List, Set
import numpy as np
from rl.action import Action
from rl.state import State
from rl.valuefunction import FeatureExtractor
class PerActionLinearVFA:
def __init__(self, num_features, actions: List[Action], initial_value=0.0):
... | StarcoderdataPython |
3359728 | <reponame>brian41005/Python-Messenger-Wrapper
import json
import logging
import os
import re
import sys
import time
import unittest
from messenger import login, logout, send
class TestSendMessage(unittest.TestCase):
def setUp(self):
with open('tests/test_config.json') as f:
user_data = json.l... | StarcoderdataPython |
139745 | import unittest
import os
import evacsim.node
import evacsim.edge
import evacsim.disaster
import evacsim.exporter
class TestExporter(unittest.TestCase):
"""Tests functionality in the exporter module. There isn't much to be tested here, so it simply tests
that a KML file with the proper name is created when ... | StarcoderdataPython |
3240866 | <filename>LeetCode/0004_Median_of_Two_Sorted_Array.py
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
i1 = 0
i2 = 0
num1 = 0
num2 = 0
len1 = len(nums1)
... | StarcoderdataPython |
1772233 | """
Pull an image from a website and save it as a PNG file.
"""
from seleniumbase import BaseCase
class ImageTest(BaseCase):
def test_pull_image_from_website(self):
self.open("https://xkcd.com/1117/")
selector = "#comic"
file_name = "comicmap.png"
folder = "images_exported"
... | StarcoderdataPython |
4800547 | # coding: utf-8
# pylint: disable=no-member, protected-access, unused-import, no-name-in-module
"""Random Number interface of mxnet."""
from __future__ import absolute_import
import ctypes
from .base import _LIB, check_call
from ._ndarray_internal import _sample_uniform as uniform
from ._ndarray_internal import _sampl... | StarcoderdataPython |
1724737 | <filename>migrations/versions/7044d2465076_.py
"""empty message
Revision ID: 7044d2465076
Revises:
Create Date: 2018-11-14 01:10:33.897024
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7044d<PASSWORD>'
down_revision = None
branch_labels = None
depends_on = ... | StarcoderdataPython |
1727610 | """
.. module:: guiclient
:platform: Windows
:synopsis: Instructor GUI tkinter frame
.. moduleauthor:: <NAME>, <NAME>, <NAME>
"""
# Standard Library imports
import tkinter as tk
from tkinter import ttk
from tkinter import Button
from tkinter import Entry
from tkinter import Frame
from tkinter import Label
fr... | StarcoderdataPython |
1711984 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preproce... | StarcoderdataPython |
1713379 | <reponame>fossabot/hoard<gh_stars>10-100
import os
from tempfile import TemporaryDirectory
from .hoard_tester import HoardTester
class MissingConfigDirTester(HoardTester):
def run_test(self):
self.reset()
old_config_path = self.config_file_path()
with TemporaryDirectory() as tmpdir:
... | StarcoderdataPython |
3201107 | from __future__ import print_function
import argparse
import os.path
import models.examples as ex
from config import cfg
from generic_op import *
from midap_simulator import *
from midap_software import Compiler, MidapModel
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_s... | StarcoderdataPython |
3331198 | from math import log10
class QueryDictionary:
"""
A class used to represent a dictionary of queries.
...
Attributes
----------
queries : {int : {str : int}}
A dictionary of queries, where the key is the number of the
query and the values are dictionaries containing the words
... | StarcoderdataPython |
1787073 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import torch
import numpy as np
from PIL import Image
import json
import argparse
import model_factory
from torch.autograd import Variable
def main():
image_path, checkpoint, top_k, category_names, gpu = get_input_args()
with open(category_names, 'r') as f:
... | StarcoderdataPython |
1667396 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : pengj
@ date : 2019/10/17 11:14
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : <EMAIL>
--------------------------------... | StarcoderdataPython |
3342844 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | StarcoderdataPython |
181472 | <reponame>dr4ke616/notifier<gh_stars>1-10
from jinja2 import Environment, PackageLoader
class Render(object):
template = 'email.tpl'
def __init__(self, template=None):
if template:
self.template = template
self.env = Environment(
loader=PackageLoader('notifier', 'tem... | StarcoderdataPython |
91536 | from gozokia.core.rules import RuleBase
class Bar(RuleBase):
def __init__(self):
self.set_reload(False)
def condition_raise(self, *args, **kwargs):
super(Bar, self).condition_raise(*args, **kwargs)
if self.sentence.lower() == 'foo':
return True
def condition_complete... | StarcoderdataPython |
1751706 | <reponame>namixoi/NamixDH
import socket
import struct
import time
import logging
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
LOGIN_TEMPLATE = b'\xa0\x00\x00\x60%b\x00\x00\x00%b%b%b%b\x04\x01\x00\x00\x00\x00\xa1\xaa%b&&%b\x00Random:%b\r\n\r\n'
GET_SERIAL = b'\xa4\x00\x00\x00\x00\x00\x00\x00\... | StarcoderdataPython |
3380271 | data_dir_test = data_dir+'test/'
N_test = len(os.listdir(data_dir_test+"/test"))
test_datagen = kpi.ImageDataGenerator(rescale=1. / 255)
test_generator = test_datagen.flow_from_directory(
data_dir_test,
#data_dir_sub+"/train/",
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode... | StarcoderdataPython |
27479 | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import UserProfile
class UserRegistrationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserRegistrationForm, self).__init__(*args, **kwargs)
... | StarcoderdataPython |
70980 | from functools import wraps
from copy import copy
from collections import OrderedDict
from ..commands import InterfaceObj
from ..core.objects.memory import StackObj, RegObj
def BeforeParse(f):
@wraps(f)
def wrapper(inst, *args, **kwargs):
# noinspection PyProtectedMember
if inst._parsed is Tr... | StarcoderdataPython |
3284669 | import torch.nn as nn
import torch as t
import torch.nn.functional as F
class CondConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size,
stride=1, padding=0, dilation=1, groups=1, bias=True,
num_experts=1):
super(CondConv2d, self).__init_... | StarcoderdataPython |
1631584 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import time
import datetime
from concurrent import futures
import parlai.chat_service.utils.logging as log... | StarcoderdataPython |
49086 |
#%%
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
import matplotlib as mpl
import random
import time
import copy
from matplotlib import animation, rc
from IPython.display import HTML
def _update_plot (i,fig,scat,qax) :
scat.set_offsets(P[i])
qax.set_offsets(P[i])
VVV=... | StarcoderdataPython |
91713 | import numpy as np
from . import stereonet_math
def fit_girdle(*args, **kwargs):
"""
Fits a plane to a scatter of points on a stereonet (a.k.a. a "girdle").
Input arguments will be interpreted as poles, lines, rakes, or "raw"
longitudes and latitudes based on the ``measurement`` keyword argument.
... | StarcoderdataPython |
3258679 | <filename>lib/checks/__init__.py
import abc
from os import walk
from os.path import join as path_join
from pkgutil import walk_packages
from inspect import getmembers, isclass
from subprocess import call
from grp import getgrgid
from lib.util import debug, log
class AbstractCheckBase(metaclass=abc.ABCMeta):
"""
... | StarcoderdataPython |
1692443 | <gh_stars>1-10
import re
from dataclasses import dataclass
from typing import List
@dataclass
class MonsterInfoReader:
name_lines: List[str]
detail_lines: List[str]
info_line: str = None
def __init__(self):
self.clear()
def clear(self):
self.name_lines = []
self.detail_li... | StarcoderdataPython |
3240722 | from setuptools import setup, find_packages
import pathlib
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / 'README.md').read_text(encoding='utf-8')
VERSION='1.0.0'
setup(
name="tinypistats",
version=VERSION,
author="<NAME>",
author_email="<EMAIL>",
d... | StarcoderdataPython |
90548 | <reponame>tkrsh/pomodoro-cli-python
"pomodoro cli for interactive pomodoro sessions"
import time # for sleep
import os
import sys
from tqdm import tqdm
time_cycle = int(sys.argv[1])
time_short_break = int(sys.argv[2])
time_long_break = int(sys.argv[3])
cycles = int(sys.argv[4])
total_cycles = int(sys.argv[5])
def d... | StarcoderdataPython |
3355942 | # Generated by Django 2.0.1 on 2018-03-08 20:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('card', '0023_card_in_pack'),
]
operations = [
migrations.CreateModel(
name='Deck',
fields=[
('id', m... | StarcoderdataPython |
100216 | from os.path import join
from numpy import sqrt, pi, linspace, array, zeros
from numpy.testing import assert_almost_equal
from multiprocessing import cpu_count
import pytest
from SciDataTool.Functions.Plot.plot_2D import plot_2D
from pyleecan.Classes.OPdq import OPdq
from pyleecan.Classes.Simu1 import Simu1
from p... | StarcoderdataPython |
1734232 | import pandas as pd
import math
import os.path
import time
from binance.client import Client
from datetime import timedelta, datetime
from dateutil import parser
# from tqdm import tqdm_notebook #(Optional, used for progress-bars)
binance_api_key = '<KEY>' # Enter your own API-key here
binance_api_secret = '<KEY>' ... | StarcoderdataPython |
187553 | <gh_stars>0
import day06 as day
INPUTFOLDER = day.get_path()
def test_part_1():
result = day.run_part_1(INPUTFOLDER+"/test1")
assert result == 11
def test_part_1_real():
result = day.run_part_1(INPUTFOLDER+"/input1")
assert result == 6551
def test_part_2():
result = day.run_part_2(INPUTFOLDER+... | StarcoderdataPython |
49153 | def ans(n):
global fib
for i in range(1,99):
if fib[i]==n: return n
if fib[i+1]>n: return ans(n-fib[i])
fib=[1]*100
for i in range(2,100):
fib[i]=fib[i-1]+fib[i-2]
n=int(input())
print(ans(n)) | StarcoderdataPython |
3296191 | # Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
from .ast_node import AST_Node
from .ast_values import AST_Ident
import dace
class AST_Assign(AST_Node):
def __init__(self, context, lhs, rhs, op):
# for a normal assignment op is "=", but there is also
# in place modific... | StarcoderdataPython |
1777268 | <reponame>kirim-Lee/nomadgram_mac<filename>nomadgram/images/urls.py
# from django.urls import path
from django.conf.urls import url
from . import views
app_name="images"
urlpatterns = [
#path("all/",view=views.ListAllImages.as_view(),name="all_images")
url(
regex=r"^all/$",
view=views.ListAllIm... | StarcoderdataPython |
1603653 | <gh_stars>1-10
from pandas import read_csv
import cv2
import glob
import os
import numpy as np
import logging
import coloredlogs
import tensorflow as tf
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG')
coloredlogs.install(level='DEBUG', logger=logger)
IM_EXTENSIONS = ['png', 'jpg', 'jpeg', 'bmp... | StarcoderdataPython |
129838 | #!/use/bin/env python3
#-*- coding:utf-8 -*-
# child.py
# A sample child process for receiving messages over a channel
import sys,os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import channel
ch = channel.Channel(sys.stdout, sys.stdin)
while True:
try:
item = ch.recv()
ch.send(("c... | StarcoderdataPython |
154070 | # httpServerLogParser.py
#
# Copyright (c) 2016, <NAME>
#
"""
Parser for HTTP server log output, of the form:
192.168.127.12 - - [20/Jan/2003:08:55:36 -0800]
"GET /path/to/page.html HTTP/1.0" 200 4649 "http://www.somedomain.com/020602/page.html"
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
127.0.0.1 - <EMAIL> ... | StarcoderdataPython |
1729794 | '''
@summary: Bootstrapper file to run gui_server, and UI associated with it.
Ensures all routing for pages, error routing, and user sessions are handled.
@author devopsec and mackhendricks
'''
from flask import Flask, render_template, request, jsonify, make_response, url_for, redirect, abort, Markup
import requests #... | StarcoderdataPython |
1635928 | mystery_string = "my cat your cat"
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Add some code below that will count and print how many
#times the character sequence "cat" appears in mystery_string.
#Fo... | StarcoderdataPython |
4823756 | def isabn(obj):
"""isabn(string or int) -> True|False
Validate an ABN (Australian Business Number).
http://www.ato.gov.au/businesses/content.asp?doc=/content/13187.htm
Accepts an int or a string of exactly 11 digits and no leading zeroes.
Digits may be optionally separated with spaces. Any other i... | StarcoderdataPython |
3224660 | from setuptools import setup
from os import sep
setup(name='hygnd',
version='0.1',
description='HYdrologic Gauge Network Datamanager',
url='',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['hygnd'],
entry_points = {
'console_scripts': [
... | StarcoderdataPython |
1767237 | <gh_stars>10-100
import torch
from huggingsound import SpeechRecognitionModel
device = "cuda" if torch.cuda.is_available() else "cpu"
batch_size = 1
model = SpeechRecognitionModel("jonatasgrosman/wav2vec2-large-xlsr-53-english", device=device)
references = [
{"path": "/path/to/sagan.mp3", "transcription": "extrao... | StarcoderdataPython |
1627854 | <filename>Calculadora-em-russo.py<gh_stars>0
lista_mult = [] #lista para tratamento do resultado
lista_div = [] #lista para tratamento do resultado
def dividindo_por_dois(n1):
while True:
lista_div.append(n1)
n1 = n1//2
if n1 == 1:
break
lista_div.append(1)
return lista_div
def multiplicando_po... | StarcoderdataPython |
3302414 | <reponame>urbas/py-air-control-exporter<filename>test/test_app.py
from unittest import mock
from py_air_control_exporter import app
@mock.patch("py_air_control_exporter.metrics.PyAirControlCollector")
def test_create_app(mock_collector):
"""
check that we can create an exporter with explicit host and protoco... | StarcoderdataPython |
4803110 | <filename>main.py
import sqlite3
import time
import random
conn = sqlite3.connect('main.db')
c = conn.cursor()
def table():
c.execute("CREATE TABLE IF NOT EXISTS username(username VARCHAR, password VARCHAR)")
table()
def login():
for i in range(3):
username = input("pls enter your username: ")
... | StarcoderdataPython |
118833 | from django.db import transaction
from django.db.models import Q
from analysis.models import TagNode, Analysis, Tag
from analysis.tasks.variant_tag_tasks import analysis_tag_created_task, analysis_tag_deleted_task
def _analysis_tag_nodes_set_dirty(analysis: Analysis, tag: Tag):
""" Needs to be sync so version is... | StarcoderdataPython |
1774719 | <reponame>Zelenyy/phd-code<gh_stars>0
from multiprocessing import Pool
import os
import pickle
from phd.thunderstorm.electric_field import generate_potential
def save_potential(filename):
res = generate_potential()
with open(filename ,'wb') as fout:
pickle.dump(res, fout)
return filename
def ma... | StarcoderdataPython |
1737014 | from .site import Site
import os
import socket
from ..minirunner import Node
class CCParallel(Site):
"""Object representing execution in the local environment, e.g. a laptop."""
def command(self, cmd, sec):
"""Generate a complete command line to be run with the specified execution variables.
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.