id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3382973
<reponame>hinnefe2/ctadelaybot """This module contains functions to be invoked by AWS lambda to scrape the CTA alerts API and record the results in S3.""" import logging import awslogging # noqa from api import get_alerts from s3io import write_to_s3 def scrape_api(context, other_thing): alerts = get_alerts(...
StarcoderdataPython
1613028
<reponame>Mmankale/private-data-objects # Copyright 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
StarcoderdataPython
1715751
<reponame>pbarton666/virtual_classroom #solution_python1_chapter02_keywords.py """Solutions to Chapter 2 keyword problem""" import keyword #get all the keywords all_kw=keyword.kwlist ####### String methods ####### #figure out how many there are kw_count=len(all_kw) #one approach might be to use string methods to ...
StarcoderdataPython
4842298
"""Support for wired switches attached to a Konnected device.""" import logging from openpeerpower.const import ( ATTR_STATE, CONF_DEVICES, CONF_NAME, CONF_REPEAT, CONF_SWITCHES, CONF_ZONE, ) from openpeerpower.core import callback from openpeerpower.helpers.dispatcher import async_dispatcher_c...
StarcoderdataPython
3333574
# draw a parallelogram from turtle import * a = 200 b = 150 angle = 60 forward(a) left(angle) forward(b) left(180-angle) forward(a) left(angle) forward(b) left(180-angle) done()
StarcoderdataPython
1776090
from django.conf import settings from django.core.management import BaseCommand, call_command from callblocker import blocker from callblocker.blocker import BootstrapMode class Command(BaseCommand): """ Runs Django and the background modem monitoring loop. Note that this will fail MISERABLY if Django forks,...
StarcoderdataPython
1697388
""" 2021 <NAME>, ETHZ, MPI IS """ import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader import wandb from healthgen.generation.base_gen_model import BaseGenModel from healthgen.generation.models import VAE from absl import flags, app FLAGS=flags.FLAGS # Model flags.DEFINE_enum('encoder...
StarcoderdataPython
1754313
#!/usr/bin/python """ Running on local host, listening on https over tcp and http over unix domain socket for authentication assertions and secure temporary storage of authorization assertions """ import os import sys import struct import socket import SocketServer import ssl import threading import tempfile import l...
StarcoderdataPython
3315559
<reponame>DHEERAJPRAKASH/CALORIE_TRACKER<gh_stars>0 from django.urls import path from .views import HomePageView,LoginPage,LogOutPage,select_food,add_food,RegisterPage,ProfilePage,update_food,delete_food urlpatterns = [ path('', HomePageView,name='home'), path('login/',LoginPage,name='login'), path('logout/',LogOu...
StarcoderdataPython
3215430
import asyncio from typing import Dict from pyzeebe import ( Job, ZeebeWorker, create_camunda_cloud_channel, create_insecure_channel, create_secure_channel, ) from pyzeebe.errors import BusinessError # Use decorators to add functionality before and after tasks. These will not fail the task async ...
StarcoderdataPython
1749176
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'os_2.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _from...
StarcoderdataPython
1673633
<reponame>LaudateCorpus1/oci-python-sdk<filename>src/oci/core/models/instance_reservation_config_details.py<gh_stars>0 # coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at http...
StarcoderdataPython
3219279
<filename>tests/system/test_gamaclassifier.py """ Contains full system tests for GamaClassifier """ import numpy as np import pandas as pd import pytest from typing import Type from sklearn.datasets import load_wine, load_breast_cancer from sklearn.ensemble import VotingClassifier from sklearn.model_selection import t...
StarcoderdataPython
3207074
import unittest from unittest import mock import amp.commands.gaids as gaids class TestGaids(unittest.TestCase): @mock.patch("commands.gaids.api.getAuthenticationHeaders") @mock.patch("commands.gaids.requests.get") def test_validate(self, mock_input, mock_api): mock_input.return_value.s...
StarcoderdataPython
1792957
SITE_ID = 1 SITE_TITLE = 'MyTardis' ''' customise the title of your site ''' SPONSORED_TEXT = None ''' add text to the footer to acknowledge someone ''' DEFAULT_INSTITUTION = "Monash University"
StarcoderdataPython
4832589
import os import tarfile import gzip from biopanning_data_bank.config import (DATA_DIRECTORY, INVALID_XML_TOKENS) def process_raw_data_file(input_filepath, release_index): filename = os.path.basename(input_filepath) print(f'Processing file: {filename} from release {r...
StarcoderdataPython
96013
<gh_stars>0 import time t1 = time.time() from typing import Dict import json import os from copy import deepcopy try: import torch except: os.system('conda install --yes pytorch torchvision cudatoolkit=10.1 -c pytorch') import tensorflow as tf from src.utils import get_logger LOGGER = get_logg...
StarcoderdataPython
3336724
<gh_stars>0 class FooClass(object): 'my very first class: FooClass' version = 0.1 # class (data) attribute def __init__(self, nm='<NAME>'): 'constructor' self.name = nm # class instance (data) attibute print 'Create a class instance for', nm def showname(self): 'Display...
StarcoderdataPython
142962
from src.utils.db_utils import execute_sql,insert_query, save_rds_pandas from src.models.save_model import save_upload, parse_filename from datetime import date, datetime from pyspark.sql import SparkSession from pyspark.sql.types import IntegerType, DoubleType from pyspark.sql.functions import monotonically_increasi...
StarcoderdataPython
3322064
<filename>booking/views/__init__.py from .event_view import EventView from .event_game_view import EventGameView from .event_list_view import EventListView from .home_view import HomeView
StarcoderdataPython
1756749
<filename>src/operators.py import bpy from bpy.props import * from . import components class AddMammothComponent(bpy.types.Operator): bl_idname = "wm.add_mammoth_component" bl_label = "Add Mammoth Component" component_name = StringProperty(name="component_name") def execute(self, context): obj = context.obj...
StarcoderdataPython
3397
# Copyright ©2020-2021 The American University in Cairo and the Cloud V Project. # # This file is part of the DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for further info. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
StarcoderdataPython
1769670
from http.server import BaseHTTPRequestHandler, HTTPServer class DummyServer(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers() self.wfile.write(...
StarcoderdataPython
3359000
# GUI (Screens) from Screens.Screen import Screen from Components.ConfigList import ConfigListScreen # GUI (Summary) from Screens.Setup import SetupSummary # GUI (Components) from Components.ActionMap import ActionMap from Components.Sources.StaticText import StaticText # Configuration from Components.config import ...
StarcoderdataPython
19256
# pylint: disable=too-many-arguments """ Observer implemtation doing OS command """ from base.iobserver import IObserver import subprocess import logging import os import sys logging.basicConfig( format='%(asctime)s %(levelname)s:%(name)s: %(message)s', level=os.environ.get('LOGLEVEL', 'INFO').upper(), d...
StarcoderdataPython
3249617
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'new.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_NewWindow(object): def setupUi(self, NewWindow): NewWindow.setOb...
StarcoderdataPython
1665033
<reponame>dingwilson/DivBin from flask import Flask, jsonify, request, render_template import Firebase import json application = Flask(__name__) test = [ { 'Test': 'Kevin', 'id': 1 }, { 'Test': 'Wislon', 'id': 2 } ] @application.route('/', methods=['GET']) def root(): ...
StarcoderdataPython
1783598
<filename>server deploy/flask/main.py #!/usr/bin/python3 import os import secrets import string import requests import boto3 from flask import Flask, request, render_template import qrcode app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @app.route('/zip', methods=['POST']) def zip_uri(): try: ...
StarcoderdataPython
3394927
<reponame>JosephThePatrician/WikipediaQA import numpy as np import spacy import re from warnings import warn class TextProcessor: def __init__(self, spacy_model : str = "en_core_web_sm"): # try: self.nlp = spacy.load(spacy_model) # except Exception: # raise Exception(f"{spacy_m...
StarcoderdataPython
13561
<filename>example/models.py """Django models for the example app.""" from django.db import models from wikidata.client import Client # type: ignore LANGS = ["fr", "en"] # ordered list of langages to check on wikidata class WikiDataModel(models.Model): """A django model to represent something available on wik...
StarcoderdataPython
3372524
<gh_stars>1-10 #!/usr/bin/env python3 import math import os import random import re import sys # # Complete the 'dynamicArray' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER n # 2. 2D_INTEGER_ARRAY queries # # To run in terminal, e...
StarcoderdataPython
3341857
<gh_stars>1-10 if __name__ == '__main__': n = int(input()) l= {} for i in range(n) : t = input().split() l[(t[0])]= (float(t[1])+float(t[2])+float(t[3]))/3 name = input() print("%.2f" % round(l[name],2))
StarcoderdataPython
96887
# Generated by Django 3.0.3 on 2020-03-14 09:14 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='pollimetermodel', fields=[ ('id', models.Au...
StarcoderdataPython
1733254
<reponame>shx2/lo99ing<gh_stars>0 #! /usr/bin/env python3 import lo99ing import datetime class ManualClock: def __init__(self, t=None): self.t = t def now(self): return self.t def main(): logger = lo99ing.get_logger('LOGGER1') logger.info('<-- 1 local time') lo99ing.use_utc(...
StarcoderdataPython
1712762
from numpy import median from lodstats.stats.RDFStatInterface import RDFStatInterface from lodstats.stats.RDFStatInterface import RDFStatInterface from utils.DisjointPropertyDetectorOwlDisjointWith import DisjointPropertyDetectorOwlDisjointWith from utils.DisjointPropertyDetectorOwlAllDisjointProperties import Disjoin...
StarcoderdataPython
1651396
<filename>simplecloud/network.py #!/usr/bin/env python3.7 # -*- coding: utf-8 -*- from abc import ABC, abstractmethod import docker import ipaddress from simplecloud import docker_client, docker_api_client, logger from sortedcontainers import SortedSet import subprocess class BaseNetwork(ABC): @abstractmethod ...
StarcoderdataPython
1683719
# -*- coding: utf-8 -*- # http://www.apache.org/licenses/LICENSE-2.0.txt # # Copyright 2016 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lic...
StarcoderdataPython
1655830
<filename>autonetkit/design/ip_addressing/general.py<gh_stars>10-100 from collections import Counter from enum import Enum from autonetkit.design.utils import filters from autonetkit.network_model.network_model import NetworkModel from autonetkit.network_model.port import Port from autonetkit.network_model.topology im...
StarcoderdataPython
3276073
<reponame>bibsian/lter<gh_stars>1-10 #!/usr/bin/env python import pytest import pytestqt from PyQt4 import QtGui import sys, os from Views import ui_dialog_covariate as covar from poplerGUI import class_inputhandler as ini from poplerGUI import class_modelviewpandas as views from poplerGUI import ui_logic_preview as tp...
StarcoderdataPython
180957
<filename>test/mirror_controller/bmc_deformable_mirror_test.py<gh_stars>0 #!/usr/bin/env python import unittest import numpy as np from plico_dm_server.controller.bmc_deformable_mirror import \ BmcDeformableMirror, BmcError from plico_dm_server.controller.fake_bmc_dm import FakeBmcDm class BmcDeformableMirrorTes...
StarcoderdataPython
1665826
<filename>scripts/cal_mean_std.py # coding=utf-8 # @Time : 2021/2/2 15:53 # @Auto : zzf-jeff import numpy as np import cv2 import os import random from tqdm import tqdm train_txt_path = './train_val_list.txt' num_img = 10000 # 挑选多少图片进行计算 img_h, img_w = 640, 640 imgs = np.zeros([img_w, img_h, 3...
StarcoderdataPython
123419
import requests import datetime import json import pandas as pd from loguru import logger # Lista negra de Tokens con los que no operar. Descartaremos los stablecoin. TOKEN_BLACKLIST = ["usd", "tether", "dai", "usd-coin", "binance-usd"] def get_top_crypto(rank: int = 12, market_cap_limit: int = 1500000000): resp...
StarcoderdataPython
138995
<reponame>chimera-linux/cports import os import io import gzip import stat import tarfile import hashlib import pathlib import tempfile import subprocess from datetime import datetime from . import util, sign # emulate `du -ks` * 1024, which is what alpine uses for size def _du_k(fl): hls = {} ret = 0 for...
StarcoderdataPython
3235288
<filename>tests/roots/test-extensions/read_serial.py def setup(app): return { 'parallel_read_safe': False }
StarcoderdataPython
4832367
<reponame>dmytrostriletskyi/dbnd<filename>modules/dbnd-airflow-monitor/src/airflow_monitor/multiserver/cmd_multiserver.py from airflow_monitor.config import AirflowMonitorConfig from airflow_monitor.multiserver.multiserver import start_multi_server_monitor from airflow_monitor.validations import run_validations from db...
StarcoderdataPython
57409
<reponame>muttiopenbts/cascade_spit # Generated by Django 3.1.5 on 2021-01-31 05:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL)...
StarcoderdataPython
1602893
pessoas = {'nome': 'Lara', 'idade': 18, 'sexo': 'F'} '''print(f"A {pessoas['nome']} tem {pessoas['idade']} anos.") print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for k in pessoas.values(): # aqui pode ser implementado o .keys() ou .items() print(k)''' del pessoas['sexo'] pessoas['nome'] = "...
StarcoderdataPython
1757944
<filename>my_timesaver_utils/all.py<gh_stars>1-10 from .profiling import * from .profiling_callback import * from .enhanced_imageclassifiercleaner import *
StarcoderdataPython
3261602
<gh_stars>0 peso = int(input("qual seu peso? ")) altura = float(input("Qual a sua altura em (m)?")) #Menor que 18,5 - Abaixo do peso #Entre 18,5 e menor que 25 - Peso normal #Entre 25 e menor que 30 - Sobrepeso (acima do peso desejado) #Igual ou acima de 30 - Obesidade imc = peso/(altura*altura) if imc<18.5: pri...
StarcoderdataPython
3363262
import unittest from os.path import dirname, abspath, join from sqlalchemy_media.descriptors import AttachableDescriptor from sqlalchemy_media.exceptions import AnalyzeError from sqlalchemy_media.processors import ImageAnalyzer class ImageAnalyzerTestCase(unittest.TestCase): @classmethod def setUpClass(cls)...
StarcoderdataPython
4831649
from django.utils.translation import ugettext_lazy as _ class Constants(object): # Experiments UNFINISHED = 0 COMPLETED = 1 EXPERIMENT_STATUS = ( (UNFINISHED, _('unfinished')), (COMPLETED, _('completed')), ) # Game PRISONERS_DILEMMA = 'PD' PUBLIC_GOODS_GAME = 'PGG' ...
StarcoderdataPython
3349068
<filename>salika/urls/auth_group_permissions_urls.py from django.conf.urls import url from ..views import (AuthGroupPermissionsListView, AuthGroupPermissionsCreateView, AuthGroupPermissionsDetailView, AuthGroupPermissionsUpdateView, AuthGroupPermissionsDeleteView) from django.contrib.auth.decorator...
StarcoderdataPython
129373
<gh_stars>1-10 # vim:set tabstop=4 shiftwidth=4 expandtab: # Copyright (c) 2008, Humanized, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must ...
StarcoderdataPython
4806571
<filename>Experimentation/communitySummarizer.py import copy import os import sys import xml.etree.ElementTree import xml.etree.ElementTree as ET from RougeNormalisation import RougeNormalisation from Experimentation.paper import Paper from Experimentation.sentence import Sentence from Experimentation.spanResult impor...
StarcoderdataPython
3202224
import os def clear_stdout(): os.system("clear") class dotdict(dict): """ To access attributes of a dict via my_dict.attribute""" def __getattr__(self, name): return self[name]
StarcoderdataPython
1755082
<reponame>knutsonchris/stacki # @copyright@ # Copyright (c) 2006 - 2019 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ # # @rocks@ # Copyright (c) 2000 - 2010 The Regents of the University of California # All rights reserved. Rocks(r)...
StarcoderdataPython
3272055
<filename>DAG_from_GNN/config.py<gh_stars>1-10 """ Contains config parameters for app """ class CONFIG: """Dataclass with app parameters""" def __init__(self): pass # You must change this to the filename you wish to use as input data! data_filename = "alarm.csv" # Epochs epochs = 30...
StarcoderdataPython
1647234
# -*- coding: utf-8 -*- # # Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de # Aplicacion de las TIC basadas en Fuentes Abiertas, Spain. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistribution...
StarcoderdataPython
1733864
<reponame>EnzoKilm/python_macgyver_maze import random map_height = 15 map_width = 15 new_map = [] # Initial map creation for y in range(0, map_height): new_map.append([]) for x in range(0, map_width): new_map[y].append('#') # First cell initialisation new_map[0][0] = '_' new_map[map_height-1][map_wid...
StarcoderdataPython
1715671
import sys import os import time import numpy as np import tensorflow as tf import tensorflow.contrib.layers as layers from PIL import Image import model.components.attention_mechanism from model.base import BaseModel from model.decoder import Decoder from model.encoder import Encoder from model.evaluati...
StarcoderdataPython
1603714
from django.conf import settings ENDPOINT_DESCRIPTION_STRING = getattr( settings, 'BILLING_ENDPOINT_DESCRIPTION_STRING', "tcp:9090:interface=127.0.0.1") API_MIN_CONNECTIONS = getattr(settings, 'BILLING_API_MIN_CONNECTIONS', 10) def get_connection_string(): """Return the database connection string""" ...
StarcoderdataPython
3315904
#G00387859 <NAME> k = 0 # DECLARE A VARIBLE TO HOLD THE COUNT myList = [] # DECLARE A EMPTY LIST with open("textFile.txt", 'r') as f: # READ THE FILE # LOOP OVER THE CHARS IN THE FILE AND ASSIGN TO A LIST while 1: char = f.read(1) if not char: break # BREAK OUT OF THE WHILE LOOP IF THERE ARE NO ...
StarcoderdataPython
3312000
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse('user:create') TOKEN_URL = reverse('user:token') ME_URL = reverse('user:me') def create_user(**params)...
StarcoderdataPython
3385881
<filename>demo.py import matrixgenerator as generate from api.led_matrix import Max7219 from time import sleep, time matrix = Max7219(4) def demo(): """Soll zeigen, was die kleine 8x8 LED Matrix drauf hat. Zu Demonstrationszwecken frei anpassbar. """ my_string = "SerNet" from matrixgenerator im...
StarcoderdataPython
75111
<filename>trubar/actions.py import os import sys from dataclasses import dataclass from typing import Union, Iterator, Tuple, Dict, List, Optional import yaml import libcst as cst from libcst.metadata import ParentNodeProvider __all__ = ["collect", "translate", "update", "missing", "load", "dump", "set_roo...
StarcoderdataPython
3215537
<reponame>cokelaer/biokit import scipy.stats import numpy as np import pandas as pd class ANOVA(object): """ assumption: normality of the data and independence (eg. True across cell line, not over protein) """ def __init__(self, df): self.df = df.copy() def anova(self): ...
StarcoderdataPython
140241
import typing from .XLineFragment import XLineFragment from .ITextBlock import ITextBlock _RESET = "\x1b[0m" class TextBlockSequence(ITextBlock): ################################################################################################################################ ## Constructor ############...
StarcoderdataPython
1647977
<filename>stats/locations/formatting.py # -*- coding: utf-8 -*- # Copyright (c) 2018-2020 <NAME> # stats.wwdt.me is relased under the terms of the Apache License 2.0 """Location name formatting functions used by the Stats Page""" from typing import Dict #region Formatting Functions def format_location_name(location: ...
StarcoderdataPython
79456
<filename>code/Dirs.py<gh_stars>0 axionlimits_dir = "/Users/bradkav/Code/AxionLimits/"
StarcoderdataPython
157330
<filename>test/test_verify_output_dir.py import os import pytest from pyega3.libs.utils import verify_output_dir def test_absolute_path_is_returned_if_directory_exists(fs): output_dir = 'user_specified_directory' os.makedirs(output_dir) assert os.path.exists(output_dir) assert os.path.isdir(output_...
StarcoderdataPython
75280
<reponame>steerapi/webdnn from webdnn.backend.webgpu.kernels.elementwise import register_elementwise_kernel from webdnn.graph.operators.tan import Tan register_elementwise_kernel(Tan, "y = tan(x0);")
StarcoderdataPython
1747706
<filename>WEB-INF/mframe/authenbase.py # -*- coding: iso-8859-15 -*- import re,sys class AuthenBase(object): """ Basisklasse fuer Authentifizierung Die Autentifizierung basiert auf einer Sessionvariable namens user. Ist diese gesetzt gilt der Benutzer als angemeldet """ user = None session...
StarcoderdataPython
3274849
<reponame>maxfischer2781/cobald<filename>src/cobald/decorator/standardiser.py from cobald.interfaces import Pool, PoolDecorator from ..utility import enforce from ..utility.primitives import infinity as inf def _clamp(low, value, high): """Clamp `value` to the range between `low` and `high`""" if value < low...
StarcoderdataPython
7987
from __future__ import print_function import argparse import os import time, platform import cv2 import torch import torch.optim as optim from torch.utils.data import DataLoader from datasets import DATASET_NAMES, BipedDataset, TestDataset, dataset_info from losses import * from model import DexiNed # from model0C ...
StarcoderdataPython
3305676
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from gen_helper import getCopyrightNotice, openNamespaces, closeNamespaces, \ include def generate(unicode_proplist_file, target): """Generates a C++ source file that contains a delimiter checking function. The delimiter checking function...
StarcoderdataPython
1711237
# Import CNTK library import cntk # Version print('CNTK version:', cntk.__version__) # Check GPU from cntk.device import try_set_default_device, gpu if try_set_default_device(gpu(0)): print('GPU device is enabled!') # Print devices print('All available devices:', cntk.all_devices()) # Simple math operation prin...
StarcoderdataPython
75267
import urllib.parse import pipestash.output import redis import json import inspect import re import time import random class RedisOutput(pipestash.output.Output): def __init__(self, config): redis_url = urllib.parse.urlparse(config.redis_url) self.redis = redis.StrictRedis(host=redis_url.hostname,...
StarcoderdataPython
106668
<gh_stars>0 import logging logger = logging.getLogger( __name__ ) ## # Interface functions for Hiearchichal Maps (hmaps) # which are jsut dictionaries-of-dictionaries :) ##============================================================================ ## # Returns true iff the given object is a structured key with # g...
StarcoderdataPython
1689181
import Util.Graph as Graph G = {} G[1] = {1:0, 2:2, 3:11, 4:12} G[2] = {2:0, 3:3, 4:6} G[3] = {3:0, 4:1} G[4] = {1:2, 4:0} def FloydWarshall2(G): dist = {} parent = {} for i in G: dist[i] = {} parent[i] = {} for j in G: dist[i][j] = float('inf') parent[i][j...
StarcoderdataPython
116276
import os,sys,subprocess,shutil,time,traceback,fileinput import yaml g_dbg = '-dbg' in sys.argv or False g_dbgexec = g_dbg or ('-dbgexec' in sys.argv or False) try: import mako.template as mako_temp except ImportError: mako_temp = None pass k_vt_col_map = { '':'\x1b[0m', 'default':'\x1b[0m', 'black':'\x1b[30m', 'r...
StarcoderdataPython
1680908
from chitty.cli import run def test_default_runs_without_instrument(mocker): fake_run = mocker.Mock() mocker.patch('chitty.cli.trio.run', fake_run) mocker.patch( 'chitty.cli.parse_args', mocker.Mock(return_value=mocker.Mock(instrument=False)) ) run() fake_run.assert_called_once() a...
StarcoderdataPython
83782
#------------------------------------------------------------------------------------------------------------------- # Packages & Settings #------------------------------------------------------------------------------------------------------------------- # General packages import time import sys import os import date...
StarcoderdataPython
1647976
<filename>utils/transactions.py<gh_stars>0 from threading import Thread, Event import os, datetime, uuid, time, math, ast from typing import List, Dict from alphaz.models.database.structure import AlphaDatabase from alphaz.models.main import AlphaClass, AlphaTransaction from ..libs import transactions_lib from core ...
StarcoderdataPython
3382951
<filename>app/index.py from utils import * monitor_db.create_index(['user', 'pid']) prod_db.create_index(['pid'])
StarcoderdataPython
63532
# -*- coding: utf-8 -*- """Copyright 2015 <NAME>. Code supporting the book Kalman and Bayesian Filters in Python https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python This is licensed under an MIT license. See the LICENSE.txt file for more information. """ from __future__ import (absolut...
StarcoderdataPython
1767313
<reponame>unoriginalbanter/tic_tac_toe<filename>main.py ''' Created on Mar 28, 2016 @author: unoriginalbanter ''' #!/usr/local/bin/python3.5 import tic_tac_toe.interface if __name__ == "__main__": sesh = tic_tac_toe.interface.Interface() sesh.session()
StarcoderdataPython
1688146
from typing import List, Optional, Iterable, Any class SerializerFieldGenerator: # Default django serializer field names. UUID_SERIALIZER_FIELD_NAME = 'serializers.UUIDField' DATE_SERIALIZER_FIELD_NAME = 'serializers.DateField' DATETIME_SERIALIZER_FIELD_NAME = 'serializers.DateTimeField' FOREIGN_K...
StarcoderdataPython
3298846
<reponame>sudarshan85/imminent-adm-mimic #!/usr/bin/env python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split, GroupShuffleSplit def test(a,b,cmp,cname=None): if cname is None: cname=cmp.__name__ assert cmp(a,b),f"{cname}:\n{a}\n{b}" def near(a,b): return np.allclose(...
StarcoderdataPython
1622851
from django.urls import reverse from django.conf import settings from django.contrib.auth.hashers import check_password from django.core.mail import EmailMultiAlternatives from rest_framework import status from restapi import models from .base import APITestCaseExtended from ..utils import decrypt_with_db_secret, get_...
StarcoderdataPython
1653492
""" Demonstrates arithmetic with mixed ints and floats. Uncomment each section to demonstrate different mixed number operations. """ #Example 1 - Adding ints together. #Declares a variable named value1 and assigns it the value 10 value1 = 10 #Declares a variable named value2 and assigns it the value 20 value2 = 20 ...
StarcoderdataPython
1720513
#!/usr/bin/env python # -*- coding: utf-8 -*- from sys import stdin from base64 import b64decode # Fra https://en.wikipedia.org/wiki/Portable_Network_Graphics magic_number = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] # Leser filen fra standard in content = b64decode(stdin.read()) # Xor'er de første 8 tegnene ...
StarcoderdataPython
111190
from mock import Mock from firstclasspostcodes.events import Events class TestEventsClass: def test_an_event_can_be_added(self): mock_handler = Mock(return_value=None) events = Events() events.on('test', mock_handler) assert 'test' in events.events assert mock_handler in ev...
StarcoderdataPython
4819180
<gh_stars>0 ################################################# # Program: CommissionerBot # Version: 0.2.0 # Version Date: 02/13/2021 # Author: <NAME> # Date: 11/14/2020 # Contributor(s): # Parameters: # This bot will auto assign roles when a user reacts to a message with an emoji # Console output will display the ...
StarcoderdataPython
196236
<reponame>Keendata/impala<gh_stars>100-1000 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, ...
StarcoderdataPython
3321553
<reponame>rcooke-ast/VICE<gh_stars>10-100 """ Produces Fig. 3 of Johnson & Weinberg (2019), a 3-column by 1-row plot showing the effect of an outflow smoothing time on starburst model predictions. The left panel shows the inflow and star formation rates with the SFE timescale plotted beneath them, the [O/Fe]-[Fe/H] tra...
StarcoderdataPython
3201607
<reponame>earth-chris/elapid """Unit tests for the elapid/utils.py module""" import os import tempfile from copy import copy import numpy as np import rasterio as rio from elapid import utils # set the test raster data paths directory_path, script_path = os.path.split(os.path.abspath(__file__)) data_path = os.path....
StarcoderdataPython
1601375
from abc import ABC, abstractmethod import networkx as nx from openfermion import QubitOperator from typing import Tuple, List from ._problem_evaluation import ( evaluate_solution, solve_graph_problem_by_exhaustive_search, ) class Problem(ABC): @abstractmethod def _build_hamiltonian(self, graph: nx.Gr...
StarcoderdataPython
1766490
<filename>tasks/black-frames/task/utils.py from base64 import b64encode from functools import reduce from pprint import pformat from time import gmtime, strftime # parses the output of ffmpeg into a dictionary def ffmpeg_black_frames_to_json(lines): lines = [x.split("] ")[1].rstrip() for x in lines if "blackdetec...
StarcoderdataPython
117688
from emaMXL.exceptions import BadApiRequest COMPLETENESS_VALUES = ['raw', 'signature', 'nospace', 'cut'] class EmaExp(object): """ Represents an EMA expression as inputted by a user; no expansion or evaluation of tokens are done yet. We cannot yet represent the request as a single nested structure because ra...
StarcoderdataPython
30009
# # PyGUI - Tasks - Generic # from GUI.Properties import Properties, overridable_property class Task(Properties): """A Task represents an action to be performed after a specified time interval, either once or repeatedly. Constructor: Task(proc, interval, repeat = False, start = True) Creates a task to cal...
StarcoderdataPython