id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
21410 | from pylab import *
import tables
def exactSol(X, Y, t):
return exp(-2*t)*sin(X)*cos(Y)
fh = tables.openFile("s251-dg-diffuse-2d_q_1.h5")
q = fh.root.StructGridField
nx, ny, nc = q.shape
dx = 2*pi/nx
Xf = linspace(0, 2*pi-dx, nx)
dy = 2*pi/ny
Yf = linspace(0, 2*pi-dy, ny)
XX, YY = meshgrid(Xf, Yf)
Xhr = linspace... | StarcoderdataPython |
1798253 | <reponame>AntoninoScala/air-water-vv<filename>2d/caissonBreakwater/fixed/geometryPlot.py
from numpy import *
from scipy import *
from pylab import *
import collections as cll
import csv
# Put tankVertices and caissonVertices arrays here
#tankVertices
tv=np.array([[0.0, 0.0],
[0.38992935246580784, 0.0],
[1.169788057... | StarcoderdataPython |
3353433 | import tensorflow as tf
class Predict(object):
def __init__(self, path1, path2):
self.graph = tf.Graph()
with self.graph.as_default():
self.saver = tf.train.import_meta_graph(path1)
self.sess = tf.Session(graph=self.graph)
with self.sess.as_default():
with se... | StarcoderdataPython |
155419 | <reponame>Jesse-Redford/SurfaceMetrology
import os
import cv2
import glob
import time
import h5py
import imageio
import numpy as np
import pandas as pd
from PIL import Image
import streamlit as st
from src.ISO251782 import iso25178
from sklearn.impute import KNNImputer
def external_folder_selector(folder_path):
pr... | StarcoderdataPython |
1783252 | <reponame>didiqu/IS_simulator
"""This file contain all functions about log configuration """
from colorama import Fore, Style
from .logic_actions_utils import execute_command, upload_file, change_fileorfolder_user_owner, restart_service
def rsyslog_client(instance, arg, verbose=True):
""" Configure rsyslog client ... | StarcoderdataPython |
1602232 | <reponame>Sim7b/jellyfin_ha<filename>__init__.py
"""The jellyfin component."""
import logging
import time
import re
import traceback
import collections.abc
from typing import Mapping, MutableMapping, Optional, Sequence, Iterable, List, Tuple
import voluptuous as vol
from homeassistant.exceptions import ConfigEntryNot... | StarcoderdataPython |
1672534 | #-------------------------------------------------------
# Annexe 2 : commander une LED à partir d'une page web
#-------------------------------------------------------
"""
AuteurDate :
Rôle :
- Connexion à une borne Wifi (partage de connexion sur téléphone)
- Afficher dans la console les paramètres réseau :... | StarcoderdataPython |
4822031 | <reponame>LoicBoileau/Projet-S4---Robot-Delta
"""
/*
* This file is part of PySide: Python for Qt
*
* Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: PySide team <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Less... | StarcoderdataPython |
95195 | import tornado.web
from settings import site_settings
apps = [
# (r'/prefix', 'app_name')
# appA
# __init__.py
# urls.py
(r"/api", "api"),
]
urls = [
# (r'relative_url', 'RequestHandler')
(r"/static", tornado.web.StaticFileHandler,
dict(path=site_settings['static_path'])),
]
| StarcoderdataPython |
1612028 | # Generated by Django 2.0.8 on 2019-03-19 16:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('caseFiles', '0006_casefile_file_pdf'),
]
operations = [
migrations.RemoveField(
model_name='casefile',
name='file_page1',
... | StarcoderdataPython |
145443 | <gh_stars>1-10
from random import choice
def main():
amount_students = 1000
amount_wishes = 100
print(amount_students)
for student_number in range(1, amount_students + 1):
wishes = []
for _ in range(amount_wishes):
while str(wish := choice(range(1, amount_students... | StarcoderdataPython |
1681655 | <gh_stars>1-10
"""
Loader module is the interface into the datagen data generation utility. This class handles loading, parsing and
delegating the handling of various data types.
"""
import json
from typing import Union, Dict
from . import suppliers
from . import utils
from .exceptions import SpecException
from .mod... | StarcoderdataPython |
175806 | from brownie import (
accounts, ERC20KP3ROracle, UniswapV2Oracle, ProxyOracle, CoreOracle,
CurveOracle, WERC20, UbeswapV1Oracle, HomoraBank, UniswapV2SpellV1, SafeBox,
SimpleOracle, WStakingRewards
)
from brownie import interface
from .utils import *
import json
def main():
deployer = accounts.load('ad... | StarcoderdataPython |
3993 | """Hyper-distributions."""
from libqif.core.secrets import Secrets
from libqif.core.channel import Channel
from numpy import array, arange, zeros
from numpy import delete as npdelete
class Hyper:
def __init__(self, channel):
"""Hyper-distribution. To create an instance of this class it is
class i... | StarcoderdataPython |
1638719 | import sys
from ephyviewer.myqt import QT_MODE
if QT_MODE == 'PyQt5':
from . import icons_PyQt5 as icons
elif QT_MODE == 'PySide2':
from . import icons_PySide2 as icons
elif QT_MODE == 'PyQt4':
from . import icons_PyQt4 as icons
else:
raise ValueError('Could not load icons for unrecognized QT_MODE: ' ... | StarcoderdataPython |
114966 | import torch
from .EMA import EMA
class PhysicsGuide:
def __init__(self, hand_model, object_model, penetration_model, fc_loss_model, args):
self.epsilon = 1e-4
self.hand_model = hand_model
self.object_model = object_model
self.penetration_model = penetration_model
self.fc_... | StarcoderdataPython |
1608395 | import numpy as np
from utils.rbo import rbo as rbo_utils
from itertools import combinations
def proportion_common_words(topics, topk=10):
"""
compute proportion of unique words
Parameters
----------
topics: a list of lists of words
topk: top k words on which the topic diversity will be compu... | StarcoderdataPython |
3307260 | import json
import os
import unittest
from mock import Mock
from testfixtures import compare, Replacer
from deployfish.terraform import Terraform
YAML = {
'statefile': 's3://foobar/baz',
'lookups': {
'lookup1': 'proxy-{environment}-cluster-name',
'lookup2': 'proxy-{environment}-elb-id',
... | StarcoderdataPython |
4832251 | <filename>ee/clickhouse/queries/column_optimizer.py
from typing import List, Set, Tuple, Union, cast
from ee.clickhouse.materialized_columns.columns import ColumnName, get_materialized_columns
from ee.clickhouse.models.action import get_action_tables_and_properties, uses_elements_chain
from ee.clickhouse.models.proper... | StarcoderdataPython |
3272008 | <reponame>acidicMercury8/xray-1.0
import exporters
from Exporter import Exporter
from declarations import *
from enumerate import enumerate
from settings import *
from CodeUnit import CodeUnit
from EnumExporter import EnumExporter
#=============================================================================... | StarcoderdataPython |
3382439 | <reponame>farzamfan/NLP-Pipeline<filename>nlpipe/Clients/client.py
import logging
import os
import argparse
import sys
from nlpipe.Clients.HTTPClient import HTTPClient
def get_client(server_name, token=None):
"""
Returns a client (for now only HTTP client)
:param server_name: address of the server (URL)
... | StarcoderdataPython |
1667214 | <reponame>muctadir/labeling-machine<filename>webapp/migrations/versions/f2321be6f3e5_description_for_each_label.py
"""description for each label
Revision ID: f<PASSWORD>
Revises: <PASSWORD>
Create Date: 2022-02-17 19:17:09.417982
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alem... | StarcoderdataPython |
115457 | """ Quandl Model """
__docformat__ = "numpy"
import logging
import pandas as pd
import quandl
from gamestonk_terminal import config_terminal as cfg
from gamestonk_terminal.decorators import log_start_end
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def get_short_interest(ticker: str, nyse: bool... | StarcoderdataPython |
3294115 | <reponame>RJT1990/mantra<filename>mantraml/ui/core/models.py
import boto3
from collections import Counter
import datetime
import os
import shutil
import yaml
from django.db import models
from .consts import MANTRA_DEVELOPMENT_TAG_NAME
from .mantra import Mantra
from .forms import StartInstanceForm, StopInstanceForm, ... | StarcoderdataPython |
1699118 | # Should match the matlab version
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
A = np.array([[0.0, 1.0], [0.0, -10.0/100]])
B = np.array([[0.0], [1.0/100.0]])
C = np.array([1.0, 0.0])
D = np.array([0.0])
K = np.array([30.0, 70.0])
X = np.array([10, 0.0])
sys = signal.StateSpace(A-B*K, B... | StarcoderdataPython |
3217460 | <filename>Lib/test/test_spwd.py
import os
import unittest
from test import support
spwd = support.import_module('spwd')
@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
'root privileges required')
class TestSpwdRoot(unittest.TestCase):
def test_getspall(self):
entr... | StarcoderdataPython |
3386230 | <filename>gandalf/api/auth.py<gh_stars>0
from flask import Blueprint
from flask_restful import Resource, Api
auth_blueprint = Blueprint("auth", __name__, url_prefix="/auth")
api = Api(auth_blueprint)
class AuthPing(Resource):
def get(self):
return {"status": "success", "message": "pong!"}
api.add_reso... | StarcoderdataPython |
3386941 | import traceback
from flask import Flask, redirect, request, render_template, session , url_for, jsonify
from flask_socketio import SocketIO, emit
from flask_compress import Compress
import os
from utils import *
ResponseThread = None
app = Flask(__name__)
app.app_context().push()
websocket = SocketIO(app)
ap... | StarcoderdataPython |
46743 | sessions = [{
"1": {
"type": "session",
"source": {"id": "scope"},
"id": "1",
'profile': {"id": "1"}
}
}]
profiles = [
{"1": {'id': "1", "traits": {}}},
{"2": {'id': "2", "traits": {}}},
]
class MockStorageCrud:
def __init__(self, index, domain_class_ref, entity):... | StarcoderdataPython |
3210166 | <filename>website_multi_company/tests/test_create.py
# Copyright 2018 <NAME> <https://it-projects.info/team/yelizariev>
# License MIT (https://opensource.org/licenses/MIT).
from odoo.tests.common import TransactionCase
class TestCreate(TransactionCase):
at_install = True
post_install = True
def test_crea... | StarcoderdataPython |
145611 | <filename>courses/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-03 15:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
... | StarcoderdataPython |
182546 | # Copyright 2018 Owkin, inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | StarcoderdataPython |
140757 | """The tests for deCONZ logbook."""
from copy import deepcopy
from homeassistant.components import logbook
from homeassistant.components.deconz.deconz_event import CONF_DECONZ_EVENT
from homeassistant.components.deconz.gateway import get_gateway_from_config_entry
from homeassistant.const import CONF_DEVICE_ID, CONF_E... | StarcoderdataPython |
3377954 | <filename>functions_legacy/FactorAnalysis.py<gh_stars>1-10
import matplotlib.pyplot as plt
import numpy as np
from numpy import sum as npsum
from numpy import zeros, sort, diag, eye, abs, sqrt, tile, maximum, argsort, max as npmax
from numpy.linalg import eig, matrix_rank
plt.style.use('seaborn')
from functions_legac... | StarcoderdataPython |
107247 | #!/usr/bin/python
# script preparing tab file to plot in R for small RNA profiling
# version 1 29-1-2012
# Usage plotter.py <bowtie input> <min size> <max size> <normalization factor> <tabular output>
import sys
def acquisition (file2parse, sizerange):
F = open (file2parse)
plus_table = {}
minus_table = {}
f... | StarcoderdataPython |
3282783 | import os
import jinja2
import reconcile.templates as templates
def get_package_environment():
"""Loads templates from the current Python package"""
templates_dir = os.path.dirname(templates.__file__)
template_loader = jinja2.FileSystemLoader(searchpath=templates_dir)
return jinja2.Environment(loade... | StarcoderdataPython |
1651153 | import subprocess as sp
import torch as th
def run_bench(name, *args, device="cpu"):
args = list(args)
args += ["-d", device]
if device == "cuda" and not th.cuda.is_available():
return "Not available /!\\"
return sp.check_output(["python3", "-m", f"bench.{name}"] + args).decode('utf8')
def m... | StarcoderdataPython |
71437 | <gh_stars>0
# Author: <NAME>
# Date: 2015
"""
Visualize the generated localization synthetic
data stored in h5 data-bases
"""
from __future__ import division
import io
import os
import os.path as osp
import numpy as np
import matplotlib.pyplot as plt
import h5py
from common import *
import string
import random
from ... | StarcoderdataPython |
1657579 |
import datetime
import logging
import mock
import os
import shutil
import socket
import tempfile
import unittest
from lib.purge_remote_folder import PurgeRemoteFolders
class TestPurgeRemoteFolders(unittest.TestCase):
@staticmethod
def _to_unix_timestamp(date_obj):
return (date_obj - datetime.date(1... | StarcoderdataPython |
3243559 | <gh_stars>0
import argparse
import os, sys
import json
from shutil import copyfile
this_file_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(this_file_path.split('generators')[0])
from helper_functions import get_Manchester_Syntax
if __name__ == "__main__":
parser = argparse.ArgumentParser()
... | StarcoderdataPython |
1656669 | """
Find the largest 0 to 9 pandigital
that can be formed by concatenating products
""" | StarcoderdataPython |
58027 | <reponame>husqvarnagroup/GETL
"""
The Utils module containing utility functions for lift jobs.
Utilities supported:
1. json_to_spark_schema: Converts a json schema to spark schema.
2. delete_files: Deletes a list of s3 files provided.
3. copy_keys: Copies files between S3 buckets.
4. copy_and_cleanup: Copies files bet... | StarcoderdataPython |
1678039 | import sqlite3
from sqlbuilder.smartsql import Q, T, Result
from sqlbuilder.smartsql.dialects.sqlite import compile
from .Users import Users
class DbUsers(Users):
def __init__(self, db_name: str) -> None:
self.db_name = db_name
def add(self, email):
# type: (str) -> None
with sqlite3... | StarcoderdataPython |
10036 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from appconf import AppConf
from django.conf import settings # noqa
class LabjsConf(AppConf):
ENABLED = not settings.DEBUG
DEBUG_TOGGLE = 'labjs'
| StarcoderdataPython |
171610 | from django.test import TestCase
from devnotes.models import Devnote
class DevnoteTestCases(TestCase):
def setUp(self):
Devnote.objects.create(name='testnote',
description='testnote description')
def test_retrieve_note(self):
"""retrieve the testnote... | StarcoderdataPython |
88417 | <gh_stars>0
import json
import requests
from requests.models import Response
from src.models.GithubException import GithubException
class Graphql:
url: str
items_per_request: int
cursor = None
def __init__(self, url: str, items_per_request: int) -> None:
self.url = url
self.items_pe... | StarcoderdataPython |
157617 | """Part of the flag-loader project.
Copyright: (C) 2014 <NAME>
License: MIT License (see LICENSE.txt)
Exported classes: BaseResolver
"""
from abc import ABCMeta, abstractmethod
class BaseResolver(object, metaclass=ABCMeta):
"""Abstract base class for all resolvers."""
@abstractmethod
... | StarcoderdataPython |
127362 | <reponame>AlbertSuarez/casescan
from src.engine.initializator import cases_db
from src.helper import response_builder
def get(case_id=None):
if case_id:
if case_id in cases_db:
return response_builder.make(
False, response=dict(results=[dict(case_id=case_id, sections=cases_db.g... | StarcoderdataPython |
3262464 | import warnings
# Version
__version__ = '0.2.0'
# Check for dependencies
hard_dependencies = ['numpy','pandas','seaborn','scipy','matplotlib','sklearn']
missing_dependencies = []
for dependency in hard_dependencies:
try:
__import__(dependency)
except ImportError as e:
missing_dependencies.ap... | StarcoderdataPython |
11818 | <filename>algorithms/python/118.py
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0: return []
rls = [[1]]
for i in range(2, numRows+1):
row = [1] * i
for j in range(1, i-1)... | StarcoderdataPython |
1617739 | <reponame>IvanGavrilin/pyview
# The MIT License (MIT)
#
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rig... | StarcoderdataPython |
3327281 | import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from data_utils import *
def predict_all(model, all_data):
"""
Predict odor probabilities for all trials.
:param model: (keras) decoding model
:param all_data: (4d numpy array) data of format ... | StarcoderdataPython |
1669854 | <reponame>bcpki/bitcoin
#!/usr/bin/env python
#
# BCPKI - BlockchainPKI
# Copyright (C) 2013 <EMAIL>, <EMAIL>
#
# This program 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 Foundation, either version 3 of the License, o... | StarcoderdataPython |
4802130 | <filename>00Python/day07/basic02.py<gh_stars>100-1000
"""
函数中的局部变量的释放狮是在函数执行完后就马上消失
全局变量是等真个程序运行完后进行销毁,作用域是整个函数
1- 如果局部变量名和全局的相同,那么执行的时候根据就近原则
2- 如果函数内找不到该变量名,那么就去找全局变量
3- 如果函数内想要就该外面的全局变量,使用globe关键字
"""
num = 10
def my_func01():
# num = 20 这里是创建一个新的内部变量
global num
num = 20 # 这里告诉函数... | StarcoderdataPython |
4819287 | <filename>backend/simulation/demandside/building.py
from simulation.demandside.component import ComponentSim
from simulation.location_entity import LocationEntity
from database.models import Building
class BuildingSim(LocationEntity):
def __init__(self, name, lat, long, listOfComponents, historicalData, hour = 0)... | StarcoderdataPython |
78492 | <filename>vim/inference_rt.py
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../'))
import numpy as np
import h5py
import argparse
import time
import logging
from sklearn import metrics
from utils import utilities, data_generator, agument
import tensorflow as tf
slim = tf.contrib.slim
import pandas... | StarcoderdataPython |
128957 | import time
from datetime import timedelta
from django.db import transaction
from dpq.queue import AtLeastOnceQueue
from dpq.decorators import repeat
def foo(queue, job):
transaction.on_commit(lambda: 1/0)
print('foo {}'.format(job.args))
def timer(queue, job):
print(time.time() - job.args['time'])
d... | StarcoderdataPython |
4829892 | <filename>20-no-commitment/plugins-src/words1.py
import sys, re, string
def extract_words(path_to_file):
"""
Takes a path to a file and returns the non-stop
words, after properly removing nonalphanumeric chars
and normalizing for lower case
"""
if type(path_to_file) is not str or not path_to_fi... | StarcoderdataPython |
3335486 | <reponame>victorjourne/ezibpy
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# ezIBpy: a Pythonic Client for Interactive Brokers API
# https://github.com/ranaroussi/ezibpy
#
# Copyright 2015-2019 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance... | StarcoderdataPython |
107774 | <reponame>Saicharan67/Interview-Coding-Questions
"""
Given an Array of non-negative intergers find if we can divide the array into two sub arrays of equal sum
"""
dp = ([[False for i in range(50)]
for i in range(10)])
def EqualSumDp(a, n):
s = sum(a)
if s & 1:
return False
s = s//2
f... | StarcoderdataPython |
147497 | <gh_stars>10-100
import csv
symptomlist = ['suicidal','hallucinations auditory','irritable mood','agitation']
disease_ = []
disease_list = []
for s in symptomlist:
with open("bucketmap.csv","rb") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if s in row:
disease_.append((row[0],s))
dis... | StarcoderdataPython |
1677920 | <gh_stars>10-100
from .modules import Module, Dropout
| StarcoderdataPython |
185858 |
from opymize import Variable, LinOp
from opymize.linear.sparse import idxop, einsumop
import numba
import numpy as np
from numpy.linalg import norm
try:
import opymize.tools.gpu
from opymize.tools.gpu import prepare_kernels
from pkg_resources import resource_stream
except:
# no cuda support
pass
... | StarcoderdataPython |
50526 | <filename>modules/sed.py
import re
import string
from util.esc import unescape
"""
The 'tr' implementation was based on github:ikegami-yukino/python-tr.
"""
all = [chr(i) for i in range(256)]
def mklist(src):
src = src.replace("\\/", "/") \
.replace("[:upper:]", string.ascii_uppercase) \
.replace("[:lower:]", ... | StarcoderdataPython |
3363177 | <filename>distro/src/bin/atlas_stop.py
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the... | StarcoderdataPython |
3228799 | import numpy as np
import tensorflow as tf
from unittest import TestCase
from .context import conv_gp
from conv_gp.views import RandomPartialView, FullView
from conv_gp.mean_functions import PatchwiseConv2d, Conv2dMean
class TestMeanFunction(TestCase):
def test_patchwise_conv(self):
filter_size = 5
... | StarcoderdataPython |
82060 | <reponame>faragher/LibreSignage
#!/usr/bin/env python3
#
# Main test unit class.
#
import requests;
from requests.models import Response;
from typing import Callable, Dict, Any, List;
from resptypes import RespVal;
from uniterr import *;
import json;
import sys;
import re;
class Unit:
# HTTP methods.
METHOD_GET: s... | StarcoderdataPython |
3306935 | # Copyright 2020 Curtin University
#
# 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 writi... | StarcoderdataPython |
57323 | """test_cvvidproc.py
First, shows image of ISCO pump setup, closes when user clicks spacebar
Second, shows first frame of video of inner stream, closes when user clicks spacebar
Third, computes background of samples video. Should look like first frame^ w/o objects.
"""
import time
import cv2
import cvvidproc
import s... | StarcoderdataPython |
3295784 | from pepmass.glycomass import GlycanNode
from print_tree import print_tree
class print_glycan_struct(print_tree):
def __init__(self, glycan, **kwargs):
if isinstance(glycan, str):
glycan = GlycanNode.from_str(glycan)
super(print_glycan_struct, self).__init__(glycan, **kwargs)
... | StarcoderdataPython |
74165 | <gh_stars>0
# -*- coding: utf-8 -*-
import base64
from marshmallow import Schema, post_load, fields
from fuocore.schemas import SongSchema
from fuocore.utils import elfhash
SOURCE = 'local'
class EasyMP3MetadataSongSchema(Schema):
"""EasyMP3 metadata"""
url = fields.Str(required=True)
title_list = fie... | StarcoderdataPython |
1797441 | #! /usr/bin/env python
#coding=utf-8
from setuptools import setup
import linciclient
setup_args = {
'name': "linciclient",
'version': linciclient.__version__,
'description': "linci client tools",
'long_description': "linci client tools for ",
'author': linciclient.__author__,
'author_email': l... | StarcoderdataPython |
1714725 | <reponame>langrenn-sprint/race-service
"""Module for raceplan commands."""
from datetime import date, datetime, time, timedelta
from typing import Any, Dict, List, Tuple, Union
from race_service.models import IndividualSprintRace, Raceplan
async def calculate_raceplan_individual_sprint( # noqa: C901
event: dict... | StarcoderdataPython |
31582 | # pyright: reportUnknownMemberType=false
import logging
import zipfile
from pathlib import Path
from typing import Dict
import requests
from us_pls._config import Config
from us_pls._download.interface import IDownloadService
from us_pls._download.models import DatafileType, DownloadType
from us_pls._logger.interfac... | StarcoderdataPython |
1662578 | <gh_stars>0
import unittest
import numpy as np
import numpy.testing as tst
import splearn as spl
class TestSp(unittest.TestCase):
def setUp(self):
self.data = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]], dtype='float6... | StarcoderdataPython |
3385027 | import sys
import zipfile
import os, os.path
class TA98ScrapedData(object):
def __init__(self, scraped_zipfile):
self.scraped_zipfile = scraped_zipfile
def __enter__(self):
self.zfile = zipfile.ZipFile(self.scraped_zipfile)
self.ids = ['A'+y for y in
(x[3:].split(' ')[... | StarcoderdataPython |
67315 | <gh_stars>0
# Copyright 2019 New Vector Ltd
#
# 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 ... | StarcoderdataPython |
11156 |
def compareMetaboliteDicts(d1, d2):
sorted_d1_keys = sorted(d1.keys())
sorted_d2_keys = sorted(d2.keys())
for i in range(len(sorted_d1_keys)):
if not compareMetabolites(sorted_d1_keys[i], sorted_d2_keys[i], naive=True):
return False
elif not d1[sorted_d1_keys[i]] == d2[sorted_... | StarcoderdataPython |
102565 | #!/usr/bin/env python
from __future__ import division
"""@package etddf
ROS interface script for delta tiering filter
Filter operates in ENU
"""
from etddf.delta_tier import DeltaTier
import rospy
import threading
from minau.msg import ControlStatus
from etddf.msg import Measurement, MeasurementPackage, NetworkEsti... | StarcoderdataPython |
1704397 | # -*- coding: utf-8 -*-
from string import Template
showfun = '''
<li class= "optitem" width="100%%">
<div style="float: left; width: 20px"> </div>
<a onclick="server.spring()" python="%s" href="#" width="100%%">%s</a>
</li>
'''
#hr = '''<HR>'''
jsonlib = r'''
if (!this.JSON) {
this.JS... | StarcoderdataPython |
1618444 | # -*- coding:utf-8 -*-
# Create by 27
# @Time : 2020/3/1 02:23
__author__ = '27'
class NoneLocal:
def __init__(self, v):
self.v = v
n = NoneLocal(1)
| StarcoderdataPython |
1746803 | <filename>sztuczna_inteligencja/1-lab/picture_row.py
def howManyHaveToFlip(list, windowSize):
oneSymbol = 1
leastFlips = len(list)
OnesInList = 0
for x in list:
if x == oneSymbol:
OnesInList += 1
OnesInWindow = 0
for i in range(windowSize):
if list[i] == oneSymbol:
... | StarcoderdataPython |
1621248 | <gh_stars>1-10
from . import (pp, Session)
from ..db.database import get_db
from .base import CRUDBase
from ..models.models_patch import Patch
from ..schemas.schemas_patch import PatchCreate, PatchUpdate
class CRUDPatch(CRUDBase[Patch, PatchCreate, PatchUpdate]):
pass
patch = CRUDPatch(Patch)
| StarcoderdataPython |
108123 | <filename>backend/app/utils/get_param.py
from flask_restful import request, abort
def get_param(param_name, default, is_valid, to_value, error_message):
param_string = request.args.get(param_name)
if param_string is None:
param_string = default
elif not is_valid(param_string):
abort(400, m... | StarcoderdataPython |
1720235 | <gh_stars>10-100
"""
Reference Compositions
=======================
This page presents the range of compositions within the reference compositon database
accessible within :mod:`pyrolite`. It's currently a work in progress, but will soon
contain extended descriptions and notes for some of the compositions and as... | StarcoderdataPython |
1607158 | <reponame>carlsummer/python_developer_tools
# !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:4/29/2021 8:41 PM
# @File:time_utils
import datetime
import time
def get_time_stamp():
"""获取毫秒级的时间"""
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y... | StarcoderdataPython |
4841837 | <gh_stars>1-10
from scipy.fft import fft, fftfreq
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from scipy.signal import hann
# Number of sample points
N = 1024
# sample spacing
Fs = 48000
T = 1.0 / Fs
#X axis
x = np.linspace(0.0, N*T, N, endpoint=False)
#Signal
y = np.cos(2.0*np.pi*x*500... | StarcoderdataPython |
3221156 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""High-level interface to a opus decoder functions"""
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright (c) 2012, SvartalF'
__license__ = 'BSD 3-Clause License'
import opuslib.api.decoder
import opuslib.api.encoder
import opuslib.api.ctl
import opuslib.constan... | StarcoderdataPython |
1735686 | <reponame>raminjafary/ethical-hacking<filename>src/14 keylogger/keylogger_3.py
#!/usr/bin/python
import pynput.keyboard
import threading
log = ""
def process_key_press(key):
global log
try:
log = log + str(key.char)
except AttributeError:
if key == key.space:
log = log + " "
else:
log = log +" " + st... | StarcoderdataPython |
17774 | <reponame>HangeZoe/django-todo-list<filename>todolist/wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todolist.settings')
application = get_wsgi_application()
| StarcoderdataPython |
142254 | <reponame>Wanghp119/py-st-dbscan
from datetime import timedelta
from geopy.distance import great_circle
def st_dbscan(df, spatial_threshold, temporal_threshold, min_neighbors):
"""
Python st-dbscan implementation.
INPUTS:
df={o1,o2,...,on} Set of objects
spatial_threshold = Maximum ... | StarcoderdataPython |
107962 | <gh_stars>1-10
import argparse
import numpy as np
import os
import pandas as pd
def main(num_tasks_all,
datasets,
algorithms,
num_seeds,
num_init_tasks,
num_epochs,
save_frequency,
results_root):
if len(num_tasks_all) == 1:
num_tasks_all = num_t... | StarcoderdataPython |
3229940 | <filename>backend/user_application/sources/serializers/user_serializers.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField()
username = serializers.CharField()
email = serializers.EmailField()
date_joined = serializers.DateTimeField()
... | StarcoderdataPython |
1653431 | # Provide an "eval()" service over BLE UART.
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_circuitplayground import cp
import time
ble = BLERadio()
uart = UARTService()
advertisement = Pro... | StarcoderdataPython |
4818308 | #!/usr/bin/env python
"""
Copyright (c) 2011, <NAME>, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list o... | StarcoderdataPython |
1724808 | <gh_stars>0
from kivy.uix.textinput import TextInput
from kivy.properties import NumericProperty
import math
class IntEntry(TextInput):
value = NumericProperty(0.0)
def __init__(self, low=-math.inf, high=math.inf, **kwds):
if low >= 10:
# Because otherwise we couldn't ever type the first ... | StarcoderdataPython |
3274357 | """Calculations with grid-aware data sets."""
import xgcm
def calculate_moc(ds, region=""):
"""Calculate the MOC.
Parameters
----------
ds : xarray dataset
A grid-aware dataset as produced by `xorca.lib.preprocess_orca`.
region : str
A region string. Examples: `"atl"`, `"pac"`, ... | StarcoderdataPython |
80679 | <reponame>Octavian-ai/synthetic-graph-data<gh_stars>10-100
from basic_types import NanoType
class Style(NanoType[str]):
pass | StarcoderdataPython |
159659 | """
Reinforcement Learning Using Q-learning, Double Q-learning, and Dyna-Q.
Copyright (c) 2020 <NAME>
References
----------
- Based on project 7 in the Georgia Tech Spring 2020 course "Machine Learning
for Trading" by Prof. <NAME>.
- Course: http://quantsoftware.gatech.edu/CS7646_Spring_2020
- Project: http://quant... | StarcoderdataPython |
1604118 | # -*- coding: utf-8 -*-
'''
The main test runner script.
Usage: ::
python run_tests.py
Skip slow tests
python run_tests.py fast
When there's no Internet
python run_tests.py no-internet
'''
from __future__ import unicode_literals
import nose
import sys
def main():
args = get_argv()
success = nose.r... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.