id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1772807
import numpy as np import gym import matplotlib.pyplot as plt if __name__ == "__main__": ENV = gym.make("FrozenLake-v0") DISCOUNT = 0.9 EPSILON = 0.1 POSSIBLE_ACTIONS = [0, 1, 2, 3] STATE_SPACE = list(range(16)) ESTIMATES = {} RETURNS = {} PAIRS_VISITED = {} for state in STATE_SPAC...
StarcoderdataPython
3265605
from fisher_py.raw_file import RawFile
StarcoderdataPython
3350327
#!/usr/bin/python import struct import os import glob import argparse pstates = range(0xC0010064, 0xC001006C) def writemsr(msr, val, cpu = -1): try: if cpu == -1: for c in glob.glob('/dev/cpu/[0-9]*/msr'): f = os.open(c, os.O_WRONLY) os.lseek(f, msr, os.SEEK_SET...
StarcoderdataPython
1609967
<gh_stars>0 # ***************************************************************** # (C) Copyright IBM Corp. 2020, 2021. 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 # # ...
StarcoderdataPython
93136
<gh_stars>0 """ Generate input ASTs from Scylla vgst files, including diagnostic plots <NAME>, November 2021 """ from glob import glob import os import beast_ast_inputs import plot_source_density_map import argparse from astropy.table import Table import pandas as pd import matplotlib.pyplot as plt def make_input_as...
StarcoderdataPython
3251143
import lldb def aslr_for_module(target, module): """ Get the aslr offset for a specific module - parameter target: lldb.SBTarget that is currently being debugged - parameter module: lldb.SBModule to find the offset for - returns: the offset as an int """ header_address = module.GetObject...
StarcoderdataPython
8104
import os import errno import sys def mock_directory_tree(tree): tree = dict([(os.path.join(*key), value) \ for key, value in tree.iteritems()]) def listdir(path): try: names = tree[path] except KeyError: raise OSError(errno.ENOENT, os.strerror(err...
StarcoderdataPython
4802870
<filename>jesse/store/state_orders.py from typing import List import pydash from jesse.config import config from jesse.models import Order from jesse.services import selectors import jesse.helpers as jh class OrdersState: def __init__(self) -> None: # used in simulation only self.to_execute = []...
StarcoderdataPython
1668748
<reponame>Men-in-Code/cool-compiler-2021 from cool.lexer.lexer import Lexer from cool.utils.LexerTokens.Tokens import tokens import ply.yacc as yacc from cool.Parser.AstNodes import * from cool.utils.Errors.parser_errors import * class Parser(): def __init__(self, lexer:Lexer = None) -> None: self.lexe...
StarcoderdataPython
110428
# type: ignore __all__ = ["linspace", "py_linspace"] from mat2py.core import * from mat2py.core._internal.helper import mp_inference_nargin_decorators py_linspace = linspace @mp_inference_nargin_decorators() def linspace(d1=None, d2=None, n=None, nargin=None): if nargin == 2: n = 100 else: ...
StarcoderdataPython
4818745
<reponame>enthought/etsproxy<filename>enthought/tvtk/pyface/ui/wx/wxVTKRenderWindowInteractor.py<gh_stars>1-10 # proxy module from __future__ import absolute_import from tvtk.pyface.ui.wx.wxVTKRenderWindowInteractor import *
StarcoderdataPython
1766435
# Project: hardInfo # Author: <NAME> # Date Started: March 18, 2022 # Copyright: (c) Copyright 2022 <NAME> # Module: service/DataSource.py # Date Started: March 21, 2022 # Purpose: Interface with the Linux data sources needed for API construction, generally by runnin...
StarcoderdataPython
4803006
from copy import Error from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options import json import time opti = Options() opti.headless = False driver = webdriver.Chrome(ChromeDriverManager().install(), port=0, options=opti) def ge...
StarcoderdataPython
3323358
<filename>src/simple_playgrounds/element/element.py """ Module that defines Base Class SceneElement """ from abc import ABC, abstractmethod from typing import List, Optional, Tuple from ..common.entity import Entity from ..common.position_utils import InitCoord class SceneElement(Entity, ABC): def __init__(self,...
StarcoderdataPython
3330620
<reponame>deanchester/sst-macro<filename>sstmac/sst_core/sstmacro.py # Load module function in Python is changed # to look for a libmacro.so in LD_LIBRARY_PATH import sst import sst.macro smallLatency = "1ps" def makeUniLink(linkType,srcComp,srcId,srcPort,dstComp,dstId,dstPort,outLat=None,inLat=None): if not outLa...
StarcoderdataPython
3294694
from django.db import models class Person(models.Model): class Meta: abstract = True def __str__(self): return self.known_as name = models.CharField(max_length=50) known_as = models.CharField(max_length=50) date_of_birth = models.DateField(null=True) nationality = models.Fore...
StarcoderdataPython
4810698
# Create list areas areas = [11.25, 18.0, 20.0, 10.75, 9.50] # Print out the index of the element 20.0 print(areas.index(20.0)) # Print out how often 14.5 appears in areas print(areas.count(14.5))
StarcoderdataPython
3279047
<filename>icists19/participant_manager/apps.py from django.apps import AppConfig class ParticipantManagerConfig(AppConfig): name = 'participant_manager'
StarcoderdataPython
45920
<filename>src/third_party/v8/js2c-wrap.py #!/usr/bin/python2 import sys js2c_dir = sys.argv[1] sys.path.append(js2c_dir) import js2c srcs = sys.argv[2] natives = sys.argv[3].split(',') type = sys.argv[4] compression = sys.argv[5] js2c.JS2C(natives, [srcs], {'TYPE': type, 'COMPRESSION': compression})
StarcoderdataPython
91327
#! /use/env/bin python import os import copy from collections import OrderedDict from CP2K_kit.tools import data_op from CP2K_kit.tools import log_info from CP2K_kit.tools import traj_info def check_step(init_step, end_step, start_frame_id, end_frame_id): ''' check_step: check the input step Args: init_st...
StarcoderdataPython
60499
<filename>core/migrations/0015_merge_20170530_1741.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-30 17:41 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0014_auto_20170530_1726'), ('cor...
StarcoderdataPython
54928
<filename>release/release.py #!/usr/bin/python3 import sys import subprocess from pathlib import Path import os os.chdir(str(Path(__file__).parent.absolute())) sys.path.insert(0, "../src") try: import mbf_bam print("Building release for", mbf_bam.__version__) except (ImportError, AttributeError): print(...
StarcoderdataPython
3212295
from typing import Dict, Tuple from monitoring.monitorlib import infrastructure, auth, fetch from monitoring.monitorlib.clients.scd_automated_testing import ( create_flight, delete_flight, QueryError, get_version, get_capabilities, ) from monitoring.monitorlib.scd_automated_testing.scd_injection_ap...
StarcoderdataPython
46449
from django.conf import settings def from_settings(request): return { 'ENVIRONMENT_NAME': settings.ENVIRONMENT_NAME, 'ENVIRONMENT_COLOR': settings.ENVIRONMENT_COLOR, }
StarcoderdataPython
1616831
(a,b,c)=[int(i) for i in input().split()] if(a+b>c and a+c>b and b+c>a): print("Yes! It's a triangle :)") else: print("No! these sides can't make a triangle :(")
StarcoderdataPython
1630680
<reponame>duointeractive/media-nommer """ Basic job caching module. """ import datetime from media_nommer.conf import settings from media_nommer.utils import logger from media_nommer.core.job_state_backend import JobStateBackend from media_nommer.utils.compat import total_seconds class JobCache(dict): """ Cach...
StarcoderdataPython
1619711
from predicthq import Client # Please copy paste your access token here # or read our Quickstart documentation if you don't have a token yet # https://docs.predicthq.com/guides/quickstart/ ACCESS_TOKEN = 'abc123' phq = Client(access_token=ACCESS_TOKEN) # broadcasts and events endpoints use the same approach for sea...
StarcoderdataPython
3209574
# <NAME> # CS 120 # Module Three: Open Ended Project import numpy as np import matplotlib.pyplot as plt import os import seaborn as sns import sys def main(): cpp_file = "cpp_data.txt" rust_file = "rust_data.txt" cpp_read_file = [] cpp_merge_sort = [] cpp_binary_search = [] rust_read_file = ...
StarcoderdataPython
163563
<reponame>purduerov/X11-New<gh_stars>1-10 # Motor Controller class initialization constants ZERO_POWER = 309 # Value to set thrusters to 0 power NEG_MAX_POWER = 226 # Value to set thrusters to max negative power POS_MAX_POWER = 391 # Value to set thrusters to max positive power FREQUENCY = 49.5 # Frequency at which...
StarcoderdataPython
139743
<gh_stars>0 import socket import thread import time so=socket.socket(socket.AF_INET,socket.SOCK_STREAM) so.bind(('127.0.0.1',1234)) so.listen(5) c_o=[] address=[] music_server=['payback.mp3'] def musicsend(a,b): def searchinpeer(a,b,music_requested): global c_o,address status=0 address1=0 for i in c_o: i...
StarcoderdataPython
181894
<reponame>noegroup/neurips2020_snf import torch import numpy as np from .base import Flow # TODO: write docstrings # TODO: refactor messy implementation class FunnelFlow(Flow): def __init__(self, eps=1e-6, min_val=-1.0, max_val=1.0): super().__init__() self._eps = eps self._min_val = min...
StarcoderdataPython
1738454
#!/usr/bin/env python ## ## /svn-src/printer/src/cxi/utils.py ## import sys import socket import re from cxifont import * DEBUG = 0 XSTART = 10 YSTART = 10 SPACE = " " EOL = "\r\n" VAR = "VARIABLE" WRITE = "WRITE" END = "END" QQ = "?" ### key for returning structure from making labels ### CXI_RET='Return value' C...
StarcoderdataPython
1690937
<reponame>MalloryWittwer/automated_grain_segmentation<gh_stars>0 import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from matplotlib.ticker import PercentFormatter from skimage.color import label2rgb from skimage.segmentation import find_boundaries from skimage.morphology import...
StarcoderdataPython
1606386
<reponame>IW-Big-Data-Analytics/scrapy-toolbox<filename>example/family/pipelines.py from scrapy_toolbox.database import DatabasePipeline import family.items as items import family.models as models class FamilyPipeline(DatabasePipeline): def __init__(self, settings): super().__init__(settings, items, models...
StarcoderdataPython
115359
<reponame>guyueming/PythonWeb<gh_stars>0 from django.contrib import admin # Register your models here. from .models import PaperModel admin.site.register(PaperModel)
StarcoderdataPython
100996
<gh_stars>0 # <NAME> # CPSC 386-01 # 2021-11-29 # <EMAIL> # @JaredDyreson # # Lab 00-04 # # Some filler text # """ This module contains a basic "factory" pattern for generating new Display instances """ import abc import dataclasses import functools import json import pathlib import pygame import sys import time impo...
StarcoderdataPython
1677630
<filename>enstools/interpolation/coarse_graining.py<gh_stars>1-10 from enstools.core import check_arguments import numpy as np @check_arguments(shape={"arr": (0, 0)}) def downsize(arr, fac): """ Reduce resolution of an array by neighbourhood averaging - 2D averaging of fac x fac element Parameters --...
StarcoderdataPython
173671
<<<<<<< HEAD #load csv import os import csv #Path to collect data budget_data_csv ="C:/Users/Keke/git/python_challenge/PyBank/Resources/budget_data.csv" #define variables totalmonths=0 #set total as integer nettotalamount=0 #calculate changes of each date netmonthlychange=[] #set first value as 0 from previous row...
StarcoderdataPython
3350654
""":mod:`tests` --- Test module of getpost ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Command: $ nosetests -sv Flags: -s, --nocapture Don't capture stdout. -v=DEFAULT, --verbose=DEFAULT Be more verbose. """ from selenium impo...
StarcoderdataPython
3297235
__author__ = 'shen'
StarcoderdataPython
1624441
<filename>backend/utils/exception.py """ exception """ class ParamError(Exception): def __init__(self, key, message): self.key = key self.message = message self.error = {key: [message]} class PermError(Exception): def __init__(self, message): self.message = message clas...
StarcoderdataPython
22861
<filename>build/lib/henmedlib/functions/hounsfield.py __author__ = "<NAME>" import numpy as np def calculate_hounsfield_unit(mu, mu_water, mu_air): """ Given linear attenuation coefficients the function calculates the corresponding Hounsfield units. :param mu: Attenuation coefficient to determine c...
StarcoderdataPython
36910
# -*- coding: utf-8 -*- """Command line interface.""" import logging import click from pathrev.pipeline import ( do_gsea, do_preranked, ) logger = logging.getLogger(__name__) @click.group(help='pathrev') def main(): """Run pathrev.""" logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s -...
StarcoderdataPython
1767242
<reponame>argenortega/AUI # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/image.ui' # # Created: Mon Aug 31 02:59:12 2015 # by: PyQt4 UI code generator 4.11.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QSt...
StarcoderdataPython
3361506
import matplotlib matplotlib.use('Agg') import pyroms import pyroms_toolbox # load the grid srcgrd = pyroms_toolbox.Grid_HYCOM.get_nc_Grid_HYCOM('/archive/u1/uaf/kate/HYCOM/Svalbard/HYCOM_GLBa0.08_North_grid2.nc') dstgrd = pyroms.grid.get_ROMS_grid('ARCTIC2') # make remap grid file for scrip pyroms_toolbox.Grid_HYCOM...
StarcoderdataPython
44073
<gh_stars>10-100 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overlo...
StarcoderdataPython
4805019
<filename>analysis/spheroid/20191003-co-culture/source/utils.py<gh_stars>0 import os import os.path as osp import numpy as np import matplotlib from cytokit import io as ck_io from cytokit import config as ck_config from cytokit.function import core as ck_core from cytokit.ops import tile_generator, tile_crop from skim...
StarcoderdataPython
3296449
<filename>00401/palindromes.py #import math #import sys character = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789' reverse = 'A 3 HIL JM O 2TUVWXY51SE Z 8 ' while(True): try: input_str = input() if not input_str: raise ValueError except ValueError: break except EOFError: break is_palin ...
StarcoderdataPython
147894
<gh_stars>10-100 # -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-09 21:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('filer',...
StarcoderdataPython
1632700
import typing import random DEFAULT_FONT = "Courier New" class Theme(typing.NamedTuple): background: str foreground: str ## Other tkinter parameters to explore # highlightbackground: The color of the focus highlight when the text widget does not have focus. # highlightcolor: The color of the f...
StarcoderdataPython
86476
<gh_stars>1000+ import pandas as pd from tensortrade.feed import Stream from tests.utils.ops import assert_op def test_add(): # (left, right) : (Stream, Stream) s1 = Stream.source([3, -4, 6, -7, 2, -6], dtype="float") s2 = Stream.source([-3, 4, -6, 7, -2, 6], dtype="float") w1 = s1.add(s2).rename...
StarcoderdataPython
1738290
### Copyright (C) 2017 NVIDIA Corporation. All rights reserved. ### Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode). import argparse import os from utils import util import torch class BaseOptions(): def __init__(self): self.parser = argparse.Argum...
StarcoderdataPython
1777649
# Licensed under the MIT license # http://opensource.org/licenses/mit-license.php or see LICENSE file. # Copyright 2007-2008 <NAME> <<EMAIL>> from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() from unittest import TestSuite, TextTestRunner from config import * from mthreading...
StarcoderdataPython
1608955
from django.db.migrations.serializer import BaseSequenceSerializer from rest_framework import serializers from products.models import Categorys, Products class ChildrenCategorysSerializer(serializers.ModelSerializer): class Meta: model = Categorys fields = "__all__" class CategorysSerializer(s...
StarcoderdataPython
77065
"""Test the collective reducescatter API on a distributed Ray cluster.""" import pytest import ray import cupy as cp import torch from ray.util.collective.tests.util import \ create_collective_multigpu_workers, \ init_tensors_for_gather_scatter_multigpu @pytest.mark.parametrize("tensor_backend", ["cupy", "t...
StarcoderdataPython
1721642
<reponame>ziqiaomeng/dgl import dgl from dgl.nn.pytorch import GATConv import torch import torch.nn as nn import torch.nn.functional as F from .. import utils class GAT(nn.Module): def __init__(self, num_layers, in_dim, num_hidden, num_classes, ...
StarcoderdataPython
132941
<reponame>pakit/test_recipes """ Formula that requires cyclea recipe. """ from pakit import Dummy, Recipe class Cycleb(Recipe): """ Dummy recipe does nothing special but have dependency. """ def __init__(self): super(Cycleb, self).__init__() self.homepage = 'dummy' self.repos =...
StarcoderdataPython
3219373
""" Canonical path locations for zipline data. Paths are rooted at $ZIPLINE_ROOT if that environment variable is set. Otherwise default to expanduser(~/.zipline) """ from errno import EEXIST import os from os.path import exists, expanduser, join import pandas as pd def hidden(path): """Check if a path is hidden...
StarcoderdataPython
80836
<gh_stars>0 from .sanic import Sanic from .blueprints import Blueprint __all__ = ['Sanic', 'Blueprint']
StarcoderdataPython
1763751
''' todo: https://en.wikipedia.org/wiki/Hungarian_algorithm '''
StarcoderdataPython
44409
from datetime import timedelta import logging from typing import Union from pyschism.enums import ( IofHydroVariables, IofDvdVariables, IofWwmVariables, IofGenVariables, IofAgeVariables, IofSedVariables, IofEcoVariables, IofIcmVariables, IofCosVariables, IofFibVariables, Iof...
StarcoderdataPython
82664
from django.db import models from django_resized import ResizedImageField from src.accounts.models import Wallet """ GENERAL """ class Country(models.Model): name = models.CharField(max_length=255, unique=True) short_code = models.CharField(max_length=2, unique=True) phone_code = models.CharField(max_l...
StarcoderdataPython
1786114
from abc import ABC, abstractmethod from typing import TypeVar, Collection, Generic from brigadier.context import CommandContext S = TypeVar('S') class Message(ABC): @abstractmethod def get_string(self) -> str: return "" class ImmutableStringReader(ABC): @abstractmethod def get_string(self...
StarcoderdataPython
1711466
<gh_stars>0 # THIS IS IN GERMAN, I WILL PROBABLY NOT CREATE AN ENGLISH VERSION OF THE PROMPTS import discord from discord.ext import commands from dotenv import load_dotenv token = "" # YOUR DISCORD BOT TOKEN HERE helpText = ("```Global:\n" " !start Starte eine private Konversation m...
StarcoderdataPython
150974
# Copyright (c) AIRBUS and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import numpy as np import gym from typing import Callable from collections.abc import Iterable from skde...
StarcoderdataPython
1722604
from __future__ import unicode_literals import argparse import os import sys import youtube_dl import subprocess from synthesia_to_sheet import * from synthesia_to_sheet.bpm_detection import * def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--video_file",default="", help="Provide the ...
StarcoderdataPython
25733
<filename>opus/opus_server.py import asyncio import zlib import queue import threading import audioop from google.cloud import speech from opuslib import Decoder from config.config import Config from config.config import Server from config.config import Opus buffer = queue.Queue() buffer_response = queue.Queue() de...
StarcoderdataPython
3374716
<gh_stars>0 import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='stadtradeln-data', version="0.0.2", setup_requires=['setuptools'], use_scm_version=False, install_requires=[ 'tqdm', ...
StarcoderdataPython
3303660
__author__ = "<NAME> <<EMAIL>>" __date__ = "2018/05/29 20:38:05" import numpy as np import torch import torch.nn as nn import scipy.optimize as optimize class MBAR(): """ The MBAR class is initialized with an energy matrix and an array of num of conformations. After initizlization, the MBAR class met...
StarcoderdataPython
1717832
import json try: from django.models import JSONField except ImportError: from django.contrib.postgres.forms.jsonb import JSONField from django.forms import ValidationError class JSONPrettyField(JSONField): def __init__(self, *args, **kwargs): self.__indent = kwargs.pop("indent", 2) self._...
StarcoderdataPython
1773291
<gh_stars>1-10 ############################################################################################ # Author: <NAME> # # File Name: Train/TPU_training.py # # Cre...
StarcoderdataPython
34624
<gh_stars>0 from airflow.models import DAG from airflow.utils.dates import days_ago from airflow.operators.python_operator import PythonOperator from datetime import datetime import pandas as pd import urllib import random import cx_Oracle import pyodbc import sqlalchemy args={ 'owner': 'BI', ### start date is u...
StarcoderdataPython
168332
<reponame>orionsring/basic_python from amaze.maze import NORTH, SOUTH, WEST, EAST DIRECTIONS = [EAST, NORTH, WEST, SOUTH] LEFT_HAND_DIR = [NORTH, WEST, SOUTH, EAST] def run(maze): """Solves the maze by a simple search: always keep wall, starting top left and ending at bottom right """ runner ...
StarcoderdataPython
55555
<filename>PathTracking/model_predictive_speed_and_steer_control/courses.py import cubic_spline_planner import math def get_straight_course(dl): ax = [0.0, 5.0, 10.0, 20.0, 30.0, 40.0, 50.0] ay = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ...
StarcoderdataPython
6189
# -*- coding: utf-8 -*- """ Check if it is Thai text """ import string _DEFAULT_IGNORE_CHARS = string.whitespace + string.digits + string.punctuation def isthaichar(ch: str) -> bool: """ Check if a character is Thai เป็นอักษรไทยหรือไม่ :param str ch: input character :return: True or False "...
StarcoderdataPython
1703109
<filename>scipy_central/pages/tests.py from django.test import TestCase from django.core.urlresolvers import reverse class TextExistance(TestCase): def test_page_exists(self): # Main page response = self.client.get(reverse('spc-main-page')) self.assertEqual(response.status_code, 200) ...
StarcoderdataPython
1763705
<filename>emojibot/find_images.py # Thanks http://stackoverflow.com/questions/20716842/python-download-images-from-google-image-search from bs4 import BeautifulSoup import requests import re import urllib2 import os def find(keyword, num): def get_soup(url,header): return BeautifulSoup(urllib2.urlopen(urll...
StarcoderdataPython
1795986
<reponame>satroutr/poppy<gh_stars>1-10 # Copyright (c) 2016 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
StarcoderdataPython
1728974
<reponame>youngsoul/PyBlynkRestApi<filename>pyblynkrestapi/BlynkClient.py # -*- coding: utf-8 -*- """ client helpers Leveraging this github repo for the heartbeat https://github.com/erazor83/pyblynk/blob/master/lib/client.py The MIT License (MIT) Copyright (c) 2015 <NAME> Permission is hereby granted, free...
StarcoderdataPython
74375
import logging import typing try: from importlib.metadata import entry_points except ImportError: from importlib_metadata import entry_points # type: ignore from karp.domain import events from karp.services import messagebus, unit_of_work, auth_service from karp.application import config from karp.infrastruc...
StarcoderdataPython
161760
import rospy import actionlib from math import radians import numpy as np import scipy.signal import time import dynamic_reconfigure.client from robot_localization.srv import SetPose from pyquaternion import Quaternion as qt from std_srvs.srv import Empty from gazebo_msgs.msg import ModelState from geometry_msgs.msg ...
StarcoderdataPython
3364691
<reponame>hankyul2/FaceDA<filename>src/data/face.py import glob import json import os import random from PIL import Image from typing import Tuple, List, Dict, Optional, Callable from torch.utils.data import Dataset from pytorch_lightning import LightningDataModule from pytorch_lightning.utilities.types import TRAIN_...
StarcoderdataPython
77664
from datetime import date atual = date.today().year nome = str(input('Digite seu nome: ')).strip().title().split() ano_Nasc = int(input(f'{nome[0]}, digite o ano de seu nascimento com 4 dígitos (0000): ')) if ano_Nasc < 100: # caso o usuário digite o ano com apenas dois dígitos (se vc conhecer um jeito mais fácil de fa...
StarcoderdataPython
1738958
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import urllib2 import argparse import os import ConfigParser import httplib2 __author__ = "<NAME> <<EMAIL>>" __version__ = "0.1" class REST_Kernel: def __init__(self, base_uri): self.base_uri = base_uri self.user_agent = "MeltdownPY {0}".fo...
StarcoderdataPython
4151
<gh_stars>0 from copy import deepcopy import bifrost as bf from bifrost.pipeline import TransformBlock from bifrost.ndarray import copy_array class CopyBlock(TransformBlock):# $\tikzmark{block-start}$ """Copy the input ring to output ring""" def __init__(self, iring...
StarcoderdataPython
4841194
# MIT (c) jtankersley 2019-05-19 import unittest from src import list from src import timer class TestList(unittest.TestCase): def test_link_doubleLinkList_head(self): dll = list.DoubleLinkList() dll.add_head(1) dll.add_head(2) dll.add_head(3) actual = timer.run_timed_resu...
StarcoderdataPython
129916
#!/usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as F ## # version 1: use pytorch autograd class HSwishV1(nn.Module): def __init__(self): super(HSwishV1, self).__init__() def forward(self, feat): return f...
StarcoderdataPython
1762217
<filename>Chapter11/listing11_6.py # Script that uses SciPy to smooth a DEM. import os import scipy.ndimage from osgeo import gdal import ospybook as pb in_fn = r"D:\osgeopy-data\Nepal\everest.tif" out_fn = r'D:\Temp\everest_smoothed.tif' in_ds = gdal.Open(in_fn) in_data = in_ds.GetRasterBand(1).ReadAsArray() # Use...
StarcoderdataPython
3379632
import numpy as np array1 = np.random.randint(10, size=(4, 3)) array2 = np.random.randint(10, size=(3, 5)) result = np.ones((4,5)) result = np.dot(array1, array2) print('first_array\n',array1); print('second_array\n',array2); print('result_array\n',result);
StarcoderdataPython
107930
<gh_stars>1-10 import time import json from flask import current_app from google.auth import crypt, jwt import requests def generate_jwt(service_account): signer = crypt.RSASigner.from_string(service_account['private_key']) now = int(time.time()) payload = { 'iat': now, 'exp': now + 3600, ...
StarcoderdataPython
1776206
from selenium import webdriver from bs4 import BeautifulSoup import time import pdfcrowd from selenium.webdriver.common.keys import Keys # import os # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Requirements: # Django==1.7.3 # argparse==1.2.1 # beautifulsoup4==4.3.2 # pdfcrowd==2.6 # selenium==2.44.0 # wsg...
StarcoderdataPython
4822796
<filename>tests/packer/test_x11_packer.py from pathlib import Path from clickgen.packer import pack_x11 def test_x11_packer(x11_tmp_dir: Path): pack_x11(x11_tmp_dir, theme_name="test", comment="test") f1 = x11_tmp_dir.joinpath("cursor.theme") f2 = x11_tmp_dir.joinpath("index.theme") assert f1.exist...
StarcoderdataPython
3264665
<reponame>cowboysmall-scratch/foobar-coding-challenge def solution(M, F): p, q, c = int(M), int(F), 0 while q != 0: c += p // q p, q = q, p % q return str(c - 1) if p == 1 else "impossible"
StarcoderdataPython
3280340
<reponame>tianyapiaozi/tensorflow<filename>tensorflow/contrib/data/python/kernel_tests/serialization/filter_dataset_serialization_test.py # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance wit...
StarcoderdataPython
1730891
<reponame>bueler/multilevel-stokes-geometry #!/usr/bin/env python3 # sent as MFE to Firedrake slack on 9 May # Lawrence responded it is unsupported ... but then on slack 13 May he patched # firedrake/src/firedrake/cython/extrusion_numbering.pyx # and now it is supported from firedrake import * # supported extruded...
StarcoderdataPython
20106
# -*- coding: utf-8 -*- import httplib as http from flask import request from framework.exceptions import HTTPError from framework.auth.decorators import must_be_logged_in from website.util import web_url_for from website.project.decorators import ( must_have_addon, must_be_addon_authorizer, must_have_permi...
StarcoderdataPython
92545
<filename>tests/test_open_redirect_scanner.py from typing import List from requests import Session from keycloak_scanner.scanners.clients_scanner import Client from keycloak_scanner.scan_base.mediator import Mediator from keycloak_scanner.scanners.open_redirect_scanner import OpenRedirectScanner from keycloak_scanner...
StarcoderdataPython
3374503
<reponame>Broad-AI-Lab/emotion from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np from sklearn.base import ClassifierMixin from sklearn.model_selection import BaseCrossValidator, cross_validate from sklearn.pipeline import Pipeline from ..utils import ScoreFunction, filter_kwargs,...
StarcoderdataPython
47977
<reponame>juniorcarvalho/python-btr<filename>tests/test_types.py from decimal import InvalidOperation import pytest from binance.types import Results, Trading, format_fee def test_results_attributes(): tr = Results( datetime_value='2018-11-13 01:58:03', pair='STORMBTC', type_operation='SE...
StarcoderdataPython
4838894
#making dictionary dic = {"expect":"wanting feeling from others", "except":"leaving that thing", "entertainment":"comedy funny things to laugh", "cricket":"its a sport played by batsman and bowler", "keyboard":"typing medium for computer"} print(dic.keys()) print("Enter the word") imp=input(...
StarcoderdataPython