text
string
size
int64
token_count
int64
import os import argparse import subprocess import random import edlib from typing import List from collections import Counter import stanza class ExtractMetric(object): """used for precision recall""" def __init__(self, nume=0, denom_p=0, denom_r=0, precision=0, recall=0, f1=0): super(ExtractMetric, ...
10,460
3,724
import pytest from thefuck.rules.git_stash_pop import get_new_command from thefuck.rules.git_stash_pop import match from thefuck.types import Command @pytest.fixture def output(): return """error: Your local changes to the following files would be overwritten by merge:""" def test_match(output): assert mat...
582
176
""" The ARIMA model. """ import torch import numpy as np class ARIMA(torch.nn.Module): """ARIMA [summary] """ def __init__(self, p: int = 0, d: int = 0, q: int = 0) -> None: """__init__ General ARIMA model constructor. Args: ...
3,642
1,091
""" Sliding window Given a string S, return the number of substrings of length K with no repeated characters. Example 1: Input: S = "havefunonleetcode", K = 5 Output: 6 Explanation: There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'. cou...
687
265
"""The File Propagator"""
26
10
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: brython (http://brython.info) (like python3) # # Imports ===================================================================== from os.path import join from browser import window from browser import document # virtual filesystem / modules provide...
4,681
1,335
from .grucell import MyGRUCell from .gru import MyGRU
53
18
#!/usr/bin/python2.7 import os import KernelCollection # Check that weak binds can be missing, so long as we check for the magic symbol def check(kernel_cache): kernel_cache.buildKernelCollection("arm64", "/kext-missing-weak-bind/main.kc", "/kext-missing-weak-bind/main.kernel", "/kext-missing-weak-bind/extension...
2,946
1,136
from elasticsearch_dsl import Boolean, Date, Double, Integer, Keyword, Long, Object, Text from datahub.search import dict_utils from datahub.search import fields from datahub.search.models import BaseESModel DOC_TYPE = 'investment_project' def _related_investment_project_field(): """Field for a related investm...
7,453
2,468
from collections import OrderedDict import torch from torch import nn class FullyConnected(nn.Module): def __init__(self, features, layers=None, dropout=0.0): super(FullyConnected, self).__init__() print("Layers:", layers) input_channels = 0 for feature in features: in...
1,670
422
#import import os #import torch #import torch.nn as nn import torch.utils.data as Data #import torchvision import matplotlib.pyplot as plt import h5py #from torch.autograd import Variable import numpy as np import torch class rawdataDataset(Data.Dataset): def __init__(self): super(rawdataDataset, self)...
2,968
1,135
from django.urls import path from . import views from .views import IndexView urlpatterns = [ # path('', views.index, name="index"), path('', IndexView.as_view(), name="index"), # path('create/', views.create, name="create"), path('create/', views.PythonCreateView.as_view(), name="create"), ]
310
95
#~ Copyright 2014 Wieger Wesselink. #~ Distributed under the Boost Software License, Version 1.0. #~ (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) def read_text(filename): with open(filename, 'r') as f: return f.read() def write_text(filename, text): with open(filenam...
356
134
import datetime t1 = datetime.datetime(2019, 3, 9, 10, 55, 30, 991882) t2 = datetime.datetime(2019, 3, 10, 10, 55, 30, 991882) print((t2-t1).total_seconds())
159
97
def is_descending(input_list: list, step: int = -1) -> bool: r"""llogic.is_descending(input_list[, step]) This function returns True if the input list is descending with a fixed step, otherwise it returns False. Usage: >>> alist = [3, 2, 1, 0] >>> llogic.is_descending(alist) True The fina...
1,401
501
from functools import partial from pipe import select, where from pydash import chunk from pydash import filter_ as filter from pydash import flatten, get, omit from .primitives import parallel, pipeline, scatter __all__ = ( "parallel", "scatter", "pipeline", "partial", "select", "where", ...
384
127
import yaml def yaml2dict(filename): with open(filename, "r") as stream: resume_dict = yaml.load(stream) return resume_dict def main(): resumeFile = "../demo/sample-resume.yaml" resume_dict = yaml2dict(resumeFile) print(resume_dict) if __name__ == '__main__': main()
304
114
""" Copyright 2012-2019 Ministerie van Sociale Zaken en Werkgelegenheid 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...
6,025
1,752
sort_functions = [ builtinsort, # see implementation above insertion_sort, # see [[Insertion sort]] insertion_sort_lowb, # ''insertion_sort'', where sequential search is replaced # by lower_bound() function qsort, # see [[Quicksort]] qsortranlc...
965
278
from rest_framework import status from rest_framework.test import APITestCase from rest_framework.test import APIClient from django.db.models import signals import factory from user_account.models import CustomUser from .models import Organization class OrganizationTestCase(APITestCase): def setUp(self): ...
6,300
1,895
# coding=utf-8 from math import log2, ceil # valid chars for a url path component: a-z A-Z 0-9 .-_~!$&'()*+,;=:@ # For the default set here (base 72) we have excluded $'();:@ radix_alphabet = ''.join(sorted( "0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ".-_~!&*+,=" )) radix =...
1,656
638
from flaskapp import app, db, mail from flask import render_template, url_for from flask import request, flash, redirect # from flaskapp.model import User from flaskapp.form import SurveyForm from flask_mail import Message @app.route('/', methods = ['POST', 'GET']) def form(): form = SurveyForm() if ...
961
296
import unittest from kameramera import camera class Camera(unittest.TestCase): def setUp(self): self.camera = camera.Camera(camera_id='canon_ae1') def test_general_manufacturer(self): self.assertEqual(self.camera.general.manufacturer, 'Canon') def test_general_name(self): se...
5,708
1,955
from pathlib import Path from PIL import Image # coordinates are sent as slightly weird URL parameters (e.g. 0.png?214,243) # parse them, will crash server if they are coming in unexpected format def parse_coordinates(args): keys = list(args.keys()) assert len(keys) == 1 coordinates = keys[0] assert...
887
282
import matplotlib.pyplot as plt import numpy as np import math import cv2 kernel = np.ones((3, 3), np.int8) # 去除雜訊 def eraseImage (image): return cv2.erode(image, kernel, iterations = 1) # 模糊圖片 def blurImage (image): return cv2.GaussianBlur(image, (5, 5), 0) # 銳利化圖片 # threshold1,2,較小的值為作為偵測邊界的最小值 def edgedImage...
2,851
1,343
import pandas as pd import numpy as np from scipy.stats import mannwhitneyu, fisher_exact, ranksums def load_geneset(gmtfn, genes=None, minsize=0): ''' Load genesets stored in gmt format (e.g. as provided by msigdb) gmtfn : str path to gmt file genes : list, optional only include gene...
2,965
1,025
from testlib_a.main_a import print_name print_name()
54
21
import pprint from nn_wtf.parameter_optimizers.neural_network_optimizer import NeuralNetworkOptimizer __author__ = 'Lene Preuss <lene.preuss@gmail.com>' class BruteForceOptimizer(NeuralNetworkOptimizer): DEFAULT_LAYER_SIZES = ( (32, 48, 64), # (32, 48, 64, 80, 96, 128), (32, 48, 64, 80, 96, 12...
2,167
729
#!/usr/bin/env python from numpy.testing import assert_array_almost_equal, assert_array_less import numpy as np from heat import BmiHeat def test_get_initial_value(): model = BmiHeat() model.initialize() z0 = model.get_value_ptr("plate_surface__temperature") assert_array_less(z0, 1.0) assert_arr...
1,856
699
import numpy as np import tensorflow as tf import sys, os sys.path.extend(['alg/', 'models/']) from visualisation import plot_images from encoder_no_shared import encoder, recon from utils import init_variables, save_params, load_params, load_data from eval_test_ll import construct_eval_func dimZ = 50 dimH = 500 n_cha...
9,158
3,049
import logging import os import cltl.combot.infra.config.local as local_config logger = logging.getLogger(__name__) K8_CONFIG_DIR = "/cltl_k8_config" K8_CONFIG = "config/k8.config" class K8LocalConfigurationContainer(local_config.LocalConfigurationContainer): @staticmethod def load_configuration(config_fi...
1,663
567
#!/usr/bin/env python import os import argparse import yaml import numpy as np from colorama import init, Fore, Style from matplotlib import rc import matplotlib.pyplot as plt import plot_utils as pu init(autoreset=True) rc('font', **{'serif': ['Cardo'], 'size': 20}) rc('text', usetex=True) kMetrics = ['det', 'mi...
17,640
6,895
# see: https://stackoverflow.com/a/34520971/3238695
52
29
import json import apiai import speech_recognition as sr def speechRecognition(): recog = sr.Recognizer() with sr.Microphone() as source: print("It's your cue") audio = recog.listen(source) i = True while i is True: try: text = recog.recognize_google(audio) ...
1,318
438
# raise NotImplementedError("Did not check!") """MSCOCO Semantic Segmentation pretraining for VOC.""" import os from tqdm import trange from PIL import Image, ImageOps, ImageFilter import numpy as np import pickle from gluoncv.data.segbase import SegmentationDataset class COCOSegmentation(SegmentationDataset): ...
4,667
1,548
# __author__ = 'sree' import urllib2 from lxml import html import requests def get_page_tree(url=None): page = requests.get(url=url, verify=False) return html.fromstring(page.text) def get_title(url=None): tree = get_page_tree(url=url) return tree.xpath('//title//text()')[0].strip().split(' -')[0] d...
1,045
358
# encoding: utf-8 # Copyright 2009-2020 Greg Neagle. # # 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...
35,235
9,144
from .. import util def configurable_class(setting_name, default_class_name=None): def getter(self): value = None try: value = self.configuration_get(setting_name) except KeyError: pass if not value: if not default_class_name: ret...
645
184
#!/usr/bin/python #-*-coding:utf-8-*- from Component import Component class MoveComponent(Component): '''This is the moveable component.''' _name = 'MoveComponent' def move(self,cmd): '''Input L,R,U,D or S to move the component or stop. Rise exception if moving out of region.''' cmd = cm...
1,606
488
import datetime, hashlib, base64, traceback, os, re import poshc2.server.database.DB as DB from poshc2.Colours import Colours from poshc2.server.Config import ModulesDirectory, DownloadsDirectory, ReportsDirectory from poshc2.server.Implant import Implant from poshc2.server.Core import decrypt, encrypt, default_respon...
35,016
9,085
class Solution: ''' 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。 输入: 2 输出: [0,1,3,2] 解释: 00 - 0, 01 - 1, 11 - 3, 10 - 2 ''' def grayCode(self, n: int): # 观察连续数值对应的格雷编码序列对应的关系 # 追加二进制位到首位, 0: 数值仍为前一个数组的值, 1: 前一个数组的每个元素 + 2的(n-1)次幂 ...
1,029
651
import argparse import os, sys os.chdir("/home/jackie/ResearchArea/SkinCancerResearch/semi_skin_cancer") sys.path.append("/home/jackie/ResearchArea/SkinCancerResearch/semi_skin_cancer") print(os.getcwd()) import os.path as osp import torchvision import numpy as np import torch # import torch.nn as nn # impo...
6,781
2,448
from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index, name='index'), path('countdown/', views.countdown, name='countdown'), #re_path(r'.+', views.redir, name='redir'), ]
226
79
from sys import argv script, first, second, third = argv print "This script called", script print "The first variable :", first print "The second variable :", second print "The third variable :", third
204
55
class FeatureRegistration: def __init__(self, key, failoverVariant, variants=[]): """docstring for __init__""" self.key = key self.failoverVariant = failoverVariant self.variants = [v.toJSON() for v in variants] def toJSON(self): """docstring for toJSON""" self._...
545
170
# Copyright (C) 2013 Nippon Telegraph and Telephone 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 appli...
913
272
import numpy as np import pytest import torch from numpy.testing import assert_almost_equal from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Vocabulary from allennlp.modules.token_embedders import BagOfWordCountsTokenEmbedder class T...
2,247
848
import tensorflow as tf import numpy as np def clipped_error(x): # Huber loss try: return tf.select(tf.abs(x) < 1.0, 0.5 * tf.square(x), tf.abs(x) - 0.5 ) except: return tf.where(tf.abs(x) < 1.0, 0.5 * tf.square(x), tf.abs(x) - 0.5 ) def linear(input_, output_size, stddev=0.02, bias_star...
1,020
377
"""Cell parameter random initializations.""" from typing import Any, Dict import numpy as np from ..parameters import ( Height, NewCellBendLowerLower, NewCellBendLowerUpper, NewCellBendOverallLower, NewCellBendOverallUpper, NewCellBendUpperLower, NewCellBendUpperUpper, NewCellLength1Me...
4,081
1,134
import qiskit import numpy as np import matplotlib.pyplot as plt import json from graph import * # Random comment P =1 def makeCircuit(inbits, outbits): q = qiskit.QuantumRegister(inbits+outbits) c = qiskit.ClassicalRegister(inbits+outbits) qc = qiskit.QuantumCircuit(q, c) q_input = [q[i] for i in ran...
7,540
2,774
# Copyright (c) 2021 OpenCyphal # This software is distributed under the terms of the MIT License. # Author: Pavel Kirienko <pavel@opencyphal.org> from ._app_descriptor import AppDescriptor as AppDescriptor from ._cmd import file_server as file_server
253
79
"""Simple code for training an RNN for motion prediction.""" import os import sys import time import numpy as np import torch import torch.optim as optim from torch.autograd import Variable import mtfixb_model import mtfixb_model2 import parseopts def create_model(args, total_num_batches): """Create MT model a...
15,959
5,605
# 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...
11,260
3,916
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """Module for assessing causal feature importance.""" import warnings from collections import OrderedDict, namedtuple import joblib import lightgbm as lgb from numba.core.utils import erase_traceback import numpy as np from...
91,964
24,264
''' problem-- Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers. For example, arr=[1,3,5,7,9]. Our minimum sum is 1+3+5+7=16 a...
1,365
424
from pprint import pprint from enum import Enum class Direction(Enum): UP = 'up' DOWN = 'down' LEFT = 'left' RIGHT = 'right' class Network: def __init__(self, diagramRows): self.diagram = self.setDiagram(diagramRows) self.currentPosition = self.setCurrentPosition() self.cur...
4,610
1,238
import argparse import copy import torch from torchvision.datasets import MNIST, CIFAR10 import torchvision.transforms as TF import torchelie as tch import torchelie.loss.gan.hinge as gan_loss from torchelie.recipes.gan import GANRecipe import torchelie.callbacks as tcb from torchelie.recipes import Recipe parser =...
2,639
1,046
print ("Hello Word!")
22
8
import xml.sax import rdflib from django.db import transaction from hs_core.serialization import GenericResourceMeta class RasterResourceMeta(GenericResourceMeta): """ Lightweight class for representing metadata of RasterResource instances. """ def __init__(self): super(RasterResourceMeta, s...
21,719
5,674
from setuptools import setup import versioneer packages = ['pygdf', 'pygdf.tests', ] install_requires = [ 'numba', ] setup(name='pygdf', description="GPU Dataframe", version=versioneer.get_version(), classifiers=[ # "Development Status :: 4 - Beta", "In...
857
259
from functools import partial from .multiagentenv import MultiAgentEnv import sys import os def env_fn(env, **kwargs) -> MultiAgentEnv: return env(**kwargs) REGISTRY = {} #REGISTRY["sc2"] = partial(env_fn, env=StarCraft2Env) def register_env(nm, env_class): global REGISTRY REGISTRY[nm] = partial(env_fn, ...
335
122
import os import os.path import sqlite3 import logging from typing import List from gumtree_watchdog.types import Listing, Contract, ListingWithChatId TConn = sqlite3.Connection DB_PATH = os.environ.get('GUMTREE_DB') def get_connection() -> TConn: if not DB_PATH: raise Exception("Please specify Sqlite3 db...
4,938
1,475
#section [initial] def _parameters_accessors_checks(): from finess.params import Parameter, Accessor, Check, \ CheckGreaterEqual, CheckGreaterThan, \ CheckOneOf, EnumParameterType parameters = [] checks = [] rhol = Parameter(variable_name = "rhol", ...
3,601
1,034
''' Chad Meadowcroft Credit to Sentdex (https://pythonprogramming.net/) ''' import asyncio async def find_divisibles(inrange, div_by): # Define division function with async functionality print("finding nums in range {} divisible by {}".format(inrange, div_by)) located = [] for i in range(inrange): ...
1,142
407
from setuptools import setup import os with open("README.md", "r", encoding="utf-8") as f: long_description = f.read() requirements = [] if os.path.isfile("./requirements.txt"): with open("requirements.txt", "r") as f: requirements = f.read() requirements = [x for x in requirements.split("\n") if ...
1,114
370
from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions from rest_framework.parsers import JSONParser from django.conf import settings import requests from api_test.common import MD5 from api_test.models import ProjectMember from django.contrib.auth.models import User,Group fr...
4,977
1,397
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: Qot_GetPriceReminder.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflect...
12,745
5,008
from django.db import models from django.db.models.deletion import CASCADE from accounts.models import User class Leave(models.Model): title = models.CharField(max_length=255, default='', blank=False) user = models.ForeignKey(User, on_delete=CASCADE, blank=False, related_name='leaves') creationDate = mode...
903
279
import time import numpy as np import vtk from vtk.util import numpy_support from svtk.lib.toolbox.integer import minmax from svtk.lib.toolbox.idarray import IdArray from svtk.lib.toolbox.numpy_helpers import normalize import math as m class VTKAnimationTimerCallback(object): """This class is called every few m...
22,021
7,142
import time import numpy as np from tqdm import tqdm from utils import RandomCNOT, RandomCNOTs def SimulatedAnnealing(quantum_count, layer_count, solver, epochs=100, save_path=None, global_best_score=0): #TODO: best_score = 0 cnot = RandomCNOTs(quantum_count, layer_count) sc, model = solver(cnot) ...
3,679
1,285
#!/usr/bin/env python # # Copyright 2013 Darragh Bailey # # 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...
4,113
1,292
from bot_interface import * import math class SeijiBot(BotBase): def __init__(self): self.initialized = False def initialize(self, gamestate): gamestate.log("Initializing...") #Getting UID self.uid = gamestate.bot.uid gamestate.log("This ship has uid " + str(self.ui...
24,625
8,664
_base_ = "./resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO_01_02MasterChefCan.py" OUTPUT_DIR = ( "output/gdrn/ycbvPbrSO/resnest50d_AugCosyAAEGray_BG05_visib10_mlBCE_DoubleMask_ycbvPbr100e_SO/09_10PottedMeatCan" ) DATASETS = dict(TRAIN=("ycbv_010_potted_meat_can_train_pbr",))
304
178
from datetime import date, datetime, timedelta import time START_DATE = date(2021, 5, 25) duration = timedelta(days=100) def countdown(): event_delta = LAST_DAY_OF_SCHOOL - datetime.now() print() print("\tTime until school is out for summer 2021:", end="\n\n") while event_delta.seconds > 0: h...
682
264
# https://leetcode.com/problems/palindrome-partitioning/ class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """
195
63
import numpy as np import keras import random from keras.datasets import mnist from keras import backend as K K.set_floatx('float64') class DataSource(object): def __init__(self): raise NotImplementedError() def partitioned_by_rows(self, num_workers, test_reserve=.3): raise NotImplementedError(...
6,071
2,237
# pylint: disable=C0121 """http://www.logilab.org/ticket/124337""" import gtk def print_some_constant(arg=gtk.BUTTONS_OK): """crash because gtk.BUTTONS_OK, a gtk enum type, is returned by astroid as a constant """ print(arg)
255
117
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = '' __author__ = 'HaiFeng' __mtime__ = '2016/8/16' """ import time from py_at.EnumDefine import * ######################################################################## class OrderItem(object): """策略信号""" #----------------------------------------------...
1,519
584
from __future__ import print_function, division import numpy as np from numpy import identity, dot, zeros, zeros_like def rf_den_via_rf0(self, rf0, v): """ Whole matrix of the interacting response via non-interacting response and interaction""" rf = zeros_like(rf0) I = identity(rf0.shape[1]) for ir,r in enume...
547
213
from app.model.model import Model class CompareUsers(Model): def get_compare_users(self, uid): cursor = self.matchadb.cursor() cursor.execute('SELECT whomid FROM likes WHERE whoid = %s', (uid,)) whomids = [item[0] for item in cursor.fetchall()] if len(whomids) == 0: rai...
669
198
import numpy as np import pytest from numpy.testing import assert_allclose from numpy.testing import assert_array_equal from sklearn.ensemble._hist_gradient_boosting.histogram import ( _build_histogram_naive, _build_histogram, _build_histogram_no_hessian, _build_histogram_root_no_hessian, _build_h...
9,004
3,416
from django.conf.urls import patterns, include, url from django.contrib import admin from gmappolygons import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^search', views.search, name='search'), url(r'^submit/$', views.submit, name='submit'), url(r'^show/(?P<area_id>\d+)/',...
349
122
from django.db import models from django import forms from django.contrib.auth.models import User from PIL import Image from django.utils.timezone import now class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) image = models.ImageField(upload_to="up...
2,407
747
import os import logging import numpy as np from typing import Optional import torch from torch.utils.data import DataLoader from ..eval import Metric from .dataset import CHMMBaseDataset from .dataset import collate_fn as default_collate_fn logger = logging.getLogger(__name__) OUT_RECALL = 0.9 OUT_PRECISION = 0.8 ...
19,880
5,754
from random import Random from collections_extended import setlist # The version of seeding to use for random SEED_VERSION = 2 # Common alphabets to use ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def shuffle(key...
6,881
2,513
"""Information for the outgoing response code - the HTTP response code (default is "200 Ok") headers - a list of key/value pairs used for the WSGI start_response """ code = None headers = [] def add_header(key, value): """Helper function to append (key, value) to the list of response headers""" headers....
377
112
jog = {} #pegando dados jog['Nome do jogador'] = str(input('Digite o nome do jogador: ')).strip().title() jog['Total partidas'] = int(input('Quantas partidas jogou: ')) #lista de gol gols = [] #Quantos gols em cada partida for i in range(0, jog['Total partidas']): gols.append(int(input(f'Quantos gols na partida ...
1,594
557
###################################################################### # # File: b2sdk/v1/account_info.py # # Copyright 2021 Backblaze Inc. All Rights Reserved. # # License https://www.backblaze.com/using_b2_code.html # ###################################################################### from abc import abstractmeth...
5,891
1,780
# -*- coding: utf-8 -*- """ pbkdf2 hashing handler module. """ import hashlib import re import pyrin.configuration.services as config_services import pyrin.security.utils.services as security_utils_services from pyrin.security.hashing.decorators import hashing from pyrin.security.hashing.handlers.base import Hashing...
9,539
2,426
'''Defines a pipeline step which prepares training and test data for named entity recognition. ''' import ast import json import pickle from mccore import EntityRecognizer from mccore import ner from mccore import persistence import pandas as pd from sklearn.utils import resample from src.step import Step class Pr...
8,652
2,357
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals __all__ = ['requireSklearn'] from jubakit.compat import PYTHON3 try: import embedded_jubatus embedded_available = True except ImportError: embedded_available = False try: import numpy import scipy ...
1,006
311
# -*- coding: utf-8 -*- """ Created on Wed Jun 28 13:03:05 2017 @author: ZHOU Yuncheng """ import cntk as C import _cntk_py import cntk.layers import cntk.initializer import cntk.losses import cntk.metrics import cntk.logging import cntk.io.transforms as xforms import cntk.io import cntk.train import os import numpy ...
9,859
3,384
# -*- coding: utf-8 -*- # __author__= "Ruda" # Date: 2018/10/16 ''' import os from rongcloud import RongCloud app_key = os.environ['APP_KEY'] app_secret = os.environ['APP_SECRET'] rcloud = RongCloud(app_key, app_secret) r = rcloud.User.getToken(userId='userid1', name='username', portraitUri='http://www.rongcloud.c...
948
403
from django.core.mail import EmailMessage from django.conf import settings def send_email(name, date, email): txt = """ <html> <body> <table cellpadding='0' cellspacing='0' width='100%' border='0'> <tbody> <tr> <td style='word-wrap:break-word;font-size:0px;padding:0px;padding-bottom:10px' alig...
2,132
875
''' Author: your name Date: 2021-12-25 17:33:51 LastEditTime: 2021-12-29 10:10:14 LastEditors: Please set LastEditors Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE FilePath: /yimingqin/code/WTAL-Uncertainty-Modeling/train.py ''' import torch import torch.nn a...
5,767
2,124
############################################################################### # Copyright (c) 2017-2020 Koren Lev (Cisco Systems), # # Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others # # # ...
3,597
1,095
"""`appengine_config` gets loaded when starting a new application instance.""" import vendor # insert `lib` as a site directory so our `main` module can load # third-party libraries, and override built-ins with newer # versions. vendor.add('lib') import os # Called only if the current namespace is not set. def namespa...
612
161
import KNN as K K.clearScreen() dataTraining= K.loadData("dataTraining.txt") X=dataTraining[:,0:3] initial_centroids=K.listToArray([[3, 3,3],[6, 2,4],[8,5,7]]) idx=K.KMean_Run(X,initial_centroids,5) K.SaveData(K.concatenateVectors(X,idx)) K.plotKNN2(X,idx)
270
141
#!/usr/bin/env python import pyqtgraph as pg from pyqtgraph import ViewBox from hummingbird.graphics.plotter_args import PlotBoxArgs from hummingbird.graphics.state_plot import StatePlot class StatePlotBox: def __init__(self, window, args): """ Create a new plotbox wrapper object Arguments: ...
3,793
1,174
import json #start print('start') with open('quizoutput.txt') as f: lines = f.readlines() print('loaded quiz data') print('changing to json') json_output = json.loads(lines[0]) print(json_output) with open('quizoutput.txt', 'w') as f: f.write(json_output) # for item in json_output: # print(item['ques...
348
125