id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9762735 | <reponame>rpsjr/erpbrasil.bank.inter<filename>src/erpbrasil/bank/inter/boleto.py
# -*- coding: utf-8 -*-
# from erpbrasil.febraban.boleto.custom_property import CustomProperty
# from erpbrasil.febraban.entidades import Boleto
class BoletoInter:
""" Implementa a Api do BancoInter """
@classmethod
def co... | StarcoderdataPython |
1720752 | <gh_stars>0
import pytest
from src.day08 import solve_part1, solve_part2
day = "08"
@pytest.mark.parametrize("day", [day])
def test_part1(day, expected_value = 0):
testdata = {"key": "sample", "file": f"test/data/day{day}.sample.dat"}
assert solve_part1(testdata) == expected_value
@pytest.mark.parametrize(... | StarcoderdataPython |
9647663 | from gym.envs.registration import register
register(
id='energy_market-v0',
entry_point='energym.envs:EnergyMarketEnv',
)
register(
id='battery-v0',
entry_point='energym.envs:BatteryEnv',
)
register(
id='energy_market_battery-v0',
entry_point='energym.envs:Ener... | StarcoderdataPython |
4890222 | <filename>pyro/util.py
from __future__ import absolute_import, division, print_function
import functools
import numbers
import random
import warnings
from collections import defaultdict
from contextlib import contextmanager
import graphviz
import torch
from six.moves import zip_longest
from pyro.poutine.util import ... | StarcoderdataPython |
9626878 | from random import shuffle
a1 = str(input('Primeiro aluno: '))
a2 = str(input('Segundo aluno: '))
a3 = str(input('Terceiro aluno: '))
a4 = str(input('Quarto aluno: '))
alunos = [a1, a2, a3, a4]
shuffle(alunos)
print('A ordem será:\033[36m{}\033[m'.format(alunos))
| StarcoderdataPython |
5019829 | # -*- coding: utf-8 -*-
r"""
Generic cell complexes
AUTHORS:
- <NAME> (2009-08)
This module defines a class of abstract finite cell complexes. This
is meant as a base class from which other classes (like
:class:`~sage.homology.simplicial_complex.SimplicialComplex`,
:class:`~sage.homology.cubical_complex.CubicalComp... | StarcoderdataPython |
397971 | from __future__ import annotations
from typing import Optional
from jsonclasses import jsonclass, types
@jsonclass
class SuperBond:
i_ub: Optional[int] = types.int.upperbond(150)
f_ub: Optional[float] = types.float.upperbond(150.0)
c_ub: Optional[int] = types.int.upperbond(lambda: 150)
t_ub: Optional[... | StarcoderdataPython |
1830382 | <gh_stars>1-10
import plotly.graph_objs as go
import pandas as pd
#historical data for 8-inch-71711
df_8_inch_71711_A1A = pd.read_csv('nc03_pipework_values_8_71711.csv')
df_12_131679_A1A = pd.read_csv('nc03_pipework_values_12_131679_A1A.csv')
df_04_71112_B1A_S = pd.read_csv('nc03_pipework_values_04_71112_B1A-S.csv')
... | StarcoderdataPython |
6438749 | """
Lightweight class that keeps track of variables and TF tensors that
should be reported. This is useful for large classes where additional
debug logic would get hectic.
This is just a thin wrapper around the reporter module.
"""
import numpy as np
import tensorflow as tf
import reporter
from utils import flatgrad... | StarcoderdataPython |
9702286 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | StarcoderdataPython |
8115271 | from django.apps import AppConfig
from warr.config import app_config
class WarrConfig(AppConfig):
name = app_config['name']
| StarcoderdataPython |
6556769 | <reponame>mpenza19/Interpretor
import sys, os, string
reload(sys)
sys.setdefaultencoding('utf-8')
import clean
from ufal.udpipe import Model, Pipeline, ProcessingError
def config():
# In Python2, wrap sys.stdin and sys.stdout to work with unicode.
if sys.version_info[0] < 3:
import codecs, locale
... | StarcoderdataPython |
253703 | from django.shortcuts import render
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic.base import View
class Data(View):
def get(self, request):
return HttpResponse("data")
#return render(request, 'data.html', {})
| StarcoderdataPython |
4988497 | <reponame>opendatadiscovery/odd-collector<filename>odd_collector/adapters/clickhouse/mappers/types.py<gh_stars>0
from odd_models.models import Type
TYPES_SQL_TO_ODD = {
"Date": Type.TYPE_DATETIME,
"DateTime": Type.TYPE_DATETIME,
"DateTime64": Type.TYPE_DATETIME,
"String": Type.TYPE_STRING,
"FixedS... | StarcoderdataPython |
3412972 | <filename>search_run/ranking/baseline/serve.py
import datetime
import json
import logging
from typing import List
import mlflow
import numpy as np
from mlflow.entities import RunInfo
from mlflow.tracking import MlflowClient
from search_run.infrastructure.redis import get_redis_client
location = "/home/jean/projects/... | StarcoderdataPython |
4997172 | class Solution:
def newInteger(self, n):
"""
:type n: int
:rtype: int
"""
lst = []
while n:
n, r = divmod(n, 9)
lst.append(r)
return int(''.join(map(str, lst[::-1])))
| StarcoderdataPython |
9604532 | <gh_stars>100-1000
#!/usr/bin/env python3
"""Mininet tests for FAUCET.
* must be run as root
* you can run a specific test case only, by adding the class name of the test
case to the command. Eg ./mininet_main.py FaucetUntaggedIPv4RouteTest
It is strongly recommended to run these tests via Docker, to ensure you... | StarcoderdataPython |
6675559 | import os
import json
APPDIR = os.path.dirname(__file__)
class SimpleCache(object):
CACHE_FILE = None
CACHE = {}
@classmethod
def exists(cls):
print("testing for",cls.CACHE_FILE )
return os.path.exists(cls.CACHE_FILE)
@classmethod
def get(cls):
if not cls.CACHE and c... | StarcoderdataPython |
1996531 | <filename>bmtools/exact/representations.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""Bolzmann machine representations.
Wrapper classes for representing Boltzmann machine with both signed and
unsigned representations and calculating associated moments.
"""
import numpy as np
import bmtools.exact.moments as mom
class ... | StarcoderdataPython |
91890 | <reponame>qagustina/python-exercises
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 16:32:23 2021
@author: qagustina
"""
# Ejercicio 8.10
import pandas as pd
df = pd.read_csv('../Data/OBS_SHN_SF-BA.csv', index_col=['Time'], parse_dates=True)
# COPIA
dh = df['12-25-2014':].copy()
delta_t = -1 # tiempo que tarda ... | StarcoderdataPython |
12814463 | <reponame>jdmonaco/grid-remapping-model<gh_stars>1-10
"""
Model Package API: Publicly accessible class and functionality
"""
# Handling time and tracking time-series data
from .timeseries import TimeSeries, TSPostMortem
# Base classes for models and interfaces
from .model import AbstractModel, ModelPostMortem
fr... | StarcoderdataPython |
11215588 | # Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. Y... | StarcoderdataPython |
3523499 | <filename>tests/src/page/gallery/test_gallery.py
"""Test of the gallery functionality"""
import panel as pn
import awesome_panel.express as pnx
from awesome_panel.database.apps_in_gallery import APPS_IN_GALLERY
from awesome_panel.express.testing import TestApp
from src.pages import gallery
pnx.fontawesome.ext... | StarcoderdataPython |
4938161 | import json
import pytest
from django.conf import settings
from django.db import connections
from django.urls import reverse
from waffle.testutils import override_flag
from dataworkspace.apps.core.charts import models
from dataworkspace.apps.core.charts.constants import CHART_BUILDER_SCHEMA
from dataworkspace.tests.c... | StarcoderdataPython |
9726976 | <filename>server/gohelper.py
#!/usr/bin/env python3
#title :gohelper.py
#description :helper functions to work with gene ontology data
#author :<NAME>
#date :20171128
#version :0.1
#usage :
#notes :
#python_version :3.6.0
#==================================... | StarcoderdataPython |
9752914 | <reponame>Sarund9/brokkr
import os
buildflags = "-out:..\\_bin\\BrokkrEngine.dll -build-mode:dll"
print("Building Engine...")
os.system("odin build src " + buildflags)
# input("Press any key to exit...\n")
| StarcoderdataPython |
6410516 | <reponame>PseudoDesign/nameplate
import requests
import uuid
import json
from datetime import datetime, timedelta
graph_endpoint = 'https://graph.microsoft.com/beta{0}'
# Generic API Sending
def make_api_call(method, url, token, user_email, payload = None, parameters = None):
# Send these headers with all API ca... | StarcoderdataPython |
1323 | <filename>backend/0_publish_audio.py
import sys
import logging
# loggers_dict = logging.Logger.manager.loggerDict
#
# logger = logging.getLogger()
# logger.handlers = []
#
# # Set level
# logger.setLevel(logging.DEBUG)
#
# # FORMAT = "%(asctime)s - %(levelno)s - %(module)-15s - %(funcName)-15s - %(message)s"
# # FORMA... | StarcoderdataPython |
145136 | <reponame>sankhaaditya/Hartree-Fock
import numpy as np
import integration as integ
import constants as ct
class rhf():
def __init__(self, basis_set, basis_per_nuclei, N_charge, e_count, x):
self.basis_set = basis_set
self.basis_per_nuclei = basis_per_nuclei
self.N_charge = N_charge
... | StarcoderdataPython |
9617342 | <reponame>johnliu4/traffic-cv<filename>ai.py
"""Top level module for the machine learning model.
Handles all usage of the model; including training, predicting, and saving the
model.
"""
import sys
import config
import convnet
import region
import matplotlib.pyplot as plt
import numpy as np
import classifier
import m... | StarcoderdataPython |
3500802 | <gh_stars>0
import librosa
import numpy as np
def extract_features(signal, freq=16000, n_mfcc=5, size=512, step=16):
# Mel Frequency Cepstral Coefficents
mfcc = librosa.feature.mfcc(
y=signal, sr=freq, n_mfcc=n_mfcc, n_fft=size, hop_length=step
)
mfcc_delta = librosa.feature.delta(mfcc)
mf... | StarcoderdataPython |
1703764 | #coding: utf-8
import workflow, console, keychain, requests, editor
import re, json, base64, time
POSTS_DIR = '_posts'
BRANCH = 'master'
GITHUB_USER = 'lildude'
GITHUB_EMAIL = '<EMAIL>'
COMMITTER = {'name': GITHUB_USER, 'email': GITHUB_EMAIL}
GITHUB_TOKEN = keycha... | StarcoderdataPython |
8108808 | import argparse
import os
import json
import math
from rich.progress import track
import sumolib
from LngLatTransfer import LngLatTransfer
# cwd: /tools/generator
# --inFile gps_small --dir . --roadnetXML Chengdu.net.xml
# OBSOLETE: --inFile gps_small --dir .\tools\generator --roadnetJSON megaChengdu.json
# input lon... | StarcoderdataPython |
3535474 | import discord
import os
from search_results import find_google_results
from db_operations import db_write_user_search,db_write_user_ping,db_read_user_history
client = discord.Client()
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
... | StarcoderdataPython |
3528276 | # coding:utf-8
import os
import sys
import torch
import torchvision
import pretrainedmodels
import matplotlib.pyplot as plt
import numpy as np
from PIL import ImageFile
from torchvision import datasets
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets import ImageFol... | StarcoderdataPython |
5011009 | <filename>loldib/getratings/models/NA/na_mordekaiser/__init__.py
from .na_mordekaiser_top import *
from .na_mordekaiser_jng import *
from .na_mordekaiser_mid import *
from .na_mordekaiser_bot import *
from .na_mordekaiser_sup import *
| StarcoderdataPython |
6566019 | """
fs.tests.test_expose: testcases for fs.expose and associated FS classes
"""
import unittest
import sys
import os, os.path
import socket
import threading
import time
from fs.tests import FSTestCases, ThreadingTestCases
from fs.tempfs import TempFS
from fs.osfs import OSFS
from fs.memoryfs import MemoryFS
from... | StarcoderdataPython |
6440279 | <filename>grblas/descriptor.py
from . import lib, ffi
from .exceptions import check_status
_desc_map = {}
# TODO: this will need to update for GraphBLAS 1.3 mask options
def build(*, output_replace=False, mask_complement=False,
transpose_first=False, transpose_second=False):
key = (mask_complement, ou... | StarcoderdataPython |
4950404 | <reponame>stenionljunior/api-rest-com-python-e-flask
from flask_restful import Resource
hoteis = [
{
'hotel_id': '"alpha',
'nome': 'Alpha Hotel',
'estrelas': 4.3,
'diaria': 420.34,
'cidade': 'Rio de Janeiro'
},
{
'hotel_id': '"bravo',
'no... | StarcoderdataPython |
5135928 | from find_terms import *
from webscore import *
def large_prefix_overlap(term1,term2):
small_length = min(len(term1),len(term2))
sub_string_length = small_length//2
answer = term1[:sub_string_length]==term2[:sub_string_length]
return(answer)
def s_filter_check(word1,word2):
if word1.endswith('s')... | StarcoderdataPython |
5165021 | <filename>models.py<gh_stars>0
from __future__ import print_function, division
from typing import OrderedDict, Union, Optional, Callable, Dict, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
import ssl
ssl._create_default_https... | StarcoderdataPython |
3284502 | <reponame>NCAR/GeoCAT-examples
"""
linint2_example.py
==================
This script illustrates the following concepts:
- Usage of geocat-comp's `linint2` function
- Bilinear Interpolation from a rectilinear grid to another rectilinear grid
- Usage of geocat-datafiles for accessing NetCDF files
- Usage of... | StarcoderdataPython |
6529458 | import os
PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
METRICS_DIR = os.path.join(PROJECT_ROOT, "metrics")
METRICS_FILE_NAME = "mlpipeline-metrics.json"
GCS_BUCKET = "thea-dev"
GCS_BASE_STR = "gs://"
HTTP_URL_BASE_STR = "http://"
HTTPS_URL_BASE_STR = "https://"
# This is a hack on yacs config system, a... | StarcoderdataPython |
11297255 | <reponame>drongood12/crossed-cogs<filename>status/ss13status.py
#Standard Imports
import asyncio
import ipaddress
import struct
import select
import socket
import urllib.parse
import html.parser as htmlparser
import time
import textwrap
from datetime import datetime
import logging
#Discord Imports
import discord
#Red... | StarcoderdataPython |
1664443 | <gh_stars>0
# -*- coding: UTF-8 -*-
# This file is part of the jetson_stats package (https://github.com/rbonghi/jetson_stats or http://rnext.it).
# Copyright (c) 2019 <NAME>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publish... | StarcoderdataPython |
317748 | <filename>semesterstat/crud/score.py
from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import NoResultFound
from semesterstat.database.models import Score
from .student import get_students
from .subject import get_subjects
def is_scores_exist(db: Session, batch: int, sem: int, dept: str = None):
try:
... | StarcoderdataPython |
272792 | #!/usr/bin/env python3
"""Calculate the value of pi using a sequential approach in Python"""
from datetime import datetime
from sys import argv
def main():
num_steps = 1000000
if len(argv) > 1:
num_steps = int(argv[1])
print("Calculating pi in {} steps...".format(num_steps))
start = datetime.now()
total = ... | StarcoderdataPython |
6651486 | import centipede
# running serialized task
centipede.TaskWrapper.Subprocess.runSerializedTask()
| StarcoderdataPython |
9798365 | <filename>tools-and-examples/logentries.py
#!/usr/bin/env python
import os
from xmlrpclib import Server as xmlrpc
server = xmlrpc(open(os.path.join(os.path.expanduser('~'), '.exaopurl')).read().strip())
for lm in reversed(server.logservice1.logEntries()[2]):
if 'executable overwritten:' in lm['message']: continue... | StarcoderdataPython |
1719720 | <reponame>ishanksoni/Hospital_management_DBMS<gh_stars>1-10
# Generated by Django 3.0.6 on 2020-05-29 15:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('Profile', '0001_initial'),
]
operat... | StarcoderdataPython |
8170006 | <gh_stars>1-10
import os
import datetime
import re
from API import API
from CeleryPy import log
from CeleryPy import move_absolute
from CeleryPy import execute_sequence
class MyFarmware():
def get_input_env(self):
prefix = self.farmwarename.lower().replace('-','_')
self.input_title = os.e... | StarcoderdataPython |
1700691 | from flask import abort, request
from marshmallow import ValidationError
from sqlalchemy.orm import joinedload
from webargs.flaskparser import use_args
from dataservice.extensions import db
from dataservice.api.common.pagination import paginated, Pagination
from dataservice.api.cavatica_app.models import CavaticaApp
f... | StarcoderdataPython |
110022 | from .get_obverter_dataloader import get_obverter_dataloader, get_obverter_features
from .get_obverter_metadata import get_obverter_metadata
| StarcoderdataPython |
3572015 | <gh_stars>0
from __future__ import annotations
from subprocess import Popen
from FlexioFlow.StateHandler import StateHandler
from Schemes.Maven.ReportFileReader import ReportFileReader
from Schemes.Dependencies import Dependencies
import random
import string
import os
class MavenPreCheck:
__state_handler: Stat... | StarcoderdataPython |
3200853 | <gh_stars>0
from typing import List
from .device import DeviceModel
from .gate import GateModel
from .room import RoomModel
from .sampleData import SampleDataModel
from .reciveData import ReciveDataModel
import json
import time
import copy
#Recive data format
#{"Gate":"BRAMKA2","Device":"DEVICE1","RSSI":-27... | StarcoderdataPython |
3417172 | <gh_stars>0
import os
import sqlite3
# database path
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "rpg_db.db")
connection = sqlite3.connect(DB_FILEPATH)
print("CONNECTION:", connection)
cursor = connection.cursor()
print("CURSOR", cursor)
query = """
SELECT
COUNT(character_id)
FROM
... | StarcoderdataPython |
6593918 | import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
# In[Functions]:
# Knowledge Gradient with Correlated Beliefs (KGCB)
# notation for the following:
# K is the number of alternatives.
# M is the number of time-steps
# K x M stands for a matrix with K rows and M columns
... | StarcoderdataPython |
263227 | <reponame>xxao/pero
# Created byMartin.cz
# Copyright (c) <NAME>. All rights reserved.
from . proxy import Proxy
from . event import Event
class EvtHandler(object):
"""
This class represents an event raising base class, to which specific
callbacks can be attached to be called when appropriate event is ... | StarcoderdataPython |
11264032 | <filename>sdk/python/pulumi_aws/apigateway/documentation_part.py
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from t... | StarcoderdataPython |
6540093 | from pathlib import Path
import pandas as pd
FOLDERS_TO_LABELS = {"n03445777": "golf ball", "n03888257": "parachute"}
#maps labels to what is contained in the folders i.e. files in folder "n03445777" all contain images of golf
#in this case we only want to label images containing golf balls and parachutes
def get_f... | StarcoderdataPython |
8140456 | import logging
# Enabling debugging at http.client level (requests->urllib3->http.client)
# you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# the only thing missing will be the response.body which is not logged.
from http.client import HTTPConnection
from clutch.clien... | StarcoderdataPython |
285773 | <reponame>zjjott/html
# coding=utf-8
from apps.core.cache.base import CacheBase, DEFAULT_TIMEOUT
from tornado.gen import Task, coroutine, Return
from pickle import loads, dumps
from library.redisclient import ReconnectClient
class RedisCache(CacheBase):
@classmethod
def configurable_base(cls):
retu... | StarcoderdataPython |
9798081 | <filename>aiomessaging/router.py
"""Router.
"""
from .message import Message
from .effects import EffectStatus, send
from .utils import class_from_string
class Router:
"""Message router.
Routes messages through output backends.
"""
def __init__(self, output_pipeline):
self.output_pipeline = ... | StarcoderdataPython |
5108057 | <gh_stars>0
# Generated by Django 2.1.7 on 2019-04-01 04:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('schedule', '0011_event_calendar_not_null'),
('profile', '0012_auto_20190331_2205'),
]
operation... | StarcoderdataPython |
1740313 | from os import listdir
from pandas import read_csv
from matplotlib import pyplot as plt
PATH = "./result/training_plot/"
data = listdir(PATH)
model = [i for i in listdir("./model/") if i.startswith("v2-")]
model += [i for i in listdir("./model/") if i.startswith("v3-epoch-979-mse-2.61582-attn1-xavier")]
titl... | StarcoderdataPython |
6423426 | <filename>model/ctr/deepfm.py
import torch
import torch.nn as nn
from model.basic.mlp import MLP
from model.ctr.fm import FM
from model.basic.output_layer import OutputLayer
"""
Model: DeepFM
Version: IJCAI 2017
Reference: <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2017).
DeepFM: A Factorization-Machin... | StarcoderdataPython |
52141 | # BSD Licence
# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
# All rights reserved.
#
# See the LICENSE file in the source distribution of this software for
# the full license text.
"""
Utilities for use with genshi
@author: <NAME>
"""
from genshi import *
class RenameElementFilter(object):
... | StarcoderdataPython |
255700 | <reponame>team-fasel/SystemCheck
from PyQt5 import QtWidgets, QtCore, QtGui
class ResultOverview(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setupUi()
def setupUi(self):
layout=QtWidgets.QVBoxLayout()
self.tree = QtWidgets.QTreeView()
layout.addWid... | StarcoderdataPython |
9620624 | from django import forms
from django.forms import ModelForm
from tally_ho.apps.tally.forms.fields import RestrictedFileField
from django.utils.translation import ugettext_lazy as _
from tally_ho.apps.tally.models.ballot import Ballot
from tally_ho.apps.tally.models.comment import Comment
class EditRaceForm(ModelForm... | StarcoderdataPython |
6403356 | <filename>app/controllers/api/__init__.py
import pathlib
import importlib
this = pathlib.Path('.')
__all__ = []
for x in this.glob('api_v*.py'):
__all__.append(x.stem)
globals()[x.stem] = importlib.import_module(x.stem) | StarcoderdataPython |
6573090 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright (c) 2018 The ungoogled-chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generates updating_patch_order.list in the buildspace for updating patches"""
import argpar... | StarcoderdataPython |
1667013 | #!/usr/bin/env python
"""Test utilities for RELDB-related testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import functools
import sys
import mock
from grr_response_core.lib.util import compatibility
from grr_response_server import data_store
... | StarcoderdataPython |
1863735 | <reponame>Godrigos/br-atlas<filename>scripts/test_merge.py
#!/usr/bin/env python3
import unittest
import json
import merge
class TestMerge(unittest.TestCase):
def test_merge_states(self):
data = {}
data[u"type"] = u"Topology"
data[u"arcs"] = []
data[u"transform"] = []
da... | StarcoderdataPython |
5027682 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# coding: utf8
from types import GeneratorType
class StagerSequential():
"""`StagerSequential` class represents a Stager pipeline Step.
"""
def __init__(self, coroutine, name=None, connections=None, main_connection_name=None):
"""
... | StarcoderdataPython |
107688 | <gh_stars>1-10
# encoding: utf-8
from okscraper_django.management.base_commands import NoArgsDbLogCommand
from optparse import make_option
import sys
import csv
from datetime import datetime
from committees.models import Committee
from mks.models import Member, Knesset
class Command(NoArgsDbLogCommand):
help = "G... | StarcoderdataPython |
9740638 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dialog_stalta.ui'
#
# Created: Sat Jul 20 23:49:58 2019
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString... | StarcoderdataPython |
1877918 | <reponame>chechons/Django3IntegracionVueUdemy
from django.contrib import admin
from .models import Element, Category, Type
# Register your models here.
class TypeAdmin(admin.ModelAdmin):
list_display = ('id','title')
class CategoryAdmin(admin.ModelAdmin):
list_display = ('id','title')
class ElementAdmin(ad... | StarcoderdataPython |
1713059 | <reponame>malywonsz/txtai<filename>docker/aws/api.py
"""
Lambda handler for a txtai API instance
"""
from mangum import Mangum
from txtai.api import app, start
# pylint: disable=C0103
# Create FastAPI application instance wrapped by Mangum
handler = None
if not handler:
# Start application
start()
# Cre... | StarcoderdataPython |
8059627 | # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
# Website Referral Lookup (Main.py)
#
# Examines a website referral URL to determine which type of content that it's referencing and the links that are
# being referenced. Includes a template engine that will determine meta data for each ... | StarcoderdataPython |
1951870 | import torch
from models import *
from config import Config
import os
from torchvision.utils import save_image
opt = Config()
def test():
#define Generator
Gen = Generator(opt)
# load pretrained models
print('Loading state dict....')
gen_state_dict = torch.load(os.path.join(opt.state_path, 'Gnet_... | StarcoderdataPython |
199251 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2018 <NAME>
""" Functions to read a CODE V .seq file and populate a sequential model
.. Created on Tue Jan 16 10:14:12 2018
.. codeauthor: <NAME>
"""
import logging
import math
from . import tla
from . import reader as cvr
import rayoptics.opt... | StarcoderdataPython |
4874699 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test case for views."""
import time
import pytest
from flask import url_for
from... | StarcoderdataPython |
1792446 | <filename>test/test_main.py
import logging
import src.utils.log
from src import main
def test_run_case():
main.run("case","kpi.agreement_overlap_check.hotel_count")
def test_run_group():
main.run("group","sae.kpi")
def test_run_scenarios():
main.run("scenarios","kpi") | StarcoderdataPython |
184649 | from django.shortcuts import render
from rest_framework import viewsets
from .models import Product, PriceObj, Service
from .serializers import ProductPriceObjSerializer, ProductSerializer, ServiceSerializer
# Create your views here.
class ProductView(viewsets.ModelViewSet):
serializer_class = ProductSerial... | StarcoderdataPython |
8033865 | <filename>src/eve_esi_jobs/typer_cli/schema.py
"""Working with ESI schema"""
import dataclasses
import json
import logging
import urllib.request
from enum import Enum
from pathlib import Path
from typing import Dict, Optional
import typer
import yaml
from eve_esi_jobs.eve_esi_jobs import EveEsiJobs
from eve_esi_jobs... | StarcoderdataPython |
6561403 | # -*- coding: utf-8 -*-
"""
This module contains the device Core APIs.
"""
import flybirds.utils.flybirds_log as log
from flybirds.core.global_context import GlobalContext as g_Context
def device_connect(device_id):
"""
Initialize device with uri, and set as current device.
:param device_id: device id
... | StarcoderdataPython |
9762096 | #!/usr/bin/env python
"""Pull out the B allele frequency from a given subpopulation in the provided vcf.
B allele frequencies are used when examining sample contaminaton.
"""
from pathlib import Path
from typing import Optional
import typer
from cgr_gwas_qc.parsers import bpm, vcf
app = typer.Typer(add_completion=F... | StarcoderdataPython |
5030707 | <gh_stars>1-10
#!/usr/bin/env python
# encoding: utf-8
import unittest
from helpers import test
from hadoop.parsers import LineParser, KeyValueParser, TSVParser
class ParserTests(unittest.TestCase):
def setUp(self):
self.fixture = [
'one\ttwo\tthree\n',
'four\tfive\tsix\n'
]
@test
def lin... | StarcoderdataPython |
11250938 | <gh_stars>0
import pickle
def load_wv(wv_path):
"""Load word vector dictionary
Arguments:
wv_path {str} -- path of pickle file
"""
with open(wv_path, 'rb') as file:
wv_dict = pickle.load(file)
return wv_dict
| StarcoderdataPython |
249236 | from enum import Enum
class OManState (Enum):
parsing = 1
processinginput = 2
selectstream = 3
downloading = 4
cleaningup = 5
finaloutput = 6 | StarcoderdataPython |
1655741 | import logging
import flask_profiler
logger = logging.getLogger(__name__)
def setup_profiler(app):
profiler = app.config['POLYSWARMD'].profiler
if not profiler.enabled:
return
if profiler.db_uri is None:
logger.error('Profiler enabled but no db configured')
return
app.confi... | StarcoderdataPython |
6458963 | # -*- coding: utf-8 -*-
import sys, time, random
#FLASK
from flask import Flask, request
from flaskJSONRPCServer import flaskJSONRPCServer
def echo(data='Hello world!'):
# Simply echo
return data
echo._alias='helloworld' #setting alias for method
def stats(_connection=None):
#return server's speed stats
... | StarcoderdataPython |
6667160 | import pygame
class Cell(object):
def __init__(self, col, row):
assert isinstance(col, int)
assert isinstance(row, int)
self.col, self.row = col, row
def __getitem__(self, key):
if 0 == key: return self.col
if 1 == key: return self.row
raise KeyError
def __setitem__(self, key, value... | StarcoderdataPython |
6479846 | from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions
from base64 import b64decode
from mtcnn.mtcnn import MTCNN
from PIL import Image
import numpy as np
import cv2
import io
detector = MTCNN()
app = FlaskAPI(__name__)
@app.route("/selfie", methods=['POST'])
def notes_list():
"... | StarcoderdataPython |
5076108 | import sys
import logging
import logging.config
class ColorizingStreamHandler(logging.StreamHandler):
# color names to indices
color_map = {
'black': 0,
'red': 1,
'green': 2,
'yellow': 3,
'blue': 4,
'magenta': 5,
'cyan': 6,
'white': 7,
}
... | StarcoderdataPython |
4846771 | # get all locations where one can buy TOTO
import sqlite3, urllib
from selenium import webdriver
from bs4 import BeautifulSoup
import re
#re.compile('<title>(.*)</title>')
# connect to database
conn = sqlite3.connect('toto.sqlite')
cur = conn.cursor()
url='http://www.singaporepools.com.sg/outlets/Pages/lo_results.aspx... | StarcoderdataPython |
1609702 | import torch
from torchvision import transforms
import os
import cv2
import time
import numpy as np
from .pse import decode as pse_decode
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _i... | StarcoderdataPython |
1931329 | <filename>DATA/workflow/ATG_Reg/databases/manual_curation/script.py<gh_stars>0
"""
Importing manual curation data from ARN v1
"""
# Imports
import logging
from SLKlib.SQLiteDBApi.sqlite_db_api import PsimiSQL
# Defining constants
SQL_SEED = '../../../../SLKlib/SQLiteDBApi/network-db-seed.sql'
DATA_FILE_LIST = ['fil... | StarcoderdataPython |
1831747 | """pypyr step to fetch a yaml file from s3 and put it in context."""
from collections.abc import MutableMapping
import logging
import pypyraws.aws.s3
import ruamel.yaml as yaml
# pypyr logger means the log level will be set correctly and output formatted.
logger = logging.getLogger(__name__)
def run_step(context):
... | StarcoderdataPython |
6689326 | <filename>variables/floats.py<gh_stars>10-100
# -----------------------------------------------------
# Tutorial: An explanation of the float datatype
# -----------------------------------------------------
# In python, decimals are stored using the float datatype
number1 = 10.10 # We can directly assign a decimal to... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.