id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3338560
from .main import get_y_pred_true from .logging import save_train_val_figures
StarcoderdataPython
6654374
<filename>tracking/combined/webcam.py from __future__ import absolute_import, division, print_function import os import sys import glob import argparse import numpy as np import PIL.Image as pil import matplotlib as mpl import matplotlib.cm as cm import cv2 from torchvision import transforms, datasets import network...
StarcoderdataPython
349732
<gh_stars>0 import pyttsx from gtts import gTTS import vlc import time import wave import contextlib class Mic: def __init__(self): self.engine = pyttsx.init() def say(self, text_to_say): self.engine(text_to_say) self.engine.runAndWait() def stop(self): self.engine.stop() ...
StarcoderdataPython
5173397
n1 = float(input('Digite sua primeira nota: ')) n2 = float(input('Digite sua segunda nota: ')) m = (n1+n2)/2 if(m<3): print('Você foi reprovado') elif(m>3 or m<7): print('Você vai para final') else: print('Você passou. Parabéns!!!')
StarcoderdataPython
12835211
<reponame>atigerboy/PythonCookBook<gh_stars>0 ''' weakref weakref.WeakValueDictionary ''' import logging a = logging.getLogger('foo') b = logging.getLogger('bar') print( a is b ) c = logging.getLogger('foo') print( a is c ) #True.same name logger is same instance # The class in question class Spam: def __init__(s...
StarcoderdataPython
6643230
<reponame>kraupn3r/intranet from django.contrib import admin from django.urls import path, include from rest_framework_jwt.views import refresh_jwt_token, obtain_jwt_token from .views import * urlpatterns = [ path('', BoardCategoryListAPIView.as_view()), path('postlist/', PostListAPIView.as_view()), path('...
StarcoderdataPython
3516255
<gh_stars>1-10 from .dataset import XrayDataset from .model import XrayModel
StarcoderdataPython
1956685
import sys from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from tqdm.auto import tqdm from sacrebleu.metrics import BLEU from anlp_project.datasets.europarl import EuroParlRaw if len(sys.argv) != 2: print(f"Usage: {sys.argv[0]} CHECKPOINT_PATH") sys.exit(1) checkpoint_name = sys.argv[1] if "e...
StarcoderdataPython
3241106
#!/usr/bin/env python """Client actions dealing with memory.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import collections import io import os import re import shutil from future.builtins import str import psutil from typing import Iterable fro...
StarcoderdataPython
5161343
<gh_stars>1-10 # The following license applies to Flask # Some of the code on this file have been based off of Flask's documentation. # Copyright 2010 Pallets # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # Redistribution...
StarcoderdataPython
11217346
<reponame>flucto-gmbh/msb_attitude<filename>src/issue_complementary.py import numpy as np from os import path import sys # add ahrs directory to PYTHONPATH SCRIPT_DIR = path.dirname(path.abspath(__file__)) sys.path.append(path.dirname(SCRIPT_DIR)) try: from ahrs.ahrs.filters import Complementary except ImportErr...
StarcoderdataPython
3269232
from .adt import ADT from .adt import memo as ADTmemo from .prelude import * from . import atl_types as T from .frontend import AST from fractions import Fraction from math import gcd as _gcd def _lcm(x,y): return (x*y)//_gcd(x,y) # notes on symbols to use # Note that BOOL is a type and Bool a formula constructo...
StarcoderdataPython
1647621
#!/usr/bin/env python # Part of sniffMyPackets framework. # Generic pcap tools and utilities that SmP uses import os import magic import datetime import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import rdpcap, conf def packet_count(pcap): conf.verb = 0 try: pk...
StarcoderdataPython
4966299
<filename>Pyro/ext/remote.py ############################################################################# # # simple Pyro connection module, originally written by <NAME> # # This is part of "Pyro" - Python Remote Objects # which is (c) <NAME> - <EMAIL> # ####################################################...
StarcoderdataPython
5063663
#!/usr/bin/env python """ Copyright (c) 2015-2017 <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, merge, ...
StarcoderdataPython
1980222
<reponame>SamuelMarks/tensorboard-plugin-example<filename>greeter_plugin/greeter_plugin.py # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # ...
StarcoderdataPython
250300
# coding=utf-8 """ Created on Monday 28 March 00:53:34 2020 @author: nkalyan🤠 '''implementing Python scripts to print student and instructor tables''' """ from typing import Dict, Iterator, Tuple, KeysView from prettytable import PrettyTable from collections import defaultdict from HW08_nikhil_kalyan import ...
StarcoderdataPython
1879306
<reponame>johnnykoo84/DS-Unit-3-Sprint-2-SQL-and-Databases import os import psycopg2 from dotenv import load_dotenv load_dotenv() # Connect to ElephantSQL-hosted PostgreSQL conn = psycopg2.connect( dbname=os.getenv("dbname"), user=os.getenv("user"), password=os.getenv("password"), host=os.getenv("host"...
StarcoderdataPython
388023
import enum from collections import OrderedDict from copy import deepcopy import gym import numpy as np from gym.spaces import Box, Dict def update_obs_space(env, delta): spaces = env.observation_space.spaces.copy() for key, shape in delta.items(): spaces[key] = Box(-np.inf, np.inf, (np.prod(shape),)...
StarcoderdataPython
9731993
<reponame>maxisoft/BravePatcher<filename>tests/test_cli_integration.py<gh_stars>1-10 import os import sys import shlex import subprocess from pathlib import Path from typing import Tuple import pefile import pytest import psutil def _get_command() -> str: return os.environ.get("CLI_COMMAND", "{} -m bravepatcher"....
StarcoderdataPython
6573196
<filename>matrix/determinant_of_nxn_matrix.py """To find determinant of NxN Matrix i have used Row Reduction method you can see wikipedia of this Method https://en.wikipedia.org/wiki/Row_echelon_form""" from __future__ import annotations from copy import deepcopy def determinant_of_nxn_matrix(matrix: list[l...
StarcoderdataPython
382747
from . import site content = 'Another Bad Module' site._registry.update({ 'foo': 'bar', }) raise Exception('Some random exception.')
StarcoderdataPython
1676628
from __future__ import annotations import multiprocessing import os import random import re from typing import Any from typing import overload from typing import Sequence from typing import TYPE_CHECKING import before_commit.constants as C from before_commit import parse_shebang from before_commit.hook import Hook fr...
StarcoderdataPython
1945132
<filename>channels/management/commands/update_managed_channel_memberships.py """Update managed channel memberships""" from django.core.management.base import BaseCommand from channels import tasks from open_discussions.utils import now_in_utc class Command(BaseCommand): """Update managed channel memberships""" ...
StarcoderdataPython
6506983
<reponame>chuckbutler/redmine-layer from charms.docker import Docker from charms.docker.compose import Compose from charms.reactive import set_state from charms.reactive import when from charms.reactive import when_not from charmhelpers.core.hookenv import config from charmhelpers.core.hookenv import open_port from c...
StarcoderdataPython
249132
<reponame>npwebste/UPS_Controller # Universal Power Supply Controller # USAID Middle East Water Security Initiative # # Developed by: <NAME> # Primary Investigator: <NAME> # # Version History (mm_dd_yyyy) # 1.00 03_24_2018_NW # ###################################################### import VFD_Modbus_Wrapper import VFD_...
StarcoderdataPython
1624732
import os from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F from torch import optim from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler from torchvision.datasets import MNIST from torchvision import transforms from tes...
StarcoderdataPython
6416182
<filename>Lib/lib-tk/test/test_tkinter/test_misc.py<gh_stars>1000+ import unittest import Tkinter as tkinter from test.test_support import requires, run_unittest from test_ttk.support import AbstractTkTest requires('gui') class MiscTest(AbstractTkTest, unittest.TestCase): def test_after(self): root = sel...
StarcoderdataPython
1989029
from feature_extraction import features from classifier_list import classifier import argparse import os parser = argparse.ArgumentParser(description = 'Training model with Traditional Features') # Paths parser.add_argument('-tr','--tr_path',type=str, default = 'data/train/images/', ...
StarcoderdataPython
1640145
from typing import Union, Optional, Any, Dict import numpy as np from l5kit.geometry import transform_points import torch __all__ = [ 'traj_stat', 'classify_traj', 'comp_val', 'filter_traj' ] def trajectory_stat( history_positions: np.array, target_positions: np.array, centroid: np.array,...
StarcoderdataPython
95615
<reponame>Adrien4193/drone_control<filename>src/drone_control/common/__init__.py from common import Pose, Attitude, Callback, Timer
StarcoderdataPython
4922113
import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) host='127.0.0.1' port=12345 s.bind((host,port)) s.listen() while True: ts,addr=s.accept() ts.send(b'Hello') print(ts.recv(1024)) ts.close()
StarcoderdataPython
3536004
<gh_stars>0 ## A module to read data from a DSS, this specifically implements the Remote ID standard as released on Oct-2020 ## For more information review: https://redocly.github.io/redoc/?url=https://raw.githubusercontent.com/uastech/standards/astm_rid_1.0/remoteid/canonical.yaml ## and this diagram https://github...
StarcoderdataPython
1926717
<gh_stars>0 import os import random import string import tempfile import unittest from grail import Grail def gen_random_string(N=10): return ''.join(random.choices(string.ascii_uppercase + string.digits, k=N)) class TestGrail(unittest.TestCase): def test_grail_2(self): # Получаем случайное имя дл...
StarcoderdataPython
8020475
<reponame>bendichter/brainrender """ This tutorial shows how to automatically take screenshots of your rendered region """ import time import brainrender brainrender.SHADER_STYLE = "cartoon" from brainrender.scene import Scene screenshot_params = dict(folder="./screenshots", name="tutorial",) # Create a scene...
StarcoderdataPython
3359767
import os import logging from functools import wraps MOD = "modification" PWD = os.getcwd() modification_logger = logging.getLogger(MOD) modification_logger.addHandler( logging.NullHandler() ) # TODO: think whether it should be nullhandler by default modification_logger.setLevel(logging.DEBUG) formatter = loggi...
StarcoderdataPython
5194610
from iocbuilder import Device, AutoSubstitution, Architecture, SetSimulation from iocbuilder.arginfo import * from iocbuilder.modules.asyn import Asyn, AsynPort, AsynIP from iocbuilder.modules.areaDetector import AreaDetector, _NDPluginBase, _ADBase, _ADBaseTemplate, simDetector class _SpecsAnalyser(AutoSubstitution)...
StarcoderdataPython
5164016
<filename>acestream/ACEStream/Core/BitTornado/BT1/Rerequester.py #Embedded file name: ACEStream\Core\BitTornado\BT1\Rerequester.pyo import sys import socket import random import struct import binascii import urlparse from ACEStream.Core.BitTornado.zurllib import urlopen from urllib import quote from btformats import ch...
StarcoderdataPython
1832165
from django import template register = template.Library() from re import compile, UNICODE #RUBY_TEXT_MARKUP_TEMPLATE = u'<ruby><rb>{expression}</rb><rp>(</rp><rt>{reading}</rt><rp>)</rp></ruby>' RUBY_TEXT_MARKUP_TEMPLATE = '<span class="ezRuby" title="{reading}">{expression}</span>' #_LEFT_CARET = u'\&lt;' #_RIGH...
StarcoderdataPython
5124918
<gh_stars>0 # -*- coding: utf-8 -*- import datetime, logging, os, pprint, random import requests from illiad_app import settings_app log = logging.getLogger(__name__) class CloudCreateUserHandler( object ): """ Creates new user via official illiad cloud api. """ def __init__( self ): self.request_...
StarcoderdataPython
1966913
""" Serializers for users app """ from django.contrib.auth.models import User from rest_framework import serializers from small_small_hr.models import StaffProfile # pylint: disable=too-many-ancestors class UserSerializer(serializers.ModelSerializer): """ UserSerializer class """ class Meta: # pyl...
StarcoderdataPython
5140217
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from contents.dice.DiceCommandProcessor import DiceCommandProcessor, InvalidFormulaException, CalculatorBase class CallOfCthulhuDice(DiceCommandProcessor): def __init__(self): super().__init__() def percent(self, command): self.comment_se...
StarcoderdataPython
9784726
from data.data_pipe import de_preprocess, get_train_loader, get_val_data from model import Backbone, Arcface, MobileFaceNet, Am_softmax, l2_norm from verifacation import evaluate import torch from torch import optim import numpy as np from tqdm import tqdm from tensorboardX import SummaryWriter from matplotlib import p...
StarcoderdataPython
6498522
<reponame>laundmo/lona-bootstrap-5 from lona_bootstrap_5 import ( ColMd6, Col, Row, TextInput, TextArea, PrimaryButton, SecondaryButton, SuccessButton, WarningButton, DangerButton, InfoButton, LightButton, DarkButton, LinkButton, Progress, Modal, Prima...
StarcoderdataPython
3371176
""" File name: main.py Author: <NAME>, <NAME> Date last modified: 21 March, 2021 Python Version: 3.8 This script contains the main function that calls Inference.py to solve and show solutions a specific inference query. It parses command line arguments that specify which query to do. """ i...
StarcoderdataPython
6424404
<reponame>crowdbotics-apps/ideapros-llc-viaggi-32125<gh_stars>0 from django.core.mail import EmailMessage from rest_framework.authtoken.models import Token from ideapros_llc_viaggi_32125.settings import FCM_SERVER_KEY, PLACES_API_KEY from notifications.models import Notification import pyotp import requests from requ...
StarcoderdataPython
1770364
from scipy import signal from PIL import Image import cv2 import numpy import math import imageio # Locating the image. If the image is not same then change to relative address. usedImage = '../../Images/test.jpg' # Opening the image into an array img = numpy.array(Image.open(usedImage).convert("L")) imageio.imwrite(...
StarcoderdataPython
5002024
import sys while sys.stdin.readline() != '': print sys.stdin.readline()
StarcoderdataPython
9706605
<reponame>shoriwe-upb/blackjack<filename>dependencies/game.py from .player import Player from .deck import Deck from .dealerai import DealerAI class Game(object): def __init__(self, number_of_players): self.__number_of_players = number_of_players self.__players = self.__create_players(number_of_pl...
StarcoderdataPython
3255838
<reponame>peterkulik/ois_api_client from typing import List from dataclasses import dataclass @dataclass class OrderNumbers: """Order numbers :param order_number: Order number """ order_number: List[str]
StarcoderdataPython
1851713
import fnmatch import os import h5py import numpy as np from basic_utils import profile from depth_utils import colorized_surfnorm @profile def process_depth_save(params): suffix = '*_' + params.data_type + '.png' data_path = os.path.join(params.dataset_path, 'eval-set/') results_dir = params.dataset_pa...
StarcoderdataPython
12820057
from django.contrib import admin from .models import Project, Cv, Technique, Info # Register your models here. admin.site.register(Project) admin.site.register(Cv) admin.site.register(Technique) admin.site.register(Info)
StarcoderdataPython
3568453
"""Tests for avro2py/rendering.py""" import io import sys import json from datetime import datetime from decimal import Decimal from pathlib import Path import importlib.util as imp from typing import Optional import avro from hypothesis import strategies as st, given, assume, note, settings, HealthCheck from avro2py...
StarcoderdataPython
6664536
<gh_stars>1-10 input_file = open('input.txt', 'r') input_list = input_file.read().split('\n') def most_common(lst): return str(max(set(lst), key=lst.count)) matrix = [[]for _ in range(12)] for row in input_list: for index, column in enumerate(row): matrix[index].append(int(column)) bit_string = "" b...
StarcoderdataPython
8109402
import node def rec(my_ip): while True: message,address = node.receive(my_ip) print(message) print(address) with open("recent_messages.txt", "a") as file: if " ".join(message) != " " or " ".join(message) != "": file.write("\n" + address[0] + " " + " "....
StarcoderdataPython
6591247
# graph definition from datetime import datetime from hiku.graph import Graph, Root, Field GRAPH = Graph([ Root([ Field('now', None, lambda _: [datetime.now().isoformat()]), ]), ]) # test from hiku.engine import Engine from hiku.result import denormalize from hiku.executors.sync import SyncExecutor...
StarcoderdataPython
9659477
<reponame>cadomani/fprime<filename>Autocoders/Python/src/fprime_ac/utils/ConfigManager.py<gh_stars>0 # # =============================================================================== # NAME: ConfigManager.py # # DESCRIPTION: This is a simple configuration class patterned after the # one in the Keck observation ...
StarcoderdataPython
6557926
#!/usr/bin/python import os import sys import glob import base64 import subprocess import xmlrpclib import time import getopt def main(argv): iDBUser = '' oDBName = '' BacKDir = '' #init variable date_backup = time.strftime('%Y%m%d_%H%M%S') #Logging command = "#Start:O...
StarcoderdataPython
11239794
<gh_stars>0 #-*- coding: utf-8 -*- from .geocodeSlc import geocodeSlc
StarcoderdataPython
4809965
<gh_stars>1-10 from . import utils class Dim(object): """Stores a list of configurations used during the experiment. For example, lets say that we want to compare variants of GP with different probability of mutation and also at the same time with different tournament sizes. The first dimension would...
StarcoderdataPython
1688637
<gh_stars>0 import sys print('Enter an integer:') num = int(input()) sum = 0 if num < 1: print(0) else : for i in range(1,num+1) : sum = sum + i print(sum) sys.exit()
StarcoderdataPython
3365846
<filename>viscid/plot/vlab.py """Convevience module for making 3d plots with Mayavi Note: You can't set rc parameters for this module! """ from __future__ import print_function, division import os import sys import numpy as np import mayavi from mayavi import mlab from mayavi.modules.axes import Axes from mayavi....
StarcoderdataPython
11286640
<reponame>surya501/usdc-system-integration from styx_msgs.msg import TrafficLight import tensorflow as tf import numpy as np import rospy import datetime CONFIDENCE_CUTOFF = 0.5 class TLClassifier(object): def __init__(self, model=None): #TODO load classifier self.GRAPH_FILE = model ...
StarcoderdataPython
3208471
import geopandas as gpd import oggm from oggm import cfg, tasks from oggm.utils import get_demo_file # Set up the input data for this example cfg.initialize() cfg.PATHS['working_dir'] = oggm.utils.get_temp_dir('oggmcontrib_inv') cfg.PATHS['dem_file'] = get_demo_file('srtm_oetztal.tif') cfg.set_intersects_db(get_demo_f...
StarcoderdataPython
5008213
#!/usr/bin/env python3 from bisect import bisect_left import math class SummaryRanges: def __init__(self): self.I = [[-math.inf, -math.inf], [math.inf, math.inf]] def addNum(self, val): ix = bisect_left(self.I, [val, val]) print(f'val = {val}, ix = {ix}') if self.I[ix-1][1]+1 ...
StarcoderdataPython
5013816
import jwt from datetime import datetime, timedelta from hashlib import md5 from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from helloworld import app, db from helloworld import login @login.user_loader def load_user(id): return User.query.get(int(id...
StarcoderdataPython
251279
<filename>pythonspain/partners/migrations/0007_notice_kind.py # Generated by Django 3.1.7 on 2021-02-28 13:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("partners", "0006_auto_20200627_1526"), ] operations = [ migrations.AddField( ...
StarcoderdataPython
3473831
import boto3 client = boto3.client('s3') Buckets = client.list_buckets() for bucket in Buckets: response = client.put_bucket_encryption(Bucket= bucket, ContentMD5='ndah2', ServerSideEncryptionConfiguration={'Rules': [{'ApplyServerSideEncryptionByDefault': {'SSEAlgorithm': 'AES256'}},]})
StarcoderdataPython
3272543
<filename>src/electionguard_cli/e2e/e2e_command.py from io import TextIOWrapper import click from ..cli_steps import ( ElectionBuilderStep, DecryptStep, PrintResultsStep, TallyStep, KeyCeremonyStep, EncryptVotesStep, ) from .e2e_input_retrieval_step import E2eInputRetrievalStep from .submit_vo...
StarcoderdataPython
244785
<filename>Terrain.py import pygame.sprite class Terrain(pygame.sprite.Sprite): all = pygame.sprite.Group() def __init__(self, x, y, width, height): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill((0, 0, 0)) self.rect = self.image.get_rect(x=x, y=y) self.all....
StarcoderdataPython
142804
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 4 17:44:53 2021 @author: mlampert """ import os import copy #FLAP imports and settings import flap import flap_nstx import flap_mdsplus flap_nstx.register('NSTX_GPI') flap_nstx.register('NSTX_THOMSON') flap_mdsplus.register('NSTX_MDSPlus') thi...
StarcoderdataPython
1689698
#!/usr/bin/env python3 # This file is part of the MicroPython project, http://micropython.org/ # The MIT License (MIT) # Copyright (c) 2019 <NAME> import os import subprocess import sys import argparse sys.path.append('../tools') import pyboard # Paths for host executables CPYTHON3 = os.getenv('MICROPY_CPYTHON3', '...
StarcoderdataPython
11329185
<reponame>JaredAllen13/insightconnect-plugins # GENERATED BY KOMAND SDK - DO NOT EDIT import insightconnect_plugin_runtime import json class Component: DESCRIPTION = "Receive events based on criteria" class Input: EVENT_ID = "event_id" class Output: ERRORS = "errors" EVENT = "event" MESSAG...
StarcoderdataPython
6442439
<filename>TranskribusDU/crf/Model_SSVM_AD3_Multitype.py # -*- coding: utf-8 -*- """ Train, test, predict steps for a CRF model - CRF model is EdgeFeatureGraphCRF (unary and pairwise potentials) - Train using SSM - Predict using AD3 Copyright Xerox(C) 2016 <NAME> Developed for the...
StarcoderdataPython
207635
<filename>NATOTranslate.py # <NAME> # NATO Phonetic/Morse Code Translator # 7/29/2020 MORSE_CODE_DICT = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-...
StarcoderdataPython
11355467
<reponame>Asifadam93/FiltreMusical<gh_stars>0 #!/usr/bin/env python import dspplot data = [ 0.015625, 0.046875, 0.078125, 0.109375, 0.140625, 0.171875, 0.203125, 0.234375, 0.265625, 0.296875, ...
StarcoderdataPython
26768
<filename>data-pipeline/src/data_pipeline/datasets/exac/exac_regional_missense_constraint.py import hail as hl def prepare_exac_regional_missense_constraint(path): ds = hl.import_table( path, missing="", types={ "transcript": hl.tstr, "gene": hl.tstr, "c...
StarcoderdataPython
1679355
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. import locale import os.path import random import re from os import stat as os_stat, lstat as os_lstat from collections import deque from time import time from ranger.container.fsobject import B...
StarcoderdataPython
3475212
<reponame>AaronFriel/pulumi-azuread # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequ...
StarcoderdataPython
390256
<filename>python/cinn/optim.py<gh_stars>1-10 from .core_api.optim import simplify from .core_api.optim import ir_copy
StarcoderdataPython
8001002
<reponame>shkarupa-alex/nlpclean import gc import os import resource import unittest from ..html import html_to_article, fragment_to_text class TestHtmlToArticle(unittest.TestCase): def test_comment(self): with open(os.path.join(os.path.dirname(__file__), 'html_to_article', 'comment_no_space.html'), 'rt')...
StarcoderdataPython
1846918
import time from threading import Thread from queue import Queue class RateLimiter: def __init__(self, limit, delay=0.01): num = int(limit * delay) if num < 1: raise ValueError("limit * delay < 1") self._limit_num = limit self._delay = delay self._num_per_dela...
StarcoderdataPython
375596
<reponame>mumupy/mmdeeplearning<filename>src/mtensorflow/tf_rbm.py #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/26 12:45 # @Author : ganliang # @File : tf_rbm.py # @Desc : 受限玻尔兹曼机(RBM)是一个两层神经网络,第一层被称为可见层,第二层被称为隐藏层,因为网络只有两层,所以又被称为浅层神经网络。 # RBM 可以用于降维、特征提取和协同过滤,RBM 的训练可以分成三部分:正向传播、反向传播和比较。下面看...
StarcoderdataPython
9606432
from math import ceil, sqrt plaintext = input().strip() length = len(plaintext) rows = int(sqrt(length)) cols = int(ceil(sqrt(length))) if cols * rows < length: rows += 1 encrypted = '' for c in range(cols): for r in range(rows): if c + cols * r < length: encrypted += plaintext[c + cols * ...
StarcoderdataPython
1609324
<reponame>test-wiz-sec/pulumi-azure-nextgen # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Un...
StarcoderdataPython
9767268
from typing import List, Tuple import clue import clue.rules from clue import turn_log class ClueRepl: """ This will grab input from the user and then update the log and scoresheet. > dave knif plum di olivia=no input: "dave knif plum di olivia=no" tokens: {player: "dave"}, {card: knife}, {car...
StarcoderdataPython
11274422
<filename>CHRLINE/e2ee.py """ Author: YinMo Version: 0.0.1-beta Description: died """ import hashlib, json, os import axolotl_curve25519 as Curve25519 from cryptography.hazmat.primitives.ciphers.aead import AESGCM from Crypto.Cipher import AES class E2EE(): def generateSharedSecret(self, private_key, public_key):...
StarcoderdataPython
69610
<reponame>lifning/picotool """The map section of a PICO-8 cart. The map region consists of 4096 bytes. The .p8 representation is 32 lines of 256 hexadecimal digits (128 bytes). The map is 128 tiles wide by 64 tiles high. Each tile is one of the 256 tiles from the spritesheet. Map memory describes the top 32 rows (128...
StarcoderdataPython
12823985
import unittest from click.testing import CliRunner import yoda class PortScanTest(unittest.TestCase): """ Test for the following commands: | Module: dev | command: portscan """ def __init__(self, methodName="runTest"): super(PortScanTest, self).__init__() ...
StarcoderdataPython
6596216
<reponame>chiragkhandhar/ODAS from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UserProfile from doctor_login.models import docDetails class RegistrationForm(UserCreationForm): email=forms.EmailFie...
StarcoderdataPython
3522371
<gh_stars>0 #!/usr/bin/env python import sys import os class Menu(object): '''Create and maintain a simple menu for PopQ''' program_name = 'PopQ' def __init__(self): self.choices = {'1': self.add_questions, '2': self.start_questionnaire, 'x': self.exit_program} def add_choices(self): ...
StarcoderdataPython
6697833
from functools import reduce import pandas as pd import warnings warnings.simplefilter(action='ignore', category=FutureWarning) def mergeAllTime(dfs:list[pd.DataFrame]): ''' Layer 1 - not useful? combines multiple mutlicolumned dataframes. to support disparate frequencies, outter join fills in missing...
StarcoderdataPython
9643871
<reponame>seongcheoljeon/HoudiniRunRender<gh_stars>0 #!/usr/bin/env python # encoding=utf-8 # created date: 2020.09.16 # author: <NAME> # email: <EMAIL> import os import sys import inspect import traceback class Default(object): def __init__(self): pass # path parameters join @staticmethod ...
StarcoderdataPython
4863718
__version__ = """1.7.0"""
StarcoderdataPython
5177997
import pickle import torch from torch import nn import numpy as np from scipy import linalg from tqdm import tqdm from calc_inception import load_patched_inception_v3 import pdb import os import csv from glob import glob import math from torch.nn import functional as F from matplotlib import pyplot as plt @torch.no_...
StarcoderdataPython
1807399
<filename>torchbenchmark/util/model.py import json import os import pandas as pd import typing from collections.abc import Iterable import torch from contextlib import contextmanager import warnings import inspect import os @contextmanager def no_grad(val): """Some meta-learning models (e.g. maml) may need to tra...
StarcoderdataPython
1886497
<reponame>shaun95/google-research<filename>symbolic_functionals/syfes/xc/mgga_test.py # coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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...
StarcoderdataPython
1681289
<gh_stars>0 """ some utilities for dealing with midi This uses python package python-midi """ import traceback import math import json import midi import os, glob, sys, string from midi.events import * import copy def is_ascii(s): return all(ord(c) < 128 for c in s) import base64 def put(dic, key, val): if k...
StarcoderdataPython
6461503
from pymongo import MongoClient from bson.objectid import ObjectId import datetime import os MONGODB_URI = os.environ.get('MONGODB_URI', 'mongodb://localhost/fmtrends') MONGODB_URI = 'mongodb://heroku_gxwl3h33:<EMAIL>:55852/heroku_gxwl3h33' print 'MONGODB_URI:',MONGODB_URI mongo_client = MongoClient(MONGODB_URI) db = ...
StarcoderdataPython
9624360
<filename>hlwtadmin/migrations/0016_auto_20200225_1006.py # Generated by Django 3.0 on 2020-02-25 09:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hlwtadmin', '0015_auto_20200224_1447'), ] operations = [ migrations.AlterField( ...
StarcoderdataPython