id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3530334
__all__ = ["crc"] from . import crc
StarcoderdataPython
11231545
import re import sys import toml from collections import namedtuple # TODO handle [[patch.unused]] Lock = namedtuple('Lock', ['packages', 'checksums']) Package = namedtuple('Package', ['name', 'version', 'source']) Source = namedtuple('Source', ['type', 'value']) Entry = namedtuple('Entry', ['package', 'dependencies...
StarcoderdataPython
1627778
import prefect from prefect import task, Flow @task def hello_task(): logger = prefect.context.get("logger") logger.info("Hello world!") with Flow("hello-flow") as flow: hello_task() flow.run()
StarcoderdataPython
11248551
<filename>melodic/lib/python2.7/dist-packages/rqt_pose_view/pose_view_widget.py # Copyright (c) 2011, <NAME>, TU Darmstadt # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions...
StarcoderdataPython
11367907
<gh_stars>0 from flask import Blueprint, g, request from flask import current_app as app import kubecortex_backend.helpers.prometheus_helper as prometheus_helper import json import os main = Blueprint('main', __name__) prometheus_host = os.environ['PROMETHEUS_HOST'] @main.route('/pods') def pods(): try: ...
StarcoderdataPython
351960
<filename>app/schema/answers/percentage_answer.py from app.schema.answer import Answer from app.schema.widgets.percentage_widget import PercentageWidget from app.validation.percentage_type_check import PercentageTypeCheck class PercentageAnswer(Answer): def __init__(self, answer_id=None): super().__init__...
StarcoderdataPython
4920574
# @author: snxq import datetime import os import os.path import shutil import sys import time """ 照片存档 参数:源文件目录,存档目录 """ def existsOrCreate(path): if not os.path.exists(path): os.makedirs(path) def archive(src_path, save_path): count = 0 for dirpath, dirnames, filenames in os.walk(src_path): ...
StarcoderdataPython
6685252
# -*- coding: utf-8 -*- import os import json from zipfile import ZipFile from gluon.contrib.markdown import markdown2 import libConCoct.concoct @auth.requires_login() def view(): """ Shows all tasks if no argument is given or details of a specific task. /task/view/[task id] -> view detailed informati...
StarcoderdataPython
3553434
<filename>src/labels/github.py import logging from typing import Any, Dict, List, Optional, Tuple import attr import requests from labels.exceptions import GitHubException @attr.s(auto_attribs=True, frozen=True) class Repository: """Represents a GitHub repository.""" owner: str name: str def not_read...
StarcoderdataPython
5173589
# -*- coding: utf-8 -*- def sum_pows(a: int, b: int, c: int, d: int) -> int: """ >>> sum_pows(9, 29, 7, 27) 4710194409608608369201743232 """ return a**b + c**d if __name__ == '__main__': a, b, c, d = (int(input()) for _ in range(4)) print(sum_pows(a, b, c, d))
StarcoderdataPython
4955903
import os from dotenv import load_dotenv from django import django, render_template, request, abort from twilio.jwt.access_token import AccessToken from twilio.jwt.access_token.grants import VideoGrant load_dotenv() twilio_account_sid = os.environ.get('TWILIO_ACCOUNT_SID') twilio_api_key_sid = os.environ.get('TWILIO_A...
StarcoderdataPython
3293867
<reponame>stefanmerb/dash_webapp<filename>simple_webapp.py import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import dash_bootstrap_components as dbc app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP]) server = app.server ap...
StarcoderdataPython
192303
from http import HTTPStatus import pytest import requests from rotkehlchen.constants.assets import A_ETH, A_EUR, A_KRW, A_USD from rotkehlchen.fval import FVal from rotkehlchen.tests.utils.api import ( api_url_for, assert_error_response, assert_proper_response, assert_proper_response_with_result, ) ...
StarcoderdataPython
1935145
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-12-20 17:34 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contentcuration', '0001_squashed_0094_auto_20180910_234...
StarcoderdataPython
1838555
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ARQUIVO.py # # Copyright 2021 # Autor: <NAME> # ############################ # Código fonte em Python 3 ############################ def reposta(n): n = str(n) arm = "" for x in range(len(n)-1,-1,-1): arm = arm + n[x] arm = int(arm...
StarcoderdataPython
9760354
<gh_stars>1-10 # Device List devices = { 'pmd':[ 'lantz.drivers.thorlabs.pm100d.PM100D', ['USB0::0x1313::0x8078::P0019269::INSTR'], {} ] } # Experiment List spyrelets = { 'align':[ 'spyre.spyrelets.single_step_align_cwicker_spyrelet.ALIGNMENT', {'pmd':'pmd'}, ...
StarcoderdataPython
4935952
<reponame>clean-code-craft-tcq-1/add-variety-python-ccharan94 import unittest import typewise_alert class TypewiseTest(unittest.TestCase): def test_infers_breach_as_per_limits(self): #Check Breaches self.assertTrue(typewise_alert.infer_breach(10, 20, 60) == 'TOO_LOW') self.assertTrue(typewise_aler...
StarcoderdataPython
6660638
<reponame>Ureimu/weather-robot # coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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
58343
import math import unittest from py_range_parse import parse_range class ParseTest(unittest.TestCase): def test_parse_equal_values(self): parsed_range = parse_range("[-inf..-inf]") self.assertIn(-math.inf, parsed_range) def test_parse_spaces(self): parsed_range = parse_range("[ -8.3...
StarcoderdataPython
6643467
<reponame>domWinter/opencv_nn import torch from PIL import Image import torch.nn as nn import torch.nn.functional as F from torchvision import transforms from torch.autograd import Variable import matplotlib.pyplot as plt from vis_utils import visualize_grid class ClassificationCNN(nn.Module): def __init__(self, i...
StarcoderdataPython
1819464
import os,sys, subprocess from time import sleep, time RED, GREEN, BLUE, YELLOW, WHITE, END= '\033[1;31m', '\033[1;32m', '\033[1;34m', '\033[1;33m', '\033[1;37m', '\033[0m' spaces = " " * 76 # Only for styling threshold = 12 mac_dict = {} time_dict = {} #Checking for root privilleges try: if os.getuid() != 0: ...
StarcoderdataPython
6547967
from dataclasses import dataclass from bindings.gmd.code_with_authority_type import CodeWithAuthorityType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class PixelInCell(CodeWithAuthorityType): """gml:pixelInCell is a specification of the way an image grid is associated with the image data attribut...
StarcoderdataPython
223840
# -*- coding: utf-8 -*- from dataclasses import dataclass from typing import Optional @dataclass class ExternalIDs: facebook_id: Optional[str] freebase_id: Optional[str] freebase_mid: Optional[str] imdb_id: Optional[str] instagram_id: Optional[str] tvdb_id: Optional[int] tvrage_id: Optiona...
StarcoderdataPython
6560261
"""Define constants for tests.""" TEST_BAD_ZIP = "abcde" TEST_ZIP = "00123"
StarcoderdataPython
11317395
<gh_stars>0 from pluto.control.modes.processes import process_factory as pf class LiveSimulationProcessFactory(pf.ProcessFactory): def __init__(self, process_factory): self._process_factory = process_factory def _create_process(self, framework_url, session_id, root_dir): pass
StarcoderdataPython
113175
<reponame>eengineergz/Lambda import random def guessing_game(): print("Guess the number!") secret_number = random.randrange(101) while True: guess = input("Input your guess: ") try: guess = int(guess) except ValueError: print("Please enter an integer.") continue print(f"...
StarcoderdataPython
3464552
<filename>code/Evaluation.py ''' <NAME> (2018UCS0078), CSE Department, IIT JMU contact: <EMAIL> This code contains a set of functions used for evaluating the Music Recommender System with the help of mean average precision at tau(=500). This is part of the Music Recommender System project (Dataset as Subset of Mil...
StarcoderdataPython
8175965
<reponame>tunealog/python-web-scraping # Python Web Scraping # Title : BeautifulSoup4 # Date : 2020-08-15 # Creator : tunealog import requests from bs4 import BeautifulSoup url = "https://comic.naver.com/webtoon/list.nhn?titleId=675554" res = requests.get(url) res.raise_for_status() soup = BeautifulSoup(res.text, "...
StarcoderdataPython
1921994
#!/usr/bin/env python import argparse import re AMPLICON_PAT = re.compile(r'.*_(?P<num>\d+).*_(?P<name>L(?:EFT)?|R(?:IGHT)?)') def write_amplicon_info_file(bed_file, amplicon_info_file): amplicon_sets = {} for line in bed_file: fields = line.strip().split('\t') start = int(fields[1]) ...
StarcoderdataPython
11223201
class Pessoa: def __init__(self): self.nome = 'Uadson' def __str__(self): return self.nome class Idade: def __init__(self): self.idade = 37 class Evolucao(Idade): def __init__(self): self.nome = Pessoa() super().__init__() self.evolui = [self.nome.nome, self.idade] def atualiza(self): self....
StarcoderdataPython
6706654
<filename>rake_tutorial.py from __future__ import absolute_import from __future__ import print_function import six __author__ = 'a_medelyan' import rake import operator import io # EXAMPLE ONE - SIMPLE stoppath = "SmartStoplist.txt" # 1. initialize RAKE by providing a path to a stopwords file rake_object = rake.Rake...
StarcoderdataPython
9685013
<gh_stars>1-10 import setuptools def long_desc(): with open('README.md', 'r') as desc: return desc.read() setuptools.setup( name = 'pyislam', version = '0.1.1', author = '<NAME>', author_email = '<EMAIL>', description = 'An Islamic Python Package', long_description = long_desc(), ...
StarcoderdataPython
3366515
<gh_stars>1-10 from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from decimal import Decimal import discord from discord.ext import commands import user_db import config # connect to coind rpc_connection = 'http://{0}:{1}@{2}:{3}'.format(config.rpc_user, config.rpc_password, config.ip, config.rpc_po...
StarcoderdataPython
1919292
from typing import Optional, Tuple from flexmeasures.data import db class GenericAssetType(db.Model): """An asset type defines what type an asset belongs to. Examples of asset types: WeatherStation, Market, CP, EVSE, WindTurbine, SolarPanel, Building. """ id = db.Column(db.Integer, primary_key=True...
StarcoderdataPython
1673711
t1 = (1, 2, 3, 'a', 'samu') """ A tupla funciona exatamente igual a uma lista, a unica diferença é que eu não posso alterar os valores que ela contem após sua formação """
StarcoderdataPython
11395974
<gh_stars>0 if __name__ == '__main__': dic = {} s = list() for _ in range(int(input())): name = input() score = float(input()) if score in dic: dic[score].append(name) else: dic[score] = [name] if score not in s: s.append(score) ...
StarcoderdataPython
6516571
<gh_stars>0 #!python def is_sorted(items): """Return a boolean indicating whether given items are in sorted order. Running time: O(n) because we are using a loop to traverse through each item in the list Memory usage: O(1) because we aren't creating any additional data structures in the function""" # ...
StarcoderdataPython
1788850
<gh_stars>0 import numpy as np from VariableUnittest import VariableUnitTest from gwlfe.BMPs.Stream import UrbLoadRed class TestUrbLoadRed(VariableUnitTest): def test_UrbLoadRed(self): z = self.z # UrbLoadRed.UrbLoadRed_1(z.NYrs, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.NRur, z.NUrb, z.Area,...
StarcoderdataPython
6496429
<gh_stars>1-10 from lenstronomy.Data.psf import PSF import lenstronomy.Util.util as util import lenstronomy.Util.image_util as image_util import lenstronomy.Util.kernel_util as kernel_util import lenstronomy.Util.mask as mask_util import numpy as np import copy import scipy.ndimage.interpolation as interp class PsfF...
StarcoderdataPython
9722147
import sys from .finalproject2 import neuralnet
StarcoderdataPython
5058723
<filename>merchant/migrations/0001_initial.py # Generated by Django 3.2 on 2021-04-25 10:02 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
StarcoderdataPython
9661528
# automatically generated by the FlatBuffers compiler, do not modify # namespace: DeepSeaVectorDrawScene import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class RadialGradient(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatb...
StarcoderdataPython
3333249
from typing import List class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: # the idea is to iterate through the "intervals" list # check if each "interval" overlaps with "newInterval" # if overlapping, we update the "newInterval...
StarcoderdataPython
9661127
#!/usr/bin/env python3 ''' Created on 04.02.2020 @author: JM ''' if __name__ == '__main__': pass import time import PyTrinamic from PyTrinamic.connections.ConnectionManager import ConnectionManager from PyTrinamic.modules.TMCC160.TMCC_160 import TMCC_160 PyTrinamic.showInfo() #connectionManager = ConnectionMana...
StarcoderdataPython
202006
import pandas as pd from trectools import TrecQrel class BaseLabelTransfer: def keep_doc(self, doc_id): return doc_id in self.ids_to_transfer class CW12UrlLabelTransfer(BaseLabelTransfer): def __init__(self, input_files): df = load_input_files_to_dataframe(input_files) df = df[(df['c...
StarcoderdataPython
210389
# Wrapper module for _elementtree from _elementtree import *
StarcoderdataPython
6495204
__author__ = 'ferrard' # --------------------------------------------------------------- # Imports # --------------------------------------------------------------- import random # --------------------------------------------------------------- # Constants # ----------------------------------------------------------...
StarcoderdataPython
1986819
import asyncio import http.client import os import re import unicodedata from io import BytesIO from math import floor from pathlib import Path from typing import Literal, Optional from urllib import parse import aiohttp import dateutil.parser import discord import httpx import pyppeteer import pyppeteer.errors import...
StarcoderdataPython
9719415
# The MIT License (MIT) # Copyright (c) 2018 Massachusetts Institute of Technology # # Author: <NAME> # This software has been created in projects supported by the US National # Science Foundation and NASA (PI: Pankratius) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this softwa...
StarcoderdataPython
12840686
<reponame>jmzhao/CS704-asn3<filename>pdr/__init__.py<gh_stars>0 # -*- coding: utf-8 -*- """ @author: jmzhao """ from pdr import * import test
StarcoderdataPython
3440789
<gh_stars>0 def peakfinder(data, time, xbin): peaks = [] for i in range(len(time)-1): if data[i]>data[i+1] and data[i]>data[i-1] and data[i]>data[i+xbin] and data[i]>data[i-xbin]: peaks.append(data[i]) indx = [] for i in range(len(data)): if data[i] in peaks: indx...
StarcoderdataPython
1797615
from fastapi import HTTPException class RequestValidationError(HTTPException): def __init__(self, loc, msg, typ): super().__init__(422, [{'loc': loc, 'msg': msg, 'type': typ}])
StarcoderdataPython
5166624
# static analysis: ignore from .test_node_visitor import skip_before from .test_name_check_visitor import TestNameCheckVisitorBase class TestPatma(TestNameCheckVisitorBase): @skip_before((3, 10)) def test_singletons(self): self.assert_passes( """ from typing import Literal ...
StarcoderdataPython
6418976
<gh_stars>0 from typing import Any, Union, Dict, Mapping from pathlib import Path from ruamel.yaml import YAML import pickle import h5py import numpy as np from numbers import Number PathLike = Union[str, Path] yaml = YAML(typ='safe') def read_yaml(fname: Union[str, Path]) -> Any: """Read the given file using ...
StarcoderdataPython
4811519
<reponame>SuviVappula/hauki # Generated by Django 3.1.2 on 2020-11-03 08:07 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("hours", "0003_add_is_public_to_resource"), ] operations = [ migrations.AlterFie...
StarcoderdataPython
1652768
import numpy as np # import torch from PIL import Image import matplotlib.pyplot as plt from functools import reduce A = np.identity(4) A P = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) P Q = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) Q B = np.arange(16).reshape((4,...
StarcoderdataPython
1748202
from distutils.core import setup with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name = 'et2adem', # How you named your package folder (MyLib) long_description = long_description, long_description_content_type = "text/markdown", packages = ['et2adem'], # Ch...
StarcoderdataPython
6524968
<filename>deep_rl/component/memory_lineworld.py<gh_stars>0 import numpy as np import gym from gym import spaces import matplotlib.pyplot as plt import random from PIL import Image, ImageDraw, ImageFont class MemoryLineWorld(gym.Env): def __init__(self, size=5, p=0, horizon=100): # Setting things u...
StarcoderdataPython
3478243
from typing import Any, Dict, List, Optional, Tuple import emojis ALLIANCE_MEMBERSHIP: Dict[str, str] = { 'Candidate': 'Candidate', 'Ensign': 'Ensign', 'Lieutenant': 'Lieutenant', 'Major': 'Major', 'Commander': 'Commander', 'ViceAdmiral': 'Vice Admiral', 'FleetAdmiral': 'Fleet Admiral' } ...
StarcoderdataPython
1964701
<gh_stars>1-10 import base64 import copy import json import logging import os import tempfile from unittest import mock import pandas as pd import pytest import requests from fortigaterepr.devicedata import get_helper, clean_columns_helper from .example_data import INTERFACE_DETAILS_RESULT # TODO: Module scoped fi...
StarcoderdataPython
3575667
<reponame>gezp/ros_ign_gazebo_py import threading import rclpy from rclpy.node import Node from geometry_msgs.msg import Transform from ros_ign_interfaces.srv import ControlWorld,SpawnEntity,DeleteEntity,SetEntityPose class IgnGazeboInterface(Node): def __init__(self,world_name="default",nodename="IgnGazeboInter...
StarcoderdataPython
3334227
<filename>rdmo_re3data/__init__.py __title__ = 'rdmo-re3data' __version__ = '1.0' __author__ = 'RDMO Arbeitsgemeinschaft' __email__ = '<EMAIL>' __license__ = 'Apache-2.0' VERSION = __version__ from .providers import *
StarcoderdataPython
1875591
# # @lc app=leetcode id=16 lang=python # # [16] 3Sum Closest # # https://leetcode.com/problems/3sum-closest/description/ # # algorithms # Medium (38.77%) # Total Accepted: 286K # Total Submissions: 704.1K # Testcase Example: '[-1,2,1,-4]\n1' # # Given an array nums of n integers and an integer target, find three in...
StarcoderdataPython
1720362
import os import subprocess import sys import tempfile import MeCab __neologd_repo_name = 'mecab-ipadic-neologd' __neologd_repo_url = 'https://github.com/neologd/mecab-ipadic-neologd.git' def download_neologd(dic_path): dic_path = os.path.abspath(dic_path) with tempfile.TemporaryDirectory() as temp_dir: ...
StarcoderdataPython
297723
def rand_phase(p): import numpy as np # This assumes -pi<p<pi. # Move p to 0<p<2pi and add random phase pf = p+np.pi+np.random.uniform(0,2*np.pi,p.size) # Move phases back into 0<pf<2pi pf[pf>2*np.pi] -= 2*np.pi # Move pf to -pi<pf<pi return pf-np.pi def signal_rand_phase(S): impor...
StarcoderdataPython
160356
""" This is uproot-browser. There is no user accessible API; only a terminal interface is provided currently. """ from __future__ import annotations __all__ = ()
StarcoderdataPython
3531900
<filename>app/helpers.py # helpers.py # # Copyright(c) <NAME> <<EMAIL>> # Licensed under MIT # Version 2.0.0 import string import random def rand_uid(length): str_pool = string.ascii_lowercase + string.ascii_uppercase + string.digits random_str = ''.join((random.SystemRandom().choice(str_pool) for _ in range(leng...
StarcoderdataPython
12845280
<filename>galaxy/main/urls.py # (c) 2012-2018, Ansible by Red Hat # # This file is part of Ansible Galaxy # # Ansible Galaxy is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by # the Apache Software Foundation, either version 2 of the License, or # (at your...
StarcoderdataPython
6459601
<filename>fiftyone/utils/data/converters.py """ Dataset format conversion utilities. | Copyright 2017-2022, Voxel51, Inc. | `voxel51.com <https://voxel51.com/>`_ | """ import inspect import logging import eta.core.utils as etau import fiftyone as fo import fiftyone.types as fot logger = logging.getLogger(__name__)...
StarcoderdataPython
128934
<filename>tests/unit/decider/test_daemon.py import pytest import floto.decider @pytest.fixture def history(init_response): return floto.History(domain='d', task_list='tl', response=init_response) @pytest.fixture def daemon(history): daemon = floto.decider.Daemon(domain='d', task_list='tl_daemon', swf='swf') ...
StarcoderdataPython
9642479
from scrapli.driver.core import NXOSDriver def test_nxos_driver_init_telnet(): conn = NXOSDriver(host="myhost", transport="telnet") assert conn.transport.username_prompt == "login:"
StarcoderdataPython
5108960
<gh_stars>0 """ You are given an array of non-negative integers, and are initially positioned at the first index of the array. Each element in the array represents your maximum jump length from that position. Determine if you are able to reach the last index. Example 1: Input: [2, 3, 1, 1, 4], Output: true Explanatio...
StarcoderdataPython
8040070
<filename>apiai_assistant/widgets/image.py<gh_stars>1-10 from . import GoogleAssistantWidget class Button(GoogleAssistantWidget): def __init__(self, title, weblink=None): self.title = title self.weblink = weblink super(Button, self).__init__() def render(self): return { ...
StarcoderdataPython
6680220
<filename>src/graphic/gquery.py #!/usr/bin/env python # -*- encoding: utf-8 -*- import copy from .graph import GraphEntity from .query.query_utils import Q, Field, Expression __all__ = ['GQuery'] class Context: FIELD_LOOKUP_SPLIT_BYS = ('__', '.', ) __slots__ = ('_name_2_ent') def __init__(self): ...
StarcoderdataPython
6463199
<reponame>shiksha360-site/site # Ported from https://github.com/Fates-List/FatesList/blob/main/modules/core/system.py from fastapi.responses import HTMLResponse from starlette.middleware.base import BaseHTTPMiddleware from loguru import logger from http import HTTPStatus import uuid import datetime from lynxfall.utils...
StarcoderdataPython
3255371
<filename>yggdrasil/examples/tests/__init__.py import os import six import uuid import unittest import tempfile import shutil import itertools import flaky from yggdrasil.components import ComponentMeta, import_component from yggdrasil import runner, tools, platform from yggdrasil.examples import ( get_example_yaml...
StarcoderdataPython
3590974
<reponame>thomasfrederikhoeck/ml_tooling import numpy as np import pandas as pd from ml_tooling.utils import DataType def target_correlation( features: pd.DataFrame, target: DataType, method: str = "pearson" ) -> pd.Series: """ Calculate target_correlation between features and target and returns a sorted...
StarcoderdataPython
5154188
import os import torch import torch.utils.data as data from PIL import Image import numpy as np import pandas as pd import ast import utils def get_loader(transform, mode='train', batch_size=1, start_word="<start>", end_word="<end>", num_worke...
StarcoderdataPython
1971794
<reponame>WilsonWangTHU/neural_graph_evolution # ----------------------------------------------------------------------------- # @brief: # In this function, we define the base agent. # The base agent should be responsible for building the policy network, # fetch the io placeholders / tensors, and se...
StarcoderdataPython
1732217
<filename>speech/livespeech_recognise.py #!/usr/bin/python # encoding: utf-8 from __future__ import print_function import os import socket from pocketsphinx import LiveSpeech, get_model_path from __playwave import playwave from __baidu_speech_recognise import get_baidu_asr sys_model_path = get_model_path() voice_pa...
StarcoderdataPython
5101155
<filename>Python - Desafios e Execercios resolvidos/Des002.py nome = input('Qual o seu nome? ') print(f'Olá {nome}, seja bem vindo!')
StarcoderdataPython
8145994
<filename>crypto_tracking/trackingAPI/tasks.py # tracking the cryptocurrecny using celery # crawling cryptocurrency using beautifulsoup4 # celery used for async tasks from celery import shared_task from celery.schedules import crontab from celery.decorators import periodic_task # beautifulsoup used for scraping da...
StarcoderdataPython
8069453
<filename>src/ai_harness/harnessutils.py import yaml import logging import logging.config from ai_harness import xml2object try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper def load_yaml(file: str): try: with open(file, 'r') as stream:...
StarcoderdataPython
5122002
<reponame>CSIRT-MU/CRUSOE class Perspectives: def __init__(self, client): self.client = client def all(self): resource = "/perspectives" return self.client.get(resource) def name_to_id(self, name): """ Obtain all perspectives and then seek for ID of perspective with...
StarcoderdataPython
4983060
<reponame>IsThisLoss/manga-notify # flake8: noqa: E402 import logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO, ) import os import datetime from . import bot from . import background from . import settings import sqlite3 import telegram.ext d...
StarcoderdataPython
272371
from pathlib import Path import os, sys, shutil import subprocess import pandas as pd import string if len(sys.argv) != 2: print("Usage: ./extract_gps.py <video dir>") sys.exit() def convert_latlong(in_str): split_latlong = in_str.split(' ') return float(split_latlong[0]) + float(split_latlong[2][:-1]...
StarcoderdataPython
1879282
<gh_stars>0 from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import authenticate, get_user_model, login, logout from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from re...
StarcoderdataPython
3211576
<filename>src/main/Client/Client.py # coding : utf-8 from ssl import SSLSocket from time import sleep from util import * import yaml import requests from PySide2.QtWidgets import QApplication, QMessageBox from PySide2.QtUiTools import QUiLoader from PySide2.QtCore import QFile # 登陆UI界面类 class ClientWindow: def...
StarcoderdataPython
1621500
"""Signal handlers of Zinnia""" import inspect from functools import wraps from django.db.models import F from django.dispatch import Signal from django.contrib import comments from django.db.models.signals import post_save from django.db.models.signals import pre_delete from django.contrib.comments.signals import com...
StarcoderdataPython
6636827
<gh_stars>0 # Generated by Django 3.2 on 2021-06-20 12:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('area', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='area', name='name', )...
StarcoderdataPython
11378595
import json import requests from ._volumes import _Volumes from ._infos import _Infos from ._liquidations import _Liquidations from ._indicators import _Indicators class Cryptometer(): def __init__(self, api_key): self._api_key = api_key self._api_url = "https://api.cryptometer.io" self.i...
StarcoderdataPython
6585537
<reponame>lynnli92/leetcode-group-solution<filename>AlgorithmProblems/0245. Shortest Word Distance III/main0245.py from typing import List class Solution0245: def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: wordLen = len(wordsDict) prev = -1 isEqual = (...
StarcoderdataPython
8040620
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Optional, Tuple, Union import hypothesis.strategies as st import torch import torch.nn as nn from hypothesis import given, settings from opacus.layers import DPGRU, DPLSTM, DPRNN from opacus.utils.packed_s...
StarcoderdataPython
9733106
<filename>backend/app/crud/crud_blog.py from datetime import datetime from typing import Any, Dict, List, Optional, Union from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from sqlalchemy import desc from app.core.security import get_password_hash, verify_password from app.crud.base imp...
StarcoderdataPython
1811314
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Testing authentication functions.""" import logging import hvac import pytest from broccolini.authentication_functions import VaultFunctions logging.basicConfig(level=logging.DEBUG, format=" %(asctime)s - %(levelname)s - %(message)s") class TestVaultFunctions: ...
StarcoderdataPython
12851055
import pandas as pd import numpy as np from os import path from path_service import LOG_DIR, DATA_DIR from sklearn.metrics import log_loss import re prob_columns = list(map(lambda x: f"prob{x}", range(8))) prob_columns_without_end = list(map(lambda x: f"prob{x}", range(7))) def row_check(df: pd.DataFrame): df.loc...
StarcoderdataPython
5008262
<gh_stars>1-10 from wrapper import Bittrex __version__ = "0.0.1"
StarcoderdataPython
4933713
<reponame>marvinquiet/RefConstruction_supervisedCelltyping ''' Configuration generation for running performance saturation ''' import os, sys, argparse import random from pipelines import method_utils, dataloading_utils from preprocess.process_train_test_data import * if __name__ == "__main__": data_dir = "~/gpu/...
StarcoderdataPython
5156661
<filename>zvt/__init__.py # -*- coding: utf-8 -*- import enum import json import logging import os from logging.handlers import RotatingFileHandler import pandas as pd from pkg_resources import get_distribution, DistributionNotFound from zvt.settings import DATA_SAMPLE_ZIP_PATH, ZVT_TEST_HOME, ZVT_HOME, ZVT_TEST_DATA...
StarcoderdataPython
11316060
<filename>chapter_05/15_kinetic_energy.py # kinetic energy def main(): mass = float(input("Please enter the object's mass in kg: ")) velocity = float(input("Please enter the object's velocity " "in meters per second: ")) kin_energy = kinetic_energy(mass, velocity) print("The ...
StarcoderdataPython