content
stringlengths
27
928k
path
stringlengths
4
230
size
int64
27
928k
nl_text
stringlengths
21
396k
nl_size
int64
21
396k
nl_language
stringlengths
2
3
nl_language_score
float64
0.04
1
## # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed u...
python/pycylon/pycylon/common/__init__.py
557
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distrib...
517
en
0.872906
"""Support for interface with an Samsung TV.""" import asyncio from datetime import timedelta import logging import socket import voluptuous as vol from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( MEDIA_TYPE_CHANN...
homeassistant/components/samsungtv/media_player.py
9,626
Representation of a Samsung TV. Initialize the Samsung device. Create or return a remote control instance. Boolean if volume is currently muted. Send next track command. Send media pause command to media player. Send play command. Simulate play pause media player. Send the previous track command. Send mute command. Ret...
1,414
en
0.871632
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'everpro.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise Import...
backend/everpro/manage.py
627
Django's command-line utility for administrative tasks. !/usr/bin/env python
77
en
0.656913
# Copyright 2016 Google Inc. 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 a...
templates/container_vm.py
2,909
Generate configuration. Creates a Container VM with the provided Container manifest. Copyright 2016 Google Inc. 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.a...
722
en
0.849014
"""Data handling by server or instance.""" import json import urllib3 class DataHandler(object): """Handle data.""" def __init__(self, server_port=None): """Initialize. :param server_port: Int. local port. """ self.server_port = server_port self.logged_requests = {} ...
monitor_requests/data.py
3,207
Handle data. Initialize. :param server_port: Int. local port. Delete data from server if applicable. Log request, store traceback/response data and update counts. Retrieve data from server or instance. Data handling by server or instance.
239
en
0.700405
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, Group ) from phonenumber_field.modelfields import PhoneNumberField # For the signal from django.dispatch import receiver from django.urls import reverse from django.core.mail import send_mail from dja...
dentalapp-backend/dentalapp/userauth/models.py
3,401
Does the user have permissions to view the app `app_label`? Does the user have a specific permission? For the signal title: message: from: to: Simplest possible answer: Yes, always Simplest possible answer: Yes, always
220
en
0.949819
# Copyright 2015 Google Inc. 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 a...
tensorflow/python/kernel_tests/matmul_op_test.py
8,392
Tests for tensorflow.ops.math_ops.matmul. Copyright 2015 Google Inc. 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 requi...
1,032
en
0.820769
#!/usr/bin/env python # Copyright 2016 Vijayaditya Peddinti. # 2016 Vimal Manohar # Apache 2.0. """ This script is similar to steps/nnet3/train_dnn.py but trains a raw neural network instead of an acoustic model. """ from __future__ import print_function from __future__ import division import argpars...
egs/wsj/s5/steps/nnet3/train_raw_dnn.py
23,833
Get args from stdin. The common options are defined in the object libs.nnet3.train.common.CommonParser.parser. See steps/libs/nnet3/train/common.py Process the options got from get_args() The main function for training. Args: args: a Namespace object with the required parameters obtained from the fun...
1,900
en
0.770116
#!/usr/bin/env python # Script for grading performance. # Performance is graded by comparing the student's best wall-clock time # (not speedup) after running the code in 64, 128, and 240 thread # configurations for bfs, kbfs, pagerank, and graph decomp against the # reference solution. import re import subprocess imp...
jobs/grade_performance.py
1,864
!/usr/bin/env python Script for grading performance. Performance is graded by comparing the student's best wall-clock time (not speedup) after running the code in 64, 128, and 240 thread configurations for bfs, kbfs, pagerank, and graph decomp against the reference solution. runGraph returns the student's score and tot...
462
en
0.874077
""" Test module for Strava API reader base module """ import os import json import pytest from pandas import DataFrame, Timedelta, Timestamp from runpandas import read_strava from runpandas import types from stravalib.protocol import ApiV3 from stravalib.client import Client from stravalib.model import Stream pytestm...
runpandas/tests/test_strava_parser.py
7,371
@TODO: I needed to mock the behavior the `stravalib.client.get_activity_streams`, it isn't the best alternative for mock the request from strava by passing a json file. Test module for Strava API reader base module we don't use access token here, since we will mock the stravalib json response we don't use access toke...
532
en
0.836659
from flask import g from app.comm.CompositeOperate import CompositeOperate from app.comm.SqlExecute import SqlExecute from app.module_config import table_module_map class CommentController(CompositeOperate): def __init__(self, module): super(CommentController, self).__init__(module) def after_deal_get...
blog_server/app/api/general/CommentController.py
1,600
่Žทๅ–็”จๆˆท็‚น่ตž่ฎฐๅฝ• ็‚น่ตž่ฎฐๅฝ• ๆ‰€ๆœ‰่ฏ„่ฎบๆ น่Š‚็‚น,ๆทปๅŠ ็”จๆˆทๆ˜ฏๅฆ็‚น่ตžๆ ‡ๅฟ— new_comments = [comment for comment in comments if not comment['bc_commentupid']] ่Žทๅ–ๆฏไธช่ฏ„่ฎบ็š„ๅ›žๅค
124
zh
0.560331
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPCs related to blockchainstate. Test the following RPCs: - getblockchaininfo - gettxouts...
test/functional/rpc_blockchain.py
12,336
Test RPCs related to blockchainstate. Test the following RPCs: - getblockchaininfo - gettxoutsetinfo - getdifficulty - getbestblockhash - getblockhash - getblockheader - getchaintxstats - getnetworkhashps - verifychain Tests correspond to code in rpc/blockchain.cpp. !/usr/bin/env ...
1,718
en
0.759356
# 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...
tests/utilities/test_deepspeed_collate_checkpoint.py
2,267
Test to ensure that with DeepSpeed Stage 3 we can collate the sharded checkpoints into a single file. 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:...
759
en
0.889291
"""meiduo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based ...
meiduo/meiduo/apps/users/urls.py
1,779
meiduo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vie...
622
en
0.608713
import pygame # TODO: make these configurable c_UP = pygame.K_UP c_DOWN = pygame.K_DOWN c_LEFT = pygame.K_LEFT c_RIGHT = pygame.K_RIGHT c_PREV = pygame.K_LEFTBRACKET c_NEXT = pygame.K_RIGHTBRACKET c_START = pygame.K_RETURN c_1 = pygame.K_1 c_2 = pygame.K_2 c_3 = pygame.K_3 c_4 = pygame.K_4 c_5 = pygame.K_5 c_6 = py...
ceControl.py
664
TODO: make these configurable
29
en
0.38381
import argparse import cv2 import numpy as np from onnxruntime.quantization import quantize_static, CalibrationDataReader, QuantType from onnxruntime.quantization.calibrate import CalibrationMethod from onnxruntime.quantization.quant_utils import QuantFormat from dataset import pre_process_vgg def parse_args(): ...
closed/FuriosaAI/code/quantization/mlperf_evaluation/python/ort_quantization.py
2,771
https://github.com/microsoft/onnxruntime/blob/master/onnxruntime/python/tools/quantization/notebooks/imagenet_v2/mobilenet.ipynb image_filepath = images_folder + '/' + image_name
178
en
0.615625
# -*- coding: utf-8 -*- import logging from dbaas_dbmonitor.provider import DBMonitorProvider from workflow.steps.util.base import BaseInstanceStep LOG = logging.getLogger(__name__) class DBMonitorStep(BaseInstanceStep): def __init__(self, instance): super(DBMonitorStep, self).__init__(instance) ...
dbaas/workflow/steps/util/db_monitor.py
3,916
-*- coding: utf-8 -*-
21
en
0.767281
import os from dataclasses import dataclass, field from enum import Enum from typing import Any, Optional from yarl import URL @dataclass(frozen=True) class ServerConfig: host: str = "0.0.0.0" port: int = 8080 name: str = "Docker Registry" @dataclass(frozen=True) class AuthConfig: server_endpoint_u...
platform_registry_api/config.py
6,717
TODO: should be derived from the WWW-Authenticate header instead https://github.com/docker/distribution/blob/dcfe05ce6cff995f419f8df37b59987257ffb8c1/registry/handlers/catalog.goL16
181
en
0.57769
# Copyright 1997 - 2018 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, p...
RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/openflow/writeactionsmisslearnedinfo.py
4,134
The WriteActionsMissLearnedInfo class encapsulates a system managed writeActionsMissLearnedInfo node in the ixnetwork hierarchy. An instance of the class can be obtained by accessing the WriteActionsMissLearnedInfo property from a parent instance. The internal properties list will be empty when the property is accesse...
2,922
en
0.809345
# -*- coding: utf-8 -*- ''' Globals variables ''' # ################################################################################## # MG ILLUMINATION # # First Crazy Debroussailleur : jDepoortere # # Author : cPO...
__InK__connect.py
2,488
-*- coding: utf-8 -*- MG ILLUMINATION First Crazy Debroussailleur : jDepoortere Author : cPOTTIER Date : 12-05-2016 ...
505
en
0.210847
import re import discord from discord.ext import commands from discord.ext.commands import clean_content from Util import Configuration, GearbotLogging, Permissioncheckers, Translator, Utils INVITE_MATCHER = re.compile(r"(?:https?:\/\/)?(?:www\.)?(?:discord\.(?:gg|io|me|li)|discordapp\.com\/invite)\/([\w|\d|-]+)", f...
GearBot/Cogs/Censor.py
2,144
we failed? guess we lost the race
33
en
0.961133
#!/usr/bin/env python """ python list_bundles.py prod b6dc9b93-929a-45d0-beb2-5cf8e64872fe python list_bundles.py staging 3b41f062-621c-46ca-abad-bce09427934d """ import argparse import json import logging import sys from ingest.api.ingestapi import IngestApi logging.getLogger('ingest').setLevel(logging.DEBUG) form...
list_bundles.py
1,889
python list_bundles.py prod b6dc9b93-929a-45d0-beb2-5cf8e64872fe python list_bundles.py staging 3b41f062-621c-46ca-abad-bce09427934d !/usr/bin/env python
154
en
0.122515
# -*- coding: utf-8 -*- """ Code to take template spectra, used for RV fitting, and pass them through 4FS to resample them to 4MOST's resolution. It then further resamples each arm onto a fixed logarithmic stride. """ import argparse import hashlib import logging import numpy as np import os from os import path as os...
src/pythonModules/fourgp_rv/fourgp_rv/templates_resample.py
10,666
A simple command-line interface for running a tool to resample a library of template spectra onto fixed logarithmic rasters representing each of the 4MOST arms. We use the python argparse module to build the interface, and return the inputs supplied by the user. :param root_path: The root path of this 4GP install...
3,217
en
0.807205
#!/usr/bin/env python import sys import os sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '../lib'))) import init import config import misc from kzcashd import KZCashDaemon from models import Superblock, Proposal, GovernanceObject, Watchdog from models import VoteSignals, VoteOutcomes, Transie...
bin/sentinel.py
8,161
!/usr/bin/env python sync kzcashd gobject list with our local relational DB backend delete old watchdog objects, create new when necessary delete expired watchdogs now, get all the active ones... none exist, submit a new one to the network create/submit one highest hash wins if remaining Watchdogs exist in the list, vo...
1,902
en
0.836922
""" """ import numpy as np from ..stellar_ages import _get_lg_age_bin_edges, _get_lgt_birth, T_BIRTH_MIN from ..stellar_ages import _get_sfh_tables, _get_age_weights_from_tables from ..sfh_model import DEFAULT_MAH_PARAMS, DEFAULT_MS_PARAMS, DEFAULT_Q_PARAMS from ..utils import _jax_get_dt_array FSPS_LG_AGES = np.aran...
dsps/tests/test_stellar_ages.py
3,374
log10 ages in years Msun/Gyr Analytically calculate age distributions for constant SFR (independent of t_obs) Calculate age distributions with DSPS Analytically calculate age distributions for SFR(t) = t Calculate age distributions with DSPS
241
en
0.848496
# -*- coding: utf-8 -*- """ Created on Sun Mar 09 21:40:30 2014 @author: yyu """ import JBCWebAutomation as jbc today=jbc.GetToday() # to override the date: today='140305' in 'yymmdd' format ################################################################### print 'Start job for date ' + today +'...' jb...
JBCMain-Chinese.py
636
-*- coding: utf-8 -*- to override the date: today='140305' in 'yymmdd' format 0 for English
91
en
0.734573
import numpy as np from skmultiflow.drift_detection.base_drift_detector import BaseDriftDetector class ADWIN(BaseDriftDetector): """ Adaptive Windowing method for concept drift detection. Parameters ---------- delta : float (default=0.002) The delta parameter for the ADWIN algorithm. No...
src/skmultiflow/drift_detection/adwin.py
16,563
Adaptive Windowing method for concept drift detection. Parameters ---------- delta : float (default=0.002) The delta parameter for the ADWIN algorithm. Notes ----- ADWIN [1]_ (ADaptive WINdowing) is an adaptive sliding window algorithm for detecting change, and keeping updated statistics about a data stream. ADWI...
4,195
en
0.817724
from django.contrib import admin from django.db import transaction from zinc.models import Policy, PolicyMember class PolicyMemberInline(admin.TabularInline): readonly_fields = ('ip_enabled',) model = PolicyMember extra = 1 verbose_name = 'member' verbose_name_plural = 'members' def ip_enabl...
zinc/admin/policy.py
2,411
get_queryset prefetches related policy members so iterating over objects is ok because we are iterating over already fetched data
129
en
0.893911
from django.shortcuts import render from django.http import HttpResponse from rango.models import Category def index(request): category_list = Category.objects.order_by('-likes')[:5] context_dict = {} context_dict['boldmessage'] = 'Crunchy, creamy, cookie, candy, cupcake!' context_dict['categories'] =...
main/files/rango/views.py
1,100
Render the response and send it back!
37
en
0.912621
import numpy as np from math import cos, sin, atan2 from errors_exceptions import OpenRAVEException from openravepy import quatFromAxisAngle, matrixFromPose, poseFromMatrix, \ axisAngleFromRotationMatrix, KinBody, GeometryType, RaveCreateRobot, \ RaveCreateKinBody, TriMesh, Environment, DOFAffine, IkParameterization, I...
opentamp/src/core/util_classes/no_openrave_body.py
21,682
Set active dof index to the one we are interested This function is implemented to simplify jacobian calculation in the CollisionPredicate inds: Optional list of index specifying dof index we are interested in dof_value_map: A dict that maps robot attribute name to a list of corresponding values make sure only sets do...
797
en
0.621923
# coding: utf-8 """ Account API The <b>Account API</b> gives sellers the ability to configure their eBay seller accounts, including the seller's policies (the Fulfillment Policy, Payment Policy, and Return Policy), opt in and out of eBay seller programs, configure sales tax tables, and get account information...
src/ebay_rest/api/sell_account/models/rate_table_response.py
3,812
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Returns true if both objects are equal RateTableResponse - a model defined in Swagger Returns true if both objects are not equal For `print` and `pprint` Gets the rate_tables of this RateTableResponse. # noqa: E5...
1,486
en
0.66982
import numpy as np import sys, os, re, gzip, struct import random import h5py import copy from keras import backend as K from keras.utils import Sequence import keras.utils import tensorflow as tf import multi_utils import mat_utils class NbestFixedDataGenerator(Sequence): def __init__(self, file, key_file, batch...
nbest_multi_fixed_generator.py
7,333
[input_sequences, label_sequences, inputs_lengths, labels_length] label is a list of string starting from 0 w/o padding for convenience splitting labels (blocks, frames, feats) expand dimensions along with batch dim. (nbest, blocks, time, feats) transpose batch and block axes for outer loop in training transpose batch ...
474
en
0.857291
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import re import sys import urllib import tarfile import zipfile import os.path as osp from scipy.io import loadmat import numpy as np import h5py from torchreid.utils.iotools import mkdi...
torchreid/datasets/dukemtmcvidreid.py
6,052
DukeMTMCVidReID Reference: Wu et al. Exploit the Unknown Gradually: One-Shot Video-Based Person Re-Identification by Stepwise Learning. CVPR 2018. URL: https://github.com/Yu-Wu/DukeMTMC-VideoReID Dataset statistics: # identities: 702 (train) + 702 (test) # tracklets: 2196 (train) + 2636 (test) Check if all files are...
500
en
0.699843
# Copyright (c) 2019 Eric Steinberger import numpy as np from PokerRL.rl.base_cls.workers.WorkerBase import WorkerBase class EvaluatorMasterBase(WorkerBase): """ Baseclass to all Evaluators. An Evaluator is an algorithm to evaluate an agent's performance in a certain metric. """ def __init__(self,...
PokerRL/eval/_/EvaluatorMasterBase.py
7,634
Baseclass to all Evaluators. An Evaluator is an algorithm to evaluate an agent's performance in a certain metric. Args: t_prof (TrainingProfile) chief_handle (class instance or ray ActorHandle) evaluator_name (str): Name of the evaluator Registers a new experiment either for each player and t...
1,285
en
0.863197
# setup.py file from setuptools import find_packages, setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="my-lambdata-dspt5", # the name that you will install via pip version="1.0", author="Devvin Kraatz", author_email="devvnet97@gmai.com ", description="Made...
module2-oop-code-style-and-reviews/lambdata_dspt5/setup.py
709
setup.py file the name that you will install via pip required if using a md file for long desc license="MIT", keywords="", ["my_lambdata"]
138
en
0.628739
#! /usr/local/bin/python # pylint: disable=invalid-name # pylint: disable=missing-docstring with open("table.txt", "r") as f: print "projections = (" lines = f.readlines() units_list = [] for line in lines: lineparts = line.rstrip().split("|") epsg = lineparts[0] wkt = linepart...
projection-scraping/parseSRS.py
1,592
! /usr/local/bin/python pylint: disable=invalid-name pylint: disable=missing-docstring
86
en
0.48927
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestri...
python/ccxt/coingi.py
12,014
-*- coding: utf-8 -*- PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.mdhow-to-contribute-code ----------------------------------------------------------------------------- Python 3 Python 2 Panama, Bulgaria, China, US maximum number of depth ...
417
en
0.59014
# -*- coding: utf-8 -*- import json import copy import types import inspect import re import traceback import datetime import markdown2 import semver import functools import platform ############################################################################### ######################################################...
Lib/typeworld/api/__init__.py
128,690
This is the response expected to be returned when the API is invoked using the `?commands=endpoint` parameter. This response contains some mandatory information about the API endpoint such as its name and admin email, the copyright license under which the API endpoint issues its data, and whether or not this endpoint ...
11,648
en
0.72831
import json import datetime import traceback import re from base64 import b64encode from ast import literal_eval from flask import Blueprint, render_template, render_template_string, make_response, url_for, current_app, request, redirect, jsonify, abort, flash, session from flask_login import login_required, current_us...
powerdnsadmin/routes/admin.py
82,532
get the deletions and status changes deletion get the additions already checked for status change get the unchanged out_changes is a list of HistoryRecordEntry objects in which we will append the new changes a HistoryRecordEntry represents a pair of add_rrest and del_rrest not a record entry this is a new record (add_...
3,425
en
0.815857
import torch import numpy as np from torch import nn import torch.nn.functional as F class Actor(nn.Module): """For advanced usage (how to customize the network), please refer to :ref:`build_the_network`. """ def __init__(self, preprocess_net, action_shape, hidden_layer_size=128): super().__i...
tianshou/utils/net/discrete.py
2,575
For advanced usage (how to customize the network), please refer to :ref:`build_the_network`. For advanced usage (how to customize the network), please refer to :ref:`build_the_network`. For advanced usage (how to customize the network), please refer to :ref:`build_the_network`. s -> Q(s, \*) s -> V(s) x -> Q(x, \*)
316
en
0.882755
"""Fixer that changes raw_input(...) into input(...).""" # Author: Andre Roberge # Local imports from .. import fixer_base from ..fixer_util import Name class FixRawInput(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< name='raw_input' trailer< '(' [any] ')' > any* > ...
utils/py27/Lib/lib2to3/fixes/fix_raw_input.py
472
Fixer that changes raw_input(...) into input(...). Author: Andre Roberge Local imports
88
en
0.435662
""" This module is the commandline interface of bowl. Created on 14 March 2014 @author: Charlie Lewis """ import argparse from bowl.cli_opts import add from bowl.cli_opts import connect from bowl.cli_opts import delete from bowl.cli_opts import disconnect from bowl.cli_opts import grant from bowl.cli_opts import host...
bowl/cli.py
25,765
This class is responsible for all commandline operations. This module is the commandline interface of bowl. Created on 14 March 2014 @author: Charlie Lewis add !! TODO use default, and restructure if/else in add connect delete disconnect grant hosts images import use non-standard naming scheme to not conflict with p...
552
en
0.681088
from flask import render_template, Blueprint, request, current_app from flask_sqlalchemy import SQLAlchemy # from QA_api import get_traintest_images import QA_api from QA_config import config from QA_db import Image, Project, Job, Roi, get_latest_modelid, get_imagetable html = Blueprint("html", __name__, static_folde...
QA_html.py
7,023
from QA_api import get_traintest_images Get the image list for the project Get the image list for the project --- should not need this function Get the image list for the project Method 1 image = Image.query.filter_by(projId=project.id, name=image_name).first() image.nROIs = Roi.query.filter_by(imageId=image.id).count(...
608
en
0.560787
# -*- coding: utf-8 -*- from django.core.cache import get_cache from django.utils.functional import cached_property from jinja2 import BytecodeCache as _BytecodeCache class BytecodeCache(_BytecodeCache): """ A bytecode cache for Jinja2 that uses Django's caching framework. """ def __init__(self, cac...
django_jinja/cache.py
791
A bytecode cache for Jinja2 that uses Django's caching framework. -*- coding: utf-8 -*-
89
en
0.618019
from django.contrib import admin from .transitions import TransactionLog, TransitionLog, EvaluationLog # Register your models here. admin.site.register(TransactionLog) admin.site.register(TransitionLog) admin.site.register(EvaluationLog)
tira-application/src/tira/admin.py
239
Register your models here.
26
en
0.957485
from unittest import TestCase from pyVHDLParser.Blocks.List import PortList from pyVHDLParser.Blocks.List.PortList import PortListInterfaceSignalBlock from pyVHDLParser.Token import WordToken, StartOfDocumentToken, SpaceToken, CharacterToken, EndOfDocumentToken from...
tests/unit/SimpleBlockSequences/PortList.py
4,296
entity e is port ( port1 : bit ); end; entity e is port ( port1 : bit ; port2 : boolean ); end;
95
en
0.585833
# Future from __future__ import division, print_function, unicode_literals # Standard Library import time # Third Party import pytest import ratelimit # DocumentCloud from documentcloud.constants import RATE_LIMIT from documentcloud.exceptions import APIError, CredentialsFailedError # pylint: disable=protected-acce...
tests/test_client.py
3,349
Test getting access and refresh tokens using valid credentials Test getting access and refresh tokens using invalid credentials Test refreshing the tokens Test setting the tokens using credentials Test setting the tokens with no credentials Test setting the tokens using refresh token Future Standard Library Third Par...
683
en
0.731561
# -*- coding: utf-8 -*- """ Esendex sms gateway backend. (http://www.esendex.es/) Configuration example. ~~~~~~~~~~~~~~~~~~~~~~ Modify your settings.py:: ESENDEX_USERNAME = 'yourusername' ESENDEX_PASSWORD = 'mysecretpassword' ESENDEX_ACCOUNT = 'account-key-provided-by-esendex' ESENDEX_SANDBOX = F...
sendsms/backends/esendex.py
3,824
SMS Backend for esendex.es provider. The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private project in the access data are dynamic, and are stored in the database. A child class overrides the method "get_xxxx" to return data stored in the database. Parse http raw respone into python dictionary...
1,266
en
0.56139
import torch class FGM(): def __init__(self, model): self.model = model self.backup = {} def attack(self, epsilon=1e-6, emb_name='embed'): # emb_name่ฟ™ไธชๅ‚ๆ•ฐ่ฆๆขๆˆไฝ ๆจกๅž‹ไธญembedding็š„ๅ‚ๆ•ฐๅ for name, param in self.model.named_parameters(): if param.requires_grad and emb_name in nam...
modules.py
2,716
emb_name่ฟ™ไธชๅ‚ๆ•ฐ่ฆๆขๆˆไฝ ๆจกๅž‹ไธญembedding็š„ๅ‚ๆ•ฐๅ emb_name่ฟ™ไธชๅ‚ๆ•ฐ่ฆๆขๆˆไฝ ๆจกๅž‹ไธญembedding็š„ๅ‚ๆ•ฐๅ emb_name่ฟ™ไธชๅ‚ๆ•ฐ่ฆๆขๆˆไฝ ๆจกๅž‹ไธญembedding็š„ๅ‚ๆ•ฐๅ print (name) emb_name่ฟ™ไธชๅ‚ๆ•ฐ่ฆๆขๆˆไฝ ๆจกๅž‹ไธญembedding็š„ๅ‚ๆ•ฐๅ
144
zh
0.749797
import unittest import numpy as np import numpy.testing as npt import wisdem.drivetrainse.gearbox as gb class TestGearbox(unittest.TestCase): def setUp(self): self.inputs = {} self.outputs = {} self.discrete_inputs = {} self.discrete_outputs = {} # 5MW inputs self...
WISDEM/wisdem/test/test_drivetrainse/test_gearbox.py
8,440
5MW inputs self.assertEqual(self.outputs['gearbox_mass'], 0.0) self.assertEqual(self.outputs['gearbox_mass'], 0.0) self.assertEqual(self.outputs['gearbox_mass'], 0.0) self.assertEqual(self.outputs['gearbox_mass'], 0.0) self.assertEqual(self.outputs['gearbox_mass'], 0.0) self.assertEqual(self.outputs['gearbox_mass'], 0....
374
en
0.202779
# client-pypeln-pl.task.py from aiohttp import ClientSession, TCPConnector import asyncio import sys import pypeln as pl limit = 1000 urls = ("http://localhost:8080/{}".format(i) for i in range(int(sys.argv[1]))) async def fetch(url, session): async with session.get(url) as response: return await respo...
benchmarks/100_million_downloads/client-pypeln-io.py
534
client-pypeln-pl.task.py
24
ar
0.121497
from __future__ import annotations import time import disnake from disnake.ext import commands from PIL import Image from main import tracked_templates from utils.arguments_parser import MyParser from utils.pxls.template_manager import ( Combo, layer, ) from utils.setup import stats from utils.discord_utils i...
src/cogs/pxls_template/layer.py
2,968
Remove unused entries, equal to None Use the combo object here because it doesn't generate a placeable mask save the URL of the image sent to use it to generate templates later
176
en
0.82395
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2010 "cuda" import os from waflib import Task from waflib.TaskGen import extension from waflib.Tools import ccroot, c_preproc from waflib.Configure import conf class cuda(Task.Task): run_str = '${NVCC} ${CUDAFLAGS} ${CXXFLAGS} ${FRAMEWORKPATH_ST:FRAMEWORKPATH} ...
Firmware/ardupilot/modules/waf/playground/cuda/cuda.py
1,357
find the cuda include and library folders use ctx.program(source='main.c', target='app', use='CUDA CUDART') cuda !/usr/bin/env python encoding: utf-8 Thomas Nagy, 2010 this should not raise any error
201
en
0.483151
#!/usr/bin/python # -*- coding: utf-8 -*- from django import template from floreal import models as m register = template.Library() @register.filter def price(f): return u"%.02fโ‚ฌ" % f @register.filter def price_nocurrency(f): return u"%.02f" % f @register.filter def weight(w): if w>=1: return u"%.2...
floreal/templatetags/floreal_filters.py
1,059
!/usr/bin/python -*- coding: utf-8 -*-
38
en
0.437977
# Copyright 2011 Justin Santa Barbara # Copyright 2012 Hewlett-Packard Development Company, L.P. # # 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/lic...
ironic/tests/unit/common/test_utils.py
26,630
Copyright 2011 Justin Santa Barbara Copyright 2012 Hewlett-Packard Development Company, L.P. 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....
1,958
en
0.788418
# Copyright (c) 2019 Bernd Wiesner. bernduwiesner@yahoo.co.uk # All rights reseArgumentS_Resultsed # """ Display the command line options in a window """ from argparse import Namespace from typing import Tuple, Union import PySimpleGUI as sg import constants as C from gui_utility import popup_window ArgumentsR...
gui_arguments.py
6,700
Window interface :param args: the arguments passed from the command line :return: Tuple[Union[str, None], Namespace] - The new arguments Display the command line options in a window Copyright (c) 2019 Bernd Wiesner. bernduwiesner@yahoo.co.uk All rights reseArgumentS_Resultsed str int bool bool bool
306
en
0.348044
import itertools as it import re import string import warnings from xml.dom import minidom from manimlib.constants import * from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import RoundedRectangle from manimlib.mobject.types.vectorized_mobject...
manimlib/mobject/svg/svg_mobject.py
15,787
Must be filled in in a subclass, or when called if False, creates a hierarchy of VGroups "fill_color" : LIGHT_GREY, TODO, handle style TODO warnings.warn("Unknown element type: " + element.tagName) Remove initial "" character TODO, This seems hacky... <circle class="st1" cx="143.8" cy="268" r="22.6"/> input preprocessi...
1,256
en
0.712923
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2019 Zimeng Qiu <zimengq@andrew.cmu.edu> """ F19 11-411/611 NLP Assignment 3 Task 1 N-gram Language Model Implementation Script Zimeng Qiu Sep 2019 This is a simple implementation of N-gram language model Write your own implementation in this file! """ ...
lm.py
10,230
Base class for all language models Initialize language model :param corpus: input text corpus to build LM on :param ngram: number of n-gram, e.g. 1, 2, 3, ... :param min_freq: minimum frequency threshold to set a word to UNK placeholder set to 1 to not use this threshold :param uniform: boolean flag, s...
2,151
en
0.675535
""" --- title: Compressive Transformer Experiment summary: This experiment trains a compressive transformer model on tiny Shakespeare dataset. --- # Compressive Transformer Experiment This is an annotated PyTorch experiment to train a compressive transformer model. """ from typing import List, Tuple, NamedTuple impo...
labml_nn/transformers/compressive/experiment.py
13,020
## Auto regressive model ## Configurations The default configurations can and will be overridden when we start the experiment. ### Initialize the attention reconstruction loss ### Initialize the auto-regressive model ### Run the experiment Concatenate new memories and compress the oldest memories. ### Sampling functio...
3,868
en
0.788086
# coding:utf8 from flask import request routes = dict() class ApiServiceBase(type): def __new__(cls, name, base, attrs): # super(type, obj) require isinstance(obj, type) return super(ApiServiceBase, cls).__new__(cls, name, base, attrs) def __init__(self, name, base, attrs): if name == 'ApiService': pas...
flask/api_service.py
650
coding:utf8 super(type, obj) require isinstance(obj, type)
58
en
0.53124
""" # EXCEL SHEET COLUMN TITLE Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 Output: "A" Example 2: Input: 28 Output: "AB" Example 3: Input: 70...
Leetcode/easy/excel-sheet-column-title.py
705
# EXCEL SHEET COLUMN TITLE Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 Output: "A" Example 2: Input: 28 Output: "AB" Example 3: Input: 701 Out...
329
en
0.601338
from __future__ import print_function import random import struct import sys import time import os import zmq from msgpack import ExtType, packb, unpackb class AlignClient(object): # A synchronous Python2 alignment client REQ_PREFIX = struct.Struct('=HH') REQ_SUFFIX = struct.Struct('=Ld') RESP = st...
pomoxis/align/py2client.py
2,106
A synchronous Python2 alignment client
38
en
0.720643
########################################################################## # # Copyright (c) 2017, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
python/GafferDelightUITest/DocumentationTest.py
2,151
Copyright (c) 2017, John Haddon. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the fol...
1,572
en
0.888161
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # --------------------------------------------...
skbio/stats/ordination/_correspondence_analysis.py
7,512
Compute correspondence analysis, a multivariate statistical technique for ordination. In general, rows in the data table will correspond to sites and columns to species, but the method is symmetric. In order to measure the correspondence between rows and columns, the :math:`\chi^2` distance is used, and those distance...
4,828
en
0.817447
""" Projection class for the Sunyaev-Zeldovich effect. Requires SZpack (version 1.1.1), which is included in SZpack.v1.1.1 and will be automatically installed. Website for the SZpack library: http://www.chluba.de/SZpack/ For details on the computations involved please refer to the following references: Chluba, Nagai, ...
pymsz/SZpack_models.py
24,244
Theoretical calculation of y and T_sz -map for the thermal SZ effect. model = TH_model(model_file, npixel, axis) Parameters ---------- simudata : the simulation data from load_data freqs : The frequencies (in GHz) at which to compute the SZ spectral distortion. array_like npixel : number of pixels for your image,...
20,623
en
0.525232
""" Example file on how to display a networkx graph on a browser """ import json import networkx as nx from networkx.readwrite import json_graph import http_server import random # https://www.alanzucconi.com/2015/11/03/recreational-maths-python/ # Converts a number in the list of its digits def int_to_list(n): #...
program.py
1,169
Example file on how to display a networkx graph on a browser https://www.alanzucconi.com/2015/11/03/recreational-maths-python/ Converts a number in the list of its digits The number is firstly converted into a string using str(n) map -> converts each character of the string into an integer https://www.alanzucconi.com...
515
en
0.819458
# TODO: not very happy with this state of affairs of having unencrypted passwords (use keyring ?) ALYX_PWD = 'alyxpassword' HTTP_DATA_SERVER_PWD = 'httpserverpass' # password for flat iron server for IBLail
python/oneibl/params_secret.py
208
TODO: not very happy with this state of affairs of having unencrypted passwords (use keyring ?) password for flat iron server for IBLail
136
en
0.888545
from typing import Optional, List from pydantic import BaseModel class LogSetting(BaseModel): LOG_LEVEL: Optional[str] = 'DEBUG' LOG_PATH: str class ServiceSetting(BaseModel): # openapi swagger INCLUDE_IN_SCHEMA: Optional[bool] = True # socket.io on SOCKET_IO_ON: Optional[bool] = False c...
conf/settings.py
448
openapi swagger socket.io on
28
en
0.515969
# -------------- # Importing header files import numpy as np # print(path) # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Code starts here census = np.array([]) data=np.genfromtxt(path, delimiter=",", skip_header=1) census = np.conc...
Make-Sense-of-census/code.py
2,474
-------------- Importing header files print(path) Path of the file has been stored in variable called 'path'New recordCode starts here print(census) --------------Code starts here -------------- Code starts here race_0 = np.array([]) race_1 = np.array([]) race_2 = np.array([]) race_3 = np.array([]) race_4 = np.array([]...
1,273
en
0.314756
""" Generate and operate on geometric elements and meshes. """ from __future__ import absolute_import from .geometry import Polygon, Square, Prism, Tesseroid, Sphere from .geometry import PolygonalPrism from .mesh import SquareMesh, PointGrid, PrismRelief, PrismMesh, TesseroidMesh
fatiando/mesher/__init__.py
283
Generate and operate on geometric elements and meshes.
54
en
0.811383
import subprocess import gdspy import shutil from utils import * from codegen.caravel_codegen import generate_openlane_files from urllib.parse import urlparse import os, json REQUIRED_KEYS_SINGLE = ["project", "caravel_test", "module_test", "wrapper_proof", "openlane", "gds"] class Project(object): def __init__...
project.py
16,201
the repo on github not strictly a commit, could be a branch the project's directory is made by joining project dir to last part of the repo url print out info about the project don't run this as part of test-all currently broken, waiting on testing a new netgen hack - better to add this to the info.yaml but for now we...
1,430
en
0.892664
""" MX Platform API The MX Platform API is a powerful, fully-featured API designed to make aggregating and enhancing financial data easy and reliable. It can seamlessly connect your app or website to tens of thousands of financial institutions. # noqa: E501 The version of the OpenAPI document: 0.1.0 ...
test/test_statement_response.py
935
StatementResponse unit test stubs Test StatementResponse MX Platform API The MX Platform API is a powerful, fully-featured API designed to make aggregating and enhancing financial data easy and reliable. It can seamlessly connect your app or website to tens of thousands of financial institutions. # noqa: E501 The ve...
514
en
0.795463
"""Criteria for parametric methods. .. topic:: This module provides criteria to automatically select order in parametric PSD estimate or pseudo spectrum estimates (e.g, music). Some criteria such as the AIC criterion helps to chose the order of PSD models such as the ARMA model. Nevertheless, it is diffic...
src/spectrum/criteria.py
9,878
Criteria class for an automatic selection of ARMA order. Available criteria are ======= ===================== ======= ===================== AIC see :func:`AIC` AICc see :func:`AICc` KIC see :func:`KIC` AKICc see :func:`AKICc` FPE see :func:`FPE` MDL see :func:`MDL` CAT see :func:`_CAT` ======...
5,225
en
0.65429
__author__ = "Laurence Elliott - 16600748" import os, math import numpy as np # sampleLens = [] # count = 0 # for file in os.listdir("corpus"): # sample = np.load("corpus/" + file) # zeroArr = [0] # try: # zerosInSample = np.isin(sample, zeroArr) # zerosIndexes = np.where(zerosInSample) # ...
bin-utf8-vec/truncateCorpus.py
1,226
sampleLens = [] count = 0 for file in os.listdir("corpus"): sample = np.load("corpus/" + file) zeroArr = [0] try: zerosInSample = np.isin(sample, zeroArr) zerosIndexes = np.where(zerosInSample) zerosStart = zerosIndexes[0][0] sample = sample[:zerosStart] sampleLen = l...
685
en
0.351961
# This file is part of the MapProxy project. # Copyright (C) 2010, 2011 Omniscale <http://omniscale.de> # # 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/L...
mapproxy/seed/seeder.py
19,719
:param coverage: area for the cleanup :param complete_extent: ``True`` if `coverage` equals the extent of the grid TileWalker traverses through all tiles in a tile grid and calls worker_pool.process for each (meta) tile. It traverses the tile grid (pyramid) depth-first. Intersection with coverages are checked before ha...
3,823
en
0.832963
import minimalmodbus import serial.tools.list_ports import argparse import time #Creates a new instance of a minimal modbus connection #Change portname to whatever you're using (/dev/USB0, COM4, etc) #Or just change it when you create the new serial object #247 is the default address for Renogy devices class RenogySma...
Renogy.py
5,034
Creates a new instance of a minimal modbus connectionChange portname to whatever you're using (/dev/USB0, COM4, etc)Or just change it when you create the new serial object247 is the default address for Renogy devicesReads number of CellsReads the Serial NumberGets unit current flow in A (0), unit voltage (1), capacity ...
1,188
en
0.779607
import pygame import random import helpers from ItemManager import ItemManager import scorer class BlockManager: def __init__(self,main): self.main = main self.blockSize = 75 self.gridWidth = 12 self.gridHeight = 12 self.grid = [] for x in range(0,self.gridWidth): newColumn = [] ...
src/BlockManager.py
5,318
Check for game over.If none in the top row were None:Check grid for triple adjacency.+self.blockSize/2 so it's in the center.Move all blocks down.From gridHeight-2 to 0. Blocks on the bottom (y=gridHeight - 1) won't move down no matter what.Remember: Blocks will not move right if there is a block directly below them.Fr...
761
en
0.883823
# coding: utf-8 """ Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environmen...
test/test_vnic_eth_adapter_policy_list.py
1,967
VnicEthAdapterPolicyList unit test stubs Test VnicEthAdapterPolicyList Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analy...
1,453
en
0.888637
import logging from pyrogram.errors import InputUserDeactivated, UserNotParticipant, FloodWait, UserIsBlocked, PeerIdInvalid from info import AUTH_CHANNEL, LONG_IMDB_DESCRIPTION, MAX_LIST_ELM from imdb import IMDb import asyncio from pyrogram.types import Message from typing import Union import re import os from dateti...
untils.py
11,861
temp db for banned https://t.me/GetTGLink/4183 https://github.com/odysseusmax/animated-lamp/blob/2ef4730eb2b5f0596ed6d03e7b05243d93e3415b/bot/utils/broadcast.pyL37 https://github.com/SpEcHiDe/PyroGramBot/blob/f30e2cca12002121bad1982f68cd0ff9814ce027/pyrobot/helper_functions/extract_user.pyL7 don't want to make a reque...
635
en
0.683476
""" #Trains a ResNet on the CIFAR10 dataset. """ from __future__ import print_function import keras from keras.layers import Dense, Conv2D, BatchNormalization, Activation from keras.layers import AveragePooling2D, Input, Flatten from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, LearningRa...
examples/pwr_run/checkpointing/timed/max_par/job2.py
7,697
#Trains a ResNet on the CIFAR10 dataset. Training parameters first step is to update the PID epochs = int(save_file.split('/')[4].split('_')[1].split('.')[0]) Subtracting pixel mean improves accuracy Model name, depth and version'P100_resnet50_he_256_1' Load the CIFAR10 data. Normalize data. If subtract pixel mean...
847
en
0.542521
# vmimages.py - azurerm functions for Microsoft.Compute RP publishers and images from .restfns import do_get from .settings import azure_rm_endpoint, COMP_API # list_offers(access_token, subscription_id, location, publisher) # list available VM image offers from a publisher def list_offers(access_token, subscription...
mcazurerm/vmimages.py
2,530
vmimages.py - azurerm functions for Microsoft.Compute RP publishers and images list_offers(access_token, subscription_id, location, publisher) list available VM image offers from a publisher list_publishers(access_token, subscription_id, location) list available image publishers for a location list_skus(access_token, s...
548
en
0.667398
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or without # ...
auto1/venv/Lib/site-packages/pywinauto/timings.py
15,079
Central storage and manipulation of timing values Set all timings to the default time Set fast timing values Currently this changes the timing in the following ways: timeouts = 1 second waits = 0 seconds retries = .001 seconds (minimum!) (if existing times are faster then keep existing times) Set slow timing values ...
7,946
en
0.661094
from corvus.structures import Handler, Exchange, Loop, Update import corvutils.pyparsing as pp import os, sys, subprocess, shutil #, resource import re from scipy.interpolate import CubicSpline from scipy.integrate import quad from scipy.signal import convolve import numpy as np # Debug: FDV import pprint pp_debug = p...
corvus/mbconv.py
5,995
, resource Debug: FDV Define dictionary of implemented calculationsfor s in subs(['cell_vectors', 'cell_struct_xyz_red', 'cell_scaling_iso', 'cell_scaling_abc', 'number_density']): key = strlistkey(s) autodesc = 'Get ' + ', '.join(s) + ' using cif2cell' cost = 10 implemented[key] = {'type':'Exchange','out':...
1,080
en
0.510909
# https://adventofcode.com/2020/day/14 import itertools import re SAMPLE_PATH = "../../input/2020-14-sample.txt" INPUT_PATH = "../../input/2020-14-input.txt" def get_data(filename): with open(filename) as file: data = file.read().split("\n\n") data = [block.splitlines() for block in data] if l...
python/2020/day14.py
1,885
https://adventofcode.com/2020/day/14 4297467072083 5030603328768
64
en
0.462645
import copy from unittest import mock import matplotlib import pytest from matplotlib import pyplot as plt from matplotlib._pylab_helpers import Gcf @pytest.fixture(autouse=True) def mpl_test_settings(qt_module, mpl_test_settings): """ Ensure qt_module fixture is *first* fixture. We override the `mpl_te...
tests/test_backend_qt.py
9,414
Ensure qt_module fixture is *first* fixture. We override the `mpl_test_settings` fixture and depend on the `qt_module` fixture first. It is very important that it is first, because it skips tests when Qt is not available, and if not, then the main `mpl_test_settings` fixture will try to switch backends before the skip...
2,396
en
0.836091
import os from indexing.pathanalyzer import PathAnalyzer from indexing.pathanalyzerstore import PathAnalyzerStore class Indexer: """ Traverses the given directory using the DFS algorithm. Allows registering different rules for handling different file types and calls the associated PathAnalyzers and Collec...
src/indexing/indexer.py
5,037
Traverses the given directory using the DFS algorithm. Allows registering different rules for handling different file types and calls the associated PathAnalyzers and Collectors indirectly for each type. Initializes attributes and checks the maximum depth provided. Parameters ---------- max_depth : int The maximum...
1,377
en
0.770215
from __future__ import annotations import logging import os import time from functools import partial from typing import Callable, Optional, Sequence, Union import torch from hivemind.averaging.control import AveragingStage, StepControl from hivemind.compression import CompressionBase, NoCompression from hivemind.dh...
hivemind/optim/optimizer.py
44,615
hivemind.Optimizer wraps your regular PyTorch Optimizer for training collaboratively with peers. By default, Optimizer is configured to be exactly **equivalent to synchronous training** with target_batch_size. There are advanced options make training semi-asynchronous (delay_optimizer_step and delay_gradient_averaging...
15,444
en
0.802908
'''A temporarily outdated visualization module.''' import graphviz as gv from .model import Model def visualize(model: Model, structural_part=True, measurement_part=False, view=True, filename=None, title=''): """Visualization of SEM model via graphviz library. Keyword arguments: model ...
semopy/visualization.py
1,157
Visualization of SEM model via graphviz library. Keyword arguments: model -- A SEM model. structural_part -- Should structural part be visualised? measurement_part -- Should measurement part be visualised? view -- Should graph be displayed? filename -- Filename/path. title --...
372
en
0.632921
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
sdk/datamigration/azure-mgmt-datamigration/azure/mgmt/datamigration/models/migrate_sql_server_sql_db_task_properties.py
2,873
Properties for the task that migrates on-prem SQL Server databases to Azure SQL Database. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar errors: Array of errors. This is ignored if submitted. :vartype ...
1,666
en
0.51092
from setuptools import find_packages, setup setup( # Application info name="pytorch_common", version="1.5.3", author="Mihir Rana", author_email="ranamihir@gmail.com", description="Repo for common PyTorch code", long_description=open("README.md", "r", encoding="utf-8").read(), long_descr...
setup.py
993
Application info Packages that this package requires Optional dependencies for NLP related projects Add config and sql files to the package https://python-packaging.readthedocs.io/en/latest/non-code-files.html
209
en
0.638735
from torch import nn import torch.nn.functional as F from torch import distributions as pyd class TanhTransform(pyd.transforms.Transform): domain = pyd.constraints.real codomain = pyd.constraints.interval(-1.0, 1.0) bijective = True sign = +1 def __init__(self, cache_size=1): super().__in...
distributions/squashed_normal.py
1,544
We do not clamp to the boundary here as it may degrade the performance of certain algorithms. one should use `cache_size=1` instead We use a formula that is more numerically stable, see details in the following link https://github.com/tensorflow/probability/commit/ef6bb176e0ebd1cf6e25c6b5cecdd2428c22963fdiff-e120f70e92...
342
en
0.818183
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
src/tests/test_tracking/test_run_tracking.py
63,652
!/usr/bin/python Copyright 2018-2021 Polyaxon, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in w...
854
en
0.834254
# Copyright 2014 Joe Cora. # Revisions copyright 2017 Peter Cock. # All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Objects to represent NEXUS standard data type matrix coding....
Bio/Nexus/StandardData.py
3,980
Create a StandardData iterable object. Each coding specifies t [type] => (std [standard], multi [multistate] or uncer [uncertain]) and d [data] Returns the length of the coding, use len(my_coding). Returns the full coding as a python string, use str(my_coding). Deprecated Python 2 style alias for Python 3 style __next...
1,089
en
0.773303
""" Words analyses by Amardjia Amine. Free software utility which allows you to find the most frequent phrases and frequencies of words. French and English language texts are supported. It also counts number of words, characters, the lexical density, sentences...etc. https://github.com/Layto888/Words-Analysis...
words.py
8,602
Input : text file name Do some operations to a text and return results. count the total of characters without any space char count the average length of sentences avg = words / sentences This function will deduce language between French and English. Using the lexical words found on the text. select only the total of d...
1,718
en
0.810108
import logging as log import time from . import gitlab from .approvals import Approvals GET, POST, PUT, DELETE = gitlab.GET, gitlab.POST, gitlab.PUT, gitlab.DELETE class MergeRequest(gitlab.Resource): @classmethod def create(cls, api, project_id, params): merge_request_info = api.call(POST( ...
marge/merge_request.py
6,331
missing means auto-squash not supported GitLab botched the v4 api before 9.2.2 We wanted to rebase and someone just happened to press the button for us! if provided, ensures what is merged is what we want (or fails) 'id' needed for for GitLab 9.2.2 hack (see Approvals.refetch_info())
284
en
0.898337
import gdax import os import json API_KEY = os.environ['GDAX_API_KEY'] API_SECRET = os.environ['GDAX_API_SECRET'] API_PASS = os.environ['GDAX_API_PASS'] def main(): ''' Cancels all bitcoin orders. ''' client = gdax.AuthenticatedClient(API_KEY, API_SECRET, API_PASS) r = client.cancel_all(product='...
cancel.py
395
Cancels all bitcoin orders.
27
en
0.535647
import pyupbit import time from datetime import datetime # ์ดˆ๊ธฐํ™” ์ค€๋น„ def init_prepairing(investable_coins_map, all_market_codes, all_market_names, order_money): # ์ด์ „ ํˆฌ์ž ์‹œ ์ฝ”์ธ ๋ณ„ ์ „๋‚  ๋Œ€๋น„ ์ƒ์Šน๋ฅ  prev_coins_map = pyupbit.get_prev_dict(investable_coins_map, all_market_codes, all_market_names) # ํˆฌ์žํ•  ๋งŒํ•œ ์ฝ”์ธ ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ in...
pyupbit/strategy.py
14,197
๋งค๋„ ํ•  ํƒ€์ด๋ฐ์€ ์Šค์ฝ”์–ด๊ฐ€ 5์  ์ด์ƒ์ธ ๊ฒฝ์šฐ๋กœ ํ•œ๋‹ค. 1. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋†’์€ ๊ฒฝ์šฐ - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+) rage_score = rage_score + minus_change_rate * 2 - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ์˜ฌ๋ผ๊ฐ”์„ ๋•Œ(-) rage_score = rage_score + minus_change_rate / 2 2. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋‚ฎ์€ ๊ฒฝ์šฐ๋Š” ๊ทธ๋ƒฅ 97% ๋ฏธ๋งŒ์ผ ๋•Œ ๋งค๋„ ์ฒ˜๋ฆฌ(๋นก์นจ ์Šค์ฝ”์–ด๋Š” ๊ณ„์‚ฐ) - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+) rage_score = rage_score + mi...
2,226
ko
0.999985
import itertools import multiprocessing as mp import os import pickle import random import string import tempfile from concurrent.futures import ProcessPoolExecutor from copy import copy from functools import partial from unittest import mock import numpy as np import pandas as pd import pytest import dask import das...
dask/dataframe/tests/test_shuffle.py
44,361
conflicts with keyword argument disjoint Every value in exactly one partition ensure temporary files are cleaned up when there's an internal exception. Divisions must be sorted with sorted=True, divisions must be same length as df.divisions Divisions must be sorted See https://github.com/dask/dask/issues/3867 https://g...
2,903
en
0.838349
import os from dataclasses import dataclass from tequila import TequilaException, BitString, TequilaWarning from tequila.hamiltonian import QubitHamiltonian from tequila.wavefunction import QubitWaveFunction from tequila.hamiltonian.paulis import Sp, Sm, Qp, Qm from tequila.circuit import QCircuit, gates, _gates_impl ...
src/tequila/quantumchemistry/qc_base.py
84,601
Coupled-Cluster Amplitudes We adopt the Psi4 notation for consistency I,A for alpha i,a for beta Parameters ---------- Returns ------- Convenience class for handling N-body tensors Specialization of ParametersHamiltonian Parameters ---------- elems: Tensor data as numpy array active_indices: List of active indices i...
19,631
en
0.708281
#!/usr/bin/env python # # svnadmin_tests.py: testing the 'svnadmin' tool. # # Subversion is a tool for revision control. # See http://subversion.apache.org for more information. # # ==================================================================== # Licensed to the Apache Software Foundation (ASF) under one #...
subversion/tests/cmdline/svnadmin_tests.py
162,337
Manages indexes of a rev file in a FSFS format 7 repository. The interface returns P2L information and allows for item offsets and lengths to be modified. Read P2L index using svnfsfs. Rewrite indexes using svnfsfs. Verify that the SRC BDB repository has been correctly copied to DST. Verify that the SRC FSFS reposit...
32,514
en
0.784129