text
string
size
int64
token_count
int64
# coding: utf-8 """ App Center Client Microsoft Visual Studio App Center API # noqa: E501 OpenAPI spec version: preview Contact: benedetto.abbenanti@gmail.com Project Repository: https://github.com/b3nab/appcenter-sdks """ import pprint import re # noqa: F401 import six class BranchConfigur...
5,752
1,622
from click.testing import CliRunner import unittest from mock import patch, Mock, PropertyMock from floyd.cli.version import upgrade class TestFloydVersion(unittest.TestCase): """ Tests cli utils helper functions """ def setUp(self): self.runner = CliRunner() @patch('floyd.cli.version.pi...
1,156
448
"""Contains HelpCommand class.""" import discord from discord.ext import commands from offthedialbot import utils class HelpCommand(commands.DefaultHelpCommand): """Set up help command for the bot.""" async def send_bot_help(self, mapping): """Send bot command page.""" list_commands = [ ...
4,181
1,135
def is_anagram ( word1, word2 ): ''' Returns True if word1 is 'anagram' of word2 or False if otherwise. word1: str word2: str ''' return sorted(word1) == sorted(word2) print(is_anagram("silence", "listen"))
255
90
import torch from torch import nn as nn from learning.modules.blocks import ResBlock, ResBlockConditional class ResNetConditional(nn.Module): def __init__(self, embed_size, channels, c_out): super(ResNetConditional, self).__init__() self.block1 = ResBlock(channels) # RF...
3,017
1,089
# Used for deploying on Apache with mod_wsgi from cryptovote.app import create_app application = create_app()
110
33
# # @lc app=leetcode id=203 lang=python3 # # [203] Remove Linked List Elements # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: ListNode, val: int)...
802
252
""" A module that defines the QLearning Agent for the pricing game as a class. Note that we have a numba version (for speed) which inherits everything from QLearningAgentBase. """ import numpy as np from numba import float64 from numba import int32 from numba import njit from numba.experimental import jitclass from ....
7,178
1,984
#!/usr/bin/python # with help from teleop_keyboard.py, # https://github.com/ros-teleop/teleop_twist_keyboard/blob/master/teleop_twist_keyboard.py # Graylin Trevor Jay and Austin Hendrix, BSD licensed import roslib; #roslib.load_manifest('teleop_move') import rospy from geometry_msgs.msg import Twist import sys, ...
2,825
1,105
""" File: shrink.py Name: Wilson Wang 2020/08/05 ------------------------------- Create a new "out" image half the width and height of the original. Set pixels at x=0 1 2 3 in out , from x=0 2 4 6 in original, and likewise in the y direction. """ from simpleimage import SimpleImage def shrink(filename): ...
1,561
533
""" show ip dhcp database show ip dhcp snooping database show ip dhcp snooping database detail """ # Python import re # Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import (Schema, Any, Optional, Or, And, Default, Use) # Pa...
15,349
4,584
import os import sys import json import ipaddress import paramiko def func_createcont(br,r,IP): print("\nMaking containers "+r) print("sudo docker run -itd --cap-add=NET_ADMIN --name "+r+" main-vm") os.system("sudo docker run -itd --cap-add=NET_ADMIN --name "+r+" main-vm") print("ovs-docker add-port "+...
848
308
### flaskr/__init__.py import os from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(test_config = None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:toor!@lo...
1,051
352
import boto3 import time class AwsEc2(object): def __init__(self, access_key, secret_key): self.access_key = access_key self.secret_key = secret_key self.client = boto3.client(service_name='ec2', region_name="ap-northeast-1", aws_access_key_id=self.access_key, ...
7,228
1,868
import control import speech_recognition as sr def recognize_speech_from_mic(recognizer, microphone): """Transcribe speech from recorded from `microphone`. Returns a dictionary with three keys: "success": a boolean indicating whether or not the API request was successful "error": `Non...
2,299
599
from .consts import * # Object matching by classid OBJECTS_CLSID_RULES = [ {'type' : RULETYPE_EQUAL, 'text' : 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000', 'entities' : [ {'name' : 'web:tech/flash'} ] }, {'type' : RULETYPE_EQUAL, 'text' : 'clsid:d27cdb6e-ae6d-11cf-96b8-44455354...
6,721
2,855
# Why does this file exist, and why not put this in `__main__`? # # You might be tempted to import things from `__main__` later, # but that will cause problems: the code will get executed twice: # # - When you run `python -m failprint` python will execute # `__main__.py` as a script. That means there won't be any # ...
6,020
1,773
# -*- coding: utf-8 -*- # Copyright (c) 2020, RC and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class ItemLabel(Document): def on_submit(self): for d in self.get("items"): # Check for Price list...
1,112
432
# coding:utf-8 # author:MurphyWan # 蓝图放在www.py中 """ controller.py/index.py from flask import Blueprint route_index = Blueprint('index_page', __name__) @route_index.route("/") def index(): return "Hello World" """ from application import app ''' 统一拦截器 , 都放在这里 ''' from web.interceptors.Authinterceptor import * '...
1,308
508
# -------------- #Header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #path of the data file- path data=pd.read_csv(path) data["Gender"].replace("-","Agender",inplace=True) gender_count=data.Gender.value_counts() gender_count.plot(kind="bar") #Code starts here # ---...
1,410
583
#!/usr/bin/env python3 #MIT License #Copyright (c) 2018 The University of Michigan #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 ...
6,962
3,091
# coding: utf-8 # In[35]: import matplotlib.pyplot as plt from pylab import * import numpy as np main_image=plt.figure(figsize=(10,10)) subplots_adjust(hspace=0.3,wspace=0.3)#控制子图间的行间距、列间距 #子图1-单线 x_0=np.linspace(0,2*np.pi,20) #自变量X的取值范围 sub_image_1=plt.subplot(2,2,1) plt.xlabel('X value') plt.ylabel('Sin value')...
2,222
1,150
"""Generated class for event_audit.json""" class Object0C54FB6D: """Generated schema class""" def __init__(self): self.subFolder = None self.subType = None @staticmethod def from_dict(source): if not source: return None result = Object0C54FB6D() result.subFolder = source.get('subFo...
2,190
698
#!/usr/bin/env python # -*- coding: utf-8 -*- """ RGB Colourspace Transformations =============================== Defines the *RGB* colourspace transformations: - :func:`XYZ_to_RGB` - :func:`RGB_to_XYZ` - :func:`RGB_to_RGB` See Also -------- `RGB Colourspaces IPython Notebook <http://nbviewer.ipython.org/gith...
7,624
3,032
from typing import List import pandas as pd import pytest from preprocessing.assign_folds import assign_folds testdata = [ [ [ "patient1", "patient2", "patient3", "patient4", "patient5", "patient6", "patient7", ...
1,768
624
from django.contrib.auth.models import User from django.db import models from apps.tags.models import Tag class Note(models.Model): owner = models.ForeignKey(User, related_name="notes") tags = models.ManyToManyField(Tag, related_name="notes", blank=True) created = models.DateTimeField(auto_now_add=True)...
456
140
"""Tests for __main__.py.""" # import logging from unittest.mock import MagicMock, patch import pytest import viseron.__main__ @pytest.fixture def mocked_viseron(mocker): """Mock Viseron class.""" mocker.patch("viseron.__main__.Viseron", return_value="Testing") def test_init(simple_config, mocked_viseron)...
1,116
358
# 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 # d...
11,950
3,815
from flask import session, redirect, url_for from flask.json import jsonify from api import app, oauth from api import models @app.route("/api/v2/login") def _get_api_v2_login(): redirect_uri = url_for("_get_api_v2_redirect", _external=True) return oauth.google.authorize_redirect(redirect_uri) @app.route("/...
1,105
389
def column_generator(): with open('columns.csv', encoding='utf-8') as f: for line in f: keyword = line.strip('\n') # <columnOverride column="tid" property="tid"/> # print(r'<columnOverride column="{}" property="{}"/>'.format(keyword,keyword)) print(r'<ignoreCo...
418
119
# -*- coding: utf-8 -*- """ This file contains language-specific implementation for an Afrikaans voice. The idea is that this file contains subclassed Voice and Phoneset implementations. This package ttslab/voices may then also contain speaker specific implementations e.g. "afrikaans_SPEAKER.py" """ fr...
22,250
6,848
#!/usr/bin/python # -*- coding: utf-8 -*- """ This module contains analysis done for the Ocean iodide (Oi!) project This includes presentation at conferences etc... """ import numpy as np import pandas as pd import sparse2spatial as s2s import sparse2spatial.utils as utils import matplotlib import matplotlib.pyplot...
144,813
53,156
import pandas as pd from . import cashUtils as utils class ReadStockBhavDataCSV: def __init__(self, fileName): self.df = pd.read_csv(fileName) self.columns = self.df.columns def getCSVColumnList(self): return self.columns def getStockFlatData(self): ''' Returns a ...
4,331
1,292
from distutils.core import Extension, setup from Cython.Build import cythonize from Cython.Compiler import Options Options.docstrings = False ext = Extension(name="cyt_module", sources=["cyt_module.pyx"]) setup( ext_modules = cythonize(ext), )
253
83
from flask import request, url_for from flask_api import FlaskAPI, status, exceptions from flask_cors import CORS, cross_origin import torch import json import numpy as np import torch from modeling_gptneo import GPTNeoForCausalLM from modeling_gpt2 import GPT2LMHeadModel from transformers import ( GPTNeoConfig...
18,995
5,626
""" post_bands: post_bands extract data from static-o_DS3_EBANDS.agr and it will build the kpoints length: xcoord_k from the high symmetry line and the corresponding basis for reciprocal space. b1 = 1 / a1, b2 = 1 / a2 and b3 = 1 / a3. """ import os import numpy as np import matplotlib.pypl...
20,391
7,259
import logging import logging.config logging.config.fileConfig('./instance/logging.conf') # create logger logger = logging.getLogger('Cognitive-API') # 'application' code ''' logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('criti...
337
98
import json import unittest from buter.app.services import load_from_file, detect_app_name from buter.server import docker from buter.util.Utils import unzip from config import getConfig class AppServiceTest(unittest.TestCase): def setUp(self): """ 这里只需要初始化 server.docker 对象 :return: ...
1,735
584
# -*-coding:utf-8-*- __author__ = 'Mason' import re import zipfile z = zipfile.ZipFile('channel.zip', mode='r') number = '90052' comments = [] while True: text = z.read(number + '.txt') number = re.findall('([0-9]+)', text) print number try: number = number[0] comments.append(z.getinfo...
397
148
from products.product import Product from notifications.notification import Notification from clients.client import Client class Subscription: def __init__(self, product: Product, timing: int): self.notifications = [] self.product = product self.timing = timing def add_notification(se...
728
175
# https://atcoder.jp/contests/joi2008yo/tasks/joi2008yo_e R, C = list(map(int, input().split())) senbei_pos = [] ans = 0 for _ in range(R): pos = list(map(int, input().split())) senbei_pos.append(pos) for bit in range(2**R): total = 0 copied_pos = senbei_pos[:] # Rの上限が10なので10桁の2進数になるように0で埋める fl...
654
283
#!/usr/env python3 import requests import os import glob import telegram from time import sleep token = "token" bot = telegram.Bot(token=token) # Боту шлется ссылка на ютуб, он загоняет ее в bash комманду youtube-dl -x --audio-format mp3 <link>, шлет загруженный mp3 обратно клиенту class BotHandler: def __init__...
2,850
949
#!/usr/bin/python # ex:set fileencoding=utf-8: from __future__ import unicode_literals from djangobmf.views import ModuleCreateView from djangobmf.views import ModuleUpdateView from djangobmf.views import ModuleDetailView from .forms import BMFTeamUpdateForm from .forms import BMFTeamCreateForm class TeamCreateVie...
530
170
from __future__ import division, print_function import sys, os, glob, time, warnings, gc # import matplotlib.pyplot as plt import numpy as np from astropy.table import Table, vstack, hstack import fitsio from astropy.io import fits from scipy.interpolate import interp1d output_path = '/global/cfs/cdirs/desi/users/ro...
1,038
561
import telepot # Não criei um bot no telegram ainda, dessa forma este codigo não funciona # TODO: Criar bot no telegram e pegar chave bot = telepot.Bot("Aqui vai minha chave do Telegram") def recebendoMsg(msg): print(msg['text']) bot.message_loop(recebendoMsg) while True: pass
290
105
# Support for english (EN) language def missing_translation(tr_id): return "MISSING TRANSLATION FOR STRING ID '" + str(tr_id) + "'" helper_commands = { "AUTHORIZE": "Usage:\n/authorize @<username>\n/authorize <user id>", "DEAUTHORIZE": "Usage:\n/deauthorize @<username>\n/deauthorize <user id>", "GIVEN": "Usage:\n...
4,590
1,609
# Generated by Django 2.1.7 on 2019-03-31 10:31 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
1,855
524
#!/usr/bin/env python3 # encoding: utf-8 # Douglas Crockford's idea for making generators # basically "why do you need a `yield` keyword when you can just maintain some state" # in my view, a class would be a better way to do this, and indeed, in python, # that's how Iterators are defined. def iter(list): i = 0 def ...
448
161
from time import time from ss.utils import INF import sys import os import shutil TEMP_DIR = 'temp/' DOMAIN_INPUT = 'domain.pddl' PROBLEM_INPUT = 'problem.pddl' TRANSLATE_OUTPUT = 'output.sas' SEARCH_OUTPUT = 'sas_plan' ENV_VAR = 'FD_PATH' FD_BIN = 'bin' TRANSLATE_DIR = 'translate/' SEARCH_COMMAND = 'downward --inter...
6,336
2,477
import requests from api import config def get_docgen_token(): params = { "grant_type": "client_credentials", "client_id": config.COMMON_DOCGEN_CLIENT_ID, "client_secret": config.COMMON_DOCGEN_CLIENT_SECRET, "scope": "" } req = requests.post( config.COMMON_DOCGEN_S...
564
196
''' Library for gcode commands objects that render to strings. ''' from .number import num2str from .point import XYZ class GcodePoint(XYZ): def __str__(self): ret_list = [] for label, val in zip(('X', 'Y', 'Z'), self.xyz): if val is not None: ret_list.append('{}{}'.for...
3,164
1,100
''' Description: Problem 3 (rearrange the code) Version: 1.0.1.20210116 Author: Arvin Zhao Date: 2021-01-14 22:51:16 Last Editors: Arvin Zhao LastEditTime: 2021-01-16 04:11:18 ''' def get_data(): username = input('Enter your username: ') age = int(input('Enter your age: ')) data_tuple = (username, age) ...
619
241
from tensorflow import keras # Make sure the tf_trees directory is in the search path. from tf_trees import TEL # The documentation of TEL can be accessed as follows print(TEL.__doc__) # We will fit TEL on the Boston Housing regression dataset. # First, load the dataset. from keras.datasets import boston_housing (x_t...
1,046
344
#!/usr/bin/env python # Core Library modules import argparse import os # Third party modules import pytest # First party modules import nntoolkit.utils as utils def test_is_valid_file(): parser = argparse.ArgumentParser() # Does exist path = os.path.realpath(__file__) assert utils.is_valid_file(pa...
725
239
sum = 0 for x in range(1,1000): if x%3 == 0 or x%5 == 0: sum += x print ("Total is:", sum)
101
58
import smtplib import os from email.mime.text import MIMEText from email.utils import formataddr from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header try: from src.config import CONFIG except ImportError: class...
1,977
796
from typing import List, Optional from can_decoder.Signal import Signal class Frame(object): id = 0 # type: int size = 0 # type: int signals = None # type: List[Signal] multiplexer = None # type: Optional[Signal] def __init__( self, frame_id: int, fram...
2,679
718
largura = float(input('Digite a largura da parede: ')) altura = float(input('Digite a altura da parede: ')) area = largura * altura tinta = area / 2 print('A área da parede é de {}'.format(area)) print('Será necessário para pintar {} litros de tinta'.format(tinta))
268
95
#Kyle Slater import re def terraformable(content:str): pattern = re.compile("\"TerraformState\":\"Terraformable\"") matches = pattern.findall(content) return len(matches)
174
61
import os import tempfile import requests api_url = "http://127.0.0.1:8989" def test_no_token(): """Request home without token""" response = requests.get(api_url+"/isvalid") print(response.status_code) assert response.status_code == 401
256
92
#!/usr/bin/python3 # MIT License # # Copyright (c) 2021 gh0$t # # 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,...
6,279
2,162
# Generated by Django 3.1.2 on 2021-09-23 21:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('payment_module', '0004_auto_20210924_0009'), ] operations = [ migrations.RenameField( model_name='commission', old_name='age...
955
296
import tensorflow as tf import keras import numpy as np def get_bias_major_weights(model): weights = model.get_weights() biasMajor = [] for arrI in range(0, len(weights), 2): inWeights = weights[arrI] biasWeights = weights[arrI+1].reshape((1,-2)) l = np.concatenate((biasWeights, inW...
935
398
import os MONGO_HOST = os.getenv('OPENSHIFT_NOSQL_DB_HOST') MONGO_PORT = os.getenv('OPENSHIFT_NOSQL_DB_PORT') MONGO_USERNAME = os.getenv('OPENSHIFT_NOSQL_DB_USERNAME') MONGO_PASSWORD = os.getenv('OPENSHIFT_NOSQL_DB_PASSWORD') MONGO_DBNAME = 'speakeasy' PRIV_KEY_FILE = os.getenv('OPENSHIFT_DATA_DIR') + '/server_privat...
486
226
r''' perl_io - Opens a file or pipe in the Perl style Copyright (c) 2016 Yoichi Hariguchi 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 rig...
10,047
3,273
from .. import bp from flask import request, render_template, flash, redirect, url_for from flask_login import current_user, login_required from app.lib.base.provider import Provider from app.lib.base.decorators import admin_required @bp.route('/logs/errors', methods=['GET']) @login_required @admin_required def logs_...
919
301
#!/usr/bin/env python # Copyright 2014 Open Connectome Project (http://openconnecto.me) # # 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 # #...
5,539
2,019
# Copyright 2017 reinforce.io. 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 # # Unless required by applicable law or...
2,241
612
import os import re import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver import Chrome from s...
9,970
4,880
import os import tempfile import shutil import requests import sys import logging import json from src.server.dependency import ModelData import tensorflow as tf class StreamToLogger(object): """ Fake file-like stream object that redirects writes to a logger instance. Source: https://stackoverflow.com/a/3...
8,644
2,594
from flask import Flask from flask import render_template from flask import request from model import MovieWebDAO import json from ml import Forcast app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None)...
3,287
1,147
import h5py import numpy as np import cv2 def read_new(archive_dir): with h5py.File(archive_dir, "r", chunks=True, compression="gzip") as hf: """ Load our X data the usual way, using a memmap for our x data because it may be too large to hold in RAM, and loading Y as normal ...
1,438
505
# -*- coding: utf-8 -*- """ Automate WhatsApp - Sending WhatsApp message @author: DELL Ishvina Kapoor """ #importing the necessary modules import pywhatkit as pkt import getpass as gp #displaying a welcome message print("Automating Whatsapp!") #capturing the target phone number from the user phone_...
646
231
import gast as ast from beniget import Ancestors, DefUseChains as DUC, UseDefChains from beniget.beniget import Def __all__ = ["Ancestors", "DefUseChains", "UseDefChains"] class DefUseChains(DUC): def visit_List(self, node): if isinstance(node.ctx, ast.Load): dnode = self.chains.setdefault...
894
277
# -*- coding: utf-8 -*- """ Created on Thu Sep 3 16:43:28 2020 @author: nicholls """
88
51
from collections import Counter def read_file(filepath): with open(filepath,'r') as f: a = [x for x in f.read().split('\n\n')] b = []; d = [] for x in [[x[0],x[1].split(' or ')] for x in [x.split(': ') for x in a[0].split('\n')]]: for y in x[1]: ...
2,401
813
# Author: Ibrahim Alhas - ID: 1533204. # MODEL 3: CNN with built-in tensorflow tokenizer. # This is the final version of the model (not the base). # Packages and libraries used for this model. # ** Install these if not installed already **. import numpy as np import pandas as pd import matplotlib.pyplot ...
9,512
3,172
#!/usr/bin/env python2 # -*- coding: utf8 -*- # # Copyright (c) 2017 unfoldingWord # http://creativecommons.org/licenses/MIT/ # See LICENSE file for details. # # Contributors: # Richard Mahn <rich.mahn@unfoldingword.org> """ This script generates the HTML tN documents for each book of the Bible """ from __future_...
40,857
13,324
import pandas as pd import numpy as np from tqdm import tqdm import argparse from pyscenic.aucell import aucell from .aucell import create_gene_signatures from .aucell import assign_bootstrap def main(): parser = argparse.ArgumentParser(description='AUcell Bootstrapping.') parser.add_argument( '-i', '-...
2,565
861
"""Custom topology example s7 ---- s8 ---- s9 / \ / \ / \ h1 h2 h3 h4 h5 h6 """ from mininet.topo import Topo print('Loading MyTopo') class MyTopo(Topo): "Simple topology example." def __init__(self): Topo.__init__(self) # Add hosts and switches h1, h2, h3, h4, h5, h6 = (se...
696
323
from rule_condition import Condition from rule_action import Action from rule_template import RuleTemplate from rule_engine import RuleEngine from rule import Rule from rule_data import Data from rule_scope import Scope from action_handler_send_email import SendEmailHandler from action_handler_report_alarm import Repor...
2,383
824
from django.urls import path from .views import * rest_urls = list(map(lambda x: path(x[0], x[1], name=x[2]), [ ('login/', login, 'login'), ('issue_asset/', issue_asset, 'issue_asset'), ('buy/', buy, 'buy'), ('get_assets/', get_assets, 'get_assets'), ('get_transactions/', get_transactions, 'get_tr...
362
134
import os import numpy as np import monai import math import torch import glob from skimage.morphology import remove_small_holes, remove_small_objects from monai.transforms import ( LoadImaged, AddChanneld, Orientationd, Spacingd, ScaleIntensityRanged, SpatialPadd, RandAffined, RandCropB...
4,898
1,803
import json import pytest from unittest import TestCase from rest_framework.test import APIClient from ..models import Group, Prediction @pytest.mark.django_db class PredictionViewSetTest(TestCase): def setUp(self): self.client = APIClient() def test_prediction_list(self): response = self.cl...
867
258
import stringdist def levenshtein(stru1, stru2): """ Measures the Levenshtein distance between two strings Parameters --------------- stru1 First string stru2 Second string Returns --------------- levens_dist Levenshtein distance """ return stringd...
414
135
"""Specification for the RoboMaker delete. simulation application component.""" # 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,873
792
DOWNLOADS_PER_DATASET = ''' /* VER 1.2 used for total downloads from 2016-08-01 which is used to sort datasets by "most downloads" for the "XXX downloads" counter on /search and on each individual dataset gets all download events and counts occurrences of unique combinations of user, resource, and dataset, and day, t...
7,595
2,442
""" Profile ../profile-datasets-py/div83/077.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div83/077.py" self["Q"] = numpy.array([ 3.01408100e+00, 3.40341800e+00, 3.94918400e+00, 4.08209300e+00, 4.65722800e+00, 5.59385900e+00, 5.9688...
13,343
10,391
#!/usr/bin/python import fnmatch import logging class sflow_sub_record: def __init__(self,scheme,app_id,app_ip,app_port,subscription_info,sub_info_filter): logging.debug("* Updating subscription_info ") self.scheme = scheme self.app_id = app_id self.ipaddress = app_ip self...
2,624
843
""" A script to run XFaster for gcorr calculation. Called by iterate.py. """ import os import xfaster as xf import argparse as ap from configparser import ConfigParser # Change XFaster options here to suit your purposes opts = dict( likelihood=False, residual_fit=False, foreground_fit=False, # change o...
3,148
1,107
import unittest from src.examples.c_decisions.decisions import is_letter_consonant, logical_op_precedence, num_is_not_in_range_or, number_is_in_range_and, test_config from src.examples.c_decisions.decisions import get_letter_grade from src.examples.c_decisions.decisions import logical_op_precedence from src.examples.c...
1,888
718
from .client import MQTT_Client
32
11
# 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...
23,824
6,015
from mezzanine.conf import register_setting register_setting( name="PAGEDOWN_SERVER_SIDE_PREVIEW", description="Render previews on the server using the same " "converter that generates the actual pages.", editable=False, default=False, ) register_setting( name="PAGEDOWN_MARKDOWN_E...
444
133
""" --- Day 5: Hydrothermal Venture --- You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible. They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your puzzle input)...
4,274
1,532
from typing import Callable class Solution: def sortArrayByParityII(self, nums: list[int]) -> list[int]: # Crucial lesson: 2 pointer approach doesn't necessarily mean # the pointers should start at opposite ends of the array. evens, odds = 0, 1 end = len(nums) while evens <...
1,316
485
from flask_sqlalchemy import SQLAlchemy # Initialize the Flask-SQLAlchemy extension instance db = SQLAlchemy()
112
36
import re UNITS_XML_FILE = 'poscUnits22.xml' UNITS_PICKLE_FILE = 'units.pickle' OUTPUT_DECIMALS = 6 SOURCE_PATTERN = r'^(?P<quantity>.*[\d.]+)\s*(?P<from>[^\d\s]([^\s]*|.+?))' SOURCE_RE = re.compile(SOURCE_PATTERN + '$', re.IGNORECASE | re.VERBOSE) FULL_PATTERN = r'(\s+as|\s+to|\s+in|\s*>|\s*=)\s(?P<to>[^\d\s][^\s...
4,285
1,831
def RetT(): print('True'); return True def RetF(): print('False'); return False print('----- or -----') RetT() or RetF() RetF() or RetT() #第一引数が偽のときにのみ、第二引数が評価されます。 print('----- and -----') RetT() and RetF() #第一引数が真のときにのみ、第二引数が評価されます。 RetF() and RetT() #第一引数が真のときにのみ、第二引数が評価されます。 print('----- not -----') print(not Tr...
462
222
from enum import Enum from pathlib import Path import click from mbox.click import EnumChoice, ParsedDate, PathParam class AF(Enum): IPv4 = 4 IPv6 = 6 def test_enum_choice(runner): @click.command() @click.option("--af", type=EnumChoice(AF, int)) def cmd(af): click.echo(af) result ...
1,548
565