text
string
size
int64
token_count
int64
from ..doctools import document from .geom_bar import geom_bar @document class geom_col(geom_bar): """ Bar plot with base on the x-axis This is an alternate version of :class:`geom_bar` that maps the height of bars to an existing variable in your data. If you want the height of the bar to represe...
834
279
from django.contrib import admin from .models import Search # Register your models here. admin.site.register(Search)
117
30
# Max-Heinrich Laves # Institute of Mechatronic Systems # Leibniz Universität Hannover, Germany # 2019 # Code From https://github.com/mlaves/bayesian-temperature-scaling import torch __all__ = ['accuracy', 'kl_loss', 'nentr', 'xavier_normal_init'] def accuracy(input, target): _, max_indices = torch.max(input.dat...
1,155
428
#!usr/bin/env python #! -*- coding: utf-8 -*- from __future__ import unicode_literals import re import traceback import urllib import pprint OPENING_QUOTES = set(['«', '„', '“']) CLOSING_QUOTES = set(['»', '“', '”']) QUOTES = OPENING_QUOTES | CLOSING_QUOTES | set(['"', "'"]) WHITESPACE = set([' ', ' ', '\n']) PUNCTUAT...
8,927
3,502
import random as random import numpy as np from dynamics import Simulator, Pursuer, Evader def test_evader(): num_d_states = 25 num_phi_states = 20 num_phi_d_states = 20 num_actions = 10 num_states = num_d_states*num_phi_states*num_phi_d_states num_epochs = 1000 p = Pursuer() e = Evader(num_d_states, num_phi...
1,029
451
import unittest from core.drive import copy from core.aesthetics import * class TestingDrivepy(unittest.TestCase): def test_copy_function(self): source_tests = [ r"D:\Alexzander__\programming\python\Python2Executable", r"D:\Alexzander__\programming\python\byzantion", ...
1,892
531
from app import app from flask_restful import Api from app.resources.auth import TokenResource api = Api(app) # Token resource api.add_resource(TokenResource, '/authservice/token', endpoint='auth_token')
207
60
# -- coding: utf-8 -- """ This module is an extension for xarray to provide rasterio capabilities to xarray datasets/dataarrays. Credits: The `reproject` functionality was adopted from https://github.com/opendatacube/datacube-core # noqa Source file: - https://github.com/opendatacube/datacube-core/blob/084c84d78cb6e1...
60,084
18,271
#! /usr/bin/env python import os import rospy import rospkg from readbag import restore from qt_gui.plugin import Plugin from python_qt_binding.QtCore import Qt from python_qt_binding import loadUi from python_qt_binding.QtGui import QFileDialog, QGraphicsView, QIcon, QWidget from PyQt4 import QtGui, QtCore from exam...
905
302
import models import os import copy import torch import torch.nn as nn from lifelines import KaplanMeierFitter as KMFitter import pycox import numpy as np # local import catdist import data_utils import _concordance import _nll import _saver def str_to_bool(arg): """Convert an argument string into its boolean val...
2,387
935
from distutils.core import setup from pathlib import Path # TODO(joschnei): Add typing info setup( name="active", version="0.1", packages=["active",], install_requires=[ "scipy", "numpy", "driver @ git+https://github.com/jordan-schneider/driver-env.git#egg=driver", ], p...
377
131
import tableprint from collections import Counter from .args import * from .util import * if __name__ == "__main__": args = get_args() output_classes = Counter() question_types = Counter() with tableprint.TableContext(headers=["Type", "Question", "Answer"], width=[40,50,15]) as t: for i in read_gqa(args):...
762
293
#!/usr/bin/env python3 # Copyright (2021-) Shahruk Hossain <shahruk10@gmail.com> # # 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...
10,811
3,047
# Instruksi: # Buatlah komentar di garis pertama, # Buat variabel bernama jumlah_pacar yang isinya angka (bukan desimal), # Buat variabel bernama lagi_galau yang isinya boolean, # Buat variabel dengan nama terserah anda dan gunakan salah satu dari operator matematika yang telah kita pelajari. #variabel untuk menyimpan...
534
210
print((lambda x: lambda y: 2*x)(3)(4))
38
18
from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status, permissions import pyotp import base64 from rest_framework_simplejwt.tokens import RefreshToken from .serializers import CustomUserSerializer from .models import ...
3,612
1,035
"""Methods to convert between different file formats.""" import collections as col import gzip import os import re import Bio.PDB.Atom import Bio.PDB.Chain import Bio.PDB.Model import Bio.PDB.Residue import Bio.PDB.Structure import numpy as np import pandas as pd # -- MANIPULATING DATAFRAMES -- def split_df(df, ke...
22,550
8,175
# About: Implementation of the accumulator program # in python 3 specialization # ask to enter string phrase = input("Enter a string: ") # initialize total variable with zero tot = 0 # iterate through the string for char in phrase : if char != " " : tot += 1 # print the result print(tot)
304
88
class MapHash: def __init__(self, maxsize=6): self.maxsize = maxsize # Real scenario 64. self.hash = [None] * self.maxsize # Will be a 2D list def _get_hash_key(self, key): hash = sum(ord(k) for k in key) return hash % self.maxsize def add(self, key, value)...
2,014
699
import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--d_model', type=int, default=0, help='d_model') parser.add_argument('--d_head', type=int, default=2, help='head') parser.add_argument('--d_inner', type=bool, default=True, help='inner lay...
983
332
from django.forms import forms, ModelForm from .models import Comment, Post class CommentForm(ModelForm): class Meta: model = Comment fields = ['author_name', 'text'] labels = { 'author_name': 'Your name', 'text': 'Comment' } class PostForm(ModelForm): ...
628
173
import copy import logging import numpy as np import operator import pickle import random import mmcv import torch import torch.multiprocessing as mp import torch.utils.data as data from torch.utils.data import dataloader from detectron2.utils.serialize import PicklableWrapper from detectron2.data.build import worker_...
12,257
3,812
# -*- coding: utf-8 -*- # # django-coconuts # Copyright (c) 2008-2017, Jeremy Lainé # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above ...
4,204
1,451
# -*- coding: utf-8 -*- import datetime import os import subprocess from odoo import fields, models from odoo.tools import OrderedSet class MusicTranscoder(models.Model): _name = "oomusic.transcoder" _description = "Music Transcoder" _order = "sequence" name = fields.Char("Transcoder Name", require...
3,419
962
#Refer AlexNet implementation code, returns last fully connected layer fc7 = AlexNet(resized, feature_extract=True) shape = (fc7.get_shape().as_list()[-1], 43) fc8_weight = tf.Variable(tf.truncated_normal(shape, stddev=1e-2)) fc8_b = tf.Variable(tf.zeros(43)) logits = tf.nn.xw_plus_b(fc7, fc8_weight, fc8_b) probs = tf....
341
145
#!C:\Users\Administrator\Desktop\装饰器代码\venv\Scripts\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line()
169
62
import logging import sys import os from logging.handlers import RotatingFileHandler from multiprocessing.pool import ThreadPool from optparse import OptionParser import requests from requests.packages import urllib3 urllib3.disable_warnings() # Workers configurations ASYNC_WORKERS_COUNT = 100 # How many threads wi...
11,704
3,446
#Template of the Purkinje cell model, Zang et al. 2018 #Templating by Lungsi 2019 based on ~/PC2018Zang/purkinje.hoc #purkinje.hoc has been converted from original purkinje_demo and using readme.html as a guide from neuron import h #from pdb import set_trace as breakpoint from random import randint class Purkinje(obje...
1,432
514
from flask_babel import gettext from marshmallow import ValidationError import intelhex import zipfile def is_correct_file_type(filename): try: with zipfile.ZipFile(filename, "r") as _: pass except zipfile.BadZipfile: try: ih = intelhex.IntelHex() ih.loadhex(filename) except intelhex.IntelHexError: ...
375
138
# -*- coding: utf-8 -*- """Git functions for zazu.""" import zazu.imports zazu.imports.lazy_import(locals(), [ 'filecmp', 'git', 'os', 'pkg_resources', 'shutil', 'zazu.util', ]) __author__ = 'Nicholas Wiles' __copyright__ = 'Copyright 2016' def get_repo_root(starting_dir): """Get the roo...
3,203
1,098
""" @brief Class to store data from a specific event @date Created July 2, 2018 @author R. Joseph Paetz @bug No known bugs """ from fprime.common.models.serialize import time_type from fprime_gds.common.data_types import sys_data class EventData(sys_data.SysData): """ The EventData class stores a specific ...
4,284
1,145
import dadi, pickle import numpy as np import matplotlib.pyplot as plt fig = plt.figure(figsize=(8,6)) def plot_single_sfs(fs, projections, output, vmin): fs = dadi.Spectrum.from_file(fs) fig = plt.figure(219033) if len(fs.sample_sizes) == 1: if projections == None: projections = [20] ...
5,607
2,217
from .exports import ( # noqa create_account_from_zenmoney_account, delete_account, get_accounts_by_user, get_user_account_by_id, get_user_account_by_title, update_account_transactions_count, ) from .schemas import AccountModel # noqa from .tables import * # noqa
291
100
import time import logging import threading from collections import Counter _logger = logging.getLogger('akita') class SlidingWindowBase: """ Data structure that keeps track of the total number of events that have occurred in a given time frame. Events are binned into time windows based on their tim...
5,136
1,394
Schmoe Joe 12345 90 91 94 87 89 Doe Jane 74836 91 99 82 81 100
62
56
from os.path import exists, join import pytest from flask_dj import startproject from tests.basic_project_creator import ProjectCreate class TestBaseSettingProjectConstructor(ProjectCreate): def setup(self, need_static=False, need_templates=False): super().setup() def test_project_folder_exist(self):...
2,360
725
def isSubsetSum(arr, n, sum): ''' Returns true if there exists a subset with given sum in arr[] ''' # The value of subset[i%2][j] will be true # if there exists a subset of sum j in # arr[0, 1, ...., i-1] subset = [[False for j in range(sum + 1)] for i in range(3)] for i in range(n...
1,075
382
# -*-coding: utf-8-*- # @Author : Charlesxu # @Email : charlesxu.ai@gmail.com from models.matching import * class FFM_Layer(Layer): def __init__(self, dense_feature_columns, sparse_feature_columns, k, w_reg=1e-4, v_reg=1e-4): super(FFM_Layer, self).__init__() self.dense_feature_columns = dense_...
3,156
1,008
from django.test import TestCase from rest_framework.test import APIRequestFactory from .views import LoginView, SignupView from common.tests import USER_DATA, prepare_dummy_user_data # Create your tests here. class ApiViewTests(TestCase): factory = APIRequestFactory() def test_signup(self): user_da...
1,822
580
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ''' Utility functions for all things related to manipulating google play services related files. ''' import argparse import filecmp import json import loggi...
5,205
1,582
# -*-coding: utf-8 import sys import argparse from tagger import FileTagger def tagger_add(args): tg = FileTagger() res = tg.add_tags(args.path, *args.tags) if not res: print("[-] Fail to add tags.") def tagger_rm(args): tg = FileTagger() res = tg.rm_tags(args.path, *args.tags) if n...
4,179
1,412
import numpy as np import argparse import pycountry import lang2vec.lang2vec as l2v from sklearn import preprocessing, linear_model, svm from lang_vec.lang_vec_tools import load_lang_vec from utils.tools import read_data from typing import Dict def get_language_alpha3(language_code: str): if len(language_code) ==...
4,487
1,495
import os FILES_TO_REMOVE = ["setup.cfg", "pyproject.toml", "setup.py"] if "{{ cookiecutter.as_package }}" == "no": for file in FILES_TO_REMOVE: os.remove(file) if "{{ cookiecutter.remove_test_script }}" == "yes": os.remove("test_log.py")
258
103
from django import forms from crispy_forms.helper import FormHelper class MiscForm(forms.Form): notes = forms.CharField( label='Notes for the registration team', help_text='Anything else you need to describe. ' 'The registration team will see this. ' 'The bursa...
620
176
#Import libraries import cv2 #Read image file into n dimensional numpy array #Read as greyscale image -> 0, Read as color image w/o transparency -> 1, Read as color image w transparency -> -1 img = cv2.imread("Practice/images/galaxy.jpg", 0) print(type(img)) print(img) #To know the number of rows and columns print(i...
948
332
tup = ('a','b',1,2,3) print(tup[0]) print(tup[1]) print(tup[2]) print(tup[3]) print(tup[4])
94
59
import asyncio from .main import create_app loop = asyncio.get_event_loop() app = create_app(loop)
101
38
import io, re, codecs, sys, os.path import pprint REG = 0 SHFT = 1 CTRL = 2 ALT = 4 ALTGR = 6 COMPRESSED_OUTPUT=1 def get_kbd_layout(base_filename, load_patch = False): filename_klc = base_filename filename_changes = base_filename + 'patch' f = io.open(filename_klc, mode="r", encoding="utf-8") lines = f.r...
16,419
8,486
import socket,time tcpSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print "try connect",tcpSock tcpSock.connect(('169.254.1.1',2000)) print "connected - wait for response" print tcpSock.recv(8) time.sleep(0.1) tcpSock.send("$$$") time.sleep(0.5) print tcpSock.recv(1024) print "Param set" tcpSock.se...
1,219
502
from __future__ import annotations from typing import TYPE_CHECKING, Any, Callable, ClassVar, TypeVar from typing_extensions import final from returns.context import NoDeps from returns.interfaces.specific import reader_result from returns.primitives.container import BaseContainer from returns.primitives.hkt import ...
20,582
5,734
import pandas as pd from gooey import Gooey, GooeyParser import numpy as np import xlsxwriter import xlrd @Gooey(program_name="FEC FILE FOR FRANCE", required_cols= 4,default_size=(710, 700),navigation='TABBED', header_bg_color = '#48a7fa') def parse_args(): parser = GooeyParser() FilesGL = par...
86,104
33,502
"""Code for turning user delineations into dense segmentations.""" import json import numpy as np import nibabel as nib from PIL import Image, ImageDraw from numpy.core.fromnumeric import cumsum import torch import torch.nn.functional from scipy import signal from skimage import measure import cv2 #pylint: disable=no...
25,479
9,556
from EvernoteController import EvernoteController from Memo import Memo MEMO_NAME = 'Memo' MEMO_DIR = 'Memo' MEMO_STORAGE_DIR = 'S-Memo' def f(fn, *args, **kwargs): try: fn(*args, **kwargs) except: pass m = Memo() e = EvernoteController() f(e.create_notebook, MEMO_DIR) f(e.cre...
458
202
import boto3 def handler(event, _): boto3.client('codebuild').start_build( projectName=event['Records'][0]['customData'])
128
45
# menu.py # 维护暂停界面 import pygame from pygame.locals import * import sys from utility import globe from process.scene import menu_confirm from PIL import Image, ImageFilter class Pause_Menu(object): # 暂停页面 def __init__(self): self.button_rect = [] self.rs = globe.destiny.rsManager.image ...
6,173
2,086
from setuptools import setup # get the version here pkg_vars = {} with open("version.py") as fp: exec(fp.read(), pkg_vars) setup( name='sn_simulation', version= pkg_vars['__version__'], description='Simulations for supernovae', url='http://github.com/lsstdesc/sn_simulation', author='Philippe...
602
227
import gc from unittest import TestCase from testing import await_true gc.collect() class TestGPSInteractive(TestCase): def test_read_value(self): import adafruit_blinka adafruit_blinka.patch_system() # needed before adafruit_gps imports time import microcontroller.pin gc.coll...
1,059
411
"""Exercício Python 64: Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag (999)).""" q = 0 s = 0 print('[Digit...
678
256
import base64 import contextlib import os import re import sys import tkinter as tk from tkinter import messagebox, ttk from AutoElectsysUtil import (config_file_name, course_rounds, file_read_json, file_read_lines, file_write_json, file_write_lines, first_categories, general_val...
25,202
9,251
"""React Preset""" import shutil import os from .Preset import Preset from ..utils.filesystem import make_directory from ..utils.location import resources_path, views_path class React(Preset): """ Configure the front-end scaffolding for the application to use ReactJS Will also remove Vue as Vue and Reac...
1,746
501
from django.db import models from django.core.validators import MinLengthValidator from apps.user.models import User from pangpangeats.settings import AUTH_USER_MODEL from apps.common.models import BaseModel from apps.common.validators import numeric_validator class CreditCard(BaseModel): owner: User = models.For...
1,445
431
import contextlib import datetime import json import StringIO from django.contrib.auth import logout as logout_user from django.contrib import messages from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponseRedirect, JsonResponse, Http404,...
13,450
3,965
from bs4 import BeautifulSoup import requests import os """ This script download all songs with given genre from midiworld.com """ genre_name = input( "type in genre name (lowercase, no space, no special characters): ") # Just in case someone don't respect the rules. genre_name = genre_name.lower() genre_name = g...
1,302
417
#!/usr/bin/env python # coding: utf-8 __author__ = 'Zhuo Zhang' __copyright__ = 'Copyright 2017-2020, Zhuo Zhang' __license__ = 'MIT' __version__ = '0.5' __email__ = 'imzhuo@foxmail.com' __status__ = 'Development' __description__ = 'Tkinter based GUI, visualizing PASCAL VOC object detection annotation' """ Changelog:...
23,446
8,057
import frappe def delete_approved_build_requests(): """ Scheduled hook to delete approved Review Requests for changing site deployments. """ approved_build_requests = frappe.get_all( "Review Request", filters={ "request_type": ["in", ["Build", "Upgrade", "Delete"]], "request_status": "Approved", }, ...
416
147
__author__ = 'QinyuanYe' import sys import random from shutil import copyfile # split the original train set into # 90% train-set (train_split.json) and 10% dev-set (dev.json) if __name__ == "__main__": random.seed(1234) if len(sys.argv) != 3: print 'Usage:feature_generation.py -DATA -ratio' ...
1,064
394
__author__ = 'dimd' from twisted.python import log from zope.interface import implementer from NetCatKS.Logger.api.interfaces import ILogger GLOBAL_DEBUG = True @implementer(ILogger) class Logger(object): def __init__(self): pass def debug(self, msg): if GLOBAL_DEBUG is True: ...
717
257
# coding: utf-8 from enum import Enum, unique @unique class FailureCategory(Enum): TEMPORARY_ISSUE = "TEMPORARY_ISSUE" INTERNAL = "INTERNAL" END_USER = "END_USER" CONFIGURATION = "CONFIGURATION" DEVELOPER = "DEVELOPER"
247
101
# -*- coding: utf-8 -*- """ Author: Xi Lin <xi.lin@my.cityu.edu.hk> website: http://www.cs.cityu.edu.hk/~xilin4/ github: This code is a demo for this paper: A Decomposition based Multiobjective Evolutionary Algorithm with Classification Xi Lin, Qingfu Zhang, Sam Kwong Proceedings of the...
20,146
6,472
## MIT LICENSE #Copyright (c) 2014 Hugo Arguinariz. #http://www.hugoargui.com # #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 u...
9,388
2,395
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: final = list() # ---------------------------------------------------- if len(nums)==1: return [[],nums] if len(nums)==0: return [] # ----------------------------------------------------...
733
188
import pandas as pd def parse_headered_csv (file: str, desired_keys: list): """ Takes a headered CSV file and extracts the columns with the desired keys :param file: CSV filename :param desired_keys: Names of columns to extract :return: pandas dataframe """ if file is None: return...
1,203
352
from plenum.test.bls.helper import check_bls_multi_sig_after_send from plenum.test.pool_transactions.conftest import looper, clientAndWallet1, \ client1, wallet1, client1Connected nodeCount = 4 nodes_wth_bls = 0 def test_each_node_has_bls(txnPoolNodeSet): for node in txnPoolNodeSet: assert node.bls_b...
660
235
metros = float(input('Quantos metros de piso vc deseja? ')) preco = 70 total = metros*preco print('O preço total do pedido é: R$ %.2f' % (total))
149
61
import base64 import os.path path=os.path.dirname(__file__) misha = base64.b64encode(open(os.path.join(path, "../Pics/Miahs.jpg"), "rb").read()).decode("UTF-8") yaroslav = base64.b64encode(open(os.path.join(path, "../Pics/Yaroslav.jpg"), "rb").read()).decode("UTF-8") goblin = base64.b64encode(open(os.path.join(path, ...
1,639
720
from rest_framework import serializers class HelloSerializer(serializers.Serializer): """Serializers a name field for testing our APIView""" name = serializers.CharField(max_length= 10)
202
56
from __future__ import division, print_function from .. import __version__ from ._global_imports import * try: import h5py except ImportError: print('Install h5py to enable signal caching.') raise class _Cache(object): """ Cache numerical model objects computed during likelihood evaluation. :pa...
7,116
1,879
from multiprocessing import Process, Manager ''' Custom Module Imports ''' from calculator.add import addition from calculator.subtract import subtraction from calculator.multiply import multiplication from calculator.divide import division class Main: def __init__(self) -> None: pass d...
1,234
380
"""minor fixes Revision ID: d7cd5138bb9b Revises: 0fed690a57ce Create Date: 2020-09-18 07:56:14.159782 """ from alembic import op import geoalchemy2 import sqlalchemy as sa import backend # revision identifiers, used by Alembic. revision = 'd7cd5138bb9b' down_revision = '0fed690a57ce' branch_labels = () depends_on ...
1,797
675
#!/usr/bin/python ''' creates bundle graph from filtered multigraph ''' ### imports ### import sys import os import logging import networkx as nx import numpy as np import scipy.stats as stats import cPickle import helpers.io as io import helpers.misc as misc ### definitions ### ### functions ### def compress_edg...
8,883
3,087
from .Arbitrage import ArbitrageEqualFundSimplePortfolio, \ ArbitrageEqualFundVolatilityPortfolio, ArbitrageStrategy from .BacktestEngine import BacktestEngine from .BacktestMarketSupply import BacktestMarketSupply from .BarBacktestExecution import BarBacktestExecution from .BarPortfolio import BarPortfolio from .I...
903
255
from .swin_stem_pooling5_transformer import swin_stem_pooling5_encoder from .swin_stem_pooling5_transformer import SwinStemPooling5TransformerMatting from .decoder import SwinStemPooling5TransformerDecoderV1 __all__ = ['p3mnet_swin_t'] def p3mnet_swin_t(pretrained=True, img_size=512, **kwargs): encoder = swin_...
529
207
""" Tests for Day 22 """ from day22.module import part_1, part_2, \ FULL_INPUT_FILE, TEST_INPUT_FILE_1, TEST_INPUT_FILE_2, TEST_INPUT_FILE_3 def test_part_1_1(): result = part_1(TEST_INPUT_FILE_1) assert result == 39 def test_part_1_2(): result = part_1(TEST_INPUT_FILE_2) assert result == 59078...
702
328
from spatial_kde import * from sklearn.model_selection import train_test_split import pandas as pd import matplotlib.pyplot as plt data_loc = "../../data/RPD_crime2011toNow.csv" data = process_RPD_data(data_loc) print("Loaded data") Y = data[["class"]] X = data[["X", "Y"]] print("Starting Predictions") n_trials = 25...
1,441
575
# -*- coding: utf-8 -*- # DO NOT EDIT THIS FILE! # This file has been autogenerated by dephell <3 # https://github.com/dephell/dephell try: from setuptools import setup except ImportError: from distutils.core import setup import os.path readme = "" here = os.path.abspath(os.path.dirname(__file__)) readme_p...
2,872
893
import ENVIRONMENT from src.database.database_creation import createPlayerTrueSkillDictionary from src.skill_algorithms.algorithms import trueSkillMatchWithRawNums, trueSkillTipWinProb from src.skill_algorithms.common_data_processing import beforeMatchPredictions, runAlgoForSeason, runAlgoForAllSeasons # backlogtodo...
5,840
2,017
# std import datetime from copy import deepcopy from collections import deque import yaml # from .lazy_loader import LazyLoader as LL # yaml = LL('yaml', globals(), 'yaml') # json = LL('json', globals(), 'json') # types from typing import Dict, Any, Union, Tuple __all__ = [ 'load_config_file', 'save_config...
7,881
2,403
__author__ = 'multiangle' # 这是实现 霍夫曼树相关的文件, 主要用于 针对层次softmax进行 word2vec 优化方案的一种 ''' 至于 为什么要进行层次softmax 可以简单理解 因为词表很大 针对上完个类别单词进行softmax 计算量大 更新参数过多 无法训练,而采用softmax 层次化 只需要 计算几个有限单词的sigmod 就可以 更新参数也非常少 提高训练速度 什么是霍夫曼树 简单理解就是 将训练文本 进行词频统计 通过构建加权最短路径来构造二叉树 这样 词频高的 位置在前 词频低的位置在后 每一个 霍夫曼编码代表一个词 路径 并且是唯一 不是其他词的前缀 ''' impo...
5,223
2,243
__all__ = [ "fit_gp", "ft_gp", "fit_lm", "ft_lm", "fit_rf", "ft_rf", "fit_kmeans", "ft_kmeans", ] ## Fitting via sklearn package try: from sklearn.base import clone from sklearn.linear_model import LinearRegression from sklearn.gaussian_process import GaussianProcessRegresso...
14,313
4,459
# Original source code: https://github.com/bklim5/python_video_indexer_lib import os import re import time import datetime import requests def get_retry_after_from_message(message): match = re.search(r'Try again in (\d+) second', message or '') if match: return int(match.group(1)) return 30 # ...
7,306
2,118
password="pbkdf2(1000,20,sha512)$b24904a15adb4514$85f395bc9c1f6be8227d9f7540e54127cd4f0fdf"
92
75
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.mail import Mail from config import ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, \ MAIL_PASSWORD, SQLALCHEMY_DATABASE_URI from .momentjs import momentjs from flask.json import JSON...
3,086
1,051
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser from collections import Counter from functools import partial from pathlib import Path from knarrow import find_knee def gte_0(value): x = float(value) assert x >= 0.0 return x METHODS = [ "angle", "c_method", "distance", ...
2,904
884
# coding: utf-8 from __future__ import absolute_import from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase from bitmovin_api_sdk.common.poscheck import poscheck_except from bitmovin_api_sdk.notifications.webhooks.encoding.encodings.finished.finished_api import FinishedApi from bitmovin_api_sdk.notifica...
2,129
674
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import gi gi.require_version("Gtk", "3.0") from gi.repository import GdkPixbuf import time import dbus __author__ = "Christian Heider Nielsen" __doc__ = ( "Based on the notifications spec at: http://developer.gnome.org/notification-spec/" ) __version__ = "0.0.1" EX...
12,581
3,878
from time import sleep from pymongo import MongoClient from FakePersona import getPage base_url = "https://www.exploit-db.com" def getExploitCategories(): #access page as fake persona soup = getPage(base_url) #find all list items <li> categories = soup.find("ul", {"class":"w-nav-list"}).findAll("li",...
2,863
866
from django.conf import settings from django.test import TestCase # Create your tests here. class SettingsTest(TestCase): def test_settings(self): self.assertEqual(settings.SERVER, 'prodserver.com') self.assertEqual( settings.STATIC_URL, '/changed/in/settings.toml/by/dynaconf/') ...
2,303
689
# -*- coding: utf8 -*- __author__ = 'Viktor Winkelmann' from Queue import Queue from Worker import Worker class Pool: def __init__(self, size): self.size = size self.workers = [] self.tasks = Queue() def _removeDeadWorkers(self): self.workers = [w for w in self.workers if w.is...
869
267
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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...
1,792
646
from flask import Flask, request, render_template, url_for from views import * app = Flask(__name__) app.secret_key = "mockapi.dev" urls = [ ('/', ['GET'], Start.as_view('view')), ('/login', ['GET','POST'], Log.as_view('log_alllist')), #- Login into mockapi ('/logout', ['GET'], Logout.as_view('logout')),...
845
329