id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
28245
import numpy as np class perceptron(object): #eta learning rata #n_iter times def __init__(self,eta,n_iter): self.eta=eta self.n_iter=n_iter def fit(self,x,y): ''' x=ndarray(n_samples,n_features),training data y=ndarray(n_samples),labels returns se...
StarcoderdataPython
1797994
#!/usr/bin/env python #coding: utf-8 import os import re import json import time import subprocess import threading from datetime import datetime import psutil import requests TEST_SERVER_HOSTS = ['192.168.40.215', '192.168.40.91'] TEST_SERVER_PORT = 8999 TEST_REQ_TMPL = 'http://%(host)s:%(port)d/test' APP_SERVER_I...
StarcoderdataPython
140286
<gh_stars>0 from math import * import os class Servo: def __init__(self, number): self.number = number self.angle = 0 def set_servo_angle(self, angle): self.angle = angle self.write_value_to_hardware() def get_servo_angle(self): return self.angle def w...
StarcoderdataPython
13007
<reponame>BramKaashoek/commercetools-python-sdk import typing from commercetools import schemas, types from commercetools.services import abstract from commercetools.typing import OptionalListStr __all__ = ["TypeService"] class TypeDeleteSchema(abstract.AbstractDeleteSchema): pass class TypeQuerySchema(abstra...
StarcoderdataPython
117971
import torch from torch import nn from torch.nn import functional as F from torch.distributions.uniform import Uniform from networks.layers.non_linear import NonLinear, NonLinearType from networks.layers.conv_bn import ConvBN class DropConnect(nn.Module): def __init__(self, survival_prob): """ A m...
StarcoderdataPython
1747193
<reponame>dirtysalt/pyorc import re from typing import Mapping, Tuple, Dict from types import MappingProxyType from pyorc._pyorc import _schema_from_string from .enums import TypeKind class TypeDescription: name = "" kind = -1 def __init__(self) -> None: self._column_id = 0 self._attrib...
StarcoderdataPython
1757479
#!/usr/bin/python import argparse # * nargs expects 0 or more arguments parser = argparse.ArgumentParser() parser.add_argument('num', type=int, nargs='*') args = parser.parse_args() print(f"The sum of values is {sum(args.num)}")
StarcoderdataPython
1745125
<reponame>joskid/vardbg from pathlib import Path from PIL import Image, ImageDraw, ImageFont from .config import Config from .gif_encoder import GIFEncoder from .opencv_encoder import OpenCVEncoder from .text_format import irepr from .text_painter import TextPainter from .webp_encoder import WebPEncoder WATERMARK = ...
StarcoderdataPython
1644104
from typing import List, Union from indico.queries import ( RetrieveStorageObject, GraphQLRequest, JobStatus, CreateModelGroup, ModelGroupPredict, CreateStorageURLs ) from indico.types import Dataset, ModelGroup from indico import IndicoClient from indico.errors import IndicoRequestError from i...
StarcoderdataPython
1685082
"""Sensor representation for mytoyota""" import logging from mytoyota.const import CLOSED, INCAR, LOCKED, OFF, STATE, WARNING _LOGGER: logging.Logger = logging.getLogger(__package__) class Hood: """Representation of the hood of the car""" warning: bool = False closed: bool = True def __init__(self...
StarcoderdataPython
91611
<filename>open_spiel/python/games/optimal_stopping_game_config.py from typing import List import numpy as np import pyspiel from open_spiel.python.games.optimal_stopping_game_config_base import OptimalStoppingGameConfigBase class OptimalStoppingGameConfig(OptimalStoppingGameConfigBase): def __init__(self, p: flo...
StarcoderdataPython
1652305
import numpy as np import time from pykin.kinematics.transform import Transform JOINT_TYPE_MAP = {'revolute' : 'revolute', 'fixed' : 'fixed', 'prismatic' : 'prismatic'} LINK_TYPE_MAP = {'cylinder' : 'cylinder', 'sphere' : 'sphere', 'box' ...
StarcoderdataPython
82588
<reponame>BloomTech-Labs/Quick-Slack-ds """empty message Revision ID: 57f3951597c0 Revises: Create Date: 2020-01-23 23:11:22.197394 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>0' down_revision = None branch_labels = None depends_on = None def upgra...
StarcoderdataPython
72602
<filename>src/worker/worker_initializer.py #!/usr/bin/python # -*- coding: utf-8 -*- import os import queue from flask import Flask from helpers import unmunge_request, munge_response from worker.blueprints.api import blueprint as api from worker.config_handler import ConfigHandler from worker.tool_config_parser im...
StarcoderdataPython
39352
<filename>orglearn/mind_map/backend/graphviz.py import colour import graphviz from orglearn.mind_map.backend.backend import Backend class Graphviz(Backend): def __init__(self, *args, **kwargs): self.ignore_shallow_tags = set(kwargs.get("ignore_shallow_tags_list", [])) self.ignore_tags = set(kwargs...
StarcoderdataPython
100240
# -*- coding: utf-8 -*- # Copyright (c) <NAME>. All Rights Reserved. # Distributed under the MIT License. See LICENSE file for more info. import threading import time from asyncframes import Frame, Event, sleep from asyncframes.pyqt5_eventloop import EventLoop class Thread(threading.Thread): def __init__(self, *a...
StarcoderdataPython
3343833
<reponame>yiyin/neurodriver<filename>neurokernel/LPU/NDComponents/DendriteModels/__init__.py import os import fnmatch __all__ = [] NDC_dir = os.path.dirname(__file__) for root, dirnames, filenames in os.walk(NDC_dir): mod_imp = False for f in fnmatch.filter(filenames,"*.py"): if '__init__'!=f[:8] and ...
StarcoderdataPython
3218137
<filename>flit_core/flit_core/tests/test_buildapi.py from contextlib import contextmanager import os import os.path as osp import tarfile from testpath import assert_isfile, assert_isdir from testpath.tempdir import TemporaryDirectory import zipfile from flit_core import buildapi samples_dir = osp.join(osp.dirname(__...
StarcoderdataPython
1754369
<filename>xCave/osm.py import json import numpy as np import os import requests from itertools import tee, izip from math import atan2, cos, radians, sin, sqrt from os.path import basename, exists, isfile from os import makedirs from operator import itemgetter from scipy.spatial import ConvexHull#, Delaunay from sys im...
StarcoderdataPython
1614447
<gh_stars>0 from keras import backend as K from .tools import stretch_array import tensorflow as tf def build_network(X_nodes, X_edges, X_nodes_in_out, X_messages_in, X_messages_out, message_passers, state_updater, readout, ndim_features_nodes, fake_message_const, steps): for ...
StarcoderdataPython
1743854
import os import matplotlib.pyplot as plt import numpy as np from tensorflow.keras.layers import Activation from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Input from tensorflow.keras.layers import Reshape from tensorflow.keras.models import Mod...
StarcoderdataPython
188913
# -*- coding: UTF-8 -*- from typing import Union import torch import torch.nn as nn import numpy as np from .tn_module import _TNBase __all__ = ["_TNConvNd"] class _TNConvNd(_TNBase): def __init__(self, in_shape: Union[list, np.ndarray], out_shape: Union[list, np.ndarray], ranks: Union[list, ...
StarcoderdataPython
144661
import numpy as np import re from rdkit import Chem if __name__ == "__main__": import sys args = sys.argv[1:] smiless = args for smiles in smiless: m = Chem.MolFromSmiles(smiles)
StarcoderdataPython
3375956
<reponame>losolio/website<filename>content_notes/migrations/0002_citation.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import modelcluster.fields import wagtail.wagtailcore.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('art...
StarcoderdataPython
40614
# Advent of Code 2015 # # From https://adventofcode.com/2015/day/12 import json import re filename = '' data = [re.findall(r'(-?\d+)', row.strip()) for row in open(f'../inputs/Advent2015_12{filename}.json', 'r')] print(f"AoC 2015 Day 12, Part 1 answer is {sum(int(x[0]) for x in data if x)}") with open(f'../inputs/A...
StarcoderdataPython
3365197
<gh_stars>1-10 import time import board import neopixel pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.1) # Colors BLACK = (0, 0, 0) RED = (255, 0, 0) PINK = (255, 100, 120) ORANGE = (255, 100, 0) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) PURPLE = (255, 0, 255) BLUE = (0, 0, 255) LI...
StarcoderdataPython
3280659
<filename>RRDGraphs/rrd_8years.py import time import matplotlib.pyplot as plt import matplotlib.dates as mdate import numpy as np import rrdtool start = 252288000 end = 0 if int(end) <= 0: end = 2 if int(start) <= 0: start = 600 epochTimeNow = int(time.time()-1) data = rrdtool.fetch('/home/bca/rrdtoolfilesav...
StarcoderdataPython
3235700
from recent import module
StarcoderdataPython
47049
import os import pytest import csv_diff import logging import torch from unit_tests.t_utils import remove_tmp_dir, create_tmp_dir, __data_testing_dir__, __tmp_dir__ from ivadomed.loader import utils as imed_loader_utils from ivadomed.loader import loader as imed_loader logger = logging.getLogger(__name__) def setup_f...
StarcoderdataPython
186645
#!/usr/bin/env python3 ''' This script converts MongoDB records for the Workspace Shock backend into records for the workspace S3 backend. The script does not alter the Shock backend records and may be re-run multiple times without issue. To run: 1) Start the workspace at least once with the S3 backend enabled to cre...
StarcoderdataPython
3307945
# # # # import my stuff from myscripts import write_batchfile from myscripts import commit_batchfiles from myscripts import show_jobs # path to PASC_inference library library_path = "~/soft/PASC_inference"; # image_path = [image_dir]/[begin]_[width]_[height].bin image_name = "C_noise_medium"; #image_name = "C_noise_...
StarcoderdataPython
4825069
from typing import Union, IO from pathlib import Path FilePathOrBuffer = Union[str, Path, IO] Buffer = IO
StarcoderdataPython
167327
#!/usr/bin/env python3.6 # Create an HTML page listing all the ad hoc queries in Redmine import sys import jinja2 from jinja2 import Template import re import string from optparse import OptionParser import csv def main(): usage = "usage: %prog -i ad_hoc_listing_file -t ad_hoc_listing_template_file -o project_li...
StarcoderdataPython
173551
# -*- coding: utf-8 -*- """ Generic vault related helpers """ import os import pathlib from typing import Any import chameleon from rumps import MenuItem from shellescape import quote def generate_launchagent(profile_name: str) -> str: """ Generate the launchctl launchagent xml """ path = os.path.di...
StarcoderdataPython
1688905
<reponame>vinissimus/pytest-mp import pytest @pytest.mark.parametrize('use_mp', (False, True)) def test_group_info_marker_kwargs_from_args(testdir, use_mp): testdir.makepyfile(""" import pytest @pytest.mark.mp_group('One') def test_one(request): kwargs = request.node.get_close...
StarcoderdataPython
1655654
<gh_stars>0 from django.shortcuts import render from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login...
StarcoderdataPython
193330
#%% import cv2; from pathlib import Path from dotenv import find_dotenv, load_dotenv # not used in this stub but often useful for finding various files #project_dir = Path(__file__).resolve().parents[2] # find .env automagically by walking up directories until it's found, then # load up the .env entries as environ...
StarcoderdataPython
4829834
<filename>FATERUI/common/__init__.py #!/usr/bin/env python2.7 # coding=utf-8 ''' @date = '15/3/23' @author = 'xiekun' @email = '<EMAIL>' ''' from .camera import Camera from .camera import cameramanage # from camera.camera_factory import * from .infrared.infrared import Infrared # from camera import CameraProcess, R...
StarcoderdataPython
43019
import os class PathManager: input_folder_label = None output_folder_label = None _input_folder_path = None _output_folder_path = None _import_file_path = None _import_file_style = None @classmethod def set_input_folder_label(cls, label): cls.input_folder_label = label @classmethod def set_output_folder...
StarcoderdataPython
1712090
from pydivert import WinDivert from threading import Thread from requests import Session from time import sleep def DivertRST(): while True: with WinDivert("tcp.SrcPort == 443 and tcp.PayloadLength == 0") as w: try: for packet in w: packet.tcp.rst = False ...
StarcoderdataPython
1787675
import datetime import os import json # environment variables must be set TEST_USE_STATIC_DATA = os.getenv('TEST_USE_STATIC_DATA', True) test_api_key_search = os.getenv('TEST_API_KEY_SEARCH') test_api_key_stream = os.getenv('TEST_API_KEY_STREAM') NUMBER_OF_ADS = 1495 DAWN_OF_TIME = '1971-01-01T00:00:01' current_time_s...
StarcoderdataPython
3277920
<reponame>spowlas/sarpy from algorithm_toolkit import app if (__name__) == '__main__': import argparse parser = argparse.ArgumentParser(description='Development Server Help') parser.add_argument( "-d", "--debug", action="store_true", dest="debug_mode", help="run in...
StarcoderdataPython
1621734
<gh_stars>1-10 """Example with a device defined in pyvisa-sim ============================================== """ from fluidlab.interfaces import PhysicalInterfaceType, set_default_interface from fluidlab.interfaces.visa_inter import set_default_pyvisa_backend from fluidlab.instruments.drivers import Driver from flu...
StarcoderdataPython
3284438
<gh_stars>0 # # <NAME>, <NAME> # 10/09/2018 # import tensorflow as tf import numpy as np def iou(prediction, mask, name): # Compute the argmax for the output to match mask shape prediction = tf.expand_dims(tf.argmax(prediction, axis=-1), axis=-1) # Thresholds as specified by competition thresholds = np...
StarcoderdataPython
1771616
<filename>scripts/build_all.py # Copyright 2019-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2...
StarcoderdataPython
3253129
<reponame>jesnyder/MeasuredStress<gh_stars>0 from c0101_retrieve_ref import retrieve_ref from c0101_retrieve_ref import retrieve_ref_color from c0101_retrieve_ref import retrieve_sensor_unit from c0102_timestamp import timestamp_source from c0103_trim_record_to_max import trim_record_to_max from c0104_plot_timestamp im...
StarcoderdataPython
3289274
<filename>test.py<gh_stars>10-100 import argparse import glob import os import PIL.Image as pil import cv2 from crossView import model, CrossViewTransformer, CycledViewProjection import numpy as np import torch from torchvision import transforms from easydict import EasyDict as edict import matplotlib.pyplot as ...
StarcoderdataPython
3252907
from ntpath import join from posixpath import dirname import numpy as np import pandas as pd class CopperModel : DEMAND = 'copper_demand' YEAR_START = 'year_start' YEAR_END = 'year_end' ANNUAL_EXTRACTION = 'annual_extraction' INITIAL_RESERVE = 'initial_copper_reserve' INITIAL_STOCK = 'i...
StarcoderdataPython
11228
<gh_stars>1-10 { "targets": [ { "target_name": "cclust", "sources": [ "./src/heatmap_clustering_js_module.cpp" ], 'dependencies': ['bonsaiclust'] }, { 'target_name': 'bonsaiclust', 'type': 'static_library', 'sources': [ 'src/cluster.c' ], 'cflags': ['-fPIC', '-I',...
StarcoderdataPython
1786914
<filename>quizzes/quiz1_1.py contador = 0 q1 = input("Pergunta 1") if q1 == "sim": contador += 1 q2 = input("Pergunta 2") if q2 == "sim": contador += 1 q3 = input("Pergunta 3") if q3 == "sim": contador += 1 q4 = input("Pergunta 4") if q4 == "sim": contador += 1 q5 = input("Pergunta 5") if q5 == "sim...
StarcoderdataPython
106979
<filename>nuxeo/client.py # coding: utf-8 import atexit import json import logging from typing import Any, Dict, Optional, Tuple, Type, Union from warnings import warn import requests from requests.adapters import HTTPAdapter from urllib3 import __version__ as urllib3_version from urllib3.util.retry import Retry from...
StarcoderdataPython
3279531
<reponame>erezsh/runtype from datetime import datetime from unittest import TestCase from typing import List, Dict from runtype import dataclass, String, Int, Dispatch class TestCasts(TestCase): def test_typing_cast(self): @dataclass(check_types='cast') class P: a: Int(mi...
StarcoderdataPython
1628622
<reponame>watxaut-alpha/joke-app<filename>src/api/src/db/jokes.py import datetime import pandas as pd import sqlalchemy.exc from sqlalchemy.engine import Engine import src.db.core as db def get_random_joke() -> pd.DataFrame: conn = db.get_jokes_app_connection() return db.get_random_element(conn, "jokes_to_s...
StarcoderdataPython
4810456
# protocol type GRN_PROTO_GQTP = "gqtp" GRN_PROTO_HTTP = "http" # gqtp GQTP_HEADER_SIZE = 24 # groonga status GRN_STATUS_SUCCESS = 0 GRN_STATUS_END_OF_DATA = 1 GRN_STATUS_UNKNOWN_ERROR = 65535 GRN_STATUS_OPERATION_NOT_PERMITTED = 65534 GRN_STATUS_NO_SUCH_FILE_OR_DIRECTORY = 65533 GRN_STATUS_NO_SUCH_PROCESS = 65532 GR...
StarcoderdataPython
4823038
"""Queue implementation using two stacks.""" from data_structure.stack.oop_stack import Stack from data_structure.exceptions.collection_exeption import CollectionIsEmptyExeption from data_structure.exceptions.error_messages import queue_is_empty class Queue(object): """The implementation using two stacks.""" ...
StarcoderdataPython
1797089
<reponame>kiyoon/PyVideoAI import torch import numpy as np from torch import nn class BatchRelationalModule(nn.Module): def __init__(self, input_feature_dim, use_coordinates=False, num_layers=2, num_units=64): super(BatchRelationalModule, self).__init__() self.input_feature_dim = input_feature_dim...
StarcoderdataPython
56226
import unittest import pandas as pd class TestDataFrameStats(unittest.TestCase): def setUp(self): # initialize and load df self.df = pd.DataFrame(data={'data': [0,1,2,3]}) def test_min(self): self.assertGreaterEqual(self.df.min().values[0], 0) def test_max(self): ...
StarcoderdataPython
58530
# Copyright 2017 The Tulsi 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 by applicable ...
StarcoderdataPython
159131
<reponame>misteraverin/flake8-annotations-coverage def foo(): pass def bar(*args, kwonly_arg: str = None): pass
StarcoderdataPython
19220
<reponame>DSciLab/mlutils from typing import Callable, Optional, Union, Tuple, List import torch from torch import nn from cfg import Opts from torch import Tensor from torch.nn import functional as F from mlutils import LogitToPreds EPS = 1.0e-8 __all__ = ['IOULoss', 'GDiceLoss', 'SoftDiceLoss', 'CrossE...
StarcoderdataPython
4842169
#!/pxrpythonsubst # # Copyright 2017 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # ...
StarcoderdataPython
3370894
# ----- Info ------------------------------------------------------------------ __author__ = '<NAME> <<EMAIL>>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.services.table_builder.exception \ import TableBuilderException from tinyAPI.base.services.table_builde...
StarcoderdataPython
1663864
<filename>main/construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal-scratch.py # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def ...
StarcoderdataPython
3232031
<filename>lib/BloatAPI.py ''' Author: <NAME> Email: <EMAIL> Most the functions are based on the paper: - 'Bounds and Perturbation Bounds for the Matrix Exponential' by Bo Kagstrom - 'The Sensitivity of the Matrix Exponential' by <NAME> - 'Norms of Interval Matrices' by <NAME>, <NAME> and <NAME> - Linear Dynamical Sy...
StarcoderdataPython
1765585
import os from deepblast.dataset.utils import state_f, revstate_f import pandas as pd import numpy as np from collections import Counter def read_mali(root, tool='manual', report_ids=False): """ Reads in all alignments. Parameters ---------- root : path Path to root directory tool : str ...
StarcoderdataPython
1633822
import pytest # noinspection PyProtectedMember from infoblox import _settings @pytest.mark.parametrize(('setting_name', 'setting_type'), [ ('DEFAULT_CONNECT_TIMEOUT', float), ('DEFAULT_READ_TIMEOUT', float), ('DEFAULT_MAX_RETRIES', int), ('DEFAULT_BACKOFF_FACTOR', float) ]) def test_settings_presence...
StarcoderdataPython
3295594
from datetime import datetime from typing import Optional from uuid import UUID from server.schemas.base import BoilerplateBaseModel class ShopToPriceBase(BoilerplateBaseModel): active: bool new: bool price_id: UUID shop_id: UUID category_id: UUID kind_id: Optional[UUID] = None product_id...
StarcoderdataPython
3213387
<reponame>IvanTodorovBG/SoftUni import re racers = input().split(", ") my_dict = {} data = input() string_pattern = r"[a-zA-Z]" num_pattern = r"[0-9]" while data != "end of race": name = "".join(re.findall(string_pattern, data)) if name in racers: numbers = re.findall(num_pattern, data) nums ...
StarcoderdataPython
1733252
"""Tests for spiketools.stats.permutations""" from spiketools.stats.permutations import * ################################################################################################### ################################################################################################### def test_vec_perm(): d...
StarcoderdataPython
3277939
'''set_stall_detection(stop_when_stalled) Turns stall detection on or off. Stall detection senses when a motor has been blocked and can’t move. If stall detection has been enabled and a motor is blocked, the motor will be powered off after two seconds and the current motor command will be interrupted. If stall detectio...
StarcoderdataPython
1715607
<filename>Harpe-website/website/contrib/communication/admin.py # -*- coding: utf-8 -*- from django.conf import settings from django.contrib import admin #from django.utils.translation import ugettext_lazy as _ #from webcore.utils.admin import AdminThumbnailMixin #from grappellifit.admin import TranslationAdmin from we...
StarcoderdataPython
1702659
from pytest import raises from Lexer import Lexer from Token import Token, TokenTypes def test_repr(): assert repr(Lexer('1 + 3')) == '<Lexer [1] + 3>' def test_advance(): lexer = Lexer('1 + 3') lexer.advance() assert repr(lexer) == '<Lexer 1[ ]+ 3>' lexer.advance() assert repr(lexer) == ...
StarcoderdataPython
1616640
<filename>choose_nodes/lazy.py #!/usr/bin/env python3 import numpy as np def lazy(N, n): ''' Chose first n nodes as the measure nodes Arguments: 1. N: Total number of nodes 2. n: Number of measure nodes Returns: 1. measure_id: Measured node indices of the original (whole) net...
StarcoderdataPython
1776935
<filename>satori.web/satori/web/setup.py # vim:ts=4:sts=4:sw=4:expandtab """Takes care of settings required by Django. Import this module before django.* """ import os os.environ['DJANGO_SETTINGS_MODULE'] = 'satori.web.settings' from django.core.management import setup_environ from satori.web import settings setup_e...
StarcoderdataPython
1761397
import os import csv csv_path = os.path.join("..", "Resources", "PyBank", "budget_data.csv") output_path = os.path.join("..", "Analysis", "PyBank_Analysis.txt") with open(csv_path) as csv_file: csv_read = csv.reader(csv_file) next(csv_read) months = 0 total = 0 total_ch = 0 prev_rev = 0 ...
StarcoderdataPython
3375023
<filename>cli-image-processing/src/controller.py import os import settings import cv2 import time import requests class App: original_images = [] processed_images =[] original_images_paths = [] cv_images = [] resized_images = [] grayscale_image = [] canny_edge_detection = [] def __in...
StarcoderdataPython
1666218
from math import factorial mod = int(1e9 + 7) n = int(input()) ans = factorial(n) print(ans % mod)
StarcoderdataPython
3377477
""" Use of this source code is governed by the MIT license found in the LICENSE file. Base for serial or socket connections """ class StickConnection(object): """ Generic Plugwise stick connection""" def open_port(self) -> bool: """Placeholder to initialize the connection""" raise NotImplemen...
StarcoderdataPython
4818815
<reponame>Milo-Goodfellow-Work/GuildsDevelopmentBuild from django.apps import AppConfig class FullsearchConfig(AppConfig): name = 'FullSearch'
StarcoderdataPython
164262
from django.shortcuts import render from django.core import serializers from . models import Sensor, Devices, Online, Speedtest import json from django.http import HttpResponse from django.views.decorators.http import require_GET # Create your views here. def index(request): template='temprature/index.html' result...
StarcoderdataPython
1620348
# Copyright 2016 Brocade Communications Systems, 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 required by applicable law or ...
StarcoderdataPython
144792
<reponame>0x008800/Sandbox import urllib.request response = urllib.request.urlopen('https://google.com/') products = response.read() mystr = products.decode("utf8") response.close() file = open('file.txt', 'w') file.write(mystr) file.close() print(mystr)
StarcoderdataPython
171187
import matplotlib.pyplot as plt from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval import numpy as np import skimage.io as io import ipdb;pdb=ipdb.set_trace from collections import OrderedDict # markdown format output def _print_name_value(name_value, full_arch_name): names = name_value.ke...
StarcoderdataPython
1727036
<filename>hrflow/hrflow/job/__init__.py<gh_stars>1-10 from .parsing import JobParsing from .indexing import JobIndexing from .embedding import JobEmbedding from .searching import JobSearching from .scoring import JobScoring from .reasoning import JobReasoning class Job(object): def __init__(self, client): ...
StarcoderdataPython
4822310
#from airflow import DAG #from airflow.operators.python import PythonOperator #from airflow.utils.dates import days_ago import sqlite3 import pandas as pd default_args = {'owner': 'airflow'} path = "C:\\Users\\joaoa\\Documents\\bootcamp" path_db_producao = path+"\\data\\imoveis_prod.db" path_db_datawarehouse = path+"...
StarcoderdataPython
1732017
import logging from abc import ABC from typing import Any, Dict, Type, Union from torch.optim import Optimizer from torch.tensor import Tensor from torch.utils.data import DataLoader, TensorDataset from melbe.collections.pipelines.torch.configs import TorchConfig from melbe.data import PREDICTIONS, TEXT_SENTENCE, LIS...
StarcoderdataPython
4822301
<gh_stars>1-10 import os from os import path from importlib import import_module from flask import Flask from flask import url_for from flask_login import LoginManager import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration from api.views.new_cases import new_cases_views from api.views.redirects ...
StarcoderdataPython
1633591
from output.models.nist_data.atomic.duration.schema_instance.nistschema_sv_iv_atomic_duration_enumeration_5_xsd.nistschema_sv_iv_atomic_duration_enumeration_5 import ( NistschemaSvIvAtomicDurationEnumeration5, NistschemaSvIvAtomicDurationEnumeration5Type, ) __all__ = [ "NistschemaSvIvAtomicDurationEnumerat...
StarcoderdataPython
3257059
<reponame>ifwe/digsby import logging logging.Logger.debug_s = logging.Logger.debug import wx from gui.browser.webkit import WebKitWindow def test_webkit_unicode(): f = wx.Frame(None) w = WebKitWindow(f, initialContents = 'test') #w.RunScript('document.write("test");') def foo(): ...
StarcoderdataPython
3215985
import sys import json from subprocess import Popen, PIPE try: import yaml except ImportError: print('Unable to import YAML module: please install PyYAML', file=sys.stderr) sys.exit(1) class Reporter(object): """Collect and report errors.""" def __init__(self): """Constructor.""" ...
StarcoderdataPython
1635251
# -*- encoding: utf-8 -*- ''' HubbleStack Nova-to-Splunk returner :maintainer: HubbleStack :platform: All :requires: SaltStack Deliver HubbleStack Nova result data into Splunk using the HTTP event collector. Required config/pillar settings: .. code-block:: yaml hubblestack: returner: splunk: ...
StarcoderdataPython
3218939
""" Adafruit BME280 temp/press/hum """ from datetime import datetime import logging from threading import Event, Thread import time import Adafruit_BME280 from sensor_feed.sensor_multi import MultiSensorDevice, ChildSensor LOGGER = logging.getLogger(__name__) class BME280Sensor(MultiSensorDevice): """Adafruit...
StarcoderdataPython
3354159
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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 require...
StarcoderdataPython
3378150
import math def parse(z): ast = None return z print(parse('z')) math.log(42)
StarcoderdataPython
125377
import json import re import ast import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold, cross_val_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, log_los...
StarcoderdataPython
4833139
from mock import Mock from mock import patch import pytest import typing # NOQA from optuna import distributions from optuna import samplers from optuna import storages from optuna.study import create_study from optuna.trial import FixedTrial from optuna.trial import Trial parametrize_storage = pytest.mark.parametri...
StarcoderdataPython
3221756
<filename>oregami/sark_bc.py import sark ########################################################## # Adding backwards compatability for sark before python3 # ########################################################## # Sark started using start_ea, end_ea instead of start_ea, end_ea # We will make the old sark (for py...
StarcoderdataPython
1783369
<gh_stars>1-10 import hashlib m = [hashlib.sha256(), hashlib.sha512(), hashlib.blake2b(), hashlib.blake2s(), hashlib.sha3_256(), hashlib.sha3_512()] input = b"testByteArray" for n in m: n.update(input) print(n.digest().hex().upper())
StarcoderdataPython
107397
#!/usr/bin/env python """JARVIS 2 helper script Usage: run.py -j [-s] [NAME] run.py [-d] Options: -h --help Show usage -d --debug Run app in debug mode -j --job Run a job, will prompt if NAME is not given -s --json Print job output as JSON """ from __future__ import print...
StarcoderdataPython
3250391
def swap(i,j): tmp=line[i] line[i]=line[j] line[j]=tmp a=input() line=input() a=a.split(' ') num=a[0] time=int(a[1]) line=[i for i in line] while(time>0): time-=1 flagBoy=False for i in range(len(line)): if(line[i]=='B'): flagBoy=True if(flagBoy and line[i]=='G'): ...
StarcoderdataPython