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
# layout.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # A...
tracking/layout.py
5,782
A Layout manages the static information about the game board. Coordinates are flipped from the input format to the (x,y) convention here The shape of the maze. Each character represents a different type of object. % - Wall . - Food o - Capsule G - Ghost P - Pacman Other characters are ignored. layout.py ------...
961
en
0.846475
# Connection libraries import os import shutil import re # Class create project class Create: def __init__(self, path): self.path = path # Create project def createProject(self, name): if not os.path.isdir(self.path + name): shutil.copytree("launcher/shablon/", self.path + name) else: n, a = os.listdir...
create.py
550
Connection libraries Class create project Create project Delete project
71
en
0.748998
import matplotlib.pyplot as plt, streamlit as st from typing import Iterable, Union from sklearn.metrics import classification_report from sklearn.metrics import roc_curve, auc, RocCurveDisplay def train(estimator: object, X: Iterable[Union[int, float]], y: Iterable): """ Train custom classifier model...
ml.py
1,912
Predict with custom classifier model. Parameters: estimator: Fitted estimator. X: Input test data. Returns: Predicted labels. Predict with custom classifier model. Parameters: estimator: Fitted estimator. X: Input test data. y: Labels for test data. Returns: Predicted labels. Predict wit...
684
en
0.343033
""" CAR CONFIG This file is read by your car application's manage.py script to change the car performance. EXMAPLE ----------- import dk cfg = dk.load_config(config_path='~/mycar/config.py') print(cfg.CAMERA_RESOLUTION) """ import os #PATHS CAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__)) ...
donkeycar/templates/cfg_basic.py
5,773
CAR CONFIG This file is read by your car application's manage.py script to change the car performance. EXMAPLE ----------- import dk cfg = dk.load_config(config_path='~/mycar/config.py') print(cfg.CAMERA_RESOLUTION) PATHSVEHICLECAMERA (PICAM|WEBCAM|CVCAM|CSIC|V4L|D435|MOCK|IMAGE_LIST) default RGB=3, make 1 for mon...
3,485
en
0.779375
# -*- coding: utf-8 -*- """ # Author : Camey # DateTime : 2022/3/12 8:49 下午 # Description : """
my_work/config/__init__.py
108
# Author : Camey # DateTime : 2022/3/12 8:49 下午 # Description : -*- coding: utf-8 -*-
96
en
0.329278
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ A module that provides algorithms for performing linear fit between sets of 2D points. :Authors: Mihai Cara, Warren Hack :License: :doc:`../LICENSE` """ import logging import numbers import numpy as np from .linalg import inv from . import __versio...
tweakwcs/linearfit.py
26,996
An error class used to report when there are not enough points to find parameters of a linear transformation. An error class used to report when a singular matrix is encountered. Create an affine transformation matrix (2x2) from the provided rotation angle(s) and scale(s): .. math:: M = \begin{bmatrix} ...
10,890
en
0.744401
''' @Date: 2019-08-22 20:40:54 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors: ywyz @LastEditTime: 2019-08-22 20:48:24 ''' years, months = eval(input("Enter years and months: ")) if (months == 1 or months == 3 or months == 5 or months == 7 or months == 8 or months == 10 or mon...
Exercise04/4-11.py
725
@Date: 2019-08-22 20:40:54 @Author: ywyz @LastModifiedBy: ywyz @Github: https://github.com/ywyz @LastEditors: ywyz @LastEditTime: 2019-08-22 20:48:24
149
en
0.196449
#!/usr/bin/env python2 # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
arp/arp_infer.py
22,884
!/usr/bin/env python2 Copyright (c) 2017-present, Facebook, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or ag...
2,773
en
0.605303
#!/usr/bin/python3 # Helper script for the transactions method that can read the log file # and use it to detect and recover the state to one of the transactions # at which the script had previously been restarted. import sys import os import re import json import subprocess import codecs import argparse import temp...
recover_state_from_log.py
4,375
!/usr/bin/python3 Helper script for the transactions method that can read the log file and use it to detect and recover the state to one of the transactions at which the script had previously been restarted.
208
en
0.95829
# Generated by Django 3.1.7 on 2021-07-12 13:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contact', '0002_feedback_phone'), ] operations = [ migrations.RenameField( model_name='feedback', old_name='name', ...
OmegaErp/contact/migrations/0003_auto_20210712_1539.py
360
Generated by Django 3.1.7 on 2021-07-12 13:39
45
en
0.707983
"""Plugin ========= The fixtures provided by pytest-kivy. """ import pytest import weakref from typing import Tuple, Type, Optional, Callable import gc import logging from os import environ from pytest_kivy.app import AsyncUnitApp __all__ = ('trio_kivy_app', 'asyncio_kivy_app', 'async_kivy_app') #: NOTE: Kivy canno...
pytest_kivy/plugin.py
5,561
Plugin ========= The fixtures provided by pytest-kivy. : NOTE: Kivy cannot be imported before or while the plugin is imported or configured as that leads to pytest issues.
173
en
0.913644
"""Test data purging.""" from datetime import datetime, timedelta import json from unittest.mock import patch from homeassistant.components import recorder from homeassistant.components.recorder.const import DATA_INSTANCE from homeassistant.components.recorder.models import Events, RecorderRuns, States from homeassist...
tests/components/recorder/test_purge.py
7,933
Add a few events for testing. Add a few recorder_runs for testing. Add multiple states to the db for testing. Test purge method. Test deleting old events. Test deleting old recorder runs keeps current run. Test deleting old states. Test data purging. make sure we start with 6 states run purge_old_data() run purge_old...
813
en
0.898183
"""An abstract class for entities.""" from abc import ABC import asyncio from datetime import datetime, timedelta import functools as ft import logging from timeit import default_timer as timer from typing import Any, Awaitable, Dict, Iterable, List, Optional from homeassistant.config import DATA_CUSTOMIZE from homeas...
homeassistant/helpers/entity.py
24,720
An abstract class for Home Assistant entities. An abstract class for entities that can be turned on and off. Return the comparison. Return the representation. Write the state to the state machine. Abort adding an entity to a platform. Start adding an entity to a platform. Return True if unable to access real state of t...
4,714
en
0.822937
# from https://stackoverflow.com/questions/8032642/how-to-obtain-image-size-using-standard-python-class-without-using-external-lib import struct import imghdr def get_image_size(fname): """Determine the image type of fhandle and return its size. from draco""" with open(fname, "rb") as fhandle: ...
mdpdfbook/mdpdf/image.py
1,508
Determine the image type of fhandle and return its size. from draco from https://stackoverflow.com/questions/8032642/how-to-obtain-image-size-using-standard-python-class-without-using-external-lib Read 0xff next We are at a SOFn block Skip `precision' byte. IGNORE:W0703
273
en
0.776093
# Copyright 2021 Zeppelin Bend Pty Ltd # # 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 https://mozilla.org/MPL/2.0/. __all__ = ["get_upstream_end_to_tns"] from typing import List, Tuple, Typ...
src/pp_creators/utils.py
1,120
Copyright 2021 Zeppelin Bend Pty Ltd 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 https://mozilla.org/MPL/2.0/. TODO: How to account for the fact you can have phases with different directions??
315
en
0.9192
# coding: utf-8 # Modified Work: Copyright (c) 2018, 2022, 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...
src/oci/_vendor/requests/models.py
34,762
The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Instances are generated from a :class:`Request <Request>` object, and should not be instantiated manually; doing so may produce undesirable effects. Usage:: >>> import requests >>> req...
12,247
en
0.827411
#!/usr/bin/env python # -*- coding=utf8 -*- """ # Author: achao # File Name: weight_init.py # Description: """ import copy import math import warnings import numpy as np import torch import torch.nn as nn from torch import Tensor from deep3dmap.core.utils import Registry, build_from_cfg, get_logger, print_log INITIA...
deep3dmap/core/utils/weight_init.py
26,051
Initialize module parameters with constant values. Args: val (int | float): the value to fill the weights in the module with bias (int | float): the value to fill the bias. Defaults to 0. bias_prob (float, optional): the probability for bias initialization. Defaults to None. layer (str | list[s...
9,397
en
0.551292
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The minc module provides classes for interfacing with the `MINC <http://www.bic.mni.mcgill.ca/ServicesSoftware/MINC>`_ command line tools. This module was written to work with MI...
nipype/interfaces/minc/minc.py
111,220
Average a number of MINC files. Examples -------- >>> from nipype.interfaces.minc import Average >>> from nipype.interfaces.minc.testdata import nonempty_minc_data >>> files = [nonempty_minc_data(i) for i in range(3)] >>> average = Average(input_files=files, output_file='/tmp/tmp.mnc') >>> average.run() # doctest: +...
18,815
en
0.583231
""" A file to contain specific logic to handle version upgrades in Kolibri. """ from shutil import rmtree from django.conf import settings from kolibri.core.upgrade import version_upgrade # Before 0.15 we copied static files to the KOLIBRI_HOME directory. # After 0.15 we read them directly from their source directo...
kolibri/core/device/upgrade.py
443
A file to contain specific logic to handle version upgrades in Kolibri. Before 0.15 we copied static files to the KOLIBRI_HOME directory. After 0.15 we read them directly from their source directories.
203
en
0.850235
""" Copyright 2020 The OneFlow 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 applicable law or agr...
python/oneflow/test/graph/test_graph_optim_lamb.py
5,311
Copyright 2020 The OneFlow 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 applicable law or agreed ...
717
en
0.842175
#- # Copyright (c) 2016 Michael Roe # All rights reserved. # # This software was developed by SRI International and the University of # Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 # ("CTSRD"), as part of the DARPA CRASH research programme. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BER...
tests/cp2/test_cp2_c0_sc.py
1,460
- Copyright (c) 2016 Michael Roe All rights reserved. This software was developed by SRI International and the University of Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237 ("CTSRD"), as part of the DARPA CRASH research programme. @BERI_LICENSE_HEADER_START@ Licensed to BERI Open Systems C.I.C....
1,079
en
0.850213
from graphql import Undefined from .mountedtype import MountedType from .structures import NonNull from .utils import get_type class InputField(MountedType): """ Makes a field available on an ObjectType in the GraphQL schema. Any type can be mounted as a Input Field except Interface and Union: - Obj...
graphene/types/inputfield.py
2,617
Makes a field available on an ObjectType in the GraphQL schema. Any type can be mounted as a Input Field except Interface and Union: - Object Type - Scalar Type - Enum Input object types also can't have arguments on their input fields, unlike regular ``graphene.Field``. All class attributes of ``graphene.InputObject...
1,684
en
0.758379
# -*- coding: utf-8 -*- from cms.exceptions import CMSDeprecationWarning from django.conf import settings from patch import post_patch, post_patch_check, pre_patch import warnings def patch_settings(): """Merge settings with global cms settings, so all required attributes will exist. Never override, just app...
cms/conf/__init__.py
1,185
Merge settings with global cms settings, so all required attributes will exist. Never override, just append non existing settings. Also check for setting inconsistencies if settings.DEBUG -*- coding: utf-8 -*- patch settings merge with global cms settings check if settings are correct, call this only if debugging is...
328
en
0.788147
#!/usr/bin/env py.test # -*- coding: utf-8 -*- __author__ = "Varun Nayyar <nayyarv@gmail.com>" import numpy as np import pytest import NN.layerversions.layers4 as layer def test_fc(): l1 = layer.FullyConnected(5, 10) x = np.ones((100, 5)) y, c = l1.forward(x) assert y.shape == (100, 10) assert ...
tests/test_layers4.py
1,460
!/usr/bin/env py.test -*- coding: utf-8 -*-
44
en
0.300577
import unittest class IntcodeComputer(): OP_ADD = 1 OP_MULTIPLY = 2 OP_INPUT = 3 OP_OUTPUT = 4 OP_JUMP_TRUE = 5 OP_JUMP_FALSE = 6 OP_LESS_THAN = 7 OP_EQUALS = 8 OP_MOD_REL = 9 OP_HALT = 99 PARAM_MODE_POS = '0' PARAM_MODE_IMD = '1' PARAM_MODE_REL...
AoC 2019/intcode.py
6,642
Reverse of the first three chars integer of the last two chars
62
en
0.847323
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
sdk/python/pulumi_azure_native/documentdb/v20191212/list_database_account_keys.py
4,465
The access keys for the given database account. The access keys for the given database account. :param str account_name: Cosmos DB database account name. :param str resource_group_name: Name of an Azure resource group. Base 64 encoded value of the primary read-write key. Base 64 encoded value of the primary read-only...
634
en
0.840372
import pytest import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal, assert_equal) from nose.tools import assert_raises from pystruct.models import NodeTypeEdgeFeatureGraphCRF, EdgeFeatureGraphCRF from pystruct.inference.linear_prog...
pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py
36,982
Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF how many node type?how many labels per node type?how many features per node type?how many...
8,711
en
0.571907
from __future__ import print_function, absolute_import import importlib import logging import os from argparse import ArgumentParser from six import string_types from adr.formatter import all_formatters from .errors import MissingDataError log = logging.getLogger('adr') here = os.path.abspath(os.path.dirname(__file...
adr/recipe.py
3,156
Given a recipe, calls the appropriate query and returns the result. The provided recipe name is used to make a call to the modules. :param str recipe: name of the recipe to be run. :param list args: remainder arguments that were unparsed. :param Configuration config: config object. :returns: string end of day
314
en
0.736307
import bbi import clodius.tiles.format as hgfo import functools as ft import logging import numpy as np import pandas as pd import re from concurrent.futures import ThreadPoolExecutor MAX_THREADS = 4 TILE_SIZE = 1024 logger = logging.getLogger(__name__) aggregation_modes = {} aggregation_modes['mean'] = {'name': 'M...
clodius/tiles/bigwig.py
10,577
Get a list of chromosome sizes from this [presumably] bigwig file. Parameters: ----------- filename: string The filename of the bigwig file Returns ------- chromsizes: [(name:string, size:int), ...] An ordered list of chromosome names and sizes TODO: replace this with negspy Also, return NaNs from any missin...
2,031
en
0.691378
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-02-22 09:00 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('waldur_jira', '0011_unique_together'), ] operations = [ migrations.AlterFie...
src/waldur_jira/migrations/0012_backend_id_null.py
810
-*- coding: utf-8 -*- Generated by Django 1.11.7 on 2018-02-22 09:00
68
en
0.612917
#!/usr/bin/python # Copyright (c) 2014 Wladmir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that...
share/seeds/generate-seeds.py
4,298
Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that is passed as an argument: nodes_main.txt nodes_test.txt These files must consist of lines in the format <ip> <ip>:<port> [<ipv6>] [<ipv6>]:<port> <onion>.onion 0xDDBBC...
965
en
0.623813
import law import luigi import os from subprocess import PIPE from law.util import interruptable_popen from framework import Task class CROWNBuild(Task): """ Gather and compile CROWN with the given configuration """ # configuration variables channels = luigi.Parameter() shifts = luigi.Param...
processor/tasks/CROWNBuild.py
5,702
Gather and compile CROWN with the given configuration configuration variables get output file path find crown create build directory same for the install directory set environment variables checking cmake path actual payload: run CROWN build step if successful save Herwig-cache and run-file as tar.gz TODO Create Tarb...
351
en
0.599292
#!/usr/bin/env python # encoding: utf-8 class MeanVariance(object): def __init__(self): self.n = 0 self.K = 0.0 self.ex0 = 0.0 self.ex2 = 0.0 def add_variable(self, x): if self.n == 0: self.K = x self.n += 1 delta = x - self.K self.e...
src/main/python/mean-variance.py
729
!/usr/bin/env python encoding: utf-8
36
en
0.34219
#!/usr/bin/python3 # -*- coding:utf-8 -*- # FORKED FROM https://github.com/floydawong/LuaFormat # Copyright (c) 2017 Floyda (floyda@163.com) # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software w...
lua-format.py
17,873
!/usr/bin/python3 -*- coding:utf-8 -*- FORKED FROM https://github.com/floydawong/LuaFormat Copyright (c) 2017 Floyda (floyda@163.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restric...
2,006
en
0.625816
""" 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 use this ...
metron-deployment/packaging/ambari/metron-mpack/src/main/resources/common-services/METRON/CURRENT/package/scripts/rest_master.py
3,848
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 use this file...
917
en
0.880309
## Ao arrumar os NCM nos registros nãoesteaindaC180 e C190 pode ocorrer duplicidade ## nos conjuntos de campos de acordo com o manual. ## No caso preciso juntar todos os registros com estas caracteristicas import helper def exec(conexao): cursor = conexao.cursor() print("RULE 02 - Inicializando",end=' ') ...
sped_correcao/rule02.py
5,083
Ao arrumar os NCM nos registros nãoesteaindaC180 e C190 pode ocorrer duplicidade nos conjuntos de campos de acordo com o manual. No caso preciso juntar todos os registros com estas caracteristicasrselect.append(rselect[len(rselect)-1] + 1000) verifica se tem C190 repetido em cada C010 se não tiver repetido, continua a ...
716
pt
0.959265
import argparse from functools import partial import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize def read_args(): '''Reads command line arguments. Returns: Parsed arguments.''' parser = argparse.ArgumentParser() ...
orbitdeterminator/kep_determination/ellipse_fit.py
6,629
Converts a list of cartesian coordinates into polar ones. Arguments: points: The list of points in the format [x,y]. Returns: A list of polar coordinates in the format [radius,angle]. Finds coordinates of points in a plane wrt a basis. Given a list of points in a plane, and a basis of the plane, this function return...
2,989
en
0.798229
from os import environ from os.path import join, dirname # Third party imports from flask_compress import Compress class Config: """ Common configurations """ # private variable used by Flask to secure/encrypt session cookies SECRET_KEY = environ['SECRET_KEY'] # get the root url and concant...
config.py
4,396
Common configurations Development configurations Production configurations Testing configurations Multiple app configurations Third party imports private variable used by Flask to secure/encrypt session cookies get the root url and concantenate it with the client secrets file test out login and registration in develo...
2,045
en
0.73698
"""Module with functions around testing. You can run tests including doctest with generating coverage, you can generate tests from readme or you can configure tests in conftest with single call.""" from mypythontools_cicd.tests.tests_internal import ( add_readme_tests, deactivate_test_settings, default_tes...
mypythontools_cicd/tests/__init__.py
532
Module with functions around testing. You can run tests including doctest with generating coverage, you can generate tests from readme or you can configure tests in conftest with single call.
191
en
0.92687
# -*- coding: utf-8 -*- import tkinter as tk from tkinter import messagebox import ipaddress from model import RecvTcpThread, RecvUdpThread, RecvMonitorThread, HachiUtil from controller import LogController # ================================= # == 定数 # ================================= DEF_PROTO = 1 # 0:TCP 1:UDP D...
controller/RxController.py
4,992
受信モニター情報クラス 受信パラメータ情報クラス スレッド間で値を共有するためのクラス 受信パラメータチェック パケット受信監視スレッド TCPパケット送信スレッド UDPパケット受信スレッド -*- coding: utf-8 -*- ================================= == 定数 ================================= 0:TCP 1:UDP ================================= == 公開クラス ================================= "bps換算"動的更新 スレッド変数 入力パラメータチェッ...
511
ja
0.919497
# Copyright 2014, Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain # rights in this software. from behave import * import numpy import toyplot import testing @given(u'a sample plot, the plot can be rendered with a dashed line style.') d...
features/steps/style.py
508
Copyright 2014, Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software.
167
en
0.84275
# Copyright 2020 The TensorFlow 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 applica...
tensorflow/python/grappler/arithmetic_optimizer_test.py
1,757
Tests for Grappler Arithmetic Optimizer. Copyright 2020 The TensorFlow 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 U...
720
en
0.82264
from .DtnAbstractParser import DtnAbstractParser from pydantic import confloat, PositiveFloat from typing import Optional class DtnFileBroadcasterParser(DtnAbstractParser): """ Validator for a file generator """ # Data Tyoe data_type: str # Start time of the file transmission (in simulation time) ...
simulator/parsers/DtnFileBroadcasterParser.py
785
Validator for a file generator Data Tyoe Start time of the file transmission (in simulation time) Bundle size in bits File size in [bits] Bundle Time-to-live (TTL) in [sec] Data criticality. If True, then network will be flooded with this data How many times to send the file How long in [sec] to wait between sending...
336
en
0.880581
# this file is only for presentation of the swallow fish game # http://www.4399.com/flash/201247_4.htm from pyautogui import press, keyDown, keyUp from time import time import serialPart # u = 'up' # d = 'down' # l = 'left' # r = 'right' u = 'w' d = 's' l = 'a' r = 'd' def key_unit(key, p...
simKeyControlGame_temp2.py
5,027
this file is only for presentation of the swallow fish game http://www.4399.com/flash/201247_4.htm u = 'up' d = 'down' l = 'left' r = 'right' start = time() mind that these them selves take time also print('cannot be too short',time()) print(time()-start) in second adjust this period(second) for better game control tod...
1,108
en
0.488682
#!/usr/bin/env python3 ''' A series of test for PyKMCFile class. ''' import sys import os import subprocess import kmer_utils import init_sys_path import py_kmc_api as pka import pytest if not init_sys_path.is_windows(): import resource @pytest.fixture(scope="module", autouse=True) def create_kmc_db(): ''' ...
tests/py_kmc_api/test_py_kmc_file.py
6,881
Simple k-mer counting routine. Generate k-mers that are not present in the database. :kmers: existing k-mers :kmer_len: length of k-mers Open kmc database for listing and check if opened sucessfully. Open kmc database for random access and check if opened sucessfully. Runs kmc. Save reads from input to file named ...
1,004
en
0.830258
import tensorflow as tf def leakyrelu(x, leak=0.01): """ leakyrelu激活函数 Args: x (Tensor): input leak (int): x<0时的斜率 Returns: Tensor """ f1 = 0.5 * (1 + leak) f2 = 0.5 * (1 - leak) return f1 * x + f2 * tf.abs(x)
algorithm/BST/leakyrelu.py
290
leakyrelu激活函数 Args: x (Tensor): input leak (int): x<0时的斜率 Returns: Tensor
86
ja
0.214631
from unittest import TestCase from generative_playground.codec.hypergraph_grammar import HypergraphGrammar from generative_playground.molecules.models.conditional_probability_model import CondtionalProbabilityModel from generative_playground.models.pg_runner import PolicyGradientRunner class TestStart(TestCase): de...
src/tests/runner_tests.py
3,766
'hyper_grammar.pickle' lr_schedule=shifted_cosine_schedule, 'rnn_graph', 'attention', lambda x: toothy_exp_schedule(x, scale=num_batches), 'hyper_grammar.pickle' lr_schedule=shifted_cosine_schedule, 'rnn_graph', 'attention', lambda x: toothy_exp_schedule(x, scale=num_batches),
277
en
0.452611
import glob print(glob.glob("./src/ibmaemagic/sdk/*")) # import sys # sys.path.append("./src/ibmaemagic/magic/") # from analytic_magic_client import AnalyticMagicClient # import analytic_engine_client.AnalyticEngineClient # from ibmaemagic.magic.analytic_magic_client import AnalyticMagicClient # from ibmaemagic.sdk.a...
tests/sdk/foo.py
525
import sys sys.path.append("./src/ibmaemagic/magic/") from analytic_magic_client import AnalyticMagicClient import analytic_engine_client.AnalyticEngineClient from ibmaemagic.magic.analytic_magic_client import AnalyticMagicClient from ibmaemagic.sdk.analytic_engine_client import AnalyticEngineClient from ibmaemagic imp...
344
en
0.472904
from pyinfra import host from pyinfra.modules import git, pip, server # Ensure the state of git repositories git.repo( {'Clone pyinfra repository'}, 'git@github.com:Fizzadar/pyinfra', host.data.app_dir, branch='develop', ssh_keyscan=True, sudo=True, # Carry SSH agent details w/sudo pre...
examples/python_app.py
944
Ensure the state of git repositories Carry SSH agent details w/sudo Manage pip packages Use operation meta to affect the deploy Create a virtualenv and manage pip within it
172
en
0.639418
# Generated by Django 3.0.3 on 2021-03-05 03:35 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='User', f...
app/core/migrations/0001_initial.py
1,700
Generated by Django 3.0.3 on 2021-03-05 03:35
45
en
0.70765
# -*- coding: utf-8 -*- from dfa import * """ Created on Mon Apr 1 09:50:10 2019 @author: Savio """ #Example of a simple DFA #DFA only accepts odd-sized string states = {0, 1} alphabet = {'0','1'} transition = { (0, '0'): 1, (0, '1'): 1, (1, '0'): 0, (1, '1'): 0, } start_state = 0 accept_s...
main.py
493
-*- coding: utf-8 -*-Example of a simple DFADFA only accepts odd-sized stringAcceptstring= list('1010') Reject
110
en
0.516756
from amaranth import * from amaranth.asserts import * from amaranth.utils import log2_int from amaranth_soc import wishbone from amaranth_soc.memory import MemoryMap from amaranth_soc.periph import ConstantMap from . import Peripheral from ..cores import litedram __all__ = ["WritebackCache", "SDRAMPeripheral"] c...
lambdasoc/periph/sdram.py
14,493
SDRAM controller peripheral. Parameters ---------- core : :class:`litedram.Core` LiteDRAM core. cache_size : int Cache size, in bytes. cache_dirty_init : boot Initialize cache as dirty. Defaults to `False`. Write-back cache. A write-back cache designed to bridge the SoC interconnect to LiteDRAM. Paramete...
918
en
0.440515
# -*- coding: utf-8 -*- import json import logging import re from lncrawl.core.crawler import Crawler logger = logging.getLogger(__name__) search_url = 'https://www.novelall.com/search/?name=%s' class NovelAllCrawler(Crawler): base_url = 'https://www.novelall.com/' def search_novel(self, query): que...
sources/novelall.py
2,856
Download body of a single chapter and return as clean html format. Get novel title, autor, cover etc -*- coding: utf-8 -*- end for end def end if end for end for end if end for end def end def end class
204
en
0.766613
import requests import ratelimit from arcas.tools import Api from .api_key import api_key from arcas.tools import APIError class Ieee(Api): """ API argument is 'ieee'. """ def __init__(self): self.standard = 'https://ieeexploreapi.ieee.org/api/v1/search/articles?' self.key_api = api_...
src/arcas/IEEE/main.py
4,026
API argument is 'ieee'. Creates the search url, combining the standard url and various search parameters. Request from an API and returns response. Parsing the xml file A function which takes a dictionary with structure of the IEEE results and transform it to a standardized format.
282
en
0.735623
# # Copyright 2015-2019, Institute for Systems Biology # # 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 ...
scripts/bigquery/cohort_table_utils.py
5,794
Copyright 2015-2019, Institute for Systems Biology 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 writ...
681
en
0.850626
#!/usr/bin/env python3 import datetime import os import signal import subprocess import sys import traceback from multiprocessing import Process import cereal.messaging as messaging import selfdrive.crash as crash from common.basedir import BASEDIR from common.params import Params, ParamKeyType from common.text_window...
selfdrive/manager/manager.py
6,417
!/usr/bin/env python3 update system time from panda HKG set unset params is this dashcam? Make sure we can create files with 777 permissions Create folders needed for msgq set version params set dongle id Needed for swaglog save boot logsubprocess.call("./bootlog", cwd=os.path.join(BASEDIR, "selfdrive/loggerd")) trigge...
576
en
0.740721
from __future__ import print_function, division import _init_paths import math import os.path as osp from shapely.geometry import Polygon from gen_data import get_cent from bbox_util import is_rect import argparse import sys from model.config import cfg def parse_args(): """ Parse input arguments """ parser =...
tools/eval_frame.py
6,491
:param results: :param gts: :param point_dis: :param rect_label: use rectangle or not :return right_num, error_num, mid_num Parse input arguments for i in range(len(info)): info[i] = max(0, info[i]) only use rectangle gt if is_gt: print(pts) print(x1, y1, x2, y2) frame = frame.convex_hull print(a1, a2) print(...
1,194
en
0.316575
from twisted.protocols import stateful from twisted.internet import reactor from twisted.internet.protocol import Factory, Protocol from twisted.internet.endpoints import TCP4ClientEndpoint from datetime import datetime import sys import struct import zlib import time import threading import Queue import uuid import...
AndroidGatewayPlugin/Testdriver/AndroidConnector/ammo/AndroidConnector.py
15,714
initial state receives the headerlittle-endian byte order for nowTODO: signal the authentication loop so it knows we disconnected tooArgument False tells the reactor that it's not on themain thread, so it doesn't attempt to register signalhandlers (which doesn't work on other threads)don't block if queue is empty; rais...
680
en
0.865899
# Generated by Django 3.1.8 on 2021-05-20 18:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0020_auto_20210415_0831'), ] operations = [ migrations.AddField( model_name='candidateusermodel', name='org...
users/migrations/0021_candidateusermodel_organization.py
455
Generated by Django 3.1.8 on 2021-05-20 18:22
45
en
0.626734
import math import numpy as np import pytest import tensorflow as tf import kerastuner as kt from kerastuner.engine import hyperparameters as hp_module from kerastuner.engine import trial as trial_module from kerastuner.tuners import bayesian as bo_module @pytest.fixture(scope="function") def tmp_dir(tmpdir_factory...
tests/kerastuner/tuners/bayesian_test.py
11,504
Make examples with high 'a' and high score. Make examples with low 'a' and low score Assert that the oracle suggests hps it thinks will maximize. Populate initial trials. Update the space. Make a new trial, it should have b set. Populate initial trials. Check that oracle respects the `step` param. Maximum at a=-1, b=1,...
512
en
0.898495
import abc from ... import errors, utils from ...tl import types class ChatGetter(abc.ABC): """ Helper base class that introduces the `chat`, `input_chat` and `chat_id` properties and `get_chat` and `get_input_chat` methods. Subclasses **must** have the following private members: `_chat`, `_...
telethon/tl/custom/chatgetter.py
4,047
Helper base class that introduces the `chat`, `input_chat` and `chat_id` properties and `get_chat` and `get_input_chat` methods. Subclasses **must** have the following private members: `_chat`, `_input_chat`, `_chat_peer`, `_broadcast` and `_client`. As an end user, you should not worry about this. Returns the :tl:`Us...
1,325
en
0.851309
# -*- coding: utf-8 -*- import json import os import os.path as osp import time from pprint import pprint import random import glob import numpy as np import cv2 def generate_db(dataPath='./thor_DB.json', categoryPath='./categories.json', \ newDataPath='./thor_DB_msdn.json'): # msdn style # ...
data_preprocessing.py
15,992
-*- coding: utf-8 -*- msdn style GUI 툴로 생성한 ai2thor DB를 msdn 폼으로 재구성하여 저장됨 DB = json.load(f) 물체가 없으면 넘김 float 형태 [마이너스는 없음] 정면 int 형태 오른쪽 뒤 왼쪽 global idx -> local idx 'off_state':categories['off_state'][obj['off_state']]}) index는 string label로 변경 index가 안맞을 수 있음. 확인요망 relation...!!!! global relation...!!!! object, rel,...
1,288
ko
0.87825
#!/usr/bin/env python import numpy as np import sys sys.path.append("../ar/") import fastopc, time import functionLib as lib import micStream nStrips = 16 lStrip = 64 client = fastopc.FastOPC('localhost:7890') pixels = lib.Pixels(nStrips, lStrip, 0) theoStrip = np.zeros([lStrip, 3]) stream = micStream.Stream(fps...
deprecated/ledWall/ar_bassThumpAllSame.py
991
!/usr/bin/env pythonprint(displayPower * colorWheel[frameNumEff])
65
en
0.161254
# Polygraph (release 0.1) # Signature generation algorithms for polymorphic worms # # Copyright (c) 2004-2005, Intel Corporation # All Rights Reserved # # This software is distributed under the terms of the Eclipse Public # License, Version 1.0 which can be found in the file named LICENSE. # ANY ...
polygraph/sig_gen/sig_gen.py
3,080
Abstract signature class. Abstract class for signature generation factories. Estimate false positive rate of a single-token signature. Estimates using the 'tokensplit' and trace-modeling methods, and returns the higher (most pessimistic of the two). Note that both of these estimates are strictly equal to or higher tha...
1,153
en
0.842408
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2018, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## import json impor...
pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/tests/test_table_put.py
5,809
This class will add new collation under schema node. This function will fetch added table under schema node. pgAdmin 4 - PostgreSQL Tools Copyright (C) 2013 - 2018, The pgAdmin Development Team This software is released under the PostgreSQL Licence Fetching default URL for table node. Disconnect the database
311
en
0.589055
#!/usr/bin/env python3 import pytest import shutil import sys import os import logging from datetime import datetime from src.dependency import check_dependencies from src.exif import Exif from src.phockup import Phockup os.chdir(os.path.dirname(__file__)) def test_check_dependencies(mocker): mocker.patch('shut...
tests/test_phockup.py
14,491
!/usr/bin/env python3 Assume no errors == skip XMP file
55
en
0.52252
# Copyright 2018 The TensorFlow 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 applica...
models/experimental/distribution_strategy/imagenet_input_keras.py
5,548
Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The validation data is in ...
2,094
en
0.819791
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
torchmetrics/functional/retrieval/fall_out.py
2,528
Computes the Fall-out (for information retrieval), as explained in `IR Fall-out`_ Fall-out is the fraction of non-relevant documents retrieved among all the non-relevant documents. ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, ``0`` is returned. ``targe...
1,717
en
0.772739
""" Views for the web service """ import os import json import urllib.parse from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseBadRequest from django.http import HttpResponse from django.urls import reverse import requests from django.views.decorator...
webserver/pkgpkr/webservice/views.py
11,933
Return about info arguments: :request: GET HTTP request returns: Rendered about page GitHub redirect here, then retrieves token for API arguments: :request: GET HTTP request returns: Redirects to index Return landing page arguments: :request: GET HTTP request returns: Rendered home (index)...
2,809
en
0.68716
# Alacritty config options # Antonio Sarosi # December 10, 2020 from typing import List, Dict, Any from collections.abc import Mapping from pathlib import Path from sys import stderr import yaml import log class ConfigError(Exception): def __init__(self, message='Error applying configuration'): super()._...
src/alacritty.py
10,535
Alacritty config options Antonio Sarosi December 10, 2020
57
en
0.193457
#!/usr/bin/python """ This script runs a convergence study for solid elements """ #from subprocess import call import os import pylab import numpy import re # Calculix solid element types with their cgx counterparts. #~ eltyps={"C3D8":"he8", #~ "C3D4":"te4", #~ "C3D10":"te10"} eltyps={"C3D8":"he8", "C3D8R"...
Elements/Solid/solid-conv.py
2,428
!/usr/bin/pythonfrom subprocess import call Calculix solid element types with their cgx counterparts.~ eltyps={"C3D8":"he8",~ "C3D4":"te4",~ "C3D10":"te10"}elsizes=[500,250,100,50,25,10,5] read the template fbd file loop over element types open results summary file loop over element sizes modify solid.fbd and write out...
646
en
0.705268
from textattack.shared.utils import default_class_repr from textattack.constraints.pre_transformation import PreTransformationConstraint from textattack.shared.validators import transformation_consists_of_word_swaps import nltk class StopwordModification(PreTransformationConstraint): """ A constraint disallow...
textattack/constraints/pre_transformation/stopword_modification.py
1,317
A constraint disallowing the modification of stopwords Returns the word indices in ``current_text`` which are able to be modified. The stopword constraint only is concerned with word swaps since paraphrasing phrases containing stopwords is OK. Args: transformation: The ``Transformation`` to check compatibility wit...
322
en
0.862794
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from bw2data import mapping, Database, databases from ..units import normalize_units as normalize_units_function from ..errors import StrategyError from ..utils import activity_hash, DEFAULT_FIELDS from copy import deep...
bw2io/strategies/generic.py
7,612
Add database name to datasets Assign only product as reference product. Skips datasets that already have a reference product or no production exchanges. Production exchanges must have a ``name`` and an amount. Will replace the following activity fields, if not already specified: * 'name' - name of reference product ...
1,649
en
0.772076
# Generated by h2py from \mssdk\include\winnt.h APPLICATION_ERROR_MASK = 536870912 ERROR_SEVERITY_SUCCESS = 0 ERROR_SEVERITY_INFORMATIONAL = 1073741824 ERROR_SEVERITY_WARNING = -2147483648 ERROR_SEVERITY_ERROR = -1073741824 MINCHAR = 128 MAXCHAR = 127 MINSHORT = 32768 MAXSHORT = 32767 MINLONG = -2147483648 MAXLONG = 2...
env/Lib/site-packages/win32/winnt.py
38,419
Generated by h2py from \mssdk\include\winnt.h Included from pshpack4.h Included from poppack.h ACE types ACE inheritance flags Token types TOKEN_INFORMATION_CLASS, used with Get/SetTokenInformation Included from string.h dispositions returned from RegCreateKeyEx flags used with RegSaveKeyEx flags used with RegRestoreKe...
539
en
0.69689
import os from hexbytes import HexBytes import web3_api import csv import numpy as np import sys import copy block_start = 12865000 block_end = 13135000 gasused = {} sibling_cnt = {} timestamp = {} is_hotspot = {} avggas_per = {} def set_block_interval(start,end): global block_start,block_end block_start = st...
Data/spike.py
3,728
set_block_interval(13035000,13105000)
37
en
0.21223
from nextcord.ext import commands import requests # the prefix is not used in this example bot = commands.Bot(command_prefix='$') # @bot.event # async def on_message(message): # print(f'Message from {message.author}: {message.content}') @bot.command() async def ping(ctx): await ctx.send(f"The bot latency is ...
bot.py
470
the prefix is not used in this example @bot.event async def on_message(message): print(f'Message from {message.author}: {message.content}')
143
en
0.416065
# 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/siminterfaceipv6config_189f3bfbc365f2b105e35cd8b9d542d6.py
9,856
Data associated with simulated IPv6 interface link configuration inside a Network Topology. The SimInterfaceIPv6Config class encapsulates a list of simInterfaceIPv6Config resources that are managed by the system. A list of resources can be retrieved from the server using the SimInterfaceIPv6Config.find() method. Execut...
5,718
en
0.677957
# Copyright 2014 NEC Corporation. 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 l...
magnum/conductor/handlers/cluster_conductor.py
7,452
Copyright 2014 NEC Corporation. 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 agreed to in...
751
en
0.862786
#!/usr/bin/env python """ This action will display a list of volumes for an account """ from libsf.apputil import PythonApp from libsf.argutil import SFArgumentParser, GetFirstLine, SFArgFormatter from libsf.logutil import GetLogger, logargs from libsf.sfcluster import SFCluster from libsf.util import ValidateAndDefa...
account_list_volumes.py
3,772
Show the list of volumes for an account Args: account_name: the name of the account account_id: the ID of the account by_id: show volume IDs instead of names mvip: the management IP of the cluster username: the admin user of the cluster pa...
591
en
0.659891
""" Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan...
intersight/model/storage_net_app_sensor_all_of.py
9,573
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the a...
5,850
en
0.842474
'''entre no sistema com um valor float e saia com a sua parte inteira''' cores = {'limpa': '\033[m', 'azul': '\033[1;34m'} print('{:-^40}'.format('PARTE INTEIRA DE UM VALOR')) num = float(input('Digite um valor com ponto [Ex: 1.20]: ')) print('{}{}{} - sua parte inteira é - {}{}{} ' .format(cores['azul'], num, cores[...
script_python/parte_inteira_float_016.py
406
entre no sistema com um valor float e saia com a sua parte inteira
66
pt
0.983155
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- r""" event...
msticpy/analysis/eventcluster.py
23,231
Add commandline default features. Parameters ---------- output_df : pd.DataFrame The dataframe to add features to force : bool If True overwrite existing feature columns Add process name default features. Parameters ---------- output_df : pd.DataFrame The dataframe to add features to force : bool If T...
9,842
en
0.629022
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division import argparse import platform import subprocess import sys import os import errno import stat import gzip import six.moves.urllib as urllib from pkg_resources import parse_version DEFAULT_SCHEMES = { ...
oscarlm/taskcluster.py
6,165
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
# -*- coding: utf-8 -*- """ webapp2_extras.auth =================== Utilities for authentication and authorization. :copyright: 2011 by tipfy.org. :license: Apache Sotware License, see LICENSE for details. """ import time import webapp2 from webapp2_extras import security from webapp2_extras imp...
Webapp2_samplesite/webapp2_extras/auth.py
21,327
Authentication provider for a single request. Base auth exception. Provides common utilities and configuration for :class:`Auth`. Raised when a user can't be fetched given an auth_id. Raised when a user password doesn't match. Initializes the session store. :param app: A :class:`webapp2.WSGIApplication` instance. ...
9,947
en
0.671951
from tests.common import reboot, port_toggle import os import time import random import logging import pprint import pytest import json import ptf.testutils as testutils import ptf.mask as mask import ptf.packet as packet from abc import ABCMeta, abstractmethod from collections import defaultdict from tests.common i...
tests/acl/test_acl.py
42,091
Base class for testing ACL rules. Subclasses must provide `setup_rules` method to prepare ACL rules for traffic testing. They can optionally override `teardown_rules`, which will otherwise remove the rules by applying an empty configuration file. Test ACL rule functionality after toggling ports. Verify that ACLs sti...
7,156
en
0.853936
""" Django settings for ask project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import o...
ask/ask/settings.py
2,121
Django settings for ask project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ Build paths inside the project like this: os.path.join(BASE_DIR, ...) Quick-start devel...
824
en
0.694034
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.> """Utilities to evaluate motion forecasting predictions and compute metrics.""" import numpy as np from av2.utils.typing import NDArrayBool, NDArrayFloat, NDArrayNumber def compute_ade(forecasted_trajectories: NDArrayNumber, gt_trajectory: NDArrayNum...
src/av2/datasets/motion_forecasting/eval/metrics.py
2,554
Compute the average displacement error for a set of K predicted trajectories (for the same actor). Args: forecasted_trajectories: (K, N, 2) predicted trajectories, each N timestamps in length. gt_trajectory: (N, 2) ground truth trajectory. Returns: (K,) Average displacement error for each of the predicted...
1,495
en
0.678142
from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Factor(models.Model): group = models.TextField() factor = models.TextField() note = models.TextField(blank=True, null=True) class Meta: ordering = ('-group', 'factor',) def __str__(self): ...
geo/bms/element/models.py
1,042
class MPTTMeta: order_insertion_by = ['factor']def get_absolute_url(self): return(reverse('element:element_detail', args=[self.id]))
138
en
0.073094
from typing import FrozenSet from collections import Iterable from math import log, ceil from mathsat import msat_term, msat_env from mathsat import msat_make_constant, msat_declare_function from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type from mathsat import msat_make_and, msa...
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/3-sender_receiver_5.py
15,990
invar delta >= 0 delta > 0 -> (r2s' = r2s & s2r' = s2r) (G F !s.stutter) -> G (s.wait_ack -> F s.send) send & c = 0 & msg_id = 0 invar: wait_ack -> c <= timeout delta > 0 | stutter -> l' = l & msg_id' = msg_id & timeout' = timeout & c' = c + delta & out_c' = out_c (send & send') -> (msg_id' = msg_id & timeout' = base_t...
858
en
0.254738
import os import numpy as np import pandas as pd from fedot.core.data.data import InputData from fedot.core.pipelines.node import PrimaryNode, SecondaryNode from fedot.core.pipelines.pipeline import Pipeline from fedot.core.repository.dataset_types import DataTypesEnum from fedot.core.repository.tasks import Task, Ta...
test/unit/data_operations/test_data_operation_params.py
2,949
Function return pipeline with lagged transformation in it Function return pipeline with lagged transformation in it The function define a pipeline with incorrect parameters in the lagged transformation. During the training of the pipeline, the parameter 'window_size' is corrected Check that on a small dataset the RAN...
731
en
0.843883
# Copyright (c) 2010-2012 OpenStack Foundation # # 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 agree...
test/unit/common/middleware/test_domain_remap.py
6,065
Copyright (c) 2010-2012 OpenStack Foundation 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, s...
565
en
0.859753
from __future__ import absolute_import from .base import BasePage from .global_selection import GlobalSelectionPage class IssueDetailsPage(BasePage): def __init__(self, browser, client): super(IssueDetailsPage, self).__init__(browser) self.client = client self.global_selection = GlobalSel...
tests/acceptance/page_objects/issue_details.py
3,534
Resolve should become unresolve Ignore should become unresolve Open the assignee picker Click the member/team
109
en
0.942679
#!/usr/bin/python import livejournal import os import getpass import urllib lj = livejournal.LJ('evan', getpass.getpass(), 'evan_tech') def dump_entries(dirname, response): """Given a getevents response, dump all the entries into files named by itemid. Return the set of itemids received.""" all_itemi...
dump.py
3,500
!/usr/bin/python Assume it exists already. Fetch syncitems; convert to a map of itemid => time. Download items, crossing them off as we get them.
145
en
0.900052
import logging import sys import gym logger = logging.getLogger(__name__) root_logger = logging.getLogger() requests_logger = logging.getLogger('requests') # Set up the default handler formatter = logging.Formatter('[%(asctime)s] %(message)s') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatt...
gym/configuration.py
1,186
Undoes the automatic logging setup done by OpenAI Gym. You should call this function if you want to manually configure logging yourself. Typical usage would involve putting something like the following at the top of your script: gym.undo_logger_setup() logger = logging.getLogger() logger.addHandler(logging.StreamHandl...
574
en
0.860058
"""Child worker process module.""" import os import sys import time import signal import socket import shutil import logging import argparse import platform import threading import subprocess import traceback def parse_cmdline(): """Child worker command line parsing""" parser = argparse.ArgumentParser(descri...
testplan/runners/pools/child.py
14,836
Child process loop that can be started in a process and starts a local thread pool to execute the tasks received. Pool that creates no runpath directory. Has only one worker. Will use the one already created by parent process. Pool that creates no runpath directory. Will use the one already created by parent process. S...
1,475
en
0.905106
# Copyright (c) 2022 Mira Geoscience Ltd. # # This file is part of geoapps. # # geoapps is distributed under the terms and conditions of the MIT License # (see LICENSE file at the root of this source code package). import numpy as np from geoh5py.io import H5Writer from geoh5py.objects import Curve, Points, Surfa...
geoapps/contours/application.py
7,219
Application for 2D contouring of spatial data. Get current selection and trigger update :obj:`ipywidgets.Text`: String defining sets of contours. Contours can be defined over an interval `50:200:10` and/or at a fix value `215`. Any combination of the above can be used: 50:200:10, 215 => Contours between values 50 and 2...
843
en
0.672019
"""[directory] cd /Users/brunoflaven/Documents/02_copy/_000_IA_bruno_light/article_bert_detecting_fake_news_1/fake_news_nlp_detection/ python fake_news_nlp_detection_2.py """ # This is a Python 3 environment # Base level imports for data science work import numpy as np import pandas as pd import re,string,unicod...
fake_news_nlp_detection/fake_news_nlp_detection_2.py
11,603
A simple function to cleanup text data [directory] cd /Users/brunoflaven/Documents/02_copy/_000_IA_bruno_light/article_bert_detecting_fake_news_1/fake_news_nlp_detection/ python fake_news_nlp_detection_2.py This is a Python 3 environment Base level imports for data science work Visualization Libs NLP Libs Additiona...
3,522
en
0.78238
#! /usr/bin/env python2 """ mbed SDK Copyright (c) 2011-2013 ARM 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 License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicabl...
tools/build.py
12,768
! /usr/bin/env python2 Be sure that the tools directory is in the search path Parse Options Extra libraries Only prints matrix of supported toolchains Get target list Get toolchains list This import happens late to prevent initializing colorization when we don't need it Get libraries list Additional Libraries Build res...
452
en
0.799252
# Copyright 2017-2020 Spotify AB # # 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 writi...
spotify_confidence/examples.py
3,070
Returns an output dataframe with categorical features (country and test variation), and orginal features (date), as well as number of successes and total observations for each combination Copyright 2017-2020 Spotify AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in...
803
en
0.863634
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors # For information on the respective copyright owner see the NOTICE file # # 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 # #...
pcg_libraries/src/pcg_gazebo/parsers/sdf/kd.py
955
Copyright (c) 2019 - The Procedural Generation for Gazebo authors For information on the respective copyright owner see the NOTICE file 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....
657
en
0.862835