text
string
size
int64
token_count
int64
from schedule.scheduler4_0 import schedule from schedule.ra_sched import Schedule, RA from unittest.mock import MagicMock, patch from datetime import date import unittest import random class TestScheduler(unittest.TestCase): def setUp(self): # -- Create a patchers for the logging -- self.patcher_...
2,264
671
""" Main Module """ import logging from ulauncher.api.client.Extension import Extension from ulauncher.api.client.EventListener import EventListener from ulauncher.api.shared.event import KeywordQueryEvent from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem from ulauncher.api.shared.action.R...
2,583
656
# -*- coding: utf-8 -*- from geeklist.api import BaseGeeklistApi, GeekListOauthApi, GeekListUserApi from access import consumer_info #please access.py which contains consumer_info = { 'key': YOUR_KEY, 'secret': secret} BaseGeeklistApi.BASE_URL ='http://sandbox-api.geekli.st/v1' oauth_api = GeekListOauthApi(consumer_i...
957
330
""" Template for Characters Copy this module up one level and name it as you like, then use it as a template to create your own Character class. To make new logins default to creating characters of your new type, change settings.BASE_CHARACTER_TYPECLASS to point to your new class, e.g. settings.BASE_CHARACTER_TYPEC...
2,448
716
""" Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл. ""...
3,170
1,178
from w_i_stage import IStage from direct.interval.IntervalGlobal import Sequence, Func, Wait class CutsceneTest(IStage): def __init__(self): IStage.__init__(self) def setup(self): self.previousMap = base.gameData.currentMap base.gameData.currentMap = 'city' self.previousPos = ...
1,203
377
# -*- coding: utf-8 -*- """ 工具包 """ from . import convertor from . import model_loader from . import storage from . import parallel from . import logging
154
54
"""NeuronUnit model class for reduced neuron models""" import numpy as np from neo.core import AnalogSignal import quantities as pq import neuronunit.capabilities as cap import neuronunit.models as mod import neuronunit.capabilities.spike_functions as sf from neuronunit.models import backends from generic_network imp...
1,808
616
#!/usr/bin/env python3 import argparse import csv import datetime import json import logging import os import sys import warnings from collections import defaultdict from copy import copy from dataclasses import dataclass from itertools import islice, cycle, chain from random import randint, shuffle, choice, sample fro...
28,812
11,343
from typing import Union from unittest.mock import Mock, create_autospec import pytest from pytest import MonkeyPatch from philipstv import PhilipsTVAPI, PhilipsTVPairer, PhilipsTVRemote, PhilipsTVRemoteError from philipstv.model import ( AllChannels, AmbilightColor, AmbilightColors, AmbilightLayer, ...
9,093
3,200
"""Implementation of benchmarks. Copyright (c) 2019 Red Hat Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program...
9,612
2,895
# Core Django imports from django.contrib import admin # Imports from my apps from bus_system.apps.bus.models import BusModel admin.site.register(BusModel)
159
47
''' Various astro calcs mainly based on Meuss. ''' import numpy as np import math import time from datetime import datetime def julian_date(when): # from Meuss p 61; 'when' is a datetime object y = when.year m = when.month d = when.day + when.hour/24 + when.minute/(24*60) + when.second/(24*3600) if m < 3: y...
2,454
1,384
import win32com.client import time class CalcClient(object): def __init__(self): # CAOエンジンの作成 self._eng = win32com.client.Dispatch('CAO.CaoEngine') self._ws = self._eng.Workspaces(0) self._ctrl = self._ws.AddController('bb1', 'CaoProv.Blackboard') # 変数の追加 ...
1,221
496
''' Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor. ''' n = int(input('Entre com um valor: ')) antecessor = n - 1 sucessor = n + 1 msg = 'o antecessor do número {} é {} e seu sucessor é {}'.format(n, antecessor, sucessor) print(msg)
282
108
import pytest from mitzasql.sql_parser.parser import parse from mitzasql.utils import dfs def test_simple_insert_is_parsed(): raw_sql = ''' INSERT DELAYED INTO table (col1, col2, col3) VALUES (100, 200, 300) ''' ast = parse(raw_sql) assert len(ast) > 0 ast = ast[0] assert ast.type == 'i...
3,505
1,172
version = '2.0.1048'
21
14
# Importing standard libraires import sys ''' Main Function for the program. Logic is as follows Make two frequency tables for two strings Take overlap of both and add up the non overlapping regions (absolute values) ''' if __name__ == "__main__": # Parsing in the input s1 = list(sys.stdin.readline...
775
278
from .utilities import Response SCHEDULE_RESPONSE = b""" {"error":{"code":200,"message":"Success"},"data":{"classes":[{ "id":113209,"sector":"F","class_type_id":48,"start_date":"2020-06-07", "end_date":"2020-06-07","start_time":"09:00:00","end_time":"09:45:00", "duration":"2700000","teacher_id":782,"location_id":10,"l...
1,181
514
''' Ta-lib计算MACD ''' import pandas as pd import numpy as np import talib as ta import tushare as ts from matplotlib import rc import matplotlib.pyplot as plt import seaborn as sns rc('mathtext', default='regular') sns.set_style('white') # %matplotlib plt.rcParams["figure.figsize"] = (20, 10) dw = ts.get_k_data("60060...
518
201
import logging from regression_model.config import config from regression_model.config import logging_config VERSION_PATH = config.PACKAGE_ROOT / 'VERSION' with open(VERSION_PATH, 'r') as version_file: __version__ = version_file.read().strip()
252
74
from datetime import date year_current_date = date.today().year def get_info(name, age, height, weight): year_birth = year_current_date - age imc = round(weight / (height ** 2), 2) print(f"{name} tem {age} anos, {height} de altura e pesa {weight} KG.") print(f"O IMC do {name} é: {imc}") print(f"{...
508
200
import json from sys import stdout # START data = '''{ "name": "bugs", "age": 76 }''' obj = json.loads(data) json.dump(obj, stdout) # END print(obj)
160
67
"""Tests for SpeedTest integration.""" from unittest.mock import patch import speedtest from openpeerpower import config_entries from openpeerpower.components import speedtestdotnet from openpeerpower.setup import async_setup_component from tests.common import MockConfigEntry async def test_setup_with_config(opp):...
2,306
714
# Kertaus, kerta 3 # Muuttujat ja syötteen lukeminen käyttäjältä nimi = input("Anna nimesi: ") kengännumero = input("Mikä on kengännumerosi: ") print("Moi vaan, " + nimi + "! Kengännumerosi on " + kengännumero + ".") # F-merkkijono print(f"Moi vaan, {nimi}! Kengännumerosi on {kengännumero}.") # Numerot # Ikälaskuri...
1,258
625
import requests from lxml import etree if __name__ == '__main__': headers = {"User-Agent":'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'} url = 'https://www.apache.org/dist/ant/' sourceHTML = requests.get(url, headers = headers) selec...
616
236
from h1d_wrapper.h1d_wrapper import Element, Mesh, Linearizer
62
22
import pytest from jelm import Jelm, Node, Edge from jelm.tests.network_case_set_class import NetwokCaseTemplate def test_eq(jelm_pair_case: NetwokCaseTemplate): jelm_pair_case.evaluate_fun(non_altering_function=lambda x: x) assert not (10 == Jelm()) assert not ("fing" == Jelm()) def test_jelm_repr(...
5,132
1,954
''' Evaluation code for trajectory prediction. We record the objects in the last frame of every sequence in test dataset as considered objects, which is stored in considered_objects.txt. We compare the error between your predicted locations in the next 3s(six positions) and the ground truth for these considered object...
6,582
2,034
# !/usr/bin/python # -*- coding: utf-8 -*- import click import os try: # Python 2.x version from urllib2 import HTTPError, URLError except: # Python 3.x version from urllib.error import HTTPError, URLError from shellfoundry.exceptions import FatalError from shellfoundry.utilities.config_reader import ...
2,561
691
#!/usr/bin/python import rospy from rospy import ROSException from std_msgs.msg import Header, Bool from std_srvs.srv import SetBool from geometry_msgs.msg import PoseWithCovarianceStamped, Point, Quaternion from sensor_msgs.msg import NavSatFix, NavSatStatus from sam_msgs.msg import GetGPSFixAction, GetGPSFixFeedback...
9,064
3,014
# -*- coding: utf-8 -*- from puremvc.patterns.proxy import Proxy from .. import ApplicationFacade class RoleProxy(Proxy): NAME = 'RoleProxy' def __init__(self, proxyName=None, data=[]): super(RoleProxy, self).__init__(proxyName, data) self.data = data def addItem(self, role): ...
1,307
392
import pygame import os class Radio: def __init__(self, settings): """ Method that initiates the object Radio for game sounds Input = (Dict) """ pygame.mixer.init() self.file_die_sound = pygame.mixer.Sound('Assets/Sounds/die.mp3') self.file_hit_sound = ...
1,358
434
# This Python file uses the following encoding: utf-8 from app.package.views.Calibrate_view import CalibrateView from app.package.controllers.Calibrate_controller import CalibrateController from app.package.models.Calibrate_model import CalibrateModel import sys import matplotlib from PySide2.QtWidgets import QApplica...
4,405
1,310
import datetime import decimal from playhouse.sqlite_ext import * # Peewee assumes that the `pysqlite2` module was compiled against the # BerkeleyDB SQLite libraries. from pysqlite2 import dbapi2 as berkeleydb berkeleydb.register_adapter(decimal.Decimal, str) berkeleydb.register_adapter(datetime.date, str) berkeleyd...
557
168
from numpy.random import standard_normal from numbers import Number def simulation_analysis(project, sim_dict, iterations=250, valuator=None): """ Purpose: Analyses the effects of uncertainty of a system by performing a Monte Carlo simulation. Args: project: An instance of Project to pe...
1,513
407
import logging from telegram.ext import CommandHandler logger = logging.getLogger(__name__) def handle_dispatcher(dispatcher): dispatcher.add_handler(ping()) dispatcher.add_error_handler(error) def error(a, b, c): logger.error('Error %s %s "%s"' % a, b, c) def ping(): def handle(bot, update): ...
433
149
# -*- coding: utf-8 -*- """ @file @brief Fonctions retournant des jeux de données. """ import os def get_data_folder(): """ Retourne le répertoire de données inclus dans ce module. """ this = os.path.dirname(__file__) data = os.path.join(this, "data") return os.path.abspath(data)
307
114
from django.db import models class Coupon(models.Model): coupon = models.CharField(max_length=20) discount = models.IntegerField() valid_from = models.DateTimeField() valid_to = models.DateTimeField() active = models.BooleanField(default=True) def __str__(self): return self.coupon ...
464
145
import os from os.path import join import traceback from bs4 import BeautifulSoup from nose.plugins import Plugin class AdvancedLogging(Plugin): name = "advanced-logging" enabled = False capture_screen = True score = 1 _log_path = join(os.getcwd(), 'test_output') _script_path = None def...
6,470
1,925
""" aiohttp-ultrajson ----------------- Integrates UltraJSON with your aiohttp application. """ from setuptools import setup setup( name='aiohttp-ultrajson', version='0.1.0', url='https://github.com/sunghyunzz/aiohttp-ultrajson', license='MIT', author='sunghyunzz', author_email='me@sunghyunzz....
999
329
n, m = map(int, input().split()) scores = list(map(int, input().split())) answers = list(map(int, input().split())) for i in range(n): actuals = list(map(int, input().split())) result = 0 for i, score in enumerate(scores): if actuals[i] == answers[i]: result += score print(result...
322
111
""" Tools for network communication. """ import abc import io import json import socket import struct import sys import time import zlib import dh.ejson import dh.utils # NumPy is only needed for some parts and is optional try: import numpy as np except ImportError as e: _NUMPY_ERROR = e else: _NUMPY_ERR...
12,652
3,592
from setuptools import setup def get_readme(): with open('README.md') as f: return f.read() setup( name = 'apache-replay', version = '0.0.3', url = 'https://github.com/danizen/apache-replay.git', author = 'Daniel Davis', author_email = 'dan@danizen.net', description = 'Facilitate...
1,225
375
from distutils.core import setup setup( name='do_more', packages=['do_more'], version='0.1.0', description='A library enhancing pydoit features.', author='Duy Tin Truong', author_email='', url='https://github.com/duytintruong/do_more', download_url='https://github.com/duytintruong/do_mor...
464
175
import pandas as pd import numpy as np import elist.elist as elel import edict.edict as eded import tlist.tlist as tltl import copy __all__ = [ '_append_col', '_append_cols', '_append_row', '_append_rows', '_cn2clocs', '_col', '_cols', '_columns_map', '_crop', '_get_clocs', '_get_rlocs', '_getitem', '_ind...
16,361
6,529
from typing import List, Tuple import sentencepiece as spm import tensorflow as tf import tensorflow.keras as keras from npgru.predictor.category_predictor import CategoryPredictor from npgru.preprocessor.model_file import get_model_dir class TensorflowPredictor(CategoryPredictor): def __init__(self): ...
901
274
# Generated by Django 3.1.6 on 2021-04-25 19:46 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('eo_sensors', '0004_coveragemask'), ] operations = [ migrations.AlterUniqueTogether( name='raster', unique_together={('date',...
358
129
import math line = raw_input().strip().split() N = int(line[0]) cap = float(line[1]) items = [] for _ in xrange(N): items.append(map(float, raw_input().split())) def custcmp(x, y): _x = x[0]/x[1] _y = y[0]/y[1] if _x < _y: return 1 if _x == _y: return 0 if _x > _y: return -1 items = sorted(items, cm...
503
241
from random import randint from time import sleep opcao = 123 cont = 0 while opcao != 0: print('-=-' * 20) print('Vou pensar em um número entre 0 e 10, quer tentar adivinhar?') print('-=-' * 20) print('\n[ 1 ] Sim [ 0 ] Não') opcao = int(input('Escolha uma das opções acima\n>')) if opcao == 1:...
1,131
397
# -*- coding: utf-8 -*- """Demo153_RareCategories.ipynb ## Rare Categories - Labels - The number of labels in the dataset are different - __high cardinality__ refers to uniqueness of data values - The lower the cardinality, the more duplicated elements in a column - A column with the lowest possible cardinali...
1,896
672
#!/usr/bin/env python import sys import os import argparse import adios import skel_settings import skel_bpls # Command line parsing is chained together. This is stage two. The first stage happens in ../bin/skel def pparse_command_line (parent_parser): parser = argparse.ArgumentParser ( parents=[...
6,640
2,030
# Copyright 2021 LINE Corporation # # LINE Corporation licenses this file to you 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: # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
786
250
"""Provides a Preprocessed action for the Microsoft Visual Studio compilers. """ import os import SCons.Action import SCons.Util import preprocessed_builder # XXX These are internal to SCons and may change in the future...but it's unlikely from SCons.Tool.msvc import CSuffixes, CXXSuffixes, msvc_batch_key # TODO Con...
3,834
1,276
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Country' db.create_table('django_geoip_country', ( ('code', self.gf('django.db...
5,716
1,833
import requests import json from os import environ from .models import Order, Piece from .BLConsul import BLConsul GATEWAY_PORT = environ.get("HAPROXY_PORT") GATEWAY_ADDRESS = environ.get("HAPROXY_IP") MACHINE_SERVICE = "machine" PAYMENT_SERVICE = "payment" DELIVERY_SERVICE = "delivery" AUTH_SERVICE = "auth" CA_CERT ...
878
315
# Generated by Django 3.1.7 on 2021-02-26 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('envdaq', '0005_controller_alias_name'), ] operations = [ migrations.AddField( model_name='controllerdef', name='comp...
429
139
#################################################################################################### # # congruence_closure_module.py # # Authors: # Jeremy Avigad # Rob Lewis # # This module maintains a union-find structure for terms in Blackboard, which is currently only used # for congruence closure. It should perhap...
2,569
744
import pandas as pd import numpy as np import csv def buildPat(row,key): if key == "extension.valueAddress.city": return row.A01_DESC_LUOGO_NASCITA elif key == "identifier.value": return row.A01_ID_PERSONA elif key == "name.family": return row.A01_COGNOME elif key == "name.given...
3,280
1,238
import http.server import os import socketserver Handler = http.server.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(("127.0.0.1", 8080), Handler) print("server:\thttp://127.0.0.1:8080\n\nlog:") httpd.serve_forever()
231
97
#!/usr/bin/env python3 import locale import sys from datetime import datetime as dt import pywikibot as pwb def main(argv): dump_only = False if len(argv) > 1: if argv.pop() == '--dump': dump_only = True else: print('Error: Unrecognized option.', file=sys.stderr) ...
2,109
764
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> # pip install imapclient // pip install pyzmail >>> import imapclient >>> conn= imapclient.IMAPClient('imap.gmail.com', ssl=True) #True to use S...
1,494
600
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ...
2,633
1,076
import unittest from gilded_rose import Item, GildedRose class GoldenMasterTest(unittest.TestCase): def test_golden_master(self): output_file = None try: output_file = open("output.txt", 'r') golden_master_lines = [output_file.readlines()] finally: outp...
1,850
652
import random import string class RandomData: def __init__(self): pass @staticmethod def get_random_bool(): i = random.randrange(2) if i == 0: return True else: return False @staticmethod def get_random_list_value(list): i = rando...
895
292
from douyin.utils import fetch from douyin.config import hot_trend_url, common_headers from douyin.utils.tranform import data_to_music, data_to_topic from douyin.structures.hot import HotTrend from douyin.utils.common import parse_datetime # define trend query params query = { 'version_code': '2.9.1', 'count'...
1,120
361
# Import the hashing Library import hashlib # Get the string as input word = input("Enter the word for Hashing: ") # Get the hashing hashed_code = hashlib.sha256(word.encode()) final = hashed_code.hexdigest() # Print the result print("Hashed with 256 bit: ") print(final)
288
105
from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.dispatch import receiver from django.conf import settings from taggit.managers import TaggableManager import requests class Bookmark(models.Model): title = models.CharField(max_length=200, blank=T...
1,416
413
""" Vernam Cipher Benjamin D. Miller Takes a key, and a message Encripts the message using the key """ def vernam(key,message): message = str(message) m = message.upper().replace(" ","") # Convert to upper case, remove whitespace encrypt = "" try: key = int(key) # if the key...
797
282
from datetime import datetime as d def stringify_date(date): try: return '{0}-{1}-{2}-{3}-{4}'.format(date.year, date.month, date.day, date.hour, date.minute) except ValueError: raise ValueError('Invalid date format', date) def parse_date(date): try: return d.strptime(date, '%Y-%m-...
421
138
from fineract.objects.currency import Currency from fineract.objects.fineract_object import FineractObject from fineract.objects.types import ChargeTimeType, ChargeAppliesTo, ChargeCalculationType, ChargePaymentMode class Office(FineractObject): """ This class represent an Office """ def _init_attrib...
3,694
1,065
from heapq import heapify, heappop, heappush class Solution: def minimumEffortPath(self, heights): # get the max rows and cols m, n = len(heights), len(heights[0]) # make a heap to store the current min cost, x, and y heap = [(0, 0, 0)] # keep track of current cost cu...
1,736
551
def example_plotting_functions(): #Sort then plot pass
62
18
activate_this = '/var/www/html/venv/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) import sys, os, logging from flask_apscheduler import APScheduler sys.path.insert(0, 'var/www/html/StuffMart/vagrant/catalog') logging.basicConfig(stream=sys.stderr) from server import flask as application ...
1,427
481
import unittest from unittest.mock import patch, Mock import pandas as pd from pandas.testing import assert_frame_equal from parameterized import parameterized from dgraphpandas.strategies.horizontal import horizontal_transform class HorizontalTests(unittest.TestCase): @parameterized.expand([ (None, {'...
18,161
5,646
#!/usr/bin/python # This is client.py file import socket # Import socket module s = socket.socket() # Create a socket object #host = socket.gethostname() # Get local machine name host = socket.gethostbyname("localhost") print host port = 53 # Reserve a port for your serv...
378
113
import os import shutil from flask import render_template, redirect, url_for, request from werkzeug.utils import secure_filename from config import Config from application import app from application.model import Model @app.route('/') def index(): return redirect(url_for('submit')) def allowed_file(filename): ...
1,759
592
""" Tests onnxml Imputer converter """ import unittest import warnings import numpy as np import torch from sklearn.impute import SimpleImputer from hummingbird.ml._utils import onnx_ml_tools_installed, onnx_runtime_installed, lightgbm_installed from hummingbird.ml import convert if onnx_runtime_installed(): imp...
4,095
1,454
import configparser, os, glob, csv, json, hashlib, time import pandas as pd import psycopg2 from pprint import pprint from rs_sql_queries import staging_events_insert, staging_songs_insert from rs_sql_queries import insert_table_queries import boto3 from botocore import UNSIGNED from botocore.config import Config DE...
7,520
2,553
#!/usr/bin/python import json, urllib2, datetime from sqlite3 import dbapi2 as sqlite3 # zip codes to log zipcodes = ['07740','11210','33139','90210'] # configuration DATABASE = '../db/weather.db' SECRET_KEY = 'hackerati' DEBUG = True # open database db = sqlite3.connect(DATABASE) for zipcode in zipcodes: # pu...
1,002
369
from git import Repo from git_inspector import find_git_directories def test_find_git_directories(repo: Repo): generator = find_git_directories(search_paths=[repo.working_dir]) assert next(generator) == repo.working_dir
234
78
#!/usr/bin/env python3 try: from gelpia import bin_dir except: print("gelpia not found, gaol_repl must be in your PATH\n") bin_dir = "" from pass_utils import * from output_flatten import flatten import re import sys import subprocess import os.path as path def div_by_zero(exp, inputs, assigns, consts): qu...
3,480
1,276
import os from pip.req import parse_requirements from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # parse_requirements() returns generator of pip.req.InstallRequirement objects install_reqs = parse_requirements( os....
2,150
628
import csv import ipaddress import logging.handlers import sys import argparse try: import vat.vectra as vectra import requests except Exception as error: print('\nMissing import requirements: {}\n'.format(str(error))) sys.exit(0) LOG = logging.getLogger(__name__) INVALID_CHARS = ['~', '#', '$', '^'...
7,517
2,173
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Python变量不需要声明数据类型 # 变量在使用前必须赋值 # 变量没有类型 类型指内存中对象的类型 # 不可变数据 Number / String / Tuple # 可变数据 List / Dictionary / Set # 数字 Number # 整数 Int IntNum = 100 # 浮点数 Float FloatNum = 100.10 # 布尔值 Boolean // True:1 False:0 BoolNum = True # 复数 Complex ComplexNum = 1.00j ...
512
297
"""Generate Docs for ThreatConnect API""" # standard library import importlib import sys from abc import ABC from typing import Any, Optional # first-party from tcex.api.tc.v3._gen._gen_abc import GenerateABC class GenerateArgsABC(GenerateABC, ABC): """Generate docstring for Model.""" def __init__(self, typ...
3,526
1,042
#!/usr/bin/python sootv = {} #Read file sootvetstviya for l in open ("filesootv"): data = l.strip().split("\t") if data[0] not in sootv: sootv[data[0]] = data[1] #Read FinalReport file for l in open('Ire30_GP'): data = l.strip().split("\t") if data[1] in sootv: print(data[0]+"\t"+sootv[data[1]]...
382
192
# Quiz01_1.py items = {"콜라":1000,"사이다":900,"씨그램":500,"우유":700,"활명수":800} print("=== 음료 자판기 입니다 ====") print("[콜라][사이다][씨그램][우유][활명수] 중 선택") print("복수 선택 시 --> 예) 사이다,우유 ") def pItems(*args1,**args2) : price = 0 for i in args1: price = price + args2[i.strip()] return price # 선택목록 item, 가격 pr...
448
276
""" Copyright 2019 Sangkug Lym Copyright 2019 The University of Texas at Austin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless require...
2,619
1,017
# -*- coding: utf-8 -*- import numpy import csv import re, nltk from sklearn.feature_extraction.text import CountVectorizer from nltk.stem.porter import PorterStemmer from sklearn.linear_model import LogisticRegression # from sklearn.cross_validation import train_test_split from sklearn.externals import joblib...
3,089
1,253
class Solution: def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int: return ceil(log(buckets)/log(minutesToTest//minutesToDie + 1))
162
61
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import sys import os from PIL import Image import numpy as np size = None matrix_x = None for image in os.listdir('./washington'): try: print(image) with Image.open(os.path.join('./washington',image)) as im: imgVector = np.array(list(im.get...
2,596
1,026
import boto3 import sys if __name__ == "__main__": if len(sys.argv) > 2: print("[ERROR] You have passed in an invalid target-id, example target-id is ou-zhz0-prn5fmbc") sys.exit() else: print("[INFO] Valid argument detected, proceeding with account migration") destination_id = ...
1,677
455
#!/usr/bin/env python3 from sys import argv from sys import stdin from sys import stdout alp = len(argv) if alp > 1 and argv[1] == "--version": print ('version 0.1') quit() if alp > 1 and argv[1] == "--help": print ('ctrl+d to quit') quit() print('todo')
274
108
# https://rosalind.info/problems/rna/ # Transcribing DNA into RNA exercise from ROSALIND DNA = "ACAACAAAGGATCGGCGAGGAGCTGGTTAATCTCGATTCTAACAAAGGCCTCTTGAGTGACATAAAGTTGCTGTTCGGCCCCCGTTGCAGCCAAGCCTAGACTCGAGCGGGGTCTACCTCTGTAAACCCAAGTCGCAGGCCAAGGGCATTTTAACCCCCAAAGTTAGATACGTCGATTGAGTGCGCACTCCCTAACTTCAGACAGGATGGCGCTTAGCACTGG...
1,142
610
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-04 10:44 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('micro_admin', '0009_page'), ] operations = [ migrations.AlterModelOptions( ...
516
172
# The MIT License (MIT) # Copyright (c) 2016 Dell Inc. or its subsidiaries. # 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 ...
3,823
1,172
import struct import itertools import numpy as np from bitarray import bitarray RANDOM_SEED = 2387613 IMAGE_SIZE = 128 BATCH_SIZE = 2048 # Assign an integer to each word to be predicted. WORD2LABEL = { 'The Eiffel Tower': 0, 'The Great Wall of China': 1, 'The Mona Lisa': 2, 'airplane': 3, 'alar...
8,227
4,291
from collections import Counter from Bio import SeqIO import numpy as np import warnings import math warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') from gensim.models import Word2Vec Max_length = 100 # maximum length of used peptides def check_length(file): len...
34,734
15,714
from .excel4_anti_analysis import *
35
11