text
string
size
int64
token_count
int64
# coding: utf-8 sales= [255, 100, 353, 400] print len(sales) print sales[2] sales[2] = 100 print sales[2] # 含んでいるか否か print 100 in sales print 500 in sales # range print range(10) print range(3,10) print range(3,10,2)
219
123
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import coloredlogs import logging import json import itertools import shlex import time import queue import sys import os import collections import tempfile from jsonpath_ng import jsonpath, parse from .runner import AsyncRunner from .common import merge_p...
18,034
5,823
''' FuSeConv: Fully Separable Convolutions for Fast Inference on Systolic Arrays Authors: Surya Selvam, Vinod Ganesan, Pratyush Kumar Email ID: selvams@purdue.edu, vinodg@cse.iitm.ac.in, pratyush@cse.iitm.ac.in ''' import os import torch import wandb import random import argparse import torchvision import torch.nn as ...
8,346
2,845
import os.path from fabric.api import local, env from fabric.utils import fastprint from prezi.fabric.s3 import CommonTasks, S3Deploy, NoopServiceManager env.forward_agent = True env.user = 'publisher' env.roledefs = {'production': [], 'stage': [], 'local': []} class SingleVirtualenvS3Deploy(S3Deploy): def __in...
2,590
870
from __future__ import unicode_literals import warnings from django import get_version as get_django_version __title__ = "dj-stripe" __summary__ = "Django + Stripe Made Easy" __uri__ = "https://github.com/pydanny/dj-stripe/" __version__ = "0.5.0" __author__ = "Daniel Greenfeld" __email__ = "pydanny@gmail.com" __li...
706
270
import logging import os import time import numpy as np from autolamella.acquire import ( grab_images, save_reference_images, save_final_images, ) from autolamella.align import realign from autolamella.autoscript import reset_state def milling( microscope, settings, stage_setting...
10,283
3,076
import pygame from Robot import Robot class SlowRobot(Robot): moveState = -15 shootState = 0 def __init__(self, image, name): super().__init__(image, name) self.movingLeft = False self.movingRight = True self.movingUp = False self.movingDown = True def update(se...
2,210
610
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ---------- from typing import Iterable from itertools import zip_longest from .internal import TypeMatcher from .g import isinstanceof, issubclassof def match(args: (list, tuple), types: Iterable...
934
312
from aetherling.space_time.space_time_types import * from aetherling.space_time.nested_counters import * from aetherling.modules.ram_any_type import * from aetherling.modules.term_any_type import TermAnyType from aetherling.modules.mux_any_type import DefineMuxAnyType from aetherling.modules.map_fully_parallel_sequenti...
3,669
1,245
# Process two rose images by summing them together # FIN Laske kaksi ruusukuvaa yhteen # # Samuli Siltanen April 2021 # Python-käännös Ville Tilvis 2021 import numpy as np import matplotlib.pyplot as plt # Read in the images # FIN Lue kuvat levyltä im1 = plt.imread('../_kuvat/ruusu1.png') im2 = plt.imread('../_kuvat...
1,227
566
############################## # Copyright (C) 2009-2011 by # Dent Earl (dearl@soe.ucsc.edu, dent.earl@gmail.com) # Benedict Paten (benedict@soe.ucsc.edu, benedict.paten@gmail.com) # Mark Diekhans (markd@soe.ucsc.edu) # ... and other members of the Reconstruction Team of David Haussler's # lab (BME Dept. UCSC). # # ...
6,931
2,323
from django.contrib import admin from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from django.utils.html import format_html from datetime import date, datetime from django_summernote.admin import SummernoteModelAdmin from mptt.admin import MPTTModelAdmin, DraggableMPTTAdmin from .m...
5,712
1,739
# connectorDetails # Returns a connector object if a valid identifier was provided. # Reference: https://fivetran.com/docs/rest-api/connectors#retrieveconnectordetails import fivetran_api # Fivetran API URL (Replace {connector_id} with a valid connector id). url = "https://api.fivetran.com/v1/connectors/{connector_i...
369
132
from django.contrib import admin from .models import Address, Coupon, Item, Order, OrderItem, Payment, Session def make_refund_accepted(modeladmin, request, queryset): queryset.update(refund_requested=False, refund_granted=True) make_refund_accepted.short_description = "Update orders to refound granted" clas...
1,703
534
"""Metadata for cleaning, re-encoding, and documenting coded data columns. These dictionaries are used to create Encoder instances. They contain the following keys: 'df': A dataframe associating short codes with long descriptions and other information. 'code_fixes': A dictionary mapping non-standard codes to canonical...
37,194
9,223
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. import unittest from cdm.utilities import StorageUtils class StorageUtilsTest(unittest.TestCase): """Test to validate StorageUtils functions""" def test...
1,179
360
import raguel.fptp import raguel.irv
36
15
# -*- coding: utf-8 -*- """ Part of slugdetection package @author: Deirdree A Polak github: dapolak """ import numpy as np import pandas as pd from datetime import datetime import matplotlib.pyplot as plt from pyspark.sql import functions as F from pyspark.sql.window import Window class Data_Engineering: """ ...
18,624
5,247
import os import time import yaml import argparse from PIL import Image import matplotlib.pyplot as plt from vietocr.tool.predictor import Predictor from vietocr.tool.config import Cfg def main(): parser = argparse.ArgumentParser() parser.add_argument("--img", required=True, help="foo help") parser.add_a...
2,632
1,454
# -*- coding: utf-8 -*- #--------------------------------------------------------------------------- # Copyright 2020 VMware, Inc. All rights reserved. # AUTO GENERATED FILE -- DO NOT MODIFY! # # vAPI stub file for package com.vmware.esx.settings.depot_content.components. #--------------------------------------------...
12,231
3,228
#! python3 # Multi-atlas segmentation scheme trying to give a platform to do tests before translating them to the plugin. from __future__ import print_function from GetMetricFromElastixRegistration import GetFinalMetricFromElastixLogFile from MultiAtlasSegmentation import MultiAtlasSegmentation from ApplyBiasCorrection...
9,790
3,369
# -*- coding: utf-8 -*- """ jes.gui.dialogs.intro ===================== The "intro" dialog, which displays the JESIntroduction.txt file. :copyright: (C) 2014 Matthew Frazier and Mark Guzdial :license: GNU GPL v2 or later, see jes/help/JESCopyright.txt for details """ from __future__ import with_statement import JES...
1,591
507
"""Assist """
15
9
import tornado.web import tornado.websocket import tornado.httpserver import tornado.ioloop from worker_gateway.server import WebSocketChannelHandler from heartbeat.handler import HeartbeatHandler from orm import Worker class Application(tornado.web.Application): def __init__(self): handlers = [ ...
678
214
import time from websocket_server import WebsocketServer # Called for every client connecting (after handshake) def new_client(client, server): print("New client connected and was given id %d" % client['id']) #server.send_message_to_all("Hey all, a new client has joined us") short_message = "" middle...
1,536
501
import collections class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: cols = collections.defaultdict(set) rows = collections.defaultdict(set) grid = collections.defaultdict(set) for r in range(len(board)): for c in range(len(board)...
899
247
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt # In[2]: from sklearn.preprocessing import LabelEncoder from sklearn.metrics import classification_report from sklearn.m...
9,375
3,882
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class ZhimaCreditOrderRepaymentApplyModel(object): def __init__(self): self._action_type = None self._category = None self._order_info = None self._out_ord...
3,950
1,272
#!/usr/bin/env python """ Newton Generate Boot Images Usage: generateBootImage.py <target> <file_name> [--sim][--frontdoor][--seed=<seed_value>][--count=<word_count>][--hsp_fw_0p97] Options: -h --help Shows this help message. Target is one of the following: useq_seq_ram : Microsequencer Sequence RAM ...
36,170
12,886
import os, json __author__ = 'Manfred Minimair <manfred@minimair.org>' class JSONStorage: """ File storage for a dictionary. """ file = '' # file name of storage file data = None # data dict indent = ' ' # indent prefix for pretty printing json files def __init__(self, path, name): ...
1,503
443
from setuptools import setup setup( name="scienz", version="0.0.1", packages=["scienz"], zip_safe=False, include_package_data=True, package_data={"scienz": ["scienz/*"],}, long_description=""" Common dataset definitions for aorist package. """, long_description_content_type="tex...
332
113
#!-*- conding: utf8 -*- #coding: utf-8 """ Aluno: Gabriel Ribeiro Camelo Matricula: 401091 """ import matplotlib.pyplot as pplt # gráficos import math # Matemática import re # expressões regulares import numpy as np # matrizes from statistics import p...
2,219
918
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: weixin.py @time: 2018-02-10 17:55 """ import re import time import hashlib # from urlparse import urljoin # PY2 # from urllib.parse import urljoin # PY3 from future.moves.urllib.parse import urljoin ...
4,424
1,571
import numpy arr = map(int, input().strip().split(' ')) d2_arr = numpy.array(list(arr)) d2_arr.shape = (3, 3) print(d2_arr)
126
57
import os.path import json class Temprature_scaling: def __init__(self, label): fname = './parameters/Models/Txm/' + label + '_parameters.json' if os.path.isfile(fname) == False: print("Error: %s does not exists it uses Tx scaling default parameters."%s) exit(1) ...
1,359
485
import multiprocessing import os from settings.default import QUANDL_TICKERS, CPD_QUANDL_OUTPUT_FOLDER_DEFAULT N_WORKERS = len(QUANDL_TICKERS) if not os.path.exists(CPD_QUANDL_OUTPUT_FOLDER_DEFAULT): os.mkdir(CPD_QUANDL_OUTPUT_FOLDER_DEFAULT) all_processes = [ f'python script_cpd_example.py "{ticker}" "{os....
545
244
# Generated by Django 3.1.7 on 2021-03-08 14:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0048_auto_20210307_1644'), ] operations = [ migrations.AlterField( model_name='event', name='email_conf', ...
1,248
373
# -*- coding: utf-8 -*- from odoo import models, fields, api class Cowin_custom_model_data(models.Model): _name = 'cowin_settings.custome_model_data' # name = fields.Char(string=u'ID') model_name = fields.Char(string=u'model ID') _sql_constraints = [ ('model_name_key', 'UNIQ...
369
159
"""iex_parser""" from .parser import Parser from .messages import DEEP_1_0, TOPS_1_6, TOPS_1_5 __all__ = [ 'Parser', 'DEEP_1_0', 'TOPS_1_5', 'TOPS_1_6' ]
172
90
from pathlib import Path import json import re import numpy as np import os from collections import OrderedDict from .TxtMpiFile import TxtMpiFile from .BaseSource import BaseSource from tweezers.meta import MetaDict, UnitDict class TxtMpiSource(BaseSource): """ Data source for \*.txt files from the MPI with...
14,129
4,025
# keys IMPLEMENTATION_FILE_PATHS_KEY = r'implementation_file_paths' LPROJ_DIR_PATHS_KEY = r'lproj_file_paths' KEY_KEY = r'key' TRANSLATION_KEY = r'translation' # file names LOCALIZABLE_STRINGS_FILE_NAME = r'Localizable.strings'
232
97
#!/usr/bin/env python3 from threading import Thread from time import sleep import logging import shexter.requester import shexter.platform as platform import shexter.config """ This file is for the shexter daemon, which runs persistantly. Every 5 seconds, it polls the phone to see if there are unread messages. If t...
6,482
1,966
import sys import os import logging import time import datetime from PIL import ( Image, ImageDraw, ImageFont ) from config import * from util import * from info_epd import praytimes DEBUG_PRAYTIMES = False class SalahMixin: """Uses praytimes library for calculating prayer times. Make sure s...
7,218
2,459
import pandas as pd import pytest from denstatbank.denstatbank import StatBankClient from denstatbank.utils import data_dict_to_df, add_list_to_dict from .mock_responses import ( mock_sub_resp_default, mock_sub_resp_2401, mock_tables_resp, mock_tableinfo_resp, mock_tableinfo_variable_resp, mock_...
5,871
2,013
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ s = str(num) l = list(s) sum = 0 for digit in l: sum += int(digit) if len(list(str(sum))) == 1: return sum else: r...
473
157
import sys from os.path import join, dirname with open(join(dirname(sys.executable), 'license.lic'), 'rb') as fs: with open(join(sys._MEIPASS, 'license.lic'), 'wb') as fd: fd.write(fs.read())
205
78
from django.template import Library register = Library() hundreds = [ '', 'сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот' ] first_decade = [ '', ('одна', 'один'), ('две', 'два'), 'три', 'четыре', 'пять...
2,689
1,067
#!/usr/bin/env python # -*- coding: utf-8 -*- from sympy import * x, y, z = symbols('x y z') init_printing(use_unicode=True) print(Eq(x, y)) print(solveset(Eq(x**2, 1), x)) print(solveset(Eq(x**2 - 1, 0), x)) print(solveset(x**2 - 1, x)) print(solveset(x**2 - x, x)) print(solveset(x - x, x, domain=S.Reals)) print(so...
1,577
840
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='ptwitter', version='0.0.1', description="Tiny python library for Twitter's REST API.", author='Mitchel Kelonye', author_email='kelonyemitchel@gmail.com', url='https://github.com/kelonye/python-twitter', packages...
421
142
import sys import a print(datetime, sys, a)
44
16
""" Unit tests for resdk/resources/utils.py file. """ # pylint: disable=missing-docstring, protected-access import unittest import six from mock import MagicMock, call, patch from resdk.resources import Collection, Data, Process, Relation, Sample from resdk.resources.utils import ( _print_input_line, endswith_co...
10,444
3,375
class BSBIIndex(BSBIIndex): def parse_block(self, block_dir_relative): """Parses a tokenized text file into termID-docID pairs Parameters ---------- block_dir_relative : str Relative Path to the directory that contains the files for the block ...
1,136
321
"""test unit for core/initializer.py""" import runtime_path # isort:skip from core.initializer import * TEST_SHAPE = (100000, 1) TOR = 1e-2 def test_get_fans(): fan_in, fan_out = get_fans(shape=(100, 10)) assert fan_in == 100 and fan_out == 10 fan_in, fan_out = get_fans(shape=(64, 5, 5, 128)) ass...
1,674
727
class VCFEntry(object): def __init__(self, vkey, ssid, pid, ac, passFilter=1, qual=-1, gq=-1, dp=-1, ad=-1): self.vkey = vkey if not ssid: self.ssid = "UNKNOWN" else: self.ssid = ssid self.pid = pid self.ac = ac self.passFilter = passFilter ...
1,117
403
#!/usr/bin/env python # (c) 2012, Marco Vito Moscaritolo <marco@agavee.com> # modified by Tomas Karasek <tomas.karasek@digile.fi> # # This file is part of Ansible, # # Ansible 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 S...
14,321
4,504
from datetime import date import numpy as np from sklearn.metrics import ( roc_curve, auc, ) import torch from torch.utils.data import DataLoader from .metrics import accuracy_thresh, fbeta, pairwise_confusion_matrix import pandas as pd from tqdm import tqdm class ModelEvaluator: """Class for evaluati...
7,003
2,112
import collections import xml.etree.ElementTree as x_etree import synapse.common as s_common import synapse.lib.syntax as s_syntax class DataElem: def __init__(self, item, name=None, parent=None): self._d_name = name self._d_item = item self._d_parent = parent self._d_special = ...
7,381
2,159
bl_info = { "name": "plantFEM (Seed)", "author": "Haruka Tomobe", "version": (1, 0), "blender": (2, 80, 0), "location": "View3D > Add > Mesh > plantFEM Object", "description": "Adds a new plantFEM Object", "warning": "", "wiki_url": "", "category": "Add Mesh", } import bpy from bp...
1,851
743
from assignment_1.envs.gaussianBandit import gaussianBandit from assignment_1.envs.bernoulliBandit import bernoulliBandit from assignment_1.envs.RWE import RWE
159
57
# -*- coding: utf-8 -*- import unittest from datetime import datetime, timedelta from context import aged_out_report, find_todays_file class Test_FTP_worker(unittest.TestCase): """ Test FTP_worker module functionality""" def test_find_today_file(self): self.assertIsNone( find_todays_fil...
1,401
514
"Usage: python -m get_version ./setup.py" import setuptools import sys setuptools.setup = lambda *args, version=None, **kwargs: print(version) exec(open(sys.argv[1]).read())
177
62
#!/usr/bin/python3 from dialectUtil import * from java.javaProperty import JAVAProperty from java.javaSnippets import * from java.javaLink import JAVALink import constants as CONST JAVA_PROPERTIES = {} JAVA_PROPERTIES['JAVA_AUTO_IMPORTABLE'] = ['created_by','last_modified_by','created_date', 'last_modified_date'] clas...
4,815
1,417
from tkinter import * import os main = Tk() main.geometry('{}x{}'.format(550, 550)) main.wm_title("Welcome to Face Recognition Based Attendence System ") svalue3= StringVar() # defines the widget state as string svalue2 = StringVar() #imagePath = PhotoImage(file="facerec.png") #widgetf = Label(main, image=imagePath)....
1,295
506
"""Extensions module - Set up for additional libraries can go in here.""" from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
133
39
#!/usr/bin/env python3 # # Copyright 2017-2020 GridGain Systems. # # 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...
2,586
810
from __future__ import division import cv2 import track import detect def main(video_path): cap = cv2.VideoCapture(video_path) ticks = 0 lt = track.LaneTracker(2, 0.1, 500) ld = detect.LaneDetector(180) while cap.isOpened(): precTick = ticks ticks = cv2.getTickCount() d...
859
342
SEECRET = 'Extremely secretive seecret. You could not guess this one if your life depended on it.' DATABASE = 'db/data.db' DATABASE_PRICES = 'db/prices.db' SESSION_TTL = 240 WEBSOCKETS_PORT= 7334 WEBSOCKETS_URI = 'ws://localhost:' + str(WEBSOCKETS_PORT) DEFAULT_LEDGER = { 'value': 10000, 'asset_id': 1 } DEFAU...
368
172
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'telas/telaEditUser.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QMessageBox import PyrebaseConnector as P...
6,349
2,177
import pytest from edera import Condition from edera import Task from edera.exceptions import TargetVerificationError from edera.testing import DefaultScenario from edera.testing import ScenarioWithProvidedStubs def test_default_scenario_works_correctly(): class A(Task): def execute(self): ...
1,303
393
# 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...
1,604
474
#!/usr/bin/python3 import MySQLdb from ognddbfuncs import getognchk unkglider = [] def getflarmid(conn, registration): # get the FLARMID from the GLIDERS table on the database cursG = conn.cursor() # set the cursor for searching the devices try: cursG.execute("select idglider, flarmtype from...
2,160
687
"""Edinburgh Genomics Online SF2 web application. examples: To start the tornado server: $ start_sf2_webapp More information is available at: - http://gitlab.genepool.private/hdunnda/sf2-webapp """ __version__="0.0.1" import os import tornado.options from tornado.options import define, options import sf2...
1,916
565
#!/usr/bin/env python # coding:utf-8 import cv2 from PIL import Image from PyPDF2 import PdfFileReader import logging Image.MAX_IMAGE_PIXELS = None log = logging.getLogger(__name__) def variance_of_laplacian(image): # compute the Laplacian of the image and then return the focus # measure, which is simply th...
828
276
#Copy a image def copyImage(imagePathToCopy, imageNameToPaste): with open(imagePathToCopy, 'rb') as rf: with open(imageNameToPaste, 'wb') as wf: for line in rf: wf.write(line)
216
75
# import paddle def check_logits_losses(logits_list, losses): # 自动权重和衰减 if 'ceof' not in losses.keys(): losses['ceof'] = [1] * len(losses['type']) if 'decay' not in losses.keys(): losses['decay'] = [1] * len(losses['type']) if len(losses['type']) == len(losses['ceof']) and \ ...
1,705
624
import numpy as np from futile.Utils import write HaeV = 27.21138386 def _occ_and_virt(log): """ Extract the number of occupied and empty orbitals from a logfile """ norb = log.log['Total Number of Orbitals'] if log.log['Spin treatment'] == 'Averaged': norbv = log.evals[0].info[0]-norb ...
28,150
8,695
import torch from torch.autograd import Variable from sklearn.metrics import confusion_matrix, classification_report import numpy as np import time # import our model and data from rnn import RNN from data import get_data hidden_size = 10 learning_rate = 0.01 num_layers = 2 num_epochs = 1000 sequence_length = 10 batc...
1,290
454
# Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath a=int(input("Enter a:")) b=int(input("Enter b:")) c=int(input("Enter c:")) # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solutio...
357
149
import numpy as np from fos.core.scene import Scene from fos.core.plots import Plot from fos.core.tracks import Tracks from fos.core.points import Points #data=200*np.random.rand(1000000,3) #colors=np.random.rand(1000000,4) data=[200*np.random.rand(int(np.round(30*np.random.rand()))+1,3).astype('float32') for i in...
712
326
"""vis widgets """ # Copyright (c) 2020 ipyradiant contributors. # Distributed under the terms of the Modified BSD License. __all__ = [ "CytoscapeVisualizer", "DatashaderVisualizer", "VisualizerBase", "LayoutSelector", "NXBase", ] from .base import NXBase, VisualizerBase from .cytoscape import Cyto...
419
139
r""" .. _compartmental-modeling-tools: Compartmental Modeling Tools ---------------------------- These functions build theoretical distributions with which to understand how Dismod-AT works, and how disease processes work. 1. Specify a disease process by making simple Python functions that return disease rates ...
11,780
3,763
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-11-13 01:17 from __future__ import unicode_literals from django.db import migrations, models import randomslugfield.fields class Migration(migrations.Migration): dependencies = [ ('badge', '0009_auto_20161112_1649'), ] operations = [ ...
722
246
import sys from typing import Callable, List try: sys.getsizeof(0) getsizeof = lambda x: sys.getsizeof(x) except: # import resource getsizeof = lambda _: 1#resource.getrusage(resource.RUSAGE_SELF).ru_maxrss def get_size(obj, seen=None): """Recursively finds size of objects""" size = getsizeof(...
2,084
744
from __future__ import division import numpy as np import pandas as pd import math from tqdm import tqdm from matplotlib.colors import rgb2hex def MonodExt(k1,k2,kt,l,Stmp,ks=200): # source: Lejeune et al 1995, Morphology of Trichoderma reesei QM 9414 in Submerged Cultures return (k1+k2*(l/(l+kt)))*(Stmp/(Stmp...
7,331
2,469
import sys sys.setrecursionlimit(10**6) class Node: def __init__(self, val, pos): self.left = None self.right = None self.pos = pos self.val = val def insert(node, val, pos): if node is None: print(pos) return Node(val, pos) if val < node.val: # move to left...
1,636
509
from kubernetes import client, config import json # 生成YML def main(): pod = create_pod("dev") print(json.dumps(client.ApiClient().sanitize_for_serialization(pod))) def create_pod(environment): return client.V1Pod( api_version="v1", kind="Pod", metadata=client.V1ObjectMeta( ...
814
221
"""Animations that update mobjects.""" __all__ = ["UpdateFromFunc", "UpdateFromAlphaFunc", "MaintainPositionRelativeTo"] import operator as op import typing from ..animation.animation import Animation if typing.TYPE_CHECKING: from ..mobject.mobject import Mobject class UpdateFromFunc(Animation): """ ...
1,680
496
import torch import torch.nn as nn def _make_divisible(ch, divisor=8, min_ch=None): if min_ch is None: min_ch = divisor new_ch = max(min_ch, int(ch + divisor / 2) // divisor * divisor) if new_ch < 0.9 * ch: new_ch += divisor return new_ch # ---------------------- # Mobi...
5,583
2,377
from xbrr.base.reader.base_parser import BaseParser from xbrr.edinet.reader.element_value import ElementValue class Stock(BaseParser): def __init__(self, reader): tags = { "dividend_paid": "jpcrp_cor:DividendPaidPerShareSummaryOfBusinessResults", # 一株配当 "dividends_surplus": "jppf...
538
190
"""This program first reads in the sqlite database made by ParseAuthors.py. Then, after just a little data cleaning, it undergoes PCA decomposition. After being decomposed via PCA, the author data is then clustered by way of a K-means clustering algorithm. The number of clusters can be set by changing the value of n_cl...
2,031
645
class NumMatrix: def __init__(self, matrix: List[List[int]]): if not matrix or not matrix[0]: return None m, n = len(matrix), len(matrix[0]) self.dp = [[0] * (n + 1) for _ in range(m + 1)] for r in range(m): for c in range(n): self.dp[r + 1][c + 1] = self...
718
291
""" 格式: \033[0m -> 默认字体显示 \033[显示方式;前景色;背景色m -> 格式 三个参数顺序不敏感,因为值各不相同 显示方式列表: 0 - 默认值 1 - 高亮 4 - 下划线 5 - 闪烁 7 - 反显 8 - 不可见 前景色: 30 - 黑色 31 - 红色 32 - 绿色 33 - 黄色 34 - 蓝色 35 - 梅色 36 - 青色 37 - 白色 背景色: 40 - 黑色 前景色+10即可 """ from co...
2,951
1,342
import abc from functools import cached_property, partial import jax import jax.numpy as jnp class Kernel(abc.ABC): """Covariance kernel interface.""" @abc.abstractmethod def __call__(self, X, Y): raise NotImplementedError class _PairwiseKernel(Kernel): @partial(jax.jit, static_argnums=(0,...
5,765
2,120
# super class from genie.libs.ops.msdp.iosxe.msdp import Msdp as MsdpXE class Msdp(MsdpXE): ''' Msdp Ops Object ''' pass
148
68
import aiohttp import pytest from aiohttp import web from virtool_workflow.api.client import JobApiHttpSession from tests.api.mocks.mock_api import mock_routes @pytest.fixture def loop(event_loop): return event_loop @pytest.fixture async def jobs_api_url(): return "/api" @pytest.fixture async def mock_jo...
740
253
# Generated by Django 3.0.14 on 2021-08-08 10:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("pbn_api", "0020_przemapuj"), ] operations = [ migrations.AlterField( model_name="scientist", name="lastName", ...
1,359
414
"""Unit test for google.py""" __author__ = "Mark Pilgrim (f8dy@diveintomark.org)" __version__ = "$Revision: 1.4 $" __date__ = "$Date: 2004/02/06 21:00:53 $" __copyright__ = "Copyright (c) 2002 Mark Pilgrim" __license__ = "Python" import google import unittest import sys, os import GoogleSOAPFacade from StringIO impor...
11,047
3,299
import sys import asyncio import tornado.ioloop from classes.rabbitmq_tornado import TornadoAdapter from tornado import gen from services.read_sheet import read_sheet RABBIT_URI = "amqp://guest:guest@localhost:5672/" @gen.coroutine def handle_message(logger, message): logger.info("File request {}".format(messag...
1,591
460
#!/usr/bin/env python3 import json import argparse import re import datetime import paramiko import requests # cmd ['ssh', 'smart', # 'mkdir -p /home/levabd/smart-home-temp-humidity-monitor; # cat - > /home/levabd/smart-home-temp-humidity-monitor/lr.json'] from btlewrap import available_backends, Blu...
16,428
6,731
# Copyright (c) 2021 CNES/JPL # # All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. """ Orbital error ------------- """ from typing import Dict, Tuple # import dask.array as da import numpy as np # from .. import random_signal from .. import setti...
2,880
981