text
string
size
int64
token_count
int64
from django.urls import path from purple_admin import views urlpatterns = [ path('', views.cabinet, name='admin_panel_cabinet'), # Адмника Наименований маршрутов path('route_list', views.cabinet_list, {'type': 'route'}, name='admin_panel_route_list'), path('route_add', views.cabinet_add, {'type': 'rou...
1,807
629
mock_dbcli_config = { 'exports_from': { 'lpass': { 'pull_lastpass_from': "{{ lastpass_entry }}", }, 'lpass_user_and_pass_only': { 'pull_lastpass_username_password_from': "{{ lastpass_entry }}", }, 'my-json-script': { 'json_script': [ ...
1,893
589
# This file is used by CrossLanguageInvocationTest.java to test cross-language # invocation. from __future__ import absolute_import from __future__ import division from __future__ import print_function import six import ray @ray.remote def py_func(value): assert isinstance(value, bytes) return b"Response f...
586
179
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:dabai time:2019/2/24 class GameStats(): """跟踪游戏的统计信息""" def __init__(self,ai_settings): """初始化统计信息""" self.ai_settings=ai_settings self.reset_stats() # 让游戏一开始处于非活动状态 self.game_active=False # ...
534
274
import tensorflow as tf from os import path import numpy as np from scipy import misc from styx_msgs.msg import TrafficLight import cv2 import rospy import tensorflow as tf class CarlaModel(object): def __init__(self, model_checkpoint): self.sess = None self.checkpoint = model_checkpoint ...
4,464
1,566
from typing import Tuple, List from transform.transformer import TimeSeriesTransformer import numpy as np class IndexedTransformer: def __init__(self, transformer: TimeSeriesTransformer, padding: int, step: int): self.transformer = transformer self.padding = padding self.step = step ...
542
158
#------------------------------------------ # this script combine result of different # nets and report final result #------------------------------------------ import sys import numpy as np from util import pickle, unpickle def evaluate_result( result, text ): # pre-condition check num_batches = len( result[...
2,177
772
""" ``goless`` introduces go-like channels and select to Python, built on top of Stackless Python (and maybe one day gevent). Use :func:`goless.chan` to create a synchronous or buffered channel. Use :func:`goless.select` like you would the ``Select`` function in Go's reflect package (since Python lacks a switch/case st...
1,556
501
1+2 3+5 7+8 6>7 abs(-3) if 8 < 9: min(3,5) else 4 < 5: abs(-2) else 4 > 5: max(3, 7) round(2.1) round(3.6) len("jfdgge") type(4) any(1, 3, 4) any(0.0, 0.0, 0.0) all("abc", "a") all(0, 1) bin(45) lower("ABC") upper("abc") join("abc", "abc") bool(0) bool("abc") ord('r') chr(100) str(130) globals() help() hex(15) oct(27) ...
643
341
# Practica de funciones #! /usr/bin/python # -*- coding: iso-8859-15 def f(x): y = 2 * x ** 2 + 1 return y # Programa que usa la funcion f n = int(input("Ingrese número: ")) for i in range(n): y = f(i) print (i,y)
235
111
from distutils.core import setup from setuptools import find_packages with open('README.md', 'r') as fh: long_description = fh.read() setup( name='pyroaman', version='0.1.1', license='MIT', description='Roam Research with Python', author = 'Bruno Godefroy', author_email='brgo@mail.com', ...
1,070
353
import sys from pgel_sat import ProbabilisticKnowledgeBase, solve import argparse def str_lp(lp): return f'''lp solution: x: {lp.x} y: {lp.y} cost: {lp.cost}''' def main(): parser = init_argparse() args = parser.parse_args() filename = args.file[0] kb = ProbabilisticKnowledgeBase.fr...
974
322
""" STATEMENT Divide two integers without using multiplication, division and mod operator. CLARIFICATIONS - Do I have to handle 32-bit integer overflow? Yes, return the MAX_INT in that case. - Can the divisor be zero? Yes, return the MAX_INT. EXAMPLES 34/3 -> 11 COMMENTS - This solution is by tusizi in Leetcode (pic...
1,075
403
class Samples: def __init__(self): #COMMANDS self.PP = ('Für [https://osu.ppy.sh/b/{} {} [{}]{}] (OD {}, AR {}, ' 'CS {}, {}★, {}:{}) wirst du {} {}') self.PP_FOR = ('| {}pp bekommen für {}% ') self.PP_PRED = ('Für [https://osu.ppy.sh/b/{} {} [{}]{}] (OD {},...
1,409
466
from setuptools import setup, find_packages """ https://tia.mat.br/posts/2020/06/21/converting-gwbasic-to-z80.html """ setup( name="z80conv", version='0.0.1', author="lp", description="Porting GW-BASIC from 8086 back to the Z80", license="GPLv2", packages=find_packages(), long_description=...
508
208
# -*- coding: utf-8 -*- # Copyright (c) 2021 The HERA Collaboration # Licensed under the MIT License """Utilities for dealing with galaxy/QSO catalogs.""" import numpy as np import matplotlib.pyplot as plt from astropy.coordinates import SkyCoord from .util import deg_per_hr _xshooter_ref = "https://ui.adsabs.harva...
8,046
3,327
#!/usr/bin/python # coding:utf-8 """ @author: yyhaker @contact: 572176750@qq.com @file: __init__.py @time: 2019/3/9 15:41 """ from .util import * from .functions import * from .nn import * from .attention import *
216
101
from configparser import ConfigParser from os import path def create_config() -> None: _config.add_section("Telegram") _config.set("Telegram", "api_id", "you api_id here") _config.set("Telegram", "api_hash", "you api_hash here") _config.set("Telegram", "username", "magicBot") _config.set("Telegram...
1,236
414
# Time: O(n) # Space: O(1) class Solution(object): def minDistance(self, height, width, tree, squirrel, nuts): """ :type height: int :type width: int :type tree: List[int] :type squirrel: List[int] :type nuts: List[List[int]] :rtype: int """ ...
609
210
import pandas as pd import sys from dotenv import load_dotenv load_dotenv() src = pd.read_csv(sys.argv[1]) dst = pd.read_csv(os.getenv('FILE_PATH')) fdf = pd.concat([dst, src]) fdf = fdf[~((fdf['user'].duplicated(keep='first')) & (fdf['user']!='Point'))] fdf = fdf[~fdf.duplicated(keep='first')] fdf.to_csv(os.getenv('...
345
143
import location import unittest class LocationTest(unittest.TestCase): def testToJson(self): test_location = location.Location(name='foo', local_ip_address={'en0': {'local_ip_address': '1.2.3.4'}}) test_json = test_location.to_json() self.assertEqual(test_json['name'], 'foo') self.assertEqual(...
395
140
"""***************************************************************************************** MIT License Copyright (c) 2022 Murad Tukan, Xuan Wu, Samson Zhou, Vladimir Braverman, Dan Feldman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation fi...
41,489
13,933
# Copyright 2000-2004 Michael Hudson mwh@python.net # # All Rights Reserved # # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice appear in all copies and # that both ...
2,549
789
# # Defines data that is consumed by the header2whatever hooks/templates # to modify the generated files # import enum from typing import Dict, List, Tuple, Optional from pydantic import validator from .util import Model, _generating_documentation class ParamData(Model): """Various ways to modify parameters""" ...
15,818
4,775
from auspex.log import logger from auspex.experiment import Experiment, FloatParameter from auspex.stream import DataStream, DataAxis, SweepAxis, DataStreamDescriptor, InputConnector, OutputConnector import auspex.instruments import auspex.filters import bbndb import numpy as np import sys import os if sys.platform ==...
27,482
8,120
#! /usr/bin/env python """ Copyright 2013 Southwest Research Institute 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 req...
2,288
686
#!/usr/bin/env python3 import argparse import logging import sys import cte def main(args=None): parser = argparse.ArgumentParser( prog="cte", usage="cte <command> <options>", description="cte: test-covid-eval" ) parser.add_argument("--version", action="version", version=cte.__version__) su...
4,112
1,312
# -*- coding: utf-8 -*- """ Module that implements the questions types """ import json from . import errors def question_factory(kind, *args, **kwargs): for clazz in (Text, Password, Confirm, List, Checkbox): if clazz.kind == kind: return clazz(*args, **kwargs) raise errors.UnknownQuesti...
3,684
1,037
import os import json import string from tkinter import filedialog, simpledialog from tkinter import * class CsvImporter(object): def __init__(self): self.csv_data = None self.languages = [] def import_csv(self, csv_filename): with open(csv_filename, 'r') as file: self.csv...
4,216
1,127
from pdb import set_trace from time import time import matplotlib.pyplot as plt import numpy as np from numpy import random from scipy.stats import chi2 import renom as rm class Enc(rm.Model): def __init__( self, pre, latent_dim, output_act = None, ): self.pre = pre self.l...
6,134
2,143
import markdown import re from markdown.extensions import attr_list def makeExtension(**kwargs): # pragma: no cover return ImpliedAttrListExtension(**kwargs) class ImpliedAttrListExtension(markdown.Extension): """Extension for attatching `attr_list` entries to implied elements. Specifically: lists and tab...
2,245
621
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # main.pool application # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # ----------------------------------------------------------...
704
189
import sympy ''' @test($$;type(sympy)) @alt(シンボル|記号|変数) @alt(数式として、|) [代数計算|シンボル計算|数式処理][|ライブラリ]を使う ''' s = 'z' sympy.symbol(s) ''' @test(sympy=missing;$$) 数式として、sをシンボルに変換する ''' z = sympy.symbol(s) ''' @test(sympy=missing;$$;z) @prefix(z;[変数|式]) 数式として、sを[シンボル|変数][に|化]して、zにする ''' e = e2 = sympy.symbol(s) n = 2 e.subs...
2,396
1,745
from ...app.models import App from ...webhook.event_types import WebhookEventType def test_qs_for_event_type(payment_app): qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE) assert len(qs) == 1 assert qs[0] == payment_app def test_qs_for_event_type_no_payment_permissions(payment_app): ...
1,224
477
from . import null from . import abstract_detection_method from . import tech_detect from . import tiered_detect
113
35
from django.apps import AppConfig class TransactionsConfig(AppConfig): name = 'apps.transactions' verbose_name = "Transactions" def ready(self): import apps.transactions.signals default_app_config = 'apps.transactions.TransactionsConfig'
263
77
with open('./8/input_a.txt', 'r') as f: input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f] num = sum([sum([1 if len(a) in {2,3,4,7} else 0 for a in o[1]]) for o in input ]) print(f'Part A: Number of 1,4,7 or 8s in output - {num}') def getoutput(i): nums = ['0','1...
1,260
610
import logging from itertools import groupby import attr import numpy as np from ..explosion import Explosion from .core import GalaxyOrder logger = logging.getLogger("game") @attr.s() class ProduceResources(GalaxyOrder): name = "produce_resources" def execute(self) -> None: for planet in self.ga...
6,144
1,682
from .process_manager_factory import ProcessManagerFactory
59
13
# Copyright (c) 2011-2020 Eric Froemling # # 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, modify, merge, publish,...
4,221
1,247
import os import math import shutil import textwrap from datetime import datetime from terminaltables import AsciiTable class Display: def __init__(self): self.colors = { 'RED': '\033[38;5;196m', 'ORANGE': '\033[38;5;220m', 'GREEN': '\033[38;5;46m', 'BOLD': ...
10,940
3,268
class Node: def __init__(self, data): self.data = data self.next = None def sumLinkedListNodes(list1, list2): value1, value2 = "", "" head1, head2 = list1, list2 while head1: value1 += str(head1.data) head1 = head1.next while head2: value2 += str(head2.dat...
797
300
import logic import numpy as np import gym ACTION_MAP = { 0: 'up', 1: 'down', 2: 'left', 3: 'right' } class Env2048(gym.Env): metadata = {'render.modes': ['human']} def __init__(self, n=4, max_idle=100, seed=None): super(Env2048, self).__init__() self.n = n self.max...
3,674
1,325
from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from .forms import InstaRegistrationForm, UserUpdateForm, ProfileUpdateForm from django.views.generic import DetailView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages fro...
1,697
476
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 12:55:47 2018 @name: CSVMachLearn.py @description: 1D CNN using CSV vector for machine learning @author: Aleksander Dawid """ from __future__ import absolute_import, division, print_function import matplotlib.pyplot as plt from matplotlib.lines import Line2...
9,865
3,576
# -*- coding: utf-8 -*- """ Created on 2020/03/16 Feature selection: Relief-based feature selection algorithm. ------ @author: LI Chao """ import numpy as np from sklearn import preprocessing import os from sklearn.externals import joblib from el_classify_sensitive_person_train_validation import ClassifyFourKindOfPer...
6,037
1,845
import random cor = { 'fim':'\033[m', 'amarelo':'\033[1;033m', 'vermelho':'\033[1;031m', 'vermelhof':'\033[7;031m', 'azul':'\033[1;034m', 'verde':'\033[1;32m', 'verdef':'\033[7;32m', 'branco':'\033[1;030m' } print(''' Escolha uma das opções abaixo: \t {}1{} {...
2,483
1,193
from pandas.core.algorithms import mode import torch import torch.nn as nn from albumentations import Compose,Resize,Normalize from albumentations.pytorch import ToTensorV2 import wandb import time import torchvision import torch.nn.functional as F import torch.optim as optim from torch.cuda.amp import autocast,GradSc...
5,316
1,991
import conftest from asaprog import pac_encode from asaprog.util import * if __name__ == "__main__": pac = { 'command': asaProgCommand.CHK_DEVICE.value, 'data': b'test' } res = pac_encode(pac) print(res) print(res[-1])
257
98
from http import HTTPStatus import winter.web from winter.web import ExceptionHandler from winter.web.exceptions import ThrottleException class CustomThrottleExceptionHandler(ExceptionHandler): @winter.response_status(HTTPStatus.TOO_MANY_REQUESTS) def handle(self, exception: ThrottleException) -> str: ...
1,098
366
# -*- coding: UTF=8 -*- __author__ = 'Tomas Hartmann' import glob from appwebshare.scripts import config def get_file_list(): without_dir = [] for i in glob.glob(config.DIR + '*.*') : without_dir.append(i.replace(config.DIR, "")) return without_dir
269
94
import pytest import checkout_sdk from checkout_sdk.environment import Environment from checkout_sdk.exception import CheckoutArgumentException def test_should_create_four_sdk(): checkout_sdk.FourSdk() \ .secret_key('sk_sbox_m73dzbpy7cf3gfd46xr4yj5xo4e') \ .public_key('pk_sbox_pkhpdtvmkgf7hdnpwnb...
1,132
408
#!/usr/bin/env python2 import sys import transitfeed import run_transitfeed_web_server import util def main(): print ("Hello, world.") if __name__ == '__main__': main()
181
63
#!/usr/bin/env python from __future__ import with_statement from __future__ import print_function from __future__ import division import os from multiprocessing import Pool import click import mercantile as merc import numpy as np import rasterio from rasterio import Affine from rasterio.warp import reproject try: ...
7,980
2,740
import os from os.path import join, dirname from dotenv import load_dotenv load_dotenv(verbose=True) dotenv_path = join(dirname(__file__), '.env') load_dotenv(verbose=True, dotenv_path=dotenv_path) TOKEN = os.getenv('DISCORD_TOKEN')
236
92
class Stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 def isEmpty(self): if(self.top == -1): return True else: return False def isFull(self): if(self.top == self.max -1): return True else: ...
1,476
477
import numpy import pickle readfile1 = open('intermediate_data/post_1.txt','r'); readfile2 = open('intermediate_data/cmnt_1.txt','r'); writefile = open('intermediate_data/dictionary.pkl','w'); #writefile1 = open('intermediate_data/post_2.txt','w'); #writefile2 = open('intermediate_data/cmnt_2.txt','w'); def staticDic...
1,316
492
import itertools import os from collections import defaultdict import matplotlib.pyplot as plt #plt.style.use('ggplot') from matplotlib.ticker import FuncFormatter import pickle import os import numpy as np def calculate_cm(pred_vals, true_vals, classes): """ This function calculates the confusion matrix....
4,245
1,413
# -*- coding: utf-8 -*- """ Created on Thu Nov 1 12:54:07 2018 @author: bsala_000 """ import os import numpy as np import pandas as pd def getFilename(RECORDS_DIR='myo_data'): """ Function to allow user to pick filename of CSV to load in the input records directory. Filename is picked by it...
7,188
2,186
#---------------------------------------------------------------------- # Basis Set Exchange # Version v0.8.13 # https://www.basissetexchange.org #---------------------------------------------------------------------- # Basis set: STO-3G # Description: STO-3G Minimal Basis (3 functions/AO) # Role: orbital # ...
739
342
def setup(): # Insert light. Driftwood.light.insert("lightmap_circle1.png", 2, 64, 60, 56, 56, "22FF66DD")
115
56
from rest_framework import permissions class IsAadminOrReadOnly(permissions.BasePermission): """ The request is authenticated as a admin, or is a read-only request. """ def has_permission(self, request, view): return bool( (request.user and request.user.is_authenticated and request...
422
118
import pandas as pd def derive_termination_rate_year(df, start_business_year, extraction_year, main_column_contract_date, policy_id_column_name, column_to_sum_name): """Derives the contracts termination rates per year Arguments --> the dataframe, the business starting year, the extraction year ...
2,294
737
""" auth.py Author: Joseph Maclean Arhin """ import os import inspect from functools import wraps import jwt from flask import request from jwt.exceptions import ExpiredSignatureError, InvalidTokenError, PyJWTError from .exc import Unauthorized, ExpiredTokenException, OperationError def auth_required(other_roles=No...
2,538
663
import json from typing import Any import prefect from prefect.engine.result_handlers import ResultHandler class SecretResultHandler(ResultHandler): """ Hook for storing and retrieving sensitive task results from a Secret store. Only intended to be used for Secret tasks. Args: - secret_task ...
1,221
320
import os.path as op from urllib.request import urlretrieve import matplotlib import numpy as np from numpy.testing import assert_allclose import pytest import hnn_core from hnn_core import read_params, read_dipole, average_dipoles from hnn_core import Network, jones_2009_model from hnn_core.viz import plot_dipole fr...
9,283
3,456
from setuptools import setup, find_packages with open('docs/README-rst') as f: desc = f.read() setup( name='chinese', version='0.2.1', license='MIT', url='https://github.com/morinokami/chinese', keywords=['Chinese', 'text analysis'], classifiers=[ 'Development Status :: 3 - Alpha',...
1,280
402
from ..models import EntityOnServer, AccessToken, Organisation, Server, ServerUser, Key, KeyFetchEvent, AuditNote, AuditEvent, LoginAttempt from django.template import Context, Template from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from uuid import uuid4 from datetime import...
2,880
918
from typing import List from parser import parse_bytes, split_bytes_from_lines, get_bytes, parse_instruction_set, wrap_parsed_set from reader import dump_file_hex_with_locs class Translator: """ Class handling file translations from *.mpy to hex dumps and opcodes """ def __init__(self, file: str): ...
2,870
881
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Niko Sandschneider """Module implementing Signals for communicating with the GUI.""" from functools import wraps import logging from PyQt5.QtCore import QObject, pyqtSignal class Signals(QObject): """Class for signal communication between worker classes and G...
3,987
1,060
import sys from ctypes import * def test_getattr(): class Stuff(Union): _fields_ = [('x', c_char), ('y', c_int)] stuff = Stuff() stuff.y = ord('x') | (ord('z') << 24) if sys.byteorder == 'little': assert stuff.x == b'x' else: assert stuff.x == b'z' def test_union_of_struct...
623
239
# # Copyright (c) 2021 Citrix Systems, Inc. # # 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...
13,977
4,871
import json import boto3 # Amazon S3 client library s3 = boto3.resource('s3') dynamodb = boto3.resource('dynamodb') problems_table = dynamodb.Table('codebreaker-problems') bucket = s3.Bucket('codebreaker-testdata') def lambda_handler(event, context): problemName = event['problemName'] testcaseCount = 0 fo...
770
245
#!/usr/bin/env python3 """ Packs/unpacks Hextream content to/from the Varipacker format """ import sys import argparse from itsybitser import hextream, varipacker def main(): """ Program entry point """ parser = argparse.ArgumentParser( description="Packs/unpacks Hextream content to/from the Varipack...
2,003
586
import attr from reobject.models.manager import ManagerDescriptor, RelatedManagerDescriptor from reobject.models.store import Store, ModelStoreMapping class ModelBase(type): """ Metaclass for all models, used to attach the objects class attribute to the model instance at runtime. """ def __new__...
1,665
463
import os import re import sys import pdb import numpy as np from math import log, e from scipy.signal import find_peaks import word from utils import * # hit object subword integer representations from word.py h_int = word.obj_str2int[word.HITCIRCLE] e_int = word.obj_str2int[word.EMPTY] sb_int = word.obj_str2int[wor...
11,525
4,152
#!/usr/bin/env python """ Southern California Earthquake Center Broadband Platform Copyright 2010-2017 Southern California Earthquake Center These are acceptance tests for the broadband platforms $Id: AcceptTests.py 1795 2017-02-09 16:23:34Z fsilva $ """ from __future__ import division, print_function # Import Python...
8,982
2,711
import torch import torch.nn as nn import torchvision.models as models from torch.nn.utils.rnn import pack_padded_sequence as pack from torch.nn.utils.rnn import pad_packed_sequence as unpack from torch.autograd import Variable class EncoderCNN(nn.Module): def __init__(self, embed_size): """Load the pretr...
6,375
2,077
{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "001887f2", "metadata": {}, "outputs": [], "source": [ "# import os modules to create path across operating system to load csv file\n", "import os\n", "# module for reading csv files\n", "import csv" ] }, { ...
3,525
1,407
from Algorithms.Problems.MaximumSubarray.maximum_substring_naive import ( maximum_subarray_naive, ) class TestMaximumSubarrayNaive: def test_returns_maximum_subarray(self): data = [1, -2, 3, 10, -5, 14] expected = [3, 10, -5, 14] result = maximum_subarray_naive(data) assert r...
338
126
""" Helios Election Workflows """ from helios.datatypes import LDObjectContainer class WorkflowObject(LDObjectContainer): pass
138
44
""" Unit tests for the searcher module. Those tests mock the Entrez class and do not make any sort of HTTP request. """ # pylint: disable=redefined-outer-name import io from pathlib import Path from Bio import Entrez from dbvirus_searcher import Searcher def test_searcher_initialization(searcher): """ Tests a...
2,210
739
try: import unittest2 as unittest except ImportError: import unittest from isso.core import Config from isso.utils import html class TestHTML(unittest.TestCase): def test_markdown(self): convert = html.Markdown(extensions=()) examples = [ ("*Ohai!*", "<p><em>Ohai!</em></p>"...
2,296
773
""" Definition of the :class:`OtherDoubleTestCase` class. """ from dicom_parser.data_elements.other_double import OtherDouble from tests.test_data_element import DataElementTestCase class OtherDoubleTestCase(DataElementTestCase): """ Tests for the :class:`~dicom_parser.data_elements.other_double.OtherDoub...
373
114
#!/usr/bin/env python """Command line interface for the compact ACME library.""" import acme_lib import argparse import sys import textwrap def _gen_account_key(account_key, key_length, algorithm): key = acme_lib.create_key(key_length=key_length, algorithm=algorithm) acme_lib.write_file(account_key, key) d...
14,317
4,301
""" VPC stack for running ConsoleMe on ECS """ import urllib.request from aws_cdk import ( aws_ec2 as ec2, core as cdk ) class VPCStack(cdk.NestedStack): """ VPC stack for running ConsoleMe on ECS """ def __init__(self, scope: cdk.Construct, id: str, **kwargs) -> None: super().__ini...
1,530
497
from core.kapp import Kapp from core.httpResponse import HTTPResponse from core.Kcommand import Kcommand import uuid import os class GetImage(Kcommand): getImageHash = str(uuid.uuid4()) def __init__(self): super(GetImage, self).__init__( "GetImage", self.getImageHash) class ViewImage(Kc...
1,837
563
class Solution: """ @param A : an integer array @return : a integer """ def singleNumber(self, A): # write your code here return reduce(lambda x, y: x ^ y, A) if A != [] else 0
214
68
from torch import nn, optim import torch import model import torch.nn.utils import utils import argparse device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') parser = argparse.ArgumentParser(description='training parameters') parser.add_argument('--n_hid', type=int, default=128, ...
2,356
790
# File: kapi_io.py # Purpose: I/O of between dataframes and Kinetica with native API. # Author: Chad Juliano # Date: 07/20/2018 ############################################################################### import numpy as np import pandas as pd import gpudb import sys KDBC = gpudb.GPUdb(encoding='BINARY', host='127...
4,904
1,691
import time import asyncio import sortedcontainers from hailtop.utils import retry_transient_errors class K8sCache: def __init__(self, client, refresh_time, max_size=100): self.client = client self.refresh_time = refresh_time self.max_size = max_size self.secrets = {} sel...
2,581
763
class UploadFailedException(Exception): pass
49
13
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This progr...
3,376
963
import torch.nn as nn RNN_TYPES = { 'lstm': nn.LSTM, 'gru': nn.GRU }
78
45
# USAGE # python extract_embeddings.py --dataset dataset --embeddings output/embeddings.pickle \ # --detector face_detection_model --embedding-model openface_nn4.small2.v1.t7 # import the necessary packages from imutils.face_utils import FaceAligner from imutils import paths import numpy as np import argparse import i...
5,391
1,961
# Copyright (c) 2020 Horizon Robotics. 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 applicab...
5,628
1,584
"""route.py Linux parsers for the following commands: * route """ # python import re # metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Schema, Any, Optional from netaddr import IPAddress, IPNetwork # ======================================================= # Sch...
16,781
4,370
import json import datetime import requests from nameko.web.handlers import http from nameko.timer import timer from statsd import StatsClient from circuitbreaker import circuit class DemoChassisService: name = "demo_chassis_service" statsd = StatsClient('localhost', 8125, prefix='simplebank-demo') @htt...
1,437
462
# Copyright 2018 Luddite Labs Inc. # # 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...
2,009
539
# -*- coding: utf-8 -*- import argparse import logging import os import re from .. import __version__ from ..config import ALLOWED_IMAGE_REGEXPS from ..config import ALLOWED_PORT_MAPPINGS from ..config import CAPS_ADD from ..config import CAPS_DROP from ..config import ENV_VARS from ..config import ENV_VARS_EXT from ...
11,037
3,540