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 |
|---|---|---|---|---|---|---|
from io import BufferedIOBase
import os
import sys
if sys.platform == 'win32':
import _winapi
import msvcrt
class WindowsPipe:
def __init__(self, experiment_id: str):
self.path: str = r'\\.\pipe\nni-' + experiment_id
self.file = None
self._handle = _winapi.Crea... | nni/experiment/pipe.py | 1,779 | only accepts one connection | 27 | en | 0.827018 |
import os
import scipy.misc
import torch
import numpy as np
import torch.optim as optim
import config
import data_loader
import d_net
import loss_funs
import g_net
dtype = config.dtype
def save_samples(generated_images, iteration, prefix):
generated_images = generated_images.data.cpu().numpy()
num_images,... | process.py | 4,332 | Load Pacman dataset batch_size x noise_size x 1 x 1 WGAN loss https://github.com/keras-team/keras-contrib/blob/master/examples/improved_wgan.py TESTING: Vanilla Video Gan Fake batch TODO: Validate if it's right. Real batch TODO: Validate if it's right. batch_size x noise_size x 1 x 1 print('G_Time:', end - start) TESTI... | 481 | en | 0.599673 |
# coding: ascii
"""Python 2.x/3.x compatibility tools"""
import sys
__all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_',
'unicode_', 'raw_input_', 'as_bytes', 'as_unicode',
'bytes_', 'imap_', 'PY_MAJOR_VERSION']
PY_MAJOR_VERSION = sys.version_info[0]
def geterror():
... | Python_MiniGame_Fighter/venv/Lib/site-packages/pygame/compat.py | 3,214 | '<binary literal>' => b'<binary literal>'
'<binary literal>' => '<binary literal>'
r'<Unicode literal>' => '<Unicode literal>'
r'<Unicode literal>' => u'<Unicode literal>'
Python 2.x/3.x compatibility tools
coding: ascii Python 3 Represent escaped bytes and strings in a portable way. as_bytes: Allow a Python 3.x ... | 1,227 | en | 0.538474 |
from .fhirbase import fhirbase
class CapabilityStatement(fhirbase):
"""
A Capability Statement documents a set of capabilities (behaviors) of
a FHIR Server that may be used as a statement of actual server
functionality or a statement of required or desired server
implementation.
Attributes:
... | cardea/fhir/CapabilityStatement.py | 42,927 | A Capability Statement documents a set of capabilities (behaviors) of
a FHIR Server that may be used as a statement of actual server
functionality or a statement of required or desired server
implementation.
Attributes:
resourceType: This is a CapabilityStatement resource
url: An absolute URI that is used to i... | 20,571 | en | 0.806964 |
import os
import sys
import argparse
import datetime
import time
import csv
import os.path as osp
import numpy as np
import warnings
import importlib
import pandas as pd
warnings.filterwarnings('ignore')
import torch
import torch.nn as nn
from torch.optim import lr_scheduler
import torch.backends.cudnn as cudnn
import... | main.py | 6,885 | dataset optimization model misc parameters for generating adversarial examples define loss function (criterion) and optimizer | 125 | en | 0.490819 |
import requests
from bs4 import BeautifulSoup
import jinja2
import re
class Chara:
name = ''
job = ''
hp = 0
mp = 0
str = 0
end = 0
dex = 0
agi = 0
mag = 0
killer = ""
counter_hp = ""
skills = ""
passive_skills = ""
class HtmlParser:
def __init__(self, text):
... | gen_chara.py | 18,267 | has attack print(buffs_str) print(debuffs_str)limit_break_status_table = parser.get_next_div() | 94 | en | 0.259444 |
"""Base classes for Axis entities."""
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import DeviceInfo, Entity
from .const import DOMAIN as AXIS_DOMAIN
class AxisEntityBase(Entity):
"""Base common to all Axis entiti... | homeassistant/components/axis/axis_base.py | 1,887 | Base common to all Axis entities.
Base common to all Axis entities from event stream.
Initialize the Axis event.
Initialize the Axis event.
Return True if device is available.
Update the entities state.
Base classes for Axis entities. | 234 | en | 0.861874 |
'''
This module has all relevant functions to make predictions using a previously
trained model.
'''
import os
import numpy as np
import tensorflow.keras as keras
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model
import cv2
model = load_model('../models/app_ban_ora_selftra... | src/predict.py | 1,384 | Decodes predictions and returns a result string.
Takes a frame as input, makes a prediction, decoodes it
and returns a result string.
This module has all relevant functions to make predictions using a previously
trained model. | 226 | en | 0.850624 |
import asyncio
import math
import time
import traceback
from pathlib import Path
from random import Random
from secrets import randbits
from typing import Dict, Optional, List, Set
import aiosqlite
import chia.server.ws_connection as ws
import dns.asyncresolver
from chia.protocols import full_node_protocol, introduce... | chia/server/node_discovery.py | 31,433 | This is a double check to make sure testnet and mainnet peer databases never mix up. If the network is not 'mainnet', it names the peer db differently, including the selected_network. Updates timestamps each time we receive a message for outbound connections. Mark it as a softer attempt, without counting the failures. ... | 2,294 | en | 0.924678 |
from collections.abc import Mapping
import inspect
import types
from typing import Callable
import numpy as np
import sympy
from sympy.codegen import cfunctions as sympy_cfunctions
from numpy.random import randn, rand
from sympy import Function as sympy_Function
from sympy import S
import brian2.units.unitsafefunctio... | brian2/core/functions.py | 35,780 | An abstract specification of a function that can be used as part of
model equations, etc.
Parameters
----------
pyfunc : function
A Python function that is represented by this `Function` object.
sympy_func : `sympy.Function`, optional
A corresponding sympy function (if any). Allows functions to be
interpre... | 12,070 | en | 0.709796 |
# -*- coding: utf-8 -*-
"""SQLAlchemy models for Bio2BEL HGNC."""
from __future__ import annotations
from sqlalchemy import Column, ForeignKey, Integer, String, Table
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
from sqlalchemy.orm import relationship
from bio2bel.compath import CompathP... | src/bio2bel_hgnc/models.py | 3,634 | A SQLAlchemy model for an HGNC Gene family.
A SQLAlchemy model for a human gene.
A SQLAlchemy model for a mouse gene.
A SQLAlchemy model for an rat gene.
SQLAlchemy models for Bio2BEL HGNC.
-*- coding: utf-8 -*- | 213 | en | 0.723093 |
"""
With these settings, tests run faster.
"""
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="Zr7lk4kl3... | config/settings/test.py | 1,679 | With these settings, tests run faster.
noqa GENERAL ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/secret-key https://docs.djangoproject.com/en/dev/ref/settings/test-runner CACHES -------------------------------------------------------... | 900 | en | 0.371199 |
#!/usr/bin/env python
import sys, os
import itertools, operator
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def reader(myfile):
t = np.array([])
print(myfile)
with open(myfile) as f:
lines = f.readlines()
for line in lines:
parts = line.split(" ")
if(len... | ex3/z1/graph.py | 2,555 | !/usr/bin/env pythonax.yaxis.set_ticks(np.arange(0,210,10))print(t1,t2) uncomment in order to print line plots | 110 | en | 0.431387 |
# Copyright 2020 Google LLC.
#
# 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... | notebooks/samples/tensorflow/sentiment_analysis/dataflow/PubSubToBigQueryWithAPI.py | 10,311 | A composite transform that groups Pub/Sub messages based on publish
time and outputs a list of dictionaries, where each contains one message
and its publish timestamp.
Analyzing Sentiment in a String
Args:
text_content The text content to analyze
Processes PubSub messages and calls AI Platform prediction.
:param ... | 2,264 | en | 0.820158 |
#https://docs.pymc.io/notebooks/GLM-hierarchical-binominal-model.html
import matplotlib.pyplot as plt
import scipy.stats as stats
import numpy as np
import pandas as pd
#import seaborn as sns
import pymc3 as pm
import arviz as az
import theano.tensor as tt
np.random.seed(123)
# rat data (BDA3, p. 102)
y = np.arr... | scripts/hbayes_binom_rats_pymc3.py | 3,785 | prior density
https://docs.pymc.io/notebooks/GLM-hierarchical-binominal-model.htmlimport seaborn as sns rat data (BDA3, p. 102) Uninformative prior for alpha and betatrace = pm.sample(1000, tune=2000, target_accept=0.95)az.plot_trace(trace)plt.savefig('../figures/hbayes_binom_rats_trace.png', dpi=300) | 303 | en | 0.394721 |
import os
from os.path import join
from ...utils import remove
from .. import run_nbgrader
from .base import BaseTestApp
class TestNbGraderExport(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["export", "--help-all"])
def test_export(self, db, co... | nbgrader/tests/apps/test_nbgrader_export.py | 2,046 | Does the help display without error? | 36 | en | 0.746264 |
#MenuTitle: Set Transform Origin
# -*- coding: utf-8 -*-
__doc__="""
Sets origin point for Rotate tool.
"""
import vanilla
class SetTransformOriginWindow( object ):
def __init__( self ):
# Window 'self.w':
windowWidth = 370
windowHeight = 60
windowWidthResize = 0 # user can resize width by this value
wi... | Paths/Set Transform Origin.py | 2,790 | MenuTitle: Set Transform Origin -*- coding: utf-8 -*- Window 'self.w': user can resize width by this value user can resize height by this value default window size window title minimum size (for resizing) maximum size (for resizing) stores last window position and size UI elements: Run Button: Load Settings: Open windo... | 386 | en | 0.77844 |
# 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... | tensorflow_probability/python/distributions/truncated_cauchy.py | 15,816 | The Truncated Cauchy distribution.
The truncated Cauchy is a Cauchy distribution bounded between `low`
and `high` (the pdf is 0 outside these bounds and renormalized).
Samples from this distribution are differentiable with respect to `loc`
and `scale`, but not with respect to the bounds `low` and `high`.
### Mathema... | 4,998 | en | 0.791131 |
# http://rosalind.info/problems/mmch/
from math import factorial
def nPr(n, k):
'''Returns the number of k-permutations of n.'''
return factorial(n) / factorial(n-k)
f = open("rosalind_mmch.txt", "r")
dnas = {}
currentKey = ''
for content in f:
# Beginning of a new sample
if '>' in content:
... | rosalind/mmch.py | 762 | http://rosalind.info/problems/mmch/ Beginning of a new sample There are nPr(max, min) edges for each AU, CG. Total number of edges is then the product. | 151 | en | 0.765164 |
# Copyright (c) 2006-2016 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2010 Daniel Harding <dharding@gmail.com>
# Copyright (c) 2012-2014 Google, Inc.
# Copyright (c) 2013-2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2014 Brett Cannon <brett@python.org>
# Copyright (c) 2014 Arun Persau... | venv/lib/python3.8/site-packages/pylint/checkers/base.py | 100,471 | checks for :
* doc strings
* number of arguments, local variables, branches, returns and statements in
functions, methods
* required module attributes
* dangerous default values as arguments
* redefinition of function / method / class
* uses of the global statement
Regex rules for camelCase naming style.
Checks for com... | 14,537 | en | 0.737427 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
# @Time : 2020-01-16 15:53
# @Author : 行颠
# @Email : 0xe590b4@gmail.com
# @File : view
# @Software: view
# @DATA : 2020-01-16
"""
import os
import asyncio
import motor.motor_asyncio
import aiohttp
from aiohttp import web
import aiohttp_jinja2
import json
... | apps/package/view.py | 3,727 | # @Time : 2020-01-16 15:53
# @Author : 行颠
# @Email : 0xe590b4@gmail.com
# @File : view
# @Software: view
# @DATA : 2020-01-16
!/usr/bin/python3 -*- coding: utf-8 -*- await ws.send_json({"$or":params}) 实时获取输出 print("sub process err: ", err) print("sub process output: ", out) 子进程返回值 | 295 | en | 0.270924 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Models for storing inactive and deprecated tables from the CAL-ACCESS database.
"""
from __future__ import unicode_literals
# Models
from django.db import models
from calaccess_raw import fields
from .base import CalAccessBaseModel
from django.utils.encoding import pyt... | calaccess_raw/models/inactive.py | 75,087 | Ballot-measure dates and times.
The cover page for officeholder and candidate short and supplemental forms.
Logs from the Electronic Filing Subsystem, which accepts and validates electronic filings.
Undocumented.
The table's official description contains this note: "J M needs to document. This is
in his list of tables... | 10,299 | en | 0.822327 |
from rdflib import Graph
import requests
import ipaddress
import json
import socket
from urllib.parse import urlparse
from .base import BaseLDN
class Sender(BaseLDN):
def __init__(self, **kwargs):
super(self.__class__, self).__init__(**kwargs)
self.allow_localhost = kwargs.get('allow_localhost'... | ldnlib/sender.py | 2,017 | Send the provided data to an inbox. | 35 | en | 0.68172 |
"""
A helper class for using TLS Lite with stdlib clients
(httplib, xmlrpclib, imaplib, poplib).
"""
from tlslite.Checker import Checker
class ClientHelper:
"""This is a helper class used to integrate TLS Lite with various
TLS clients (e.g. poplib, smtplib, httplib, etc.)"""
def __init__(self,
... | third_party/tlslite/tlslite/integration/ClientHelper.py | 6,851 | This is a helper class used to integrate TLS Lite with various
TLS clients (e.g. poplib, smtplib, httplib, etc.)
For client authentication, use one of these argument
combinations:
- username, password (SRP)
- username, sharedKey (shared-key)
- certChain, privateKey (certificate)
For server authentication, you can e... | 3,457 | en | 0.719124 |
""":mod:`kinsumer.version` --- Version information
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
VERSION_INFO = (0, 5, 3)
VERSION = '{}.{}.{}'.format(*VERSION_INFO)
if __name__ == '__main__':
print(VERSION)
| kinsumer/version.py | 222 | :mod:`kinsumer.version` --- Version information
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | 98 | pl | 0.228766 |
"""
SYNOPSIS
--------
Get the details of unused resources present across regions in the AWS account
DESCRIPTION
-----------
This script provides a detailed overview of the number of unused resources present in the AWS account.
It provides service-wise details of unused resources lying around in all t... | unused_aws_resources.py | 21,740 | SYNOPSIS
--------
Get the details of unused resources present across regions in the AWS account
DESCRIPTION
-----------
This script provides a detailed overview of the number of unused resources present in the AWS account.
It provides service-wise details of unused resources lying around in all the re... | 1,447 | en | 0.73123 |
import os
from ....modules.utils.config_utils import get_yaml_config
str2yaml = {
"gat": "gat.yaml",
"gcn": "gcn.yaml",
"ggnn": "ggnn.yaml",
"graphsage": "graphsage.yaml",
}
dir_path = os.path.dirname(os.path.realpath(__file__))
def get_graph_embedding_args(graph_embedding_name):
"""
It... | graph4nlp/pytorch/modules/config/graph_embedding/__init__.py | 1,373 | It will build the template for ``GNNBase`` model.
Parameters
----------
graph_embedding_name: str
The graph embedding name. Expected in ["gcn", "gat", "graphsage", "ggnn"].
If it can't find the ``graph_embedding_name``, it will return ``{}``.
Returns
-------
template_dict: dict
The template dict.
The st... | 702 | en | 0.597779 |
import numpy as np
from skimage import io as ios
import PySimpleGUI as sg
import warnings
import m_specfun as m_fun
def select_lines(infile, contrast, lines, res_dict, fits_dict, wloc, outfil):
"""
displays new window with image infile + start + 'fit
a rectangle around the selected line can be... | myselect.py | 8,658 | displays new window with image infile + start + 'fit
a rectangle around the selected line can be selected with dragging the mouse
:param infile: filebase of image
:param contrast: brightness of image
:param lines: list of calibration wavelengths
:param res_dict: dictionary
:param fits_dict: "
:param wloc: location of d... | 1,289 | en | 0.784972 |
# -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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
#
# U... | qiskit/extensions/standard/x.py | 1,932 | Pauli X (bit-flip) gate.
Create new X gate.
Invert this gate.
Return OPENQASM string.
Reapply this gate to corresponding qubits in circ.
Apply X to q.
Pauli X (bit-flip) gate.
Author: Andrew Cross
-*- coding: utf-8 -*- Copyright 2017 IBM RESEARCH. All Rights Reserved. Licensed under the Apache License, Version 2.0 (... | 884 | en | 0.803278 |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | darling_ansible/python_venv/lib/python3.7/site-packages/oci/vault/models/schedule_secret_deletion_details.py | 2,549 | Details for scheduling the deletion of the specified secret.
Initializes a new ScheduleSecretDeletionDetails object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param time_of_deletion:
The value to assign to the time_of_del... | 1,378 | en | 0.776249 |
# Generated by Django 2.0.4 on 2018-04-20 09:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('daily_tracker', '0001_in... | office_tracker/daily_tracker/migrations/0002_auto_20180420_0946.py | 897 | Generated by Django 2.0.4 on 2018-04-20 09:46 | 45 | en | 0.67918 |
"""
Copyright (c) 2017, Syslog777
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... | psak_src/psak_src/exploit_modules/ping.py | 3,034 | Copyright (c) 2017, Syslog777
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 followin... | 1,522 | en | 0.89263 |
import os
import pyconll
from ufal.udpipe import Model, Pipeline, ProcessingError
class UDPipeToken:
def __init__(self, ud_token, upos=None, tags=None):
self.id = ud_token.id
self.form = ud_token.form
self.upos = ud_token.upos if upos is None else upos
self.lemma = ud_token.lemma
... | py/generative_poetry/udpipe_parser.py | 2,024 | Исправляем ошибки разметки некоторых слов в UDPipe.Syntagrus | 60 | ru | 0.92086 |
"""
Laplacian of a compressed-sparse graph
"""
# Authors: Aric Hagberg <hagberg@lanl.gov>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Jake Vanderplas <vanderplas@astro.washington.edu>
# License: BSD
from __future__ import division, print_function, absolute_import
import numpy as np
from scip... | docker_version/resources/usr/local/lib/python2.7/dist-packages/scipy/sparse/csgraph/_laplacian.py | 4,487 | Return the Laplacian matrix of a directed graph.
For non-symmetric graphs the out-degree is used in the computation.
Parameters
----------
csgraph : array_like or sparse matrix, 2 dimensions
compressed-sparse graph, with shape (N, N).
normed : bool, optional
If True, then compute normalized Laplacian.
return_... | 1,800 | en | 0.744554 |
"""
Copyright 2015 Rackspace
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
dist... | cloudcafe/events/models/compute/common.py | 6,212 | Bandwidth Response Model
@summary: Response model for bandwidth from a compute
event notification
@note: Although the 'public' and 'private' interfaces are
not required, they are the most common names, and are
included as optional attributes for the sake of convenience
@note: This type may contain addition... | 3,166 | en | 0.743016 |
# -*- coding: utf-8 -*-
"""Test i18n module."""
#
# (C) Pywikibot team, 2007-2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals
__version__ = '$Id: 791a455ab0a66f7bafcfb71718f915c9dd7b7ab2 $'
import sys
import pywikibot
from pywikibot import i18n, bot, plural
from t... | tests/i18n_tests.py | 16,847 | Test i18n.input.
Test misssing messages package.
Real messages test.
Partial base class for TranslateWiki tests.
Base class for TranslateWiki tests.
Test {{PLURAL:}} support.
Test twtranslate method.
Test translate method.
Base class for tests using config.userinterface_lang.
Use a dictionary.
Use additional format str... | 1,408 | en | 0.686094 |
import socket
import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
process = cms.Process("LHCInfoPopulator")
from CondCore.CondDB.CondDB_cfi import *
#process.load("CondCore.DBCommon.CondDBCommon_cfi")
#process.CondDBCommon.connect = 'sqlite_file:lhcinfo_pop_test.db'
#process.Con... | CondTools/RunInfo/python/LHCInfoPopConAnalyzerStartFill.py | 4,917 | process.load("CondCore.DBCommon.CondDBCommon_cfi")process.CondDBCommon.connect = 'sqlite_file:lhcinfo_pop_test.db'process.CondDBCommon.DBParameters.authenticationPath = '.'process.CondDBCommon.DBParameters.messageLevel=cms.untracked.int32(1)default valuedefault valuedefault valueendTime = cms.untracked.string('2018-03-... | 386 | en | 0.197523 |
"""
CSVLogger writes power values to a csv file.
"""
__author__ = 'Md Shifuddin Al Masud'
__email__ = 'shifuddin.masud@gmail.com'
__license__ = 'MIT License'
from pv_simulator.FileWriter import FileWriter
import csv
from datetime import datetime
import aiofiles
from aiocsv import AsyncWriter
import logging
class CSV... | pv_simulator/CSVFileWriter.py | 1,401 | :param destination:
CSVLogger writes power values to a csv file. | 64 | en | 0.581016 |
'''
This function takes in index_list, data_path , save_path as the arguments. It writes a video consisting
of the frame in data_path into save_path and writes a text file with the indexed of the representative
frame into the same directory
inputs :
- frames = list of frames i.e. numpy arrays
- sca... | storage/compression/write_original_video.py | 2,302 | This function takes in index_list, data_path , save_path as the arguments. It writes a video consisting
of the frame in data_path into save_path and writes a text file with the indexed of the representative
frame into the same directory
inputs :
- frames = list of frames i.e. numpy arrays
- scale = scale t... | 513 | en | 0.781772 |
"""Tests for _data_finder.py."""
import os
import shutil
import tempfile
import pytest
import yaml
import esmvalcore._config
from esmvalcore._data_finder import (get_input_filelist, get_input_fx_filelist,
get_output_file)
from esmvalcore.cmor.table import read_cmor_tables
# Initi... | tests/integration/test_data_finder.py | 3,425 | Create an empty file.
Create directory structure and files.
Print path.
Root function for tests.
Test retrieving input filelist.
Test retrieving fx filelist.
Test getting output name for preprocessed files.
Print path, similar to the the `tree` command.
Tests for _data_finder.py.
Initialize with standard config devel... | 422 | en | 0.599473 |
# Copyright (C) 2003-2005 Peter J. Verveer
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following d... | kapteyn/interpolation.py | 20,228 | Apply an affine transformation.
The given matrix and offset are used to find for each point in the
output the corresponding coordinates in the input by an affine
transformation. The value of the input at those coordinates is
determined by spline interpolation of the requested order. Points
outside the boundaries of th... | 7,938 | en | 0.769068 |
# coding: utf-8
"""
Katib
Swagger description for Katib # noqa: E501
OpenAPI spec version: v1alpha3-0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from kubeflow.katib.models.v1alpha3_algorithm_spec import V1alpha3Alg... | sdk/python/v1alpha3/kubeflow/katib/models/v1alpha3_experiment_spec.py | 12,954 | 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
V1alpha3ExperimentSpec - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the algorithm of this V1alpha3ExperimentSpec. # ... | 5,259 | en | 0.661605 |
## utility functions
## including: labelling, annotation, continuous borders
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
## create labels
def generate_class_label(data):
"""
generates class label on a copy of data using the columns
State, From_X, From_Y, To_X, To_Y
... | notebooks/pawel_ueb2/utility.py | 6,794 | draws annotation into a sns heatmap using plt annotation
a : dictonary with activity name and borders
generates class label on a copy of data using the columns
State, From_X, From_Y, To_X, To_Y
generates class label on a copy of data using the columns
State, From_X, From_Y, To_X, To_Y
generates class label only for pr... | 1,472 | en | 0.663768 |
# Script:
#
# remove all articles from the DB which have no
# references to them and are older than a number of days
#
# works with the db that is defined in the configuration
# pointed by ZEEGUU_CORE_CONFIG
#
# takes as argument the number of days before which the
# articles will be deleted.
#
# call like this to remo... | tools/remove_unreferenced_articles.py | 1,716 | Script: remove all articles from the DB which have no references to them and are older than a number of days works with the db that is defined in the configuration pointed by ZEEGUU_CORE_CONFIG takes as argument the number of days before which the articles will be deleted. call like this to remove all articles older th... | 377 | en | 0.918489 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... | packages/fetchai/skills/confirmation_aw3/__init__.py | 985 | This module contains the implementation of the confirmation_aw3 skill.
-*- coding: utf-8 -*- ------------------------------------------------------------------------------ Copyright 2018-2019 Fetch.AI Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in com... | 831 | en | 0.732108 |
import pytest
from django.test import TestCase
from .factories import CoopTypeFactory, CoopFactory, AddressFactory, PhoneContactMethodFactory
from directory.models import Coop, CoopType
class ModelTests(TestCase):
@classmethod
def setUpTestData(cls):
print("setUpTestData: Run once to set up non-modif... | web/tests/test_models.py | 3,380 | Test address model
Test customer model
Test customer model
Test customer model
Test coop type model
Test phone contact method
Test phone contact method
Look for coops with addresses without latitude/longitude coords
management.call_command('loaddata', 'test_data.yaml', verbosity=0) create phone instance create ... | 552 | en | 0.664679 |
import json
from io import BytesIO
from six import text_type
import attr
from zope.interface import implementer
from twisted.internet import address, threads, udp
from twisted.internet._resolver import HostResolution
from twisted.internet.address import IPv4Address
from twisted.internet.defer import Deferred
from tw... | tests/server.py | 10,677 | A fake Twisted Web Channel (the part that interfaces with the
wire).
A fake Twisted Web Site, with mocks of the extra things that
Synapse adds.
A twisted.internet.interfaces.ITransport implementation which sends all its data
straight into an IProtocol object: it exists to connect two IProtocols together.
To use it, in... | 1,676 | en | 0.84291 |
import torch.nn as nn
import torch.nn.functional as F
class RNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(RNNAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidd... | src_convention/modules/agents/rnn_agent.py | 1,138 | make hidden states on same device as model 主要是在 controllers 中使用 | 63 | zh | 0.605508 |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class TutorialSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy... | tutorial/tutorial/middlewares.py | 3,601 | -*- coding: utf-8 -*- Define here the models for your spider middleware See documentation in: https://doc.scrapy.org/en/latest/topics/spider-middleware.html Not all methods need to be defined. If a method is not defined, scrapy acts as if the spider middleware does not modify the passed objects. This method is used by ... | 1,931 | en | 0.87019 |
from keras.engine.topology import Layer
from keras.backend.tensorflow_backend import tf
class Multiplexer(Layer):
def __init__(self, output_dim, nb_ctrl_sig, **kwargs):
"""
This layer is used to split the output of a previous Dense layer into
nb_ctrl_sig groups of size output_dim, and choo... | multiplexer.py | 6,374 | This layer is used to split the output of a previous Dense layer into
nb_ctrl_sig groups of size output_dim, and choose which group to provide
as output using a discrete control signal.
It takes as input two tensors, namely the output of the previous layer
and a column tensor with int32 or int64 values for the control... | 1,713 | en | 0.71992 |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.documents import urls as wagtaildocs_urls
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/... | aldryn_wagtail/urls.py | 732 | -*- coding: utf-8 -*- Serve static and media files from development server | 74 | en | 0.882196 |
#! /usr/bin/python
import sys,shutil, urllib2, json, time, subprocess, os, commands, signal, re
sys.path.insert(0, 'srch2lib')
import test_lib
port = '8087'
# This test case reads data from the json files
# Then it reads all the access control data from json files too
# Then it does some search and it uses roleId i... | test/wrapper/system_tests/access_control/record-based-ACL.py | 5,842 | ! /usr/bin/python This test case reads data from the json files Then it reads all the access control data from json files too Then it does some search and it uses roleId in the query And all the results should have this roleId in their access list it reads the keywords and role ids from queriesAndResults.txt file the f... | 1,057 | en | 0.648562 |
# SPDX-FileCopyrightText: Copyright 2021, Siavash Ameli <sameli@berkeley.edu>
# SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileType: SOURCE
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the license found in the LICENSE.txt file in the root directory
# of this source ... | ortho/_orthogonal_functions/declarations.py | 563 | SPDX-FileCopyrightText: Copyright 2021, Siavash Ameli <sameli@berkeley.edu> SPDX-License-Identifier: BSD-3-Clause SPDX-FileType: SOURCE This program is free software: you can redistribute it and/or modify it under the terms of the license found in the LICENSE.txt file in the root directory of this source tree. ======= ... | 416 | en | 0.646381 |
from abc import ABC, abstractmethod
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
class mab_user(ABC):
def __init__(self, n_arms, lamb=1):
super(mab_user, self).__init__()
self.t = torch.tensor(1.0)
self.r = torch.zeros(n_arms)
self.n = torch.zero... | user.py | 3,272 | users that always make perfect decision -- can be paired with recEngines in CF simulationsthis setup routine must be called before perfect_user can run | 152 | en | 0.893964 |
from flask import request, jsonify
from flask_restful import Resource, reqparse, abort
from flask_jwt import current_app
from app.auth.models import User
def generate_token(user):
""" Currently this is workaround
since the latest version that already has this function
is not published on PyPI yet and we do... | Chapter04/app/auth/resources.py | 1,732 | Currently this is workaround
since the latest version that already has this function
is not published on PyPI yet and we don't want
to install the package directly from GitHub.
See: https://github.com/mattupstate/flask-jwt/blob/9f4f3bc8dce9da5dd8a567dfada0854e0cf656ae/flask_jwt/__init__.py#L145 | 295 | en | 0.894915 |
import unittest
import cryptomon.common as common
class Testcryptomon(unittest.TestCase):
def setUp(self):
self.response = [
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "15653.... | tests/test_cryptomon.py | 3,436 | all items must have same number of fields | 41 | en | 0.90827 |
import logging
import random
import re
from urllib.parse import urljoin
from urllib.parse import urlparse
import requests
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
IMAGE_FILE_REGEX = re.compile(r'([-\w]+\.(?:jpg|jpeg|gif|png))',
re.IGNORECASE)
def crawl_page(p... | simple_workflow/v1/crawl.py | 2,010 | Picks a random image off of the passed URL.
Fetches a url's HTML and extracts all image sources in an <img> tag.
Crawl the website for images. Return a random one. Fetch the content. Find images in the content. | 217 | en | 0.75655 |
import math
import random
from typing import Dict, Iterable, Sequence, Tuple
from eth.constants import ZERO_HASH32
from eth_typing import BLSPubkey, BLSSignature, Hash32
from eth_utils import to_tuple
from eth_utils.toolz import keymap as keymapper
from eth_utils.toolz import pipe
from eth2._utils.bitfield import get... | eth2/beacon/tools/builder/validator.py | 21,728 | Create a mocking attestation of the given ``attestation_data`` slot with ``keymap``.
Get ``message_hash`` and voting indices of the given ``committee``.
Aggregate the votes.
Return a `ProposerSlashing` derived from the given block roots.
If the header roots do not match, the `ProposerSlashing` is valid.
If the header ... | 1,244 | en | 0.688763 |
import base64
import deployment_options
import os
import tempfile
import utils
def render_file(namespace, private_key, public_key):
src_file = os.path.join(os.getcwd(), 'deploy/assisted-installer-local-auth.yaml')
dst_file = os.path.join(os.getcwd(), 'build', namespace, 'assisted-installer-local-auth.yaml')
... | tools/deploy_local_auth_secret.py | 2,329 | Render a file without values for the operator as we don't want every deployment to have the same values | 103 | en | 0.956093 |
# -*- coding: utf-8 -*-
data = ''
with open('input.txt') as f:
data = f.read().strip()
def Reacts(a, b):
if a == b:
return False
if a.lower() == b or b.lower() == a:
return True
return False
def Collapse(polymer):
i = 1
while i < len(polymer):
... | 05/aoc05.py | 911 | -*- coding: utf-8 -*-data = 'bbbbAaccc' | 39 | en | 0.603952 |
# Copyright 2013 Cloudbase Solutions Srl
# 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 r... | nova/virt/hyperv/pathutils.py | 9,588 | Wrapper on __builtin__.open used to simplify unit testing.
Copyright 2013 Cloudbase Solutions Srl 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.ap... | 1,281 | en | 0.866854 |
"""
Module for all Form Tests.
"""
import pytest
from django.utils.translation import gettext_lazy as _
from djcutter.users.forms import UserCreationForm
from djcutter.users.models import User
pytestmark = pytest.mark.django_db
class TestUserCreationForm:
"""
Test class for all tests related to the UserCrea... | djcutter/users/tests/test_forms.py | 1,165 | Test class for all tests related to the UserCreationForm
Tests UserCreation Form's unique validator functions correctly by testing:
1) A new user with an existing username cannot be added.
2) Only 1 error is raised by the UserCreation Form
3) The desired error message is raised
Module for all Form Tests.
... | 369 | en | 0.84332 |
#!/usr/bin/env python3
import depthai as dai
import subprocess as sp
from os import name as osName
# Create pipeline
pipeline = dai.Pipeline()
# Define sources and output
camRgb = pipeline.createColorCamera()
videoEnc = pipeline.createVideoEncoder()
xout = pipeline.createXLinkOut()
xout.setStreamName("h264")
# Pro... | gen2-play-encoded-stream/main.py | 1,571 | !/usr/bin/env python3 Create pipeline Define sources and output Properties Linking Running on Windows Start the ffplay process Connect to device and start pipeline Output queue will be used to get the encoded data from the output defined above Blocking call, will wait until new data has arrived | 295 | en | 0.797659 |
# https://github.com/TrustyJAID/Trusty-cogs/blob/master/notsobot/converter.py
import re
from discord.ext.commands.converter import Converter
from discord.ext.commands.errors import BadArgument
from redbot.core.i18n import Translator
_ = Translator("ReverseImageSearch", __file__)
IMAGE_LINKS = re.compile(
r"(htt... | reverseimagesearch/converters.py | 3,075 | This is a class to convert notsobots image searching capabilities
into a more general converter class
https://github.com/TrustyJAID/Trusty-cogs/blob/master/notsobot/converter.py print(match.group(1)) | 201 | en | 0.641046 |
import titration.utils.analysis as analysis
import titration.utils.constants as constants
import titration.utils.devices.serial_mock as serial_mock
import titration.utils.interfaces as interfaces
class Syringe_Pump:
def __init__(self):
self.serial = serial_mock.Serial(
port=constants.ARDUINO_P... | titration/utils/devices/syringe_pump_mock.py | 4,723 | Converts volume to cycles and ensures and checks pump level and values
cycles and direction are integers
Communicates with arduino to add HCl through pump
:param cycles: number of rising edges for the pump
:param direction: direction of pump
pull in solution check if volume to add is greater than space left pump out ... | 666 | en | 0.900069 |
# Copyright (c) 2019-2020, Manfred Moitzi
# License: MIT-License
from typing import TYPE_CHECKING, Iterable, cast, Union, List, Set
from contextlib import contextmanager
import logging
from ezdxf.lldxf import validator, const
from ezdxf.lldxf.attributes import (
DXFAttr, DXFAttributes, DefSubclass, RETURN_DEFAULT, ... | src/ezdxf/entities/dxfgroups.py | 11,294 | Groups are not allowed in block definitions, and each entity can only
reside in one group, so cloning of groups creates also new entities.
Returns ``True`` if item is in :class:`DXFGroup`. `item` has to be
a handle string or an object of type :class:`DXFEntity` or inherited.
Returns entities by standard Python indexing... | 2,866 | en | 0.823031 |
import numpy as np
import pandas as pd
from pylab import rcParams
from sklearn.metrics import mean_absolute_error, mean_squared_error
# Additional custom functions
from cases.industrial.processing import multi_automl_fit_forecast, plot_results
from fedot.core.constants import BEST_QUALITY_PRESET_NAME
from fedot.core.d... | cases/industrial/multivariate_forecasting.py | 2,600 | Additional custom functions Below is an example of multivariate time series forecasting. An example of how forecasts can be made is presented and a simple validation is given on a single block which length is equal to the length of the forecast horizon. Define forecast horizon and read dataframe Wrap time series data i... | 488 | en | 0.8607 |
"""
Source code for PyGMT modules.
"""
# pylint: disable=import-outside-toplevel
from pygmt.src.basemap import basemap
from pygmt.src.blockm import blockmean, blockmedian
from pygmt.src.coast import coast
from pygmt.src.colorbar import colorbar
from pygmt.src.config import config
from pygmt.src.contour import contour
... | pygmt/src/__init__.py | 1,300 | Source code for PyGMT modules.
pylint: disable=import-outside-toplevel "text" is an argument within "text_" | 109 | en | 0.583758 |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
from parser_base import RegexParser
import model
class RegexSemantics(object):
def __init__(self):
super(RegexSemantics, self).__init__()
self._count = 0
def START(self, ast):
re... | examples/regex/regex_parser.py | 993 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.7
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from .... | pypureclient/flasharray/FA_2_7/models/volume_snapshot_get_response.py | 5,392 | Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
Keyword args:
more_items_remaining (bool): ... | 2,102 | en | 0.698974 |
"""A fingerprint + random forest model.
Try to generate independent and identically distributed figerprint as decoy.
"""
import os
import sys
import json
import argparse
import numpy as np
from pathlib import Path
from tqdm import tqdm
import scipy.sparse as sp
from scipy.spatial import distance
from multiprocessing i... | pdbbind/props_random_forest.py | 4,767 | A fingerprint + random forest model.
Try to generate independent and identically distributed figerprint as decoy.
already converted ligand.mol2 to ligand.pdb by babel fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=512) all cluster smaller than 5 will set as cluster 0 filter None min_samples_split=10, | 313 | en | 0.686599 |
from datanator_query_python.util import mongo_util
from pymongo.collation import Collation, CollationStrength
class QueryXmdb:
def __init__(self, username=None, password=None, server=None, authSource='admin',
database='datanator', max_entries=float('inf'), verbose=True, collection_str='ecmdb',
... | datanator_query_python/query/query_xmdb.py | 2,831 | Get all entries that have concentration values
Args:
projection (dict, optional): mongodb query projection. Defaults to {'_id': 0, 'inchi': 1,'inchikey': 1, 'smiles': 1, 'name': 1}.
Returns:
(list): all results that meet the constraint.
Get metabolite's name by its inchikey
Args:
inchikey (:obj:`str`): i... | 639 | en | 0.539199 |
# Copyright (c) Facebook, Inc. and its affiliates.
import copy
import logging
import numpy as np
from typing import List, Optional, Union
import torch
from detectron2.config import configurable
from . import detection_utils as utils
from . import transforms as T
"""
This file contains the default mapping that's appl... | detectron2/data/dataset_mapper.py | 8,113 | A callable which takes a dataset dict in Detectron2 Dataset format,
and map it into a format used by the model.
This is the default callable to be used to map your dataset dict into training data.
You may need to follow it to implement your own one for customized logic,
such as a different way to read or transform ima... | 2,789 | en | 0.84747 |
#!/usr/bin/env python3.8
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import contextlib
import errno
import json
import os
import shutil
import sys
import tarfile
import tempfile
from fu... | scripts/sdk/merger/merge.py | 15,050 | Copy an entire SDK element to a given directory.
Copies a file to a given path, taking care of creating directories if
needed.
Copies a set of files to a given directory.
Verifies that two sets of files are absolutely identical and then copies
them to the output directory.
Ensures that the directory hierarchy of the gi... | 2,311 | en | 0.876273 |
import boto
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.table import Table
conn = boto.dynamodb.connect_to_region('us-west-2')
connection=boto.dynamodb2.connect_to_region('us-west-2')
users = Table.create('users', schema=[
HashKey('username'), # defaults to STRING data_type
], throughput={
... | samplescripts/create_table.py | 400 | defaults to STRING data_type | 28 | te | 0.103459 |
"""
Airflow API (Stable)
# Overview To facilitate management, Apache Airflow supports a range of REST API endpoints across its objects. This section provides an overview of the API design, methods, and supported use cases. Most of the endpoints accept `JSON` as input and return `JSON` responses. This means t... | airflow_client/test/test_dag_collection_all_of.py | 8,993 | DAGCollectionAllOf unit test stubs
Test DAGCollectionAllOf
Airflow API (Stable)
# Overview To facilitate management, Apache Airflow supports a range of REST API endpoints across its objects. This section provides an overview of the API design, methods, and supported use cases. Most of the endpoints accept `JSON` as ... | 8,464 | en | 0.839024 |
# -*- coding: utf-8 -*-
from __future__ import division, unicode_literals
from __future__ import absolute_import
from uuid import uuid1
from datetime import datetime
import pytest
import pytz
from pycoin.key.BIP32Node import BIP32Node
from transactions import Transactions
from transactions.services.daemonservice im... | tests/test_spoolex.py | 13,840 | Test :staticmethod:`check_script`.
Args;
alice (str): bitcoin address of alice, the sender
bob (str): bitcoin address of bob, the receiver
rpconn (AuthServiceProxy): JSON-RPC connection
(:class:`AuthServiceProxy` instance) to bitcoin regtest
transactions (Transactions): :class:`Transactions` in... | 1,365 | en | 0.693011 |
#!/usr/bin/python3
import time
from flask import url_for
from urllib.request import urlopen
from . util import set_original_response, set_modified_response, live_server_setup
sleep_time_for_fetch_thread = 3
# Basic test to check inscriptus is not adding return line chars, basically works etc
def test_inscriptus():
... | changedetectionio/tests/test_backend.py | 4,279 | !/usr/bin/python3 Basic test to check inscriptus is not adding return line chars, basically works etc Add our URL to the import page Do this a few times.. ensures we dont accidently set the status Give the thread time to pick it up It should report nothing found (no new 'unviewed' class) Default no password set, this s... | 1,051 | en | 0.9083 |
# -*- coding: utf-8 -*-
"""
kay.ext.gaema.urls
:Copyright: (c) 2009 Takashi Matsuo <tmatsuo@candit.jp>
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
from kay.routing import (
ViewGroup, Rule
)
view_groups = [
ViewGroup(
Rule('/login/<service>', endpoint='login',
... | kay/ext/gaema/urls.py | 839 | kay.ext.gaema.urls
:Copyright: (c) 2009 Takashi Matsuo <tmatsuo@candit.jp>
All rights reserved.
:license: BSD, see LICENSE for more details.
-*- coding: utf-8 -*- | 186 | en | 0.54642 |
"""
Asyncio using Asyncio.Task to execute three math function in parallel
"""
import asyncio
@asyncio.coroutine
def factorial(number):
f = 1
for i in range(2, number+1):
print("Asyncio.Task: Compute factorial(%s)" % (i))
yield from asyncio.sleep(1)
f *= i
print("Asyncio.Task - facto... | Chapter 4/asyncio_Task.py | 1,178 | Asyncio using Asyncio.Task to execute three math function in parallel | 69 | en | 0.627545 |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import unittest
from dataclasses import dataclass
from textwrap import dedent
from typing import Dict
from pants.engine.fs import FileContent
from pants.option.config import Config, TomlS... | src/python/pants/option/config_test.py | 7,911 | Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). Licensed under the Apache License, Version 2.0 (see LICENSE). This is used in `options_bootstrapper.py` to ignore default values when validating options. NB: string interpolation should only happen when calling _ConfigValues.get_value(). The values for _C... | 703 | en | 0.61469 |
import contextlib
import logging
from cStringIO import StringIO
from teuthology import misc
from teuthology.job_status import set_status
from teuthology.orchestra import run
log = logging.getLogger(__name__)
@contextlib.contextmanager
def syslog(ctx, config):
"""
start syslog / stop syslog on exit.
""... | teuthology/task/internal/syslog.py | 5,609 | start syslog / stop syslog on exit.
disable this whole feature if we're not going to archive the data anyway a mere reload (SIGHUP) doesn't seem to make rsyslog open the files race condition: nothing actually says rsyslog had time to flush the file fully. oh well. xfs_fsr ignore cron noise 6097 FIXME see 2523 part of... | 363 | en | 0.884214 |
#https://www.codechef.com/problems/DECINC
n = int(input())
if(n%4==0):
print(n+1)
else:
print(n-1) | CodeChef/DECINC_Decrement OR Increment.py | 106 | https://www.codechef.com/problems/DECINC | 40 | en | 0.34274 |
r"""Distributed TensorFlow with Monitored Training Session.
This implements the 1a image recognition benchmark task, see https://mlbench.readthedocs.io/en/latest/benchmark-tasks.html#a-image-classification-resnet-cifar-10
for more details
Adapted from official tutorial::
https://www.tensorflow.org/deploy/distrib... | tensorflow/imagerecognition/openmpi-cifar10-resnet20-all-reduce/main.py | 9,469 | Define graph for synchronized training.
Distributed TensorFlow with Monitored Training Session.
This implements the 1a image recognition benchmark task, see https://mlbench.readthedocs.io/en/latest/benchmark-tasks.html#a-image-classification-resnet-cifar-10
for more details
Adapted from official tutorial::
https... | 832 | en | 0.730821 |
# ===============================================================================
# Copyright 2014 Jake Ross
#
# 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/licens... | pychron/pipeline/tagging/base_tags.py | 1,157 | =============================================================================== Copyright 2014 Jake Ross 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 U... | 960 | en | 0.713752 |
import time
import types
import unittest
from unittest.mock import (
call, _Call, create_autospec, MagicMock,
Mock, ANY, _CallList, patch, PropertyMock
)
from datetime import datetime
class SomeClass(object):
def one(self, a, b):
pass
def two(self):
pass
def three(self, a=None):
... | Mark_attandance_py_selenium/py/App/Python/Lib/unittest/test/testmock/testhelpers.py | 27,816 | see mock issue 128 this is expected to fail until the issue is fixed Note: no type checking on the "self" parameter because spec as a list of strings in the mock constructor means something very different we treat a list instance as the type. we could replace builtin functions / methods with a function with *args / **k... | 806 | en | 0.905684 |
# Generated by Django 3.2.4 on 2021-08-06 15:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_alter_tag_tag_name'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='subject',
),... | blog/migrations/0003_remove_comment_subject.py | 327 | Generated by Django 3.2.4 on 2021-08-06 15:38 | 45 | en | 0.758967 |
# 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
# distribu... | src/openfermion/ops/_binary_code.py | 11,940 | The BinaryCode class provides a representation of an encoding-decoding
pair for binary vectors of different lengths, where the decoding is allowed
to be non-linear.
As the occupation number of fermionic mode is effectively binary,
a length-N vector (v) of binary number can be utilized to describe
a configuration of a ... | 5,423 | en | 0.739648 |
# Copyright 2020 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/ut/python/dataset/test_dataset_numpy_slices.py | 8,500 | Copyright 2020 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... | 640 | en | 0.808401 |
""" Bu kod MQTT den alir FireBase e atar """
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import paho.mqtt.client as mqtt
from time import sleep
import json
import sys
Fb_Coll = "color"
def main():
x = open("../ip.json")
data_ = json.load(x)
... | MyAwsomeMainCode/send_.py | 1,412 | Bu kod MQTT den alir FireBase e atar | 36 | tr | 0.368284 |
#
# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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... | samples/python/uff_ssd/utils/engine.py | 4,146 | Allocates host and device buffer for TRT engine inference.
This function is similair to the one in ../../common.py, but
converts network outputs (which are np.float32) appropriately
before writing them to Python buffer. This is needed, since
TensorRT plugins doesn't support output type description, and
in our particul... | 1,749 | en | 0.85045 |
from .imports import *
def rainbow_to_vector(r, timeformat='h'):
""" Convert Rainbow object to np.arrays
Parameters
----------
r : Rainbow object
chromatic Rainbow object to convert into array format
timeformat : str
(optional, default='hours')
The time ... | src/utils.py | 4,410 | Convert Rainbow object to pandas dataframe
Parameters
----------
r : Rainbow object
chromatic Rainbow object to convert into pandas df format
timeformat : str
(optional, default='hours')
The time format to use (seconds, minutes, hours, days etc.)
Returns
----------
pd.DataFrame
Conve... | 1,358 | en | 0.374662 |
"""
This test will initialize the display using displayio
and draw a solid red background
"""
import board
import displayio
from adafruit_st7735r import ST7735R
spi = board.SPI()
tft_cs = board.D5
tft_dc = board.D6
displayio.release_displays()
display_bus = displayio.FourWire(spi, command=tft_dc, chip_... | infra/libs-400rc2-20190512/examples/st7735r_128x160_simpletest.py | 826 | This test will initialize the display using displayio
and draw a solid red background
Make the display context | 112 | en | 0.412232 |
#!/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 wallet import RPCs.
Test rescan behavior of importaddress, importpubkey, importprivkey, and
impor... | test/functional/import-rescan.py | 9,050 | Helper for importing one key and verifying scanned transactions.
Verify that getbalance/listtransactions return expected values.
Call one key import RPC.
Test wallet import RPCs.
Test rescan behavior of importaddress, importpubkey, importprivkey, and
importmulti RPCs with different types of keys and rescan options.
I... | 2,577 | en | 0.827854 |
#
# -------------------------------------------------------------------------
# Copyright (c) 2018 Intel Corporation Intellectual Property
#
# 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... | conductor/conductor/tests/unit/api/controller/test_root.py | 1,536 | Test case for RootController /
------------------------------------------------------------------------- Copyright (c) 2018 Intel Corporation Intellectual Property 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 ... | 781 | en | 0.734668 |
from apollo.viewsets import UserViewSet
from applications.assets.viewsets import EquipmentViewSet, ServiceViewSet
from applications.business.viewsets import BusinessViewSet, BusinessMembershipViewSet
from applications.charge_list.viewsets import ChargeListViewSet, ActivityChargeViewSet, \
ActivityChargeActivityCoun... | apollo/router.py | 2,781 | Internal API Definition | 23 | en | 0.438078 |
from whey.mixin import BuilderMixin
class GettextMixin:
def build_messages(self: BuilderMixin):
from babel.messages.mofile import write_mo
from babel.messages.pofile import read_po
locales = self.pkgdir / "locales"
if self.verbose:
print(" Building messages")
for po in locales.glob("*/LC_MESSAGES/pm2h... | build_hooks.py | 925 | class SDistBuilder(GettextMixin, builder.SDistBuilder): def call_additional_hooks(self): self.build_messages() class WheelBuilder(GettextMixin, builder.WheelBuilder): def call_additional_hooks(self): self.build_messages() | 227 | en | 0.539856 |
# coding: utf-8
"""
"""
from copy import deepcopy
import datetime
import io
import json
import math
import os
import zipfile
import flask
import flask_login
import itsdangerous
import werkzeug.utils
from flask_babel import _
from . import frontend
from .. import logic
from .. import models
from .. import db
from ..... | sampledb/frontend/objects.py | 110,241 | Return all objects
coding: utf-8 ensure old links still function default objects per page TODO: ensure that advanced search does not cause exceptions TODO: error handling/logging? Ignore invalid placeholder data The form allows notations like '1.2e1' for '12', however Python can only parse these as floats The object ... | 754 | en | 0.64156 |
from decimal import Decimal, ROUND_DOWN
from time import time
def elapsed(t0=0.0):
"""get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string
"""
now = time()
dt = now - t0
dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), ... | andes/utils/time.py | 477 | get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string | 111 | en | 0.616296 |
# Copyright 2019 Splunk, Inc.
#
# Use of this source code is governed by a BSD-2-clause-style
# license that can be found in the LICENSE-BSD2 file or at
# https://opensource.org/licenses/BSD-2-Clause
from jinja2 import Environment
from .sendmessage import *
from .splunkutils import *
from .timeutils import *
import ... | tests/test_aruba.py | 3,309 | Copyright 2019 Splunk, Inc. Use of this source code is governed by a BSD-2-clause-style license that can be found in the LICENSE-BSD2 file or at https://opensource.org/licenses/BSD-2-Clause time format for Apr 5 22:51:54 2021 <187>{{ arubadate }} {{ host }} authmgr[4130]: <124198> <4130> <ERRS> <{{ host }} 10.10.10.10... | 1,086 | en | 0.588242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.