text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Oct 26 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### impor...
3,677
1,532
import json import click from tqdm import tqdm import numpy as np from PIL import Image from skimage.exposure import rescale_intensity from . import extraction, pipeline np.seterr(all='raise') @click.command() @click.argument('pipeline_manifest', required=True) @click.argument('files', nargs=-1, required=True) # un...
1,371
463
from mezzanine import template from homepage.models import Info register = template.Library() @register.as_tag def about(): about = Info.objects.get(type="ABOUT") return about
186
56
#!/usr/bin/python # -*- coding: utf-8 -*- """pytests for :mod:`.__main__`""" from mini_project_1.__main__ import get_parser, main import mock def test_get_parser(): parser = get_parser() assert parser def test_main(tmpdir): tmp_file = tmpdir.join("thefile_name.json") tmp_file_name = str(tmp_file)...
514
186
from kafka import KafkaConsumer consumer = KafkaConsumer('myTestTopic', bootstrap_servers='localhost:9092') for item in consumer: print("The Message is :", item) # https://kafka-1:9092
189
65
expected_output = { "instance": { "default": { "vrf": { "L3VPN-0050": { "address_family": { "vpnv4": { "default_vrf": "L3VPN-0050", "prefixes": { "1...
67,701
15,797
""" This file is here to register apps. """ from django.apps import AppConfig class HomeConfig(AppConfig): """ Register app. """ name = 'pages'
154
44
from .client import client from .config import db_pass, db_user import string import random def test_login_logout(client): return_login_status = client.post('/login', data={"username": db_user, "password": db_pass}) # Redirected to home assert return_login_status.status_code==302 # Now that user is lo...
1,150
368
import hashlib import json import datetime import Util #Defining the block into our blockchain class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp.isoformat() self.data = data self.previous_hash = previous_hash ...
1,575
508
from pwn import * def malloc(name): p.sendlineafter('>> ','1 '+name) def free(id): p.sendlineafter('>> ', '2 '+str(id)) p = process("./vuln_3.o") gdb.attach(p) for i in range(8): malloc('a') malloc('a') malloc('a') for i in range(9): free(i-1) free(8) free(9) free(8) for i in range(8): ma...
437
208
#!/usr/bin/env python """ sentry-twilio ============= Sentry Notification plugin for Twilio Programmable SMS. :copyright: 2017 Luis Nell. :license: MIT, see LICENSE for more details. """ from __future__ import absolute_import from setuptools import setup, find_packages VERSION = '1.0' install_requires = [ 'twil...
1,202
395
import re from datetime import timedelta import responses from django.test import override_settings from django.utils.timezone import now from model_mommy.mommy import make from websubsub.models import Subscription from websubsub.tasks import refresh_subscriptions, retry_failed from .base import BaseTestCase, method_...
3,146
904
import Constants from .Hydrogen import Hydrogen from .Cosmology import Cosmology from .HaloMassFunction import HaloMassFunction from .RateCoefficients import RateCoefficients from .SecondaryElectrons import SecondaryElectrons from .CrossSections import PhotoIonizationCrossSection
281
85
from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import numpy as np import random from collections import deque import torch from os.path import exists from torch.nn.functional import smooth_l1_loss, mse_loss # noqa from torch.optim import Adam...
9,452
3,019
"""Widgets abstract out common View rendering patterns like displaying a list of logging messages or a bar chart. They typically take the ClusterData object, a window, and a list of keys they should care about from ClusterData. They then draw directly onto the window.""" from operator import itemgetter from .curses_u...
1,449
448
""" Copyright 2020 Twitter, Inc. SPDX-License-Identifier: Apache-2.0 """ import unittest import math import torch from feature_propagation import FeaturePropagation class TestFeaturePropagation(unittest.TestCase): def test_feature_propagation(self): X = torch.Tensor([1 / 2, 0, 1 / 3, 0]).reshape(-1, 1) ...
958
405
# -*- coding: utf-8 -*- from publication_backbone.views.publication import PublicationListHybridView from publication_backbone import conf as config #============================================================================== # PromotionListHybridView #===============================================================...
1,282
372
import os import unittest import numpy.testing as npt from tradssat import SoilFile, WTHFile, MTHFile, ExpFile, CULFile, ECOFile, DSSATResults from tradssat.out import SoilTempOut, SoilNiOut, SummaryOut, PlantGroOut, ETOut, SoilWatOut, MulchOut from tests.utils import _test_read, _test_write, rsrcs, read_json, get_re...
2,427
859
# 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 u...
2,840
773
import logging import unittest from src.gh_action_docs import app logging.disable(logging.CRITICAL) class TestActionFileCheck(unittest.TestCase): def test_no_files_found(self): results = app.check_for_file("not-existent-file") self.assertFalse(results) if __name__ == "__main__": unittest.ma...
325
108
#! /usr/bin/env python # coding=utf-8 from __future__ import print_function, division from scipy.stats import sigmaclip from astwro.pydaophot import daophot from astwro.pydaophot import fname from astwro.pydaophot import allstar from astwro.starlist import read_dao_file from astwro.starlist import write_ds9_regions ...
2,785
903
from xml.dom.minidom import parse def printLine(): print('------------------------------------------') if __name__ == '__main__': # 获取参数 DOMTree = parse("config.xml") collection = DOMTree.documentElement header = collection.getElementsByTagName('header')[0].childNodes[0].data printLine() ...
2,330
992
from django.test import TestCase from django.contrib.auth.models import User from dixit import settings from dixit.game.models.game import Game, GameStatus from dixit.game.models.player import Player class PlayerTest(TestCase): fixtures = ['game_testcards.json', ] def setUp(self): self.user = User....
865
267
# -*- coding: utf-8 -*- """ Django settings for portality project. Generated by 'django-admin startproject' using Django 1.8.17. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/...
7,933
3,806
def test(a, b): print b()
29
13
from django.apps import AppConfig class BackupCodesConfig(AppConfig): name = "backup_codes"
98
32
def convert(n,base): if n < base: res = str(n) else: res = convert(n//base,base) + str(n%base) return res print(convert(10,2)) def convert_inv(n,base): if n < base: res = str(n) else: res = str(n%base) + convert(n//base,base) return res print(convert_inv(10,2...
323
130
from pybricks.pupdevices import Motor from pybricks.tools import wait from pybricks.parameters import Port, Direction from pybricks.robotics import SpikeBase from pybricks import version print(version) # Initialize base. left_motor = Motor(Port.C) right_motor = Motor(Port.D) spike_base = SpikeBase(left_motor, right_m...
1,029
381
from typing import Any, Dict def deep_update(dest: Dict[Any, Any], other: Dict[Any, Any]) -> None: """Update `dest` with the key/value pairs from `other`. Returns `None`. Note that we modify `dest` in place. Unlike the built-in `dict.Update`, `deep_update` recurses into sub-dictionaries. This effect...
1,136
337
# runs ApiLogicServer basic web app: # python ui/basic_web_app/run.py # Export PYTHONPATH, to enable python ui/basic_web_app/run.py import os, sys, logging from pathlib import Path logger = logging.getLogger() current_path = Path(os.path.abspath(os.path.dirname(__file__))) current_path = current_path.parent.absolute...
2,312
836
from output.models.nist_data.list_pkg.non_positive_integer.schema_instance.nistschema_sv_iv_list_non_positive_integer_length_1_xsd.nistschema_sv_iv_list_non_positive_integer_length_1 import NistschemaSvIvListNonPositiveIntegerLength1 __all__ = [ "NistschemaSvIvListNonPositiveIntegerLength1", ]
300
112
from .main import CBot __version__ = '0.1.0' __author__ = 'Felix Wang' __email__ = 'felix2@foxmail.com' __url__ = 'https://github.com/wangyitao/cbot' __all__ = ( 'CBot', )
190
94
#!/usr/bin/python3 """ Infer service. It pick up single frame from frame queue and do inference. The result will be published to stream broker like below. +---------------------+ +---------------+ +-----------------------+ | Frame Queue (redis) | => | Infer Service | => | Stream broker (redis) | +--------...
4,219
1,378
# 使用Python copy一个文件,从a目录,copy文件到b目录 import os from pathlib import Path import shutil src_path=Path('a/test') dst_path=Path('b/test') with open(src_path,'w') as src_file: src_file.write('abcd\n1234') shutil.copy(src_path,dst_path) print(os.stat(src_path)) print(os.stat(dst_path))
288
132
from vanirio.module.interface.base import Base class Textfield(Base): def __init__(self, tag: str, label: str): """ A Textfield interface object is used as a parameter for module software. The interface can be used for string values. :param label: GUI label name :param tag...
548
152
import numpy as np from PIL import Image def count_params(model): param_num = sum(p.numel() for p in model.parameters()) return param_num / 1e6 class meanIOU: def __init__(self, num_classes): self.num_classes = num_classes self.hist = np.zeros((num_classes, num_classes)) def _fast_h...
2,348
1,032
import zmq import json """ Class used by the Client entity to communicate to the Server. The communication channel should be configured using the three ports: - com_port: Used to receive broadcast messages from the Server entity. - set_port: Used to send messages/request data to the Server entity. - res_port: Used t...
3,671
1,047
from __future__ import division from __future__ import print_function from __future__ import absolute_import import numpy as np import tensorflow as tf def lrelu(x, alpha=0.2): return tf.maximum(x, alpha * x) def linear(input, output_dim, scope='linear', stddev=0.01): norm = tf.random_normal_initializer(stdd...
2,821
1,006
from __future__ import unicode_literals import os import random import contextlib import shutil import pytest import tempfile from pathlib import Path import pathlib from ...gold import GoldParse from ...pipeline import EntityRecognizer from ...language import Language try: unicode except NameError: unicode ...
2,431
768
try: from ._version import __version__ except(ImportError): pass from . import instruments from . import sources from . import sky from . import utils from . import telescopes from . import detectors from . import filters __all__ = ['instruments', 'sources', 'sky', 'utils', 'telescopes', 'detectors', 'filters...
323
97
from unittest import TestCase import sys sys.path.append("./PathTracking/lqr_speed_steer_control/") from PathTracking.lqr_speed_steer_control import lqr_speed_steer_control as m print(__file__) class Test(TestCase): def test1(self): m.show_animation = False m.main()
293
106
#lists, tuplas, strings -> sequencias -> iteraveis nome = 'nome qualquer' print('comportamento esperado de um valor iteravel') print('o valor vai sempre estar la para ser exibido novamente') for l in nome: print(l) print(nome) print(10 * '=====') iterador = iter(nome) try: # quando mostrado x valor de um itera...
825
303
import dropbox try: from secrets_dict import DROPBOX_APP except ImportError: # Not running locally print("Couldn't get DROPBOX_APP from file, trying environment **********") from os import environ try: DROPBOX_APP = environ['DROPBOX_APP'] except KeyError: # Not in environment ...
1,002
325
import random import unittest from hearthbreaker.agents.basic_agents import DoNothingBot from tests.agents.testing_agents import SelfSpellTestingAgent, EnemySpellTestingAgent, MinionPlayingAgent, \ EnemyMinionSpellTestingAgent, SpellTestingAgent from hearthbreaker.constants import CHARACTER_CLASS from hearthbreake...
32,165
10,637
from django.contrib import admin from.models import Job admin.site.register(Job) # Register your models here.
111
31
from sklearn.neighbors import KNeighborsClassifier from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split x , y = make_classification(n_samples=1000,n_features=40,random_state=42) #构造数据 x_train, x_test ,y_train ,y_test = train_test_split(x,y,random_state=42) #划分数据...
504
232
from egg.resources.console import * from egg.resources.server import * from egg.resources.structures import * from egg.resources.auth import * from egg.resources.constants import * from egg.resources.extensions import * from egg.resources.help import * from egg.resources.modules import * from egg.resources.parser impor...
484
139
from jinja2 import Template articles_template = Template("""{{ index }}. {{ title }} \tAuthor: {{ author }} \tPublished on: {{ publication_date }} \tSource: {{ url }} """)
174
57
""" Defines exceptions used in the context of this module "algorithm" """ class ProblemStatusError(Exception): """Error thrown when SCSF algorithm experiences something other than an 'optimal' problem status during one of the solve steps."""
255
62
from sqlalchemy.ext.declarative import declarative_base from flask import Flask from flask import jsonify from flask_marshmallow import Marshmallow Base = declarative_base() app = Flask(__name__) ma = Marshmallow(app)
220
70
import tensorflow as tf import numpy as np import pandas as pd from MACD_RSI import init_train_data def get_batch(data, label, batch_size, num_epochs): input_queue = tf.train.slice_input_producer([data, label], num_epochs=num_epochs, shuffle=True, capacity=32) x_batch, y_batch = tf.train.batch(input_queue, bat...
3,622
1,432
""" Threshold-based transformers """ from typing import Dict, Iterable, Union from ..changemap.changemap import ChangeMap from ..utils.arrays import flatten, shape_of_array from .base import ColumnHandlingTransformer class RunningStats(ColumnHandlingTransformer): """ A helpful transformer that does not perfo...
3,525
1,098
line = input() (a, b, c) = [int(i) for i in line.split(' ')] greatest1 = (a + b + abs(a - b)) / 2 greatest2 = int((greatest1 + c + abs(greatest1 - c)) / 2) print('{} eh o maior'.format(greatest2))
197
93
import argparse from pathlib import Path import random def get_args(): parser = argparse.ArgumentParser(description='Launching VK chat bot') parser.add_argument('-m', '--memcached_server', default='redis-12388.c52.us-east-1-4.ec2.cloud.redislabs.com', help='Set the server to store and ...
1,907
582
#Author Shubham Nagaria. ShubhamLabs. #Coder. #subhamnagaria@gmail.com import tkinter from tkinter import * from tkinter import Tk, scrolledtext, filedialog, messagebox root = Tk(className=" TextEditor-ShubhamLabs") #name your texteditor in quotes textPad = scrolledtext.ScrolledText(root, width=100, ...
2,684
916
from ...schemas import ICON_EVENT from ...skosmos import get_collection_members from ..base import BaseSchema from ..general import get_contributors_field, get_date_range_time_range_location_group_field, get_url_field from ..utils import years_from_date_range_time_range_location_group_field ICON = ICON_EVENT TYPES = ...
852
275
from instabot import Bot import os import shutil import time # Dado un tweet (str) e imaxe (str '*.jpeg'), publica o contido en instagram def upload(tweet, imaxe): clean_up() bot = Bot() bot.login(username="usename", password="password") time.sleep(1) bot.upload_photo(imaxe, caption=tweet) # ... d...
787
275
import time import logging from functools import wraps logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s] %(message)s') def timehttp(endpoint): @wraps(endpoint) def timed(self, request, response): start = time.time() result = endpoint(self, reque...
2,088
599
"""cssedit: PyQt specific stuff """ import sys import os import PyQt5.QtWidgets as qtw import PyQt5.QtGui as gui import PyQt5.QtCore as core from .cssedit import parse_log_line, get_definition_from_file class MainGui(qtw.QMainWindow): """Hoofdscherm van de applicatie """ def __init__(self, master, app, ti...
24,641
7,690
from django.utils.crypto import get_random_string from cashbook.tests.test_functional import CashbookTestCase from disbursements.templatetags.disbursements import format_sortcode class DisbursementTestCase(CashbookTestCase): def tearDown(self): self.click_logout() def click_button(self, text=None): ...
13,425
4,244
# Copyright 2017 QuantRocket - 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 applicable law or ...
2,199
645
import copy from flask import g from app.comm.TableModule import TableModule from app.comm.SqlExecute import SqlExecute from app.unit_config import default_result, default_limit_size, depth_post_map class GeneralOperate(object): def __init__(self, module:TableModule): self.module = module # 请求参数检查链...
12,367
4,492
"""No identified need to test plotting functionality."""
57
13
'''MobileNetV2 in PyTorch. See the paper "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" for more details. ''' import torch import torch.nn as nn import torch.nn.functional as F from se import SEConv2d, SELinear THRESHOLD = 4e-3 __all__ = ['SEMaskMobileNet...
4,921
1,947
import requests def get_link(): return input("Give me a twitter video link: ") def download(url: str): name = url.rsplit('/')[-1] if("?tag" in name): name = name.split('?')[0] r = requests.get(url, allow_redirects=True) open(name, 'wb').write(r.content) def main(): ...
911
313
import frappe, re from frappe import _ from frappe.utils import cstr from erpnext.regional.india import states, state_numbers from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount def validate_gstin_for_india(doc, method): if not hasattr(doc, 'gstin'): return if doc.gstin:...
2,951
1,230
import numpy import pytest import cupy from cupy import cublas from cupy import testing from cupy.testing import _attr @testing.parameterize(*testing.product({ 'dtype': ['float32', 'float64', 'complex64', 'complex128'], 'n': [10, 33, 100], 'bs': [None, 1, 10], 'nrhs': [None, 1, 10], })) @_attr.gpu cl...
22,922
8,759
import re import csv # Unpaywall citing, cited list based on mag ids unpaywall_citing_cited_file = open('AdditionalOutputs/unpaywallmag_references.tsv', 'w') fieldnames = ['citing_mag_id', 'cited_mag_id'] writer = csv.DictWriter(unpaywall_citing_cited_file, delimiter="\t", fieldnames=fieldnames) citation_pattern = r...
706
262
import FWCore.ParameterSet.Config as cms # HLT dimuon trigger import HLTrigger.HLTfilters.hltHighLevel_cfi hltMinBiasHI = HLTrigger.HLTfilters.hltHighLevel_cfi.hltHighLevel.clone() hltMinBiasHI.HLTPaths = ["HLT_PAL1MinimumBiasHF_OR_SinglePixelTrack_ForSkim_v*"] hltMinBiasHI.throw = False hltMinBiasHI.andOr = True # s...
721
273
import datetime from calendar import monthrange import calendar import numpy as np ####### #For generate origin repayment schedule date and days columns ####### start_day = 1 start_month = 1 start_year = 2012 num_installment = 12 installment_time_period = 'months' change_col_idx = 1 change_row_idx = 2 change_val = 10...
4,523
1,678
from __future__ import print_function import argparse import json from boto.mturk.price import Price from boto.mturk.question import HTMLQuestion from boto.mturk.connection import MTurkRequestError import os import simpleamt import sys import inspect def printPlus(*args): print(inspect.getouterframes(inspect.cu...
3,696
1,159
from maya import cmds from maya.api import OpenMaya from maya.api import OpenMayaAnim from functools import partial from skinning.utils import api from skinning.vendor import apiundo def get_cluster_fn(node): """ Loop over an objects history and return the skin cluster api node that is part dependency gr...
2,405
707
import re REGEX = { "name": r"name is (?P<name>[A-Z][A-Za-z]+ [A-Z][A-Za-z]+)", "age": r" (?P<age>[0-9]{2}) years", "date": r"on (?P<date>[0-9]{2}-[0-9]{2}-[0-9]{4})." } class Person: def __init__(self, full_name, age, birth_date): self.__full_name = full_name self.__age = age ...
1,607
547
""" NOTE on google sheets format: The google sheets document must have the following: Columns A and B from cell 2 down are all the sample details Column A is the name of the detail and Column B is the value of the detail Columns B and onwards can be anything but there must be three speicifc...
7,667
1,947
import json import base64 import boto3 import uuid import traceback def valid_uuid(uuid_str): try: val = uuid.UUID(uuid_str, version=4) return True except ValueError: return False def lambda_handler(event, context): # TODO implement print(event, context) method = event['...
1,720
592
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 28 22:41:26 2017 @author: lamahamadeh """ ''' Case Study about Language Processing ''' #counting words #--------------- text = "This is a test text. We're keping this text short to keep things manageable." #test text #Using loops #----------- d...
6,565
1,895
from dataclasses import dataclass from bindings.csw.brief_record_type import BriefRecordType __NAMESPACE__ = "http://www.opengis.net/cat/csw/2.0.2" @dataclass class BriefRecord(BriefRecordType): class Meta: namespace = "http://www.opengis.net/cat/csw/2.0.2"
273
106
# -*- coding: utf-8 -*- '''check and clean and export as .csv - 150602 pike aTimeLogger2 date into .csv - 150601 make handlog export all date into *_all.csv - 150525 make handlog wxport 2types files ''' import os import sys import fnmatch def _load_timeline(flines,fpath): _titles = flines[0] _exp = ""...
8,109
3,055
import asyncio import aiormq async def publish(method, event_id): connection = await aiormq.connect('') channel = await connection.channel() body = bytes(str(event_id), 'utf-8') await channel.basic_publish( body, exchange='', routing_key='admin' ) await connection.close()
313
97
"""Embeds for Timezone Legends discord bot.""" import time import discord from dateutil.parser import parse # pip install python-dateutil from pytz import timezone from datetime import datetime class Timezone_Embeds: def __init__(self, description=None, color=0x5c0708, show_footer=True, show_timestamp=True, show_t...
8,473
3,255
import hashlib import shutil import requests import os from config import constants def get_sha_hash(content): sha = hashlib.sha1() sha.update(content) return sha.hexdigest() def download_image(image_url,filename_to_save): response = requests.get(image_url, stream=True) with open(filename_to_sav...
1,521
497
import time, os import tomtomSearch from flask_bootstrap import Bootstrap from flask import Flask, render_template, request, redirect, flash, session, jsonify, url_for from flask_wtf import FlaskForm from wtforms import StringField, BooleanField, SubmitField, IntegerField, SelectField, RadioField from wtforms.val...
14,635
4,798
# Copyright 2016-2021, Pulumi 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 t...
2,634
773
# generate data from bag images from PIL import Image from pathlib import Path import os, glob # manipulate file or directory import numpy as np class DataArrangement(object): def __init__(self): self.path = Path(__file__).parent self.current_directories = ['not_traking', 'traking'] self...
1,800
536
#! /usr/bin/env python # -*- coding: utf-8 -*- # flask_restapi import from flask_restapi.views import APIMethodView from .models import Book from .forms import BookForm class BookView(APIMethodView): model = Book paginate_by = 10 context_object_name = 'items' pk_url_kwarg = 'book_id' form_class ...
331
118
# -*- coding:utf-8 -*- from django.db import models from account.models import User # from cmdb.types import get_instance from cmdb.models import Model class Field(models.Model): """ 资产模型的字段 """ code = models.SlugField(verbose_name="字段", max_length=40) name = models.CharField(verbose_name="字段(中文...
2,484
985
import math def Bellman_ford(G): n = len(G) distance = [-math.inf]*n parents = [None]* n distance[0] = 0 for _ in range(n-1): for u in range(n): for v, w in G[u]: if distance[v-1] < distance[u-1] + w: distance[v-1] = distance[u-1] + w ...
604
242
from django.contrib import messages from dfirtrack_config.models import SystemExporterMarkdownConfigModel from dfirtrack_main.logger.default_logger import warning_logger import os def check_config(request): """ check variables in config """ # get config model model = SystemExporterMarkdownConfigModel.obje...
1,743
508
# -*- coding: utf8 -*- from header_factions import * #################################################################################################################### # Each faction record contains the following fields: # 1) Faction id: used for referencing factions in other files. # The prefix fac_ is automa...
44,309
23,953
#MAIN PROGRAM STARTS HERE: num = int(input('Enter the number of rows and columns for the square: ')) for x in range(0, num): i = x + 1 for y in range(0, num): print ('{} '.format(i), end='') i += num print()
236
84
import pickle import torch import torch.nn as nn from torchtext.data import Field from common.paths import ROOT_RELATIVE_DIR, MODEL_PATH from models.bert_layer import BERTLayer from probability.tables import TransitionTable from utility.model_parameter import Configuration, ModelParameter class BERTWithConversation...
4,602
1,286
import sys import math from time import gmtime, strftime sys.dont_write_bytecode = True class Position(): def __init__(self, x, y): super().__init__() self.x, self.y = x, y def distance(pos1, pos2): return ((pos1.x - pos2.x)**2 + (pos1.y - pos2.y)**2 )**0.5 class Warehouse(object): def __...
3,468
1,251
from flask import Flask from flask_restful import Api from saml2 import saml, samlp from saml2.config import IdPConfig from saml2.mdstore import MetadataStore from saml2.server import Server from app.config import config from app.database import db from app.resources.idp_config import IdpConfigResource from app.resour...
2,313
703
import os os.mkdir("3D") os.chdir("3D") print("Configuring 3D...") print("Fetching Intro...") os.system("wget https://raw.githubusercontent.com/mrobraven/majestic-pi/master/majestic-pi/intro.mp4") print("Fetching 3D Feature...") os.system("wget https://raw.githubusercontent.com/mrobraven/majestic-pi/master/majestic-pi/...
5,190
2,306
# # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or mo...
9,274
2,821
import datetime import typing import localization from configurator import Config def get_restriction_time(string: str) -> typing.Optional[int]: """ Get user restriction time in seconds :param string: string to check for multiplier. The last symbol should be one of: "m" for minutes, "h" for hours...
2,094
633
import numpy as np from syft.frameworks.torch.differential_privacy import pate def test_base_dataset(): num_teachers, num_examples, num_labels = (100, 50, 10) preds = (np.random.rand(num_teachers, num_examples) * num_labels).astype(int) # fake preds indices = (np.random.rand(num_examples) * num_labels)....
548
218
#Programa ejemplo para usar función #funcion sin parametros def imprimir_mensaje(): print("Mensaje especial:") print("Estoy aprendiendo:") imprimir_mensaje() #funcion con parametros valorA= "Hola mundo" valorB= "Función con parametros" def imprimir_mensaje_param(mensaje1, mensaje2): print(mensaje1)...
381
151
# -*- coding: utf-8 -*- # # Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES) # # 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 # # ...
7,130
2,079
from cStringIO import StringIO import inspect import textwrap import pytest from twisted.internet import defer, task from theseus._tracer import Function, Tracer class FakeCode(object): def __init__(self, filename='', name='', flags=0): self.co_filename = filename self.co_name = name sel...
7,374
2,619