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 |
|---|---|---|---|---|
evennia/locks/lockhandler.py | frnknstn/evennia | 127 | 9592796 | <filename>evennia/locks/lockhandler.py
"""
A *lock* defines access to a particular subsystem or property of
Evennia. For example, the "owner" property can be impmemented as a
lock. Or the disability to lift an object or to ban users.
A lock consists of three parts:
- access_type - this defines what kind of access t... |
azure-iot-device/samples/async-hub-scenarios/provision_x509.py | danewalton/azure-iot-sdk-python | 366 | 9592805 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import os
... |
SOFTWARE/A13/PYTHON-A13-GPIO/blink.py | GitHubRepoDescription/OLINUXINO-forked | 880 | 9592846 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# blink.py
#
# Copyright 2013 OLIMEX LTD <<EMAIL>>
#
# 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 2 of the License, or
... |
test/comments/typing5.py | kylebarron/MagicPython | 1,482 | 9592865 | if isinstance(t1, TypeVar): # type: ignore
continue
if : keyword.control.flow.python, source.python
: source.python
isinstance : meta.function-call.python, source.python, support.function.builtin.python
( : meta.function-call.python, punctuation.definition.arguments.begin.... |
tests/openbb_terminal/test_loggers.py | tehcoderer/GamestonkTerminal | 255 | 9592906 | from pathlib import Path
import pytest
from openbb_terminal import loggers
from openbb_terminal.core.log.generation.settings import (
Settings,
AppSettings,
AWSSettings,
LogSettings,
)
settings = Settings(
app_settings=AppSettings(
commit_hash="MOCK_COMMIT_HASH",
name="MOCK_COMMIT_H... |
nncf/torch/quantization/extensions.py | GreenWaves-Technologies/nncf | 136 | 9592914 | """
Copyright (c) 2022 Intel Corporation
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 writin... |
pyunity/errors.py | Knight1632/pyunity | 158 | 9592942 | """Module for all exceptions and warnings related to PyUnity."""
__all__ = ["PyUnityException", "ComponentException",
"GameObjectException"]
class PyUnityException(Exception):
"""Base class for PyUnity exceptions."""
pass
class ComponentException(PyUnityException):
"""Class for PyUni... |
openbox/utils/multi_objective/scalarization.py | Dee-Why/lite-bo | 184 | 9592945 | <reponame>Dee-Why/lite-bo<filename>openbox/utils/multi_objective/scalarization.py
# License: MIT
r"""
Helper utilities for constructing scalarizations adapted from botorch.
References
.. [Knowles2005]
<NAME>, "ParEGO: a hybrid algorithm with on-line landscape approximation
for expensive multiobjective optimi... |
plugins/Operations/Misc/misc_ops.py | nmantani/FileInsight-plugins | 120 | 9592947 | #
# Misc operations - Miscellaneous operations
#
# Copyright (c) 2018, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above c... |
commons.py | janghyuncho/PiCIE | 113 | 9592959 | import os
import numpy as np
import torch
import torch.nn as nn
from sklearn.utils.linear_assignment_ import linear_assignment
from modules import fpn
from utils import *
import warnings
warnings.filterwarnings('ignore')
def get_model_and_optimizer(args, logger):
# Init model
model = fpn.PanopticFPN(ar... |
macro_benchmark/CNN_PyTorch/RN50v1.5/image_classification/training.py | songhappy/ai-matrix | 180 | 9593014 | import os
import time
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from . import logger as log
from . import resnet as models
from . import utils
try:
from apex.parallel import DistributedDataParallel as DDP
from apex.fp16_utils import *
from apex import amp
exc... |
integrations/urlmon/settings.py | frekel/alerta-contrib | 114 | 9593024 | <gh_stars>100-1000
# ENDPOINT = "http://10.0.2.2:8080"
ENDPOINT = "http://localhost:8080"
API_KEY = None
checks = [
{
"resource": "www.google.com",
"url": "http://www.google.com?q=foo#q=foo",
"environment": "Production",
"service": ["Google", "Search"],
"api_endpoint": "htt... |
cogdl/layers/se_layer.py | cenyk1230/cogdl | 1,072 | 9593029 | <gh_stars>1000+
import torch
import torch.nn as nn
class SELayer(nn.Module):
"""Squeeze-and-excitation networks"""
def __init__(self, in_channels, se_channels):
super(SELayer, self).__init__()
self.in_channels = in_channels
self.se_channels = se_channels
self.encoder_decoder... |
src/RelaxedIK/GROOVE/groove.py | ajay5447/relaxed_ik | 133 | 9593061 | from GROOVE_Utils.groove_type import GrooveType_scipy, GrooveType_nlopt
def get_groove(vars, optimization_package='scipy', solver_name='slsqp'):
'''
:param vars: vars object
:param optimization_package: either 'scipy' or 'nlopt'
:param solver_name:
for scipy, options are 'methods' under this re... |
doorbell.py | ridiculousfish/One-Second-Dash | 189 | 9593071 | #!/usr/bin/python
import os
import signal
import subprocess
import sys
import time
# Ignore SIGCHLD
# This will prevent zombies
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
# After ringing, how many seconds before we allow ourselves to ring again
DEBOUNCE_INTERVAL = 7
# The token to look for in tcpdump's output
# T... |
lib-src/lv2/suil/waflib/extras/protoc.py | joshrose/audacity | 7,892 | 9593108 | <gh_stars>1000+
#!/usr/bin/env python
# encoding: utf-8
# <NAME>, 2012
# <NAME>, 2012
import re, os
from waflib.Task import Task
from waflib.TaskGen import extension
from waflib import Errors, Context, Logs
"""
A simple tool to integrate protocol buffers into your build system.
Example for C++:
def configure(co... |
rman_operators/rman_operators_vol_aggregates.py | prman-pixar/RenderManForBlender | 432 | 9593111 | from bpy.props import StringProperty, BoolProperty, EnumProperty, IntProperty, CollectionProperty, PointerProperty
from ..rfb_utils import string_utils
from ..rfb_logger import rfb_log
from ..rfb_utils import shadergraph_utils
from ..rfb_utils import scenegraph_utils
from ..rfb_utils import object_utils
from ..rfb_uti... |
tests/test_06_math/test_609_point_on_line.py | jkjt/ezdxf | 515 | 9593122 | <gh_stars>100-1000
# Copyright (c) 2020 <NAME>
# License: MIT License
import pytest
from ezdxf.math import Vec2, distance_point_line_2d, is_point_on_line_2d
def test_distance_point_horiz_line():
start, end = Vec2(0, 0), Vec2(10, 0)
assert distance_point_line_2d(Vec2(5, 2), start, end) == 2
assert distance... |
ontobio/io/gafgpibridge.py | vanaukenk/ontobio | 101 | 9593132 | <filename>ontobio/io/gafgpibridge.py<gh_stars>100-1000
import json
from typing import Dict, NewType, List
from ontobio.model.association import GoAssociation, gp_type_label_to_curie
class Entity(dict):
def __init__(self, d):
super(Entity, self).__init__(d)
def __hash__(self):
d = json.dumps(... |
airflow/providers/google/cloud/links/bigquery_dts.py | npodewitz/airflow | 8,092 | 9593150 | <filename>airflow/providers/google/cloud/links/bigquery_dts.py
#
# 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... |
utils.py | w4c/language-models-are-knowledge-graphs-pytorch | 113 | 9593151 | import numpy as np
import torch
import re
alphabet = re.compile(r'^[a-zA-Z]+$')
from copy import copy
from collections import defaultdict
def build_graph(matrix):
graph = defaultdict(list)
for idx in range(0, len(matrix)):
for col in range(idx+1, len(matrix)):
graph[idx].append((col, ma... |
bumblebee_status/modules/contrib/battery_upower.py | spxtr/bumblebee-status | 1,089 | 9593166 | # UPowerManger Class Copyright (C) 2017 <NAME> (wogscpar) under MIT licence from upower-python
"""Displays battery status, remaining percentage and charging information.
Parameters:
* battery-upower.warning : Warning threshold in % of remaining charge (defaults to 20)
* battery-upower.critical : Crit... |
confidant/schema/blind_credentials.py | chadwhitacre/confidant | 1,820 | 9593170 | import attr
import toastedmarshmallow
from marshmallow import fields
from confidant.schema.auto_build_schema import AutobuildSchema
@attr.s
class BlindCredentialResponse(object):
id = attr.ib()
name = attr.ib()
cipher_version = attr.ib()
cipher_type = attr.ib()
revision = attr.ib()
enabled = ... |
Lib/test/test_tuple_jy.py | jeff5/jython-whinchat | 577 | 9593189 | <reponame>jeff5/jython-whinchat<filename>Lib/test/test_tuple_jy.py<gh_stars>100-1000
import unittest
from test import test_support
class TupleTestCase(unittest.TestCase):
def test_big_tuple(self):
"""Verify that fairly large collection literals of primitives can be constructed."""
# use \n to sepa... |
src/queues.py | kdcis/PyBitmessage | 1,583 | 9593193 | """Most of the queues used by bitmessage threads are defined here."""
import threading
import time
from six.moves import queue
try:
from multiqueue import MultiQueue
except ImportError:
from .multiqueue import MultiQueue
class ObjectProcessorQueue(queue.Queue):
"""Special queue class using lock for `.t... |
hiitpi/redisclient.py | jingw222/hiitpi | 146 | 9593198 | <reponame>jingw222/hiitpi
import redis
class RedisClient(object):
"""Sets up a Redis database client for data storage and transmission"""
def __init__(self, host, port, db):
self.pool = redis.BlockingConnectionPool(host=host, port=port, db=db)
@property
def conn(self):
if not hasattr... |
bookwyrm/forms/forms.py | mouse-reeve/fedireads | 270 | 9593200 | """ using django model forms """
from django import forms
from django.forms import widgets
from django.utils.translation import gettext_lazy as _
from bookwyrm import models
from bookwyrm.models.user import FeedFilterChoices
from .custom_form import CustomForm
# pylint: disable=missing-class-docstring
class FeedStat... |
TrainingExtensions/tensorflow/test/python/test_cost_calculator.py | Rohan-Chaudhury/aimet | 945 | 9593202 | # /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2019, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification,... |
packages/syft/src/syft/core/store/storeable_object.py | vishalbelsare/PySyft | 8,428 | 9593207 | # stdlib
from typing import Any
from typing import List
from typing import Optional
# third party
from google.protobuf.reflection import GeneratedProtocolMessageType
# syft absolute
import syft as sy
# relative
from ...logger import traceback_and_raise
from ...proto.core.store.store_object_pb2 import StorableObject ... |
eth/db/chain_gaps.py | ggs134/py-evm | 1,641 | 9593218 | import enum
from typing import Iterable, Tuple
from eth_typing import BlockNumber
from eth_utils import (
ValidationError,
to_tuple,
)
from eth.exceptions import GapTrackingCorrupted
from eth.typing import BlockRange, ChainGaps
class GapChange(enum.Enum):
NoChange = enum.auto()
NewGap = enum.auto()
... |
nnunet/dataset_conversion/Task076_Fluo_N3DH_SIM.py | nasyxx/nnUNet | 1,621 | 9593253 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
Lib/fontTools/colorLib/unbuilder.py | gregdavill/fonttools | 38,667 | 9593255 | from fontTools.ttLib.tables import otTables as ot
from .table_builder import TableUnbuilder
def unbuildColrV1(layerV1List, baseGlyphV1List):
unbuilder = LayerV1ListUnbuilder(layerV1List.Paint)
return {
rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint)
for rec in baseGlyphV1List.BaseGlyphV1Recor... |
fomalhaut/settings.py | restran/fomalhaut | 159 | 9593261 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# created by restran on 2015/12/19
from __future__ import unicode_literals, absolute_import
import logging.config
import os
# 当前目录所在路径
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
# 日志所在目录
LOG_PATH = os.path.join(BASE_PATH, 'logs')
HOST = '1... |
classification/training/update/WindowClassificationTrainUpdateModelParam.py | Tessellate-Imaging/Monk_Gui | 129 | 9593267 | <reponame>Tessellate-Imaging/Monk_Gui
import os
import sys
import json
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class WindowClassificationTrainUpdateModelParam(QtWidgets.QWidget):
forward_layer_param = QtCore.pyqtSignal();
forward_analyse_model_list = QtCor... |
sample_factory/envs/doom/wrappers/exploration.py | eles13/sample-factory | 320 | 9593291 | import math
from collections import deque
import numpy as np
import gym
class ExplorationWrapper(gym.Wrapper):
def __init__(self, env):
super().__init__(env)
self.landmarks = deque([], maxlen=200)
self.landmark_threshold = 75.0
def _calc_intrinsic_reward(self, info):
pos = in... |
thrift_tools/printer.py | cbweixin/thrift-tools | 222 | 9593296 | <reponame>cbweixin/thrift-tools<gh_stars>100-1000
from collections import defaultdict, deque, namedtuple
from datetime import datetime
import json
import pprint
import sys
import time
from tabulate import tabulate
import colors
from .stats import percentile
from .idl import parse_idl_file
fromtimestamp = datetime... |
models/match/multiview-simnet/transform.py | ziyoujiyi/PaddleRec | 2,739 | 9593316 | <reponame>ziyoujiyi/PaddleRec
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... |
amadeus/travel/analytics/air_traffic/_busiest_period.py | tsolakoua/amadeus-python | 125 | 9593326 | from amadeus.client.decorator import Decorator
class BusiestPeriod(Decorator, object):
def get(self, **params):
'''
Returns a list of air traffic reports, based on number of travelers.
.. code-block:: python
amadeus.travel.analytics.air_traffic.busiest_period.get(
... |
nuplan/planning/nuboard/base/data_class.py | motional/nuplan-devkit | 128 | 9593347 | from __future__ import annotations
import pathlib
import pickle
from dataclasses import dataclass
from typing import Dict, List, Optional
from nuplan.planning.metrics.metric_dataframe import MetricStatisticsDataFrame
@dataclass
class MetricScenarioKey:
"""Metric key for scenario in nuBoard."""
log_name: st... |
python/tvm/relay/backend/contrib/ethosu/tir/identity.py | shengxinhu/tvm | 4,640 | 9593353 | <reponame>shengxinhu/tvm<gh_stars>1000+
# 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, Vers... |
Scripts/sims4communitylib/utils/sims/common_sim_name_utils.py | ColonolNutty/Sims4CommunityLibrary | 118 | 9593374 | """
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from typing import Tuple
from sims.sim_info import SimInfo... |
Mathematics/Sieve_of_Eratosthenes.py | Amanjakhetiya/Data_Structures_Algorithms_In_Python | 195 | 9593392 | <reponame>Amanjakhetiya/Data_Structures_Algorithms_In_Python
# Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
""" The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is
smaller than 10 million or so """
# funct... |
examples/chaining.py | gselzer/magicgui | 185 | 9593397 | <gh_stars>100-1000
from magicgui import magicgui, widgets
@magicgui(auto_call=True)
def func_a(x: int = 64, y: int = 64):
print("calling func_a")
return x + y
@magicgui(auto_call=True, input={"visible": False, "label": " ", "max": 100000})
def func_b(input: int, mult=1.0):
print("calling func_b")
re... |
VariationalAutoEncoder_with_SELFIES/original/VAE_dependencies/GrammarVAE_codes.py | akshat998/selfies | 367 | 9593409 | import nltk
import pdb
#import zinc_grammar
import numpy as np
import h5py
#import molecule_vae
import GrammarVAE_grammar as zinc_grammar
#f = open('data/250k_rndm_zinc_drugs_clean.smi','r')
#L = []
#
#count = -1
#for line in f:
# line = line.strip()
# L.append(line) # The zinc data set
#f.close()
#
NC... |
orchestra/models/core/models.py | code-review-doctor/orchestra | 444 | 9593424 | <reponame>code-review-doctor/orchestra
from django.conf import settings
from django.db import models
from django.utils import timezone
from djmoney.models.fields import MoneyField
from jsonfield import JSONField
from phonenumber_field.modelfields import PhoneNumberField
from orchestra.models.core.mixins import Certific... |
redun/tests/test_type_registry.py | cclauss/redun | 303 | 9593433 | from enum import Enum
import pytest
from redun import File, Handle, Task, task
from redun.expression import Expression
from redun.task import PartialTask
from redun.utils import pickle_dumps
from redun.value import Bool, ProxyValue, Set, Value, get_type_registry
def test_unbound_method_call():
# Define a custom... |
pylibui/controls/radiobuttons.py | superzazu/pylibui | 222 | 9593456 | """
Python wrapper for libui.
"""
from pylibui import libui
from .control import Control
class RadioButtons(Control):
def __init__(self, items=[]):
"""
Creates a new radio buttons.
"""
super().__init__()
self.control = libui.uiNewRadioButtons()
for item in item... |
plugins/modules/oci_identity_tag_actions.py | slmjy/oci-ansible-collection | 108 | 9593478 | <gh_stars>100-1000
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# Se... |
antlr-python/ChatTests.py | evilkirin/antlr-mega-tutorial | 138 | 9593552 | <reponame>evilkirin/antlr-mega-tutorial
from antlr4 import *
from ChatLexer import ChatLexer
from ChatParser import ChatParser
from HtmlChatListener import HtmlChatListener
from ChatErrorListener import ChatErrorListener
import sys
import unittest
import io
class TestChatParser(unittest.TestCase):
def setup(self,... |
explainaboard/tasks/absa/eval_spec.py | Shadowlized/ExplainaBoard | 255 | 9593562 | # -*- coding: utf-8 -*-
import explainaboard.error_analysis as ea
import explainaboard.data_utils as du
import os
import numpy
def get_aspect_value(sent_list, aspect_list, sample_list_tag, sample_list_tag_pred, dict_aspect_func):
dict_span2aspect_val = {}
dict_span2aspect_val_pred = {}
for aspect, fun in... |
Deprecated/PythonClient/carla/driving_benchmark/__init__.py | AbdulHoffmann/carla_carissma | 204 | 9593587 | from .driving_benchmark import run_driving_benchmark
|
apps/single_stroke.py | AntonBiryukovUofC/diffvg | 488 | 9593592 | <reponame>AntonBiryukovUofC/diffvg<gh_stars>100-1000
import pydiffvg
import torch
import skimage
import numpy as np
# Use GPU if available
pydiffvg.set_use_gpu(torch.cuda.is_available())
canvas_width, canvas_height = 256, 256
num_control_points = torch.tensor([2])
points = torch.tensor([[120.0, 30.0], # base
... |
tests/protein/nodes/features/test_amino_acid.py | jadechip/graphein | 342 | 9593614 | <filename>tests/protein/nodes/features/test_amino_acid.py
"""Tests for graphein.protein.features.nodes.amino_acids
"""
from pandas.testing import assert_series_equal
from graphein.protein.features.nodes.amino_acid import (
expasy_protein_scale,
load_expasy_scales,
)
def test_load_expasy_scale():
"""Examp... |
hfnet/export_predictions.py | maxtomCMU/hfnet | 555 | 9593644 | <gh_stars>100-1000
import numpy as np
import argparse
import yaml
import logging
from pathlib import Path
from tqdm import tqdm
from pprint import pformat
logging.basicConfig(format='[%(asctime)s %(levelname)s] %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
from ... |
wetectron/solver/build.py | akobiisr/wetectron | 332 | 9593662 | # --------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# --------------------------------------------------------
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .lr_scheduler imp... |
experiments/hmdb-51/test_hmdb_rgb.py | 13551132330/I3D-Tensorflow | 119 | 9593677 | <gh_stars>100-1000
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
samples/example_01/basic_01.py | cair/deep-rts | 144 | 9593700 | <gh_stars>100-1000
from DeepRTS import Engine
import cv2
if __name__ == "__main__":
# Minimal example of DeepRTS in python.
# on my machine, the recorded FPS is: 60772
# if you run purely in C++, the number is 4 001 004
num_episodes = 100000
config: Engine.Config = Engine.Config().defaults()
... |
citeomatic/display.py | IntheGrass/citeomatic_learning | 162 | 9593715 | from citeomatic.common import Document
def document_to_bibtex(doc: Document):
"""
Return a BibTeX string for the given document.
:param doc:
:return: str:
"""
authors = doc.authors
if authors:
author_prefix = authors[0].split(' ')[-1].lower()
else:
author_prefix = ''
... |
modules/audio_processing/test/py_quality_assessment/apm_quality_assessment_boxplot.py | wnpllrzodiac/webrtc_code_mirror | 344 | 9593749 | <gh_stars>100-1000
#!/usr/bin/env python
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the f... |
Android/sample/android-app-hook.py | jiaxw32/FridaLib | 106 | 9593758 | #!/usr/bin/python
import frida
import sys
import time
import os
import codecs
def on_message(message, data):
if message['type'] == 'send':
print("[*] {0}".format(message['payload']))
else:
print(message)
def load_js_from_file(js_path):
script_dir = os.path.dirname(os.path.realpath(__file__... |
tacker/conf/vnf_package.py | takahashi-tsc/tacker | 116 | 9593789 | # Copyright (C) 2019 NTT DATA
# 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 ... |
transformations/azerty_qwerty_chars_swap/transformation.py | JerryX1110/NL-Augmenter | 583 | 9593855 | <filename>transformations/azerty_qwerty_chars_swap/transformation.py
import numpy as np
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
class AzertyQwertyCharsSwap(SentenceOperation):
tasks = [TaskType.TEXT_CLASSIFICATION, TaskType.TEXT_TO_TEXT_GENERATION]
langu... |
benchpress/tests/test_packetdrill.py | fakeNetflix/facebook-repo-fbkutils | 346 | 9593856 | #!/usr/bin/env python3
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
i... |
chainer/functions/math/linear_interpolate.py | zaltoprofen/chainer | 3,705 | 9593893 | from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class LinearInterpolate(function_node.FunctionNode):
def check_type_forward(self, in_types):
type_check._argname(in_types, ('p', 'x', 'y'))
p_type, x_type, y_type = i... |
generating/model_wrappers.py | PeganovAnton/transformer-xl | 133 | 9593895 | import math
from typing import List, Dict, Union, Tuple
import torch
import torch.nn.functional as F
import tqdm
from transformers import GPT2LMHeadModel, GPT2Config
from configs.config_types import (
TokenizerWrapperConfig,
ModelWrapperConfig,
TransformerXLWrapperConfig,
GPT2ModelWrapperConfig,
)
fro... |
tests/test_option.py | tobricz/Expression | 135 | 9593915 | <reponame>tobricz/Expression<filename>tests/test_option.py
from typing import Any, Callable, Generator
import pytest
from hypothesis import given
from hypothesis import strategies as st
from expression import Nothing, Option, Some, effect, match, option, pipe, pipe2
from expression.extra.option import pipeline
from t... |
typer-cli-python/source_code_step_4/tests/test_rptodo.py | syberflea/materials | 3,682 | 9593923 | <filename>typer-cli-python/source_code_step_4/tests/test_rptodo.py
from typer.testing import CliRunner
from rptodo import cli, __app_name__, __version__
runner = CliRunner()
def test_version():
result = runner.invoke(cli.app, ["--version"])
assert result.exit_code == 0
assert f"{__app_name__} v{__versio... |
tkinter_examples/button__change_button_icon_on_click/main__next_image_generator__using__itertools_cycle.py | gil9red/SimplePyScripts | 117 | 9593951 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import itertools
import tkinter as tk
root = tk.Tk()
root.geometry('200x200')
CYCLED_IMAGES = itertools.cycle([
tk.PhotoImage(file="icons/ok.png"),
tk.PhotoImage(file="icons/no.png"),
tk.PhotoImage(file="icons/help.png"),
])
def... |
blogger_cli/tests/test_basic.py | Himanshu-singhal-creator/blogger-cli | 427 | 9593970 | import os
import unittest
from click.testing import CliRunner
from blogger_cli.cli import cli
from blogger_cli.tests.messages import BloggerMessage as BM
class TestBasic(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
result = self.runner.invoke(cli, ["addblog", "test1", "-s"])
... |
telemetry/third_party/modulegraph/modulegraph_tests/test_implies.py | tingshao/catapult | 2,151 | 9593984 | <reponame>tingshao/catapult
import unittest
import os, shutil, sys
from modulegraph import modulegraph
class ImpliesTestCase(unittest.TestCase):
if not hasattr(unittest.TestCase, 'assertIsInstance'):
def assertIsInstance(self, object, types, message=None):
self.assertTrue(isinstance(object, t... |
tests/nnapi/specs/V1_2/not_equal_float_nnfw.mod.py | periannath/ONE | 255 | 9594003 | <reponame>periannath/ONE<filename>tests/nnapi/specs/V1_2/not_equal_float_nnfw.mod.py<gh_stars>100-1000
# model
model = Model()
i1 = Input("op1", "TENSOR_FLOAT32", "{3}") # a vector of input
i2 = Input("op2", "TENSOR_FLOAT32", "{3}") # a vector of input
i3 = Output("op3", "TENSOR_BOOL8", "{3}") # a vector of output
mode... |
aws-blog-vpc-toptalkers/bin/flowlogs-counter.py | securityscorecard/aws-big-data-blog | 305 | 9594022 | <gh_stars>100-1000
#!/usr/bin/python2.7
import os
import sys
import fileinput
import shlex
## Index
SRC=3
DST=4
PORT=6
def stream_index():
try:
if os.environ['mapred_input_format_class'] == \
'org.apache.hadoop.mapred.lib.NLineInputFormat' and \
os.environ['mapreduce_task_... |
next/lib/pijemont/tests/test_all.py | erinzm/NEXT-chemistry | 155 | 9594036 | """
Can be run with
cd /path/to/pijemont
py.test
The following command will print sys.stdout
py.test -s
"""
import json, sys, yaml, os
from pprint import pprint
import pytest
from .. import verifier
def verify_yaml(test_name, test):
"""
This function does the actual work of verifying the YAML.... |
disprcnn/structures/calib.py | reinforcementdriving/disprcnn | 191 | 9594055 | import numpy as np
from copy import deepcopy
from warnings import warn
import torch
from disprcnn.utils.kitti_utils import Calibration
class Calib:
def __init__(self, calib: Calibration, image_size):
# assert isinstance(calib, Calibration)
self.calib = calib
self.size = image_size
@... |
corehq/apps/linked_domain/tests/test_update_custom_data_fields.py | akashkj/commcare-hq | 471 | 9594057 | from corehq.apps.custom_data_fields.models import (
CustomDataFieldsDefinition,
CustomDataFieldsProfile,
Field,
)
from corehq.apps.linked_domain.tests.test_linked_apps import BaseLinkedDomainTest
from corehq.apps.linked_domain.updates import update_custom_data_models
from corehq.apps.users.views.mobile.cust... |
migration/migrator/migrations/system/20210130203255_upgrade_git.py | jportorreal00/Submitty | 411 | 9594063 | # upgrade git to 2.28.0 or greater
# https://git-scm.com/docs/git-init/2.28.0
# need the --initial-branch option
# for creating student submission vcs git repositories
import os
def up(config):
os.system("add-apt-repository ppa:git-core/ppa -y")
os.system("apt-get install git -y")
pass
def down(config):
... |
bodymocap/mocap_api.py | realblack0/eft | 241 | 9594090 | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
import numpy as np
from bodymocap.core import constants
from torchvision.transforms import Normalize
from bodymocap.models import hmr, SMPL, SMPLX
from bodymocap.core import config
from bodymocap.utils.imutils import crop,crop_bboxInfo, process_image_bbo... |
tools/reformat.py | dentes-purgo/opacclient | 120 | 9594091 | <filename>tools/reformat.py
#!/usr/bin/python3
# Searches the assets/bibs/ directory and reformat all json files
import json
import os
DIR = 'opacclient/opacapp/src/main/assets/bibs/'
for filename in os.listdir(DIR):
f = os.path.join(DIR, filename)
data = json.load(open(f))
with open(f, 'w') as fp:
... |
PythonAPI/carissma_project/lib/python3.5/site-packages/matplotlib/backends/_gtk3_compat.py | AbdulHoffmann/carla_carissma | 130 | 9594102 | <gh_stars>100-1000
"""
GObject compatibility loader; supports ``gi`` and ``pgi``.
The binding selection rules are as follows:
- if ``gi`` has already been imported, use it; else
- if ``pgi`` has already been imported, use it; else
- if ``gi`` can be imported, use it; else
- if ``pgi`` can be imported, use it; else
- e... |
_cockroachdb-createdb.py | rboixaderg/guillotina | 173 | 9594128 | <filename>_cockroachdb-createdb.py
import asyncpg
import asyncio
async def run():
# Establish a connection to an existing database named "test"
# as a "postgres" user.
conn = await asyncpg.connect("postgresql://root@localhost:26257?sslmode=disable")
# Execute a statement to create a new table.
awa... |
treeio/core/administration/api/handlers.py | Andrea-MariaDB-2/treeio | 242 | 9594145 | # encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
# -*- coding: utf-8 -*-
from __future__ import absolute_import, with_statement
__all__ = ['GroupHandler', 'UserHandler', 'ModuleHandler',
'PerspectiveHandler', 'PageFolderHandler', 'PageHandler'... |
setup.py | robin900/gspread-dataframe | 170 | 9594149 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
import sys
PY3 = sys.version_info >= (3, 0)
with open(os.path.join(os.path.dirname(__file__), 'VERSION'), 'rb') as f:
VERSION = f.read()
if PY3:
VERSION = VERSION.decode('utf8')
VERSION =... |
vampire/data/dataset_readers/semisupervised_text_classification_json.py | SparkJiao/vampire | 177 | 9594166 | <gh_stars>100-1000
import json
import logging
from io import TextIOWrapper
from typing import Dict
import numpy as np
from overrides import overrides
from allennlp.common.checks import ConfigurationError
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers import TextClassificationJsonR... |
packages/pyright-internal/src/tests/samples/protocol16.py | sasano8/pyright | 4,391 | 9594199 | <filename>packages/pyright-internal/src/tests/samples/protocol16.py
# This sample tests that function parameter names match in a protocol.
from typing import Any, Protocol
class Session(Protocol):
def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None:
...
class CoolSession(Protocol):
... |
pytorch/skip_gram.py | lyq628/NLP-Tutorials | 643 | 9594226 | <reponame>lyq628/NLP-Tutorials
from torch import nn
import torch
from torch.nn.functional import cross_entropy,softmax
from utils import Dataset,process_w2v_data
from visual import show_w2v_word_embedding
corpus = [
# numbers
"5 2 4 8 6 2 3 6 4",
"4 8 5 6 9 5 5 6",
"1 1 5 2 3 3 8",
"3 6 9 6 8 7 4 6... |
applications/PoromechanicsApplication/python_scripts/poromechanics_cleaning_utility.py | lkusch/Kratos | 778 | 9594243 | <gh_stars>100-1000
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
import os
def CleanPreviousFiles(problem_path):
file_ending_type = ".post.bin"
CleanPreviousFileType(file_ending_type,problem_path)
file_ending_type = ".post.re... |
examples/dha_example_multiprocessing.py | vishalbelsare/crosscat | 207 | 9594244 | <filename>examples/dha_example_multiprocessing.py
#
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# Lead Developers: <NAME> and <NAME>
# Authors: <NAME>, <NAME>, <NAME>, <NAME>
# Research Leads: <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may n... |
lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py | bytesnake/Enzyme | 427 | 9594264 | <reponame>bytesnake/Enzyme
"""
The LLVM Compiler Infrastructure
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
Sync lldb and related source from a local machine to a remote machine.
This facilitates working on the lldb sourcecode on mu... |
panel/pane/vtk/synchronizable_deserializer.py | datalayer-contrib/holoviz-panel | 1,130 | 9594272 | import json
import zipfile
import vtk
import re
import struct
from .synchronizable_serializer import arrayTypesMapping
METHODS_RENAME = {
"AddTexture": "SetTexture",
"SetUseGradientOpacity": None,
"SetRGBTransferFunction": "SetColor",
}
WRAP_ID_RE = re.compile(r"instance:\${([^}]+)}")
ARRAY_TYPES = {
... |
corr.py | nnmhuy/flownet2-tf | 438 | 9594286 | import tensorflow as tf
import numpy as np
import math
BATCH_SIZE = 8
HEIGHT = 30
WIDTH = 60
CHANNELS = 3
NEIGHBORHOOD_SIZE = 41
MAX_DISPLACEMENT = int(math.ceil(NEIGHBORHOOD_SIZE / 2.0))
STRIDE_2 = 2
assert(STRIDE_2 <= NEIGHBORHOOD_SIZE)
# Define two feature maps
fmA = tf.ones((BATCH_SIZE, HEIGHT, WIDTH, CHANNELS)... |
conceptnet5/language/english.py | tesYolan/conceptnet5 | 2,195 | 9594295 | """
Tools for working with English text.
"""
from .lemmatize import LEMMATIZER
STOPWORDS = [
'the', 'a', 'an'
]
DROP_FIRST = ['to']
def english_filter(tokens):
"""
Given a list of tokens, remove a small list of English stopwords.
"""
non_stopwords = [token for token in tokens if token not in STO... |
xknx/io/udp_client.py | iligiddi/xknx | 179 | 9594353 | """
UDPClient is an abstraction for handling the complete UDP io.
The module is build upon asyncio udp functions.
Due to lame support of UDP multicast within asyncio some special treatment for multicast is necessary.
"""
from __future__ import annotations
import asyncio
import logging
import socket
from sys import pl... |
tests/simple_slice.py | ZYAZP/python2 | 1,062 | 9594354 | print 'meow'[:2]
print 'meow'[2:]
|
applications/detection/ddos/spark/detection_ddos.py | t-umeno/Stream4Flow | 101 | 9594381 | <reponame>t-umeno/Stream4Flow
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2016 <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
# Institute of Computer Science, Masaryk University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... |
torchnlp/ner.py | Yoark/Transformer-Attention | 262 | 9594393 | """
Named Entity Recognition
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
from .common.hparams import HParams
from .data.conll import conll2003_dataset
from .data.nyt import nyt_ingredients_ner_dataset
from .tasks.sequence_tagging impor... |
babi_rnn/summarize_result.py | seominjoon/qrn | 102 | 9594402 | import argparse
import os
import json
from collections import defaultdict
def bool_(string):
if string == 'True':
return True
elif string == 'False':
return False
else:
raise Exception()
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model_name"... |
graphdash/struct/tree.py | NunoEdgarGFlowHub/GraphDash | 306 | 9594404 | # -*- coding: utf-8 -*-
"""
Tree implementation.
"""
class Tree(object):
__slots__ = ['sons', 'parent', 'data', '__factory']
def __init__(self, factory=dict):
self.data = factory()
self.__factory = factory
self.sons = {}
self.parent = None
def create_from_path(self, path... |
examples/nested_procs.py | pycampers/zproc | 106 | 9594408 | """
Demonstration of how to handle nested processes
"""
import zproc
ctx = zproc.Context(wait=True)
print("level0", ctx.state)
ctx.state["msg"] = "hello from level0"
@ctx._process
def child1(state):
print("level1:", state)
state["msg"] = "hello from level1"
ctx = zproc.Context(state.address, wait=True)... |
python/tests/teleporter_test.py | xuyanbo03/lab | 7,407 | 9594438 | # Copyright 2018 Google Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the ho... |
tests/test_simple_x.py | Conflate/elasticpypi | 199 | 9594448 | <reponame>Conflate/elasticpypi
from flask_testing import TestCase
from elasticpypi.api import app
from elasticpypi.config import config
from tests import fixtures
from moto import mock_dynamodb2
from tests import mock_dynamodb_table
TABLE = config['table']
class ElasticPypiTests(TestCase):
def create_app(self):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.