text
string
size
int64
token_count
int64
from calendarApp import shell, models import os def main(): os.system("clear") calendar = models.Calendar("main") shell.main_screen(calendar) if __name__ == "__main__": main()
196
63
import time import numpy as np import scipy.sparse as sps from gensim.models import Word2Vec from tqdm import tqdm from recommenders.recommender import Recommender from utils.datareader import Datareader from utils.evaluator import Evaluator from utils.post_processing import eurm_to_recommendation_list from recommender...
4,329
1,535
from ._version import __version__ # noqa from .pyesasky import ESASkyWidget # noqa from .catalogue import Catalogue # noqa from .catalogueDescriptor import CatalogueDescriptor # noqa from .cooFrame import CooFrame # noqa from .footprintSet import FootprintSet # noqa from .footprintSetDescriptor import FootprintSetDesc...
1,321
397
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Jared """ import numpy as np import pandas as pd import myConfig import matplotlib.pyplot as plt from ast import literal_eval from plotter import getTrendPlot1 from matplotlib.pyplot import figure df = pd.read_csv(myConfig.extOutput) dffExt = pd.read_csv(my...
2,930
1,196
name = input("Enter your name? ") if name == "guna": print("1234567890") elif name == "david": print("0987654321") elif name == "rakulan": print("12345") elif name == "raj": print("1234455667") else: print("No contacts found")
237
114
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import emoji import string import csv import os def getFileSize(nameFile): return os.stat(nameFile).st_size browser = webdriver.Chrome() def loginInstagram(url, username, password): browser.get(url) #Masu...
13,409
4,369
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objects as go import plotly.express as px import plotly.figure_factory as ff from sklearn.metrics import roc_curve import pandas as p...
5,310
1,707
from katana.sdk.service import get_component from katana.sdk.service import Service def test_service_component(): # Check service component singleton creation assert get_component() is None service = Service() assert get_component() == service def action_callback(): pass assert servi...
599
156
from .base_controller import BaseController from ..helper.utils import render_template from ..helper.constants import STATUS_OK class IndexController(BaseController): def __init__(self, client_address): self.user_ip = client_address[0] self.user_port = str(client_address[1]) self.title = "...
527
157
# -*- coding: utf-8 -*- # Copyright 2017 GIG Technology NV # # 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...
3,919
1,129
from django.conf import settings from selenium import webdriver from selenium.webdriver.chrome.options import Options import pytest import os @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get(...
1,582
478
# Generated by Django 3.0.3 on 2020-02-05 08:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('erp', '0025_auto_20200205_0839'), ] operations = [ migrations.AddField( model_name='cheminement', name='aide_humaine...
3,519
1,123
import os, sys import json class Config: def __init__(self, config_path='./config.json'): super(Config, self).__init__() self.config_path = config_path self.bin2mem_path = None self.init_configs(json.load(open(config_path))) def init_configs(self, json_data): self.bin...
3,629
1,264
#!/bin/python3 # Copyright (C) 2021, Michigan State University. # # 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,...
3,161
1,076
import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from preprocess import * from torch.utils.data import Dataset, DataLoader from blazeface import BlazeFace import os import cv2 import numpy as np from matplotlib import pyplot as plt import random import pickle ...
10,970
3,884
# Copyright 2020 Makani Technologies LLC # # 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...
18,373
7,470
#!/usr/bin/env python ########################################################################### # This software is graciously provided by HumaRobotics # under the Simplified BSD License on # github: git@www.humarobotics.com:baxter_tasker # HumaRobotics is a trademark of Generation Robots. # www.humarobotics.com #...
4,122
1,391
from siptrackdlib import errors from siptrackdlib import log class ObjectClass(object): """A class definition in the object registry. Stores a reference to the class itself and also a list of valid child classes (class_ids). """ def __init__(self, class_reference): self.class_reference = c...
4,453
1,206
from GenericAdventuringRequest import GenericAdventuringRequest class CombatRequest(GenericAdventuringRequest): """ A request used for a single round of combat. The user may attack, use an item or skill, or attempt to run away. """ # What follows are a list of available actions. ATTACK = 0 USE_ITEM = 1 USE_S...
1,139
415
''' myclient1.py - imports mymod.py and check its operation. ''' from mymod import test, countChars, countChars1, countLines, countLines1 text = 'test.txt' file = open(text) print(test(text), test(file)) print(countChars(text), countChars1(file)) print(countLines(text), countLines1(file)) print('\nedited again versio...
325
111
from .date import Date from ..response import handleResponse from datetime import datetime def searchDates(): req = Date().searchAll() message = "Listado de citas" if req['status'] == True else "No se pudo conseguir el listado de citas, inténtelo más tarde" dateToday = datetime.now().isoformat().split('...
632
195
#!/usr/bin/python import sys from pyspark import SparkContext from shutil import rmtree import os.path as path def generar(line): array = [] array.append(line[0]) array.append(line[1]) aux = line[2] ini = 2 fin = 18 if aux != "I" and aux != "D" and aux != "N": aux = line[3] ...
6,045
2,202
from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse, reverse_lazy from django.http import HttpResponseRedirect from django.shortcuts import render,HttpResponse from django.views.generic.edit import CreateView, Updat...
13,148
3,923
#!/usr/bin/env python3 import logging import os import pickle import time from os.path import join as pjoin import matplotlib.pyplot as plt import numpy as np import scipy from matplotlib import rc from scipy.optimize import least_squares import asymptotic_formulae from asymptotic_formulae import GaussZ0 from asympto...
29,706
12,145
import pytest from pxtrade.assets import reset, Stock, Portfolio from pxtrade.compliance import ( Compliance, UnitLimit, WeightLimit, ) class TestCompliance(object): def setup_method(self, *args): reset() stock1 = self.stock1 = Stock("BBB US", 2.00, currency_code="USD") stock2 ...
2,645
863
from article.serializers.serializers import ( ArticleListSerializer, ArticleDetailSerializer )
103
25
# set up the environment by reading in libraries: # os... graphics... data manipulation... time... math... statistics... import sys import os from urllib.request import urlretrieve import matplotlib as mpl import matplotlib.pyplot as plt import PIL as pil from IPython.display import Image import pandas as pd from p...
1,447
374
# # Bentobox # SDK - Graph # Graph Value # from typing import Any from bento.value import wrap from bento.protos.graph_pb2 import Node def wrap_const(val: Any): """Wrap the given native value as a Constant graph node. If val is a Constant node, returns value as is. Args: val: Native value to wrap...
608
188
from marshmallow import Schema, fields from marshmallow.validate import Length, Range class UserCreateValidator(Schema): name = fields.Str(required=True, validate=Length(max=60)) age = fields.Integer(required=True, validate=Range(min=18, max=100)) driver_license_type = fields.Str(required=True, validate=Le...
771
258
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import sys import numpy as np from joblib import Parallel, delayed import joblib import argparse import importlib from itertools import product import collections from copy import deepcopy from mcpy.utils import fi...
11,660
3,220
#------------------------------------------------------------------------------------------------------ # File Name: MusicGame.py # Author: Kyle Parrish # Date: 7/4/2014 # Description: This is a simple program that I wrote for the raspberry pi so that my daughter can # play with. It is a simple pro...
5,845
1,988
from __future__ import print_function from robin.utils import img_processing_utils import numpy as np def test_normalize_gt(in_img_array): out_img = img_processing_utils.normalize_gt(in_img_array) assert type(out_img) == np.ndarray
243
83
#4) 신경망 구현하기 ##########KEYWORD############### ################################ #신경망은 입력층에서 출력층으로 기본적으로 한 방향으로 흐른다. 한 싸이클이 끝나면 역전파 알고리즘을 통해 #계속 학습으 진행하지만 역전파 알고리즘과 같은 고급 알고리즘은 다음장에서.. #한 방향으로만 정보가 전방으로 전달되는 신경망을 피드포워드 신경망(Feed Forward NN)이라고 한다. #기본적으로 신경망은 입력층에서 데이터 입력을 받은 뒤 은닉층에서 데이터를 학습하고 출력층으로 결과를 내보낸다. #입력...
5,763
6,883
import os import pandas as pd dictt = {} i = 0 for label in ['down', 'up', 'left', 'right']: img_lst = os.listdir("./data/img_data/" + label + "/") temp_label = [0] * 4 temp_label[i] = 1 for img in img_lst: print(label + " " + img) dictt[img] = temp_label i += 1 label_df = pd.Dat...
466
188
''' Created on Jun 27, 2017 @author: lawrencezeng ''' import unittest from rubiks_race import solver class Test(unittest.TestCase): def setUp(self): self.initial_position = [ ['g', 'g', 'y', 'r', 'r' ], ['w', 'g', 'w', 'w', 'y' ], ['g', 'o', ' '...
2,398
820
# -*- coding: utf-8 -*- from __future__ import unicode_literals from modeltranslation import settings as mt_settings from modeltranslation.utils import build_localized_fieldname, get_translation_fields from django.db import migrations, models def url_path_fix(apps, schema_editor): # cannot use apps.get_model her...
1,625
462
#!/usr/bin/env python # Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
99,195
26,821
import argparse import json import re def remove_urls(tweet): return re.sub(r"http\S+", "", tweet) def fix_amp(tweet): return tweet.replace("&", "&") def remove_hashtags(tweet): return re.sub(r"#\w+\s*", "", tweet) def remove_mentions(tweet): return re.sub(r"@\w+\s*", "", tweet) def remove_rt(t...
2,019
737
# Generated by Django 2.2.5 on 2019-10-26 20:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chat', '0006_auto_20191022_1218'), ] operations = [ migrations.RemoveField( model_name='membership', name='is_admin'...
528
182
# -*- coding: utf-8 -*- # # Copyright (c) 2020 CPV.BY # # For suggestions and questions: # <7664330@gmail.com> # # LICENSE: Commercial import webbrowser from kivymd.theming import ThemableBehavior from kivymd.uix.screen import MDScreen class AboutScreen(ThemableBehavior, MDScreen): def open_url(self, instance, u...
354
143
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from gym import Env from scipy.spatial import distance from typing import Optional, Tuple, Any from causal_rl.environments import CausalEnv class MultiTyped(CausalEnv): """A simulation of balls bouncing with gravity and elastic collisio...
7,715
2,769
from flask import Flask app = Flask(__name__) @app.route("/en") def hello(): return "Hello SPIS 2016!" @app.route("/cn") def ni_hao(): return "Ni Hao SPIS 2016!" @app.route("/es") def hola(): return "Hola SPIS 2016!" @app.route("/fa") def sobh_bx(): return "Sobh Bexair SPIS 2016!" if __name__ == "_...
353
166
#!/usr/bin/env python3 import pandas as pd import sys import json from Bio import SeqIO sample_name=sys.argv[1] pango=pd.read_csv('pango.csv') nextclade=pd.read_csv('nextclade.tsv', sep='\t') aln2type=pd.read_csv('aln2type.csv') pango['sampleName']=sample_name nextclade['sampleName']=sample_name aln2type['sampleName...
3,189
1,212
from alerta.models.alert import Alert from alerta.webhooks import WebhookBase from alerta.exceptions import RejectException import os import hashlib class StatusCakeWebhook(WebhookBase): def incoming(self, query_string, payload): alert_severity = os.environ.get('STATUSCAKE_DEFAULT_ALERT_SEVERITY', 'major'...
1,484
406
# 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 # distributed under the...
3,738
1,138
################################################## # 翻訳の設定 # 変更した設定は次回起動時から適用されます ################################################## # []でくくってある項目は""でくくって,で区切ることでいくつも設定できます。 # 無視するユーザー ignore_user = ["Nightbot","Streamelements","Moobot"] # 翻訳する前に削除するワード。正規表現対応。 # URLや同じ言葉の繰り返しなどはデフォルトで削除してますので足りなかったら追加してください。 del_wor...
964
628
import logging from sqlalchemy.exc import OperationalError from wxcloudrun import db from wxcloudrun.model import Counters # 初始化日志 logger = logging.getLogger('log') logger.info("aaaaaaa") def query_counterbyid(id): """ 根据ID查询Counter实体 :param id: Counter的ID :return: Counter实体 """ logger.info(...
1,489
487
# -*- encoding: utf-8 -*- import os import sys import uuid import pytest from django.apps import apps from django.contrib.auth.models import Group from django.core.files.base import ContentFile try: from django.core.urlresolvers import reverse except ImportError: from django.urls import reverse from django.db...
7,411
2,607
from typing import List from typing import Tuple from bot.utilities.api.constants import SCORE_TEMPLATE def beautify_score(raw_score_table_data: List[List[str]]) -> List[Tuple[str, str]]: # Slightly refining traditional assessment to be written starting with lower case letter for (subject_index, subject_score_data...
1,373
474
# -*- coding: utf-8 -*- # @Time : 2021/4/6 下午9:21 # @Author : 司云中 # @File : carousel_serializers.py # @Software: Pycharm from rest_framework import serializers from Emall.exceptions import DataFormatError from shop_app.models.commodity_models import Carousel class ManagerCarouselSerializer(serializers.ModelSeriali...
1,192
434
from itertools import chain from typing import List, Tuple from .br.br_nud import * class Nud: name: str # chunk name mesh_groups: List['NudMeshGroup'] def init_data(self, name, br_nud: BrNud): self.name = name self.bounding_sphere = br_nud.boundingSphere self.mesh_groups = lis...
7,312
2,452
import argparse import gc import pathlib import sys import typing import uvicorn # type: ignore from attack_surface_pypy import __service_name__, __version__, asgi from attack_surface_pypy import logging as app_logging from attack_surface_pypy import settings # logger = structlog.get_logger() gc.disable() parser =...
2,389
788
# Generated by Django 2.2.5 on 2020-06-30 11:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('subscriptions', '0003_auto_20200630_1156'), ] operations = [ migrations.RenameField( model_name='subscriptionplan', old_name...
391
142
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 2 16:54:10 2021 @author: sdn1 """ class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLI...
545
293
import datetime from pathlib import Path from typing import Optional, Tuple from .common import _IMAGE_SUFFIXES, _PERMITTED_EXTENSIONS, PathDetails, rebuild_event_store def parse_path(path: Path, tzinfo: datetime.tzinfo) -> Optional[PathDetails]: if path.suffix.lower() not in _PERMITTED_EXTENSIONS: retur...
1,717
599
# ESnet Network Operating System (ENOS) Copyright (c) 2015, The Regents # of the University of California, through Lawrence Berkeley National # Laboratory (subject to receipt of any required approvals from the # U.S. Dept. of Energy). All rights reserved. # # If you have questions about your rights to use or distribut...
4,049
1,172
import math def distanceInMilesOrKilos(milesOrKilos,originLat,originLon,destinationLat,destinationLon): radius = 3959 if milesOrKilos == "miles" else 6371 lat1 = originLat lat2 = destinationLat lon1 = originLon lon2 = destinationLon dlat = math.radians(lat2 - lat1) dlon = mat...
599
242
from __future__ import division import inspect import types from functools import wraps function_type = type(lambda x: x) # using this instead of callable() because classes are callable, for instance class NoDefault(object): def __repr__(self): return 'no_default' no_default = NoDefault() class imd...
8,837
2,903
#!/usr/bin/env python from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) def get_version(): import mippy return mippy.__version__ def test_version(): version = get_version() import datetime import os # Get times...
1,635
554
"""Run a sample problem to test full system.""" # pylint: disable=invalid-name,missing-docstring import unittest from collections import namedtuple import math import os from physprog import classfunctions from physprog import optimize THIS_DIR = os.path.dirname(__file__) SAMPLE_INPUT = os.path.join(THIS_DIR, 'sam...
3,543
1,256
import os import sys from collections import defaultdict import tensorflow as tf import tensorflow.keras.backend as K import numpy as np import scipy.stats as ss import matplotlib.pyplot as plt from sklearn.metrics import roc_curve from sklearn.linear_model import LogisticRegression from utils import process_texts, ...
10,131
3,785
from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from rest_framework.test import APIClient from rest_framework import status from core.models import Tag from recipe.serializers import TagSerializer TAGS_URL = reverse("recipe:tag-list") class PublicTag...
2,685
819
import numpy as np # import open3d as o3d from . import BaseAnnotationDefinition # from scipy.spatial.transform import Rotation as R import logging logger = logging.getLogger(name=__name__) class Cube3d(BaseAnnotationDefinition): """ Cube annotation object """ type = "cube_3d" def __init__(s...
5,736
1,959
#!/usr/bin/env python # coding: utf-8 from my_module.exceptions import InvalidArgumentsError class SimpleCalculator(object): """SimpleCalculator SimpleCalculator is a simple calculator. Attributes: operator (str): String that represents operation type. Acceptable va...
3,702
1,142
import keras from keras.layers import Conv2D, Conv3D, Flatten, Dense, Reshape, BatchNormalization from keras.layers import Dropout, Input from keras.models import Model from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint from keras.utils import np_utils from sklearn.decomposition impo...
12,114
5,482
#!/usr/bin/env python3 from setuptools import setup, find_packages requirements = ["pyp2rpm~=3.3.1"] setup( name="utest", version="0.1.0", description="Micro test module", license="GPLv2+", author="pyp2rpm Developers", author_email='bkabrda@redhat.com, rkuska@redhat.com, mcyprian@redhat.com, ...
754
269
# 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 at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
4,235
1,496
from math import log from PIL import Image, ImageDraw from collections import Counter import numpy as np from pandas import DataFrame # my_data = [['slashdot', 'USA', 'yes', 18, 213.2, 'None'], # ['google', 'France', 'yes', 23, 121.2, 'Premium'], # ['digg', 'USA', 'yes', 24, 21.32, 'Basic'], # ...
5,570
2,107
from datetime import datetime class fileWrapper(object): def __init__(self): self.data = {} self.keys = set() # JSON data size 16KB in Bytes self.max_data_size = 16384 # Max database size 1GB in Bytes self.max_database_size = 1073741824 self.current_database...
488
160
#!/usr/bin/env python3 from __future__ import print_function import sys sys.path.append('./method') import os import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import model as m """ Run fit. """ predict_list = ['sinewave', 'staircase', 'activation', 'ap'] try: which_pred...
4,504
1,808
''' python3 classifier_service.py data.csv This service runs a scikit-learn classifier on data provided by the csv file data.csv. The idea of this is a simple spam detector. In the file, you will see a number, 1 or -1, followed by a pipe, followed by a piece of text. The text is designed to be a subject email, and...
7,752
2,275
# SPDX-License-Identifier: MIT import os import idaapi import idautils from PyQt5 import QtWidgets from uefi_analyser import dep_browser, dep_graph, prot_explorer, ui AUTHOR = "yeggor" VERSION = "1.2.0" NAME = "UEFI_RETool" WANTED_HOTKEY = "Ctrl+Alt+U" HELP = "This plugin performs automatic analysis of the input UE...
2,657
880
import os import logging import matplotlib matplotlib.use('Agg') import pylab as p import numpy as np import dolfin as df from finmag import Simulation as Sim from finmag.energies import Exchange, Demag from finmag.util.meshes import from_geofile, mesh_volume import pytest logger = logging.getLogger(name='finmag') M...
10,063
4,137
from ..helpers import get_obj_and_params, all_from_objects from ...extensions.samplers import OverSampler SAMPLERS = { 'oversample': (OverSampler, ['default']), } def get_sampler_and_params(obj_str, extra_params, params, **kwargs): obj, extra_obj_params, obj_params =\ get_obj_and_params(obj_str, SAM...
440
159
N, K = map(int, input().split()) ans = N for i in range(K): num_list = [int(n) for n in str(ans)] g1 = sorted(num_list, reverse=True) g1 = ''.join((str(g) for g in g1)) g2 = sorted(num_list, reverse=False) g2 = ''.join((str(g) for g in g2)) ans = int(g1) - int(g2) print(ans)
300
132
# Python modules import time from datetime import timedelta def consistency(func, args, expected, n=10**4): """Analyze and report on the consistency of a function.""" print('\n[CONSISTENCY TEST] {0}'.format(func.__doc__.format(*args))) def show(num, den, t, p, end='\r'): print('{3}|{4:.3f}: {0}/{...
1,008
367
from itertools import permutations from collections import Counter import time print(time.time()) s=["dgajkhdjkjfkl","ahfjkh","jfskoj","hfakljfio","fjfjir","jiosj","jiojf","jriosj","jiorjf","jhhhhaskgasjdfljjriof"] t=10 while t>0: S=s[10-t] c=dict(Counter(S)) Cperm=list(permutations(c.values())) flag= False for i...
520
262
import configparser import os from typing import ByteString import requests from core.speaker import Speaker from core.texttospeech import TextToSpeechGenerator class RhasspySpeech(Speaker, TextToSpeechGenerator): def __init__(self): Speaker.__init__(self) TextToSpeechGenerator.__init__(self) ...
784
245
import pandas as pd import os import ssl # I'm getting SSL certificates issues when downloading files from MDIC. # The code below is a hack to get around this issue. try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context =...
4,953
1,696
# Generated by Django 3.1.1 on 2020-10-02 01:11 from django.db import migrations, models import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ...
903
273
from socket import socket, AF_INET, SOCK_STREAM, IPPROTO_TCP import struct import pickle class ServerSock(socket): def __init__(self, PORT): super().__init__(AF_INET, SOCK_STREAM, IPPROTO_TCP) self.bind(("", PORT)) self.listen() def getMessage(self): payload_size = str...
1,366
396
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import namedtuple import numpy as np import pandas as pd from .series import Series class DataFrame: def __init__(self, data=None): self._data = {} if isinstance(data, dict): for key, value in data.items(): ...
3,867
1,143
""" instructions: blah blah blah settings: tifa: enabled: True unit test by function (bool): Whether to test each function entirely before moving onto the next one, or to first check that all functions have been defined, and then checking their parameters, etc. Defaults to True....
21,620
6,079
import enum from .ELF import ELF32, enums from .util import SegmentRegs, MissingOpcodeError from .CPU import CPU32 import logging logger = logging.getLogger(__name__) class FetchLoopMixin: _attrs_ = 'eip', 'mem', 'reg.ebx', 'fmt', 'instr', 'sizes', 'default_mode' def execute_opcode(self: CPU32) -> None: ...
8,732
2,889
from termcolor import colored from ...utils.feedback import feedback from .constants import DEPLOYMENT_PREFIX, DEPLOYMENT_REGISTRY from .exceptions import EntityDoesNotExist, EntityExists from .operations import delete_parameter, get_parameter, set_parameter from .project import assert_project_exists from .utils impor...
2,753
821
import numpy as np from ..tools import batchGenerator # LOGISTIC REGRESSION # for (binary) categorical data class LogisticRegression(): ''' Logistic regression with Gradient Descent binary Logistic regression Parameters ---------- epochs : int maximum epochs of gradient descent lr...
5,897
1,872
bits = '110' def turnBitsIntoInteger(listOfBits): valore = 0 lunghezza = len(listOfBits) for x in range(lunghezza): if listOfBits[x] != '0' and listOfBits[x] != '1': raise Exception('Not a combinations of bits!') valore = valore + 2**(lunghezza -1 - x) * int(listOfBits[x]) ...
1,946
1,612
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -----------------------------------------------------------------...
4,175
1,183
# coding: utf-8 from random import randint from urllib.parse import parse_qs import socket import sys import json import traceback import os import base64 import yaml import datetime import requests import re class Route: def __init__(self): self._route = [] def route(self, method, path, handler): ...
12,269
4,019
from PyQt5.QtWidgets import QTabWidget from glia.widgets.editor import Editor class EditorTabs(QTabWidget): def __init__(self, parent=None): """ Generates tab with editor depending on the file and it's type selected. """ super(EditorTabs, self).__init__(parent) # ...
656
201
""" Test Driven Development. """ import pytest @pytest.fixture def profiles() -> dict: production = 'production' staging = 'staging' qa = 'qa' return {'production': production, 'staging': staging, 'qa': qa} @pytest.mark.skip(reason='Method not yet implemented.') def test_add_profile(environment, pro...
2,296
678
#!/usr/bin/python # -*- coding: UTF-8 -*- # pylint: disable=E1601 """ 17/02/2018 Profesores: Álvaro Sánchez de Cruz / ??? - Se hace un repaso de lo que se impartió el día anterior. - Subprogramas o funciones: - Viene de la programación estructurada. - Sintaxis: def nombreFuncion([para...
1,743
635
import logging import requests import json import azure.functions as func dapr_url = "http://localhost:3500/v1.0" def main(msg: func.QueueMessage): logging.info(f"Python queue-triggered function received a message!") message = msg.get_body().decode('utf-8') logging.info(f"Message: {message}") # Publ...
576
195
import os import json from logging import config name = os.path.splitext(__file__)[0] json_filename = os.path.join(os.path.dirname(__file__), f'{name}.json') with open(json_filename) as fh: config.dictConfig(json.load(fh))
260
88
import responses from tamr_unify_client import Client from tamr_unify_client.auth import UsernamePasswordAuth @responses.activate def test_upstream_dataset(): dataset_json = { "id": "unify://unified-data/v1/datasets/12", "name": "Project_1_unified_dataset_dedup_features", "description": ...
2,618
939
import warnings warnings.simplefilter("ignore", category=FutureWarning) from skbio import TabularMSA from skbio.sequence import GrammaredSequence from io import StringIO, IOBase from shutil import copyfileobj import copy import numpy as np from pmaf.internal.io._seq import SequenceIO from pmaf.sequence._sequence._nucl...
14,531
3,823
class ArvoreDerivacao: def __init__(self, conteudo, esquerda=None, direita=None): self._conteudo = conteudo self._esquerda = esquerda self._direita = direita self.children = [self._esquerda, self._direita] @property def conteudo(self): return self._conteudo def...
1,498
531
import re import sys from operator import add from pyspark.sql import SparkSession def computeContribs(urls, rank): """Calculates URL contributions to the rank of other URLs.""" num_urls = len(urls) for url in urls: yield (url, rank / num_urls) def parseNeighbors(urls): """Parses a urls pai...
1,404
440
from __future__ import absolute_import, unicode_literals from django.conf import settings from django.templatetags.static import static from django.utils.html import format_html from django.utils.module_loading import import_string from wagtail.core import hooks @hooks.register('insert_editor_css') def editor_css()...
1,312
417
# Copyright 2009-2010 Yelp # Copyright 2013 David Marin # Copyright 2014 Disco Project # # 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...
3,333
1,241