id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
1611673
#!/usr/bin/python3 s="Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." one=[1, 5, 6, 7, 8, 9, 15, 16, 19] wlen=[] for i in range(1, 21): if i in one: wlen.append(1) else: wlen.append(2) ret={} for idx, w in enumerate(s.split()): re...
StarcoderdataPython
8170137
def rot_90_clock(strng): ar = strng.split('\n') return '\n'.join(''.join(j[i] for j in ar)[::-1] for i in range(len(ar[0]))) def diag_1_sym(strng): arr = strng.split('\n') return '\n'.join(''.join(j[i] for j in arr) for i in range(len(arr[0]))) def selfie_and_diag1(strng): ar = strng.split('\n')...
StarcoderdataPython
24150
<reponame>gconine88/MATH_6204<filename>hw10_conine/thomas.py # -*- coding: utf-8 -*- """ Created on Mon Nov 20 23:06:49 2017 @author: Grant An implementation of the Thomas algorithm in Python, using just-in-time compiling from numba for additional speed """ import numpy as np from numba import njit, f8 ...
StarcoderdataPython
5120236
<reponame>james7132/rTouhouModBot<gh_stars>0 import os from util import * from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base db_path = "/db/r_touhou_mod.db" engine = create_engine('sqlite:///{0}'.format(db_path)) Session = sessionmaker(bind=engine) Base = de...
StarcoderdataPython
9642756
from .testutils import VerminTest class VerminExclusionsTests(VerminTest): def test_module(self): visitor = self.visit("from email.parser import FeedParser") self.assertEqual([(2, 4), (3, 0)], visitor.minimum_versions()) self.config.add_exclusion("email.parser.FeedParser") visitor = self.visit("from...
StarcoderdataPython
324677
from distutils.core import setup setup( name='rss2producer', version='0.1.1', description="Simplifies the process of creating an RSS 2.0 feed.", author='<NAME>', author_email='<EMAIL>', url='https://github.com/nathan-osman/rss2producer', license='MIT', packages=['rss2producer'], cla...
StarcoderdataPython
4883
# -*- coding: utf-8 -*- import os,sys from PyQt4 import QtGui,QtCore dataRoot = os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardir,os.pardir,'histdata')) sys.path.append(dataRoot) import dataCenter as dataCenter from data.mongodb.DataSourceMongodb import Mongodb import datetime as dt ...
StarcoderdataPython
3318523
<reponame>synapticarbors/mpire<gh_stars>100-1000 class StopWorker(Exception): """ Exception used to kill workers from the main process """ pass class CannotPickleExceptionError(Exception): """ Exception used when Pickle has trouble pickling the actual Exception """ pass
StarcoderdataPython
5068993
''' Created on 13.06.2014 @author: schaffrr ''' import csv import sys import getopt class EnsemblAnnotation(): def __init__(self, inputFile): self._inputFile = inputFile def readAndModifyEnsembleAnnotation(self, ouputFile): r = csv.reader(open(self._inputFile), delimiter="\t") #...
StarcoderdataPython
5023269
import sys sys.path.append('/home/dhe/hiwi/Exercises/Pretrained_Models_NMT/') import onmt.Markdown import argparse from pretrain_module.roberta_tokenization_ch import FullTokenizer from transformers import RobertaTokenizer parser = argparse.ArgumentParser(description='preprocess.py') onmt.Markdown.add_md_help_argume...
StarcoderdataPython
3541957
import unittest from ..src.sfbulkapiv2 import Bulk import uuid import os class BulkTest(unittest.TestCase): # test case method should startpip with test def connect_test_org(self): # set the below enviroment variables before running test. username = os.environ["USERNAME"] password = o...
StarcoderdataPython
9704758
<gh_stars>1-10 from .connection import set_db_config_file_path from .connection import DIALECT_MYSQL, DRIVER_PYMYSQL from .connection import CURW_FCST_HOST, CURW_FCST_PORT, CURW_FCST_DATABASE, CURW_FCST_USERNAME, CURW_FCST_PASSWORD from .connection import CURW_OBS_HOST, CURW_OBS_PORT, CURW_OBS_DATABASE, CURW_OBS_USERNA...
StarcoderdataPython
3248565
<reponame>rishusingh022/My-Journey-of-Data-Structures-and-Algorithms<filename>Project Euler Problems/Problem30.py def check_self_behaviour(num,pow): return num == sum([int(elem)**pow for elem in str(num)]) final_ans = 0 for i in range(2,1000000): if check_self_behaviour(i,5): final_ans += i print(f...
StarcoderdataPython
6442323
<reponame>AnimeThemes/animethemes-batch-encoder from ._bitrate_mode import BitrateMode class EncodingConfig: # Config keys config_allowed_filetypes = 'AllowedFileTypes' config_encoding_modes = 'EncodingModes' config_crfs = 'CRFs' config_include_unfiltered = 'IncludeUnfiltered' # Default Confi...
StarcoderdataPython
3547390
<gh_stars>1-10 """ Models thermodynamic properties of the metal such as generalized coordination number dependent dependent binding energies """ import numpy as np import os class metal: ''' Class for properties of a metal ''' def __init__(self, met_name): ''' Pt DFT da...
StarcoderdataPython
3283155
input() arr = list(map(int, input().split())) arr.reverse() for num in arr: print(f"{num} ", end="")
StarcoderdataPython
5098924
from typing import Union from flask import Blueprint, current_app, jsonify, request, json from app import SessionKey, socketio from app.models import KeyLookupTable from app.utils import error_respond from app.utils.decorators import session_verify, master_password_verify from app.utils.master_password import MasterP...
StarcoderdataPython
8161971
<reponame>supercatex/Machine_Learning import numpy as np from keras.models import Sequential from keras import layers from keras import activations from keras import optimizers from keras import losses from keras import metrics from keras.callbacks import EarlyStopping import matplotlib.pyplot as plt import os os.envir...
StarcoderdataPython
12847250
# Copyright (c) 2019, MD2K Center of Excellence # - <NAME> <<EMAIL>> # 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, th...
StarcoderdataPython
1779256
# Copyright 2020 AppScale Systems, Inc # SPDX-License-Identifier: BSD-2-Clause from awscli_plugin_logs_tail.tail import TailCommand def awscli_initialize(cli): cli.register('building-command-table.logs', inject_tail_command) def inject_tail_command(command_table, session, **kwargs): command_table['tail'] = Ta...
StarcoderdataPython
1657415
import warnings import numpy as np import pandas as pd from scipy import optimize from autocnet.camera import camera from autocnet.camera import utils as camera_utils from autocnet.utils.utils import make_homogeneous, normalize_vector try: import cv2 cv2_avail = True except: # pragma: no cover cv_avail = ...
StarcoderdataPython
6483077
<filename>WebMirror/management/rss_parser_funcs/feed_parse_extractYoursiteCom.py def extractYoursiteCom(item): ''' Parser for 'yoursite.com' Note: Feed returns incorrect URLs! Actual site is pbsnovel.rocks ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "...
StarcoderdataPython
3548850
# Generated by Django 2.1.5 on 2020-02-07 14:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20200207_1349'), ] operations = [ migrations.RenameField( model_name='tutorial', old_name='tutorial_tittle...
StarcoderdataPython
3260694
<gh_stars>1-10 # -*- coding: utf-8 -*- import QueueBase from ssdb.connection import BlockingConnectionPool from ssdb import SSDB import json class QueueSSDB(QueueBase.QueueBase): def __init__(self, name, host='localhost', port=8888, **kwargs): QueueBase.QueueBase.__init__(self, name, host, port) ...
StarcoderdataPython
387123
<filename>tests/test_Vitodens200W.py import unittest from tests.ViCareServiceMock import ViCareServiceMock from PyViCare.PyViCareGazBoiler import GazBoiler from PyViCare.PyViCare import PyViCareNotSupportedFeatureError import PyViCare.Feature class Vitodens200W(unittest.TestCase): def setUp(self): self.ser...
StarcoderdataPython
8045116
#!/usr/bin/env python3 from data_loader import DataLoader from keras import backend as K import keras as ker from keras.models import Sequential, Model from keras.layers import Dense, Conv2D, Flatten, MaxPool2D, Reshape from keras.layers import Conv2DTranspose from keras.layers import ZeroPadding2D, ZeroPadding3D fr...
StarcoderdataPython
4897912
import os import logging from logging.handlers import RotatingFileHandler from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_moment import Moment from flask_login import LoginManager from config import Config db = SQLAlchemy() migrate = Migrate() ...
StarcoderdataPython
12810833
# -*- coding: utf-8 -*- import sys import versioneer if sys.version_info < (3, 0): print('\nInstaMsg requires at least Python 3.0!') sys.exit(1) from setuptools import setup, find_packages __version__ = versioneer.get_version() cmdclass = versioneer.get_cmdclass() with open('README.md') as f: readme = ...
StarcoderdataPython
6610841
# -*- coding: UTF-8 -*- import csv import math import operator import random import numpy as np import pandas as pd import os from math import exp import math import sklearn from sklearn import svm from sklearn.model_selection import train_test_split basedir = os.path.abspath(os.path.dirname(__file__)...
StarcoderdataPython
11265584
<reponame>DunnCreativeSS/cash_carry_leveraged_futures_arbitrageur ''' Copyright (C) 2017-2020 <NAME> - <EMAIL> Please see the LICENSE file for the terms and conditions associated with this software. ''' import logging from decimal import Decimal from sortedcontainers import SortedDict as sd from yapic impo...
StarcoderdataPython
12864748
<reponame>uw-it-aca/course-roster-lti<gh_stars>0 from .base_settings import * INSTALLED_APPS += [ 'course_roster.apps.CourseRosterConfig', 'compressor', ] COMPRESS_ROOT = '/static/' COMPRESS_PRECOMPILERS = (('text/less', 'lessc {infile} {outfile}'),) COMPRESS_OFFLINE = True STATICFILES_FINDERS += ('compressor...
StarcoderdataPython
135038
import abc import numpy as np import torch from utils.rbf import * from utils.normalizer import * class IEncoder(nn.Module): def __init__(self, cfg): super().__init__() self.n_history = cfg['history_count'] self.n_features = cfg['history_features'] @abc.abstractmethod def out_siz...
StarcoderdataPython
1749753
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class SettingsDeviceSupportBundlesGridRemote(RemoteModel): """ | ``id:`` none | ``attribute type:`` string | ``name:`` none | ``attribute type:`` string | ``version:`` none...
StarcoderdataPython
3407411
# Generated by Django 2.2.9 on 2020-02-06 23:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Ride_Share', '0033_registeredsharer_pass_num'), ] operations = [ migrations.AddField( model_name='ride', name='speci...
StarcoderdataPython
3451979
# --------------------------------------------------------------------- # Span handler # --------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # Python modules imp...
StarcoderdataPython
1750273
<filename>src/NFixedPointQuery.py<gh_stars>0 # NFixedPointQuery.py # <NAME> # Modified from # DoubleFixedPointQuery.py # MIT LICENSE 2016 # <NAME> from DSGRN.Query.FixedPointTables import * import os, sys class HiddenPrints: def __enter__(self): self._original_stdout = sys.stdout sys.stdout = o...
StarcoderdataPython
1939591
import sys import logging import semver import anymarkup import reconcile.queries as queries import reconcile.openshift_base as ob import reconcile.openshift_resources_base as orb from utils.openshift_resource import OpenshiftResource as OR from utils.openshift_resource import ConstructResourceError from utils.defer ...
StarcoderdataPython
3383943
<filename>api_tools/urls.py from .utils import DefaultModelSerializer import debug_toolbar from django.conf import settings from django.conf.urls import url, include from django.contrib import admin from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token # Routing urlpatterns = [ ...
StarcoderdataPython
3218634
import discord from discord.ext import commands from discord.ext.commands import has_permissions, BucketType, cooldown from datetime import datetime, timedelta import asyncio import json import pymongo class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=['m']) @comm...
StarcoderdataPython
4818687
import elevation import numpy as np import matplotlib.pyplot as plt import seaborn as sns import geopandas as gpd %matplotlib inline from rasterio.transform import from_bounds, from_origin from rasterio.warp import reproject, Resampling import rasterio as rio bounds = gpd.read_file('E:/Msc/Dissertation/Code/Data/Input...
StarcoderdataPython
3464149
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
StarcoderdataPython
192002
<reponame>Farbfetzen/Advent_of_Code # https://adventofcode.com/2020/day/22 from collections import deque from copy import deepcopy from itertools import islice from src.util.types import Data, Solution def prepare_data(data: str) -> list[deque[int]]: return [deque([int(card) for card in deck.splitlines()[1:]]) ...
StarcoderdataPython
6428962
<reponame>lukemshannonhill/LeetCode_Daily_Problem_Solutions # https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: # if flips are possible, then we can flip everything top = [[0],[0],...
StarcoderdataPython
6446876
<filename>recbole/model/knowledge_aware_recommender/kgnnls.py # -*- coding: utf-8 -*- # @Time : 2020/10/3 # @Author : <NAME> # @Email : <EMAIL> r""" KGNNLS ################################################ Reference: Hongwei Wang et al. "Knowledge-aware Graph Neural Networks with Label Smoothness Regularization...
StarcoderdataPython
1788392
import datetime from django.db import models from django.utils import timezone class Location(models.Model): image = models.ImageField(upload_to = 'artifacts/uploads', default = 'artifacts/uploads/qmark.png') text = models.CharField(max_length=200) def __str__(self): return self.text class A...
StarcoderdataPython
1792995
<filename>scrapy/contrib/ibl/extraction/similarity.py """ Similarity calculation for Instance based extraction algorithm. """ from itertools import izip, count from operator import itemgetter from heapq import nlargest def common_prefix_length(a, b): """Calculate the length of the common prefix in both sequences p...
StarcoderdataPython
1736835
import pandas as pd from torch.utils.data import Dataset, DataLoader from sklearn.preprocessing import LabelEncoder import Dataset import text_normalization from pickle import dump, load from sklearn.model_selection import train_test_split def loadTrainValData(batchsize=16, num_worker=2, pretraine_path="bert-base-unca...
StarcoderdataPython
314058
<gh_stars>10-100 import requests from bs4 import BeautifulSoup, NavigableString, Tag import time import urllib import pickle res = requests.get('http://www.imsdb.com/all%20scripts/').text soup = BeautifulSoup(res, 'html5lib') movies = soup.find_all('td', {'valign': 'top'})[2].find_all('p') base_url = 'http://www.im...
StarcoderdataPython
6621660
"""An easy-to-use wrapper for NTFS-3G on macOS.""" __version__ = "1.1.1"
StarcoderdataPython
1988790
# Zadání: ######### # # Pro výpočet směrodatné odchylky, potřebujete znát střední hodnotu, kterou # spočtete jako aritmetický průměr hodnot v poli. Napište funkci getMean, # která vypočte střední hodnotu zadaného pole. # # Napište funkci getDeviation, která vypočte směrodatnou odchylku, ve funkci # použijte volání fun...
StarcoderdataPython
237706
<filename>Emall/loggings.py<gh_stars>1-10 # -*- coding: utf-8 -*- # @Time : 2020/5/9 8:50 # @Author : 司云中 # @File : loggings.py # @Software: PyCharm import abc import logging # 工厂模式 class AbstractLoggerFactory(metaclass=abc.ABCMeta): @abc.abstractmethod def common_logger(self): pass @abc.abs...
StarcoderdataPython
3416659
class Solution: def rob(self, nums: List[int]) -> int: # Max Amount (nth house) = max(Amount at nth house + Max Amount(n -2), # Max Amount(n - 1)) # base case if(len(nums) == 0): return 0; hr = []; for i in range(len(nums)): h2 = 0 h...
StarcoderdataPython
98170
<gh_stars>0 from PyQt5.QtCore import * class Factorial(QObject): @pyqtSlot(int, result=int) def factorial(self,n): if n == 0 or n == 1: return 1 else: return self.factorial(n - 1) * n
StarcoderdataPython
312604
''' Licensing Information: Please do not distribute or publish solutions to this project. You are free to use and extend Driverless Car for educational purposes. The Driverless Car project was developed at Stanford, primarily by <NAME> (<EMAIL>). It was inspired by the Pacman projects. ''' from engine.const import Cons...
StarcoderdataPython
4812640
from core.settings import SITE_BASE_URL from weedid.models import Dataset, WeedidUser from weedid.utils import send_email from textwrap import dedent def upload_notification(upload_id): upload_entity = Dataset.objects.get(upload_id=upload_id) uploader = upload_entity.user email_body = f"""\ User {uplo...
StarcoderdataPython
1809805
<filename>InfrastructureManager/utils/utils.py """ A collection of common utility functions which can be used by any module within the AppScale Infrastructure Manager implementation. """ import os import sys import time import uuid __author__ = 'hiranya' __email__ = '<EMAIL>' def get_secret(filename='/etc/appscale/se...
StarcoderdataPython
5193984
<filename>tools/test_PoseEstimation.py import numpy as np import cv2 from loadYamlData import * data = loadYamlData("cam_left_1.yml") K = data["K"] D = data["D"] """ data = loadYamlData("cam_stereo_1.yml") K1 = data["K1"] D1 = data["D1"] K2 = data["K2"] D2 = data["D2"] R = data["R"] T = data["T"] E = data["E"] """ foc...
StarcoderdataPython
11233383
<filename>app/manage.py import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from flask import Flask from flask_sqlalchemy import SQLAlchemy from .models import Ideas app = Flask(__name__, static_folder="", static_url_path="") app.config.from_object(__name__) app.config.update( ...
StarcoderdataPython
8117802
print('='*50) print('PESO IDEAL'.center(50)) print('='*50) linha = '\033[1;96m=\033[m' * 50 def peso(): sexo = int(input('''Você é: [ 1 ] Homem [ 2 ] Mulher Digite a número da sua opção: ''')) print('='*50) altura = float(input('\nDigite a sua altura: ')) print(f'\n{linha}') if sexo == 1:...
StarcoderdataPython
8064807
<filename>viewsets/__init__.py try: from django.core.exceptions import ImproperlyConfigured except ImportError: ImproperlyConfigured = ImportError try: from .base import ViewSet from .model import ModelViewSet # Allows to see module metadata outside of a Django project # (including setup.py). except (I...
StarcoderdataPython
1602336
# import sys # sys.path.append('../../') import numpy as np import pandas as pd import json import copy from plot_helper import coloring_legend, df_col_replace from constant import REPORTDAYS, HEADER_NAME, COLUMNS_TO_DROP, FIRST_ROW_AFTER_BURNIN def single_setting_IQR_json_generator(fpath_pattern_list, outfile_dir, ou...
StarcoderdataPython
1747313
<gh_stars>1-10 #© Copyright IBM Corporation [2018], [2019] [<NAME>] #LICENSE: [Apache License 2.0 (Apache-2.0) http://www.apache.org/licenses/LICENSE-2.0] import sys import requests import json import datetime from datetime import date,timedelta def main(dict): #required parameters - actual secrets are entered in ...
StarcoderdataPython
5012347
<filename>tests/test_cli.py import unittest import outputs from smb.cli import ps_cmd from smb.cli.smb_log import get_logger, log from infi.execute import execute_assert_success, execute from smb.cli.ibox_connect import InfiSdkObjects share_names = ['share1', 'share 2', 'long_share_3_and more'] limited_share = 'limi...
StarcoderdataPython
5174085
<reponame>tor4z/shinypy<filename>tests/test_msg.py import json import random from shiny.message import Message, Status, Method from shiny.util import randstr def test_str_msg_parser(): msg = {} data = {} for _ in range(10): data[randstr(5)] = randstr(5) reason = randstr(10) msg['status']...
StarcoderdataPython
11256029
<filename>airflow/migrations/versions/2e541a1dcfed_task_duration.py # -*- coding: utf-8 -*- # # 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 # # ...
StarcoderdataPython
3366777
from .custom_map_tests import *
StarcoderdataPython
6619257
""" Copyright 2018 Accelize 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 agreed to in writing, software di...
StarcoderdataPython
6524511
<reponame>bycristhian/psp # Django from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.shortcuts import render # Views from psp.views import DashboardView, IndexView, HomeView, DashboardConfigurationView from us...
StarcoderdataPython
350536
import os import git import gnupg import shutil from loguru import logger def sync_password_store(repo_url=None, repo_dir='~/.password-store') -> git.Repo: try: repo = git.Repo(repo_dir) logger.info(f'Password store at `{repo_dir}`') if repo.git.diff(): raise ValueError('There ...
StarcoderdataPython
4869380
from pytest import mark from audit_log.api.serializers import AuditLogSerializer _common_fields = { "audit_event": { "origin": "APARTMENT_APPLICATION_SERVICE", "status": "SUCCESS", "date_time_epoch": 1590969600000, "date_time": "2020-06-01T00:00:00.000Z", "actor": { ...
StarcoderdataPython
133747
import requests import json import click import datetime import logging logging.basicConfig(level=logging.INFO, format='[*] %(asctime)s %(levelname)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S") @click.command() @click.option('--net/--no-net', help='use the online data', default=True, show_default...
StarcoderdataPython
64449
# Lib from setuptools import setup, find_packages exec(open('methylprep/version.py').read()) test_requirements = [ 'methylcheck', # 'git+https://github.com/FoxoTech/methylcheck.git@feature/v0.7.7#egg=methylcheck', 'pytest', 'pytest_mock', 'matplotlib', 'scikit-learn', # openpyxl uses this, and forc...
StarcoderdataPython
6440398
# -*- coding:utf-8 -*- import os from sqlalchemy import create_engine from pandas.io.pytables import HDFStore import tushare as ts def csv(): df = ts.get_hist_data('000875') df.to_csv('c:/day/000875.csv',columns=['open','high','low','close']) def xls(): df = ts.get_hist_data('000875') #...
StarcoderdataPython
78487
<gh_stars>1-10 # encoding: utf-8 # page show record size """ show_cnt = 15 """ # msyql dababase connection info """ mysqldb_conn = { 'host' : 'localhost', 'user' : 'root', 'password' : '', 'db' : '', 'charset' : 'utf8' } """ # with out save http response content to database """ save_content = Tru...
StarcoderdataPython
3545291
<reponame>baklanovp/pystella import numpy as np from pystella.rf import band from pystella.rf.ts import TimeSeries, SetTimeSeries __author__ = 'bakl' class LightCurve(TimeSeries): def __init__(self, b, time, mags, errs=None, tshift=0., mshift=0.): """Creates a Light Curve instance. Required parameters:...
StarcoderdataPython
8016198
<filename>market/market.py<gh_stars>0 import json, hmac, hashlib, time, requests, base64 from requests.auth import AuthBase from websocket import create_connection class Market(AuthBase): def __init__(self, api_key, secret_key, passphrase, api_url, ws_url, name): self.api_key = api_key self.secret...
StarcoderdataPython
9744566
<gh_stars>10-100 # Copyright (c) 2015 <NAME> # # See the file license.txt for copying permission. from __future__ import annotations import logging import random import yaml import typing if typing.TYPE_CHECKING: from amqtt.session import Session logger = logging.getLogger(__name__) def format_client_message...
StarcoderdataPython
238215
<reponame>QualiSystems/OpenStack-Shell<filename>package/cloudshell/cp/openstack/command/operations/connectivity_operation.py from cloudshell.cp.openstack.domain.services.connectivity.vlan_connectivity_service import VLANConnectivityService class ConnectivityOperation(object): public_ip = "Public IP" def __in...
StarcoderdataPython
1779555
<filename>stix2-jailbreak.py #!/usr/bin/env python3 # Code based off of https://github.com/mvt-project/mvt import sys import os from stix2.v21 import (Indicator, Malware, Relationship, Bundle, DomainName) if __name__ == "__main__": if os.path.isfile("jailbreak.stix2"): os.remove("jailbreak.stix2") w...
StarcoderdataPython
47823
<filename>tests/test_bloomfilter.py # -*- coding: utf-8 -*- import unittest import redis import src.bloomfilter as bf import src.exceptions as ep class BloomFilterTest(unittest.TestCase): redis_host = '' redis_port = 6379 redis_db = 0 redis_client = None name = 'bloom_for_test' bloom_filter...
StarcoderdataPython
5150428
import unittest from my_list import MyList class TestStringMethods(unittest.TestCase): """ Realizar 3 unit tests por cada uno de los siguientes requerimientos para una lista: We need to get the size of the list We need to clear the list We need to add Items We need to be ab...
StarcoderdataPython
1720662
<gh_stars>1-10 """:mod:`getpost.hogwarts` --- Controller module of getpost ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from collections import namedtuple from flask import Blueprint, render_template from ..orm import Session ACCOUNT_PER_PAGE = 20 # Permissions SELF_NONE = 0x0 ...
StarcoderdataPython
3220559
import torch import torch.nn as nn from torch import sigmoid from torch.nn.init import xavier_uniform_, zeros_, kaiming_uniform_ import torchvision as tv def conv(in_planes, out_planes, kernel_size=3): return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=(kernel_size-1)/...
StarcoderdataPython
304552
<filename>rough_surfaces/__init__.py from . import analyse from . import generate from . import params from . import contact from . import surface from . import plot
StarcoderdataPython
5171934
<filename>nn_init.py import os def main(): print('Would you like to reset the network configurations?') choice = input() if (choice == 'Y' or choice == 'y'): # reset models, pickles and clean dir folders = ['clean/', 'models/', 'pickles/'] for folder in folders: for file in os.listdir(folder): ...
StarcoderdataPython
11390694
import json from pprint import pprint # Open data file and load into data dict with open('data.json', 'r') as data_file: data = json.load(data_file) pprint(data) # Just for fun, to try JSON dump m = {'id': 2, 'name': 'hussain'} n = json.dumps(m) print type(n)
StarcoderdataPython
4929042
<gh_stars>0 import numpy as np import matplotlib.pyplot as plt ###########THE FUNCTIONS########################################### ####Task1 Equation (dy/dt=-2x)#################################### def f(x,T): return -2*x #####Task 1 analytical soltution################################## def f1(): ...
StarcoderdataPython
3216675
<filename>0023/driver.py #!/usr/bin/python import cProfile def d(n): if n in (0, 1): return 0 y, q = int(n ** 0.5), [1] m = y + 1 if y * y == n: q.append(y) m = y for x in range(2, m): if n % x == 0: q.extend([x, int(n / x)]) return sum(q) def metho...
StarcoderdataPython
9719019
<reponame>PJ-Schulz/reddish from dataclasses import dataclass from hiredis import ReplyError class Ok: @classmethod def __get_validators__(cls): yield cls._validate @classmethod def _validate(cls, value): if isinstance(value, cls): return value elif b'OK' == val...
StarcoderdataPython
3378130
expected_output = { 'vlan': {'100': {'vni': '8100'}, '1000': {'vni': '9100'}, '1005': {'vni': '9105'}, '1006': {'vni': '9106'}, '1007': {'vni': '9107'}, '1008': {'vni': '9108'}, '1009': {'vni': '9109'}, '101': {'vni': '8101'}, '103': {'vni': '8103'}, '105': {'vni': '...
StarcoderdataPython
1801325
<reponame>LawrenceDior/thetis """ Test GridInterpolator object """ from thetis.interpolation import GridInterpolator import numpy as np from scipy.interpolate import griddata import pytest def do_interpolation(dataset='random', plot=False): """ Compare GridInterpolator against scipy.griddata """ np.r...
StarcoderdataPython
1925320
import json from math import ceil, degrees from System.Net import WebClient from pyrevit import revit, DB from fetchbim import settings from fetchbim.family import Family, GroupedFamily from fetchbim.attributes import Parameter def isclose(a, b, rel_tol=1e-9, abs_tol=0.0): return abs(a - b) <= max(rel_tol * ma...
StarcoderdataPython
1743965
import math from functools import partial from keras import backend as K from keras.callbacks import ModelCheckpoint, CSVLogger, LearningRateScheduler, ReduceLROnPlateau, EarlyStopping from keras.models import load_model from legacy.unet3dlegacy.metrics import (dice_coefficient, dice_coefficient_loss, dice_coef, dice...
StarcoderdataPython
296205
import argparse import logging import os import warnings from pathlib import Path import numpy as np import matplotlib.pyplot as plt from PIL import Image from scipy.ndimage import gaussian_gradient_magnitude from skimage import feature, morphology from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS warni...
StarcoderdataPython
109319
# -*- coding: utf-8 -*- import unittest from converter import Converter, ConverterRequest, ConverterResponse from datetime import datetime from .rate_providers import RateProviderInterface class TestConverter(unittest.TestCase): def test_constructor_raises_when_invalid_rate_provider_is_given(self): with...
StarcoderdataPython
1789446
<reponame>andremartins746/OpenCV_Python-Processamento_de_imagens import numpy as np import cv2 #caminhos dos videos VIDEO_SOURSE = 'videos/Cars.mp4' VIDEO_OUT = 'videos/results/filtragem_mediana_temporal.avi' #amarzenando o video em uma variavel cap = cv2.VideoCapture(VIDEO_SOURSE) #lendo o video hasFrame, frame = ca...
StarcoderdataPython
6552708
# Python edgegrid module """ Copyright 2015 Akamai Technologies, 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 http://www.apache.org/licenses/LICENSE-2.0 Unles...
StarcoderdataPython
6537222
<gh_stars>1-10 import ujson as json import asyncpg from fuzzywuzzy import process from collections import deque import random class Server: @classmethod async def create(cls, settings): self = Server() credentials = {"user": settings['sql'][0], "password": settings['sql'][2], "database": settin...
StarcoderdataPython
6591463
class A1Stock: ''' A1_Stock: shorthand for stock with Component A, and 1 solvent. class called AB2 would consist of Components A and B, and 2 solvents. Minimum information: components_dict - dictionary pointing to Component objects: e.g. {'A':Component, 'solvent1':Component} wtf...
StarcoderdataPython
8185674
print((lambda x, y: pow(y, 2) - x)(sum(map(lambda x: pow(x, 2), range(101))), sum(range(101))))
StarcoderdataPython