id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
5004601 | <reponame>carnot-shailesh/cr-sparse<gh_stars>10-100
# Copyright 2021 CR.Sparse Development Team
#
# 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
#
# https://www.apache.org/licenses/LICENSE... | StarcoderdataPython |
3477047 |
expected_output = {
'dir': {
'dir_name': 'disk0a:/usr',
'files': {
'start': {
'date': 'Thu Jan 15 15:29:26 2015',
'index': '9867',
'permission': '-rwx',
'size': '8909'
}
},
'total_bytes': '25627... | StarcoderdataPython |
1800404 | # -*- coding: utf-8 -*-
from mathics.builtin.base import Builtin, Predefined
from mathics.core.expression import Expression
from mathics.core.symbols import (
Symbol,
fully_qualified_symbol_name,
)
from mathics.core.atoms import (
String,
Integer,
)
from mathics.builtin.assignments.internals import g... | StarcoderdataPython |
6509539 | <reponame>BeryJu/passbook
"""totp authenticator signals"""
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django_otp.plugins.otp_static.models import StaticDevice
from authentik.events.models import Event
@receiver(pre_delete, sender=StaticDevice)
# pylint: disable=unused-a... | StarcoderdataPython |
316100 | # -*- coding: utf-8 -*-
from .pyface import PyFace
from .config import config
__all__ = (PyFace, config)
# Version of the pyface package
__version__ = "0.0.1"
__author__ = "<NAME>"
| StarcoderdataPython |
5053964 | import unittest
from eosfactory.eosf import *
verbosity([Verbosity.INFO, Verbosity.OUT, Verbosity.TRACE, Verbosity.DEBUG])
class Test(unittest.TestCase):
def run(self, result=None):
super().run(result)
@classmethod
def setUpClass(cls):
SCENARIO('''
Create a contract from templat... | StarcoderdataPython |
5021761 | <filename>setup.py
import re
from pathlib import Path
from setuptools import setup # type: ignore
path = Path(__file__).parent
txt = (path / 'aiofreqlimit' / '__init__.py').read_text('utf-8')
version = re.findall(r"^__version__ = '([^']+)'\r?$", txt, re.M)[0]
readme = (path / 'README.rst').read_text('utf-8')
setup(... | StarcoderdataPython |
3582523 | # 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
# 本文链接:https://blog.csdn.net/u013314786/article/details/78226902
import sqlite3
class EasySqlite:
"""
sqlite数据库操作工具类
database: 数据库文件地址,例如:db/mydb.db
"""
_connection = None
def __init__(self, database):
# 连接数据库
self._conne... | StarcoderdataPython |
1988087 | <gh_stars>0
# This script shows how to use the client in anonymous mode
# against jira.atlassian.com.
# from flaskblog import my_jira_client
from jira import JIRA
import re
# By default, the client will connect to a Jira instance started from the Atlassian Plugin SDK
# (see https://developer.atlassian.com/displ... | StarcoderdataPython |
3336973 | from math import sqrt, erf, log, exp
from random import random
# Gauss
def get_next_standard_gauss():
return sum([random() for _ in range(12)]) - 6
def get_next_gauss(m, s):
return m + s * get_next_standard_gauss()
def gauss(m, s, n):
"""
N(m, s^2)
:param m: mean
:param s: dispers... | StarcoderdataPython |
1869322 | """Pytest plugins and test support infrastructure."""
| StarcoderdataPython |
1683924 | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""Lista de modelos del programa.
En este fichero podemos encontrarnos todos los modelos,
que se pueden usar para nuestro programa.
"""
from src.model.Model import Model
class RtpModel(Model):
def search(self, filename):
"""Lectura de un fichero ... | StarcoderdataPython |
4999548 | # This is the class of the input root. Do not edit it.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def branchSums(root):
sum_array = []
branchSumsHelper(root, sum_array, 0)
return sum_array
def branchSumsHelper(tree, sum_... | StarcoderdataPython |
8195829 | <filename>network_moments/tensorflow/general/affine/affine.py
import tensorflow as tf
from ...utils import matmul, mul_diag
def mean(mean, A, b=None, transposed=False):
'''Output mean of Affine for general input.
f(x) = A * x + b.
Args:
mean: Input mean of size (Batch, Size).
A: Matrix o... | StarcoderdataPython |
210136 | <reponame>maxmuffin/SmartSeat
import serial
import csv
serDevSeduta = serial.Serial('/dev/ttyACM0', 9600)
serDevSchienale = serial.Serial('/dev/ttyACM1', 9600)
print("Inserisci peso:")
peso = float(input())
print("Inserisci la postura assunta (1-8): ")
postura = int(input())
print("Peso: " + str(peso) + " Postura: ... | StarcoderdataPython |
3462185 | <filename>portfolios/apps.py
from django.apps import AppConfig
class PortfoliosConfig(AppConfig):
name = 'portfolios'
| StarcoderdataPython |
5179357 | <reponame>zhangyuo/cf-nlp-py
# coding=utf-8
"""
@ license: Apache Licence
@ github: invoker4zoo
@ author: invoker/cc
@ wechart: whatshowlove
@ software: PyCharm
@ file: mysql_connector.py
@ time: $19-2-21 上午10:12
"""
import pymysql.cursors
import sys
from cfnlp.tools.logger import logger
class mysqlConnector(object):... | StarcoderdataPython |
1872809 | import gym
import numpy as np
import torch
import torchvision.transforms as T
from PIL import Image
# Resize frames we grab from gym and convert to tensor
resizer = T.Compose([
T.ToPILImage(),
T.Resize(40, interpolation=Image.CUBIC),
T.ToTensor()
])
# Start cartpole application through gym
def init():
return gym.... | StarcoderdataPython |
8063986 | <filename>aioreactive/operators/skip.py
from typing import TypeVar
from aioreactive.core import AsyncSingleStream
from aioreactive.core import AsyncDisposable, AsyncCompositeDisposable
from aioreactive.core import AsyncObserver, AsyncObservable, chain
T = TypeVar('T')
class Skip(AsyncObservable[T]):
def __init... | StarcoderdataPython |
211093 | <gh_stars>0
from torch import nn
def feed_forward(dim_input: int = 512, dim_feedforward: int = 2048) -> nn.Module:
return nn.Sequential(
nn.Linear(dim_input, dim_feedforward),
nn.ReLU(),
nn.Linear(dim_feedforward, dim_input),
) | StarcoderdataPython |
11231802 | # This process handles logs
import datetime, time, sys
class handle_logs():
def init_logs(data_changed_flags, log_queue):
print(' [ START ] Log subprocess started.')
handle_logs.data_changed_flags = data_changed_flags
handle_logs.log_queue = log_queue
file = open("./Reports/server_logs.txt", "a+")
file2 =... | StarcoderdataPython |
9736779 | <filename>keras_test/regressor_example2.py
# coding:utf-8
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
# create some data
X = np.linspace(-1, 1, 200)
# X = np.linspace(1, 100, 100)
np.random.shuffle... | StarcoderdataPython |
83512 | <reponame>aebrahim/FastAPIQuickCRUD<filename>setup.py
from setuptools import setup, find_packages
VERSION = '0.1.8'
print("""
- upload
- build wheel: python setup.py sdist
- upload to server: twine upload dist/*
- download
- Just pip install <package>
""")
if __name__ == '__main__':
setup(
... | StarcoderdataPython |
3575916 | <filename>day02/app/views/views.py
import os
from app.models import db, Person
from flask import Blueprint, session, render_template
from jinja2 import Template
blue = Blueprint(
name='bp',
import_name=__name__
)
@blue.route('/set/')
def set_session():
session['name'] = 'daShaDiao'
retu... | StarcoderdataPython |
1777856 | <gh_stars>1-10
from sys import stdout, stderr
from scell import Selector
from pytest import fixture
import scell.core
@fixture(autouse=True)
def mock_select(monkeypatch):
def select(rlist, wlist, xlist, timeout=None):
if not timeout and not rlist and not wlist:
raise RuntimeError
retur... | StarcoderdataPython |
15700 | <gh_stars>1-10
# Licensed under an MIT style license -- see LICENSE.md
import numpy as np
from scipy.stats import gaussian_kde
from matplotlib.colors import LinearSegmentedColormap, colorConverter
import corner
__author__ = ["<NAME> <<EMAIL>>"]
def _set_xlim(new_fig, ax, new_xlim):
if new_fig:
return ax... | StarcoderdataPython |
6628684 | <filename>expressivar/dec.py
from io import SEEK_SET, SEEK_CUR
import builtins
import contextlib
import inspect
import os
from expressivar.exceptions import UnmodifiableAttributeError
from expressivar.exceptions import UnmodifiableModeError
import wrapt
def is_file_like(f):
return callable(getattr(f, 'read', None... | StarcoderdataPython |
8197474 | <reponame>ChrisCraddock/PythonSchoolWork
import turtle
# drawBase = draw the base of the snowman, the largest snowball at the bottom
# drawMidSection = draw the middle snowball
# drawArms = draw snowman arms
# drawHead = draw snowman head, with eyes/mouth/ect
# drawHat = draw snowman hat
# Make it faster th... | StarcoderdataPython |
9680392 | '''
Data access objects for representing complex structures.
Created on Nov 30, 2011
:Authors: <NAME>
:Version: 1.1
'''
import os
import mimetypes
import logging
from django.core.files import File
from .utils import guess_fext
from mds.core.models import Observation, Concept
__all__ = ['ObservationSet']
class Set(... | StarcoderdataPython |
6690754 | <filename>pymatgen/analysis/tests/test_bond_valence.py<gh_stars>1-10
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
'''
Created on Oct 24, 2012
@author: shyue
'''
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ ... | StarcoderdataPython |
11240848 | <filename>tests/anime/test_stats.py<gh_stars>1-10
import pytest
from httpx import AsyncClient
from ..util import DEFAULT_PARAMS
@pytest.mark.asyncio
async def test_stats(client: AsyncClient) -> None:
params = DEFAULT_PARAMS | {"mal_request": "stats"}
response = await client.get("/anime", params=params)
s... | StarcoderdataPython |
9601649 | #!/usr/bin/env python
from linklist import *
class Solution:
def reverseKGroup(self, head, k):
new_head = None
while True:
i, tail = 1, head
while i < k and tail != None:
tail, i = tail.next, i+1
if i < k-1:
break
next... | StarcoderdataPython |
1932625 | <reponame>nuaalixu/MatrixSlow
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@Author: chenzhen
@Date: 2020-04-22 14:57:10
@LastEditTime: 2020-04-22 15:29:33
@LastEditors: chenzhen
@Description:
'''
import sys
sys.path.append('../../')
import matrixslow_serving as mss
print(mss.serving.MatrixSlowServer)
serving ... | StarcoderdataPython |
1822230 | <filename>tests/test_settings.py
import vectorbt as vbt
# ############# Global ############# #
def teardown_module():
vbt.settings.reset()
# ############# settings.py ############# #
class TestSettings:
def test_save_and_load(self, tmp_path):
vbt.settings.set_theme('seaborn')
vbt.settings.... | StarcoderdataPython |
1965094 | #!/usr/bin/env python
COPY_GOOGLE_DOC_KEY = '<KEY>'
| StarcoderdataPython |
3263753 | <filename>config/urls.py
from django.contrib import admin
from django.conf.urls import include, url
urlpatterns = [
url('^admin/', admin.site.urls),
url('^', include('apps.cms_first.urls'))
]
| StarcoderdataPython |
6674132 | <reponame>Amourspirit/ooo_uno_tmpl<filename>src/parser/api/api_method_exception.py
# coding: utf-8
from typing import Union, List
from bs4.element import Tag, ResultSet
from .api_proto_block import ApiProtoBlock
from ..dataclass.summary_info import SummaryInfo
from ..web.block_obj import BlockObj
class ApiMethodExcep... | StarcoderdataPython |
5095597 | <filename>pymc3_ext/examples/baseball.py<gh_stars>0
#
# Demonstrates the usage of hierarchical partial pooling
# See http://mc-stan.org/documentation/case-studies/pool-binary-trials.html for more details
#
import pymc3_ext as pm
import numpy as np
def build_model():
data = np.loadtxt(pm.get_data('efron-morris-75-... | StarcoderdataPython |
349521 | import math
from unittest.mock import MagicMock, patch
import pytest
from bluefoglite.common.store import InMemoryStore
from bluefoglite.common.tcp.agent import AgentContext
from bluefoglite.testing.util import multi_thread_help
def mocked_create_pair(self, peer_rank):
pair = MagicMock()
pair.self_address =... | StarcoderdataPython |
294631 | <filename>ouranos/utils/log.py
import aiohttp
import logging
import sys
from collections import deque
from loguru import logger
from discord.webhook import Webhook, AsyncWebhookAdapter
from auth import WEBHOOK_URL_PROD
class InterceptHandler(logging.Handler):
def emit(self, record):
# Get corresponding ... | StarcoderdataPython |
1772001 |
# lax_coord = [(33.9425, -118.408056), (90.25, 98.36)]
# lst =[]
# lst1=[]
#
# for latlong, _ in lax_coord: #gets first value only
# lst.append(latlong)
# for _, latlong in lax_coord: #gets second value only
# lst1.append(latlong)
# print(lst)
# print(lst1)
# traveller_id = [('usa', '31256'), ('nms'... | StarcoderdataPython |
3461452 | from helpers.motors import MotorController
mc = MotorController()
mc.stop()
| StarcoderdataPython |
11360356 | <gh_stars>0
"""CSS parsing and serialization."""
| StarcoderdataPython |
8082614 | from lxml import html
import requests
import csv
f = csv.writer(open("./asli9.csv", "w", encoding='utf-8'))
f.writerow(["my data"])
class AppCrawler:
def __init__(self, starting_url, depth):
self.starting_url = starting_url
self.depth = depth
self.current_depth = 0
self.depth_li... | StarcoderdataPython |
1669043 | # !/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Program to sort files by date. #
# Program Author : <NAME... | StarcoderdataPython |
6438630 | <reponame>s0b0lev/raiden-client-python<gh_stars>1-10
from raiden_client.endpoints.connections import Connections
def test_connections_request():
connection = Connections()
assert connection.endpoint == "/connections"
assert connection.method == "get"
assert connection.name == "connections"
assert ... | StarcoderdataPython |
270802 | <gh_stars>0
from typing import List
from fastapi import APIRouter
from fastapi.requests import Request
from src.core.data import save, save_relation, save_graph
from src.model.exe_status import ExecutionStatus
from src.model.node_data import NodeData, Relation, GraphData
router = APIRouter(prefix="/api/v1/data")
@... | StarcoderdataPython |
1780327 | <reponame>Estevo-Aleixo/pysvg
#!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup
setup(name="pysvg",
version="0.2.2",
description="Python SVG Library",
author="<NAME>",
author_email="<EMAIL>",
url="http://codeboje.de/pysvg/",
packages=['... | StarcoderdataPython |
4808933 | from structs import *
from ai import *
def selectBestUpgrade():
if (player.HealthUpgrades <= player.CollectingUpgrades):
return UpgradeType.MaximumHealth
if (player.CollectingUpgrades <= player.CarryingUpgrades):
return UpgradeType.CollectingSpeed
if (player.CarryingUpgrades <= player.Attac... | StarcoderdataPython |
1954163 | #Modificar el ejercicio anterior generando que únicamente sume números que sean múltiplos de 3, 5 o 7 hasta el número ingresado.
i = int(input("Ingrese un número:"))
acumulador = ""
suma = 0
acumuladorDeTres = 3
for j in range(i+1):
if j % acumuladorDeTres == 0 and j > 0:
suma += j
acumuladorDe... | StarcoderdataPython |
1924933 | <reponame>ricklentz/pytorchvideo<filename>pytorchvideo_trainer/pytorchvideo_trainer/module/moco_v2.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
from dataclasses import dataclass
from typing import Optional, List, Callable, Union, Any, Tuple
import pytorchvideo_trainer.module.... | StarcoderdataPython |
11373894 | import asyncio
import logging
import random
import socket
from enum import IntEnum
from operator import attrgetter
from typing import Callable, Iterable, List, NamedTuple, Optional
import aiodns
import aiohttp
LOG = logging.getLogger("photonpump.discovery")
class NodeState(IntEnum):
Initializing = 0
Unknown... | StarcoderdataPython |
3208790 | # 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 under the... | StarcoderdataPython |
8091937 | # Copyright (c) 2001-2022 Aspose Pty Ltd. All Rights Reserved.
#
# This file is part of Aspose.Words. The source code in this file
# is only intended as a supplement to the documentation, and is provided
# "as is", without warranty of any kind, either expressed or implied.
import os
import aspose.words as aw
import a... | StarcoderdataPython |
5145374 | #!/usr/bin/env python
import base64
import os
import sys
from flask import Flask, request, Response, make_response
from flask.ext.api import status
app = Flask(__name__)
@app.route('/')
def login():
byte_str = request.args.get('bytes', '0')
num_bytes = int(byte_str)
return base64.b64encode(os.urandom(nu... | StarcoderdataPython |
11298286 | from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from .constants import REGIONS_DICT
from .models import *
from django.core.handlers.wsgi import WSGIR... | StarcoderdataPython |
5112645 | """
Module: libfmp.c8.c8s2_f0
Author: <NAME>, <NAME>
License: The MIT license, https://opensource.org/licenses/MIT
This file is part of the FMP Notebooks (https://www.audiolabs-erlangen.de/FMP)
"""
import numpy as np
import librosa
from scipy import ndimage, linalg
from scipy.interpolate import interp1d
from numba im... | StarcoderdataPython |
11323077 | # -*- coding: utf-8 -*-
channel_id = "@yourchannel" # @username for public channels / chat_id for private channels
token = "token" # Your bot's token from @BotFather
db_name = "storage.db" # Name of SQL Database to use
number_of_entries = 15 # How many entries will be included in RSS
admin_ids = [111111, 2222222] ... | StarcoderdataPython |
3308567 | import logging
import sys
import argparse
from argparse import RawDescriptionHelpFormatter
import os
from Modules import source_parser, alignment, bio_helpers, basic, platypus
__author__ = 'Gyfis'
data_path = 'data'
if __name__ == "__main__":
logging.basicConfig(format='%(levelname)s @%(asctime)s: %(message)s'... | StarcoderdataPython |
285141 | <filename>input/03_multi-inputs/03-08.py<gh_stars>0
def main():
# input
S = input()
T = input()
U = input()
# compute
# output
print(U + T + S)
if __name__ == '__main__':
main()
| StarcoderdataPython |
5115028 | import csv
#import os
import urllib
#import dataconverters.xls
sources = ["http://www3.epa.gov/climatechange/images/indicator_downloads/glaciers_fig-1.csv"]
archive = 'archive/glaciers_fig-1.csv'
data = 'data/glaciers.csv'
def string_between(string, before, after):
temp = string.split(before)[1]
temp = temp.split(af... | StarcoderdataPython |
11383842 | <gh_stars>0
import numpy as np
import re
def readLVM( filepath ):
# Open and read file
with open( filepath ,'r') as f:
lines = f.readlines()
# Define variables
numbering = []
time = []
mode = []
# Store ID given in file
fileID = lines.pop... | StarcoderdataPython |
6412752 | from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.impute import SimpleImputer
from sklearn_callba... | StarcoderdataPython |
1790557 | """Tests for the gym_fin.utils module"""
import pytest
def test_softmax():
import numpy as np
from gym_fin.envs import utils
rng = np.random.RandomState(0)
X = rng.randn(5)
exp_X = np.exp(X)
sum_exp_X = np.sum(exp_X, axis=0)
result = exp_X / sum_exp_X
np.testing.assert_array_almost_e... | StarcoderdataPython |
12810772 | <filename>survey/t11/prop.py<gh_stars>0
import json
import os
import time
import datetime
from flask import (
Blueprint
)
from core.utils import cents_repr
from survey._app import app, csrf_protect
from survey.txx.prop import handle_check, handle_done, handle_index, insert_row, handle_index_dss
from survey.globa... | StarcoderdataPython |
8158574 | print('\033[32m_\033[m'*20)
print('\033[1;32m{:^20}\033[m'.format('JOKENPÔ'))
print('\033[32m-\033[m'*20)
from random import choice
from time import sleep
print('\033[1;33mGESTOS:\033[36m\nPedra:...1\nPapel:...2\nTesoura:.3\033[m')
gesto1 = int(input('\033[1;35mDigite o seu gesto de acordo com a tabela acima: \033[m'... | StarcoderdataPython |
9731229 | <filename>test/unit/test_exception.py<gh_stars>0
# coding: utf-8
from mock import Mock
import pytest
from boxsdk.exception import BoxAPIException, BoxOAuthException
from boxsdk.network.default_network import DefaultNetworkResponse
def test_box_api_exception():
status = 'status'
code = 400
message = 'mes... | StarcoderdataPython |
8155637 | import random
import time
from environmentinterface import EnvironmentInterface
# === TD(0) ===
# Initialize V(s) arbitrarily, pi to the policy to be evaluated
# Repeat (for each episode)
# Initialize s
# a <- action given by pi for s
# Take action a; observe reward r and next state s'
# V(s) <- V(s) + alpha[r ... | StarcoderdataPython |
11279046 | <reponame>Guigui14460/project-automation
import argparse
import inspect
from project_automation import projects, utils
def main():
# Creation the base of the CLI parser
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('-i', '--allow-install',
help='allows t... | StarcoderdataPython |
1637352 | <gh_stars>1-10
import pandas as pd
import ipdb
import os
from shutil import copyfile
ano_keyword_to_label = {
"left": 0,
"right": 1,
}
def get_label(f):
global ano_keyword_to_label
for key in ano_keyword_to_label:
if key in f:
return ano_keyword_to_label[key]
raise Exception("c... | StarcoderdataPython |
8145430 | <filename>tripp/__init__.py
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| StarcoderdataPython |
6513076 | <filename>as_shinchan/__init__.py<gh_stars>0
from turtle import *
s=Screen()
s.screensize(700,1000)
speed(5)
def my_goto(x, y):
penup()
goto(x, y)
pendown()
def short():
pensize(2)
fillcolor('#ffec40')
begin_fill()
right(25)
forward(20)
right(45)
forward(20)
l... | StarcoderdataPython |
4905523 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-26 14:48
from __future__ import unicode_literals
import core.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies =... | StarcoderdataPython |
3392043 | from __future__ import division
from functools import reduce
from collections import defaultdict
from edit_distance import SequenceMatcher
import string
class EvaluateTranscription():
"""Calculate various metrics for the speech transcription service.
Required input:
- Reference transcript (gro... | StarcoderdataPython |
4966831 | <reponame>mintzer/pupillometry-rf-back
class _LogEntry(object):
def __init__(self, data):
if not isinstance(data, dict):
raise ValueError("You shouldn't create _LogEntry objects yourself.")
self.__system_time_stamp = data["system_time_stamp"]
self.__source = data["source"]
... | StarcoderdataPython |
6550189 | <filename>sudoku/main.py
#import os
from sudoku.wsgi import application
#import sqlalchemy
app = application
'''
db_user = os.environ.get("DB_USER")
db_pass = <PASSWORD>("DB_PASS")
db_name = os.environ.get("DB_NAME")
cloud_sql_connection_name = os.environ.get("CLOUD_SQL_CONNECTION_NAME")
db = sqlalchemy.create_engine... | StarcoderdataPython |
11390246 | <reponame>mwbub/binary-evolution
import warnings
import unittest
import numpy as np
from galpy.orbit import Orbit
from galpy.potential import MWPotential2014, evaluatePotentials
from galpy.util.bovy_conversion import time_in_Gyr
from binary_evolution.tools import v_circ, v_esc, period, ecc_to_vel
# Factors for conver... | StarcoderdataPython |
6504276 | import eventlet
eventlet.monkey_patch(
os=True,
select=True,
socket=True,
thread=True,
time=True)
from eventlet.green import asyncore
import smtpd_green as smtpd
from flanker import mime
import hashlib
import base64
import six
from st2reactor.sensor.base import Sensor
class SMTPSensor(Sensor):
... | StarcoderdataPython |
4992590 | import collections as co
import numpy as np
import os
import pathlib
import sktime.utils.load_data
import torch
import urllib.request
import tarfile
from .gas import GAS
from .miniboone import MINIBOONE
here = pathlib.Path(__file__).resolve().parent.parent.parent
def download():
base_base_loc = here / 'data'
... | StarcoderdataPython |
1999012 | import re
import pytest
import numpy as np
import morphops.procrustes as procrustes
from .helpers import make_haus, make_ngon, get_2d_refl
class TestProcrustesAlgos(object):
# A weird house, plus its rotated, reflected, aligned versions.
(haus,
haus_c, haus0_b, haus0, two, haus0_scld,
haus0_Ro, haus0... | StarcoderdataPython |
9670034 | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
plotly.tools.set_credentials_file(username='mickisgay', api_key='... | StarcoderdataPython |
3438937 | """Liveness/readiness checks for supervisor"""
from django.core.cache import cache, InvalidCacheBackendError
from django.db import DatabaseError
from django.http import JsonResponse
from django.views.decorators.cache import never_cache
from .models import SoftwareCollection
SUCCESS = "OK" # sentinel value indicatin... | StarcoderdataPython |
6527067 | <filename>app/search/index.py
from typing import Tuple, List
import annoy
class FlatIndex(object):
_cls: annoy.AnnoyIndex
def k_nearest_neighbors(self, X, n_neighbors=50, include_distances=True) -> Tuple[List[int], List[float]]:
indices, dists = self._cls.get_nns_by_vector(X, n_neighbors, include_di... | StarcoderdataPython |
6404937 | #! /usr/bin/env python3
# -*-coding:utf-8 -*-
# @Time : 2019/06/16 16:45:29
# @Author : che
# @Email : <EMAIL>
from threading import Thread
import subprocess
from queue import Queue
num_threads = 3
queue = Queue()
ips = ["192.168.1.%d" % ip for ip in range(1, 255)]
def pinger(i, q): # 实际工作
while True:
... | StarcoderdataPython |
1905471 | <gh_stars>0
import discord
import re
import os
import random
import asyncio
from discord.ext import commands
from discord.voice_client import VoiceClient
bot = discord.Client()
bot = commands.Bot(command_prefix='.')
players = {}
def foreach(function, iterable):
for element in iterable:
fun... | StarcoderdataPython |
3286353 | import os
import re
import glob
import socket
import struct
import logging
import binascii
import threading
import subprocess
import netfilterqueue
from debuglevels import *
from collections import defaultdict
from . import diverterbase
class IptCmdTemplateBase(object):
"""For managing insertion and removal of ip... | StarcoderdataPython |
173346 | # Test some weird getattr/hasattr guarding scenarios
# Make sure that we guard correctly when a __getattr__ is involved:
def f(o):
print hasattr(o, "a")
print getattr(o, "a", None)
class C(object):
def __getattr__(self, key):
print "getattr", key
raise AttributeError(key)
for i in xrange... | StarcoderdataPython |
1705058 | from portfolio_manager.objects.account import Account
from portfolio_manager.objects.asset import Asset
class Portfolio():
def __init__(self, parsed_assets, account_details_list):
assert isinstance(parsed_assets, list), 'Portfolio requires @parsed_assets be a list'
assert isinstance(account_detail... | StarcoderdataPython |
4883572 | <reponame>zeciola/Berghem_API
from http import HTTPStatus
from flask import request
from flask_restplus import Resource
from app.main.service.transactions_service import (create_transaction, update_product_name_by_id_transaction,
delete_transaction_by_id, list_all_tr... | StarcoderdataPython |
8084018 | <reponame>dia38/walt-python-packages
VPN_SOCK_PATH = "/var/run/walt-vpn.sock"
VPN_SOCK_BACKLOG = 20
| StarcoderdataPython |
110406 |
import os
import csv
import codecs
import logging
import pandas
__author__ = 'robodasha'
__email__ = '<EMAIL>'
class DataParser(object):
# mapping of columns in the responses.csv file
_MAPPING = {
'response': {
0: 'timestamp', 1: 'research_area', 2: 'research_area_details',
... | StarcoderdataPython |
1641363 | <filename>Aplikasi Sapaan.py
from datetime import datetime
nama = input("Masukkan Namamu: ")
jam = datetime.now().hour
if jam < 10:
sapaan = "Selamat Pagi"
elif 10 < jam < 1:
sapaan = "Selamat Siang"
elif 15 < jam < 18:
sapaan = "Selamat Sore"
elif 18 < jam <= 24:
sapaan = "Selamat Malam"
print("Hal... | StarcoderdataPython |
3204357 |
class Communication:
def __init__(self):
self.client = None
self.lock = threading.Lock()
def connectToDevice(self, address):
"""Connection to the client - the method takes the IP address (as a string, e.g. '192.168.1.11') as an argument."""
self.client = ModbusTcpClient(address)
def ... | StarcoderdataPython |
9682375 | <gh_stars>10-100
# %%
import forge
import torch
import math
import numpy as np
import matplotlib.pyplot as plt
import argparse
import time
from types import SimpleNamespace
from configs.constellation.constellation import load as load_data
# reset parser so forge doesn't throw errors
forge.flags._global_parser = argpar... | StarcoderdataPython |
4968825 | import pickle
import platform
import os
import getpass
import wx
def store(content, directory):
with open(directory, "wb") as f:
encrypt_data = pickle.dumps(content)
pickle.dump(encrypt_data, f)
def load(directory):
with open(directory, "rb") as f:
data = pickle.load(f)
data ... | StarcoderdataPython |
9628735 | <filename>illumidesk/teams/decorators.py
from functools import wraps
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from .roles import user_can_access_team, user_can_administer_team
from .models import Team
def login_and_team_requ... | StarcoderdataPython |
263908 | <reponame>cshjin/Vanilla-GCN<filename>models/layers.py
import tensorflow as tf
from tensorflow.keras import activations, regularizers, constraints, initializers
spdot = tf.sparse.sparse_dense_matmul
dot = tf.matmul
class GCNConv(tf.keras.layers.Layer):
def __init__(self,
units,
... | StarcoderdataPython |
9757393 | import numpy as np
import sys
import gc
import chroma.api as api
if api.is_gpu_api_cuda():
import pycuda.driver as cuda
from pycuda import gpuarray as ga
elif api.is_gpu_api_opencl():
import pyopencl as cl
#from pyopencl.array import Array as ga
import pyopencl.array as ga
from chroma.tools import p... | StarcoderdataPython |
3300161 | <reponame>yugangzhang/pyFAI
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Azimuthal integration
# https://github.com/silx-kit/pyFAI
#
# Copyright (C) 2018 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: <NAME> (<EMAIL>)
#
# This program is free ... | StarcoderdataPython |
6405087 | <gh_stars>0
'''
-*- coding: utf-8 -*-
Python Version: 3.6
Course: GEOG5790M Programming-for-Spatial-Analysts-Advanced-Skills
Author: <NAME>
File name: explosionscript.py
'''
# imports
import arcpy
p0 = arcpy.GetParameterAsText(0)
p1 = arcpy.GetParameterAsText(1)
p2 = arcpy.GetPara... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.