text
string
size
int64
token_count
int64
from setuptools import setup setup( name = "awslambdacicd-cli", version = "0.1.2", author = "Janos Potecki", license = "MIT", packages = [ "awslambdacontinuousdelivery.cli", "awslambdacontinuousdelivery.cli.templates.python" ], entry_points = { ...
461
143
#! /usr/bin/env python3 from PyQt4 import QtGui import Signal class UI_InputSignal(QtGui.QDialog): """ """ def __init__(self, parent=None): super(UI_InputSignal, self).__init__(parent) vbox = QtGui.QVBoxLayout() label = QtGui.QLabel("Input Signal") vbox.addWidget(label) ...
3,587
1,190
import pytest from stacks.stacks import Stack def test_Can_successfully_instantiate_an_empty_stack(): new_stack = Stack() actual = new_stack.top expected = None assert actual == expected def test_Can_successfully_push_onto_a_stack(): new_stack = Stack() new_stack.push("a") actual = new_...
1,790
601
# -*- coding: UTF-8 -*- from flask.ext.restful import abort from leancloud.errors import LeanCloudError from leancloud.query import Query from leancloud.user import User from handlers import request_validator from models.auth_token import AuthToken import datetime import uuid __author__ = 'Panmax' from flask import re...
1,941
530
"""Extend api keys with sample_store columns. Revision ID: cad2875fd8cb Revises: 385f842b2526 Create Date: 2017-02-22 11:52:47.837989 """ import logging from alembic import op import sqlalchemy as sa log = logging.getLogger('alembic.migration') revision = 'cad2875fd8cb' down_revision = '385f842b2526' def upgrade...
1,044
414
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,870
492
#!/usr/bin/python3 # -*- coding: utf8 -*- """ cron: 30 9 * * * new Env('集勋章'); 活动入口:东东农场->东东乐园(点大风车)->集勋章 500豆 """ # 是否开启通知,Ture:发送通知,False:不发送 isNotice = True # UA 可自定义你的, 默认随机生成UA。 UserAgent = '' import asyncio import json import random import os, re, sys try: import requests except Exception as e: print(...
11,059
4,372
from __future__ import division, absolute_import, print_function import os import csv import re import sys import numpy as np import multiprocessing re_split = re.compile("([NS])(\d+)([EW])(\d+)") SAMPLES = 1201 def read_hgt_file(f): fname = os.path.split(f)[-1][:-4].upper() with open(f, "rb") as hgt_data: ...
1,726
621
#!/usr/bin/env python ''' Reformats <.rtsc> files such that correlation may be easily caluclated, either genome-wide or on a per transcript basis. Output is a <.csv>. You may filter output by using a coverage overlap. where you only want to get the correlation between transcripts mutually above a certain threshold. Yo...
5,361
1,742
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def getMinimumDifference(self, root: TreeNode) -> int: nodes = [] def traversal(root, nodes: list): if not root: ...
895
279
from trojan import Trojan, parasite from cktnet import read_bench_file, write_bench_file, get_partitions from random_bsc_partition import repartition_ckt import copy import argparse import random import os.path as path try: import cPickle as pickle except ImportError: import pickle def randbits(seed=None): r...
3,744
1,238
""" Test module for barbante.text. """ import nose.tools import barbante.utils.text as text def test_calculate_tf_en(): """ Tests calculate_tf for English contents. """ language = "english" contents = "Cooks who don't love cooking don't cook well." results = text.calculate_tf(language, contents)...
2,964
999
#Imports from django.http.response import HttpResponse from django.shortcuts import render from django.contrib import messages from .forms import DownloadForm from pytube import YouTube from math import pow, floor, log from datetime import timedelta from requests import get # Your YouTube V3 Api Key KEY = "" # Conver...
3,365
1,091
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import re import json import datetime from pathlib import Path import stringcase # type: ignore from typing import Any, Dict, List, Optional, Union, TYPE_CHECKING from .logger import logger from . import fhirclass if TYPE_CHECKING: from .generato...
45,429
12,293
from django.test import TestCase from django.db import models from hutils.managers import QuerySetManager class TestModel(models.Model): i = models.IntegerField() objects = QuerySetManager() class QuerySet(models.query.QuerySet): def less_than(self, c): return self.filter(id__lt=c) class QuerySetM...
731
245
def merge_role_json(files): merged = {} for i in files: merged.update(i) return merged
109
37
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """ from typing import Tuple, Any, Callable from protocolbuffer...
1,868
553
""" DOCSTRING """ import app import flask import keras import numpy import os import random @app.app.route('/') #disease_list = [ # 'Atelectasis', # 'Consolidation', # 'Infiltration', # 'Pneumothorax', # 'Edema', # 'Emphysema', # 'Fibrosis', # 'Effusion', # 'Pneumonia', # 'Pleural_Thicke...
1,923
724
""" Challenge to choose options from lists """ CHOICE = "-" while CHOICE != "0": if CHOICE in "12345": print("You chose {}".format(CHOICE)) else: print("Please choose your option from the list below:") print("1:\tLearn Python") print("2:\tLearn Java") print("3:\tGo Swimmi...
437
150
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 4 11:31:43 2021 @author: Michi """ import numpy as np class Prior(object): ''' Class implementing the prior. At the moment it only supports disjoint priors. contains a method logPrior that returns the sum of log priors for each varia...
3,001
897
import numpy as np import matplotlib.pyplot as plt tfinal = 10 T = 0.1 N = int(tfinal/T) t = np.linspace(0,tfinal,N) t[1] = T t[2] = 2*T y = np.linspace(0,tfinal,N) y[1] = 0 y[2] = 0 u = np.linspace(0,tfinal,N) u[1] = 0 u[2] = 0 r = np.linspace(0,tfinal,N) r[1] = 1 r[2] = 1 e = np.linspace(0,tfinal,N) e[1] = r[1] - y[1...
682
453
from typing import Iterable, Optional, Tuple, Union import torch from pytorch3d.structures import Meshes from mmhuman3d.core.cameras import MMCamerasBase from .base_renderer import BaseRenderer from .builder import RENDERER, build_shader from .utils import normalize @RENDERER.register_module( name=['Depth', 'de...
4,058
1,143
# -*- coding: utf-8 -*- # filename : bot.py # description : Discord bot interface for interacting with the server # author : LikeToAccess # email : liketoaccess@protonmail.com # date : 08-01-2021 # version : v2.0 # usage : python main.py # notes ...
7,131
2,584
class MyClass: def __init__(self, *args): pass def __lt__(self, other): pass def __gt__(self, other): return True
152
48
"""RQ3: Happiness algorithm as impacted by localness""" import csv import os import argparse import sys from collections import OrderedDict import numpy from scipy.stats import spearmanr from scipy.stats import wilcoxon sys.path.append("./utils") import bots LOCALNESS_METRICS = ['nday','plurality'] HAPPINESS_EVALU...
12,277
3,704
import logging import random import time import threading from threading import Event from patched_commands import PrestoCommand class WorkloadRunner(threading.Thread): log = logging.getLogger(__name__) def __init__(self, exitEvent, silencePeriodEvent, tid, queries, cluster_label): threading.Thread...
4,239
1,217
from chainerltr.evaluation.ndcg import ndcg from chainerltr.evaluation.dcg import dcg
86
35
from typing import List, Tuple, Dict from avalanche.benchmarks.datasets.imagenet_data import ( IMAGENET_TORCHVISION_WNID_TO_IDX, IMAGENET_TORCHVISION_CLASSES, ) MINI_IMAGENET_WNIDS: List[str] = [ "n02110341", "n01930112", "n04509417", "n04067472", "n04515003", "n02120079", "n039246...
2,509
1,697
#!/usr/bin/env python3 ### while loops #a = 10 #while a <= 100000: # a *= 10 # print(a) #print('this is no longer in the loop because not indented') #a = 10 #while a > 0: # print(a) # if a == 5: # break # a -= 1 #a = 10 #while a > 0: # a -= 1 # if a % 2 == 0: # continue # skip if ...
465
225
def ws_message(message): message.reply_channel.send({ "text": "Just for fun %s" % message.content['text'], })
126
42
from common import * from trezor.crypto import rfc6979 from trezor.crypto.hashlib import sha256 class TestCryptoRfc6979(unittest.TestCase): def test_vectors(self): vectors = [ ("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721", "sample", "a6e3c57dd...
1,991
1,121
import modules.database as db import modules.entity as entity category = 'Depuração' entity.Command.newcategory(category, 'Depuração',is_visible=False) async def exe(message, commandpar, bot): if commandpar != None: cont = commandpar.split() text = f'Executando: {cont[0]}' if le...
2,585
845
import os import signal import pytest from typing import Any from tomodachi.transport.amqp import AmqpTransport, AmqpException from run_test_service_helper import start_service def test_routing_key(monkeypatch: Any) -> None: routing_key = AmqpTransport.get_routing_key('test.topic', {}) assert routing_key == '...
2,877
1,257
# -*- coding: utf-8 -*- # # Enteletaor - https://github.com/cr0hn/enteletaor # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of con...
3,451
1,176
"""Selector and proactor event loops for Windows.""" from . import events from . import selector_events from . import windows_utils __all__ = ['SelectorEventLoop', 'DefaultEventLoopPolicy', ] class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): """Windows version of selec...
628
160
import random import time def send_bytes(con, channel, msg): con.send((f'PRIVMSG #{channel} : {msg}\r\n').encode('utf-8')) def sync_fn(con, channel, epoch, user, msg): pass def async_fn(con, channel, epoch, user, msg): if msg.startswith('!8ball'): answer_list = [ 'it is certain', ...
1,110
339
import logging from configuration.config import LOGGING_LEVEL from alexa_handlers.AlexaForRFXHandler import AlexaForRFXHandler """ Main entry point for the Lambda function. """ logging.basicConfig(format='%(asctime)s %(message)s') logging.getLogger().setLevel(LOGGING_LEVEL) def lambda_handler(event, context): ...
518
175
from django.contrib import admin import nfsmain.models # Register your models here. admin.site.register(nfsmain.models.Organisation) admin.site.register(nfsmain.models.Speech) admin.site.register(nfsmain.models.Interview) admin.site.register(nfsmain.models.Event)
265
86
# wow. such script. many calculation. wow. # let's do some operations and save the results in variables a=20 + 22 b=2077 - 93 c=578 * 4 d=1332/2 e=16**2 print(a, b, c, d, e) # tell the computer to show us the values of each variable
236
102
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'modify_env.ui', # licensing of 'modify_env.ui' applies. # # Created: Wed Dec 25 11:08:05 2019 # by: pyside2-uic running on PySide2 5.13.2 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWi...
3,384
1,139
from django.db import models # TODO: from django.contrib.gis.db.models import RasterField from companies.models import Company class Facility(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name='Компания') name = models.CharField(max_length=200, verbose_name='Наименова...
593
200
#Crie um programa que vai gerar cinco números aleatórios e colocar em um tupla #Depois, mostra a listagem de números gerados e tambem indique o menor e o maior valor que estão na tupla from random import randint n = (randint(1,10),randint(1,10),randint(1,10),randint(1,10),randint(1,10)) print(f'Sorteei os valores ...
421
162
# -*- coding: utf-8 -*- # Author: pistonyang@gmail.com import argparse import os import mxnet as mx import sklearn import numpy as np from mxnet import gluon, nd from mxnet.gluon.data import DataLoader from mxnet.gluon.data.vision import transforms from gluonfr.model_zoo import get_model from gluonfr.data import get_r...
5,070
1,746
"""Read the current state of Xbox Controllers""" from ctypes import * import pandas as pd from time import time_ns # Xinput DLL try: _xinput = windll.xinput1_4 except OSError as err: _xinput = windll.xinput1_3 class _xinput_gamepad(Structure): """CType XInput Gamepad Object""" _fields_ = [ ("...
7,043
2,221
#!/usr/bin/env python import os, sys, logging, tempfile new_path = [ os.path.join( os.getcwd(), "lib" ), os.path.join( os.getcwd(), "test" ) ] new_path.extend( sys.path[1:] ) sys.path = new_path log = logging.getLogger() log.setLevel( 10 ) log.addHandler( logging.StreamHandler( sys.stdout ) ) from galaxy import egg...
31,470
7,769
""" .. currentmodule:: clifford.taylor_expansions ===================================================== taylor_expansions (:mod:`clifford.taylor_expansions`) ===================================================== .. versionadded:: 1.4.0 This file implements various Taylor expansions for useful functions of multivecto...
4,433
1,523
from flask import Flask, render_template, redirect # from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy # bootstrp = Bootstrap() db = SQLAlchemy()
175
51
import json import scrapy import time import requests from ..items import TecentItem class TencentSpider(scrapy.Spider): name = 'tencent' allowed_domains = ['careers.tencent.com'] first_url = 'https://careers.tencent.com/tencentcareer/api/post/Query?timestamp={}&countryId=&cityId=&bgIds=&productId=&cate...
2,521
829
import argparse def ad1para(): parser = argparse.ArgumentParser(description="PyTorch DeeplabV3Plus Training") parser.add_argument('--train_path', type=str, default='E:/lab2_train_data.h5', help='the path of train data') parser.add_argument('--val_path', type=str, default='...
2,365
743
# -*- coding: utf-8 -*- """ Created on Fri Oct 8 09:04:27 2021 @author: @Daniel03 """ from watex.viewer.plot import QuickPlot # path to dataset # data_fn = 'data/geo_fdata/BagoueDataset2.xlsx' data_fn ='data/geo_fdata/main.bagciv.data2.csv' # set figure title fig_title= '`sfi` vs`ohmS|`geol`' # list of feature...
837
326
from django.conf.urls import url from . import views app_name = 'customer' urlpatterns = [ # url(r'^$', views.index, name='index'), url(r'^fooditems/(?P<shop_id>[0-9]+)/$', views.fooditems, name="fooditems"), url(r'^buyitem/(?P<fooditem_id>[0-9]+)/$', views.buy_fooditem, name="buy_fooditem") ]
309
133
__title__ = "simulation" __author__ = "murlux" __copyright__ = "Copyright 2019, " + __author__ __credits__ = (__author__, ) __license__ = "MIT" __email__ = "murlux@protonmail.com" # Global imports from enum import Enum from typing import Any, Dict from playground.messaging.flow import Flow, flow_from_json from playgr...
2,149
629
from rest_framework.routers import DefaultRouter from intask_api.tasks.views import TaskViewSet, TaskUserViewSet router = DefaultRouter() router.register(r'tasks', TaskViewSet, basename='tasks') router.register(r'tasks/(?P<task_id>[0-9]+)/users', TaskUserViewSet, basename='task-users') urlpatterns = router.urls
314
99
import pandas as pd from pymongo import MongoClient from MongoDB.marc import Marc import re import sys class Mongo: tag_mongodb_connection_uri = 'MONGODB_CONNECTION_URI' tag_mongodb_user = 'MONGODB_USER' tag_mongodb_password = 'MONGODB_PASSWORD' tag_mongodb_database = 'MONGODB_DATABASE' tag_mongod...
5,413
1,580
#!/usr/bin/env python3 import rospy import numpy as np import math import time from sensor_msgs.msg import JointState from std_msgs.msg import Float32, Float32MultiArray, Bool, Header from robot3_18c1054.msg import HandClose from robot3_18c1054.srv import GetHandState, GetHandStateResponse, GetInitTime, GetInitTimeRes...
5,673
2,729
# # Copyright (c) 2019-2020, NVIDIA CORPORATION. # # 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 ag...
6,980
2,555
import json import logging from django.db.models import Q from core.forms import ExternalRecordForm, ExternalRecordRelationForm from .constants import ErrorConstants from api.helpers import FormHelpers from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import sta...
13,768
3,545
from random import randint, choice from time import sleep print('_' * 40) print('Vou pensar em um número entre 0 e 10.\n') print('PROCESSANDO...') sleep(3) print('pronto!') sleep(0.5) n = int(input('Em que número eu pensei? ')) print('-' * 80) sleep(2) x = randint(0, 10) cont = 0 while n != x: if n < x: n...
584
257
# Generated by Django 2.0.2 on 2018-04-28 16:31 import core.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('cinfo', '0002_test_data'), ] operations = [ migrations.CreateModel( ...
6,142
1,884
from abc import ABC, abstractmethod from collections import OrderedDict from os import mkdir from os.path import exists, join from typing import Optional, Callable, get_type_hints, Dict import requests from cardbuilder.common.util import dedup_by, retry_with_logging from cardbuilder.exceptions import CardBuilderUsage...
8,409
2,421
#!/usr/bin/env python # -*- python -*- #BEGIN_LEGAL # #Copyright (c) 2020 Intel Corporation # # 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-...
19,912
6,652
#! /usr/bin/python #Copyright 2008, Meka Robotics #All rights reserved. #http://mekabot.com #Redistribution and use in source and binary forms, with or without #modification, are permitted. #THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS #"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDI...
1,638
688
valor = float(input('Insira o valor do produto: ')) desconto = float(input('Insira o vlaor do deaconto: ')) novo_valor = valor - (valor * (desconto / 100)) print(f'O novo valor com {desconto}% de desconto é {novo_valor:.2f}')
229
100
import os import time from expects import expect, have_key, contain, have_keys, be_empty, equal from mamba import it, before, description from sdcclient.monitor import EventsClientV1 from specs import be_successful_api_call with description("Events v1", "integration") as self: with before.all: self.clien...
2,271
701
from rest_framework.exceptions import APIException __author__ = "Mihail Butnaru" __copyright__ = "Copyright 2020, All rights reserved." class APPServerError(APIException): status_code = 500 default_detail = "Service temporarily unavailable, contact the administrator" default_code = "internal_server_error...
322
97
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2016 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Creates binary images from input files controlled by a description # from collections import OrderedDict import os import sys import tools import command import elf from image import Image import state...
6,771
1,822
class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: years_mapped = dict() # Map each person = O(n) # First bottleneck is having to map every year out which increases processing time # The second is also here since we use additional storage to account f...
2,683
761
# -*- coding: utf-8 -*- """ Project : Deep-Learning-in-Action File : Vit.py Description : 论文题目: An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale 论文地址: https://arxiv.org/abs/2010.11929 Author : xingximing.xxm Date : 2021/7/11 11:36 AM """ import torch fr...
5,027
1,910
import subprocess import re import smtplib from email.message import EmailMessage command_output = subprocess.run(["netsh", "wlan", "show", "profiles"], capture_output=True)\ .stdout.decode('Windows-1251') profile_names = (re.findall("All User Profile : (.*)\r", command_output)) wifi_list = list() if len(pr...
1,677
554
import gspread import time gc = gspread.service_account(filename='creds.json') sheetKey = "<insert shet key here>" wb = gc.open_by_key(sheetKey) localtime = time.asctime() newSheetName = f'XY on {localtime}' worksheet = wb.sheet1 scoreSheet = worksheet.duplicate(insert_sheet_index=1, new_sheet_name=newSheetName) #ma...
3,518
1,510
import glob import os import numpy as np from io import BytesIO from tqdm import tqdm import bcolz import platform MAX_SEQUENCE_LENGTH = 700 def filter_input_files(input_files): disallowed_file_endings = (".gitignore", ".DS_Store") return list(filter(lambda x: not x.endswith(disallowed_file_endings), input_f...
3,538
1,206
import grpc from stfsclient.tensorflow_serving import model_pb2 from stfsclient.tensorflow_serving import get_model_metadata_pb2, predict_pb2 from stfsclient.tensorflow_serving import get_model_status_pb2, model_management_pb2 from stfsclient.tensorflow_serving import prediction_service_pb2_grpc from stfsclient.tensor...
12,046
3,491
import unittest from metropolis.core.serializer import DefaultMessageSerializer from metropolis.core.serializer import JsonMessageSerializer class TestDefaultMessageSerializer(unittest.TestCase): def test_default_serializer_should_returns_bytes_msg(self): msg = 'hello' encoded = DefaultMessageSer...
1,058
300
#! /bin/python """Calculate provisioned space""" from __future__ import division import sys import subprocess import json import functools import multiprocessing import configparser from pprint import pprint from math import ceil from pyzabbix import ZabbixMetric, ZabbixSender from pyzabbix_socketwrapper import PyZa...
5,704
1,860
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright(c) 2019 Nippon Telegraph and Telephone Corporation # Filename: em_monitor.py ''' EM Monitoring Module for RA ''' import sys import os import time from ncclient import manager from ncclient import transport from ncclient import operations USERNAME = None PASSWO...
4,905
1,425
#functions: #to get the dependencies create a conda environment: #conda create --name live_cnn keras ipython opencv scikit-learn #note that the dim ordering here is the theano one - it's faster on CPU. #TODO: do some detection/ bounding box CNN's? import time import os import cv2 import numpy as np from keras.models...
6,307
2,173
#!/usr/bin/python3 """ State Controller Module """ import subprocess from robotarm.controllers import proxy_url import requests import pathlib import psutil BASE_DIR = pathlib.Path(__file__).resolve().parent.parent #print(BASE_DIR) class APIServiceController(): """ contolls api service actions: h...
2,292
619
"""Constants for the Jellyfin integration tests.""" from typing import Final from jellyfin_apiclient_python.connection_manager import CONNECTION_STATE TEST_URL: Final = "https://example.com" TEST_USERNAME: Final = "test-username" TEST_PASSWORD: Final = "test-password" MOCK_SUCCESFUL_CONNECTION_STATE: Final = {"Stat...
597
222
from .imports import * #Put all views that don't belong elsewere here @login_required def index(request): return render(request, 'LibreBadge/home.html', context = {})
175
56
from firepack.fields import IntField, StrField from firepack.service import FireService from firepack.errors import SkipError, ValidationError CRAWLED_DB = [] def page_name_validator(name, value): if not value.endswith('.html'): raise ValidationError(name, 'I only know html pages!') class Crawler(Fire...
1,266
404
""" NodePath for Jam-o-Drum model @author: Ben Buchwald <bb2@alumni.cmu.edu> Last Updated: 11/29/2005 @var DRUMPAD_RADIUS: constant representing the radius of the drumpad as a percentage of the radius of the table @type DRUMPAD_RADIUS: float @var SPINNER_RADIUS: constant representing the radius o...
10,460
3,185
import pytest from unittest.mock import patch from ..api import * from ..alarm import Alarm from .. import AlarmClockApp from ..alarm_states import Disabled, Enabled class AlarmClockMock(AlarmClockApp): auto_store = False def __init__(self, alarms=None, off=False, snooze=False): super().__init__() ...
2,927
1,147
"Functions implementing FilePage editing" from ... import ValidateError, FailPage, ServerError from ....ski.project_class_definition import SectionData from ... import skilift from ....skilift import editpage from .. import utils def retrieve_edit_filepage(skicall): "Retrieves widget data for the edit file...
4,519
1,446
""" Django settings for django_resto project. Generated by 'django-admin startproject' using Django 1.11.3. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ impo...
5,583
2,131
#!/usr/bin/env python # Copyright (C) 2015 University of Southern California and # Nan Hua # # Authors: Nan Hua # # 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, eith...
5,710
1,987
from radixlib.api_types.identifiers import ( TransactionIdentifier, ValidatorIdentifier, NetworkIdentifier, AccountIdentifier, TokenIdentifier, StateIdentifier, ) from radixlib.actions import ActionType from radixlib.network import Network import radixlib as radix import requests from typing im...
23,313
5,532
#!/usr/bin python3 STATS_QUERY = """\ INSERT INTO covid19.release_stats (release_id, record_count) SELECT ts.release_id AS id, COUNT(*) AS counter FROM covid19.time_series AS ts WHERE ts.partition_id = ANY('{partitions}'::VARCHAR[]) GROUP BY ts.release_id ON CONFLICT ( release_id ) DO UPDATE SET record_count = EXC...
1,127
367
# -*- coding: utf-8 -*- import os import sys from shutil import rmtree from setuptools import setup, find_packages, Command from filometro import __version__ from filometro import __author__ here = os.path.abspath(os.path.dirname(__file__)) class PublishCommand(Command): """Support setup.py publish.""" d...
3,109
983
from typing import List, Tuple from .._device import DeviceControlInterface, DeviceDetails from ..data.device import Device, DeviceWifi class DummyDeviceControl(DeviceControlInterface): @property def show_args(self): return self._show_args @property def connect_args(self): return self...
2,953
906
""" Example 2.6 (PAV, seq-PAV, revseq-PAV). From "Multi-Winner Voting with Approval Preferences" by Martin Lackner and Piotr Skowron https://arxiv.org/abs/2007.01795 """ from abcvoting import abcrules from abcvoting.preferences import Profile from abcvoting import misc from abcvoting.output import output, DETAILS ou...
801
346
import asyncio import discord from discord.ext import commands import base64 import binascii import re from Cogs import Nullify def setup(bot): # Add the bot and deps settings = bot.get_cog("Settings") bot.add_cog(Encode(bot, settings)) class Encode: # Init with the bot reference def __init__(self, bot, set...
7,605
3,127
#!/usr/bin/env python3 class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' def class_objects(): print(MyClass.i) print(MyClass.f) print(MyClass.f(None)) x = MyClass() class Complex: def __init__(self, realpart, imagpart): ...
1,968
720
from itertools import zip_longest def strict_zip(*sequences): sentinel = object() for tup in zip_longest(*sequences, fillvalue=sentinel): if sentinel in tup: raise ValueError('value out of range') yield tup
245
76
from pyramid.response import Response def my_view(request): return { 'user': { 'friendly_name': 'Carlos Andres Lopez'}} def home(request): return Response(''' <div style="margin: 200px"> <form action="login/facebook" method="POST"> <input type="submit" value="Authenticate With Facebook"...
1,435
436
import base64 import aiohttp from io import BytesIO from nonebot import log # 图片转base64 async def pic_2_base64(url: str) -> str: async def get_image(pic_url: str): timeout_count = 0 while timeout_count < 3: try: timeout = aiohttp.ClientTimeout(total=10) ...
1,664
531
from __future__ import print_function import sys import socket import numpy as np from PIL import Image try: import cPickle as pickle except ImportError: import pickle from datetime import datetime import threading from client_send_message import MessageSender from color_classifier import detect_color import ...
2,972
997
from __future__ import absolute_import from blazeform.form import Form class TestForm(Form): def __init__(self): Form.__init__(self, 'withactionform', action='/submitto') self.add_text('text', 'Text')
223
69
# coding=utf-8 """ 'input_matrix.py' script hosts the following functions: (1) collect CEA inputs (2) collect CEA outputs (demands) (3) add delay to time-sensitive inputs (4) return the input and target matrices """ from math import sqrt import pandas as pd from legacy.metamodel.nn_generator import ra...
4,332
1,482
import feedparser import models import time import datetime as dt from bs4 import BeautifulSoup VALID_IMAGE_ATTRIBUTES = ('alt', 'title', 'src') def fetch(url): f = feedparser.parse(url) feed = models.Feed() feed.link = url feed.website = f.feed.get('link') feed.title = f.feed.get('title') f...
1,512
474
""" https://www.hackerrank.com/challenges/whats-your-name/problem Input: Ross Taylor Output: Hello Ross Taylor! You just delved into python. """ def print_full_name(first, last): print(f'Hello {first} {last}! You just delved into python.') if __name__ == '__main__': first_name, last_name = 'Ross', 'Taylor...
365
138