id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
1840691
# -*- coding: utf-8 -*- import os from django.conf import settings from django import forms from django.utils.translation import ugettext_lazy as _ from .models import * class VideoForm(forms.ModelForm): class Meta: model = Example exclude = [] widgets = { 'video': forms.Clea...
StarcoderdataPython
80326
from django.test import TestCase from addressbase.models import UprnToCouncil, Address from councils.tests.factories import CouncilFactory from data_importers.tests.stubs import stub_addressimport # High-level functional tests for import scripts class ImporterTest(TestCase): opts = {"nochecks": True, "verbosity"...
StarcoderdataPython
6521789
<filename>backend/model_api/urls.py from django.urls import path from model_api import views urlpatterns = [ path('affected_by/', views.affected_by), path('areas/', views.areas), path('cumulative_infections/', views.cumulative_infections), path('predict/', views.predict), path('predict_all/', view...
StarcoderdataPython
5178258
import json import uuid import aiohttp import pytest HOSTNAME, PATH = 'https://test.ar', 'index' async def test_match_request(ar, session): ar.get(HOSTNAME, PATH, handler={}) try: await session.get(f'{HOSTNAME}/{PATH}') except aiohttp.ClientConnectionError as e: pytest.fail(f'Should not...
StarcoderdataPython
3428963
import argparse import collections import inspect import re import signal import sys from datetime import datetime as dt import numpy as np def argparsify(f, test=None): args, _, _, defaults = inspect.getargspec(f) assert(len(args) == len(defaults)) parser = argparse.ArgumentParser() i = 0 for ar...
StarcoderdataPython
278578
#!/usr/bin/python #coding=utf-8 """ 第 0009 题:一个HTML文件,找出里面的链接 """ from bs4 import BeautifulSoup def find_the_link(filepath): links = [] with open(filepath) as f: text = f.read() bs =BeautifulSoup(text) for i in bs.find_all('a'): links.append(i['href']) return links ...
StarcoderdataPython
294967
""" Django settings for matatu project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os fro...
StarcoderdataPython
6502997
#!/usr/local/bin/python3 from driver import Driver from log import Log from selenium.common.exceptions import NoSuchElementException class Element(Driver): def find_by_id(self, id=None): if not id: return False try: return self.driver.find_element_by_id(id) except...
StarcoderdataPython
5130331
<filename>tg_gui_core/__init__.py from . import implementation_support from .implementation_support import TYPE_CHECKING from .shared import Identifiable, Pixels, UID from .widget import Widget from .attrs import WidgetAttr, widget from .container import ContainerWidget
StarcoderdataPython
11283566
from .binomial_regression import BinomRegression from .linear_regression import BayesianLinearRegression
StarcoderdataPython
8360
<filename>tests/pyre/components/component_class_registration_model.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # <NAME> # orthologue # (c) 1998-2018 all rights reserved # """ Verify that component registration interacts correctly with the pyre configurator model """ # access # print(" -- importing...
StarcoderdataPython
8159114
<filename>apps/auth/views.py import logging import datetime from misc.mixins import myTemplateView class indexView(myTemplateView): template='index.tpl' class expressauthView(myTemplateView): template='auth/expressauth.tpl' class regView(myTemplateView): template='auth/reg.tpl' class repairView(myTemp...
StarcoderdataPython
1739936
List = list(map(int, input().split())) List.insert(0, List.pop()) print(*List)
StarcoderdataPython
300589
#// #// ------------------------------------------------------------- #// Copyright 2004-2011 Synopsys, Inc. #// Copyright 2010 Mentor Graphics Corporation #// Copyright 2010-2011 Cadence Design Systems, Inc. #// Copyright 2019-2020 <NAME> (tpoikela) #// All Rights Reserved Worldwide #// #// Licensed ...
StarcoderdataPython
1960162
<gh_stars>1-10 from chutil.visualize import show
StarcoderdataPython
3229582
# -*- coding: utf-8 -*- import os from distutils.core import setup here = os.path.dirname(__file__) def get_long_desc(): return open(os.path.join(here, 'README.rst')).read() # Function borrowed from carljm. def get_version(): fh = open(os.path.join(here, "faq", "__init__.py")) try: for line in...
StarcoderdataPython
3297897
from .base import UrbanClient, UrbanDefinition, UrbanDictionaryError
StarcoderdataPython
6469605
<filename>cloakifyFactory.py #!/usr/bin/python # # Filename: cloakifyFactory.py # # Version: 1.0.1 # # Author: <NAME> (TryCatchHCF) # # Summary: Cloakify Factory is part of the Cloakify Exfiltration toolset that transforms # any fileype into lists of words / phrases / Unicode to ease exfiltration of data across ...
StarcoderdataPython
1769435
<gh_stars>1-10 """ 参数化clock装饰器 """ import time DEFAULT_FMT = '[{elapsed:0.8f}s] {name}({args}) ->{result}' def clock(fmt=DEFAULT_FMT): # 参数化装饰器工厂函数 def decorate(func): # 真正的装饰器 def clocked(*_args): # 包装被装饰的函数 t0 = time.time() _result = func(*_args) # 被装饰的函数返回额真正结果 ...
StarcoderdataPython
11267301
<reponame>niacdoial/armory from arm.logicnode.arm_nodes import * class TimeNode(ArmLogicTreeNode): """Returns the application execution time and the delta time.""" bl_idname = 'LNTimeNode' bl_label = 'Get Application Time' arm_version = 1 def init(self, context): super(TimeNode, self).init...
StarcoderdataPython
11229289
import unittest import json from pyvdk.tools import Keyboard, TextButton class KeyboardTests(unittest.TestCase): def test_limit(self): # Arrange keyboard = Keyboard(inline=True) b = [ TextButton( color='w', label=str(i), payload=s...
StarcoderdataPython
9613089
<filename>more_collections/sorted/_sorted_iterable.py from __future__ import annotations import sys from typing import Generic, TypeVar if sys.version_info < (3, 9): from typing import Iterable, Iterator else: from collections.abc import Iterable, Iterator from ._abc_iterable import SortedIterable, SortedIter...
StarcoderdataPython
8147711
import math class Circulo(): def __init__(self): super() self.__raio = None def get_perimetro(self): return 2 * math.pi * self.raio def get_area(self): return math.pi * self.raio ** 2 @property def raio(self): return self.__raio @raio.setter ...
StarcoderdataPython
12818857
<reponame>mhungerford/pebble-glracer #!/usr/bin/env python # encoding: utf-8 # <NAME>, 2013 """Writes the c and cpp compile commands into build/compile_commands.json see http://clang.llvm.org/docs/JSONCompilationDatabase.html""" import json import os from waflib import Logs, TaskGen, Task from waflib.Tools import c, ...
StarcoderdataPython
9787361
""" Easier factory functions for creating Pymunk objects. """ from functools import wraps from typing import Sequence, Union, Callable, TypeVar, TYPE_CHECKING, Any from . import Color, DrawOptions from .helpers import get_pyxel from ..core import CircleBody, SegmentBody, PolyBody, Body, Space from ..typing import VecL...
StarcoderdataPython
3377062
<reponame>pcarivbts/vbts-webadmin<filename>vbts_webadmin/tests/locust/locustfile_api_promo.py """ Copyright (c) 2015-present, Philippine-California Advanced Research Institutes- The Village Base Station Project (PCARI-VBTS). All rights reserved. This source code is licensed under the BSD-style license found in the LIC...
StarcoderdataPython
1761779
<gh_stars>0 # Generated by Django 2.1.5 on 2019-06-09 09:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('gpsschool', '0013_auto_20190609_0557'), ] operations = [ migrations.AddField( model...
StarcoderdataPython
6458655
"""Util functions.""" import logging from functools import wraps from pathlib import Path from morphio.mut import Morphology from tqdm import tqdm tqdm.pandas() EXTS = {".asc", ".h5", ".swc"} # allowed extensions def is_morphology(filename): """Returns True if the extension is supported.""" try: M...
StarcoderdataPython
3267265
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ import os import sys # Parse arguments if len(sys.argv) != 3: print('Incorrect number of args') exit(...
StarcoderdataPython
8144729
<reponame>kpahawa/quick_config import os from quick_config.provider_wrapper import load_config_from_path from quick_config.validator import validate_config_dir config = None _env_key = 'CONFIG_DIR' __all__ = [ 'config', 'load_config', 'setup_config_with_path', 'clear_config', ] def clear_config():...
StarcoderdataPython
6642065
<filename>CUILArg.py class CUIL(): def __init__(self, Dni, Sexo): self.dni = Dni.replace('.', '') self.sexo = Sexo self.get = '' self.get_dni() self.get_sexo() self.get_cuil() def get_dni(self): if len(self.dni) == 7: self.dni = '0' + self.dni return True elif len(self.dni) != 8: ...
StarcoderdataPython
6527373
import os from daskperiment.util.text import trim_indent class TestText(object): def test_trim_indent(self): res = trim_indent("") assert res == "" res = trim_indent("ab") assert res == "ab" res = trim_indent(os.linesep) assert res == os.linesep def test_tri...
StarcoderdataPython
6651092
from lxml import etree from dataset.data import Data from strategy.parser.default_parser import DefaultParser import re class PostParser(DefaultParser): def __init__(self): self.super = super(PostParser, self) self.super.__init__() def get_url_value(self): v = re.search(r'\d*.html$', se...
StarcoderdataPython
5082141
<reponame>lh70/s-connect-python import esp32 from lh_lib.sensors.sensor import AbstractSensor class Hall(AbstractSensor): """ sets an integer of range +- unknown representing the current internal hall sensor reading """ def update(self): self.value = esp32.hall_sensor()
StarcoderdataPython
9642762
from django.test import TestCase from playlists.models import Playlist # Create your tests here. class PlaylistModelTests(TestCase): def setUp(self): Playlist.objects.create(code='1', title='playlist title 1') def test_instance_get_string_repr(self): """ Playlist object string representati...
StarcoderdataPython
1613404
from leapp.actors import Actor from leapp.libraries.actor import opensshuseprivilegeseparationcheck from leapp.models import Report, OpenSshConfig from leapp.tags import ChecksPhaseTag, IPUWorkflowTag class OpenSshUsePrivilegeSeparationCheck(Actor): """ UsePrivilegeSeparation configuration option was removed....
StarcoderdataPython
3375923
import torch import matplotlib.pyplot as plt from matplotlib.pyplot import cm import h5py import os from glob import glob from patch_manager import StridedRollingPatches2D, StridedPatches2D, NoPatches2D from utils import squeeze_repr import torch.utils.data as torch_data import numpy as np from transforms import RndAug...
StarcoderdataPython
208585
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sistema', '0023_auto_20170105_1514'), ] operations = [ migrations.RenameField( model_name='detallefactura', ...
StarcoderdataPython
8008180
def add(x, y): return (x+y) def mul(x, y): return (x*y) def sub(x, y): return (x-y) def div(x, y): return (x/y)
StarcoderdataPython
1631979
#!/usr/bin/python import os import sys import binascii import grpc from lndlibs import rpc_pb2 as ln from lndlibs import rpc_pb2_grpc as lnrpc from pathlib2 import Path print("This is the legacy - Python2 only - version.") if sys.version_info > (3, 0): print("Can't run on Python3") sys.exit() # display config...
StarcoderdataPython
3433461
<gh_stars>0 from ayeauth import db from ayeauth.models import BaseModel, _get_uuid class AuthorizationCode(BaseModel): __tablename__ = "authorization_codes" code = db.Column(db.String(36), nullable=False, default=_get_uuid) expiry = db.Column(db.DateTime(), nullable=False) state = db.Column(db.String...
StarcoderdataPython
6695280
<reponame>beikerta/sasmodels<gh_stars>0 r""" .. warning:: This model and this model description are under review following concerns raised by SasView users. If you need to use this model, please email <EMAIL> for the latest situation. *The SasView Developers. September 2018.* Def...
StarcoderdataPython
11327942
# Owner(s): ["oncall: jit"] import os import sys import warnings import torch from typing import List, Dict, Optional # Make the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) from torch.testing._internal.jit_utils im...
StarcoderdataPython
8129698
<reponame>igushev/fase_lib<gh_stars>1-10 import re DEMO_PHONE_REGEXP = '\+100000000[0-9][0-9]' DEMO_ACTIVATION_CODE = 321654 def PhoneNumberIsDemo(phone_number): return re.fullmatch(DEMO_PHONE_REGEXP, phone_number) is not None
StarcoderdataPython
1693531
<reponame>andrewsmedina/django-admin2 from __future__ import unicode_literals from blog.views import BlogListView, BlogDetailView from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from djadmin2.site import djadmin2_si...
StarcoderdataPython
5085668
__all__ = [ "RunTest" ]
StarcoderdataPython
9681277
from pypika.dialects import Query from weaverbird.backends.pypika_translator.dialects import SQLDialect from weaverbird.backends.pypika_translator.translators.base import SQLTranslator class AthenaTranslator(SQLTranslator): DIALECT = SQLDialect.ATHENA QUERY_CLS = Query SUPPORT_ROW_NUMBER = True SUPPO...
StarcoderdataPython
5099691
<reponame>SaxenaKartik/Convin-Backend from django.contrib import admin from tracker_api import models # Register your models here. admin.site.register(models.Task) admin.site.register(models.TaskTracker)
StarcoderdataPython
9718521
# number = [5, 6, 4, 2, 1, 9] # max = number[0] # for x in number: # if number > x: # x = number # print(max) number = [1, 1, 2, 2, 5, 7, 8, 5, 5] # number = list(dict.fromkeys(number)) # print(number) numbers = [] for numb in number: if numb not in number: numbers.append(numb) prin...
StarcoderdataPython
3213275
<filename>backend/readImages.py import numpy as np # import pandas as pd # f = open('dataset/data/imagedata.txt') # contents = f.read() # f.close() checkArray = np.loadtxt('dataset/data/imagedata.npy') checkArray = checkArray.reshape(1800, 48400) print(checkArray.shape) print(checkArray.size)
StarcoderdataPython
1818412
""" * ******************************************************* * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved. * SPDX-License-Identifier: MIT * ******************************************************* * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, WHET...
StarcoderdataPython
8188956
<gh_stars>1-10 import discord from discord_components import Button, ButtonStyle import modules.buttons.globals as global_values class ComponentMessage: def __init__(self, actionrows, **kwargs): self.temporary = kwargs["temporary"] if "temporary" in kwargs else True self.components = [] i = 0 for row in act...
StarcoderdataPython
3515855
<filename>src/models/ops/conv_blocks.py import tensorflow as tf from tensorflow.keras import layers from tensorflow.nn import relu6 from models.ops import conv_ops as ops # Bloque comun de convolucion que consiste: # > conv2d # > batch normalization # > activation # > dropout class basic_conv_block(layers...
StarcoderdataPython
1873864
import numpy as np from scipy import integrate from matplotlib.pylab import * import matplotlib.pyplot as plt ''' Stiff combustion equation ''' def combustion(t,y): n = len(y) dydt = np.zeros((n,1)) #dydt[0] = -15*y dydt[0] = y**2 - y**3 return dydt # The ``driver`` that will integrate the ODE(s)...
StarcoderdataPython
6640460
from alembic import op """Drop UserObservation unique constraint in favor of history Revision ID: <KEY> Revises: <PASSWORD> Create Date: 2018-04-06 04:47:18.518343 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<PASSWORD>' def upgrade(): # ### commands auto generated by Alemb...
StarcoderdataPython
11275326
# Generated by Django 3.2.4 on 2021-06-16 18:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('quiz', '0013_auto_20210616_2305'), ] operations = [ migrations.RenameModel( old_name='Questions', new_name='QuizQuestions', ...
StarcoderdataPython
9697876
from Clases.Helpers import Helpers from Clases.QLDBDriver import QLDBDriver from Clases.Password import Password class Service(): def __init__(self): self.password = Password() self.db = QLDBDriver() def validate_user(self, user, password): user_data = self.get_user(user) if u...
StarcoderdataPython
5010266
#!/usr/bin/env python # -*- coding: utf-8 -*- import setuptools from pbr.packaging import parse_requirements entry_points = { } setuptools.setup( name='placementclient', version='0.3.0', description=('Client for the Placement API'), author='<NAME>', author_email='<EMAIL>', url='https://gi...
StarcoderdataPython
9792563
import mkdocs_gen_files import os import glob # iterate over pages and append glossary for file in glob.glob("/docs/docs/**/*.md", recursive = True): if file.endswith('.md'): text = open(file).read() with mkdocs_gen_files.open(file.replace('/docs/docs/', ''), "w") as f: print(text + '\n--8<-- "./glossa...
StarcoderdataPython
6484546
import os import docx from docx.shared import Inches class doc: def __init__(self, filesize, filename,generator,WORD_SEPARATOR): self.filesize = filesize self.filename = filename self.generator = generator self.word_separator = WORD_SEPARATOR def execute(self): for i in ...
StarcoderdataPython
4853168
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 14 14:45:53 2022 @author: fatemehmohebbi """ from Bio import Phylo import networkx as nx import numpy as np import pandas as pd from scipy import sparse import scipy.special as sc import matplotlib.pyplot as plt import pydot from networkx.drawing.n...
StarcoderdataPython
3518345
import json def lambda_handler(event, context): #debugEvent(event) #.1 Parse the querystring parameters params = readParams(event) #.2 Construct the body of the response responseBody = { "transactionId": params["transactionId"], "transactionType": params["transactionType"], ...
StarcoderdataPython
9710475
import sys from flask import Flask app = Flask(__name__) @app.route("/") def main(): with open("pylabs.html") as f: return f.read() @app.route("/favicon.ico") def favicon(): with open("favicon.ico", "rb") as fb: return fb.read() @app.route("/hello") def hello(): return "Hello, world."
StarcoderdataPython
4852171
# This is where the classes and objects are defined import random class Game: def __init__(self, difficulty, length, cave_map): self.cave_map = cave_map self.difficulty = difficulty self.length = length class Condition: def __init__(self, name, damage, ac_reduction, dura...
StarcoderdataPython
5008172
from tts_pipeline.pipelines.waterfall.pipeline import WaterfallPipeline from tts_pipeline.pipelines.waterfall.models.UnifiedKeywordExtractor import UnifiedKeywordExtractor from tts_pipeline.pipelines.waterfall.models.gnews_models import GNewsWaterfallEmbedder from tts_pipeline.pipelines.waterfall.models.examples import...
StarcoderdataPython
181004
<gh_stars>1000+ # Copyright (c) 2020, NVIDIA CORPORATION. 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 r...
StarcoderdataPython
6543960
# ./pyxb/bundles/wssplat/raw/wsdl11.py # -*- coding: utf-8 -*- # PyXB bindings for NM:d363f64a147eb09d66a961a815c9d842964c1c79 # Generated 2016-09-18 17:34:04.329631 by PyXB version 1.2.5 using Python 2.7.12.final.0 # Namespace http://schemas.xmlsoap.org/wsdl/ from __future__ import unicode_literals import pyxb import...
StarcoderdataPython
5097165
#pragma error #pragma repy restrictions.fewevents def foo(timername): mycontext[timername] = True sleep(2) if callfunc=='initialize': mycontext['timetogo'] = False myval = settimer(.2, foo, ('a',)) myval = settimer(.3, foo, ('b',)) myval = settimer(.4, foo, ('c',)) sleep(1) if mycontext['a'] and mycon...
StarcoderdataPython
146966
# Copyright 2020 Google LLC. 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 law or a...
StarcoderdataPython
6443411
<gh_stars>1-10 import json import os import requests from urllib3 import Retry class Reporter: def __init__(self, cookie: str) -> None: self.__read_sites() self.__init_session(cookie) def __read_sites(self) -> None: with open(os.path.join("src", "sites.json"), "r", encoding="utf-8") ...
StarcoderdataPython
26782
# -*- coding: utf-8 -*- # Author: t0pep0 # e-mail: <EMAIL> # Jabber: <EMAIL> # BTC : 1ipEA2fcVyjiUnBqUx7PVy5efktz2hucb # donate free =) # Forked and modified by <NAME> # Compatible Python3 import hmac import hashlib import time import urllib.request, urllib.parse, urllib.error import json class Api(object): __...
StarcoderdataPython
1812593
from django.shortcuts import render # Create your views here. from django.db import transaction from django.utils.decorators import method_decorator #create global transactional class mixin from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters class TransactionalViewMixin(o...
StarcoderdataPython
6598969
<filename>src/empirical_fire_modelling/analysis/pfi.py # -*- coding: utf-8 -*- """PFI calculation.""" import eli5 from wildfires.qstat import get_ncpus from ..cache import cache @cache def calculate_pfi(rf, X, y): """Calculate the PFI.""" rf.n_jobs = get_ncpus() perm_importance = eli5.sklearn.Permutatio...
StarcoderdataPython
11290772
<filename>scripts/mmd/MMD-critic/mmd.py # maintained by <EMAIL> from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np # from mpi4py import MPI import sys import math ##############################################################################...
StarcoderdataPython
11211858
from motor_typing import TYPE_CHECKING def options(option_context): # type: (Options.OptionsContext) -> None pass if TYPE_CHECKING: from waflib import Options
StarcoderdataPython
5121322
# utility functions for working with json from types import * # merges keys from j2 into j1 def json_merge_missing_keys(j1, j2, overwrite=False, exclude=[]): for key in j2: if ((not key in j1) or overwrite) and (key not in exclude): j1[key] = j2[key]; def get_child_by_key_values(j1, kvs={...
StarcoderdataPython
201651
<gh_stars>1-10 #!/usr/bin/python # (c) 2018-2019, NetApp Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_vscan ''' from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
StarcoderdataPython
3491775
import logging import random import string from datetime import date, datetime from enum import Enum, auto from threading import RLock, Timer from typing import TYPE_CHECKING, Dict, Literal, Optional from localstack import config from localstack.services.awslambda.invocation.executor_endpoint import ServiceEndpoint fr...
StarcoderdataPython
8086306
<reponame>technoborsch/AtomREST<gh_stars>0 NO_REMARKS_TIPS = [ 'Это ненадолго :)', 'По крайней мере, мы о них не знаем', 'Это не значит, что всё правильно', 'Сейчас добавим :)', 'Держу в курсе', 'Можно расслабиться', 'Удивительно', 'Классно же', 'Вау!', 'Но ты-то сам знаешь, где ...
StarcoderdataPython
6687367
<reponame>marty1912/dna_app<filename>trialgen.py #!/bin/python3 import sys import json import shutil import os import subprocess import random import time import pandas as pd import argparse import copy from os import listdir from os.path import isfile, join, basename ,splitext from os import walk from pandas.core.f...
StarcoderdataPython
228442
<reponame>yyht/topmine_py3<gh_stars>1-10 import numpy as np def merge_single_char(phrase): segment_lst = phrase[0].strip().split() leng = [len(item) for item in segment_lst]
StarcoderdataPython
8050832
# -*- coding: utf-8 -*- import os import sys import cv2 import pytest import mock import numpy as np import sksurgeryutils.common_overlay_apps as coa def test_OverlayOnVideoFeedCropRecord_from_file(setup_qt, tmpdir): in_github_ci = os.environ.get('CI') if in_github_ci and sys.platform.startswith("linux"): ...
StarcoderdataPython
1827458
<gh_stars>1-10 # Copyright 2017-present Open Networking Foundation # # 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 applic...
StarcoderdataPython
8092540
text = open("out-sorted.txt").read().strip("\n") a = []; b = [] for i in text.split("\n"): a.append(i.split(",")[0]) for i in text.split("\n"): b.append(i.split(",")[1]) text = "" for i in range(0, len(b)): text += chr(int(a[i])) print text
StarcoderdataPython
1715694
#!/usr/bin/python3 from serial import Serial from time import sleep ser = Serial('/dev/ttyUSB0', baudrate=115200) # open music.raw unsigned 8-bit PCM audio with open('music.raw','rb') as f: b = f.read(16) while(len(b)>0): ser.write(b) ser.flush() b = f.read(16) print("done")
StarcoderdataPython
11248178
<filename>src/tests/utils.py<gh_stars>1-10 import os from abc import abstractmethod from unittest import TestCase from PIL import Image SHOW_MISMATCH = True ASSERT_ON = False def get_reference_img_path(folder, *args): return get_reference_dir_path(folder) + '_'.join(map(str, args)) + '.png' def get_reference...
StarcoderdataPython
4990917
<reponame>Bakkhos/aepp-sdk-python import logging import os from aeternity.config import Config from aeternity.signing import Account from aeternity import node # for tempdir import shutil import tempfile from contextlib import contextmanager import random import string logging.getLogger("requests").setLevel(logging.DE...
StarcoderdataPython
11227915
import duckdb try: import pyarrow import pyarrow.parquet import urllib.request can_run = True except: can_run = False class TestArrow(object): def test_arrow(self, duckdb_cursor): if not can_run: return parquet_filename = 'userdata1.parquet' urllib.reques...
StarcoderdataPython
9643270
import matplotlib.pyplot as plt from wordcloud import WordCloud import platform def create_cloud(word_list): pf = platform.system() if pf == 'Windows': font_path = r"C:\WINDOWS\Fonts\UDDIGIKYOKASHON-R.TTC" elif pf == 'Darwin': font_path = "/System/Library/Fonts/ヒラギノ角ゴシック W4.ttc" elif...
StarcoderdataPython
11237079
<reponame>VaCH2/tosca-analysis import os import pandas as pd #calculator is the class that calculates the source code measurements upon provided TOSCA blueprints from toscametrics import calculator import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_sim...
StarcoderdataPython
4886192
import redis import time import math class RedisMonitor: """ Monitor Redis keys and send updates to all web socket clients. """ def __init__(self, host="localhost", port=6379, password="", db=0, refresh_rate=0.5, key_filter="", realtime=False): """ If realtime is specified, RedisMonito...
StarcoderdataPython
6568423
""" @file: __init__.py @time: 2020-09-23 20:37:10 """
StarcoderdataPython
4999770
#!/usr/bin/env python # coding: utf-8 # In[1]: from matplotlib import pyplot as plt #get_ipython().magic(u'matplotlib notebook') from keras.models import load_model from model import get_personlab from scipy.ndimage.filters import gaussian_filter import cv2 import numpy as np from time import time from config impor...
StarcoderdataPython
6508299
<gh_stars>0 #!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, <NAME>, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source...
StarcoderdataPython
5138658
from __future__ import absolute_import, division, print_function from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.utils import isiterable, split BATCH_SIZE = 50 class User(PanoptesObject): _api_slug = 'users' _link_slug = 'users' _edit_attributes = ( 'valid_ema...
StarcoderdataPython
1849464
import sys from typing import Dict from reportlab.lib.units import inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont import uharfbuzz as hb SCALE_MULT = 1e5 class RLKerningError(Exception): pass # TODO drop the text arg once drawGlyphs has been implemented # TODO rajou...
StarcoderdataPython
8118471
<filename>covariant_compositional_networks_tf2/tests/testModel_2.py from covariant_compositional_networks_tf2.CCN_Model import CCN_Model import tensorflow as tf from functools import reduce from operator import mul from ordered_set import OrderedSet import numpy as np from sklearn.metrics import accuracy_score from gra...
StarcoderdataPython
1824825
import pickle import time import numpy as np from sklearn import metrics from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import RandomForestClassifi...
StarcoderdataPython
12825797
<reponame>iamharshit/ML_works import tensorflow as tf import numpy as np import cv2 img_original = cv2.imread('jack.jpg') #data.camera() img = cv2.resize(img_original, (64*5,64*5)) # for positions xs = [] # for corresponding colors ys = [] for row_i in range(img.shape[0]): for col_i in range(img.shape[1]): xs.a...
StarcoderdataPython
1945085
<reponame>immuta/tap-canny """tap-canny"""
StarcoderdataPython