id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
6419438
from ptree.generators.tree_generator import TreeGenerator from ptree.rptree import DirectoryTree import argparse import pathlib import sys from termcolor import colored ERROR_BANNER = colored("ERROR:", "red") def parse_args(): parser = argparse.ArgumentParser( prog="ptree", description="print tre...
StarcoderdataPython
6443717
import cv2 def change_brightness(img, value=30): hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(hsv) v = cv2.add(v,value) v[v > 255] = 255 v[v < 0] = 0 final_hsv = cv2.merge((h, s, v)) img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR) return img for datax in range(0,1): ...
StarcoderdataPython
1728331
<reponame>Anirban166/tstl<filename>tstl/replay.py from __future__ import print_function import sys import traceback import os import time # Appending current working directory to sys.path # So that user can run randomtester from the directory where sut.py is located current_working_dir = os.getcwd() sys.path.append(c...
StarcoderdataPython
4960863
<reponame>radmirnovii/databend #!/usr/bin/env python3 import os import sys import signal CURDIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURDIR, '../../helpers')) from client import client log = None # uncomment the line below for debugging log = sys.stdout client1 = client(nam...
StarcoderdataPython
166003
<gh_stars>1-10 # -*- encoding: utf-8 -*- """ Copyright (c) 2019 - present AppSeed.us License: https://github.com/app-generator/license-eula """ class COMMON: NULL = None # not set NA = -1 # not set OK = 0 # all ok ERR = 1 # not ok NOT_FOUND = 2 # file ...
StarcoderdataPython
3583059
<filename>system_test_progress_tracking/tm_api/admin.py from django.contrib import admin from .models import ( Machine, Test, Scenario, MasterScenario, DryRunData, ) admin.site.register(Machine) admin.site.register(Test) admin.site.register(Scenario) admin.site.register(MasterScenario) admin.site....
StarcoderdataPython
3436071
<reponame>ydong08/PythonCode #!/usr/bin/python #encoding=utf-8 from SocketServer import TCPServer, ForkingMixIn, StreamRequestHandler import time class Server(ForkingMixIn, TCPServer): #自定义Server类 pass class MyHandler(StreamRequestHandler): def handle(self): #重载handle函数 addr = self.request.getpeername...
StarcoderdataPython
9764066
<gh_stars>1-10 import copy import torch import torch.nn as nn from others.transformers import BertModel, BertConfig from others.transformers import RobertaModel, RobertaConfig from torch.nn.init import xavier_uniform_ from models.decoder import TransformerDecoder from models.encoder import Classifier, ExtTransformerE...
StarcoderdataPython
4864987
<gh_stars>0 from microbit import * import utime import machine import music class Robit: PRESCALE_REG = 0xFE MODE_1_REG = 0x00 SRV_REG_BASE = 0x08 MOT_REG_BASE = 0x28 REG_OFFSET = 4 SERVO_MULTIPLIER = 226 SERVO_ZERO_OFFSET = 0x66 chipAddress = 0x40 initialised = Fals...
StarcoderdataPython
3417560
print "Hello, Pyhons!"
StarcoderdataPython
371037
import json import cassandra import sys from cassandra.cluster import Cluster import os def main(): #create database connection cluster = Cluster() #use keyspace 'hash' session = cluster.connect() #!!! #CREATE KEYSPACE IF NOT EXITSTS hash WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor'...
StarcoderdataPython
3556586
from django.conf import settings as django_setting __all__ = ( 'LIKES_MODELS', 'LIKES_REST_PAGINATION_CLASS' ) LIKES_MODELS = getattr( django_setting, 'LIKES_MODELS', {} ) LIKES_REST_PAGINATION_CLASS = getattr( django_setting, 'LIKES_REST_PAGINATION_CLASS', None )
StarcoderdataPython
320175
<gh_stars>0 import easyocr import os reader = easyocr.Reader(['en']) images=os.listdir(r'NIC_Images') def get_data(data:list): Name=Father_Name=Gender=Id_Number=D_O_Birth=D_O_Issue=D_O_Expiry='-' gaurdian='Father Name' #father name if list(filter(lambda x: 'Father' in x, data)): Father_Name=d...
StarcoderdataPython
3398722
<reponame>realsifocopypaste333/sifo-player-binary # Generated by Django 3.0 on 2019-12-03 12:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('music', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='al...
StarcoderdataPython
6486814
<gh_stars>1000+ from cookies.resources.helpers import makeDropCookie, setNoCacheAndCORSHeaders def main(request, response): """Respond to `/cookies/resources/dropSameSiteMultiAttribute.py by dropping the cookies set by setSameSiteMultiAttribute.py""" headers = setNoCacheAndCORSHeaders(request, response) ...
StarcoderdataPython
8141114
import numpy as np class Space: """A space is a general concept, where it can be discrete or continuous.""" def __init__(self, check): """Defines a space, by having a check lambda. :param check A lambda verifying if the element is in the space. """ self.check = np.vectorize(...
StarcoderdataPython
11326564
<reponame>alex-oleshkevich/malanka<filename>malanka/sockets.py<gh_stars>1-10 import json import typing as t from starlette import status from starlette.concurrency import run_until_first_complete from starlette.types import Receive, Scope, Send from starlette.websockets import WebSocket from malanka.backends import Ev...
StarcoderdataPython
6530523
# The MIT License (MIT) # # Copyright (c) 2016 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
StarcoderdataPython
3535550
<filename>Chapter_9/try_9.13.py<gh_stars>0 #Done by <NAME> in 09/07/2020 """ Make a class Die with one attribute called sides , which has a default value of 6. Write a method called roll_die() that prints a random number between 1 and the number of sides the die has. Make a 6-sided die and roll it 10 times. Make a 10-...
StarcoderdataPython
67280
import bisect import collections import os import queue import random import subprocess import threading import time import traceback from hydrus.core import HydrusData from hydrus.core import HydrusExceptions from hydrus.core import HydrusGlobals as HG NEXT_THREAD_CLEAROUT = 0 THREADS_TO_THREAD_INFO = {} THREAD_INF...
StarcoderdataPython
5056358
from django.apps import AppConfig class WagtailFaviconConfig(AppConfig): name = 'wagtail_favicon'
StarcoderdataPython
11357002
<filename>src/keyedtensor/_repr_utils.py from typing import List def format_field(kstr: str, rows: List[str], prefix: str = '') -> str: kprefix = f'{prefix}{kstr}' pad = ' ' * (len(kprefix)) tensorstr = '\n'.join(f'{pad if i > 0 else ""}{v}' for i, v in enumerate(rows)) return f'{kprefix}{tensorstr}' ...
StarcoderdataPython
3510987
<filename>benchmark/algorithms/puck_t1.py<gh_stars>0 #-*- coding:utf-8 -*- ################################################################################ # # Copyright (c) 2021 Baidu.com, Inc. All Rights Reserved # ################################################################################ """ @file: puck_t1.py ...
StarcoderdataPython
11335563
# file: xpand.py # vim:fileencoding=utf-8:fdm=marker:ft=python # # Copyright © 2013-2017 <NAME> <<EMAIL>>. # SPDX-License-Identifier: MIT # Created: 2013-08-13T23:13:48+0200 # Last modified: 2018-04-17T20:45:41+0200 """Function to expand filename globs.""" import glob def xpand(args): # {{{1 """Expand command l...
StarcoderdataPython
6551502
<filename>kapitel-8_Funktionen_Methoden_und_Attribute/main.py wert = max([3,6,3,5,8,6,9,10]) liste = [2,5,7,2,9,8,6,7,2] var = 12 referenz.methode(var, "<NAME>!") print(wert/2) liste.sort() print(liste)
StarcoderdataPython
1967453
<reponame>lhj940825/FDA_Integration_to_INTRA_DA import numpy as np import torch import torch.nn as nn from advent.utils.loss import cross_entropy_2d def bce_loss(y_pred, y_label): y_truth_tensor = torch.FloatTensor(y_pred.size()) y_truth_tensor.fill_(y_label) y_truth_tensor = y_truth_tensor.to(...
StarcoderdataPython
396619
<gh_stars>0 #Need to import our own stuff! import constants from level_manager import * from title_screen import * from music import * import pygame # Initialize Pygame pygame.init() screen = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]) # Used to man...
StarcoderdataPython
6402189
<reponame>mythus/python-designateclient from __future__ import print_function import logging from keystoneauth1.identity import generic from keystoneauth1 import session as keystone_session from designateclient import shell from designateclient.v2 import client logging.basicConfig(level='DEBUG') auth = generic.Pass...
StarcoderdataPython
5064882
from datetimex import getTime from datetimex.error import WrongfulError from datetimex.formatTime import FormatTime from datetimex.formatChinese import FormatChinese from datetimex.legalizationTime import LegalizationTime def getTimeString(strTime): """ 将传入的中文时间字符串转换为包含有的数字字符串 例如:传入值:"三年之后",传出值:“3年之后” 如果其中出现异常,直...
StarcoderdataPython
3305973
import numpy as np import matplotlib.pyplot as plt import torch from torch.utils.data import Dataset import torch.utils.data import os from os import listdir from torchvision import transforms from numpy import clip from skimage import io from skimage.color import rgb2gray from skimage.util import img_as_float, img_as_...
StarcoderdataPython
1996788
import datetime import pytest import pytz from .....product.models import Collection, CollectionChannelListing from ....tests.utils import assert_graphql_error_with_message, get_graphql_content @pytest.fixture def collections_for_sorting_with_channels(channel_USD, channel_PLN): collections = Collection.objects....
StarcoderdataPython
6503965
""" The chemml.chem module includes (please click on links adjacent to function names for more information): - Molecule: :func:`~chemml.chem.Molecule` - XYZ: :func:`~chemml.chem.XYZ` - CoulombMatrix: :func:`~chemml.chem.CoulombMatrix` - BagofBonds: :func:`~chemml.chem.BagofBonds` - RDKitFingerprint:...
StarcoderdataPython
4997189
<reponame>UKGovernmentBEIS/BRE_DigitalRegulationNavigator_Alpha from django import forms from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from crispy_forms.helper import FormHelper User = get_user_model() class RegistrationForm(forms.ModelForm): email = forms.Ema...
StarcoderdataPython
8178673
<gh_stars>0 """ a) State Representation: (matrix, (zero_pos_row, zero_pos_col)) Initial State: (randomized matrix, random position in matrix) (matrix should have the numbers from 0 to rows*cols) Operators: (zero_pos_x >= 0) moveup -> (matrix, (zero_pos_row, zero_pos_col)) => (upt_matrix, (zero_pos_row - 1, zero_pos_co...
StarcoderdataPython
5071328
#!/usr/bin/env python import numpy as np import cv2 import rospy from std_msgs.msg import String from sensor_msgs.msg import Image from sensor_msgs.msg import PointCloud2 from cv_bridge import CvBridge, CvBridgeError class Kinect: def __init__(self): self.bridge = CvBridge() self.image=Image() ...
StarcoderdataPython
9648803
<gh_stars>0 #!/usr/bin/env python import sys #import math from scipy import spatial # Cosine similarity calculation #import average_vector import filter_vocab_words import string_util def getDistanceBetweenSets( arr_words1, arr_words2, model): """ Get distance between two sets of words. (1) ::, ...
StarcoderdataPython
8073534
<filename>sympy/calculus/tests/test_singularities.py from sympy import Symbol, exp, log from sympy.calculus.singularities import (singularities, is_increasing, is_strictly_increasing, is_decreasing, is_strictly_decreasing, is_monotonic)...
StarcoderdataPython
8190025
from genie import parsergen def show_ip_eigrp_neighbors(uut): """ Parsing show ip eigrp neigbors using parsergen sample output EIGRP-IPv4 Neighbors for AS(100) H Address Interface Hold Uptime SRTT RTO Q Seq ...
StarcoderdataPython
247631
class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: missing = [] limit = arr[-1] nums = set(arr) for i in range(1,limit): if i not in nums: missing.append(i) if len(missing) >= k: return missing...
StarcoderdataPython
6557993
"""CUCM AXL Device APIs.""" from .._internal_utils import flatten_signature_kwargs from .base import DeviceAXLAPI from .base import SimpleAXLAPI class CommonDeviceConfig(DeviceAXLAPI): _factory_descriptor = "common_device_config" supported_methods = ["model", "create", "add", "get", "list", "update", "remove...
StarcoderdataPython
5009176
<reponame>TrainingByPackt/Intelligent-Projects-Using-Python-eLearning<filename>Lesson06/rbm.py import numpy as np import pandas as pd import tensorflow as tf import os print(tf.__version__) import fire from elapsedtimer import ElapsedTimer class recommender: def __init__(self,mode,train_file,outdir,test_file=...
StarcoderdataPython
12825516
import json # file_to_read_from = "toy_data/verb_only/constrained_training_data.txt" # file_to_write_to = "toy_data/verb_only/constrained_predicate_list.txt" all_preds = set() with open(file_to_read_from, 'r') as in_file, open(file_to_write_to, "w") as out_file: for sample in in_file: row = json.loads(sam...
StarcoderdataPython
5068384
from checker_functions import * # check where we are running # check the license server exists # check the license server is a license server # check all the paths in the thinclient.xml check_file("./thinclient.xml","thinclient.xml") validate_xml("./thinclient.xml") # check for pit file check_file("./var/opt/Au...
StarcoderdataPython
11233189
import _pickle as pickle import copy import sys import numpy as np import os import timeit import torch import torch.multiprocessing as mp import shutil from collections import namedtuple from functools import partial from pprint import pprint import rl_sandbox.constants as c from rl_sandbox.envs.utils import make_...
StarcoderdataPython
6546781
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2015,掌阅科技 All rights reserved. 摘 要: test_key.py 创 建 者: WangLichao 创建日期: 2015-08-18 """ import sys import os sys.path.append(os.path.dirname(os.path.split(os.path.realpath(__file__))[0])) import unittest from zyredis.key import Key class TestKeyModel...
StarcoderdataPython
8106049
<reponame>bogdancarpusor/flight-price-predictions from sqlalchemy import Column, Integer, String, TIMESTAMP, Numeric from .database import db class Flight(db.Model): __tablename__ = 'flights' id = Column(Integer, primary_key=True) city_from = Column(String(64), index=True) city_to = Column(String(64...
StarcoderdataPython
5089919
<gh_stars>1-10 # Copyright 2010 by <NAME>. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Code to parse BIG GenePop files. The difference between this class and the standar...
StarcoderdataPython
1639729
#!/usr/bin/python -u from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import json, os, sys, hmac, hashlib, subprocess, time def getenv_default(env_name, default_value): if env_name in os.environ and os.environ[env_name]: return os.environ[env_name] else: return default_value clas...
StarcoderdataPython
173102
<reponame>alainivars/utils2devops<filename>utils2devops/aws/security_group.py import boto3 from utils2devops.aws import SecurityGroup, Gress """ Aws configuration iiles should be present: ~/.aws/credentials ~/.aws/config """ def _make_gress(ports): gress = Gress() gress.protocol = ports['IpProtocol'] ...
StarcoderdataPython
8151691
<filename>accessApp/models.py from .entities.VehicleEntity import Vehicle from .entities.AccessEntity import Access
StarcoderdataPython
11233364
from unidef.languages.common.ir_model import * from unidef.utils.typing_ext import * def walk_nodes( node: IrNode, foreach: Callable[[IrNode, List[Any], Dict[str, Any]], bool], *args, **kwargs ): stop_cond = foreach(node, *args, **kwargs) if not stop_cond: for key in node.keys(): ...
StarcoderdataPython
252027
<reponame>doyaguillo1997/Data2Gether from colour import Color from app.external_sources.csv.services.csv_service import get_load_properties from app.external_sources.idealista.services.idealista_service import get_last_info from app.external_sources.idealista.services.idealista_service import get_predictions from app....
StarcoderdataPython
6466256
# automatically generated by the FlatBuffers compiler, do not modify # namespace: apemodefb class EInterpolationModeFb(object): Const = 0 Linear = 1 Cubic = 2
StarcoderdataPython
6450227
<gh_stars>100-1000 #!/usr/bin/env python import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() VERSION = open(os.path.join(here, 'lwp/version')).read() setup( name='lwp', version=VERSION, description=...
StarcoderdataPython
11372712
def add(a, b): return a + b def sub(a, b): return a - b def prod(a, b): return a * b def div(a, b): return a / b def file_add(file_name): f = open(file_name) s = 0 for l in f: s += int(l) f.close() return s def file_prod(file_name): f = open(file_name) s = 1 ...
StarcoderdataPython
3423386
<reponame>jbjjbjjbj/eittek651 # Copyright 2021 <NAME> <<EMAIL>>, <NAME>, <NAME>, <NAME>, <NAME> <<EMAIL>> # # SPDX-License-Identifier: Beerware OR MIT import numpy as np import pandas as pd import ad_path import antenna_diversity as ad ad_path.nop() nr_packets = 2000 snrs_db = np.arange(-5, 25, 1) x_crc_error_ratios...
StarcoderdataPython
144654
<filename>jigls/jeditor/jdantic.py from os import name from typing import Any, Callable, List, Dict, Optional from pydantic import BaseModel, create_model, ValidationError, validator from uuid import UUID from pprint import pprint from pydantic import BaseModel as PydanticBaseModel # from pydantic.types import UUID4 ...
StarcoderdataPython
3454745
from .base import Attr, Context, Load, AST, ACO, Expression, CC from syn.base_utils import quote_string, setitem from syn.type.a import List from syn.five import PY2, STR #------------------------------------------------------------------------------- # Base Class class Literal(Expression): _opts = dict(max_len ...
StarcoderdataPython
6557445
from .source import get_source, source_info, read_sources as sources
StarcoderdataPython
3487847
<gh_stars>1-10 # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # # ---------------------------------------------------------------------------- # # spack install py-tpot # # You can e...
StarcoderdataPython
190906
def multiply(a,b): return a*b def divide(a,b): return a/b
StarcoderdataPython
5134831
import asyncio _EVENTS = {} def get(name): if name not in _EVENTS: _EVENTS[name] = asyncio.Event() return _EVENTS[name] def clear(): _EVENTS.clear()
StarcoderdataPython
3370596
<filename>neurofire/inference/blending.py import numpy as np # Blending similar to what is done in # 'Superhuman accuracy on SNEMI' # However, the function in there probably contains a # typo and doesn't make sense # -> for now we use a linear ramp # TODO more blending modes ?! # -> this would be the sub-class `Line...
StarcoderdataPython
1927536
<filename>task3/merge_sort.py """ Merge Sort Contains two procedure: 1. half hte sequence until each sequence only has 1 element, which means each sequence has already been sorted; 2. merge those sequences, keep there original order. """ def merge(left, right): """Merge two sorte...
StarcoderdataPython
3468920
<filename>examples/demo.py from opencage.geocoder import OpenCageGeocode key = 'your-key-here' geocoder = OpenCageGeocode(key) query = '182 Clerkenwell Road, London' ret = geocoder.geocode(query) print(ret._content)
StarcoderdataPython
1991351
import gym env = gym.make('CartPole-v0') for i_episode in range(20): # one episode is everytime cartpole falls observation = env.reset() for timestep in range(1000): env.render() # render for every timestep print(observation) # prints array of velocities on where cartpole is action = env.action_space.samp...
StarcoderdataPython
1762975
<reponame>juaoantonio/curso_video_python n = int(input('Digite um número inteiro para saber seu antecessor e sucessor: ')) print(f'O antecessor de {n} é {n-1} e seu sucessor é {n+1}')
StarcoderdataPython
4900214
<reponame>whart222/cctbx_project<filename>xfel/merging/command_line/dev_cxi_mpi_merge_refltable.py from __future__ import absolute_import, division, print_function # -*- mode: python; coding: utf-8; indent-tabs-mode: nil; python-indent: 2 -*- # # LIBTBX_SET_DISPATCHER_NAME dev.cxi.mpi_merge_refltable # # $Id$ from xfe...
StarcoderdataPython
6685353
<filename>__scraping__/cnbc.com - requests/main.py # # https://stackoverflow.com/a/47744797/1832058 # from bs4 import BeautifulSoup import requests html = requests.get("https://www.cnbc.com/2017/12/07/pinterest-hires-former-facebook-exec-gary-johnson-to-run-corporate-dev.html").text soup = BeautifulSoup(html, 'html5...
StarcoderdataPython
11257745
<filename>iwant/__init__.py<gh_stars>100-1000 __version__ = '1.0.14' # version number
StarcoderdataPython
6675126
<reponame>Programming-The-Next-Step-2021/RecipesProject import unittest from Recipe_Finder import find_recipes, recipe_link class TestRecipeFinder(unittest.TestCase): def test_find_recipes(self): recipes = find_recipes('eggs,bacon,cheese') self.assertIsNotNone(recipes,'no recipes') def test_re...
StarcoderdataPython
11353361
<gh_stars>1-10 from libsim.models import ( SimulationStep ) from libsim.features import ( PausedBy, ) from libsim.util import ( latest_sample, ) from tests.helpers import ( create_flip_flop_model ) def never(*args): return False def id(x): return x model = create_flip_flop_model(start=0, f...
StarcoderdataPython
4858455
<reponame>rupenp/lin-train __author__ = '<NAME>' """ A multiprocessor version of the trainer that distributes potential feature sets to processes. Each process then performs the linear regression across the k-folds. Note that this can be very memory intensive as each process must have a copy of the data. """ from tra...
StarcoderdataPython
6567694
<gh_stars>1-10 from argparse import ArgumentParser from os.path import join from .constants import (CFG_TEMP_FILE, MD_TEMP_DIR, MD_CURRENT_FILES, FMT, LATEX_FORMATS, LATEX, EPUB, HTML, OUTPUT_FILE) from .utils import yaml_load, yaml_dump class FlightScript: def __init__(self, func, flight_...
StarcoderdataPython
9730690
<reponame>diberry/AzureStorageSnippets<filename>blobs/quickstarts/python/V12/app_framework.py import os, uuid from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__ try: print("Azure Blob Storage v" + __version__ + " - Python quickstart sample") # Quick start code goes here...
StarcoderdataPython
1695580
#!/usr/bin/env python3 import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State import dash_table import plotly.graph_objs as go import pandas as pd import numpy as np import os import math from scipy.stats import mannwhitneyu, ttest_ind from ...
StarcoderdataPython
1699690
<filename>webapp/utils/request_params.py def param2type(request, method, param, data_type, defval=None): """ get http request paramter Args: request: HttpRequest instance method: string of HTTP method param: string of parameter data_type: type of parameter defval: defaul...
StarcoderdataPython
6421381
<filename>test/test_ami_line_tool.py import unittest import context from pyamiimage.ami_plot import POLYGON, POLYLINE, AmiLine, AmiLineTool, X, Y class TestAmiLineTool: """test AmilineTool""" def test_empty_polyline(self): line_tool = AmiLineTool() assert line_tool.line_points_list == [] ...
StarcoderdataPython
6445049
# Copyright (c) 2020, Xilinx # 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 code must retain the above copyright notice, this # list of conditions and the follow...
StarcoderdataPython
36726
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2019 Lorenzo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, ...
StarcoderdataPython
9681057
<reponame>63Shivani/Python-BootCamp age1 = int(input("enter age\n")) age2 = int(input("enter age\n")) age3 = int(input("enter age\n")) age4 = int(input("enter age\n")) if(age1>age2 and age1>age3 and age1>age4): print(age1,"year old is oldest") elif(age2>age1 and age2>age3 and age2>age4): print(age2,"year old is...
StarcoderdataPython
157415
#!/usr/bin/python3 import re import nltk from nltk import pos_tag,word_tokenize,sent_tokenize from textblob import TextBlob import pandas as pd def remove_punc(sentence): return re.sub(r'[^\w\s]',' ',sentence).lower() def get_sentiment(sentence): a = TextBlob(sentence) return round(a.sentiment[0],4) def get_di...
StarcoderdataPython
212256
<filename>secedgar/utils/__init__.py import datetime import errno import os def sanitize_date(date): """Sanitizes date to be in acceptable format for EDGAR. Args: date (Union[datetime.datetime, str]): Date to be sanitized for request. Returns: date (str): Properly formatted date in 'YYYY...
StarcoderdataPython
3499840
""" The Application's Entry Point""" import os from code import create_app app = create_app() if __name__ == '__main__': app.run(debug=True)
StarcoderdataPython
3328717
<filename>face_tracking.py<gh_stars>1-10 # coding: utf-8 import picamera import picamera.array import cv2 import pigpio import time xsv = 25 #X軸サーボのPort番号 ysv = 24 #y軸サーボのPort番号 span = 300 #サーボのセンターからの可動範囲duty値 xct = 1550 #X軸サーボのセンターduty値 yct = 1490 #X軸サーボのセンターduty値 dly = 0.01 #サーボ駆動時のウェイト時間 stp = 2 #サーボ駆動時のdutyステ...
StarcoderdataPython
5122799
""" Class for managing our data. """ import csv import numpy as np import os.path import random import threading from keras.utils import to_categorical from keras.preprocessing.image import ImageDataGenerator import cv2 class DataSet(): def __init__(self, class_limit=None, image_shape=(224, 224), original_image_sh...
StarcoderdataPython
3426256
import pandas as pd import numpy as np import copy as cp import sys import pickle import hashlib as hs import base64 as b64 import os import random as rd import datetime as dt import threading import time from difflib import SequenceMatcher from darc_core.metrics import Metrics from darc_core.preprocessing import roun...
StarcoderdataPython
238098
#!/usr/bin/env python import argparse import logging import sys from autoscale import MesosReporter, MesosDecider, AwsAsgScaler def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--log-level', default="warn", help='Log level (debug, [default] info, warn, error)') parser.add_argumen...
StarcoderdataPython
3328235
a=[11,6,4,5,9,2,7,0,1,-1,-9] n=len(a) for i in range(1,n): temp=a[i] j=i-1 while j>=0: if temp>=a[j]: break a[j+1]=a[j] j-=1 a[j+1]=temp print(a)
StarcoderdataPython
4851594
from starling_sim.basemodel.trace.events import * from starling_sim.basemodel.agent.requests import UserStop, StopPoint, StationRequest from starling_sim.utils.constants import PUBLIC_TRANSPORT_TYPE class KPI: """ Generic structure of a KPI class Its sub-classes compute and update specific indicator ...
StarcoderdataPython
108488
<gh_stars>0 # -*- coding: utf-8 -*- ''' * @Author : jiangtao * @Date : 2021-12-13 14:18:45 * @Email : <EMAIL> * @LastEditTime : 2022-03-02 14:11:31 * @Description : ''' import argparse import cv2 import json import os import os.path as osp import sys import time import warnings from argparse impo...
StarcoderdataPython
1692837
from .AutomatonGenerators import generate_random_dfa, generate_random_mealy_machine, generate_random_moore_machine, generate_random_markov_chain from .AutomatonGenerators import generate_random_mdp, generate_random_ONFSM from .FileHandler import save_automaton_to_file, load_automaton_from_file, visualize_automaton from...
StarcoderdataPython
1752993
<reponame>juanelenter/basepairmodels """ This module containins training functions that are common to the CLI & the API Functions: train_and_validate: Train and validate on a single train and validation set train_and_validate_ksplits: Train and validate on one ...
StarcoderdataPython
6543218
<filename>infoset/api/__init__.py<gh_stars>0 """Initialize the API module.""" # Import PIP3 libraries from flask import Flask from flask_caching import Cache ############################################################################# # Import configuration. # This has to be done before all other infoset imports. ##...
StarcoderdataPython
6426918
<reponame>qychen13/ClusterAlignReID<filename>utils/evaluation.py<gh_stars>10-100 import time from tqdm import tqdm from collections import defaultdict import torch import torch.nn as nn import torch.nn.functional as functional import scipy.io import numpy as np from .distance import compute_distance_matrix from .rank ...
StarcoderdataPython
1996043
import json import sys import payabbhi import responses import unittest2 from .helpers import (assert_invoice, assert_list_of_invoice_items, assert_list_of_invoices, assert_list_of_payments, mock_file) class TestInvoice(unittest2.TestCase): def setUp(self): s...
StarcoderdataPython
6609046
<reponame>yhat/digit-recognizer import numpy as np import pandas as pd from PIL import Image from StringIO import StringIO import base64 import os from sklearn.decomposition import RandomizedPCA from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifi...
StarcoderdataPython
6562426
import scipy,pickle,numpy import numpy as np try: import matplotlib.pyplot as plt except: import pylab as plt import special_functions as sf from scipy import ndimage STANDARD = None class IDSpectrum: """ IDSpectrum class for identification of spectral lines starting with an initia...
StarcoderdataPython
11296788
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- ######################## -*- coding: utf-8 -*- # simple script to generate p-coordinate specific input from standard experiment import numpy as np import matplotlib.pyplot as plt import sys, os # requires that the path contains utils/python/MITgcmutils or that the u...
StarcoderdataPython
1686666
from rest_framework.permissions import BasePermission class SubjectPermission(BasePermission): def has_permission(self, request, view): if view.action == 'list': return request.user.is_authenticated() else: return False
StarcoderdataPython