id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
4922898
<reponame>mononobi/charma-server # -*- coding: utf-8 -*- """ streaming manager module. """ import os import time from time import sleep from flask import send_from_directory import pyrin.globalization.datetime.services as datetime_services import pyrin.configuration.services as config_services import pyrin.utils.pa...
StarcoderdataPython
6453787
# Standard Python Libraries import logging # Third Party Libraries from PyQt5.QtCore import QVariant, pyqtSlot, pyqtSignal, QObject, pyqtProperty from PyQt5.QtQml import QJSValue # Project Libraries from py.common.FramListModel import FramListModel class FullSpeciesListModel(FramListModel): def __init__(self, ...
StarcoderdataPython
3591298
from .base_classes import ( Attributes, Component, Container, Content, Element, ElementGroup, TextElement, Void, transform, ) from .components import ContentTemplate, Slot from .content import ( BlockQuotation, ContentDivision, DescriptionDetails, DescriptionList, ...
StarcoderdataPython
321490
from typing import List, Set, Dict, Any, Union def get_bdf_stats(model, return_type='string', word=''): # type: (Any, str, str) -> Union[str, List[str]] """ Print statistics for the BDF Parameters ---------- return_type : str (default='string') the output type ('list', 'string') ...
StarcoderdataPython
4869283
<gh_stars>0 # Server must be restarted after creating new tags file from django import template register = template.Library () @ register.simple_tag def get_comment_count (entry): '' 'Get the total number of comments for an article' '' lis = entry.article_comments.all () return lis.count () @ register.s...
StarcoderdataPython
3599946
<filename>Ene-Jun-2022/victor-geronimo-de-leon-cuellar/printing_functions.py<gh_stars>0 import print_models print_models.make_helado('Vainilla', 'Nueces') print_models.make_helado('Fresa', 'Grajea', 'Nueces', 'Cajeta')
StarcoderdataPython
6671839
<reponame>github16cp/emma #!/usr/bin/python3 from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Activation, Input from keras.utils.test_utils import layer_test from keras.utils.generic_utils import CustomObjectScope import tensorflow as tf import keras.backend as K import keras import ...
StarcoderdataPython
9782641
from flask import jsonify, request, current_app, Blueprint from api import db, bcrypt from api.models import User, Post import jwt import datetime users = Blueprint('users', __name__) session_days = 365 @users.route("/register", methods=['POST']) def register(): name = request.json.get('name') password = request....
StarcoderdataPython
245995
<filename>src/outpost/django/research/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-07 14:08 from __future__ import unicode_literals from django.db import migrations from django.conf import settings class Migration(migrations.Migration): initial = True dependen...
StarcoderdataPython
9725520
# OpenMC z-mesh # # Some code to slice the Serpent assemblies from copy import deepcopy import openmc import openmc.mgxs as mgxs from .meshes import MeshGroup from . import cuts def build_tallies(lat_id, geometry, export_file="tallies.xml"): """Create the 'tallies.xml' file Parameters ---------- lat_id: ...
StarcoderdataPython
392696
<filename>src/python/grapl-common/grapl_common/env_helpers.py from __future__ import annotations import logging import os from typing import TYPE_CHECKING, Any, Callable, NamedTuple, Optional, TypeVar from botocore.client import Config from typing_extensions import Protocol if TYPE_CHECKING: from mypy_boto3_clou...
StarcoderdataPython
3466667
<reponame>hizardapp/Hizard<filename>hyrodactil/openings/models.py from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _ from django_countries import CountryField from model_utils import Choices from model_utils...
StarcoderdataPython
8168143
<reponame>corner4world/cubeai<gh_stars>0 from app.global_data.global_data import g from app.domain.artifact import Artifact def create_artifact(artifact): sql = ''' INSERT INTO artifact ( solution_uuid, name, jhi_type, url, file_size, ...
StarcoderdataPython
6676004
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. # # For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expecte...
StarcoderdataPython
3311981
<filename>tools/videoinfer_opticalflow.py<gh_stars>10-100 import cv2, torch, argparse from time import time import numpy as np from torch.nn import functional as F from models import UNet from models import DeepLabV3Plus from utils import utils from utils.postprocess import postprocess, threshold_mask def parse_args...
StarcoderdataPython
5014070
import os import subprocess from contextlib import contextmanager from os.path import isdir, isfile @contextmanager def inside_dir(path): """ Execute code from inside the given directory :param path: String, path of the directory the command is being run. """ if not isinstance(path, str): ...
StarcoderdataPython
3225246
<reponame>saisankargochhayat/doot from tornado import websocket, web, ioloop import os path=os.getcwd() path=path.strip('Lettertrainer') + 'ML' import sys sys.path.append(path) import tornado.escape from tornado import gen import tornado.httpserver import tornado.options from sklearn.neighbors import KNeighborsClassifi...
StarcoderdataPython
161858
#!/usr/bin/env python # Gemini Flat light controller (National Control Devices Pulsar series) # RLM + DL 19 Jan 2016 import socket import struct import binascii import sys def dimmer(Intensity): # TCP port of light dimmer TCP_IP = '192.168.1.22' TCP_PORT = 2101 BUFFER_SIZE = 1024 # Get desire...
StarcoderdataPython
162343
<reponame>shannonrstewart/FLARE<filename>refactoredforgithub.py<gh_stars>0 import pandas as pd import numpy as np from pandas import DataFrame import statistics, dedupe, json, os, csv, re, unidecode, urllib.parse, requests import sklearn import matplotlib.pyplot as plt import seaborn as sns import imblearn from imblea...
StarcoderdataPython
6680936
import json import logging class Akeneo_Exception(Exception): pass class Akeneo_RequestException(Akeneo_Exception): response = None def __init__(self, response): self.response = response request_body = response.request.body status_code = response.status_code if response...
StarcoderdataPython
6670395
<gh_stars>0 from base64 import b64encode from hashlib import blake2b import random import re import sqlite3 as sql from datetime import date import json from src.constants import MAX_DAY_LIMIT, DIGEST_SIZE, SHORT_URL_SPECIFIER from flask import Flask, jsonify, redirect, request app = Flask(__name__) def url_valid(u...
StarcoderdataPython
9734572
<gh_stars>0 from rest_framework import serializers from listings.models import Listing, HotelRoom, HotelRoomType, BookingInfo class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing fields = "__all__" class HotelRoomSerializer(serializers.ModelSerializer): class Me...
StarcoderdataPython
11235589
a=input("Enter = ") for i in range (len(a)): for j in range (len(a)): if(i==j or j==4-i): print(a[j],end="") else: print(" ",end="") print()
StarcoderdataPython
273839
<gh_stars>1-10 from django.test import TestCase from friends.models import Follow from users.models import User from django.db.models import Q from django.db import connection #Tests if follow outputs the correct users for "followed" and "following" class FollowTestCase(TestCase): person1 = None person2 = Non...
StarcoderdataPython
3508621
<reponame>zatcsc/capreolus # @Collection.register # class MSMarco(Collection): # module_name = "msmarco" # config_keys_not_in_path = ["path"] # collection_type = "TrecCollection" # generator_type = "DefaultLuceneDocumentGenerator" # config_spec = [ConfigOption("path", "/GW/NeuralIR/nobackup/msmarco/...
StarcoderdataPython
325665
# coding=utf-8 # Copyright 2022 The Reach ML Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
StarcoderdataPython
1756289
''' Module functions to properly interact with Database ''' import sqlite3 def add_data(atr, connection): with connection: c = connection.cursor() c.execute("INSERT INTO tempos_atr_2019 (IDAtracacao," "TEsperaAtracacao," "TEsperaInicioOp," "TO...
StarcoderdataPython
1649123
#!/usr/bin/env python # -*- coding: utf-8 -*- # # <NAME> # import sys import os import pandas as pd def main(): # Args in_ot = '../../output/nearest_gene/180830/nearest_gene.tsv.gz' in_vep = 'output/vcf_nearest_gene.txt' # Load ot = pd.read_csv(in_ot, sep='\t', header=0, nrows=1000000) vep =...
StarcoderdataPython
5115185
""" Longest Word: Given a list of words, write a program to find the longest word made of other words in the list. Assume - A word could be formed by any number of other words. - A composed word contains only given words, with no gap in between. (17.15, p583) SOLUTION: DP with memoization to cache the result...
StarcoderdataPython
4973901
# ============================================================================ # FILE: output.py # AUTHOR: momotaro <<EMAIL>> # License: MIT license # ============================================================================ from .base import Base import re class Source(Base): def __init__(self, vim): ...
StarcoderdataPython
229559
import argparse import time import json import csv import re import pandas as pd from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup from requests_html import HTMLSession, HTML from lxml.etree import ParserError from credential import username, ...
StarcoderdataPython
3215856
<reponame>mosout/oneflow """ Copyright 2020 The OneFlow Authors. 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 required...
StarcoderdataPython
3461732
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class InvoiceOrderInfo(object): def __init__(self): self._article_code = None self._article_fee = None self._article_id = None self._article_name = No...
StarcoderdataPython
6539495
file = open('./input') canvas = {} position = (0, 0) direction = 0 input = 1 paint = True def output(x): global input global position global direction global paint if paint: canvas[position] = x else: if x == 0: direction -= 1 if x == 1: direc...
StarcoderdataPython
6401658
<gh_stars>100-1000 import numpy as np import cv2 import tensorflow as tf def postprocess_flow(flow): """ Function to visualize the flow. Args: flow : [H,W,2] optical flow Returs: grayscale image to visualize flow """ flow = flow[:,:,0] # do it dirty, ony first channel min_fl...
StarcoderdataPython
3336865
<filename>python/guided/seeds/seeders/Seed.py from typing import List, Tuple from guided.model.Guide import TransportType, Guide from guided.model.Location import Label, location from guided.model.Row import Row from guided.seeds.seeders.SeedUser import SeedUser class Seed: def __init__(self): self.gene...
StarcoderdataPython
88920
import apache_beam as beam import tensorflow as tf from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from regnety.utils.image_utils import * def _bytes_feature(value): """Returns a bytes_list from a string / byte.""" if isinstance(v...
StarcoderdataPython
4987129
""" MIT License Copyright (c) 2018 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
StarcoderdataPython
1765714
#! /usr/bin/python from twisted.spread import pb from twisted.internet import reactor def main(): rootobj_def = pb.getObjectAt("localhost", 8800, 30) rootobj_def.addCallbacks(got_rootobj) obj2_def = getSomeObjectAt("localhost", 8800, 30, "two") obj2_def.addCallbacks(got_obj2) obj3_def = getSomeObj...
StarcoderdataPython
1805630
<filename>flare/polgrad/ppo.py import torch import torch.nn as nn import torch.nn.functional as f import numpy as np import gym import pybullet_envs import time import flare.kindling as fk from flare.kindling import utils from typing import Optional, Any, Union, Callable, Tuple, List import pytorch_lightning as pl from...
StarcoderdataPython
3220951
<filename>deep_architect/contrib/deep_learning_backend/pytorch_ops.py from math import ceil import torch import torch.nn as nn import torch.nn.functional as F from deep_architect.helpers.pytorch_support import siso_pytorch_module def calculate_same_padding(h_in, w_in, stride, filter_size): h_out = ceil(float(h_...
StarcoderdataPython
5170089
#!/usr/bin/env python """Tests the TMP007 sensor""" import time import logging from nanpy import TMP007 from nanpy.serialmanager import SerialManager logging.basicConfig(level=logging.INFO) logger = logging.getLogger("TMP007") connection = SerialManager(sleep_after_connect=2) connection.open() sensor = TMP007(conn...
StarcoderdataPython
158914
<filename>AutoClean/AutoClean.py import os import sys import pandas as pd from loguru import logger from AutoClean.Modules import * class AutoClean: def __init__(self, input_data, missing_num='auto', missing_categ='auto', encode_categ=['auto'], extract_datetime='s', outliers='winz', outlier_param=1.5, logfile=Tru...
StarcoderdataPython
6685089
"""End to end tests for CLI v2""" from functools import partial try: from unittest import mock except ImportError: import mock from click.testing import CliRunner import pytest from pipcompilemulti.cli_v2 import cli, read_config from .utils import temp_dir @pytest.fixture(autouse=True) def requirements_di...
StarcoderdataPython
3456126
# coding=utf-8 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from dgl.nn import GINConv class MLP(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, num_layers): ''' num_layers: number of layers in the neural networks (EXCLUDING the input ...
StarcoderdataPython
6642373
<gh_stars>0 import numpy as np import random import torch import cv2 from PIL import ImageGrab import requests import bs4 from lxml import html from keyboard import mouse import keyboard import pyautogui import time import pynput.keyboard import os from NET import *
StarcoderdataPython
3204860
<reponame>wstong999/AliOS-Things import utime # 延时函数在utime库中 from driver import GPIO,I2C import sht3x from ssd1306 import SSD1306_I2C hum_s = 0 oled = None sht3xDev = None humi_gpio = None def sht3x_init(): global sht3xDev i2cDev = I2C() i2cDev.open("sht3x") sht3xDev = sht3x.SHT3X(i2cDev) def humi...
StarcoderdataPython
3564691
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-26 14:50 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0108_sanitize_namespace_names'), ] operations = [ migrations.AlterModelOpt...
StarcoderdataPython
1626575
<reponame>Sawyer-Middeleer/divvy-dash<gh_stars>0 from django.db import models import json import requests class Station(models.Model): num_bikes_disabled = models.IntegerField() station_id = models.CharField(max_length=50) num_bikes_available = models.IntegerField() num_docks_available = models.Intege...
StarcoderdataPython
1978895
#!/usr/bin/env python import sys import os sys.path.append(os.getcwd()+"/../modules") import pprint from netaddr import * import pynetbox import csv import yaml # Custom NB modules import my_netbox as nb_tools try: assert all(os.environ[env] for env in ['NETBOX_TOKEN']) except KeyError as exc: print(f"ERROR...
StarcoderdataPython
1940493
<gh_stars>0 from collections import namedtuple TaskCore = namedtuple('TaskCore', ['cached_data_loader', 'data_dir', 'target', 'pipeline', 'parser', 'classifier', 'cv_ratio', 'train', 'test']) class Task(object): """ A Task computes some work and outputs a dictionary which w...
StarcoderdataPython
4849659
<reponame>dfm/celerite2 # -*- coding: utf-8 -*- __all__ = ["terms", "GaussianProcess"] def __set_compiler_flags(): import aesara def add_flag(current, new): if new in current: return current return f"{current} {new}" current = aesara.config.gcc__cxxflags current = add_fl...
StarcoderdataPython
8150389
from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render from django.urls import reverse from django.utils import timezone from django.views import generic from .models import Redditor from .forms import SearchForm class DetailView(generic.DetailView): """ The detail view for...
StarcoderdataPython
214868
from common.make_tx import make_airdrop_tx from terra import util_terra from terra.make_tx import make_lp_unstake_tx def handle_unstake_and_claim(exporter, elem, txinfo): txid = txinfo.txid from_contract = elem["logs"][0]["events_by_type"]["from_contract"] actions = from_contract["action"] contract_a...
StarcoderdataPython
11315769
<reponame>oracle/accelerated-data-science<filename>ads/jobs/utils.py<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf-8; -*- # Copyright (c) 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ import os import json from o...
StarcoderdataPython
370346
import time import torch from torch.nn.utils import clip_grad_norm_ from tqdm import tqdm from custom_utils import get_tensorboard from recbole.data import FullSortEvalDataLoader from recbole.trainer import Trainer from recbole.utils import set_color, get_gpu_usage, early_stopping, dict2str, EvaluatorType class Cus...
StarcoderdataPython
6480659
<reponame>crashb/Cryptopals # solution to http://cryptopals.com/sets/3/challenges/23 # clone a MT19937 PRNG from its output import time from Challenge21 import MT19937 # undoes the right-shift and XOR tempering operation on a value in MT19937. # returns untempered value (int) def unShiftRightXOR(value, shift): resul...
StarcoderdataPython
1984054
<gh_stars>10-100 import numpy as np import torch import pdb import torch.nn as nn from torch.autograd import Variable # from pyquaternion import Quaternion inds = np.array([0, -1, -2, -3, 1, 0, 3, -2, 2, -3, 0, 1, 3, 2, -1, 0]).reshape(4,4) def hamilton_product(q1, q2): q_size = q1.size() # q1 = q1.view(-1, ...
StarcoderdataPython
3525758
<reponame>Anthlis/My_100_Days_Of_Python def my_function(): try: 1 / 0 except ZeroDivisionError: pass if __name__ == "__main__": import timeit setup = "from __main__ import my_function" print(timeit.timeit("my_function()", setup=setup))
StarcoderdataPython
3394685
<gh_stars>1-10 from tfx.orchestration import data_types from tfx import v1 as tfx import os import sys SCRIPT_DIR = os.path.dirname( os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))) ) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, ".."))) from utils import config, custom_compon...
StarcoderdataPython
4951103
import re def test_all_information_on_home_page(app): contact_from_home_page =app.contact.get_contact_list()[0] contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0) assert contact_from_home_page.firstname == contact_from_edit_page.firstname assert contact_from_home_page.lastname == ...
StarcoderdataPython
4918955
_base_url = 'http://www.biomart.org/biomart/martservice' def _attribute_xml( attribute ): "Returns xml suitable for inclusion into query" return '<Attribute name = "%s" />' % attribute def _filter_xml( name, value ): "Returns xml suitable for inclusion into query" return '<Filter name = "%s" value = ...
StarcoderdataPython
12823051
<gh_stars>1-10 from django.conf.urls.defaults import patterns, url urlpatterns = patterns('accounts.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^register/$', 'register', name='register'), url(r'^list/$', 'userlist', name='userlist'), url(r'^profile/(?P<user_i...
StarcoderdataPython
1840575
""" Class description goes here. """ from collections import namedtuple import logging from dataclay.commonruntime.Runtime import getRuntime __author__ = '<NAME> <<EMAIL>>' __copyright__ = '2016 Barcelona Supercomputing Center (BSC-CNS)' logger = logging.getLogger(__name__) DCLAY_PROPERTY_PREFIX = "_dataclay_prop...
StarcoderdataPython
188672
<filename>tests/test_opensearch.py import contextlib import json import os import unittest from collections import deque from copy import deepcopy from pprint import pformat from typing import TYPE_CHECKING from urllib.parse import parse_qsl, urlparse import mock import pytest from pyramid import testing from pyramid....
StarcoderdataPython
3313291
<reponame>protwis/Protwis from build.management.commands.base_build import Command as BaseBuild from build.management.commands.build_ligand_functions import * from django.conf import settings from django.db.models import Prefetch from django.utils.text import slugify from ligand.models import Ligand, LigandType, Assay...
StarcoderdataPython
1751336
import os, sys, re, types import matplotlib.pyplot as plt import sqlalchemy from SphinxReport.Renderer import * from SphinxReport.Tracker import * # for trackers_derived_sets and trackers_master if not os.path.exists("conf.py"): raise IOError( "could not find conf.py" ) exec(compile(open( "conf.py" ).read(), "co...
StarcoderdataPython
6628683
""" Copyright 2017 <NAME> and <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
3391114
""" https://www.practicepython.org MichelePratusevich Exercise 35: Birthday Months 2 chilis This exercise is Part 3 of 4 of the birthday data exercise series. The other exercises are: Part 1, Part 2, and Part 4. In the previous exercise we saved information about famous scientists’ names and birthdays to disk. In t...
StarcoderdataPython
1925787
<gh_stars>1-10 # Copyright 2013-2015 ARM Limited # # 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...
StarcoderdataPython
5116836
# built-in from argparse import REMAINDER, ArgumentParser from pathlib import Path # app from ..actions import get_lib_path, get_python, get_venv from ..config import builders from ..converters import CONVERTERS from ..models import Requirement from .base import BaseCommand class ProjectRegisterCommand(BaseCommand):...
StarcoderdataPython
4898333
<gh_stars>0 """ ** Filtering Info ** To filter scenes by tags one should specify a filter function Scene tags dict has following structure: { 'day_time': one of {'kNight', 'kMorning', 'kAfternoon', 'kEvening'} 'season': one of {'kWinter', 'kSpring', 'kSummer', 'kAutumn'} 'track': one of { 'Moscow' , ...
StarcoderdataPython
3506826
"""Helpers to process schemas.""" import itertools import typing from ... import types from . import iterate class TArtifacts(typing.NamedTuple): """The return value of _calculate_schema.""" schema_name: str property_name: str property_schema: typing.Any TArtifactsIter = typing.Iterator[TArtifact...
StarcoderdataPython
3414490
<gh_stars>10-100 #!/usr/bin/env python3 import os from osgeo import gdal import sys sys.path.append('/foss_fim/src') from utils.shared_variables import PREP_PROJECTION_CM import shutil from multiprocessing import Pool import argparse def reproject_dem(args): raster_dir = args[0] elev_cm ...
StarcoderdataPython
3557548
<reponame>bohdandrahan/Genome-diversity-model-Seed-Root class World(): def __init__(self, abs_max = 1000): self.abs_max = abs_max
StarcoderdataPython
11233775
<reponame>or-tal-robotics/mcl_pi<filename>particle_filter/laser_scan_get_map.py<gh_stars>1-10 #!/usr/bin/env python import rospy from sensor_msgs.msg import LaserScan from nav_msgs.srv import GetMap import numpy as np from matplotlib import pyplot as plt class MapClientLaserScanSubscriber(object): def __init__(...
StarcoderdataPython
11387406
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 import csv import logging import os import shutil from csv import DictWriter from typing import ( Any, Dict, FrozenSet, ) from pyhocon import ConfigFactory, ConfigTree from databuilder.job.base_job import Job from databuilder...
StarcoderdataPython
4892671
<filename>eth2/beacon/state_machines/forks/serenity/configs.py<gh_stars>0 from eth.constants import ( ZERO_ADDRESS, ) from eth2.configs import Eth2Config from eth2.beacon.constants import ( GWEI_PER_ETH, ) from eth2.beacon.helpers import slot_to_epoch from eth2.beacon.typing import ( Gwei, Second, ...
StarcoderdataPython
358189
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from library.python import resource import pytest import ssl # import urllib2 class TestRequest(object): @pytest.fixture def ctx(self): r = resource.find("/builtin/cacert") # ssl.create_default_context expects unicode string for pem-coded certif...
StarcoderdataPython
62503
from dataclasses import dataclass from typing import Dict from typing import Optional @dataclass(frozen=True) class CurrentDestinationStatus: number_of_pending_messages: Optional[int] number_of_consumers: int messages_enqueued: int messages_dequeued: int @dataclass(frozen=True) class ConsumerStatus:...
StarcoderdataPython
123234
from azureml.core.model import Model from azuremite.workspace import get_workspace def model_register(): ws = get_workspace() model = Model.register(workspace=ws, model_path="../artifacts/worst.pickle", model_name="worst-model") return model def get_model_path(): ws = get_workspace() model_path = ...
StarcoderdataPython
11287797
<reponame>ksbhatkana/ksbhat-for-python import re strr="Hi, This is Kumara subrahmanya bhat alias ksbhat" f1=open("File1.txt") strre=str(f1.read()) st=re.compile(r'[+91]{3}-[0-9]{10}') mates=st.finditer(strre) ls=[i for i in mates] print(ls[:])
StarcoderdataPython
3397001
<filename>hknweb/tests/views/test_users.py from django.conf import settings from django.test import TestCase from django.urls import reverse from hknweb.events.tests.models.utils import ModelFactory class UsersViewsTests(TestCase): def setUp(self): password = "<PASSWORD>" user = ModelFactory.cre...
StarcoderdataPython
181007
#!/usr/bin/env python3 import random import libyiban import libyiban_ex NEWS_K = 3 NEWS_CATEGORIES = [ libyiban_ex.XinHuaNews.CATEGORY.TECH, libyiban_ex.XinHuaNews.CATEGORY.POLITICS, libyiban_ex.XinHuaNews.CATEGORY.ENG_SCITECH_INTERNET ] def latest_news(count_per_category): ''' Prettify latest ...
StarcoderdataPython
3202374
import os import platform import tempfile import time from pathlib import Path from test.conftest import TEST_REF, conan_create_and_upload from typing import List from conan_app_launcher.core.conan import (ConanApi, ConanCleanup, _create_key_value_pair_list) from co...
StarcoderdataPython
3227115
<filename>lanzou/gui/dialogs/setting.py import os from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import (QDialog, QLabel, QDialogButtonBox, QLineEdit, QCheckBox, QHBoxLayout, QVBoxLayout, QFormLayout, QFileDialog) from lanzou.gui.qss import dia...
StarcoderdataPython
12843181
<reponame>MuhammedAshraf2020/ImageColorization from processing import * from decodingModel import * # Using Transfer learning feature_extract_model = VggModel() #Decoding model colorize = model() #prepare data in hard disk PrepareData(datapath = "/content/data" , save_file = "/content/processed/" , ta...
StarcoderdataPython
5136623
<filename>src/meadowrun/azure_integration/mgmt_functions/clean_up/__init__.py """ This code cannot reference anything outside of mgmt_functions (as that's what gets uploaded to the Azure function). We use relative imports which will work both in the "regular" environment as well as in the Azure function """ import asy...
StarcoderdataPython
1718879
from abc import ABC from typing import Dict, Sequence, Optional, List, Any from allenact.base_abstractions.experiment_config import ExperimentConfig from allenact.base_abstractions.sensor import Sensor class GymBaseConfig(ExperimentConfig, ABC): SENSORS: Optional[Sequence[Sensor]] = None def _get_sampler_a...
StarcoderdataPython
4928330
import os.path import os from os import mkdir, makedirs, rename, listdir from os.path import join, exists, relpath, abspath from data.base_dataset import BaseDataset, get_params, get_transform from data.image_folder import make_dataset from PIL import Image import random import numpy as np class PairedNirDataset(BaseD...
StarcoderdataPython
3315007
<filename>recognition/audio_settings.py<gh_stars>1-10 from typing import List from audio import AudioSettings def get_common_settings(settings: List[AudioSettings]) -> AudioSettings: channels = settings[0].channels sample_format = settings[0].sample_format sample_rate = settings[0].sample_rate for set...
StarcoderdataPython
362976
#!/usr/bin/env python #****************************************************************************** # Name: ingests1s2.py # Purpose: Unpack and ingest time series of sentinel-1 vv, vh single pol # SAR or VVVH dual pol diagonal only images # exported from Earth Engine to and downloaded f...
StarcoderdataPython
6488662
class EntityNotFoundException(Exception): pass class EntityAlreadyExistsException(Exception): pass
StarcoderdataPython
6463637
import logging import common.ibc.processor import fet.constants as co import fet.fetchhub1.constants as co2 import common.ibc.processor import common.ibc.handle import common.ibc.constants from fet.config_fet import localconfig from settings_csv import FET_NODE from fet.fetchhub1.processor_legacy import process_tx_lega...
StarcoderdataPython
3357581
__author__ = 'nick' import unittest import numpy as np from hmm_localisation.hmm import HMM from hmm_localisation.robot import Direction class TestHMM(unittest.TestCase): def test_probable_transitions_corner(self): model = HMM(8, 8) corner = (7, 0, Direction.SOUTH) expected = [((7, 1, D...
StarcoderdataPython
1738320
<filename>SPGPylibs/PHItools/phifdt_flat.py #============================================================================= # Project: SoPHI # File: phifdt_flat.py # Author: <NAME> (<EMAIL>) # Contributors: <NAME> and <NAME> (<EMAIL>) #----------------------------------------------------------------------------- # D...
StarcoderdataPython
228979
from collections import Counter from tool.runners.python import SubmissionPy class ThoreSubmission(SubmissionPy): def run(self, s): """ :param s: input in string format :return: solution flag """ N_DAYS = 100 black_hexs = self.parse_start_grid(s) for _ in ...
StarcoderdataPython
252897
from org.sfu.billing.utils.configurations import SparkConfig from org.sfu.billing.utils.dataLayer import dataLoader from org.sfu.billing.devices.cdr import CallDetailRecord from pyspark.sql import functions from pyspark.sql.functions import split class Controller: """ Controller class is used to control life...
StarcoderdataPython
34440
<reponame>BLSQ/iaso-copy<gh_stars>10-100 import re from django.db.models import Q, Count, Sum, Case, When, IntegerField, Value from iaso.models import OrgUnit, Instance, DataSource def build_org_units_queryset(queryset, params, profile): validation_status = params.get("validation_status", OrgUnit.VALIDATION_VAL...
StarcoderdataPython
11288399
import os from tabnanny import check import yaml import sys import pandas as pd import numpy as np config = yaml.load(open(os.path.join(os.path.dirname(__file__),'config.yaml')), yaml.FullLoader) SAMPLE_NUM = config['sample_number'] def refractorAppComputeInfo(computeInfoFile): infoFile = open(computeInfoFile, "r") ...
StarcoderdataPython