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 |
|---|---|---|---|---|---|---|
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _c... | venv/Lib/site-packages/tensorflow/python/ops/gen_user_ops.py | 2,986 | Output a fact about factorials.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `string`.
This is the slowpath function for Eager mode.
This is for function fact
Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
Needed to trigger the call to _set_c... | 415 | en | 0.679123 |
#!/usr/bin/env python3
# md_lj_module.py
#------------------------------------------------------------------------------------------------#
# This software was written in 2016/17 #
# by Michael P. Allen <m.p.allen@warwick.ac.uk>/<m.p.allen@bristol.ac.uk> ... | python_examples/md_lj_module.py | 10,345 | A composite variable for interactions.
Prints out concluding statements at end of run.
Takes in box, cutoff range, and coordinate array, and calculates forces and potentials etc.
Calculates Hessian function (for 1/N correction to config temp).
Prints out introductory statements at start of run.
Force routine for MD sim... | 4,405 | en | 0.839436 |
# Copyright 2013 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""Tool to find or compare big functions in a js or ll file
"""
impo... | tools/find_bigfuncs.py | 3,945 | Tool to find or compare big functions in a js or ll file
Copyright 2013 The Emscripten Authors. All rights reserved. Emscripten is available under two separate licenses, the MIT license and the University of Illinois/NCSA Open Source License. Both these licenses can be found in the LICENSE file. | 300 | en | 0.76528 |
from datetime import date
from argparse import Namespace
from django.contrib import admin
from django_q.tasks import async_task
from import_export.admin import ImportExportModelAdmin
from .models import (
MunicipalStaffContactsUpdate,
IncomeExpenditureV2Update,
CashFlowV2Update,
RepairsMaintenanceV2U... | municipal_finance/admin.py | 6,221 | Set the user to the current user Process default save behavior Queue task | 73 | en | 0.801832 |
# Author: Mainak Jas <mainak@neuro.hut.fi>
# Romain Trachel <trachelr@gmail.com>
#
# License: BSD (3-clause)
import warnings
import os.path as op
import numpy as np
from nose.tools import assert_true, assert_raises
from numpy.testing import assert_array_equal
from mne import io, read_events, Epochs, pick_typ... | mne/decoding/tests/test_transformer.py | 5,997 | Test methods of EpochsVectorizer
Test methods of FilterEstimator
Test methods of PSDEstimator
Test methods of Scaler
Author: Mainak Jas <mainak@neuro.hut.fi> Romain Trachel <trachelr@gmail.com> License: BSD (3-clause) enable b/c these tests throw warnings np invalid divide value warnings T... | 759 | en | 0.539217 |
from dataclasses import dataclass
from cannabis.types.blockchain_format.sized_bytes import bytes32
from cannabis.util.ints import uint32
from cannabis.util.streamable import Streamable, streamable
@dataclass(frozen=True)
@streamable
class PoolTarget(Streamable):
puzzle_hash: bytes32
max_height: uint32 # A m... | cannabis/types/blockchain_format/pool_target.py | 361 | A max height of 0 means it is valid forever | 43 | en | 0.833292 |
import logging
LOG = logging.getLogger(__name__)
def export_transcripts(adapter, build="37"):
"""Export all transcripts from the database
Args:
adapter(scout.adapter.MongoAdapter)
build(str)
Yields:
transcript(scout.models.Transcript)
"""
LOG.info("Exporting all transcri... | scout/export/transcript.py | 400 | Export all transcripts from the database
Args:
adapter(scout.adapter.MongoAdapter)
build(str)
Yields:
transcript(scout.models.Transcript) | 151 | en | 0.372923 |
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from .metrics import mse_score, rmse_score, r2_score, mae_score
from ..features.build_features import StandardScaler, MinMaxScaler
class LinearRegressor():
"""Linear regressor"""
def __init__(self, method='normal_equation', nor... | src/models/_linear.py | 3,283 | Linear regressor
Fit the model to the data
Get weights from the fitted model
Use the fitted model to predict on data
Score the model
mse_new = np.inf if (rmse_new > rmse_old): print("Stopped at iteration {}".format(i)) break | 246 | en | 0.741229 |
from copy import deepcopy
from quest.quest_manager import QuestManager
import settings
from twitch.channel import Channel
class QuestChannel(Channel):
def __init__(self, owner, channel_manager):
super().__init__(owner, channel_manager)
self.quest_manager = QuestManager(self)
self.mod_co... | quest_bot/quest_channel.py | 1,852 | Connect to other command lists whose requirements are met.
:param display_name: str - The display name of the command sender
:param msg: str - The full message that the user sent that starts with "!"
:param is_mod: bool - Whether the sender is a mod
:param is_sub: bool - Whether the sender is a sub
Sets the quest coold... | 551 | en | 0.588927 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Centralized catalog of paths."""
import os
class DatasetCatalog(object):
DATA_DIR = "./datasets"
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/annotations/instances_tr... | fcos_core/config/paths_catalog.py | 8,117 | Centralized catalog of paths.
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. PASCAL VOC2012 doesn't made the test annotations available, so there's no json annotation keypoints Detectron C2 models are stored following the structure prefix/<model_id>/2012_2017_baselines/<model_name>.yaml.<signat... | 543 | en | 0.77903 |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
text = """<form method="post" action="/add/">
<input type="text" name="a" value="%d"> + <input type="text" name="b" value="%d">
<input type="submit" value="="> <input type="text" value="%d">
</form>"""
# @csrf_exempt
# ... | newtest/newtest/add.py | 748 | @csrf_exempt def index(request): if 'a' in request.POST: a = int(request.POST['a']) b = int(request.POST['b']) else: a = 0 b = 0 return HttpResponse(text % (a,b,a+b)) | 210 | en | 0.265057 |
# 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 may ... | sdk/security/azure-mgmt-security/azure/mgmt/security/aio/operations/_compliance_results_operations.py | 7,770 | ComplianceResultsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.security.models
:param c... | 1,897 | en | 0.574561 |
# -*- coding: utf-8 -*-
import argparse, json, os
import numpy as np
import h5py
import codecs
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_txt', default='half_obama_weeklys.txt')
parser.add_argument('-o', '--output_h5', default='half_obama_weeklys.h5')
parser.add_argument('-oj', '--output_j... | scrape-prez-vids/scrapy/scrape_prez/preprocess.py | 3,089 | -*- coding: utf-8 -*- First go the file once to see how big it is and to build the vocab Now we can figure out the split sizes Choose the datatype based on the vocabulary size Just load data into memory ... we'll have to do something more clever for huge datasets but this should be fine for now Go through the file agai... | 489 | en | 0.901891 |
import psycopg2
import os
from dotenv import load_dotenv
load_dotenv() # Adds .env to memory
# postgres db connection
postgres_options = {
"host": os.getenv("POSTGRES_HOST"),
"database": os.getenv("POSTGRES_DATABASE"),
"user": os.getenv("POSTGRES_USER"),
"password": os.getenv("POSTGRES_PASSWORD")
... | resources/keys.py | 551 | Adds .env to memory postgres db connection | 42 | en | 0.320047 |
# Generated by Django 2.2.8 on 2019-12-24 12:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Redirect',
fields=[
('id', models.AutoField... | apps/go/migrations/0001_initial.py | 581 | Generated by Django 2.2.8 on 2019-12-24 12:45 | 45 | en | 0.707042 |
from xml.dom import minidom
from django.utils.datastructures import MultiValueDict
from django import forms
from django.utils.html import format_html, mark_safe
from django.forms.utils import flatatt
class SelectMultipleSVG(forms.SelectMultiple):
class Media:
js = ('django_svgselect.js',)
def __init_... | django_svgselect/forms.py | 1,410 | TODO: Add some validation here? | 31 | en | 0.507222 |
""" Python 'unicode-internal' Codec
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is in... | env/lib/python3.7/encodings/unicode_internal.py | 1,196 | Python 'unicode-internal' Codec
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
Codec APIs Note: Binding these as C functions will result in the class not converting them to methods. This is intended. encodings module src | 281 | en | 0.845339 |
import cv2
import numpy as np
from faster_rcnn import network
from faster_rcnn.faster_rcnn import FasterRCNN
from faster_rcnn.utils.timer import Timer
def test():
import os
im_file = 'demo/004545.jpg'
# im_file = 'data/VOCdevkit2007/VOC2007/JPEGImages/009036.jpg'
# im_file = '/media/longc/Data/data/2D... | demo.py | 1,642 | im_file = 'data/VOCdevkit2007/VOC2007/JPEGImages/009036.jpg' im_file = '/media/longc/Data/data/2DMOT2015/test/ETH-Crossing/img1/000100.jpg' model_file = '/media/longc/Data/models/faster_rcnn_pytorch3/faster_rcnn_100000.h5' model_file = '/media/longc/Data/models/faster_rcnn_pytorch2/faster_rcnn_2000.h5' network.save_net... | 475 | en | 0.486036 |
#importieren aller notwenigen Bibliotheken
import tensorflow.compat.v1 as tf
#Die Hauptbibliothek Tensorflow wird geladen
from tensorflow.keras.models import Sequential, save_model
from tensorflow.keras.layers import Conv2D, BatchNormalization, MaxPool2D, MaxPooling2D, Dense, Dropout, Activation, Flatten
from tens... | Programme/Trainingsprogramm_mit_Messdaten.py | 6,065 | importieren aller notwenigen BibliothekenDie Hauptbibliothek Tensorflow wird geladenBilder werden auf die Größe 32*32 Pixel mit RGB skaliert, damit diese eine einheitliche Größe habenDoppeltes Hinzufügen der Trainingsbilder aus Bildklassen mit wenig TrainingsbildernUmformung der Liste mit den Trainingsbildern in einen ... | 1,757 | de | 0.99013 |
# -*- coding: utf-8 -*-
import os
import random
import functools
import six
import numpy as np
import torch
from torch import nn
from torch.utils.data.distributed import DistributedSampler
from aw_nas import utils
from aw_nas.final.base import FinalTrainer
from aw_nas.final.bnn_model import BNNGenotypeModel
from aw_... | aw_nas/final/cnn_trainer.py | 20,483 | update learning rate of optimizers
-*- coding: utf-8 -*-pylint: disable=too-many-instance-attributespylint: disable=dangerous-default-value for OFA final model for optimizer optimizer and scheduler is called in `trainer.setup` call states of the trainer save the model directly instead of the state_dict, so that it ca... | 907 | en | 0.676525 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import asyncio
import dataclasses
import enum
import json
import logging
import os
import subprocess
import tempfile
import traceback
from p... | client/commands/persistent.py | 64,628 | Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. pyre-fixme[16]: Pyre doesn't understand `dataclasses_json` pyre-ignore[16] - refinement doesn't work here for some reason pyre-fixme[16]: Pyre doesn'... | 1,993 | en | 0.868283 |
# -*- coding: utf-8 -*-
'''
==============
scrim.commands
==============
Implements functionality available across multiple shell scripting languages.
'''
from __future__ import absolute_import
import abc
from collections import namedtuple
from fstrings import f
import ntpath
import posixpath
ABC = abc.ABCMeta('ABC', ... | scrim/commands.py | 6,159 | Forward commands to the specified ShellCommands implementation.
RawCommands are returned as-is if the shell matches the RawCommands
required_shell. You shouldn't need to use this class directly.
Defines the interface for all ShellCommand implementations. These are
the common commands we want to define for all shells.
... | 1,770 | en | 0.860975 |
# MIT LICENSE
#
# Copyright 1997 - 2020 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,... | uhd_restpy/testplatform/sessions/ixnetwork/topology/isistrillpseudonode_173e4463dccc2001457569c77f3570e0.py | 12,874 | TRILL Pseudo Node Configuration
The IsisTrillPseudoNode class encapsulates a list of isisTrillPseudoNode resources that are managed by the system.
A list of resources can be retrieved from the server using the IsisTrillPseudoNode.find() method.
Executes the abort operation on the server.
Abort CPF control plane (equal... | 8,460 | en | 0.713529 |
#
# Copyright SAS Institute
#
# 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... | saspy/sasdata.py | 52,269 | **Overview**
The SASdata object is a reference to a SAS Data Set or View. It is used to access data that exists in the SAS session.
You create a SASdata object by using the sasdata() method of the SASsession object.
Parms for the sasdata() method of the SASsession object are:
:param table: [Required] the name of the... | 10,793 | en | 0.631945 |
"""SqlAlchemy models."""
import datetime
from blog.extensions import db
from blog.category.models import Category
TITLE_LEN = 255
URL_LEN = 255
POST_STATUSES = {
0: 'Draft',
1: 'Page',
2: 'Archive',
3: 'Special',
4: 'Published',
}
class Post(db.Model):
"""orm model for blog post."""
__... | blog/post/models.py | 1,042 | orm model for blog post.
SqlAlchemy models. | 43 | en | 0.688152 |
# -*- coding: utf-8 -*-
"""
Module entry point.
------------------------------------------------------------------------------
This file is part of grepros - grep for ROS bag files and live topics.
Released under the BSD License.
@author Erki Suurjaak
@created 24.10.2021
@modified 02.11.2021
-------------... | src/grepros/__main__.py | 452 | Module entry point.
------------------------------------------------------------------------------
This file is part of grepros - grep for ROS bag files and live topics.
Released under the BSD License.
@author Erki Suurjaak
@created 24.10.2021
@modified 02.11.2021
-----------------------------------------... | 381 | en | 0.400522 |
"""
This module contains functions to:
- solve a single equation for a single variable, in any domain either real or complex.
- solve a system of linear equations with N variables and M equations.
- solve a system of Non Linear Equations with N variables and M equations
"""
from __future__ import print_f... | sympy/solvers/solveset.py | 77,318 | If `rnew` (A dict <symbol: soln>) contains valid soln
append it to `newresult` list.
`imgset_yes` is (base, dummy_var) if there was imageset in previously
calculated result(otherwise empty tuple). `original_imageset` is dict
of imageset expr and imageset from this result.
`soln_imageset` dict of imageset expr and ima... | 31,297 | en | 0.774509 |
import tensorflow.compat.v1 as tf
import numpy as np
m = 1740
x_batch = np.random.rand(m)
y_batch = np.random.rand(1)
weights = np.random.rand(m)
biases = np.random.rand(m)
with tf.Session() as sess:
x = tf.placeholder(tf.float32, shape=(m, ), name='x')
y = tf.placeholder(tf.float32, shape=(1, ), name='y'... | tabla/tabla/benchmarks/onnx/svm_tf.py | 1,359 | w = tf.Variable(np.random.rand(m), name='W', dtype=tf.float32) b = tf.Variable(np.random.rand(m), name='b', dtype=tf.float32) maximum = tf.maximum(0., distances)maximum = tf.boolean_mask(distances, tf.greater(0., distances)) Look here for gradient of SVM objective function: http://u.cs.biu.ac.il/~jkeshet/teaching/aml20... | 343 | en | 0.364247 |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | tests/st/ops/cpu/test_layer_norm_op.py | 8,184 | Copyright 2021 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw... | 638 | en | 0.808977 |
from rdflib import URIRef, Namespace
from definednamespace import DefinedNamespace
class RDF(DefinedNamespace):
# http://www.w3.org/1999/02/22-rdf-syntax-ns#Property
direction: URIRef # The base direction component of a CompoundLiteral.
first: URIRef # The first item in the sub... | tests/data/RDF.py | 1,978 | http://www.w3.org/1999/02/22-rdf-syntax-nsProperty The base direction component of a CompoundLiteral. The first item in the subject RDF list. The language component of a CompoundLiteral. The object of the subject RDF statement. The predicate of the subject RDF statement. The rest of the subject RDF list after the first... | 1,044 | en | 0.675351 |
from data import *
from model import *
from utils import *
import torch
from torch.autograd import Variable
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
#import matplotlib.pyplot as plt
#import matplotlib.ticker as ticker
#import numpy as np
#import io
#import torchvision
#from PIL ... | seq2seq-translation-batched/evaluate.py | 4,337 | import matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport numpy as npimport ioimport torchvisionfrom PIL import Imageimport visdomvis = visdom.Visdom() input_lengths = [len(input_seq)] xiba, 嚴重錯誤 Set to not-training mode to disable dropout Run through encoder Create starting vectors for decoder SOS Use la... | 1,781 | en | 0.362695 |
# Generated by Django 3.0.3 on 2020-02-13 07:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('locations', '0002_department'),
]
operations = [
migrations.AlterField(
model_name='department',
name='department_co... | pitchant/locations/migrations/0003_auto_20200213_0758.py | 393 | Generated by Django 3.0.3 on 2020-02-13 07:58 | 45 | en | 0.617794 |
# coding: utf-8
import urllib
import re
from google.appengine.ext import blobstore
import flask
import flask_wtf
import wtforms
import auth
import config
import model
import util
from main import app
# ###############################################################################
# # List Filters
# #############... | main/control/filter.py | 3,987 | coding: utf-8 List Filters @app.route('/resource/', endpoint='resource_grid') def resource_grid(): resource_dbs, cursors = model.Resource.get_dbs( model.Resource.query(model.Resource.hotness > 0), limit=20, prev_cursor=True, order='-hotness') return flask.render_template( 'resource/resource_grid.html... | 1,120 | en | 0.290973 |
import datetime
import warnings
import pendulum
from dagster import check
from dagster.core.definitions.partition import PartitionSetDefinition
from dagster.core.errors import DagsterInvalidDefinitionError
from dagster.utils.partitions import (
DEFAULT_DATE_FORMAT,
DEFAULT_HOURLY_FORMAT_WITHOUT_TIMEZONE,
D... | python_modules/dagster/dagster/core/definitions/decorators/schedule.py | 27,305 | Create a schedule that runs daily.
The decorated function will be called as the ``run_config_fn`` of the underlying
:py:class:`~dagster.ScheduleDefinition` and should take a
:py:class:`~dagster.ScheduleExecutionContext` as its only argument, returning the environment
dict for the scheduled execution.
Args:
pipeli... | 10,337 | en | 0.706923 |
#!/usr/bin/python
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
impor... | contrib/linearize/linearize-hashes.py | 2,761 | !/usr/bin/python linearize-hashes.py: List blocks in a linear, no-fork version of the chain. Copyright (c) 2013 The Bitcoin developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. skip comment lines parse key=value lines | 313 | en | 0.673579 |
"""Checks the repository for updates."""
import os
import sys
import urllib
import imp
from hashlib import md5
from inspect import getsourcelines
from threading import Thread
from retriever import REPOSITORY, VERSION, MASTER_BRANCH, REPO_URL, SCRIPT_WRITE_PATH
from retriever.lib.models import file_exists
global abor... | lib/repository.py | 7,235 | splash.Show() NOTE: exe auto-update functionality has been temporarily disabled since the binaries were moved to AWS.running_from[-4:] == ".exe": Windows: open master branch version file to find out most recent executable version open version.txt for current release branch and get script versions get scrip... | 397 | en | 0.912295 |
# -*- coding: utf-8 -*-
"""
Store data in the Sqlite3 Database
Table1
"""
import os
import sys
import codecs
import sqlite3
from common import log
from store.model import Question, Answer, Person, Topic
DB_PATH = 'spiderman.db'
logger = log.Logger(name='store')
def init_all_dbs():
"""
call it when cr... | store/store.py | 5,567 | call it when creating database
:return:
Store data in the Sqlite3 Database
Table1
-*- coding: utf-8 -*- 存储用户信息 -- csv path = init_people_file(dir_path) 存储问题信息 -- csv path = dir_path + 'question.txt' | 201 | en | 0.411461 |
# MIT LICENSE
#
# Copyright 1997 - 2020 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, ... | uhd_restpy/testplatform/sessions/ixnetwork/topology/bgpipv6peer_d4ac277d9da759fd5a152b8e6eb0ab20.py | 159,611 | Bgp IPv6 Peer
The BgpIpv6Peer class encapsulates a list of bgpIpv6Peer resources that are managed by the user.
A list of resources can be retrieved from the server using the BgpIpv6Peer.find() method.
The list can be managed by using the BgpIpv6Peer.add() and BgpIpv6Peer.remove() methods.
Executes the abort operation o... | 72,766 | en | 0.465953 |
# old functions (slightly more time efficient) which store forward and reverse frames in memory and don't use
# any multiprocessing.
def seqToProtein(dnaSeq, minLen):
newSeq = dnaSeq.upper().replace('N', '')
start = time.time()
forwFrames, revFrames = seqToFrames(newSeq)
peptides = []
for frame ... | DNAtoPep/OldSixFrameFunctions.py | 2,906 | old functions (slightly more time efficient) which store forward and reverse frames in memory and don't use any multiprocessing. incorporate start triplet fasta_sequences = SeqIO.parse(open(input_path), 'fasta') for fasta in fasta_sequences: name, sequence = fasta.id, str(fasta.seq) sequence = sequence.upper().... | 490 | en | 0.739218 |
# -*- coding: utf-8 -*-
# Copyright 2011 Takeshi KOMIYA
#
# 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 applica... | src/seqdiag/elements.py | 8,404 | -*- coding: utf-8 -*- Copyright 2011 Takeshi KOMIYA 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... | 646 | en | 0.840804 |
"""Init to import all the routing protocols implemented."""
from .min_hop import MinHopRouting, MinHopRoutingSink
from .etx import ETX, ETXSink
from .dap import DAPRouting, DAPRoutingSink
from .base_routing_protocol import RoutingProtocol
| wsnsim/routing/__init__.py | 240 | Init to import all the routing protocols implemented. | 53 | en | 0.641909 |
import os
from retriever.lib.defaults import DATA_DIR
from retriever.lib.dummy import DummyConnection
from retriever.lib.models import Engine
from retriever.lib.tools import open_fr, open_fw
from retriever.lib.engine_tools import sort_csv, xml2csv_test
class engine(Engine):
"""Engine instance for writing data to... | retriever/engines/xmlengine.py | 5,472 | Engine instance for writing data to a XML file.
Override create_db since there is no database just an XML file.
Create the table by creating an empty XML file.
Close out the xml files
Close all the file objects that have been created
Re-write the files stripping off the last comma and then close with a closing tag)
Wr... | 752 | en | 0.695405 |
from subprocess import STDOUT, run, PIPE
def align(x, al):
""" return <x> aligned to <al> """
return ((x+(al-1))//al)*al
class CompilationError(Exception):
def __init__(self, code, output) -> None:
super().__init__(f'compilation failed')
self.code = code
self.output = output
... | packer4/utils.py | 1,453 | return <x> aligned to <al> | 26 | en | 0.55596 |
from flask_appbuilder import BaseView, expose
from config import APP_ICON, APP_NAME
from flask import g
def get_user():
return g.user
def custom_template():
app_name = "GEA"
app_version = "1.2"
return app_name, app_version
class someView(BaseView):
"""
A simple view that implemen... | app/index.py | 1,316 | A simple view that implements the index for the site | 52 | en | 0.803684 |
# Copyright 2019-2020 Jan Feitsma (Falcons)
# SPDX-License-Identifier: Apache-2.0
#!/usr/bin/env python3
#
import sys, copy
import argparse
import yaml
import falconspy
from rdlLib import RDLFile
AGENTS_IGNORE = [1] # the ones which do not have ballHandlers
def loadYAMLcalibration(yamlfile):
f = open(yamlfile... | packages/ballHandling/py/checkBhCalibration.py | 6,879 | Copyright 2019-2020 Jan Feitsma (Falcons) SPDX-License-Identifier: Apache-2.0!/usr/bin/env python3 the ones which do not have ballHandlers only return the calibration section convert from list to dict, which is more convenient to preserve formatting, ordering and comments, we just process the yaml line by line - parsin... | 997 | en | 0.823094 |
import os
import pandas
import numpy as np
from numpy.random import default_rng
import cv2
from time import time_ns
from datetime import datetime, timedelta
from PIL import Image
class Imagebot:
def __init__(self, queue="./queue", sourcedir="./source", index="index.csv",
min_queue_length=240, im... | imagebot/imagebot.py | 4,835 | 1. Find the first file in the source directory that matches the key If none, go with the first file in the source directory 2. Extract the frame Set the frame 3. Return the result Returns the image data from a random clip in the source files 1. Pick a clip (row) from the index 2. Extract the data from the row 3. Pic... | 1,012 | en | 0.810003 |
# -*- coding:utf-8 -*-
class TabSetup(object):
def __init__(self, url_name='', click_css_selector='', pause_time=1, x_offset=8, y_offset=8, try_times=20):
"""
爬虫标签页设置
:param url_name:
:param click_css_selector:
:param pause_time:暂停时间
:param x_offset:x轴方向页面偏移
... | spider/driver/base/tabsetup.py | 1,452 | 爬虫标签页设置
:param url_name:
:param click_css_selector:
:param pause_time:暂停时间
:param x_offset:x轴方向页面偏移
:param y_offset:y轴方向页面偏移
:param try_times:尝试的次数
-*- coding:utf-8 -*-url_name与click_css_selector两者只能存在一个 | 205 | zh | 0.362532 |
# 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.
# --------------------------------------------------------------------... | sdk/formrecognizer/azure-ai-formrecognizer/samples/sample_recognize_receipts.py | 4,512 | FILE: sample_recognize_receipts.py
DESCRIPTION:
This sample demonstrates how to recognize and extract common fields from receipts,
using a pre-trained receipt model. For a suggested approach to extracting information
from receipts, see sample_strongly_typed_recognized_form.py.
See fields found on a re... | 1,032 | en | 0.779632 |
# 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 may ... | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/operations/_storage_insight_configs_operations.py | 16,003 | StorageInsightConfigsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.loganalytics.models
:param... | 4,481 | en | 0.553974 |
# Run the person detection model
# This version reads the images from the ov2640 camera on the esp32-cam board
# with minor changes this also works for the m5 timer camera
import sys
import microlite
import camera
from machine import Pin,PWM
# initialize the camera to read 96x96 pixel gray scale images
try:
# unco... | examples/person_detection/esp32-cam/person_detection_cam.py | 2,343 | Run the person detection model This version reads the images from the ov2640 camera on the esp32-cam board with minor changes this also works for the m5 timer camera initialize the camera to read 96x96 pixel gray scale images uncomment for esp32-cam-mb with ov2640 sensor uncomment for the m5 timer camera with ov3660 se... | 947 | en | 0.732177 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .base_model import BaseModel
# F.max_pool2d needs kernel_size and stride. If only one argument is passed,
# then kernel_size = stride
from .audio import MelspectrogramStretch
from torchparse import parse_cfg
# Architecture inspiration from: htt... | net/model.py | 4,586 | F.max_pool2d needs kernel_size and stride. If only one argument is passed, then kernel_size = stride Architecture inspiration from: https://github.com/keunwoochoi/music-auto_tagging-keras shape -> (channel, freq, token_time)if name.startswith(('conv2d','maxpool2d')): x-> (batch, time, channel) unpacking seqs, lengths ... | 941 | en | 0.823603 |
"""
Ballastsolver
"""
"""
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Ruben de Bruin - 2019
"""
from DAVE.gui.dockwidget import *
from PySide2 import QtGui, QtC... | src/DAVE/gui/widget_ballastsolver.py | 3,639 | Add gui components to self.contents
Do not fill the controls with actual values here. This is executed
upon creation and guiScene etc are not yet available.
Add processing that needs to be done.
After creation of the widget this event is called with guiEventType.FULL_UPDATE
Ballastsolver
or from a generated file se... | 348 | en | 0.878379 |
# Copyright (c) 2016 Shunta Saito
import os
import chainer.functions as F
import chainer.links as L
from chainer import Chain
from chainer import Variable
from chainer import cuda
from chainer import initializers
from chainer import reporter
from models.bbox_transform import bbox_transform_inv
from models.bbox_transf... | faster_rcnn_explorer/models/faster_rcnn.py | 6,963 | Faster RCNN forward
Args:
x (:class:`~chainer.Variable`): The input image. Note that the
batchsize should be 1. So the shape should be
:math:`(1, n_channels, height, width)`.
img_info (:class:`~chainer.Variable`): The input image info. It
contains :math:`(height, width)` and the batchsi... | 913 | en | 0.637431 |
import tensorflow as tf
if tf.__version__ > '2':
import tensorflow.compat.v1 as tf
import model
def top_k_logits(logits, k):
if k == 0:
# no truncation
return logits
def _top_k():
values, _ = tf.nn.top_k(logits, k=k)
min_values = values[:, -1, tf.newaxis]
return tf... | src/sample.py | 3,229 | Nucleus sampling
no truncation number of indices to include | 61 | en | 0.899149 |
# backend/server/apps/endpoints/serializers.py file
from rest_framework import serializers
from apps.endpoints.models import Endpoint
from apps.endpoints.models import MLAlgorithm
from apps.endpoints.models import MLAlgorithmStatus
from apps.endpoints.models import MLRequest
class EndpointSerializer(serializers.ModelS... | backend/server/apps/endpoints/serializers.py | 1,822 | backend/server/apps/endpoints/serializers.py file | 49 | en | 0.719629 |
"""Utilities for generating synthetic segmentation datasets."""
import os
from typing import Tuple
from pathlib import Path
import numpy as np
from skimage.draw import random_shapes
from skimage.transform import rotate
from skimage.io import imsave
def gen_shape_image(im_size: Tuple[int, int], max_shapes: int=10, o... | unet/data/synthetic_data.py | 2,351 | Utilities for generating synthetic segmentation datasets.
Generate an image with random shapes Find each shape and get the corresponding pixels for the label map If we're rotating pick a random number between -180 and 180 and then rotate Swap the background color to a random color to make things interesting | 310 | en | 0.81281 |
#!/usr/bin/env python
import sys, json, yaml, requests, random, io
import pkg_resources
from termcolor import colored
from urllib import parse
# This line is for pyinstaller and the binary release
##VERSION_PARSE##
if 'version' not in vars():
version = pkg_resources.require("majime")[0].version
def getopts(argv)... | majime/__main__.py | 9,334 | !/usr/bin/env python This line is for pyinstaller and the binary releaseVERSION_PARSE print ("Title: " + str(title)) print ("Host: " + str(host)) print ("Base Path: " + str(basepath)) print ("Scheme: " + str(scheme))print ("Path: " + api_path) We only want the first response print ("\tMethod: " + method) print ("\tDesc... | 448 | en | 0.615043 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-11-21 09:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0058_auto_20171110_1230'),
]
operations = [
migrations.AlterModelOpt... | bluebottle/cms/migrations/0059_auto_20171121_1022.py | 959 | -*- coding: utf-8 -*- Generated by Django 1.10.8 on 2017-11-21 09:22 | 68 | en | 0.629866 |
import discord
from redbot.core import commands
import datetime
import aiohttp
import asyncio
import json
import re
from typing import Optional
class Conversions(getattr(commands, "Cog", object)):
"""
Gather information about various crypto currencies,
rare metals, stocks, and converts to differen... | conversions/conversions.py | 18,051 | Gather information about various crypto currencies,
rare metals, stocks, and converts to different currencies | 109 | en | 0.837813 |
"""Analysis of a repository for needed Python updates."""
from __future__ import annotations
import logging
import subprocess
from typing import TYPE_CHECKING
from git import Repo
from neophile.analysis.base import BaseAnalyzer
from neophile.exceptions import UncommittedChangesError
from neophile.update.python impo... | src/neophile/analysis/python.py | 3,271 | Analyze a tree for needed Python frozen dependency updates.
Parameters
----------
root : `pathlib.Path`
Root of the directory tree to analyze.
virtualenv : `neophile.virtualenv.VirtualEnv`, optional
Virtual environment manager.
Analysis of a repository for needed Python updates. | 288 | en | 0.281876 |
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http, validate
from streamlink.stream import HTTPStream, HDSStream, RTMPStream
MEDIA_URL = "http://www.ardmediathek.de/play/media/{0}"
SWF_URL = "http://www.ardmediathek.de/ard/static/player/base/flash/PluginFlash.swf"
HDCORE_PARAMETER =... | src/streamlink/plugins/ard_mediathek.py | 4,342 | Needs the hdcore parameter added TODO: Replace with "yield from" when dropping Python 2. TODO: Replace with "yield from" when dropping Python 2. | 144 | en | 0.391631 |
import warnings
import numpy as np
from scipy import signal
from scipy import stats
import matplotlib.pylab as plt
class SpikeCalcsGeneric(object):
"""
Deals with the processing and analysis of spike data.
Parameters
----------
spike_times : array_like
The times of 'spikes' in the trial
... | ephysiopy/common/spikecalcs.py | 28,930 | Replaces SpikeCalcs from ephysiopy.dacq2py.spikecalcs
Deals with the processing and analysis of spike data.
Parameters
----------
spike_times : array_like
The times of 'spikes' in the trial
Should be the same length as the cluster identity vector _spk_clusters
waveforms : np.array, optional
An nSpikes x nS... | 7,206 | en | 0.780758 |
#!/Users/akshayiyer/Dev/GitHub/udacity-dend/udacity-dend-capstone-etl/bin/python3.7
# $Id: rst2odt.py 5839 2009-01-07 19:09:28Z dkuhlman $
# Author: Dave Kuhlman <dkuhlman@rexx.com>
# Copyright: This module has been placed in the public domain.
"""
A front end to the Docutils Publisher, producing OpenOffice documents... | bin/rst2odt.py | 829 | A front end to the Docutils Publisher, producing OpenOffice documents.
!/Users/akshayiyer/Dev/GitHub/udacity-dend/udacity-dend-capstone-etl/bin/python3.7 $Id: rst2odt.py 5839 2009-01-07 19:09:28Z dkuhlman $ Author: Dave Kuhlman <dkuhlman@rexx.com> Copyright: This module has been placed in the public domain. | 309 | en | 0.675697 |
#
# 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... | airflow/providers/amazon/aws/transfers/mysql_to_s3.py | 5,350 | Saves data from an specific MySQL query into a file in S3.
:param query: the sql query to be executed. If you want to execute a file, place the absolute path of it,
ending with .sql extension. (templated)
:type query: str
:param s3_bucket: bucket where the data will be stored. (templated)
:type s3_bucket: str
:par... | 2,368 | en | 0.768583 |
# Copyright 2020 The TensorFlow Probability 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 applicable law o... | spinoffs/oryx/oryx/util/summary_test.py | 2,462 | Tests for tensorflow_probability.spinoffs.oryx.util.summary.
Copyright 2020 The TensorFlow Probability 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/LI... | 729 | en | 0.786592 |
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from numpy.testing import assert_allclose
from vispy.util.transforms import (translate, scale, rotate, ortho, frustum,
pe... | vispy/util/tests/test_transforms.py | 1,497 | Test basic transforms
-*- coding: utf-8 -*- Copyright (c) 2014, Vispy Development Team. Distributed under the (new) BSD License. See LICENSE.txt for more info. Do a series of rotations that should end up into the same orientation again, to ensure the order of computation is all correct i.e. if rotated would return th... | 436 | en | 0.939456 |
###############################################################################
#
# Tests for libxlsxwriter.
#
# Copyright 2014-2019, John McNamara, jmcnamara@cpan.org
#
import base_test_class
class TestCompareXLSXFiles(base_test_class.XLSXBaseTest):
"""
Test file created with libxlsxwriter against a file cre... | libxlsxwriter/test/functional/test_chart_up_down_bars.py | 538 | Test file created with libxlsxwriter against a file created by Excel.
Tests for libxlsxwriter. Copyright 2014-2019, John McNamara, jmcnamara@cpan.org | 151 | en | 0.891439 |
import importlib.util
import sys
class VendorImporter:
"""
A PEP 302 meta path importer for finding optionally-vendored
or otherwise naturally-installed packages from root_name.
"""
def __init__(self, root_name, vendored_names=(), vendor_pkg=None):
self.root_name = root_name
self.... | virtual/lib/python3.8/site-packages/setuptools/extern/__init__.py | 2,514 | A PEP 302 meta path importer for finding optionally-vendored
or otherwise naturally-installed packages from root_name.
Figure out if the target module is vendored.
Return a module spec for vendored names.
Install this importer into sys.meta_path if not already present.
Iterate over the search path to locate and load fu... | 386 | en | 0.705522 |
from django.db import models
from django.contrib.auth import models as authmodels
from django.conf import settings
import os.path
# Models for file attachments uploaded to the site
# basically just a simple container for files
# but allowing for replacement of previously uploaded files
class Attachment(models.Model):... | signbank/attachments/models.py | 707 | Models for file attachments uploaded to the site basically just a simple container for files but allowing for replacement of previously uploaded files | 150 | en | 0.984692 |
import os
from WMCore.Configuration import Configuration
from CRABClient.UserUtilities import config, getUsernameFromCRIC
config = Configuration()
config.section_("General")
config.General.requestName = '2017_tt_SL-HDAMPdown'
config.General.transferOutputs = True
config.General.transferLogs = True
config.section_("Jo... | Kai/crab/NANOv7_NoveCampaign/2017/crab_cfg_2017_tt_SL-HDAMPdown.py | 1,700 | ['hist.root'] config.Data.totalUnits = $TOTAL_UNITS config.Data.userInputFiles = [] config.Data.outLFNDirBase = '/store/user/{}/NoveCampaign/{}'.format(getUsernameFromCRIC(), "2017") | 182 | en | 0.26731 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Test tools package alone which don't fit into other tests."""
#
# (C) Pywikibot team, 2016-2017
#
# Distributed under the terms of the MIT license.
from __future__ import absolute_import, unicode_literals
import collections
import decimal
import inspect
import os.path
impor... | tests/tools_tests.py | 30,396 | Container that stops when encountering items.
Container that stops when encountering items.
Test that ContextManagerWrapper is working correctly.
A dummy class which has some values and a close method.
Test class to verify classproperty decorator.
Test merge_unique_dicts.
Metaclass to create dynamically the tests. Set ... | 5,231 | en | 0.820948 |
import os
import posixpath
import re
from poetry.packages.constraints.constraint import Constraint
from poetry.packages.constraints.multi_constraint import MultiConstraint
from poetry.packages.constraints.union_constraint import UnionConstraint
from poetry.semver import Version
from poetry.semver import VersionUnion
f... | poetry/packages/utils/utils.py | 5,890 | Return True if `name` is a considered as an archive file.
Return True if `path` is a directory containing a setup.py file.
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
Like os.path.splitext, but take off .tar too
noqa Only for Python 3.3+ noqa | 291 | en | 0.803083 |
'''
Using aws fargate to run a fmriprep. Uses our own docker image, which contains a wrapper to download the data from S3 and push it back again.
Rhodri Cusack TCIN 2021-06, cusackrh@tcd.ie
'''
from ecs_control import register_task, run_task, wait_for_completion
import boto3
import msgpack
import msgpack_numpy as m
f... | fmriprep-cusacklab-queue-subjects.py | 1,208 | Using aws fargate to run a fmriprep. Uses our own docker image, which contains a wrapper to download the data from S3 and push it back again.
Rhodri Cusack TCIN 2021-06, cusackrh@tcd.ie
subjects with small affine shifts between fMRI runssubjlist =['sub-04','sub-02','sub-05','sub-07','sub-08','sub-09','sub-10','sub-11... | 367 | en | 0.582012 |
from scipy.sparse.linalg import LinearOperator,onenormest,aslinearoperator
from .expm_multiply_parallel_wrapper import (_wrapper_expm_multiply,
_wrapper_csr_trace,_wrapper_csr_1_norm)
from scipy.sparse.construct import eye
from scipy.sparse.linalg._expm_multiply import _fragment_3_1,_exact_1_norm
import scipy.sparse a... | quspin/tools/expm_multiply_parallel_core/expm_multiply_parallel_core.py | 10,575 | Information about an operator is lazily computed.
The information includes the exact 1-norm of the operator,
in addition to estimates of 1-norms of powers of the operator.
This uses the notation of Computing the Action (2011).
This class is specialized enough to probably not be of general interest
outside of this modu... | 4,175 | en | 0.548745 |
#
# 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 us... | python/pyspark/pandas/frame.py | 460,380 | Cached pandas-on-Spark DataFrame, which corresponds to pandas DataFrame logically, but
internally it caches the corresponding Spark DataFrame.
pandas-on-Spark DataFrame that corresponds to pandas DataFrame logically. This holds Spark
DataFrame internally.
:ivar _internal: an internal immutable Frame to manage metadata... | 200,935 | en | 0.508833 |
# -*- coding: utf-8 -*-
class C:
a = 'abc'
def __getattribute__(self, args):
print('__getattribute_ is called')
#import pdb; pdb.set_trace()
#return object.__getattribute__(self, args)
return super().__getattribute__(args)
def __getattr__(self, name):
print('__getattr()__ is called')
return name+ 'from ... | app/getattrtest.py | 668 | -*- coding: utf-8 -*-import pdb; pdb.set_trace()return object.__getattribute__(self, args) | 90 | en | 0.576421 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Module ... | msticpy/nbtools/timeline.py | 29,505 | Add a reference marker line and label at `ref_time`.
Dynamic calculation of plot height.
Create plot bar to act as as range selector.
Display a timeline of events.
Parameters
----------
data : dict
Data points to plot on the timeline.
Need to contain:
Key - Name of data type to be displayed in ... | 8,573 | en | 0.575315 |
img_size = 84
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
test_pipeline = [
dict(type='LoadImageFromBytes'),
dict(type='Resize', size=(int(img_size * 1.15), -1)),
dict(type='CenterCrop', crop_size=img_size),
dict(type='Normalize', **img_norm_cfg),
... | configs/classification/_base_/meta_test/tiered-imagenet_meta-test_5way-1shot.py | 2,335 | whether to cache features in fixed-backbone methods for testing acceleration. worker initialization is a time consuming operation seed for generating meta test episodes whether to cache features in fixed-backbone methods for testing acceleration. worker initialization for each task is a time consuming operation | 312 | en | 0.868396 |
import logging
import os
import platform
import subprocess
from xml.dom import minidom
from xml.etree import ElementTree
_RESOURCE_DIR = '../resources'
_INKSCAPE = None
_FFMPEG = None
_BASENAME = 'napkin'
_NAMESPACE = 'nap::qt'
def findAppInWindows(appexe):
try:
import winreg
except ImportError:
... | tools/napkin/tools/prepareresources.py | 5,008 | print(os.path.realpath()) only update when necessary Windows | 60 | en | 0.170792 |
#!/usr/bin/env python3
# Copyright (c) 2012-2021 The PIVX developers
# Copyright (c) 2020-2021 The PENGOLINCOIN developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Simple test checking chain movement after v5 enforcement.... | test/functional/mining_v5_upgrade.py | 1,198 | Simple test checking chain movement after v5 enforcement.
!/usr/bin/env python3 Copyright (c) 2012-2021 The PIVX developers Copyright (c) 2020-2021 The PENGOLINCOIN developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. v5 activat... | 362 | en | 0.58644 |
import uuid
from django.db import models
from django.utils.translation import gettext_lazy
from modelcluster.fields import ParentalKey
from wagtail.admin.edit_handlers import (
FieldPanel,
InlinePanel,
ObjectList,
PageChooserPanel,
StreamFieldPanel,
TabbedInterface,
)
from wagtail.core import b... | wagtail_localize/test/models.py | 16,636 | A page type that tests the builtin automatic generation of translatable fields.
Placeholder for Wagtail < 2.13
Telepath added in Wagtail 2.13 To test field level validation of snippets Don't disrupt other tests Always keep the translation mode off, regardless of the global WAGTAIL_LOCALIZE_DEFAULT_TRANSLATION_MODE va... | 607 | en | 0.813781 |
#!/usr/bin/env python3
# Copyright (c) 2013-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Generate seeds.txt from Pieter's DNS seeder
#
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 615801
#... | contrib/seeds/makeseeds.py | 5,517 | Filter out hosts with more nodes per IP
!/usr/bin/env python3 Copyright (c) 2013-2017 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Generate seeds.txt from Pieter's DNS seeder These are hosts that have be... | 1,272 | en | 0.888202 |
import fakeredis
import json
import mock
from app import bev
from app.cards import CARDS
class TestStartGame:
def test_start_with_two_players(self, two_player_game_unstarted):
fake_redis = fakeredis.FakeRedis()
fake_redis.set('cheers', json.dumps(two_player_game_unstarted))
bev.cache = f... | cribbage/app/tests/test_bev.py | 29,811 | Tom has an Ace, kathy just passed and the total is at 30
Expected: It is now Tom's turn to play, he does not receive a point for go
Kathy and Tom each have face cards, kathy just passed and the total is at 30
Expected: It is Tom's turn and he must pass.
Kathy just hit 31, and has no cards left. Tom has a card left
E... | 1,277 | en | 0.979063 |
"""
Base and utility classes for tseries type pandas objects.
"""
from __future__ import annotations
from datetime import datetime
from typing import (
TYPE_CHECKING,
Any,
Callable,
Sequence,
TypeVar,
cast,
final,
)
import warnings
import numpy as np
from pandas._libs import (
NaT,
... | pandas/core/indexes/datetimelike.py | 23,961 | Common ops mixin to support a unified interface datetimelike Index.
Mixin class for methods shared by DatetimeIndex and TimedeltaIndex,
but not PeriodIndex
Return a list of tuples of the (attr,formatted_value).
Find the `freq` for self.delete(loc).
Find the `freq` for self.insert(loc, item).
Get the freq to attach to t... | 5,812 | en | 0.693284 |
# -*- coding: utf-8 -*-
"""
__author__ = "Jani Yli-Kantola"
__copyright__ = ""
__credits__ = ["Harri Hirvonsalo", "Aleksi Palomäki"]
__license__ = "MIT"
__version__ = "1.3.0"
__maintainer__ = "Jani Yli-Kantola"
__contact__ = "https://github.com/HIIT/mydata-stack"
__status__ = "Development"
"""
from app.helpers import... | Account/app/mod_system/controller.py | 2,315 | Clear API Key database
:return: true
Clear black box database
:return: true
Clear MySQL Database
:return: true
Check system functionality
:return: dict
__author__ = "Jani Yli-Kantola"
__copyright__ = ""
__credits__ = ["Harri Hirvonsalo", "Aleksi Palomäki"]
__license__ = "MIT"
__version__ = "1.3.0"
__maintainer__ = "Jan... | 452 | en | 0.353826 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: gym.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_datab... | gym/common/protobuf/gym_pb2.py | 106,874 | -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: gym.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:gym.Apparatus) @@protoc_insertion_point(class_scope:gym.Artifacts) @@protoc_insertion_point(class_scope:gym.Info.Environment.CpuEntry) @@protoc_insertio... | 2,450 | en | 0.349838 |
# led_hello.py - blink external LED to test GPIO pins
# (c) BotBook.com - Karvinen, Karvinen, Valtokari
"led_hello.py - light a LED using Raspberry Pi GPIO"
# Copyright 2013 http://Botbook.com */
import time # <1>
import os # <2>
def writeFile(filename, contents): # <3>
with open(filename, 'w') as f: # <4>
f.wri... | getting-started-code-101/raspberrypi/led_hello/led_hello.py | 711 | led_hello.py - blink external LED to test GPIO pins (c) BotBook.com - Karvinen, Karvinen, Valtokari Copyright 2013 http://Botbook.com */ <1> <2> <3> <4> <5> main <6> <7> <8> <9> <10> seconds <11> <12> | 201 | en | 0.168666 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Nets.UNetBatchNorm import UNetBatchNorm
import tensorflow as tf
import numpy as np
from sklearn.metrics import mean_squared_error
from datetime import datetime
from optparse import OptionParser
from Data.ImageTransform import ListTransform
from Data.DataGenClass impor... | src_DummyDataSet/UNet_UNNormalized.py | 22,961 | !/usr/bin/env python -*- coding: utf-8 -*- self.NUM_TEST = NUM_TEST (3)self.annotation = tf.divide(self.annotation, 255.) self.logits = self.conv_layer_f(self.last, self.logits_weight, strides=[1,1,1,1], scope_name="logits/")self.predictions = tf.squeeze(self.logits, [3])softmax = tf.nn.softmax(self.logits)print... | 759 | en | 0.354282 |
import pytest
from plenum.common.constants import AUDIT_LEDGER_ID, AUDIT_TXN_VIEW_NO, AUDIT_TXN_PP_SEQ_NO, AUDIT_TXN_PRIMARIES
from plenum.common.messages.node_messages import Checkpoint, CheckpointState
from plenum.test.checkpoints.helper import cp_digest
from plenum.test.test_node import getNonPrimaryReplicas, getAl... | plenum/test/checkpoints/test_checkpoints_removal_after_catchup_during_view_change.py | 7,519 | Initiate view change to the next view Simulate catch-up completion Simulate catch-up completion | 95 | en | 0.880803 |
"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """
from sympy import S, sqrt, sin, oo, nan, Poly, Integer, Rational
from sympy.abc import x, y, z
from sympy.polys.domains import (ZZ, QQ, RR, CC, FF, GF,
PolynomialRing, FractionField, EX)
from sympy.polys.rings import ring
from... | PPTexEnv_x86_64/lib/python2.7/site-packages/sympy/polys/domains/tests/test_domains.py | 26,319 | Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... | 79 | en | 0.750702 |
from globconf import config
from globconf import verify_required_options
import unittest
import os
# let's test on a predefined file included in the unitteast
config.read(os.path.dirname(__file__)+'/config.ini')
class TestConf(unittest.TestCase):
def test_config_file_present(self):
self.assertTrue(os.pa... | test/test_verify_required_options.py | 629 | let's test on a predefined file included in the unitteast | 57 | en | 0.944489 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v2/proto/enums/recommendation_type.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 imp... | google/ads/google_ads/v2/proto/enums/recommendation_type_pb2.py | 6,185 | -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: google/ads/googleads_v2/proto/enums/recommendation_type.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:google.ads.googleads.v2.enums.RecommendationTypeEnum) @@protoc_insertion_point(module_scope) | 312 | en | 0.471739 |
#!/usr/bin/env python3
"""Write a type-annotated function sum_mixed_list which takes
a list mxd_lst of integers and floats and returns their sum as a float."""
from typing import Iterable, List, Union
def sum_mixed_list(mxd_lst: List[Union[int, float]]) -> float:
"""sum all float number in list
Args:
... | 0x00-python_variable_annotations/6-sum_mixed_list.py | 420 | sum all float number in list
Args:
input_list (List[float]): arg
Returns:
float: result
Write a type-annotated function sum_mixed_list which takes
a list mxd_lst of integers and floats and returns their sum as a float.
!/usr/bin/env python3 | 251 | en | 0.573961 |
"""
Камни и украшения
Даны две строки строчных латинских символов: строка J и строка S.
Символы, входящие в строку J, — «драгоценности», входящие в строку S — «камни».
Нужно определить, какое количество символов из S одновременно являются
«драгоценностями». Проще говоря, нужно проверить, какое количество символов
из ... | Python/yandex/stones_and_diamonds.py | 1,414 | Камни и украшения
Даны две строки строчных латинских символов: строка J и строка S.
Символы, входящие в строку J, — «драгоценности», входящие в строку S — «камни».
Нужно определить, какое количество символов из S одновременно являются
«драгоценностями». Проще говоря, нужно проверить, какое количество символов
из S вх... | 650 | ru | 0.995592 |
# Copyright 2017 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... | language-app/stubs/ctypes.py | 669 | Stub ``ctypes`` module.
Used by ``setuptools.windows_helpers``.
Copyright 2017 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/L... | 636 | en | 0.845418 |
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli... | python/paddle/fluid/dygraph/dygraph_to_static/partial_program.py | 16,777 | Descriptor to implement lazy initialization of property.
A wrapper class that easily to flatten and restore the nest structure of
given sequence.
PartialProgramLayer wraps all the ops from layers decorated by `@declarative`
and execute them as a static subgraph.
.. note::
**1. This is a very low level API. Users s... | 4,187 | en | 0.781852 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import re
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('wmsmanager', '0002_auto_20151125_1310'),
]
operations = [
migrations.AlterField(
... | wmsmanager/migrations/0003_auto_20151203_1448.py | 895 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/env python3
# Copyright (c) 2020 The Elixir Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Test addr relay
"""
from test_framework.messages import (
CAddress,
NODE_NETWORK,
NODE_WITNESS,... | test/functional/p2p_addr_relay.py | 8,306 | Test addr relay
!/usr/bin/env python3 Copyright (c) 2020 The Elixir Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. pop m_next_addr_send timer Keep this with length <= 10. Addresses from larger messages are not relayed... | 759 | en | 0.917599 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import tarfile
import unittest
from unittest.mock import MagicMock
import fsspec
from torchx.specs import Role... | torchx/workspace/test/docker_workspace_test.py | 5,072 | Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. no image_repo with image_repo | 227 | en | 0.886565 |
# encoding: UTF-8
import time
from redtorch.event import *
from redtorch.trader.vtEvent import *
from redtorch.trader.vtConstant import *
from redtorch.trader.vtObject import *
########################################################################
class VtGateway(object):
"""交易接口"""
#-------------------... | redtorch/trader/vtGateway.py | 4,840 | 交易接口
Constructor
撤单
关闭
连接
账户信息推送
合约基础信息推送
错误信息推送
日志推送
订单变化推送
持仓信息推送
市场行情推送
成交信息推送
查询账户资金
查询持仓
发单
订阅行情
encoding: UTF-8-------------------------------------------------------------------------------------------------------------------------------------------- 通用事件 特定合约代码的事件----------------------------------------------... | 1,329 | zh | 0.20341 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.