id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3342123 | # 准备运行示例:PythonClient / multirotor / hello_drone.py
import dronesim as airsim
import time
import numpy as np
from app.driver.cross import Cross
from app.vision.number import Number
import math
import cv2
t1 = time.time()
# 连接到AirSim模拟器
client = airsim.VehicleClient()
client.connection()
uav = airsim.VehicleMotion(c... | StarcoderdataPython |
3325701 | <filename>day_21/solution.py
def name(f):
return f
def wrap(*a, **kw):
res = f(*a, **kw)
res.name = f.__qualname__ + "(" + ", ".join(map(repr, a)) + ")"
return res
return wrap
def ident(xs, **_):
return xs
@name
def rotate(steps, direction="right"):
if steps == 0:
... | StarcoderdataPython |
3203967 | <reponame>YiqunPeng/leetcode_pro
class Solution:
def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
"""Hash table.
Running time: O(r) where r == len(reservedSeats).
"""
rd = {}
for i, j in reservedSeats:
if 2 <= j <= 9:
... | StarcoderdataPython |
3326654 | <filename>my-loop-ex1.py
#!/usr/bin/env python
b_list = range(1, 50)
for i in b_list:
if i == 13:
continue
print i
if i == 39:
break
| StarcoderdataPython |
3250944 | <filename>common/nets/net_disc.py
# © 2021 Nokia
#
# Licensed under the BSD 3 Clause license
# SPDX-License-Identifier: BSD-3-Clause
import sys
sys.path.append('../common')
from defaults import *
import utils
import torch
# ==============================================================================
# Settings ... | StarcoderdataPython |
153211 |
# from preprocess import *
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import to_categorical
from keras.models import load_model
from preprocess_spectrogram import *
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Fi... | StarcoderdataPython |
130120 | """Module containing the authentication API of the v1 API."""
from typing import Dict
from flask.helpers import url_for
from flask.views import MethodView
from dataclasses import dataclass
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
current_user,
)
from .root import API_V1
... | StarcoderdataPython |
3327095 | <reponame>dreinq/DeepQ
import multiprocessing as mp
from logging import Logger
from typing import Tuple
import torch
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from MCQ.datasets import SiftLike, Enumerate
from MCQ.envs import Env
from MCQ.utils import Saver
from MCQ.utils.runti... | StarcoderdataPython |
1695877 | <reponame>Lucino772/pymojang<gh_stars>1-10
import unittest
import mojang
from mojang.account.structures.base import (
NameInfoList,
UUIDInfo,
NameInfo,
)
from mojang.account.structures.profile import UnauthenticatedProfile
from mojang.account.structures.session import Cape, Skin
class TestMojangAPI(unitt... | StarcoderdataPython |
1708000 | import importlib
import pytest
class TestSSLFailure(object):
@pytest.mark.run(order=-1)
def test_ssl_failure(self, monkeypatch):
import ssl
monkeypatch.delattr(ssl, "PROTOCOL_TLSv1", raising=True)
import stomp.transport as t
importlib.reload(t)
assert t.DEFAULT_SSL_VER... | StarcoderdataPython |
3361872 | import random
from jogador import Jogador
class Aleatorio(Jogador):
def __init__(self, nome):
return super().__init__(nome)
def deveComprar(self, propriedade):
return self.temSaldoPositivo() and self.temProbabilidade()
def temProbabilidade(self):
return random.randint(0, 2) > ... | StarcoderdataPython |
179920 | import pandas as pd
import inspect
import unittest
import numpy as np
'''
The general.unique take a array-like object and return the unique values in it. To test this we simply pass in different lists where some
of the values are not unique, and check if general.unique returns the right values.
From documentation:... | StarcoderdataPython |
1659911 | import typing
import bleach
# import markdown2
from nasse import config, logging
# Source: en.wikipedia.org/wiki/Whitespace_character
# Note: BRAILLE PATTERN BLANK, HANGUL FILLER, <NAME>, <NAME>LER and HALFWIDTH HANGUL FILLER are also refered here as "whitespaces" while they aren't according to the Unicode standard.
W... | StarcoderdataPython |
3208493 | <reponame>harisankarh/NeMo
# Copyright (c) 2019 NVIDIA Corporation
from nemo.backends.pytorch.nm import DataLayerNM
from nemo.core.neural_types import *
from nemo.core import DeviceType
import torch
from .datasets import BertPretrainingDataset
class BertPretrainingDataLayer(DataLayerNM):
@staticmethod
def cr... | StarcoderdataPython |
3378401 | from typing import Callable, Iterable
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.linear_model import Ridge
from sklearn.metrics import r2_score
from sklearn.preprocessing import LabelBinarizer
from rvfln.activation import ActivationFunction, LeakyReLU
from ... | StarcoderdataPython |
112855 | import cv2
import gc
import numpy as np
from ctypes import *
__all__ = ['darknet_resize']
class IMAGE(Structure):
_fields_ = [("w", c_int),
("h", c_int),
("c", c_int),
("data", POINTER(c_float))]
lib = CDLL("darknet/libdarknet.so", RTLD_GLOBAL)
resize_image = li... | StarcoderdataPython |
105388 | <filename>appTests/TwitterCompetitionsBotTests.py
import unittest
import mock
from unittest.mock import call
from app.freemiumwebapp.adminConstants import AdminConstants
from app.freemiumwebapp.twitterHook import TwitterHook
from app.freemiumwebapp.TwitterCompetitionsBot import TwitterCompetitionsBot
class TwitterCom... | StarcoderdataPython |
3326062 | from dominion_object_model import object_model
class GameClient(object_model.GameClient):
"""Game represents the specific game domain
In this case Dominion
"""
def __init__(self, game):
self.game = game
def play_action_card(self, card_type):
return self.game.play_action_card(car... | StarcoderdataPython |
1778071 | <reponame>chokoswitch/stellarstation-api
# Copyright 2019 Infostellar, 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 requir... | StarcoderdataPython |
3207294 | <reponame>einarnn/pyang-plugins
"""YANG output plugin"""
import optparse
import re
from pyang import plugin
from pyang import util
from pyang import grammar
def pyang_plugin_init():
plugin.register_plugin(StripPlugin())
class StripPlugin(plugin.PyangPlugin):
def add_output_format(self, fmts):
fmts['... | StarcoderdataPython |
1690699 | import datetime
from .base import BandoriObject
###############################################################################
# Bandori Database models
class DCard(BandoriObject):
'''
Represents a bang dream card
'''
def __init__(self, data: dict, id_name='cardId', region='en/'):
super().__... | StarcoderdataPython |
1666427 | import uuid
def get_mac():
mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac = '-'.join(mac_num[i: i + 2] for i in range(0, 11, 2))
return mac
print (get_mac()) | StarcoderdataPython |
1785606 | import subprocess
import tempfile
import os
def _exec_notebook(path):
with tempfile.NamedTemporaryFile(suffix=".ipynb") as fout:
args = ["jupyter", "nbconvert", "--to", "notebook", "--execute",
"--ExecutePreprocessor.timeout=None",
"--output", fout.name, path]
subpro... | StarcoderdataPython |
3291816 | <reponame>hurek/peeker_bot
from telegram.ext import CallbackQueryHandler, CommandHandler, ConversationHandler, Filters, MessageHandler
from conversations.announce import announce, send_announce
from conversations.conv_utils import ANNOUNCE, CHAT_TIMEOUT, STORE_ADDRESS, WAIT_FEEDBACK, cancel, \
chat_timeout
from co... | StarcoderdataPython |
1769629 | <gh_stars>0
import scrapy
import re
from skindl.items import SkinItem
class MinecraftskinsSpider(scrapy.Spider):
name = 'minecraftskins'
allowed_domains = ['www.minecraftskins.net']
start_urls = ['http://www.minecraftskins.net/']
def parse(self, response):
for content in response.xpath('//div[... | StarcoderdataPython |
161756 | # Generated by Django 2.0 on 2019-07-07 02:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pages', '0005_accessanalysis'),
]
operations = [
migrations.CreateModel(
name='CategoryTools',
... | StarcoderdataPython |
3273371 | <gh_stars>10-100
# The MIT License (MIT)
#
# Copyright (c) 2021 NVIDIA CORPORATION
#
# 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 righ... | StarcoderdataPython |
1796676 | <filename>tests/test_lut.py
from aetherling.modules.lut_any_type import DefineLUTAnyType
from magma import *
from magma.bitutils import *
import fault
from aetherling.helpers.fault_helpers import compile_and_run
import builtins
def test_lut_11_13():
width = 11
numOut = 13
T = Array[width, BitOut]
init ... | StarcoderdataPython |
1797832 | import numpy as np
def get_tree_slow(sorted_indices, adj):
block = []
treeNumber = {}
nTrees = 0
for coordinate in sorted_indices:
neighbors = np.nonzero(adj[coordinate])[0]
nn = np.intersect1d(neighbors, block)
neighTrees = set()
continueFlag = False
for neigh in... | StarcoderdataPython |
3235283 | <filename>gpstec/gpslos.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 20 12:06:16 2020
@author: <EMAIL>
"""
import numpy as np
import os
import h5py
from pyGnss import gnssUtils as gu
from pyGnss import scintillation
from datetime import datetime
import warnings
from argparse import ArgumentParser
war... | StarcoderdataPython |
3325483 | <gh_stars>0
import numpy as np
import pytest
from lagom import Seeder
from lagom.core.multiprocessing import BaseWorker
from lagom.core.multiprocessing import BaseMaster
from lagom.core.multiprocessing import BaseIterativeMaster
def naive_primality(integer):
r"""Naive way to test a prime by iterating over all ... | StarcoderdataPython |
154998 | import logging
import synapse.lib.cache as s_cache
logger = logging.getLogger(__name__)
class Triggers:
def __init__(self):
self._trig_list = []
self._trig_match = s_cache.MatchCache()
self._trig_byname = s_cache.Cache(onmiss=self._onTrigNameMiss)
def clear(self):
'''
... | StarcoderdataPython |
123174 | import glob
import random
training_rate = 0.9999
val_rate = 0.0001
def find_files(path, pattren="*.wav"):
filenames = []
for filename in glob.iglob(f'{path}/**/*{pattren}', recursive=True):
filenames.append(filename)
return filenames
def create_metadata(path="datasets"):
wav_lists = find_fi... | StarcoderdataPython |
1718915 | <reponame>JosephLutz/serialCommTest<filename>serialData.py<gh_stars>0
# serialData
from OrionPythonModules import serial_settings
from msgMonitor import CREATE_SERIAL_PORT
from msgMonitor import PORT_OPENED
from msgMonitor import PORT_CLOSED
from msgMonitor import REPORT_DATA_RECIEVED
import threading
import serial
im... | StarcoderdataPython |
130012 | # -*- coding: utf-8 -*-
# mypy: ignore-errors
import jax.numpy as jnp
import numpy as np
import tinygp
def check_noise_model(noise, dense_rep):
random = np.random.default_rng(6675)
np.testing.assert_allclose(noise.diagonal(), jnp.diag(dense_rep))
np.testing.assert_allclose(noise + np.zeros_like(dense_r... | StarcoderdataPython |
1689819 | from __future__ import print_function
import torch
import torch.nn as nn
class Normalization(nn.Module):
def __init__(self, mean, std):
super(Normalization, self).__init__()
self.mean = mean.clone().detach()
self.std = std.clone().detach()
def forward(self, img):
# normalize i... | StarcoderdataPython |
1759631 | """
curso Python 3 - Exercício Python #020
Um professor quer sortear a ordem de apresentaçao dos seus quatro alunos,
faça um programa que ajude ele, lendo o nome dos alunos e listando a ordem.
25.03.2021 - <NAME>
"""
from random import shuffle
a1 = str(input('Digite o nome do aluno 1 '))
a2 = str(input... | StarcoderdataPython |
187453 | <reponame>ConnorDoyle/CPU-Manager-for-Kubernetes
# Copyright (c) 2017 Intel Corporation
#
# 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
#
#... | StarcoderdataPython |
1712989 | <filename>src/modelpath.py
from functools import reduce
import re
class ModelPath:
R = re.compile(r"[\/\\]")
EXTENSION = ".mdl"
def __init__(self, key):
self.key = key
self.models = []
self.subpaths = {}
def addSubPath(self,subdir):
self.subpaths[subdir.key] = subd... | StarcoderdataPython |
1609502 | <gh_stars>0
import pathlib
import subprocess
import pytest
official_examples = [
(
"tutorials/mnist_pytorch",
"tutorials/mnist_pytorch/const.yaml",
),
(
"tutorials/fashion_mnist_tf_keras",
"tutorials/fashion_mnist_tf_keras/const.yaml",
),
(
"tutorials/imagen... | StarcoderdataPython |
1782962 | from . import astree
from .lexer import Lexer
from . import tok
# rules:
# factor: INTEGER | variable
# value: factor | paren | (PLUS | MINUS) value
# paren: LPAREN expr RPAREN
# power: value (POW value)*
# mul: power ((MUL | DIV) power)*
# addition: mul ((PLUS | MINUS) mul)*
# expr: additon
# pascal rules
# program:... | StarcoderdataPython |
1742679 | <gh_stars>0
#!/usr/bin/env python
"""
Test routine for SEACAS exodus.py module
"""
import exodus
DATABASE_PATH = "baseline.g"
# Test outputing c-type arrays and numpy arrays
ARRAY_TYPES = ['ctype', 'numpy']
for array_type in ARRAY_TYPES:
EXO = exodus.exodus(DATABASE_PATH, array_type=array_type)
print("Exodus... | StarcoderdataPython |
1642021 | from rdflib.term import URIRef
from rdflib.namespace import DefinedNamespace, Namespace
class DCTERMS(DefinedNamespace):
"""
DCMI Metadata Terms - other
Generated from: https://www.dublincore.org/specifications/dublin-core/dcmi-terms/dublin_core_terms.ttl
Date: 2020-05-26 14:20:00.590514
"""
... | StarcoderdataPython |
1653502 | <reponame>ralbuyeh-figure/saint
import torch
from torch import nn
from models import SAINT
from data_openml import data_prep_openml,task_dset_ids,DataSetCatCon
import argparse
from torch.utils.data import DataLoader
import torch.optim as optim
from utils import count_parameters, classification_scores, mean_sq_error
fr... | StarcoderdataPython |
1732255 | ### SCIPY Y MATPLOTLIB
import numpy as np
#from scipy.special import jn
# ejemplo con funcion Bessel (foto de Rosalind Franklin)
#x = np.linspace(xmin, xmax, npts)
#layers = np.array([jn(i, x)**2 for i in range(nlayers)])
#maxi = [(np.diff(np.sign(np.diff(layers[i,:]))) < 0).nonzero()[0] + 1
# ... | StarcoderdataPython |
3222331 | from .anime import *
from .user import *
from .library import *
from .manga import *
from .drama import *
from .auth import *
from .mappings import *
class Kitsu:
"""
:ivar KitsuAnime anime: Instance interface for the Kitsu Anime endpoints
:ivar KitsuUser user: Instance interface for the Kitsu Use... | StarcoderdataPython |
4823453 | import numpy as np
from scipy.signal import convolve
def gbp(img):
g1 = np.array([[-1,0,1]])
g2 = np.array([[-1],[0],[1]])
g3 = np.array([[0,0,1],[0,0,0],[-1,0,0]])
g4 = np.array([[-1,0,0],[0,0,0],[0,0,1]])
rg1 = convolve(img, g1, mode="same")
rg2 = convolve(img, g2, mode="same"... | StarcoderdataPython |
1646361 | <filename>qufilab/indicators/stat.py
"""
@ Qufilab, 2020.
@ <NAME>
Python interface for statistics indicators.
"""
import numpy as np
from qufilab.indicators._stat import *
def std(data, periods, normalize = True):
"""
.. Standard Deviation
Parameters
----------
data : `ndarray`
An arr... | StarcoderdataPython |
99362 | <filename>Codes/Data_Structures/Week_2/Polynomial.py
'''
# 一元多项式的乘法与加法运算
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零
项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字
间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 3... | StarcoderdataPython |
4824935 | # Copyright 2019 <NAME>
#
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
from collections import OrderedDict
from copy import deepcopy
import time
import pytest
import ... | StarcoderdataPython |
1618290 | from django.urls import path
from . import views
from . import apiviews
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
... | StarcoderdataPython |
3233398 | # Generated by Django 3.2.8 on 2022-01-29 13:18
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Organisatie',
fields=[
... | StarcoderdataPython |
164704 | <reponame>JoshZero87/site<filename>contacts/forms.py<gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
class PhoneOptOutUploadForm(forms.Form):
csv_file = forms.FileField()
| StarcoderdataPython |
4806332 | """Tracing function and controls"""
import inspect
import linecache
import re
from copy import copy
from types import FrameType, FunctionType, ModuleType
from typing import Any, Dict, List, Optional, Tuple, Callable
from .complexity import is_complexity_tracing_enabled
from .memory_footprint import MemoryFootprint
f... | StarcoderdataPython |
896 | ###############################################################################
# @todo add Pilot2-splash-app disclaimer
###############################################################################
""" Get's KRAS states """
import MDAnalysis as mda
from MDAnalysis.analysis import align
from MDAnalysis.lib.mdamath ... | StarcoderdataPython |
1717103 | <filename>src/simmate/toolkit/transformations/coordinate_perturation_ordered.py
# -*- coding: utf-8 -*-
from simmate.toolkit.transformations.base import Transformation
class CoordinateOrderedPerturbation(Transformation):
# known as "coordinate mutation" in USPEX
# site locations are mutated where sites with... | StarcoderdataPython |
3216898 | <reponame>glc12125/ML_for_trading
import numpy as np
class BagLearner(object):
def __init__(self, learner, kwargs={"leaf_size":1},bags=20,boost=False, verbose = False):
self.learner=learner
self.learner_list = []
for i in range(0,bags):
self.learner_list.append(learner... | StarcoderdataPython |
1658698 | <filename>project_name/utils/__init__.py
from .download_utils import download_from_yaml
from .transform_utils import multi_page_table_to_list, write_node_edge_item
__all__ = [
"download_from_yaml", "multi_page_table_to_list", "write_node_edge_item"
] | StarcoderdataPython |
3326812 | <reponame>ranwise/djangochannel
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from .models import Category, Course, Task, RealizationTask
from .serializers import (
CategorySerializ... | StarcoderdataPython |
1674033 | <reponame>asbe/PoseCNN<gh_stars>0
import tensorflow as tf
from tensorflow.python.framework import ops
from . import hard_label_op
@ops.RegisterShape("Hardlabel")
def _hard_label_shape(op):
output_shape = op.inputs[0].get_shape()
return [output_shape]
@ops.RegisterGradient("Hardlabel")
def _hard_label_grad(op, gr... | StarcoderdataPython |
14629 | from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import Image
@receiver(m2m_changed, sender=Image.users_likes.through)
def users_like_changed(sender, instance, **kwargs):
instance.total_likes = instance.users_likes.count()
instance.save()
| StarcoderdataPython |
4833249 | <reponame>elsholz/PyMarkAuth
class Lines:
def __init__(self, *args):
c = ['\n']
for arg in args:
c.extend(['\n', arg])
c.extend(['\n'])
self.elements = c
def __str__(self):
return ''.join(str(x) for x in self.elements)
class Paragraphs:
def __init__(se... | StarcoderdataPython |
1730781 | from pymongo import MongoClient
client = MongoClient()
db = client.crandom
joke = {
"content": "从前有只麋鹿,它在森林里玩儿,不小心走丢了。于是它给它的好朋友长颈鹿打电话:“喂…我迷路啦。”长颈鹿听见了回答说:“喂,我长颈鹿啦~”",
"answer": "",
# "author": "",
# "via": "豆瓣",
# "via_url": "http://jandan.net/",
"rank": 5,
}
result = db.joke.insert_one(joke)
... | StarcoderdataPython |
3324463 | from psypose.MEVA.meva.khrylib.utils.math import *
def get_body_qposaddr(model):
body_qposaddr = dict()
for i, body_name in enumerate(model.body_names):
start_joint = model.body_jntadr[i]
if start_joint < 0:
continue
end_joint = start_joint + model.body_jntnum[i]
st... | StarcoderdataPython |
1722446 | <gh_stars>0
from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
import mysql.connector
############# Helper functions
def delete_query(conn,cursor, table_name, col_name, ID):
query= "DELETE FROM {t} WHERE {c}={i}".format(t=table_name, c=col_name, i=ID)
cursor.exe... | StarcoderdataPython |
1683223 | from django.http import HttpResponseForbidden, HttpResponseBadRequest, HttpResponse, JsonResponse
from django.contrib.auth import authenticate, login, logout
from bin import functions as fn
# ===================================================================
# Users (/user)
# ========================================... | StarcoderdataPython |
3276385 | from __future__ import print_function
from builtins import str
from builtins import object
from lib.common import helpers
class Module(object):
def __init__(self, mainMenu, params=[]):
# Metadata info about the module, not modified during runtime
self.info = {
# Name for the module t... | StarcoderdataPython |
3314793 | # 10-11
# import json
#
# number = input('\nWhat\'s your favorite number? ')
# with open('number.json', 'w') as file:
# json.dump(int(number), file)
#
# with open('number.json') as file:
# number = json.load(file)
# print("I know your favorite number! It's " + str(number) + '.')
# 10-12
# import json
#
# try:... | StarcoderdataPython |
77943 | # pylint: disable=protected-access
import os
import re
import subprocess
import tempfile
import pytest
from dagster import AssetKey, AssetMaterialization, Output, execute_pipeline, pipeline, solid
from dagster.core.errors import DagsterInstanceMigrationRequired
from dagster.core.instance import DagsterInstance
from d... | StarcoderdataPython |
4804853 | import os
import os.path
import stat
import subprocess
import sys
import pytest
@pytest.fixture
def artifact_path():
dist_dir = os.path.join(os.path.dirname(__file__), 'dist')
if not os.path.isdir(dist_dir):
raise ValueError(f"dist directory \"{dist_dir}\" does not exist")
dist_files = [dir_entry... | StarcoderdataPython |
25439 | <gh_stars>1-10
import sys
from flask_appbuilder import SQLA, AppBuilder, ModelView, Model
from flask_appbuilder.models.sqla.interface import SQLAInterface
from sqlalchemy import Column, Integer, String, ForeignKey, Table
from sqlalchemy.orm import relationship
from flask import Flask
from flask_appbuilder.actions impor... | StarcoderdataPython |
3321630 | <gh_stars>0
from postgres_api import conn, cur, logger
from psycopg2 import Error
from datetime import datetime
def get_last_update(project_type):
try:
select_query = "SELECT timestamp from run_logs WHERE process_type = %s ORDER BY timestamp DESC LIMIT 1"
cur.execute(select_query, (project_type,)... | StarcoderdataPython |
3289429 | from retriever import benchmark_indexing, benchmark_querying
from reader import benchmark_reader
from utils import load_config
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--reader', default=False, action="store_true",
help='Perform Reader benchmarks')
parser.add_argume... | StarcoderdataPython |
3369645 | import numpy as np
import quaternion
import operator
def isqrt(n):
"""
Return the integer part of the square root of the input.
(math.isqrt from Python 3.8)
"""
n = operator.index(n)
if n < 0:
raise ValueError("isqrt() argument must be nonnegative")
if n == 0:
return 0
c... | StarcoderdataPython |
1679072 | import argparse
from fabric.api import *
from fabric.tasks import Task
from playback import __version__
class Common(Task):
"""
the common library for OpenStack Provisioning
:param user(str): the user for remote server to login
:param hosts(list): this is a second param
:param key_filename(str)... | StarcoderdataPython |
3212617 | <reponame>DBernardes/Macro-SPARC4-CCD-cameras<gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# Este codigo plota os valores do ruido de leitura encontrados
#pela biblioteca hyperopt em funcao do numero de iteracao.
#22/11/2019. <NAME>.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import ... | StarcoderdataPython |
1655449 | # Software License Agreement (BSD License)
#
# Copyright (c) 2012, <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 copyri... | StarcoderdataPython |
1739826 | <gh_stars>0
#!/usr/bin/env python
"""Tests for grr.lib.timeseries."""
from grr.lib import flags
from grr.lib import test_lib
from grr.lib import timeseries
class TimeseriesTest(test_lib.GRRBaseTest):
def makeSeries(self):
s = timeseries.Timeseries()
for i in range(1, 101):
s.Append(i, (i + 5) * 1000... | StarcoderdataPython |
4829927 | # !/usr/bin/python
# coding=utf-8
#
# @Author: LiXiaoYu
# @Time: 2013-10-17
# @Info: Const
#日志类型
LOG_SYSTEM = 1 # 系统日志
LOG_QUEUE = 2 # 队列日志
#日志级别
CRITICAL = 50 # 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样
ERROR = 40 # 一般错误: 一般性错误
WARNING = 30 # 警告性错误: 需要发出警告的错误
INFO = 20 # 信息: 程序输出信息
DEBUG = 10 # 调试: 调试信息
... | StarcoderdataPython |
1790688 | <gh_stars>0
def csWhereIsBob(names):
'''
input names - a list of strings
output is an integer which is the location of Bob
if Bob not present return -1
'''
if "Bob" not in names:
return -1
... | StarcoderdataPython |
3316204 |
import os
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from mpl_toolkits.axisartist.axislines import SubplotZero
# Reading results files
os.chdir(r'C:\Users\pietro\Desktop\MESS2021\testfolder')
techs = pd.read_csv('techinfo.csv',sep =';',index_col='timestamp',parse_... | StarcoderdataPython |
3362504 | from face_recognition import face_landmarks
from .settings import TYPES_OF_ENDPOINTS
def point_dividing_a_line_segment(A, B, offset_from_A):
"""
:param A: coordinates of the start point of a line in 2D Space ([x, y] or (x, y))
:type A: list - [] or tuple - ()
:param B: coordinates of the end point of... | StarcoderdataPython |
3324375 | <filename>qtile_extras/widget/upower.py<gh_stars>10-100
# Copyright (c) 2021 elParaguayo
#
# 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 th... | StarcoderdataPython |
3316844 | <filename>UDA/pytorch0.3/DAN/utils/data_load.py
import os
import numpy as np
from nibabel import load as load_nii
import nibabel as nib
from operator import itemgetter
#from libs.CNN.build_model import define_training_layers, fit_model
from operator import add
import torch
from torch.autograd import Variable
import h5p... | StarcoderdataPython |
1765205 | <reponame>bloxmove-com/TE_Simulations_Research_Group
from radcad.engine import Engine
from collections import namedtuple
RunArgs = namedtuple("RunArgs", "simulation timesteps run subset initial_state state_update_blocks parameters deepcopy drop_substeps")
Context = namedtuple("Context", "simulation run subset timeste... | StarcoderdataPython |
3234396 | <gh_stars>1-10
from ..P9_string_rotation import is_rotated_string, is_rotated_string_naive
def test_rotate_empty():
""" '' in '' is True by convention."""
s1, s2 = '', ''
assert is_rotated_string_naive(s1, s2)
assert is_rotated_string(s1, s2)
def test_rotate_one_element_true():
s1, s2 = 'a', 'a'... | StarcoderdataPython |
131425 | <reponame>wpreimes/ecmwf_models<filename>src/ecmwf_models/erainterim/download.py
# -*- coding: utf-8 -*-
"""
Module to download ERA Interim from terminal.
"""
from ecmwfapi import ECMWFDataServer
import argparse
import sys
from datetime import datetime, timedelta
import shutil
import os
import warnings
from ecmwf_mo... | StarcoderdataPython |
1777220 | from django.conf.urls import url, include
from .views import ModuleList
urlpatterns = [
url(r'^$', ModuleList.as_view(), name='module_list'),
]
| StarcoderdataPython |
1645816 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from collections.abc import Sequence
from random import random
from time import perf_counter, sleep
import numpy as np
import pandas as pd
import yaml
from sklearn.cluster import KMeans as CPUKMeans
from sklearn.datasets import make_blobs
from sklearn.metrics i... | StarcoderdataPython |
1604676 | <reponame>wuljchange/interesting_python
import numpy as np
if __name__ == "__main__":
"""
使用numpy模块来对数组进行运算
"""
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
print(x+y)
print(x*2)
nx = np.array(x)
ny = np.array(y)
print(nx*2)
print(nx+10)
print(nx+ny)
print(np.sqrt(nx))
pri... | StarcoderdataPython |
3325490 | <reponame>zseen/advent-of-code
import unittest
from typing import List
from enum import Enum
from copy import deepcopy
INPUT_FILE = "input.txt"
TEST_INPUT_FILE_LOOP = "test_input_loop.txt"
class Operation(Enum):
JUMP = "jmp"
ACCUMULATE = "acc"
NO_OPERATION = "nop"
class Instruction:
def __init__(se... | StarcoderdataPython |
4827130 | #!/usr/bin/env python
#
# Copyright (c) 2017 Palo Alto Networks, Inc. <<EMAIL>>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROV... | StarcoderdataPython |
3202827 | import logging.config
def configure_logger(level: str = "INFO") -> None:
logging.config.dictConfig(
{
"version": 1,
"formatters": {
"colored": {
"()": "colorlog.ColoredFormatter",
"format": "%(log_color)s%(message)s%(reset)s",... | StarcoderdataPython |
121297 | from torchtext import data
from torch.utils.data import DataLoader
from graph import MTInferBatcher, get_mt_dataset, MTDataset, DocumentMTDataset
from modules import make_translate_infer_model
from utils import tensor_to_sequence, average_model
import torch as th
import argparse
import yaml
max_length = 1024
def run... | StarcoderdataPython |
1672418 | #! python3
# factorialLog.py - Learning how to log program events
import logging, os
os.chdir('S:\\Documents\\GitHub\\ATBS\\Chapter_10')
#logging.disable(logging.DEBUG)
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of p... | StarcoderdataPython |
1795688 | <gh_stars>1-10
# Imports
import nextcord, json
from nextcord.ext import commands
from nextcord.ui import View, Select, button
from Functions.Embed import *
# Load Options.json as a dict
with open('Settings/Options.json') as Settings:
Options = json.load(Settings)
# Button array for the main help command embed
c... | StarcoderdataPython |
3286262 | from hive.envs.marlgrid import ma_envs
from hive.envs.marlgrid.marlgrid import MarlGridEnv
| StarcoderdataPython |
35573 | import numpy as np
class BoundBox:
"""
Adopted from https://github.com/thtrieu/darkflow/blob/master/darkflow/utils/box.py
"""
def __init__(self, obj_prob, probs=None, box_coord=[float() for i in range(4)]):
self.x, self.y = float(box_coord[0]), float(box_coord[1])
self.w, self.h =... | StarcoderdataPython |
1639393 | <filename>wifinator/aruba.py<gh_stars>0
#!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
import re
from threading import Lock
from requests import Session, HTTPError
from time import time
from xml.etree.ElementTree import XML, ParseError
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requ... | StarcoderdataPython |
53271 | import enum
import time
from collections import namedtuple
from dataclasses import dataclass, field
from typing import List, Dict, Any, Union, Tuple, Sequence, Callable, Optional
import gym
import numpy as np
from malib.utils.notations import deprecated
""" Rename and definition of basic data types which are corresp... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.