max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 7 115 | max_stars_count int64 101 368k | id stringlengths 2 8 | content stringlengths 6 1.03M |
|---|---|---|---|---|
doc/rst/getting_started/src/hello_world_python/hello_world_rec.py | SirArep/ecal | 493 | 12616977 | import sys
import time
import ecal.core.core as ecal_core
from ecal.core.subscriber import StringSubscriber
# Callback for receiving messages
def callback(topic_name, msg, time):
print("Received: {}".format(msg))
if __name__ == "__main__":
# Initialize eCAL
ecal_core.initialize(sys.argv, "Python Hello World Pu... |
mods/TowerofHanoi/towers.py | SummitChen/opennero | 215 | 12617005 | <filename>mods/TowerofHanoi/towers.py
def On(A, B):
return ("On", A, B)
def Clear(A):
return ("Clear", A)
def Smaller(A, B):
return ("Smaller", A, B)
class Towers(object):
Pole1 = 'Pole1'
Pole2 = 'Pole2'
Pole3 = 'Pole3'
POLES = ['Pole1', 'Pole2', 'Pole3']
@classmet... |
regtests/calling/starargs.py | ahakingdom/Rusthon | 622 | 12617014 | <gh_stars>100-1000
from runtime import *
"""unpack starargs"""
def f(x, a, b, c):
return x+a+b+c
def f2(x,y,z, w=0):
return x+y+z+w
def main():
a = [1,1,1]
assert( f(1, *a) == 4)
assert( f2(*a, w=10) == 13)
b = [1,1]
assert( f2(100, *b, w=10) == 112)
main()
|
ambari-agent/src/test/python/resource_management/TestFcntlBasedProcessLock.py | likenamehaojie/Apache-Ambari-ZH | 1,664 | 12617017 | '''
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 ... |
h5Nastran/h5Nastran/h5nastran/_result.py | ACea15/pyNastran | 293 | 12617023 | <filename>h5Nastran/h5Nastran/h5nastran/_result.py<gh_stars>100-1000
from __future__ import print_function, absolute_import
from collections import OrderedDict
import numpy as np
import tables
from six import iteritems
from ._punch import H5NastranResultPunch
from ._op2 import H5NastranResultOP2
class H5NastranRes... |
catalyst/runners/__init__.py | sergunya17/catalyst | 2,693 | 12617040 | <filename>catalyst/runners/__init__.py
# flake8: noqa
from catalyst.runners.supervised import ISupervisedRunner
from catalyst.runners.self_supervised import ISelfSupervisedRunner
from catalyst.runners.runner import Runner, SelfSupervisedRunner, SupervisedRunner
from catalyst.runners.config import (
ConfigRunner,
... |
Src/StdLib/Lib/site-packages/win32comext/axdebug/documents.py | cwensley/ironpython2 | 1,078 | 12617044 | """ Management of documents for AXDebugging.
"""
import axdebug, gateways
import pythoncom
from util import _wrap, _wrap_remove, RaiseNotImpl, trace
from win32com.server.util import unwrap
import codecontainer
import contexts
from win32com.server.exception import Exception
import win32api, winerror, os, string, sys
#... |
tasks/imdb_tcn.py | evanharwin/keras-tcn | 1,473 | 12617057 | """
#Trains a TCN on the IMDB sentiment classification task.
Output after 1 epochs on CPU: ~0.8611
Time per epoch on CPU (Core i7): ~64s.
Based on: https://github.com/keras-team/keras/blob/master/examples/imdb_bidirectional_lstm.py
"""
import numpy as np
from tensorflow.keras import Sequential
from tensorflow.keras.dat... |
dynamo/plot/cell_cycle.py | xing-lab-pitt/dynamo-release | 236 | 12617072 | <gh_stars>100-1000
from anndata import AnnData
from matplotlib.axes import Axes
from typing import Union, Optional
from ..tools.utils import update_dict
from .utils import save_fig
def cell_cycle_scores(
adata: AnnData,
cells: Optional[list] = None,
save_show_or_return: str = "show",
save_kwargs: dic... |
_solved/solutions/case-conflict-mapping41.py | lleondia/geopandas-tutorial | 341 | 12617092 | <reponame>lleondia/geopandas-tutorial
data_within_border['NAME_AP'].value_counts() |
network/gra_transf_inpt5_new_dropout_2layerMLP.py | Team-Squad-Up/multigraph_transformer | 268 | 12617100 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .graph_transformer_layers_new_dropout import *
import ipdb
class GraphTransformerEncoder(nn.Module):
def __init__(self, coord_input_dim, feat_input_dim, feat_dict_size, n_layers=6, n_heads=8,
embed_dim=512,... |
checkov/cloudformation/checks/resource/aws/KMSKeyWildCardPrincipal.py | kylelaker/checkov | 4,013 | 12617120 | <reponame>kylelaker/checkov<filename>checkov/cloudformation/checks/resource/aws/KMSKeyWildCardPrincipal.py
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.cloudformation.checks.resource.base_resource_value_check import BaseResourceValueCheck
def get_recursively(search_dict, field):
... |
examples/simulation/dataset.py | Chris-george-anil/flower | 895 | 12617132 | <gh_stars>100-1000
# Copyright 2020 Adap GmbH. 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 a... |
tests/test_provider_hashicorp_oci.py | mjuenema/python-terrascript | 507 | 12617141 | # tests/test_provider_hashicorp_oci.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:23:14 UTC)
def test_provider_import():
import terrascript.provider.hashicorp.oci
def test_resource_import():
from terrascript.resource.hashicorp.oci import (
oci_ai_anomaly_detection_ai_private_endp... |
env/lib/python3.8/site-packages/numpy/random/tests/test_seed_sequence.py | acrucetta/Chicago_COVI_WebApp | 1,738 | 12617143 | import numpy as np
from numpy.testing import assert_array_equal
from numpy.random import SeedSequence
def test_reference_data():
""" Check that SeedSequence generates data the same as the C++ reference.
https://gist.github.com/imneme/540829265469e673d045
"""
inputs = [
[3735928559, 195939070... |
deluca/lung/utils/scripts/train_simulator.py | google/deluca | 105 | 12617156 | # Copyright 2021 The Deluca 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 or agreed to in w... |
InternalPythonModules/android/line.py | drwetter/autopsy | 1,473 | 12617171 | <reponame>drwetter/autopsy
"""
Autopsy Forensic Browser
Copyright 2019-2021 Basis Technology Corp.
Contact: carrier <at> sleuthkit <dot> org
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
htt... |
gcloud/tests/taskflow3/tasks/test_ensure_node_can_retry.py | brookylin/bk-sops | 881 | 12617191 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file ... |
vocoders/base_vocoder.py | ishine/DiffSinger-1 | 288 | 12617192 | <reponame>ishine/DiffSinger-1
import importlib
VOCODERS = {}
def register_vocoder(cls):
VOCODERS[cls.__name__.lower()] = cls
VOCODERS[cls.__name__] = cls
return cls
def get_vocoder_cls(hparams):
if hparams['vocoder'] in VOCODERS:
return VOCODERS[hparams['vocoder']]
else:
vocoder_... |
tensorflow/python/kernel_tests/gradient_correctness_test.py | connectthefuture/tensorflow | 680 | 12617204 | # Copyright 2015 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... |
pecos/xmc/xtransformer/predict.py | xeisberg/pecos | 288 | 12617228 | # Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acco... |
maskrcnn_benchmark/data/datasets/flickr.py | microsoft/GLIP | 295 | 12617250 | import torch
import torchvision
import torch.utils.data as data
from maskrcnn_benchmark.data.datasets.modulated_coco import ModulatedDataset
class FlickrDataset(ModulatedDataset):
pass
|
4_efficientdet/lib/train.py | deepchatterjeevns/Monk_Object_Detection | 649 | 12617296 | import os
import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import transforms
from src.dataset import CocoDataset, Resizer, Normalizer, Augmenter, collater
from src.model import EfficientDet
from tensorboardX import SummaryWriter
import shutil
import numpy as np... |
pdf2txt.py | anandurchandran007/Automated-Resume-Screening-System | 304 | 12617297 | import sys
import logging
import six
import pdfminer.settings
pdfminer.settings.STRICT = False
import pdfminer.high_level
import pdfminer.layout
from pdfminer.image import ImageWriter
def extract_text(files=[], outfile='-',
_py2_no_more_posargs=None,
no_laparams=False, all_texts=None, detect... |
mobile_deployment/pytorch/InvBlock/models/imagenet/i2rnetv2.py | zhoudaquan/rethinking_bottleneck_structure_code_release | 153 | 12617301 | """
Creates a MobileNetV2 Model as defined in:
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch.nn as nn
import math
__all__ = ['i2rnetv2',]
def _make_... |
QSTK/qstkfeat/features.py | paulopatto/QuantSoftwareToolkit | 339 | 12617305 | '''
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license. Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.
Created on Nov 7, 2011
@author: <NAME>
@contact: <EMAIL>
@summary: File containing various feature functions
'''
#''... |
image/docker/schema2/config.py | giuseppe/quay | 2,027 | 12617317 | """
Implements validation and conversion for the Schema2 config JSON.
Example:
{
"architecture": "amd64",
"config": {
"Hostname": "",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": ... |
src/main/python/systemds/operator/algorithm/__init__.py | mdbloice/systemds | 372 | 12617320 | <reponame>mdbloice/systemds
# -------------------------------------------------------------
#
# 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 lice... |
src/timeago/locales/pt_BR.py | nmb10/timeago | 220 | 12617322 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2017-8-30
@author: generated by @lolobosse script
'''
LOCALE = [
["agora mesmo", "daqui um pouco"],
["há %s segundos", "em %s segundos"],
["há um minuto", "em um minuto"],
["há %s minutos", "em %s minutos"],
["há uma ho... |
tensorflow/python/training/ftrl_test.py | connectthefuture/tensorflow | 101 | 12617323 | # Copyright 2015 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... |
feature_engine/selection/drop_duplicate_features.py | janrito/feature_engine | 650 | 12617326 | <filename>feature_engine/selection/drop_duplicate_features.py
from typing import List, Union
import pandas as pd
from feature_engine.dataframe_checks import _check_contains_na, _is_dataframe
from feature_engine.selection.base_selector import BaseSelector
from feature_engine.validation import _return_tags
from feature... |
dpaste/settings/tests.py | jcroot/dpaste | 278 | 12617332 | <filename>dpaste/settings/tests.py
"""
Settings for the testsuite runs.
"""
import django
from .base import * # noqa
SECRET_KEY = "test-key"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
|
experimental/heap_computation/test_mem.py | kokizzu/prometeo | 509 | 12617334 | <reponame>kokizzu/prometeo
# from prometeo.mem.ast_analyzer import get_call_graph
from prometeo.mem.ast_analyzer import compute_reach_graph
from prometeo.mem.ast_analyzer_2 import ast_visitor
from prometeo.mem.ast_analyzer_2 import compute_reach_graph
# from prometeo.cgen.code_gen import to_source
import ast
if __name_... |
tests/test_utils/test_utils.py | Guangyun-Xu/mmdetection3d | 2,216 | 12617336 | <filename>tests/test_utils/test_utils.py
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdet3d.core import draw_heatmap_gaussian
def test_gaussian():
heatmap = torch.zeros((128, 128))
ct_int = torch.tensor([64, 64], dtype=torch.int32)
radius = 2
draw_heatmap_gaussian(heatmap, ct_i... |
src/olympia/amo/tests/test_migrations.py | covariant/addons-server | 843 | 12617351 | <gh_stars>100-1000
from django.db import migrations, models
from ..migrations import RenameConstraintsOperation, RenameIndexesOperation
def test_rename_constraints_operation():
add_constraint = migrations.AddConstraint(
model_name='addoncategory',
constraint=models.UniqueConstraint(
f... |
pythainlp/corpus/core.py | Gorlph/pythainlp | 569 | 12617361 | # -*- coding: utf-8 -*-
"""
Corpus related functions.
"""
import hashlib
import os
from typing import Union
from urllib.request import urlopen
import json
import requests
from pythainlp.corpus import corpus_db_path, corpus_db_url, corpus_path
from pythainlp.tools import get_full_data_path
from requests.exceptions imp... |
deeprobust/graph/data/utils.py | shixiongjing/DeepRobust | 647 | 12617373 | """
This file provides functions for converting deeprobust data
to pytorch geometric data.
"""
|
official/vision/gan/megengine_mimicry/utils/common.py | pepperonibo/Models | 294 | 12617374 | <filename>official/vision/gan/megengine_mimicry/utils/common.py
# Copyright (c) 2020 <NAME>
# This code is licensed under MIT license
# (https://github.com/kwotsin/mimicry/blob/master/LICENSE)
# ------------------------------------------------------------------------------
# MegEngine is Licensed under the Apache Licen... |
recipe_scrapers/_exceptions.py | mathiazom/recipe-scrapers | 811 | 12617455 | class RecipeScrapersExceptions(Exception):
def __init__(self, message):
self.message = message
super().__init__(message)
def __str__(self):
return f"recipe-scrapers exception: {self.message}"
class WebsiteNotImplementedError(RecipeScrapersExceptions):
"""Error when website is not ... |
src/toil/wdl/versions/dev.py | Hexotical/toil | 348 | 12617481 | <reponame>Hexotical/toil
# Copyright (C) 2020-2021 Regents of the University of California
#
# 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
#... |
docs/conf.py | Pesa/ndn-cxx | 106 | 12617490 | <reponame>Pesa/ndn-cxx
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup ------------------------------------------------... |
artemis/experiments/demo_experiments.py | peteroconnor-bc/artemis | 235 | 12617496 | import numpy as np
from artemis.experiments.decorators import experiment_function
from matplotlib import pyplot as plt
from six.moves import xrange
__author__ = 'peter'
"""
This file demonstates Artemis's "Experiments"
When you run an experiment, all figures and console output, as well as some metadata such as tota... |
webservices/iss_epicentro/iss_epicentroInizio.py | ffxx68/covid19italia | 237 | 12617539 | import csv
import datetime
import sys, os
pathname = os.path.dirname(sys.argv[0])
abspath=os.path.abspath(pathname)
regioni = ['Piemonte', 'Valle Aosta', 'Lombardia', 'PA Bolzano', 'PA Trento', 'Veneto', 'Friuli', 'Liguria', 'Emilia', 'Toscana',
'Umbria', 'Marche', 'Lazio', 'Abruzzo', 'Molise', 'Campania',... |
rl_reliability_metrics/metrics/metrics_online.py | mcx/rl-reliability-metrics | 122 | 12617555 | <gh_stars>100-1000
# coding=utf-8
# Copyright 2019 The Authors of RL Reliability Metrics.
#
# 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
#
... |
dialogue-engine/src/programy/parser/template/nodes/triple.py | cotobadesign/cotoba-agent-oss | 104 | 12617578 | <filename>dialogue-engine/src/programy/parser/template/nodes/triple.py
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
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 wit... |
qiskit_nature/mappers/second_quantization/linear_mapper.py | jschuhmac/qiskit-nature | 132 | 12617584 | <reponame>jschuhmac/qiskit-nature<gh_stars>100-1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses... |
apple/internal/transition_support.bzl | tnek/rules_apple | 313 | 12617615 | <reponame>tnek/rules_apple
# Copyright 2019 The Bazel 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
#
# Unles... |
lib/python2.7/site-packages/samba/netcmd/__init__.py | abankalarm/pth-toolkit | 480 | 12617618 | # Unix SMB/CIFS implementation.
# Copyright (C) <NAME> <<EMAIL>> 2009-2012
# Copyright (C) <NAME> <<EMAIL>> 2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License... |
SBR/lib/lk/basic_utils.py | yerang823/landmark-detection | 612 | 12617628 | <filename>SBR/lib/lk/basic_utils.py
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torch.nn as nn
import torch.nn.functional as F
import numbers, mat... |
test/YACC/YACCFLAGS-fixture/myyacc.py | Valkatraz/scons | 1,403 | 12617640 | <filename>test/YACC/YACCFLAGS-fixture/myyacc.py<gh_stars>1000+
import getopt
import sys
cmd_opts, args = getopt.getopt(sys.argv[1:], 'o:I:x', [])
opt_string = ''
i_arguments = ''
for opt, arg in cmd_opts:
if opt == '-o': out = arg
elif opt == '-I': i_arguments = i_arguments + ' ' + arg
else: opt_string = op... |
src/SALib/test_functions/linear_model_1.py | zjzh/SALib | 573 | 12617675 | <reponame>zjzh/SALib
import numpy as np
def evaluate(values):
"""Linear model (#1) used in Li et al., (2010).
y = x1 + x2 + x3 + x4 + x5
Parameters
----------
values : np.array
References
----------
.. [1] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, and <NAME>, ... |
scout/utils/algorithms.py | mhkc/scout | 111 | 12617709 | import logging
LOG = logging.getLogger(__name__)
def ui_score(set_1, set_2):
"""Get the ui score of two sets
Given two bags of HPO terms, p and q, the UI score is defined as:
- let I(t) for a set of terms t, be the set of terms in t and all the ancestors of the terms
in t
- UI(p, ... |
Lib/idlelib/idle_test/test_parenmatch.py | shawwn/cpython | 52,316 | 12617763 | <filename>Lib/idlelib/idle_test/test_parenmatch.py
"""Test parenmatch, coverage 91%.
This must currently be a gui test because ParenMatch methods use
several text methods not defined on idlelib.idle_test.mock_tk.Text.
"""
from idlelib.parenmatch import ParenMatch
from test.support import requires
requires('gui')
impo... |
tests/models/DIFM_test.py | dzzxjl/DeepCTR | 6,192 | 12617769 | <filename>tests/models/DIFM_test.py
import pytest
from deepctr.models import DIFM
from ..utils import check_model, get_test_data, SAMPLE_SIZE
@pytest.mark.parametrize(
'att_head_num,dnn_hidden_units,sparse_feature_num',
[(1, (4,), 2), (2, (4, 4,), 2), (1, (4,), 1)]
)
def test_DIFM(att_head_num, dnn_hidden_un... |
threat_hunting/CB-Command_R/config.py | knightsc/tau-tools | 202 | 12617783 | #!/usr/bin/env python
active = {
'url': 'https://<SUBDOMAIN>.carbonblack.io/api/v1/process',
'key': '<API KEY>'
}
# ======================================================================
# Place API key and URL in 'active' to use with the cmdline-search.py
# ===================================================... |
third_party/blink/tools/blinkpy/tool/commands/command.py | zipated/src | 2,151 | 12617791 | <filename>third_party/blink/tools/blinkpy/tool/commands/command.py
# Copyright (c) 2016 Google Inc. 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 re... |
PythonCode/demo/app_kd_range.py | konny0311/algorithms-nutshell-2ed | 522 | 12617792 | <gh_stars>100-1000
"""
Demonstration application for range search using kd tree.
Left mouse adds point.
Right mouse click begins drag of rectangle.
"""
import tkinter
from adk.kd import KDTree, X, Y, VERTICAL
from adk.region import Region, minValue, maxValue
RectangleSize = 4
class KDT... |
fuzzers/027-bram36-config/top.py | marzoul/prjxray | 583 | 12617803 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import os
import random
import json
r... |
Python3/1039.py | rakhi2001/ecom7 | 854 | 12617809 | __________________________________________________________________________________________________
sample 92 ms submission
class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
if len(A) < 3:
return 0
elif len(A) == 3:
return A[0]*A[1]*A[2]
else:
... |
utils/meshRelax.py | fsanges/glTools | 165 | 12617817 | <filename>utils/meshRelax.py
import maya.cmds as mc
import maya.OpenMaya as OpenMaya
import glTools.utils.component
import glTools.utils.curve
import glTools.utils.mathUtils
import glTools.utils.surface
class UserInputError(Exception): pass
def neighbour(vertexList,referenceObject,meshRelax):
'''
'''
# Get meshRe... |
userena/middleware.py | mortenwh/django-userena | 501 | 12617819 | <reponame>mortenwh/django-userena
from django.utils import translation
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from userena import settings as userena_settings
from userena.compat import SiteProfileNotAvailable
from userena.utils import get_user_profile
class UserenaLoc... |
cleverhans/torch/attacks/noise.py | xu-weizhen/cleverhans | 4,333 | 12617834 | <gh_stars>1000+
"""
The Noise Attack
"""
import numpy as np
import torch
def noise(x, eps=0.3, order=np.inf, clip_min=None, clip_max=None):
"""
A weak attack that just picks a random point in the attacker's action
space. When combined with an attack bundling function, this can be used to
implement ra... |
Chapter09/chapter_09_example_01.py | pesader/hands-on-music-generation-with-magenta | 123 | 12617844 | <filename>Chapter09/chapter_09_example_01.py
"""
Utility functions for finding and creating MIDI ports.
VERSION: Magenta 1.1.7
"""
import mido
from magenta.interfaces.midi.midi_hub import MidiHub
def find_midi_ports():
print(f"Input ports: {mido.get_input_names()}")
print(f"Output ports: {mido.get_output_names(... |
rhn_train.py | vk496e1/RecurrentHighwayNetworks | 427 | 12617870 | """Word/Symbol level next step prediction using Recurrent Highway Networks.
To run:
$ python rhn_train.py
"""
from __future__ import absolute_import, division, print_function
from copy import deepcopy
import time
import os
import numpy as np
import tensorflow as tf
from sacred import Experiment
from rhn import Mode... |
peeringdb_server/migrations/0030_affiliation_request_status_add_canceled.py | CyberFlameGO/peeringdb | 224 | 12617884 | # Generated by Django 2.2.9 on 2020-04-01 10:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("peeringdb_server", "0029_auto_20200401_1006"),
]
operations = [
migrations.AlterField(
model_name="userorgaffiliationrequest",
... |
tools/check-missing-ansible.py | ResilienceCare/ansible-lint | 484 | 12617886 | """Validates linter behavior when ansible python package is missing."""
import os
import subprocess
if __name__ == "__main__":
cmd = ["ansible-lint", "--version"]
result = subprocess.run(
cmd,
universal_newlines=True,
check=False,
stdout=subprocess.PIPE,
stderr=subproces... |
cocotb/decorators.py | lavanyajagan/cocotb | 350 | 12617894 | # Copyright (c) 2013 Potential Ventures Ltd
# Copyright (c) 2013 SolarFlare Communications Inc
# 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 th... |
CalibTracker/SiPixelESProducers/python/SiPixelFakeGainForHLTESSource_cfi.py | ckamtsikis/cmssw | 852 | 12617902 | import FWCore.ParameterSet.Config as cms
SiPixelFakeGainForHLTESSource = cms.ESSource("SiPixelFakeGainForHLTESSource",
file = cms.FileInPath('CalibTracker/SiPixelESProducers/data/PixelSkimmedGeometry.txt')
)
|
bcs-ui/backend/helm/helm/urls.py | laodiu/bk-bcs | 599 | 12617904 | <filename>bcs-ui/backend/helm/helm/urls.py
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "Licens... |
chapter_10/QASystem/answer/MongoUtil.py | LifeOfGame/mongodb_redis | 183 | 12617906 | import pymongo
import json
from bson import ObjectId
class MongoUtil(object):
def __init__(self):
db = pymongo.MongoClient().qa_system
self.question = db.question
self.answer = db.answer
def query_question(self):
question_iter_obj = self.question.aggregate([
{'$look... |
chronologicon/__init__.py | rutherfordcraze/chronologicon | 103 | 12617911 | # -*- coding: utf-8 -*-
# Chronologicon v5.x
# <NAME>
# https://craze.co.uk
# 181028
import json
import os
import chronologicon.input
from easysettings import EasySettings
from chronologicon.strings import *
LOGS_FILENAME = 'logs.json'
STATS_FILENAME = 'stat.json'
PRESAVE_FILENAME = 'temp.json'
LOGS_DEFAULT = []
C... |
Code-Sleep-Python/Sprint/sprint.py | shardul08/Code-Sleep-Python | 420 | 12617933 | import msvcrt
import time
high_score = 50
name = "no-one"
while(1):
distance = int(0)
print("\n--------------------------------------------------------------")
print('\n\nWelcome to the 100m sprint, tap z and x rapidly to move!')
print('* = 10m')
print("\n**Current record: " + str(high_score) + "... |
fernet_fields/fields.py | brianhelba/django-fernet-fields | 173 | 12617948 | from cryptography.fernet import Fernet, MultiFernet
from django.conf import settings
from django.core.exceptions import FieldError, ImproperlyConfigured
from django.db import models
from django.utils.encoding import force_bytes, force_text
from django.utils.functional import cached_property
from . import hkdf
__all_... |
tests/test_pytest_overrides.py | sflems/django-constance | 899 | 12617988 | <reponame>sflems/django-constance<filename>tests/test_pytest_overrides.py
import unittest
try:
import pytest
from constance import config
from constance.test.pytest import override_config
class TestPytestOverrideConfigFunctionDecorator:
"""Test that the override_config decorator works corre... |
test/espnet2/asr/encoder/test_conformer_encoder.py | nmfisher/espnet | 5,053 | 12618007 | <filename>test/espnet2/asr/encoder/test_conformer_encoder.py
import pytest
import torch
from espnet2.asr.encoder.conformer_encoder import ConformerEncoder
@pytest.mark.parametrize(
"input_layer", ["linear", "conv2d", "conv2d2", "conv2d6", "conv2d8", "embed"]
)
@pytest.mark.parametrize("positionwise_layer_type", ... |
test/test_type_hints.py | Hacky-DH/pytorch | 60,067 | 12618012 | import unittest
from torch.testing._internal.common_utils import TestCase, run_tests, set_cwd
import tempfile
import torch
import doctest
import os
import inspect
from pathlib import Path
try:
import mypy.api
HAVE_MYPY = True
except ImportError:
HAVE_MYPY = False
def get_examples_from_docstring(docstr):
... |
dask_cloudprovider/gcp/tests/test_utils.py | moti-jfrog/dask-cloudprovider | 102 | 12618042 | import pytest
from dask_cloudprovider.gcp.utils import build_request, is_inside_gce
def test_build_request():
assert build_request()(None, lambda x: x, "https://example.com")
@pytest.mark.xfail(
is_inside_gce(), reason="Fails if you run this test on GCE environment"
)
def test_is_gce_env():
# Note: thi... |
holoviews/tests/plotting/plotly/test_violinplot.py | TheoMathurin/holoviews | 864 | 12618046 | <reponame>TheoMathurin/holoviews
import numpy as np
from holoviews.element import Violin
from .test_plot import TestPlotlyPlot
class TestViolinPlot(TestPlotlyPlot):
def test_violin_single(self):
violin = Violin([1, 1, 2, 3, 3, 4, 5, 5])
state = self._get_plot_state(violin)
self.assertEq... |
docs/tutorial.py | mrtrkmn/yellowbrick | 3,662 | 12618056 | <gh_stars>1000+
#!/usr/bin/env python
# Generate the classification report images for the tutorial
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC, NuSVC, SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import OneHotEncoder, Lab... |
lib/tamper_scripts/base64_encode.py | ikstream/Zeus-Scanner | 841 | 12618078 | <filename>lib/tamper_scripts/base64_encode.py
import base64
from lib.core.settings import (
logger,
set_color
)
def tamper(payload, **kwargs):
warning = kwargs.get("warning", True)
if warning:
logger.warning(set_color(
"base64 tamper scripts may increase the possibility of not fin... |
dl_lib/configs/segm_config.py | AndysonYs/DynamicRouting | 122 | 12618080 | <gh_stars>100-1000
from .base_config import BaseConfig
_config_dict = dict(
MODEL=dict(
LOAD_PROPOSALS=False,
MASK_ON=False,
KEYPOINT_ON=False,
BACKBONE=dict(FREEZE_AT=0, ),
RESNETS=dict(
OUT_FEATURES=["res2", "res3", "res4", "res5"],
NORM="nnSyncBN",... |
fedot/core/optimisers/gp_comp/operators/mutation.py | rozlana-g/FEDOT | 358 | 12618084 | from copy import deepcopy
from functools import partial
from random import choice, randint, random, sample
from typing import Any, Callable, List, TYPE_CHECKING, Union
import numpy as np
from fedot.core.composer.constraint import constraint_function
from fedot.core.log import Log
from fedot.core.optimisers.gp_comp.gp... |
supervisor/store/const.py | peddamat/home-assistant-supervisor-test | 597 | 12618086 | """Constants for the add-on store."""
from enum import Enum
class StoreType(str, Enum):
"""Store Types."""
CORE = "core"
LOCAL = "local"
GIT = "git"
|
Python/examples/bonds.py | yrtf/QuantLib-SWIG | 231 | 12618113 | <reponame>yrtf/QuantLib-SWIG
# ---
# jupyter:
# jupytext:
# formats: py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ... |
fastapi_simple_security/_security_secret.py | yourkin/fastapi_simple_security | 103 | 12618118 | <reponame>yourkin/fastapi_simple_security
import os
import uuid
import warnings
from fastapi import Security
from fastapi.security import APIKeyHeader
from starlette.exceptions import HTTPException
from starlette.status import HTTP_403_FORBIDDEN
try:
SECRET = os.environ["FASTAPI_SIMPLE_SECURITY_SECRET"]... |
AI-env/lib/python3.7/site-packages/charset_normalizer/cd.py | parth5795/iOT-benchmarking | 150 | 12618143 | <reponame>parth5795/iOT-benchmarking<gh_stars>100-1000
import importlib
from codecs import IncrementalDecoder
from collections import Counter
from functools import lru_cache
from typing import Dict, List, Optional, Set, Tuple
from .assets import FREQUENCIES
from .md import is_suspiciously_successive_range
from .models... |
paxos/essential.py | timgates42/paxos | 420 | 12618147 | <reponame>timgates42/paxos
'''
This module provides a minimal implementation of the Paxos algorithm
that is independent of the underlying messaging mechanism. These
classes implement only the essential Paxos components and omit
the practical considerations (such as durability, message
retransmissions, NACKs, etc).
'''... |
lona/html/document.py | korantu/lona | 230 | 12618197 | from threading import RLock
from lona.html.abstract_node import AbstractNode
from lona.html.patches import PatchStack
from lona.protocol import DATA_TYPE
class Document:
def __init__(self):
self._lock = RLock()
self.html = None
self._patch_stack = PatchStack()
@property
def lock(... |
tools/mo/openvino/tools/mo/utils/ir_reader/__init__.py | pazamelin/openvino | 2,406 | 12618222 | # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
|
components/py_engine/framework/ap3216c.py | wstong999/AliOS-Things | 4,538 | 12618255 | <gh_stars>1000+
"""
Copyright (C) 2015-2020 Alibaba Group Holding Limited
The driver for AP3216C chip, The AP3216C is an integrated ALS & PS module
that includes a digital ambient light sensor [ALS], a proximity sensor [PS],
and an IR LED in a single package.
"""
from micropython import const
from driver import I2C
fr... |
QSTK/qstkstudy/Events.py | paulopatto/QuantSoftwareToolkit | 339 | 12618267 | # (c) 2011, 2012 Georgia Tech Research Corporation
# This source code is released under the New BSD license. Please see
# http://wiki.quantsoftware.org/index.php?title=QSTK_License
# for license details.
#Created on October <day>, 2011
#
#@author: <NAME>
#@contact: <EMAIL>
#@summary: Example Event Datamatrix acceptab... |
Build Glyphs/Build Circled Glyphs.py | KatjaSchimmel/Glyphs-Scripts | 283 | 12618272 | #MenuTitle: Build Circled Glyphs
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Builds circled numbers and letters (U+24B6...24EA and U+2460...2473) from _part.circle and the letters and figures.
"""
from Foundation import NSPoint, NSClassFromString, NSAffineTrans... |
rio_tiler/colormap.py | kalxas/rio-tiler | 242 | 12618273 | """rio-tiler colormap functions and classes."""
import os
import pathlib
import re
from typing import Dict, List, Sequence, Tuple, Union
import attr
import numpy
from .constants import NumType
from .errors import (
ColorMapAlreadyRegistered,
InvalidColorFormat,
InvalidColorMapName,
InvalidFormat,
)
... |
taskw_gcal_sync/helpers.py | bergercookie/taskw_gcal_sync | 113 | 12618298 | <reponame>bergercookie/taskw_gcal_sync<gh_stars>100-1000
"""Various helper methods."""
import re
from typing import Any
def get_object_unique_name(obj: Any) -> str:
"""Return a unique string associated with the given object.
That string is constructed as follows: <object class name>_<object_hex_id>
"""
... |
internals/fetchmetrics.py | liamnewmarch/chromium-dashboard | 450 | 12618315 | <reponame>liamnewmarch/chromium-dashboard
# -*- coding: utf-8 -*-
# Copyright 2021 Google 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.... |
src/genie/libs/parser/iosxe/tests/ShowSnmpGroup/cli/equal/golden_output_expected.py | balmasea/genieparser | 204 | 12618343 | expected_output = {
1: {
"groupname": "2c",
"sec_model": "v1",
"contextname": "none",
"storage_type": "volatile",
"readview": "none",
"writeview": "none",
"notifyview": "*tv.FFFF58bf.eaFF58bf.eaFFFFFF.F",
"row_status": {"status": "active"},
},
... |
examples/point_transform/sketch_point_transform.py | hishamsajid/vsketch | 221 | 12618366 | import vsketch
class PointTransformSketch(vsketch.SketchClass):
def draw(self, vsk: vsketch.Vsketch) -> None:
vsk.size("a4", landscape=False)
vsk.scale("1mm")
with vsk.pushMatrix():
for _ in range(40):
vsk.rotate(2, degrees=True)
vsk.scale(0.95)... |
lhotse/features/kaldi/__init__.py | stachu86/lhotse | 353 | 12618371 | from .extractors import KaldiFbank, KaldiFbankConfig, KaldiMfcc, KaldiMfccConfig
from .layers import Wav2FFT, Wav2LogFilterBank, Wav2LogSpec, Wav2MFCC, Wav2Spec, Wav2Win
|
src/Launcher.py | codexgigassys/codex-backend | 161 | 12618391 | # Copyright (C) 2016 Deloitte Argentina.
# This file is part of CodexGigas - https://github.com/codexgigassys/
# See the file 'LICENSE' for copying permission.
# Funciones para realizar los analisis
import os
import time
from czipfile import ZipFile
from Cataloger import Cataloger
from Processors.ProcessorFactory impor... |
release/stubs.min/System/Windows/Forms/__init___parts/SplitterCancelEventArgs.py | htlcnn/ironpython-stubs | 182 | 12618405 | <reponame>htlcnn/ironpython-stubs
class SplitterCancelEventArgs(CancelEventArgs):
"""
Provides data for splitter events.
SplitterCancelEventArgs(mouseCursorX: int,mouseCursorY: int,splitX: int,splitY: int)
"""
@staticmethod
def __new__(self,mouseCursorX,mouseCursorY,splitX,splitY):
""" __new__(cls... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.