id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
4901849 | <filename>sound_classification/confusion_matrix.py
# -*- coding: utf-8 -*-
__author__ = 'lgeorge'
import argparse
import logging
import pylab
import numpy as np
from sklearn.metrics import confusion_matrix
def displayConfusionMatrix(aConfusion_matrix, labels=None):
#ax.set_xticklabels([''] + labels)
"""
:... | StarcoderdataPython |
6617177 | # Copyright (C) 2020 <NAME>
# 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, soft... | StarcoderdataPython |
4826250 | <filename>playAI.py
from MCTS import MCTS
from connect4.Connect4Game import Connect4Game, display
from connect4.Connect4Players import HumanConnect4Player
from connect4.tensorflows.NNet import NNetWrapper as NNet
from utils import dotdict
import numpy as np
if __name__ == '__main__':
goingFirst = True
folder =... | StarcoderdataPython |
78475 | <reponame>samhuairen/deepTools
import sys
import itertools
import numpy as np
import scipy.cluster.hierarchy as sch
import scipy.stats
import matplotlib as mpl
mpl.use('Agg')
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['svg.fonttype'] = 'none'
from deeptools import cm # noqa: F401
import matplotlib.pyplot as plt
im... | StarcoderdataPython |
5060135 | <filename>lib/solver.py
import pulp
import lib.entities as en
class Solver:
"""The solver class solves a problem on supply chain
"""
def __init__(self, supply_chain):
self._supply_chain=supply_chain
self._initialize()
def _initialize(self):
"""initializes the problem before so... | StarcoderdataPython |
3576017 | #!/usr/bin/env python
# FishStateMachine:
# Implementation of the finite state machine for SoFi (soft robotic fish)
#
# Node name: finite_state_machine
# Subscribed topics:
# - fish_pose
# - target_found
# - average_heading
# - average_pitch
# - average_dist
# - target_centroid (TODO)
# Published topics:
#... | StarcoderdataPython |
5129550 | import sys
__author__ = '<NAME>'
def p2(n):
"""
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do no... | StarcoderdataPython |
6440070 | """
Event action.
"""
import random
from muddery.events.base_event_action import BaseEventAction
class EventAttack(BaseEventAction):
"""
Event to start a combat.
"""
key = "EVENT_ATTACK"
def func(self, event, character):
"""
Start a combat.
"""
rand = random.rando... | StarcoderdataPython |
1865080 | from ArchicadDG import Rect
def rect_print(rect,title):
top=rect.GetTop()
left=rect.GetLeft()
right=rect.GetRight()
bottom=rect.GetBottom()
print "_____"+title+"_____"
print "top("+str(top)+")"
print "left("+str(left)+")"
print "right("+str(right)+")"
print "bottom("+str(bottom)+")... | StarcoderdataPython |
9676091 | import os
import secrets
from fastapi import Depends, FastAPI, HTTPException
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import HTTPBasic, HTTPBasicCredentials
# custom modules
from models.algebra import array
app = FastAPI(docs_url=None, ... | StarcoderdataPython |
8033761 |
import glob
#import os
import pandas as pd
colnames=['Ticker', 'Date', 'Open', 'High', 'Low', 'Close', 'Volume']
def pivotAndInterpolate(row,index,column,reIndex, interpolater,limiter, df):
dfOut = df.pivot_table(row, index, column)
dfOut.index = pd.to_datetime(dfOut.index, format='%Y%m%d')
... | StarcoderdataPython |
3567259 | import json
file = open('staff.json', 'r')
staffs = json.load(file)['data']
firstnames = {}
lastnames = {}
middlenames = {}
output = []
for staff in staffs:
if staff["firstname"].lower() not in firstnames.keys():
firstnames[staff["firstname"].lower()] = True
temp = {}
temp["id"] = staff["firstname"].lower()
... | StarcoderdataPython |
5177449 | # -*- coding: utf-8 -*-
"""
Created on Fri May 21 11:55:50 2021
@author: freeridingeo
"""
import os
from pathlib import Path
import numpy as np
import pandas as pd
import geopandas as gpd
from sentinelhub import BBoxSplitter, CRS
import rasterio
from rasterio.windows import Window, bounds as wind_bounds
from rasteri... | StarcoderdataPython |
5132228 | <reponame>Lee2532/airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.postgres_operator import PostgresOperator
from datetime import datetime, timedelta
import time
from datetime import datetim... | StarcoderdataPython |
12858612 | import unittest
from collections import OrderedDict
from dbcut.utils import sorted_nested_dict
def test_simple_dict_is_sorted():
data = {
"c": 1,
"a": 2,
"b": 3,
}
expected = OrderedDict([("a", 2), ("b", 3), ("c", 1)])
assert expected == sorted_nested_dict(data)
def test_nes... | StarcoderdataPython |
11220980 | <filename>Sorting_Algorithms/Insertion_sort_Ascending_and_descending.py<gh_stars>0
def insertionAscending(array):
l=len(array)
for i in range(1,l):
a=array[i]
j=i-1
while j>=0 and array[j]>a:
array[j+1]=array[j]
j-=1
array[j+1]=a
return array
def inse... | StarcoderdataPython |
6402198 | import numpy as np
ON_SEASON = [3, 4, 5, 6, 7, 8, 9]
ON_SEASON_2 = [
(np.datetime64('2017-04-02'), np.datetime64('2017-11-01')),
(np.datetime64('2018-03-29'), np.datetime64('2018-10-28')),
(np.datetime64('2019-03-20'), np.datetime64('2019-10-30')),
(np.datetime64('2020-07-23'), np.datetime64('2020-10-... | StarcoderdataPython |
11301319 | <gh_stars>10-100
# Generated by Django 1.11.2 on 2017-08-07 23:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("letters", "0004_auto_20170708_2222")]
operations = [
migrations.AddField(
model_name="letter",
name="note",
... | StarcoderdataPython |
4847374 | <filename>self_created_svm_linear_optimization_classification_prob.py
# This is a support vector machine algorithm written from scratch
# works for linear data sets
# by <NAME>
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
class Support_Vector_Machine:
def __init__(self, ... | StarcoderdataPython |
6628617 | <gh_stars>1-10
from django.test import TestCase
from custom.icds_reports.reports.service_delivery_dashboard_data import get_service_delivery_report_data
class TestServiceDeliveryData(TestCase):
def test_get_service_delivery_report_data_0_3(self):
get_service_delivery_report_data.clear('icds-cas', 0, 10,... | StarcoderdataPython |
6600413 | #copyright 2020 Huawei Technologies Co., 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 to ... | StarcoderdataPython |
8106013 | <filename>Chapter 08/Chap08_Example8.68.py
class Myfather(object):
def __init__(self):
super().__init__()
print("I am a Father class constructor")
def mydisplay_father(self):
print("I am a Father class instance method")
class Mymother(object):
def __init__(self):
super().__i... | StarcoderdataPython |
3385310 | from SpecImports import *
BattleCells = {}
CogData = []
ReserveCogData = []
| StarcoderdataPython |
1884185 | <reponame>adisbladis/geostore
from unittest.mock import MagicMock, patch
from geostore.api_keys import SUCCESS_KEY
from geostore.error_response_keys import ERROR_MESSAGE_KEY
from geostore.step_function_keys import DATASET_ID_KEY, VERSION_ID_KEY
from geostore.validation_summary.task import lambda_handler
from .aws_uti... | StarcoderdataPython |
6570732 | <filename>perspectivesx_project/django_auth_lti/backends.py
import logging
from time import time
import oauth2
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import PermissionDenied
from ims_lti_py.tool_p... | StarcoderdataPython |
3233278 | <filename>20_valid_parentheses.py<gh_stars>0
'''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that a... | StarcoderdataPython |
5148495 | from os import path
import subprocess
import anndata as ad
# import pandas as pd
import numpy as np
np.random.seed(42)
metric = 'asw_batch'
# metric_file = metric + '.tsv'
metric_file = metric + '.h5ad'
print(">> Running script")
out = subprocess.check_output([
"./" + metric,
"--input_prediction", 'resources... | StarcoderdataPython |
13035 | import pandas as pd
# Global variable to set the base path to our dataset folder
base_url = '../dataset/'
def update_mailing_list_pandas(filename):
"""
Your docstring documentation starts here.
For more information on how to proper document your function, please refer to the official PEP... | StarcoderdataPython |
8099195 | <filename>casepro/msgs/migrations/0008_messageaction.py
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import django.contrib.postgres.fields
from django.conf import settings
from django.db import migrations, models
def migrate_messageactions(apps, schema_editor):
MessageActionOld... | StarcoderdataPython |
3474441 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from six.moves import range
from keras import backend as K
from agents import DDQN
from memory import SimpleExperienceReplay, Buffer
from models import duel_atari_cnn as nn
from envs import Env
from utils impo... | StarcoderdataPython |
6433839 | from .test_paste import * | StarcoderdataPython |
6651806 | <reponame>adityagoel28/deployy
# Generated by Django 3.1.2 on 2022-02-01 16:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Home', '0003_vaccinecenterdetails_vaccinedetails'),
]
operations = [
migrations.AlterField(
model... | StarcoderdataPython |
89234 | <filename>libs/file/nxpy/core/file/__init__.py
from .file import *
| StarcoderdataPython |
341463 | <gh_stars>1-10
import multiprocessing
import os
import time
import traceback
from datetime import datetime
from multiprocessing import current_process
from multiprocessing.context import Process
from queue import Queue
from injector import inject
from pdip.base import Pdi
from pdip.configuration.models.application imp... | StarcoderdataPython |
11285248 | from vell import spell
def test_import():
assert 'check' in spell.__dict__.keys()
def test_check():
spell.check()
| StarcoderdataPython |
6611914 | # This sample tests for generic protocol variance consistency.
from typing import Protocol, TypeVar, Union
# pyright: strict
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2", bound=int)
_T3 = TypeVar("_T3", bytes, str)
_T1_co = TypeVar("_T1_co", covariant=True)
_T1_contra = TypeVar("_T1_contra", contravariant=True)
class ... | StarcoderdataPython |
4922722 | from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from model_utils import Choices
from model_utils.models import TimeStampedModel
from ..utils import markup
class Scrap(TimeStampedModel):
MARKUP_LANGUAGE = Choices(*markup.LAN... | StarcoderdataPython |
1913641 | <reponame>DanielJDufour/cambio<gh_stars>0
#-*- coding: utf-8 -*-
from unittest import main, TestCase
from cambio import add_param_to_class_instantiation
from cambio import find_all_named_parameters
from cambio import remove_class_definition
from cambio import remove_class_instantiation_parameter
from cambio import remo... | StarcoderdataPython |
1600788 | <reponame>karthikbhamidipati/reinforcement-learning<filename>algorithms/linear_wrapper.py
import numpy as np
class LinearWrapper:
"""
Wrapper for env to perform Linear Value function approximation
"""
def __init__(self, env):
"""
Constructor for LinearWrapper
:param e... | StarcoderdataPython |
1982986 | import sys
import click
from dataclasses import dataclass
from multiprocessing.context import AuthenticationError
from rich.console import Console
from rich.table import Table
from rich.text import Text
from pyrsched.rpc import RPCScheduler
from halo import Halo
PYRSCHED_LOGO = "[italic bold][#e20074]P[/#e20074][whi... | StarcoderdataPython |
1950331 | #!/usr/bin/env python
# coding: utf-8
# ___
#
# <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
# ___
# # Pandas Data Visualization Exercise
#
# This is just a quick exercise for you to review the various plots we showed earlier. Use **df3** to replicate the following plots.
# In[1... | StarcoderdataPython |
9656506 | import tensorflow as tf
import numpy as np
LR_A = 0.001
LR_C = 0.001
GAMMA = 0.9
TAU = 0.01
MEMORY_CAPACITY = 10000
BATCH_SIZE = 32
class DDPG(object):
def __init__(self, a_dim, s_dim, a_bound):
self.memory = np.zeros((MEMORY_CAPACITY, s_dim*2+a_dim+1), dtype=np.float32)
self.pointer = 0
self.memory_full ... | StarcoderdataPython |
8088262 | <reponame>LaurentAjdnik/pyqir
# Generated from MockLanguage.g4 by ANTLR 4.10.1
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
return [
4,0,8,56,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,... | StarcoderdataPython |
4841027 | # -*- encoding: utf-8 -*-
"""AMQP Specifications and Classes"""
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__since__ = '2011-09-23'
__version__ = '3.0.2'
__all__ = [
'body', 'decode', 'commands', 'constants', 'encode', 'exceptions', 'frame',
'header', 'heartbeat'
]
| StarcoderdataPython |
9696896 | """base_tiler"""
__version__ = '0.1' | StarcoderdataPython |
3576802 | <reponame>roemmele/answerquest<gh_stars>10-100
import os
import argparse
import json
import subprocess
def get_answer_annotated_data(questions, answer_sents, answers, scores,
min_score=0.0):
filtered_questions = []
filtered_answer_sents = []
for idx, (question,
... | StarcoderdataPython |
119761 | <filename>ooni/tests/test_utils.py<gh_stars>0
import os
from twisted.trial import unittest
from ooni.utils import log, generate_filename, net
class TestUtils(unittest.TestCase):
def setUp(self):
self.test_details = {
'test_name': 'foo',
'test_start_time': '2016-01-01 01:22:22'
... | StarcoderdataPython |
1735329 | <filename>django/rpg/main/models.py
from django.db import models
from datetime import datetime
import re
class UserManager(models.Manager):
def register_validator(self, post_data):
errors = {}
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if len(post_data['first... | StarcoderdataPython |
9774061 | class Pokemon():
"""A class to represent a Pokemon
Attributes
----------
name : str
the name of the pokemon
level : int
the pokemon level
hp : int
the current HP level of the pokemon
# """
generation = 'base'
def __init__(self, name, level, start_hp, energy_... | StarcoderdataPython |
6441616 | <filename>gesund_projekt/calories/migrations/0003_caloriefooddetail.py
# Generated by Django 4.0.1 on 2022-03-24 10:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('calories', '0002_caloriecategory_alter_calorieintake_... | StarcoderdataPython |
11341620 | from django.apps import AppConfig
class WordsConfig(AppConfig):
name = 'words'
| StarcoderdataPython |
9724130 | <filename>readtwice/models/input_utils.py
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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/L... | StarcoderdataPython |
8191989 | <reponame>bisnupriyasahu/cmssw
from __future__ import print_function
# Auto generated configuration file
# with command line options: stepALCA --datatier ALCARECO --conditions auto:run2_data -s ALCA:PromptCalibProdSiStripGains --eventcontent ALCARECO -n 1000 --dasquery=file dataset=/ZeroBias/Run2016C-SiStripCalMinBias-... | StarcoderdataPython |
11354643 | import numpy as np
import yaml
import collections
import torch
import json
from PIL import Image
import pandas as pd
from pathlib import Path
from .scene_dataset import SceneDataset
class RealSceneDataset(SceneDataset):
def __init__(self, root, n_objects=None, resize=(320, 240)):
self.root = Path(root)
... | StarcoderdataPython |
1833485 | <reponame>koll00/Gui_SM
# -*- coding:utf-8 -*-
#
# Copyright © 2011-2012 <NAME>
# Licensed under the terms of the MIT License
# (see SMlib/__init__.py for details)
"""
IPython v0.13+ client's widget
"""
# IPython imports
'''
try: # 1.0
from IPython.qt.console.rich_ipython_widget import RichIPythonWi... | StarcoderdataPython |
8172876 | <filename>apps/cowry_docdata/admin.py
from babel.numbers import format_currency
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.utils import translation
from .models import DocDataPaymentOrder, DocDataPayment, DocDataPaymentLogEntry
class DocDataPaymentLogEntryInine(admin.Tab... | StarcoderdataPython |
4839915 | __author__ = '<NAME>'
import roslib; roslib.load_manifest('aidu_gui')
from PySide import QtGui, QtCore
from PySide.QtGui import QApplication
from time import sleep
from window import Window
from ros_thread import ROSThread
class Manager:
"""
The manager for the application GUI. This internally handles all th... | StarcoderdataPython |
1844523 | # -*- coding: utf-8 -*-
from chainer import Chain
import chainer.functions as F
import chainer.links as L
class ImageCnn(Chain):
def __init__(self, input_channel, output_channel, filters, mid_units, n_label):
super(ImageCnn, self).__init__(
# input_channel: 1:白黒 3:RGB など
conv1=L.... | StarcoderdataPython |
6565302 | <gh_stars>1-10
import torch
from torchvision import transforms
import itertools
import numpy as np
from config import cfg
out_size = cfg.input_size
rct = transforms.Compose([transforms.ToPILImage(),
transforms.Resize((out_size,out_size)),
transforms.ToTensor()])
def ... | StarcoderdataPython |
5014494 | <gh_stars>1-10
import random
from debug import dump_func_name
import sys
import logging
import time
class noise(object):
# @dump_func_name
def __init__(self, ber, delay):
self.total_packets_sent = 0
self.total_errors = 0
self.logger = logging.getLogger('myapp')
... | StarcoderdataPython |
4916453 | import cv2
import numpy as np
#load image
img = cv2.imread('homography-test.jpg', cv2.IMREAD_COLOR)
#corners of book covers (before)
frontCoverPtsBefore = np.array([[32, 48], [279, 136], [247, 430], [39, 281]], dtype="float32")
backCoverPtsBefore = np.array([[279, 136], [474, 36], [463, 316], [247, 430]], dtype="floa... | StarcoderdataPython |
6596845 | <reponame>OpenRTDynamics/PythonAPI_Experiments<filename>openrtdynamics2/lang/signal_interface.py<gh_stars>0
from . import lang as dy
from . import block_prototypes as block_prototypes
from .diagram_core.signal_network.signals import Signal, UndeterminedSignal, BlockOutputSignal, SimulationInputSignal
from typing impor... | StarcoderdataPython |
4804443 | from django.urls import path
import wishlist.views as wishlist
app_name = 'wishlist'
urlpatterns = [
path('', wishlist.view, name='view'),
path('add/<pk>/', wishlist.wishlist_add, name='add'),
path('remove/<pk>/', wishlist.wishlist_add, name='remove'),
path('clear/', wishlist.clear, name='clear'),
] | StarcoderdataPython |
3206522 | """Common utils for the library."""
from typing import Optional
import torch as _torch
def mask_padded_values(xs: _torch.FloatTensor, n: _torch.LongTensor,
mask_value: float = -float('inf'),
mutate: bool = False):
"""Turns padded values into given mask value.
Arg... | StarcoderdataPython |
6681174 | <filename>arbitrage/private_markets/vircurex.py
from .market import Market, TradeException
import time
import requests
import hashlib
import random
from collections import OrderedDict
import config
import database
class PrivateVircurex(Market):
domain = "https://api.vircurex.com"
def __init__(self):
... | StarcoderdataPython |
9759131 |
class Config:
def __init__(self, path):
self.path = path
self.options = {}
self.votes = []
self.tunes = []
self.available_rcon_commands = []
self.rcon_commands = []
def read(self):
with open(self.path) as f:
lines = f.readlines()
... | StarcoderdataPython |
5019429 | import unittest
from lambda_tools import mapper
FAMOUS_FIVE = ['Dick', 'Julian', 'George', 'Anne', 'Timmy']
class StringFieldEntity:
hello = mapper.StringField()
class TestStringField(unittest.TestCase):
def test_simple_mapping(self):
result = mapper.parse(StringFieldEntity, { 'hello': 'world' })
... | StarcoderdataPython |
11289780 | #!/usr/bin/env python
#
# Example of how to analyse HLT objects using FWLite and pyROOT.
#
# adapted from PhysicsTools/PatExamples/bin/PatBasicFWLiteAnalyzer.py
from __future__ import print_function
import ROOT
import sys
from DataFormats.FWLite import Events, Handle
#-----------------------------------------------... | StarcoderdataPython |
8144005 | <reponame>WolfLink/qsearch<filename>qsearch/integrations.py<gh_stars>1-10
try:
from qiskit import QuantumCircuit
import qiskit
except ImportError:
qiskit = None
raise ImportError("Cannot import qiskit, please run pip3 install qiskit before importing qiskit code.")
import numpy as np
from .gates import... | StarcoderdataPython |
1937576 | # coding: utf-8
"""
Layered Insight Assessment, Compliance, Witness & Control
LI Assessment & Compliance performs static vulnerability analysis, license and package compliance. LI Witness provides deep insight and analytics into containerized applications. Control provides dynamic runtime security and analyti... | StarcoderdataPython |
3416739 | <reponame>shaunakv1/python_pillow_circular_thumbnail
from PIL import Image, ImageOps, ImageDraw
im = Image.open('avatar.jpg')
im = im.resize((120, 120));
bigsize = (im.size[0] * 3, im.size[1] * 3)
mask = Image.new('L', bigsize, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + bigsize, fill=255)
mask = mask.resize... | StarcoderdataPython |
1854590 | <filename>tests_functional/conftest.py
import pytest
from dialog_api.groups_pb2 import GROUPTYPE_GROUP, GROUPTYPE_CHANNEL
from google.protobuf import empty_pb2
from sdk_testing_framework.messaging import Messaging
from shared.data_generators import Generators
import os
import shutil
from shared.constants import Default... | StarcoderdataPython |
1860450 | <reponame>liweitianux/atoolbox<gh_stars>1-10
# -*- coding: utf-8 -*-
#
# <NAME>
# 2015/06/19
"""
Class Region for regions on the spherical surface.
Used in astronomy to select/define a certian region, e.g, DS9.
"""
import sys
class Region(object):
"""
Basic region class for regions on the spherical surface,... | StarcoderdataPython |
3267696 | <reponame>katyakats/mlrun
import http
import deepdiff
import pytest
import requests_mock as requests_mock_package
import mlrun.api.schemas
import mlrun.api.utils.clients.opa
import mlrun.config
import mlrun.errors
@pytest.fixture()
async def api_url() -> str:
api_url = "http://127.0.0.1:8181"
mlrun.mlconf.h... | StarcoderdataPython |
1863620 | <reponame>YuqianJiang/tl_shaping_experiments
import gym
import deepr
import cartpole_continuing
def main():
env = cartpole_continuing.CartPoleContinuingEnv()
act = deepr.learn(
env,
network='mlp',
method_type="shaping" #shielding, baseline
)
print("Saving model to cartpole_mod... | StarcoderdataPython |
3566588 | import os
import shutil
import numpy as np
import cmph
from diskarray import DiskVarArray
from deeputil import Dummy
DUMMY_LOG = Dummy()
class VarArray(DiskVarArray):
def __init__(self, dpath, mode="r+", growby=DiskVarArray.GROWBY, log=DUMMY_LOG):
super(VarArray, self).__init__(
dpath, dtype... | StarcoderdataPython |
3506182 | <reponame>kbase/IndexRunner
# -*- coding: utf-8 -*-
import json
import os
import unittest
from unittest.mock import patch
from IndexRunner.EventProducer import EventProducer
class EventProducerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_dir = os.path.dirname(os.path.abspath(_... | StarcoderdataPython |
3525500 | <filename>pip_services_runtime/data/__init__.py
# -*- coding: utf-8 -*-
"""
pip_services_runtime.data.__init__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Data module initialization
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for mor... | StarcoderdataPython |
4870146 | from typing import Iterable, Sequence
from .base import api_function
from .request import Request
__all__ = (
'Agent',
)
class Agent:
'''
Provides a shortcut of :func:`Admin.query()
<ai.backend.client.admin.Admin.query>` that fetches various agent
information.
.. note::
All methods i... | StarcoderdataPython |
6683760 | from datasets.base.factory_seed import BaseSeed
from datasets.types.data_split import DataSplit
class OpenImages_Seed(BaseSeed):
def __init__(self, root_path: str=None, data_split=DataSplit.Training | DataSplit.Validation | DataSplit.Testing):
if root_path is None:
root_path = self.get_path_fr... | StarcoderdataPython |
5167970 | <reponame>samuk/ros2-line-follower
import rclpy
from sensor_msgs.msg import Image
def callback(msg):
print('Received {}'.format(msg.header))
def main():
rclpy.init()
global node
node = rclpy.create_node('tester')
subscription = node.create_subscription(
Image, '/camera/image_raw', callba... | StarcoderdataPython |
1804654 | <reponame>Dimanitto/yatube
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from ..models import Group, Post
from http import HTTPStatus
User = get_user_model()
class TaskURLTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.use... | StarcoderdataPython |
1625995 | import sys
import asyncio
import time
import argparse
import logging
from typing import Dict, Tuple, List, Optional
from dataclasses import dataclass
from collections import OrderedDict
from hipee_messages import *
from bleak import BleakClient, BleakScanner
NOTIFY_CHARACTERISTIC_UUID = "0000FFF1-0000-1000-8000-00805... | StarcoderdataPython |
4960263 | <filename>eval_test.py
from doctalk.talk import *
def save_summary_and_keywords(document,summary_file,keyword_file) :
T=Talker(from_file=document)
T.save_summary(summary_file)
T.save_keywords(keyword_file)
def go() :
''' saves summary and keywords, one line each to files of your choice'''
save_summary_and_k... | StarcoderdataPython |
9788222 | <reponame>d3rp/fissle
"""Doc string handling"""
import inspect
from collections import OrderedDict
def wrap_method_docstring(cls: object, nt):
"""
In place mutation of 'nt' (NamedTuple)
Uses the implicit Schema's fields as the
classes methods' signatures i.e. helps fire to show up the
defined arg... | StarcoderdataPython |
9735836 | <filename>factory/alchemy.py<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright (c) 2013 <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... | StarcoderdataPython |
9716113 | import os
import sys
# noinspection PyUnresolvedReferences
import tests.mock_tables.dbconnector
modules_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(modules_path, 'src'))
from unittest import TestCase
import json
import mock
import re
import lldp_syncd
import lld... | StarcoderdataPython |
3284895 | """Bootstrap."""
from itertools import zip_longest
from textwrap import wrap
from icecream import ic
from align_benchmark.benchmark import benchmark
from align_benchmark.benchmark import bm2
from align_benchmark.benchmark import bm3
def main():
"""Create __main__."""
# bm1
res = round(benchmark(), 2) #... | StarcoderdataPython |
6510090 | <gh_stars>0
from sim import Particle, Simulator
def test_evolve_sim():
particles = [Particle( 0.3, 0.5, +1),
Particle( 0.0, -0.5, -1),
Particle(-0.1, -0.4, +3)]
sim = Simulator(particles)
sim.evolve(0.1)
p0, p1, p2 = particles
def fequal(a, b, eps=1e-5):
ret... | StarcoderdataPython |
1768331 | <reponame>EdsonRomao/CursoEmVideo<gh_stars>0
"""
Faça um programa que calcule a soma entre todos os números impares que são
multiplos de três e que se encontram no intervalo de 1 até 500.
num1 = 0
for n in range(1, 501):
if n % 2 == 1:
num =+ n
if num % 3 == 0:
num1 = num1 + num
print(... | StarcoderdataPython |
377767 | <gh_stars>1-10
import os
import json
import xlwt
from urllib.parse import urlparse, parse_qs
import requests
import sys
import urllib
import time
import datetime
configs = [{"config_type":"301","config_name":"角色活动祈愿"},{"config_type":"302","config_name":"武器活动祈愿"},{"config_type":"200","config_name":"常驻祈愿"}]
def avgRan... | StarcoderdataPython |
1851553 | # Standard imports. Add analysis specific ones.
import sys
import datetime
import json
from os import path
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.dates import HourLocator
from matplotlib.dates import YearLocator
sys.path.append( path.dirname( path.dirname( path.abspat... | StarcoderdataPython |
4898788 | <filename>external/unbound/testdata/pylib.tdir/pylib.lookup.py
#!/usr/bin/env python
'''
Test for unbound lookup.
BSD licensed.
'''
import unbound
ctx = unbound.ub_ctx()
status = ctx.config("ub.conf")
if status != 0:
print "read config failed ", status
exit(1)
print "config created"
status, result = ctx.resolve("w... | StarcoderdataPython |
3366126 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.9.1+dev
# kernelspec:
# display_name: Python [conda env:generic_expression] *
# language: python
# name: conda-env-g... | StarcoderdataPython |
6524175 | <filename>notaso/search/urls.py
from django.urls import path
from .views import SearchView
app_name = "search"
urlpatterns = [path("", SearchView.as_view(), name="search_list")]
| StarcoderdataPython |
8133866 | <reponame>arnov/lru-ttl<gh_stars>1-10
import unittest
from lruttl import LRUCache
from time import sleep
class TestCache(unittest.TestCase):
def test_basic(self):
cache = LRUCache(10)
cache.set('id', ['some object'], 1)
self.assertEqual(cache.get('id'), ['some object'])
def test_ttl(... | StarcoderdataPython |
4810999 | <filename>src/bioio.py
"""
A bunch of miscellaneous helpful functions copied from sonLib.
"""
import subprocess
import tempfile
import sys
def system(cmd):
"""Run a command or die if it fails"""
sts = subprocess.call(cmd, shell=True, bufsize=-1, stdout=sys.stdout, stderr=sys.stderr)
if sts != 0:
ra... | StarcoderdataPython |
5185738 | <reponame>yipstar/surf_python
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from airflow.hooks.postgres_hook import PostgresHook
from airflow.operators.slack_operator import SlackAPIPostOperator
from airflow.hooks.base_hook... | StarcoderdataPython |
383805 | <gh_stars>1-10
#!/usr/bin/python3
import sys
result = {}
for line in sys.stdin:
line = line.strip()
line = line.split(",")
if(line[0] == "ball"):
bat = line[4]
bowl = line[6]
b = bowl+"/"+bat
if b not in result:
result[b]=[int(line[7],10)+int(line[8],10),1]
else:
result[b][0]=result[b][0]+int(line[... | StarcoderdataPython |
6656008 | #-*- coding: utf-8 -*-
import re
from proxy import Proxy
from basespider import BaseSpider
class KuaiDaiLiSpider(BaseSpider):
name = 'kuaidaili'
def __init__(self, *a, **kwargs):
super(KuaiDaiLiSpider, self).__init__(*a, **kwargs)
self.urls = ['http://www.kuaidaili.com/free/inha/%s/' % i f... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.