id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
82010 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 03:48:59 2020
@author: lukepinkel
"""
import scipy as sp # analysis:ignore
import numpy as np # analysis:ignore
def difference_mat(k, order=2):
Dk = np.diff(np.eye(k), order, axis=0)
return Dk
def ... | StarcoderdataPython |
6484034 | class Heuristics:
# 当可以在多个操作之间进行选择时始终选择第一个操作
@staticmethod
def select_first_operation(jobs_to_be_done, max_operations, _):
best_candidates = {}
for job in jobs_to_be_done:
current_activity = job.current_activity
best_operation = current_activity.shortest_operation
if best_candidates.get(best_operation... | StarcoderdataPython |
1975959 | <filename>qmt/data/__init__.py
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .template import Data
from .geo_data import Geo2DData, Geo3DData
from .part_data import Part3DData
from .thomas_fermi_data import ThomasFermiData
from .schrodinger_poisson_data import Schro... | StarcoderdataPython |
3215089 | <filename>util/quick-compare.py
# What happened to the taxa in taxonomy 1, when taxonomy 1 was
# replaced by taxonomy 2?
import sys, os, json, argparse, csv
from org.opentreeoflife.taxa import Taxonomy, Nexson, Flag
def compare(t1, t2):
print 'comparing', t1, 'to', t2
retired = 0
became_hidden = 0
bec... | StarcoderdataPython |
1760471 | <reponame>sjswerdloff/pymedphys
# 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 l... | StarcoderdataPython |
12820918 | import os
import pytest
import numpy as np
@pytest.fixture
def rng():
default_test_seed = 1 # the default seed to start pseudo-random tests
return np.random.default_rng(default_test_seed)
def run_all_tests(*args):
""" Invoke pytest, forwarding options to pytest.main """
pytest.main([os.path.dirname... | StarcoderdataPython |
4969097 | '''Test fixtures for dagster-airflow.
These make very heavy use of fixture dependency and scope. If you're unfamiliar with pytest
fixtures, read: https://docs.pytest.org/en/latest/fixture.html.
'''
# pylint doesn't understand the way that pytest constructs fixture dependnecies
# pylint: disable=redefined-outer-name, u... | StarcoderdataPython |
1674424 | <reponame>Matej-Chmel/KVContest-data-test-suite
from random import randint
from src.common import storage
from src.dataset_generator import data
class Implementation:
cyc_cmd = None
I = Implementation
def add_line() -> str:
key, val = None, None
while True:
cmd_tuple = next(I.cyc_cmd)
if ... | StarcoderdataPython |
3247266 | from vars import *
print(" -> Please change input files manually if needed!")
csv_CH1 = CSV_FOLDER + "weird_mems_CH1.csv"
csv_CH2 = CSV_FOLDER + "weird_mems_CH2.csv"
fig, (ax1, ax2) = plt.subplots(2)
ax1.set_xlabel("Zeit [s]")
ax1.set_ylabel("Spannung [mV]")
ax2.set_xlabel("Zeit [s]")
ax2.set_ylabel("Spannung [mV]... | StarcoderdataPython |
4948386 | <gh_stars>0
def perms(n):
if not n:
return
for i in xrange(2**n):
s = bin(i)[2:]
s = "0" * (n-len(s)) + s
yield s
print list(perms(15)) | StarcoderdataPython |
1893661 | <gh_stars>0
# say_hi
# Created by JKChang
# 10/04/2018, 09:11
# Tag:
# Description: In this mission you should write a function that introduce a person with a given parameters in attributes.
#
# Input: Two arguments. String and positive integer.
#
# Output: String.
def say_hi(name, age):
"""
Hi!
"""
... | StarcoderdataPython |
8052473 | notice = """
Feature and speed test
for a Pure Python graphics library
that saves to a bitmap
-----------------------------------
| Copyright 2022 by <NAME> |
| [<EMAIL>] |
|-----------------------------------|
| We make absolutely no warranty |
| of any kind, expressed or implied |
|----------... | StarcoderdataPython |
3414459 | <reponame>gigasquid/gluon-nlp
import numpy as np
from numpy.testing import assert_allclose
import mxnet as mx
from gluonnlp.data import batchify
import pytest
def test_pad():
padded = batchify.Pad(pad_val=-1)([mx.nd.array([]), mx.nd.arange(1)]).asnumpy().flatten().tolist()
assert padded == [-1.0, 0.0]
@pyt... | StarcoderdataPython |
3375652 | from plant import CraneMoveTime
from simulatorutils import *
from schedule import Schedule
class Simulator(object):
def __init__(self, plant):
self.plant = plant
self.graph = []
self.createGraph()
def createGraph(self):
for m in self.plant.machines:
mList = []
for q in range(m.quantity):
mList.a... | StarcoderdataPython |
1916385 | <gh_stars>0
default_app_config = 'core.actuator.apps.ActuatorConfig' | StarcoderdataPython |
103985 | <gh_stars>0
import sys
reload(sys) # Reload does the trick!
sys.setdefaultencoding('UTF8')
sys.path.append("packages")
#from Harvest.harvest import Harvest, HarvestError
import os
from harvest import Harvest, HarvestError
from datetime import datetime, timedelta
import time
#import simplejson as json
import json
impor... | StarcoderdataPython |
6642202 | # -*- coding: utf-8 -*-
"""
@Project :
@FileName:
@Author :penghr
@Time :202x/xx/xx xx:xx
@Desc :
"""
import math
import cv2
import numpy as np
import scipy.spatial
import torch
import torch.nn as nn
import torch.nn.functional as F
def LMDS_counting(fmap, img_name, f_loc):
input_max = torch.max(fmap).it... | StarcoderdataPython |
3525034 | import asyncio
from src.init import init
loop = asyncio.get_event_loop()
loop.run_until_complete(init())
print('Finished...') | StarcoderdataPython |
4990253 | <reponame>stannida/netflix-wrapped
import imdb
def get_genres(name):
genres = {}
ia = imdb.IMDb()
movies = ia.search_movie(name)
_id = movies[0].movieID
movie = ia.get_movie(_id)
display(movie)
if movie['genres']:
return movie['genres']
| StarcoderdataPython |
6649774 | <gh_stars>0
from models.cells.esn_cell import ESNCell as ESNCell_numpy
from models.cells.esn_cell_torch import ESNCell as ESNCell_torch
from models.cells.gru_cell import GRUCell
from models.cells.lstm_cell import LSTMCell
from models.cells.rnn_cell import RNNCell
def get_cell(type, reservoir_size, radius, sparsity, s... | StarcoderdataPython |
1778246 | <gh_stars>10-100
#
# Copyright (c) 2020 Saarland University.
#
# This file is part of AM Parser
# (see https://github.com/coli-saar/am-parser/).
#
# 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 a... | StarcoderdataPython |
6478301 | <gh_stars>1-10
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten
import pickle
from keras.optimizers import Adam
import os
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
i... | StarcoderdataPython |
4920890 | <reponame>smujuzi/Consumer-Protection-Portal
# Generated by Django 3.0.6 on 2020-06-03 10:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0003_auto_20200603_1320'),
]
operations = [
migrations.AlterField(
model... | StarcoderdataPython |
1622165 | <reponame>deveil/mrq<gh_stars>100-1000
from __future__ import division
from __future__ import print_function
from builtins import str
from builtins import range
from past.utils import old_div
import time
from mrq.queue import Queue
import pytest
import os
import random
@pytest.mark.parametrize(["p_max_latency", "p_mi... | StarcoderdataPython |
5135306 | import unittest
from robopager.robopager import parse_checklist, PDInteraction
from robopager.check_type.daily_email_check import CheckEmails
from robopager.check_type.intraday_latency_check import CheckWF
from robopager.check_type import intraday_latency_check
from datetime import datetime
import pytz
from unittest.mo... | StarcoderdataPython |
3271933 | # def order():
# return 1
def filter(x):
print("filter called")
print(x)
def detect(x):
if len(x) < 4: return False
if x[0] == 3 and x[1] == 0 and x[2] == 0 and x[3] == 19 : return True
return False
| StarcoderdataPython |
1924868 | <gh_stars>0
import re
from itertools import product
with open("day14.txt", "r") as f:
data = f.read().splitlines()
def apply_mask(mask, value):
# Convert
binary_value = f"{value:>036b}"
masked_value = [
value if mask_value == "0" else "1" if mask_value == "1" else "X"
for value, mask_... | StarcoderdataPython |
12846871 | <gh_stars>0
import speedtest
# Lets test Zuku.
# Its getting frustrating now....
test = speedtest.Speedtest()
print("Loading server list...")
test.get_servers() # Get list of servers
print("Getting best server...")
best = test.get_best_server()
print(f"Found: {best['host']} located in : {best['country']}")
print(... | StarcoderdataPython |
9622101 | <reponame>paipaitou/bili2.0
import bili_statistics
import printer
import asyncio
from typing import Optional
import notifier
from cmd import Cmd
import getopt
from tasks.utils import UtilsTask
from tasks.bili_console import (
PrintGiftbagsTask,
PrintMedalsTask,
PrintMainBiliDailyJobTask,
PrintLiveBiliDa... | StarcoderdataPython |
4963520 | """
This module contains various utility functions
"""
import os
def get_url_base() -> str:
"""
Returns the base URL for the API which can be overridden from the URL_BASE environment variable
"""
url_base = "https://battleshapi.pythonanywhere.com/api/aircraft_carrier"
if os.getenv('URL_BASE') is ... | StarcoderdataPython |
11229120 | from __future__ import unicode_literals
import datetime
from django.core.validators import RegexValidator
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers, exceptions
from waldur_ansible.common import serializers as common_serializers
fr... | StarcoderdataPython |
9750549 | # merge linked lists into a single list in sorted order
from dsame.linkedLists.problems.BaseLinkedList import BaseLinkedList
def merge_lls_recursive(a, b):
if not a:
return b
if not b:
return a
if a.data <= b.data:
result = a
result.next = merge_lls_recursive(a.next, b)
... | StarcoderdataPython |
6466957 | """Test the LTI select view."""
from html import unescape
import json
from logging import Logger
import random
import re
from unittest import mock
import uuid
from django.test import TestCase
from django.utils import timezone
from rest_framework_simplejwt.tokens import AccessToken
from ..factories import DocumentFac... | StarcoderdataPython |
1969379 | <reponame>tzole1155/moai<gh_stars>1-10
from moai.validation.metrics.image.psnr import PSNR
__all__ = [
"PSNR",
] | StarcoderdataPython |
5174265 | <filename>src/binheap.py
"""Implements a max binary heap."""
class BinHeap(object):
"""Structure for values in a max binary heap.
A max binary heap is a complete binary tree where each level of the
tree is greater than the level below it. A min heap has the lowest
values at the top.
"""
def ... | StarcoderdataPython |
223440 | <filename>backend/src/account/permissions.py
from rest_framework import permissions
class AdminOnly(permissions.BasePermission):
"""
Only allow admin user to access this endpoint
"""
def has_permission(self, request, view):
message = "Non-admin user not allowed"
return request.user.is... | StarcoderdataPython |
9664544 | """
========================================
Cell Tracking (:mod:`tracking.core`)
========================================
.. currentmodule:: tracking.core
TITAN cell tracking
================
.. autosummary::
:toctree: generated/
Cell_tracks
"""
#from .cell_tracking import Cell_tracks
from .tracks import Cel... | StarcoderdataPython |
3475163 | <filename>envs/deadlineSchedulingEnv.py<gh_stars>1-10
'''
Environment to calculate the Whittle index values as a deep reinforcement
learning environment modelled after the OpenAi Gym API.
From the paper:
"Deadline Scheduling as Restless Bandits"
'''
import gym
import math
import time
import torch
import random
impo... | StarcoderdataPython |
9754379 | import logging
from dataclasses import dataclass
from aiohttp import ClientSession
VALUE_MAPPING = {
'0': {
'value': 0,
'desc': 'Keine Belastung',
},
'0-1': {
'value': 1,
'desc': 'Keine bis geringe Belastung',
},
'1': {
'value': 2,
'desc': 'Geringe B... | StarcoderdataPython |
3305151 | <reponame>Ry4nW/python-wars
class Solution:
def solve(self, matrix):
try:
for i in range(len(matrix[0])):
for j in range(len(matrix)):
if matrix[j][i] == 1:
return i
except:
pass
return -1
| StarcoderdataPython |
8072782 | <reponame>rijalanupraj/halkapan<filename>userprofile/signals.py
# External Import
from django.db.models.signals import post_save, pre_save
from django.conf import settings
from django.dispatch import receiver
import os
import time
# Internal Import
from .models import Profile
User = settings.AUTH_USER_MODEL
@receiv... | StarcoderdataPython |
363404 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 09:00:23 2018
@author: r.dewinter
"""
import numpy as np
import matplotlib.pyplot as plt
from hypervolume import hypervolume
from paretofrontFeasible import paretofrontFeasible
import os
#plt.plot(objectivesMOGA[:,0],objectivesMOGA[:,1... | StarcoderdataPython |
11242580 | # coding: utf-8
'''
# Criteria
## Pathogenic
### Pathogenic Very Strong
* PVS1 null variant (nonsense, frameshift, canonical ±1 or 2 splice sites, initiation codon, single or multiexon deletion) in a gene where LOF is a known mechanism of disease
### Pathogenic Strong
* PS1 Same amino acid change as a previously es... | StarcoderdataPython |
3547975 | # Copyright (c) 2014 Rackspace, 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 wr... | StarcoderdataPython |
6488295 | from datetime import datetime
import pytz
from django.contrib.postgres.fields import ArrayField
from django.db import models
from osf.models import Node
from osf.models import OSFUser
from osf.models.base import BaseModel, ObjectIDMixin
from osf.models.validators import validate_subscription_type
from website.notifica... | StarcoderdataPython |
5109922 | def groupingDishes(dishes):
d = {}
for l in dishes:
dish = l[0]
for i in l[1:]:
if i not in d:
d[i] = [dish]
else:
d[i] += [dish]
print(d)
out = []
for i in sorted(d):
if len(d[i]) > 1:
out += [[i] + sor... | StarcoderdataPython |
8088864 | <reponame>takaaki82/Java-Lessons
N = int(input())
a_list = [int(input()) for _ in range(N)]
man = {}
for a in a_list:
if a in man:
man[a] += 1
else:
man[a] = 1
sorted_man = sorted(man.items(), key=lambda x: -x[0])
ans = 0
minus_1 = 0
remain2 = 0
for a, cnt in sorted_man:
if a == 4:
... | StarcoderdataPython |
4998835 | """
[PYTHON NAMING CONVENTION]
module_name, package_name, ClassName, method_name, ExceptionName, function_name,
GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name,
local_var_name.
"""
import sys, os
import cv2
import re
import pprint
import numpy as np
import time, datetim... | StarcoderdataPython |
8167415 | from __future__ import annotations
from prettyqt import constants, core, gui
from prettyqt.qt import QtWidgets
from prettyqt.utils import InvalidParamError
QtWidgets.QShortcut.__bases__ = (core.Object,)
class Shortcut(QtWidgets.QShortcut):
def __str__(self):
return self.key().toString()
def serial... | StarcoderdataPython |
1705208 | from time import sleep
def lucy_apresentacao():
sleep(2)
print()
print()
print('<<<<< CARREGANDO >>>>> ')
print()
sleep(3)
print('Olá, me chamo Lucy, seja bem vindo ao meu ambiente virtual... ')
sleep(3)
print('Para que possamos ter uma experiência agradavel me diga um pou... | StarcoderdataPython |
5089856 | if 3 <= 5: # true
pass
if 3 <= 2: # false
pass
| StarcoderdataPython |
229623 | <filename>examples/red-pitaya/oscillo/python/oscillo.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import math
import numpy as np
from koheron import command
class Oscillo(object):
def __init__(self, client):
self.client = client
self.wfm_size = 8192
self.sampling_rate = 12... | StarcoderdataPython |
11285041 | import os
import json
import requests
import datetime
import jsonpickle
import shutil
import urllib
import elasticsearch.helpers
from elasticsearch import Elasticsearch
from .interfaces import SearchEngineInterface
from .utilities import configPath
#from ltr.helpers.handle_resp import resp_msg
def resp_msg(msg, resp... | StarcoderdataPython |
5113330 | <reponame>zeendeploy/dsrf
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | StarcoderdataPython |
5144728 | You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100
_
________________________________... | StarcoderdataPython |
5120698 | #! /usr/bin/jython
# -*- coding: utf-8 -*-
#
# voldemort_create.py
#
# Sep/10/2013
#
# ----------------------------------------------------------------
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import json
#
sys.path.append ('/var/www/data_base/common/python_common')
from text_manipulate import dict_di... | StarcoderdataPython |
3493094 | <reponame>vcelis/com.northwoodlabradoodles<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 <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... | StarcoderdataPython |
1659729 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Topic: 通过在类中实现__call__方法,让该类的实例变成可调用对象,即可以在实例对象后面加()来调用该实例对象
Desc : 流畅的Python 第五章示例程序5-8
"""
import random
class BingoCage:
"""
BingoCage的实例使用任何可迭代的对象构建,而且会在
"""
def __init__(self, items):
"""
在本地构建一个副本,防止列表参数的意外副作用
:param item... | StarcoderdataPython |
1855895 | <gh_stars>1-10
import re
from sys import argv
from algorithm.enclosure import enclosure_check
import csv
import logging
FUNC = re.compile('\S+ \\{[^\\}]+\\}')
ATOM = re.compile('\'[^\']*\'')
class Function:
def __init__(self, text):
self.name, self.body = text.split(' ', 1)
self.patterns = self.... | StarcoderdataPython |
3574681 |
from ops.data import OpsClass, OpsField, DszObject, DszCommandObject, cmd_definitions
import dsz
if ('traceroute' not in cmd_definitions):
dszhopinfo = OpsClass('hopinfo', {'hop': OpsField('hop', dsz.TYPE_INT), 'time': OpsField('time', dsz.TYPE_INT), 'host': OpsField('host', dsz.TYPE_STRING)}, DszObject, single=Fa... | StarcoderdataPython |
334356 | <gh_stars>10-100
from itertools import chain
#: Multiple of notch height
IDEAL_NOTCH_WIDTH = 4
def genFrontPoints(w, h, d, t):
return chain(
genHorizontalLinePoints(0, 0, w, t, 0),
genVerticalLinePoints(w, 0, h, -t, 0),
genHorizontalLinePoints(w, h - t, -w, t, 0),
genVerticalLine... | StarcoderdataPython |
8004720 | # Generated from Java9.g4 by ANTLR 4.7.2
from antlr4 import *
if __name__ is not None and "." in __name__:
from .Java9Parser import Java9Parser
else:
from Java9Parser import Java9Parser
# This class defines a complete generic visitor for a parse tree produced by Java9Parser.
class Java9Visitor(ParseTreeVisito... | StarcoderdataPython |
9758106 | <gh_stars>1-10
import torch
import torch.nn as nn
from pytorch_lightning.utilities.seed import seed_everything
from hyperbox.networks import OFAMobileNetV3, DartsNetwork, ENASMacroGeneralModel, ENASMicroNetwork, BaseNASNetwork
from hyperbox.mutator import RandomMutator
from hyperbox.utils.utils import load_j... | StarcoderdataPython |
64444 | import unittest
from pyparsing import ParseException
from media_management_scripts.support.search_parser import parse_and_execute, parse
class ParseTestCase():
def parse(self, query, expected, context={}):
self.assertEqual(parse_and_execute(query, context), expected)
class SimpleTest(unittest.TestCase,... | StarcoderdataPython |
1881287 | <filename>dot_vim/plugged/vim-devicons/rplugin/python3/denite/filter/devicons_denite_converter.py
# -*- coding: utf-8 -*-
# vim:se fenc=utf8 noet:
from .base import Base
from os.path import isdir
class Filter(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'devicons_denite_converter'
self.de... | StarcoderdataPython |
8064120 | # Copyright 2019 Google LLC
#
# 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 |
6575420 | <reponame>anubhab-code/Competitive-Programming
def lovefunc(flower, flower2):
return (flower + flower2) % 2 != 0 | StarcoderdataPython |
5087370 | import numpy as np
class LinearRegression(object):
def __init__(self, fit_intercept=True, copy_X=True):
self.fit_intercept = fit_intercept
self.copy_X = copy_X
self._coef = None
self._intercept = None
self._new_X = None
def fit(self, X, y):
pass
def predic... | StarcoderdataPython |
124796 | <filename>baekjoon/9012/valid_parenthesis_string.py
import sys
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
left_paren_count = 0
for c in input():
if c == "(":
left_paren_count += 1
elif c == ")":
left_paren_count -= 1
if left_... | StarcoderdataPython |
196724 | <filename>FictionTools/amitools/amitools/vamos/cfgcore/trafo.py
class DictTrafo(object):
def __init__(self, trafo_dict=None, prefix=None):
if trafo_dict is None:
trafo_dict = {}
self.trafo_dict = trafo_dict
if type(prefix) is str:
self.prefix = (prefix,)
elif ... | StarcoderdataPython |
1796755 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Assessment',
fields=[
... | StarcoderdataPython |
1994585 | <filename>src/trans_len.py
#!/usr/bin/env python3
import csv
import argparse
FLAG = None
def write_file(feats,lab_list, fn):
with open(fn,'w') as f:
for num, i in enumerate(feats):
for j in range(len(i)):
f.write(str(i[j]) + ',')
f.write(str([len(i)-1]) + '\n')
... | StarcoderdataPython |
1853095 | <filename>plots/create_plots.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
* Copyright (c) 2017, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source c... | StarcoderdataPython |
9773293 | <gh_stars>1-10
import json
from urllib.parse import urlparse, urlunparse
import pytest
import sirius_sdk
from sirius_sdk.agent.connections import Endpoint
from sirius_sdk.agent.aries_rfc.feature_0160_connection_protocol.state_machines import Inviter, Invitee, \
ConnRequest, Invitation
from .helpers import run_co... | StarcoderdataPython |
6671821 | import unittest
import time
from pybarker.utils.redis import SharedStorage
class Test(unittest.TestCase):
APP_REDIS_CONNECTION = 'redis://localhost:6379/3'
def setUp(self):
self.shared_storage = SharedStorage(
self.APP_REDIS_CONNECTION,
)
self.shared_storage2 = SharedSt... | StarcoderdataPython |
8114659 | """
ChainRad
========
File: model training
"""
# Standard library imports
from os import listdir, mkdir
from os.path import isdir, isfile, join
import pickle
from tqdm import tqdm
# 3rd party imports
from PIL import Image
import torch
# Project level imports
from core import IMG_DIR, LOG_DIR, MO... | StarcoderdataPython |
3425712 | #!/usr/bin/python
# coding: utf-8
import unittest
import random
import pendulum
import logging
import json
from cattledb.core._timeseries import FastFloatTSList
class CTimeSeriesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
logging.basicConfig(level=logging.INFO)
def test_base(self... | StarcoderdataPython |
8074948 | <filename>pomma/derive_initial_state_model.py
import logging
def derive_initial_state_model(max_repeats,
num_symbols,
max_extra_states=15,
start_symbol=1000,
end_symbol=1001,
... | StarcoderdataPython |
8085300 | <reponame>gearbird/calgo
# type: ignore
from functools import wraps
def log_it(prefix: str, suffix: str):
def deco(func):
@wraps(func)
def updated_func(*args, **kargs):
print(prefix)
res = func(*args, **kargs)
print(suffix)
return res
return u... | StarcoderdataPython |
192348 | from opnsense_cli.api.base import ApiBase
class Export(ApiBase):
MODULE = "haproxy"
CONTROLLER = "export"
"""
Haproxy ExportController
"""
@ApiBase._api_call
def config(self, *args):
self.method = "get"
self.command = "config"
@ApiBase._api_call
def diff(self, *ar... | StarcoderdataPython |
63694 | import unittest
import json
from typing import Any
from src.shapeandshare.dicebox.config.dicebox_config import DiceboxConfig
from src.shapeandshare.dicebox.factories.network_factory import NetworkFactory
class DiceboxNetworkTest(unittest.TestCase):
"""
The basic class that inherits unittest.TestCase
"""
... | StarcoderdataPython |
3226062 | from flask import Response, Flask, render_template, request, \
redirect, url_for, send_from_directory, send_file, jsonify, session
from werkzeug import generate_password_hash, check_password_hash, secure_filename
import sqlite3
from dateutil import parser
sqlite_file = 'LocalDB/LocalDB.db'
app = Flask(__name__)
... | StarcoderdataPython |
127698 | <filename>modules/lib/homekit/accessory.py
# Distributed under MIT License
# Copyright (c) 2021 <NAME>
""" Homekit accessory class """
from homekit.server import *
class Accessory:
""" Homekit accessory class """
CID_NONE = 0
CID_OTHER = 1
CID_BRIDGE = 2
CID_FAN ... | StarcoderdataPython |
3216662 | <gh_stars>1-10
if __name__ == '__main__':
import os
import torch
from torch.utils.data import DataLoader
from networks import Discriminator, Generator, Loss
from options import TrainOption
from pipeline import CustomDataset
from utils import binning_and_cal_pixel_cc, Manager, update_lr, weig... | StarcoderdataPython |
1754160 | class Attacker(object):
"""docstring for Attacker"""
def __init__(self, task):
super(Attacker, self).__init__()
self.arg = task
def attack(self,sentence):
return "placeholder, please use specific Attacker instead"
class Ragu(Attacker):
"""docstring for Ragu"""
def __init__(self, task):
super(Ragu, self)... | StarcoderdataPython |
375001 | <reponame>MatteoZanella/siv-texture-analysis<gh_stars>1-10
import unittest
from texture.analysis import LBP
import numpy as np
from PIL import Image
class MyTestCase(unittest.TestCase):
def test_neighbor_offset(self):
offsets = LBP._neighbors_offsets(8, 1)
expected_offsets = np.array([[-1, 0], [-1... | StarcoderdataPython |
1632611 | <filename>spine/classification/config.py
# Copyright 2021 Medical Imaging Center, Vingroup Big Data Insttitute (VinBigdata), Vietnam
#
# 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
#
# ht... | StarcoderdataPython |
302957 |
"""
aggregates coins data by time intervals (specified in INTERVALS)
Data saved in separate collections:
coins_1h
coins_24h
Each entry in the collection has the following keys:
"coin",
"rank",
"price_usd",
"24h_volume_usd",
"market_cap_usd",
"available_supply",
"total_supply",
... | StarcoderdataPython |
3384161 | <filename>Jan2019/12Jan2019/StringsDemo.py
class StringDataTypeDemo:
Instances = 0
def __init__(self):
StringDataTypeDemo.Instances += 1
def displayDetails(self, title, value):
print(f"----- {title} -----")
print(f'StringDataTypeDemo.Instances: {self.Instances}')
print(f"Va... | StarcoderdataPython |
204522 | <reponame>53X/asteroid
import torch
from torch import nn
from copy import deepcopy
from ..filterbanks import make_enc_dec
from ..masknn import LSTMMasker
from .base_models import BaseEncoderMaskerDecoder
class LSTMTasNet(BaseEncoderMaskerDecoder):
"""TasNet separation model, as described in [1].
Args:
... | StarcoderdataPython |
8056851 | <filename>real_estate_market/real_estate_market/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class RemHouseInfoItem(scrapy.Item):
# define the fields for your item here like:
# nam... | StarcoderdataPython |
8024952 |
import os,csv
if __name__ == "__main__":
ipath = "../doc_clr/textbook_data/html_txt/result1_2/"
# iipath = ipath+"existStr/"
# opath = "existRel/"
iipath = ipath+"tmpexistStr/"
# idxslist = indexlist(ipath+"index_terms.txt")
# relslist = relist(ipath+"relation_terms.txt")
files = os.listdir(iip... | StarcoderdataPython |
12837596 | <gh_stars>0
import numpy as np
def vec_reg_linear_grad(x, y,theta, lambda_):
m = x.shape[0]
x_t = x.transpose()
error = x.dot(theta) - y
nabela = x_t.dot(error) / m
# print(nabela)
nabela[1:] = nabela[1:] + theta[1:] * (lambda_ / m)
return nabela
if __name__ == "__main__":
X = np.ar... | StarcoderdataPython |
11208522 | client_id = 'Enter_Client_ID_Here'
client_secret = 'Enter_Client_Secret_Here'
client_url = 'wss://test.deribit.com/ws/api/v2'
# test | StarcoderdataPython |
9793270 | <gh_stars>0
import logging
from ferris_cli.ferris_cli import FerrisKafkaLoggingHandler
from ferris_cli.ferris_cli import CloudEventsAPI
from logstash_formatter import LogstashFormatterV1
import os
logger = logging.getLogger(os.environ['APP_NAME'])
kh = FerrisKafkaLoggingHandler()
kh.setLevel(logging.INFO)
formatter ... | StarcoderdataPython |
11398355 | <filename>codemon/codemon.py
#!/usr/bin/python3
import sys
import os
from clint.textui import colored
from codemon.CodemonHelp import showHelp
from codemon.CodemonListen import listen
from codemon.CodemonInit import init, init_single_file
from codemon.CodemonReg import codemonReg
from codemon.CodemonMeta import get_fil... | StarcoderdataPython |
4924315 | from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='dashboard-home'),
path('matchmaking/', views.matchmaking, name='matchmaking'),
path('matchmaking/lobby', views.lobby, name='lobby'),
path('matchmaking/lobby/game', views.game, name='game'),
path('profile/', ... | StarcoderdataPython |
5008394 | <filename>refbox/ui_test.py<gh_stars>1-10
import tkinter as tk
from . import ui
from uwh.gamemanager import GameManager, TeamColor, Penalty
from .noiomanager import IOManager
import itertools
def test_refbox_config_parser():
cfg = ui.RefboxConfigParser()
assert type(cfg.getint('game', 'half_play_duration')) =... | StarcoderdataPython |
1670140 | from django.urls import path, include
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from . import views
router = routers.DefaultRouter()
router.register('categories', views.CategoryView)
router.register('posts', views.PostView, base_name='post')
urlpatterns = [
p... | StarcoderdataPython |
256673 | import numpy as np
import torch
import torch.nn as nn
import pickle
from torch.utils.data import DataLoader
from vanilla_autoencoder import VanillaAE
from dataprep import AutoEncoderDataset
if __name__ == "__main__":
#Setup DEVICE
seed = 99
device = torch.device('cuda:0' if torch.cuda.is_available() ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.