text
string
size
int64
token_count
int64
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/4 0004 2:09 # @Author : Gpp # @File : obtain_url.py from app.web import api from flask_restful import Resource from flask import make_response, send_from_directory, jsonify from app.helper.encrypt import two_encrypting from app.crud.proxy_crud i...
1,318
473
import logging from argparse import ArgumentParser from dotenv import load_dotenv, find_dotenv from .config import load from .core.heart import start_loop logger = logging.getLogger(__name__) try: load_dotenv(find_dotenv()) except Exception as ex: logger.error("Error while loading .env: '{}'. Ignoring.".fo...
920
284
#!/usr/bin/env python # coding=utf-8 import glob import click import os import json import datetime import re import csv from requests.exceptions import ConnectionError from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \ EWSDateTime, EWSTimeZone, Configuration, NT...
4,113
1,677
""" Purpose: Reads the hourly ACCESS files pulled from the BoM OPeNDAP site and concatenates them into a single file. This script file takes a control file name on the command line. The control file lists the sites to be processed and the variables to be processed. Normal usage is to process all files in a monthl...
29,479
10,168
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import login from django.shortcuts import redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from Aluno.views.utils import aluno_exist from annoying.decorators import render_to from django.contrib...
639
221
try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse from django.conf import settings DEFAULT_NOSCR_ALLOWED_TAGS = 'strong:title b i em:title p:title h1:title h2:title h3:title h4:title h5:title ' + \ 'div:title span:title ol ul li:title a:href:title:rel img:src:alt:title dl td...
2,771
956
from __future__ import division import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import matplotlib.ticker as mticker import gsd import gsd.fl import numpy as np import os import sys import datetime import time import pickle from shutil import copyfile import inspect import md_tools...
15,054
5,732
import argparse import staticconf from backuppy.args import add_name_arg from backuppy.args import subparser from backuppy.manifest import lock_manifest from backuppy.manifest import Manifest from backuppy.stores import get_backup_store def main(args: argparse.Namespace) -> None: staticconf.YamlConfiguration(ar...
1,609
480
from abc import abstractmethod, ABCMeta import csv from datetime import datetime import funcy as fy from OnePy.barbase import Current_bar, Bar from OnePy.event import events, MarketEvent class FeedMetabase(metaclass=ABCMeta): dtformat = "%Y-%m-%d %H:%M:%S" tmformat = "%H:%M:%S" timeindex = None de...
6,349
2,118
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake, tools from conans.errors import ConanException import os import shutil def sort_libs(correct_order, libs, lib_suffix='', reverse_result=False): # Add suffix for correct string matching correct_order[:] = [s.__add__(lib_suffix)...
4,912
1,520
import pytest from fastjsonschema import JsonSchemaException exc = JsonSchemaException('data must be null', value='{data}', name='data', definition='{definition}', rule='type') @pytest.mark.parametrize('value, expected', [ (0, exc), (None, None), (True, exc), ('abc', exc), ([], exc), ({}, exc...
416
140
import boto3 import json def init(ACCESS_KEY, SECRET_KEY): return boto3.client(service_name='comprehend', region_name="us-west-2", aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) def get_entities(client, title): return client.detect_entities(Text=title, LanguageCode='en').get('Entitie...
644
236
def checkrot(str1,str2): if len(str1)==len(str2): str3=str1+str1 ad=str3.__contains__(str2) if ad==True: print("it is right rotate") else: print("It is not right rotate ") else: print("It is invalid string.Out of range") def main(): str1=input(" Enter the first String : ") str2=input("Enter the s...
394
166
import discord from discord.ext import commands from discord import Embed, Permissions from Util import logger import os import database # Import the config try: import config except ImportError: print("Couldn't import config.py! Exiting!") exit() # Import a monkey patch, if that exists try: import mo...
6,781
1,962
# # This file is part of the Ingram Micro CloudBlue Connect EaaS Extension Runner. # # Copyright (c) 2021 Ingram Micro. All Rights Reserved. # class EaaSError(Exception): pass class MaintenanceError(EaaSError): pass class CommunicationError(EaaSError): pass class StopBackoffError(EaaSError): pass
320
108
from django.conf.urls import url from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ from django.views.generic import TemplateView view = TemplateView.as_view(template_name='dummy.html') app_name = 'account' urlpatterns = i18n_patterns( url(_(r'^register...
354
127
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import OrderedDict from moz_sql_parser import parse as parse_sql import pyparsing import re from six.moves.urllib import parse FROM_REGEX = re.compile...
2,004
673
# -*- coding:utf-8 -*- # Bot2Human # # Replaces messages from bots to humans # typically used in channels that are connected with other IMs using bots # # For example, if a bot send messages from XMPP is like `[nick] content`, # weechat would show `bot | [nick] content` which looks bad; this script # make weecaht displ...
5,676
2,038
import xlrd import pandas as pd from openpyxl import load_workbook from xlrd import open_workbook import nltk from nltk.tree import Tree from nltk.parse.generate import generate from nltk.tree import * import os from nltk.tokenize import word_tokenize from nltk.tokenize import sent_tokenize import xml.etree....
10,713
5,963
from RFEM.initModel import Model, clearAtributes class Instersection(): def __init__(self, no: int = 1, surface_1: int = 1, surface_2: int = 2, comment: str = '', params: dict = None, model = Model): # Cl...
1,013
259
#!/usr/bin/env python # coding: utf-8 import os import sys import string import unittest from uuid import uuid4 from unittest import mock from random import random, randint from datetime import datetime, timedelta pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa sys.path.insert(0, pkg...
6,760
2,131
#!/usr/local/bin/python # coding=utf-8 # Headless firefox title test for jenkins build. intro=""" ---------------------------------------------------------------- File : ches_prod_test_titles_headless.py Description : Headless firefox title test for ches prod sites. Author : Sherri Li --------------------...
11,035
3,265
import numba import time from . import glob_var from . import structures # for some reason, caching of this function fails the run on Columbia HPC and it doesn't really affect the speed # since it only needs to compile once but it's getting called so many times @numba.jit(cache=False, nopython=True, nogil=True) def...
4,579
1,421
"""Basic cleanup on lightcurves (trimming, sigma-clipping).""" import logging import numpy as np import matplotlib.pyplot as plt import k2spin.utils as utils from k2spin import detrend def trim(time, flux, unc_flux): """Remove infs, NaNs, and negative flux values. Inputs ------ time, flux, unc_flux...
4,574
1,756
a=int(input('enter a:')) b=int(input('enter b:')) c=int(input('enter c:')) min_value= a if a<b and a<c else b if b<c else c print(min_value)
140
62
import asyncio import functools import time def _log_func_timing(f, args, kw, sec: float): print("func: %r args: [%r, %r] took: %2.4f sec" % (f.__name__, args, kw, sec)) def timing(f): "Decorator to log" if asyncio.iscoroutinefunction(f): @functools.wraps(f) async def wrap(*args, **kw)...
758
270
#!/usr/bin/env python # coding: utf-8 # BEGIN --- required only for testing, remove in real world code --- BEGIN import os import sys THISDIR = os.path.dirname(os.path.abspath(__file__)) APPDIR = os.path.abspath(os.path.join(THISDIR, os.path.pardir, os.path.pardir)) sys.path.insert(0, APPDIR) # END --- required only f...
715
260
import os import sys import io import time import zipfile import pydicom import numpy as np import scipy.interpolate import numba_interpolate from skimage import filters import nrrd import cv2 c_out_pixel_spacing = np.array((2.23214293, 2.23214293, 3.)) c_resample_tolerance = 0.01 # Only interpolate voxels furth...
27,511
10,046
# From http://julip.co/2012/05/arduino-python-soundlight-spectrum/ # Python 2.7 code to analyze sound and interface with Arduino import pyaudio # from http://people.csail.mit.edu/hubert/pyaudio/ import serial # from http://pyserial.sourceforge.net/ import numpy # from http://numpy.scipy.org/ import audioop import ...
3,285
1,177
# Copyright (c) 2021 NVIDIA Corporation. 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 applica...
6,422
1,921
""" throughput dialog """ import tkinter as tk from tkinter import ttk from typing import TYPE_CHECKING from core.gui.dialogs.colorpicker import ColorPickerDialog from core.gui.dialogs.dialog import Dialog from core.gui.themes import FRAME_PAD, PADX, PADY if TYPE_CHECKING: from core.gui.app import Application c...
3,996
1,294
from django.test.client import BOUNDARY from api.tests.unit_tests.utils import * class CardTest(APITestCase): # url = reverse('card-detail') def setUp(self): hook_init_APITestCase(self) self.test_workspace = Workspace.objects.create( name='test_workspace', # default va...
5,488
1,679
import socket def getch(): # define non-Windows version import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) ret...
1,412
582
from utils.security.auth import AccountAuthToken import falcon, uuid, datetime from routes.middleware import AuthorizeResource from utils.base import api_validate_form, api_message from utils.config import AppState class ProcessTag: def __init__(self) -> None: self._token_controller = AccountAuthToken('...
4,278
1,289
class Human(): def __init__(self, name="Human"): self.name = name def action(self, game): safe_input = False while not safe_input: pos = input("choose a position: ") if pos == "draw": game.draw() elif pos == "exit": imp...
895
240
#!/Usr/bin/env python """ Akash and Vishal are quite fond of travelling. They mostly travel by railways. They were travelling in a train one day and they got interested in the seating arrangement of their compartment. The compartment looked something like So they got interested to know the seat number facing them ...
2,338
830
def golf(p): return len(p)>9 and p!=p.lower() and p!=p.upper() and any('0'<=l and l<='9' for l in p)
101
45
#!/usr/bin/env python3 import matplotlib matplotlib.use('pgf') import matplotlib.pyplot as plt import numpy as np from multi_isotope_calculator import Multi_isotope import plotsettings as ps plt.style.use('seaborn-darkgrid') plt.rcParams.update(ps.tex_fonts()) def main(): plot() #figure5() def figure1(): ...
3,149
1,287
class Animals: def comer(self): print("Comiendo") def dormir(self): print("Durmiendo") class Perro: def __init__(self, nombre): self.nombre = nombre def comer(self): print("Comiendo") def dormir(self): print("Durmiendo") def ladrar(self): print("Ladrando") print("----------------------...
497
187
import random import torch from torch import nn from torch.nn import functional as F class Encoder(nn.Module): def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout): super().__init__() self.input_dim = input_dim self.emb_dim = emb_dim self.hid_dim = hid_dim se...
3,103
1,064
from fman import DirectoryPaneCommand, show_alert import os import zipfile from fman.url import as_human_readable from fman.url import as_url def zipdir(rootZip, path, ziph): numf = 0 # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.w...
1,753
582
import boto3 client = boto3.client('rds') def lambda_handler(event, context): target_db_cluster_identifier=event['TargetDBClusterIdentifier'] payload = event.copy() try: response = client.describe_db_clusters(DBClusterIdentifier=target_db_cluster_identifier) payload...
626
182
import re from Smell import Smell from SmellCategory import SmellCategory from Reference import Reference SMELL = "\[smell\]" SMELL_ID = "\[smell-id\]" SMELL_NAME = "\[smell-name\]" SMELL_END = "\[smell-end\]" SMELL_DES = "\[smell-description\]" SMELL_AKA = "\[smell-aka\]" SMELL_CATEGORY = "\[smell-category\]" SMELL_S...
6,545
2,085
from YorForger import REDIS # AFK def is_user_afk(userid): rget = REDIS.get(f"is_afk_{userid}") return bool(rget) def start_afk(userid, reason): REDIS.set(f"is_afk_{userid}", reason) def afk_reason(userid): return strb(REDIS.get(f"is_afk_{userid}")) def end_afk(userid): REDIS.delete(f"is_af...
414
188
import threading class mini_event: BUTTON_DOWN = 1 BUTTON_UP = 2 BUTTON_HOLD = 3 subscribers = { BUTTON_DOWN: [], BUTTON_UP : [], BUTTON_HOLD: [] } trigger_hold_stop = False # This value should be turned to True if the hold event callback needs to be stopped. def add_subscriber( self, callba...
859
291
# -*- coding: utf-8 -*- """Various utility functions for handling geometry etc.""" import math from statistics import mean from typing import Tuple, Union, Iterable, Generator, Mapping import logging MODULE_MATPLOTLIB_AVAILABLE = True try: import matplotlib.pyplot as plt import matplotlib.lines as lines exce...
13,225
5,291
#!/usr/bin/env python # Copyright 2020 Richard Maynard (richard.maynard@gmail.com) # # 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...
7,748
2,481
import wx from wx.lib.agw.floatspin import FloatSpin from shs.input.fdf_options import ChoiceLine, MeasuredLine, NumberLine, ThreeNumberLine try: from geom import Geom except ImportError: from shs.geom import Geom class Bravais(ChoiceLine): label = 'Composition' choices = ['BCC', 'FCC', 'SC'] o...
3,777
1,417
#!/usr/bin/env python ######################################### # Title: Rocksat Data Server Class # # Project: Rocksat # # Version: 1.0 # # Date: August, 2017 # # Author: Zach Leffke, KJ4QLP # # Comment: Initial Version # ###...
5,377
1,758
#!/usr/bin/env python3 import datetime import time import os import matplotlib.pyplot as plt import matplotlib.dates as md import numpy as np class handle_data: data_file = "./data/data.log" data_list = [] def __init__(self): pass def insert_data(self, timestamp, temp, state_onoff, state_light, state_cool...
3,932
1,778
import math def fuel_needed(mass): return math.floor(int(mass)/3 - 2) def fuel_needed_recursive(mass): fuel_needed_i = fuel_needed(mass) if (fuel_needed_i <= 0): return 0 return fuel_needed_i + fuel_needed_recursive(fuel_needed_i) total_fuel = 0 total_fuel_recursive = 0 with open("input.txt"...
555
218
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt4 (Qt v4.8.7) # # WARNING! All changes made in this file will be lost! from PySide import QtCore qt_resource_data = "\ \x00\x00\x03\x97\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x16\x0...
45,634
42,514
# Created by Xinyu Zhu on 2021/6/6, 21:08 from turtle import Turtle import turtle def draw_rectangle(turtle: Turtle, llx, lly, width, height): turtle.up() turtle.goto(llx, lly) turtle.begin_fill() turtle.down() turtle.goto(llx + width, lly) turtle.goto(llx + width, lly + height) turtle.go...
581
279
from __future__ import absolute_import, division from keras.layers import * from deform_conv.layers import ConvOffset2D def get_cnn(): inputs = l = Input((None, None, 1), name='input') # conv11 l = Conv2D(32, (3, 3), padding='same', name='conv11')(l) l = Activation('relu', name='conv11_relu')(l) ...
2,439
1,010
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from unit.common import Unit from helpers.eventually import eventually from helpers.shell import execute import string import time import os class LedgerRest(Unit): def __init__(self): (code, result) = execute([ "systemctl", "start", 'ledger-rest' ], si...
1,861
668
from pythonneat.neat.Species import Species import pythonneat.neat.Speciation as Speciation import pythonneat.neat.utils.Parameters as Parameters current_genomes = [] def add_genome(genome): """Adds genome to the species list based on its compatability distance to already existing species Inputs: ge...
1,431
464
from __future__ import absolute_import # flake8: noqa # import apis into api package from container_service_extension.pksclient.api.cluster_api import ClusterApi from container_service_extension.pksclient.api.plans_api import PlansApi from container_service_extension.pksclient.api.profile_api import ProfileApi from c...
387
112
""" This is a simple application for sentence embeddings: clustering Sentences are mapped to sentence embeddings and then agglomerative clustering with a threshold is applied. """ from sentence_transformers import SentenceTransformer from sklearn.cluster import AgglomerativeClustering import numpy as np embedder = Se...
1,733
542
from netapp.netapp_object import NetAppObject class VserverAggrInfo(NetAppObject): """ Assigned aggregate name and available size. """ _aggr_availsize = None @property def aggr_availsize(self): """ Assigned aggregate available size. Attributes: non-creatable, non-mo...
1,364
431
#Learning Python import os list = [1,2,3] ##using list as a queue print(list) list.pop(0) print(list) list.append(5) print(list)
133
60
import pandas as pd wine = pd.read_csv('https://bit.ly/wine-date') # wine = pd.read_csv('../data/wine.csv') print(wine.head()) data = wine[['alcohol', 'sugar', 'pH']].to_numpy() target = wine['class'].to_numpy() from sklearn.model_selection import train_test_split train_input, test_input, train_target, test_target ...
3,199
1,280
# Module to build a potential landscape import numpy as np def gauss(x,mean=0.0,stddev=0.02,peak=1.0): ''' Input: x : x-coordintes Output: f(x) where f is a Gaussian with the given mean, stddev and peak value ''' stddev = 5*(x[1] - x[0]) return peak*np.exp(-(x-mean)**2/(2*stddev**2)) d...
1,016
395
from sys import stdin input = stdin.readline from collections import deque N, Q = map(int, input().split()) tree = [[] for _ in range(N + 1)] level = [0] * (N + 1) for _ in range(N - 1): a, b = map(int, input().split()) tree[a].append(b) tree[b].append(a) visited = [False] * (N + 1) def bfs(st): glo...
878
336
""" nested field implements marshmallow field for objectfactory nested objects """ # lib import marshmallow # src from .serializable import Serializable from .factory import create class NestedFactoryField( marshmallow.fields.Field ): def __init__( self, field_type=None, **kwargs ): super().__init__( ...
1,614
435
from wasabi import msg from ._util import app, setup_cli # noqa: F401 # These are the actual functions, NOT the wrapped CLI commands. The CLI commands # are registered automatically and won't have to be imported here. from .download import download # noqa: F401 from .info import info # noqa: F401 from .package imp...
1,709
570
from direct.showbase.ShowBase import ShowBase class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Load the environment model. self.environ = self.loader.loadModel("models/environment") # Reparent the model to render. self.environ.reparentTo(self.render) ...
490
160
#!/usr/bin/env python3 # Copyright (C) 2017-2020 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
16,104
6,308
import json def get_all_pets(): pets = read_from_file() pets_in_store = [] for k, v in pets.items(): current_pet = {"id": k, **v} pets_in_store.append(current_pet) return pets def remove_pet(id): pets = read_from_file() del pets[id] write_to_file(pets) def update_pet(i...
998
412
def mango(quantity, price): return (quantity - quantity // 3) * price
73
22
import matplotlib.pyplot as plt import cv2 import imutils import pytesseract as pt from tkinter import * from tkinter import messagebox # ploting the images def plot_img(img1, img2, title1="", title2=""): fig = plt.figure(figsize=[5, 5]) # axis 1 ax1 = fig.add_subplot(121) ax1.imshow(img1...
5,582
2,161
# -*- coding: utf-8 -*- """ Created on Fri May 18 22:15:35 2018 @author: Sumudu Tennakoon References: [1] https://www.ibm.com/watson/developercloud/natural-language-understanding/api/v1/ """ from watson_developer_cloud import NaturalLanguageUnderstandingV1, WatsonException, WatsonApiException from watson_developer_cl...
13,229
3,909
# -*- coding: utf-8 -*- # # Copyright (C) 2020 CERN. # Copyright (C) 2020 Northwestern University. # # Invenio-Drafts-Resources is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """Invenio Drafts Resources module to create REST APIs.""...
6,813
1,992
# Copyright 2020 Jacob D. Durrant # # 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 writ...
56,465
17,896
from visuanalytics.analytics.control.procedures.step_data import StepData from visuanalytics.analytics.transform.transform import transform def prepare_test(values: list, data, expected_data: dict, config=None): if config is None: config = {} step_data = StepData(config, "0", 0) step_data.insert_...
568
188
_base_ = [ '../_base_/models/resnet50.py', '../_base_/datasets/cancer_bs32_pil_resize.py', '../_base_/schedules/imagenet_bs256_coslr.py', '../_base_/default_runtime.py' ] model = dict( head=dict( num_classes=2, topk=(1,)) ) data = dict( train=dict( data_prefix='/data3/zzhang/tmp...
693
298
import logging import traceback from kubernetes.client.rest import ApiException from django.conf import settings import auditor from constants.jobs import JobLifeCycle from db.models.build_jobs import BuildJob from docker_images.image_info import get_tagged_image from event_manager.events.build_job import BUILD_JOB...
4,907
1,399
#coding=utf8 from uliweb.utils.pyini import * def test_sorteddict(): """ >>> d = SortedDict() >>> d <SortedDict {}> >>> d.name = 'limodou' >>> d['class'] = 'py' >>> d <SortedDict {'class':'py', 'name':'limodou'}> >>> d.keys() ['name', 'class'] >>> d.values() ['limodou', ...
9,587
3,862
import threading from queue import Queue from blessed import Terminal FPS = 60 class Game: """The top level class for the game""" def __init__(self, manager_cls: type): self.manager_cls = manager_cls def run(self) -> None: """The run method for the game, handling the TUI""" ter...
797
236
import logging import threading import flask from .requests import Request __all__ = ['Skill'] class Skill(flask.Flask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._sessions = {} self._session_lock = threading.RLock() def script(self, generator): ...
1,366
373
import logging from main.fileextractors.compressedfile import get_compressed_file from main.utilities.fileutils import dir_path from main.utilities.subtitlesadjuster import ArchiveAdjuster class FileExtractor: def __init__(self, subname, movfile): self.sn, self.mn = subname, movfile self.subzip = ...
1,227
381
import curses from get_json import get_json def body(screen): div = curses.newwin(curses.LINES - 2, curses.COLS, 1, 0) div.box() # draw border around container window # use a sub-window so we don't clobber the the container window's border. txt = div.subwin(curses.LINES - 5, curses.COLS - 4, 2, 2) ...
476
171
import sys, os, seaborn as sns, rasterio, pandas as pd import numpy as np import matplotlib.pyplot as plt sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from config.definitions import ROOT_DIR, ancillary_path, city,year attr_value ="totalpop" gtP = ROOT_DIR + "/Evaluation/{0}_groundT...
5,518
2,630
import abc from codepack.service.service import Service class DeliveryService(Service, metaclass=abc.ABCMeta): def __init__(self): super().__init__() @abc.abstractmethod def send(self, id, serial_number, item=None, timestamp=None): """send item""" @abc.abstractmethod def receive(...
562
166
import numpy as np import pytest import nengo from nengo.builder import Builder from nengo.builder.operator import Reset, Copy from nengo.builder.signal import Signal from nengo.dists import UniformHypersphere from nengo.exceptions import ValidationError from nengo.learning_rules import LearningRuleTypeParam, PES, BCM...
23,056
8,634
# coding: utf-8 """ joplin-web """ from django.conf import settings from django.http.response import JsonResponse from django.urls import reverse from joplin_api import JoplinApiSync from joplin_web.utils import nb_notes_by_tag, nb_notes_by_folder import logging from rich import console console = console.Console() ...
922
323
import numpy as np from django.core.management.base import BaseCommand from oscar.core.loading import get_classes StatsSpe, StatsItem, Test, Speciality, Item, Conference = get_classes( 'confs.models', ( "StatsSpe", "StatsItem", "Test", "Speciality", "Item", "Conference" ) ) class Command(BaseCo...
1,449
437
import torch import torch.nn as nn import torch.nn.functional as F from math import sqrt as sqrt import collections import numpy as np import itertools from ssd_project.utils.utils import * from ssd_project.utils.global_variables import * device = DEVICE class MultiBoxLoss(nn.Module): """ For our SSD we use a ...
6,403
2,056
import trio from kivy.config import Config Config.set('graphics', 'width', '1600') Config.set('graphics', 'height', '900') Config.set('modules', 'touchring', '') for items in Config.items('input'): Config.remove_option('input', items[0]) from glitter2.main import Glitter2App from kivy.tests.async_common import U...
1,574
488
from aiohttp import web from aiohttp import WSMsgType from Settings import log class WebSocket(web.View): async def get(self): ws = web.WebSocketResponse() await ws.prepare(self.request) self.request.app['websockets'].append(ws) async for msg in ws: if msg.type == WS...
589
171
import json import os def qald(in_folder, out_folder): train = json.load(open(os.path.join(in_folder, "qald-7-train-en-wikidata.json"))) test = json.load(open(os.path.join(in_folder, "qald-7-test-en-wikidata-withoutanswers.json"))) train_q = [] test_q = [] for qs in train["questions"]: fo...
2,056
797
import requests class RestException(Exception): """ Exception to catch REST API related exceptions. """ def __init__(self, *args: object) -> None: super().__init__(*args) def _execute_rest_request( url, http_method=None, accepted_status_code=None, files=None, params=None...
1,112
335
import pandas as pd import numpy as np def missing_dict(df): ''' Function to build a dictionary of indicators of missing information per feature INPUT: df: pandas dataframe with features, description, and values that mean "unknown" OUPUT: missing_dict: dictionary of values for "unkwon" pe...
9,696
3,144
# Criar uma base de dados. O usuário pode adicionar, excluir e listar clientes (que possuem id e nome). # *utilizar encapsulamento. class Clientes: def __init__(self): self.__lista = {} # Recomenda-se estritamente não modificar essa variável def adicionar_cliente(self, id, nome): if 'cliente...
1,133
390
""" Test utility functionality.""" import datetime import decimal import json import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest from mock import patch from ..utils import JSONSerializable, DatetimeDecimalEncoder class TestJSONSerializable(unittest.TestCase): ""...
2,321
696
# 264. Ugly Number II # # Write a program to check whether a given number is an ugly number. # # Ugly numbers are positive numbers whose prime factors only include # 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it # includes another prime factor 7. # # Note that 1 is typically treated as an ugly numbe...
18,859
17,115
# Copyright 2015 OpenStack Foundation # # 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 ...
3,563
1,091
from __future__ import annotations from coredis.response.callbacks import ResponseCallback from coredis.response.types import LibraryDefinition from coredis.response.utils import flat_pairs_to_dict from coredis.typing import Any, AnyStr, Mapping, Union from coredis.utils import EncodingInsensitiveDict class Function...
2,126
524
from models.tilemap import TileMap class EditorController: def __init__(self, view): self.view = view self.tilemap = TileMap() def place_tile(self, coord, ttype): self.tilemap.add_tile(coord, ttype) self.view.board.update_tiles({coord: ttype}) def place_spawn(self, coor...
885
315
from .BasePage import BasePage from src.Locators import LoginPage from src.Services.Faker.FakeDataGenerator import DataGenerator class Login(BasePage): def create_account(self): data = DataGenerator() self.select(LoginPage.CreateCustomer.title, 'Mr.') self.input(LoginPage.CreateCustomer.fi...
815
239
""" Copyright 2016 Disney Connected and Advanced Technologies Licensed under the Apache License, Version 2.0 (the "Apache License") with the following modification; you may not use this file except in compliance with the Apache License and the following modification to it: Section 6. Trademarks. is deleted and replace...
2,777
825