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 |
|---|---|---|---|---|
recipes/Python/511431_Text_File_Searcher/recipe-511431.py | tdiprima/code | 2,023 | 11044699 | import os
def main():
try:
directory = get_directory()
text = get_text()
results = do_search(directory, text)
finish(results)
except:
pass
def get_directory():
while True:
try:
directory = raw_input('Directory: ')
assert os.path.isdir... |
tutorial/20_recipes/007_optuna_callback.py | captain-pool/optuna | 4,950 | 11044707 | """
.. _optuna_callback:
Callback for Study.optimize
===========================
This tutorial showcases how to use & implement Optuna ``Callback`` for :func:`~optuna.study.Study.optimize`.
``Callback`` is called after every evaluation of ``objective``, and
it takes :class:`~optuna.study.Study` and :class:`~optuna.t... |
datasets/deepfashion_datasets.py | nandbhat/dressing-in-order | 172 | 11044719 | <gh_stars>100-1000
import torch.utils.data as data
from PIL import Image
import numpy as np
import cv2
import torchvision.transforms as transforms
import torch
import copy, os, collections
import json
from .human_parse_labels import get_label_map, DF_LABEL, YF_LABEL
import pandas as pd
from utils import pose_utils
TES... |
sleekxmpp/plugins/xep_0242.py | elrond79/SleekXMPP | 499 | 11044743 | <gh_stars>100-1000
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2012 <NAME>, <NAME>
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.plugins import BasePlugin, register_plugin
class XEP_0242(BasePlugin):
name = 'xep_0242'
description = '... |
util/an_build_ext.py | juandesant/astrometry.net | 460 | 11044778 | # This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
from distutils.command.build_ext import build_ext # as _build_py
#from distutils.command import build_ext as _build_ext
from distutils.dep_util import newer_group, newer
from distutils import log
import os
clas... |
plasmapy/analysis/swept_langmuir/helpers.py | seanjunheng2/PlasmaPy | 429 | 11044784 | <filename>plasmapy/analysis/swept_langmuir/helpers.py<gh_stars>100-1000
"""Helper functions for analyzing swept Langmuir traces."""
__all__ = ["check_sweep"]
import astropy.units as u
import numpy as np
def check_sweep(
voltage: np.ndarray,
current: np.ndarray,
strip_units: bool = True,
) -> (np.ndarray,... |
pytools/modules/portscanner/__init__.py | maopucheng/pytools | 757 | 11044792 | '''初始化'''
from .portscanner import PortScanner |
setup.py | rongliang-tech/alpha-mind | 186 | 11044801 | # -*- coding: utf-8 -*-
"""
Created on 2017-4-25
@author: cheng.li
"""
import io
from setuptools import setup
from setuptools import find_packages
VERSION = "0.3.1"
setup(
name='Alpha-Mind',
version=VERSION,
packages=find_packages(),
url='',
license='MIT',
author='wegamekinglc',
author_e... |
hypernets/tabular/collinearity.py | Enpen/Hypernets | 1,080 | 11044814 | <gh_stars>1000+
# -*- coding:utf-8 -*-
"""
Adapted from https://scikit-learn.org/stable/auto_examples/inspection/plot_permutation_importance_multicollinear.html
handling multicollinearity is by performing hierarchical clustering on the features’ Spearman
rank-order correlations, picking a threshold, and keeping a singl... |
learnpy_ecourse/class3/ex2_as_path_processing.py | fallenfuzz/pynet | 528 | 11044864 | #!/usr/bin/env python
'''
Disclaimer - This is a solution to the below problem given the content we have
discussed in class. It is not necessarily the best solution to the problem.
In other words, I only use things we have covered up to this point in the class
(with some minor exceptions).
Python for Network Engine... |
tools/polly/bin/detail/target.py | Kondr11/LABA7 | 861 | 11044870 | <gh_stars>100-1000
# Copyright (c) 2015, <NAME>
# All rights reserved.
import sys
class Target:
def __init__(self):
self.name = ''
def add(self, condition, name):
if not condition:
return
if not name:
sys.exit('No name for target')
if not self.name:
self.name = name
return... |
cbl/template_type.py | Commodoreprime/Command-Block-Assembly | 223 | 11044884 | <reponame>Commodoreprime/Command-Block-Assembly
import contextlib
from .native_type import NativeType
from .struct_type import StructuredType
from .function_type import Invokable, FunctionType, IntrinsicCallable
from .containers import Temporary
class TemplatedType(NativeType):
def __init__(self, params, parent,... |
fhir/resources/DSTU2/diagnosticorder.py | cstoltze/fhir.resources | 144 | 11044936 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/DiagnosticReport
Release: DSTU2
Version: 1.0.2
Revision: 7202
"""
from typing import List as ListType
from pydantic import Field
from . import fhirtypes
from .backboneelement import BackboneElement
from .domainresource imp... |
main.py | americast/mtrl | 129 | 11044943 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""This is the main entry point for the code."""
import hydra
from mtrl.app.run import run
from mtrl.utils import config as config_utils
from mtrl.utils.types import ConfigType
@hydra.main(config_path="config", config_name="config")
def launch(... |
archive/genut/modules/enc/rnn_enc.py | jennhu/vmf_vae_nlp | 159 | 11044956 | import unittest
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as Var
class RNNEncoder(nn.Module):
def __init__(self, opt, input_size, hidden_size, rnn_type='lstm'):
super(RNNEncoder, self).__init__()
# RNN Init
self.n_layers = opt.... |
webui_alternative/server/chatservice.py | puneet739/ChatLearner | 590 | 11044958 | <reponame>puneet739/ChatLearner<gh_stars>100-1000
# Copyright 2017 <NAME>. 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-... |
examples/tk_widget.py | pzahemszky/guizero | 320 | 11044963 | from guizero import App, Box, Text
from tkinter import Spinbox
from tkinter.ttk import Progressbar
app = App(title="Using tk widgets")
Text(app, text="Spinbox")
# add a spinbox widget to the app
sp = Spinbox(from_=0, to=10)
app.add_tk_widget(sp)
Text(app, text="and Progressbar")
box = Box(app, border=True)
# add ... |
runtime/space/slices.py | cheery/lever | 136 | 11044972 | from builtin import signature
from interface import Object, null
from rpython.rlib.objectmodel import compute_hash
from rpython.rlib.rarithmetic import intmask
import space
class Slice(Object):
_immutable_fields_ = ['start', 'stop', 'step']
__slots__ = ['start', 'stop', 'step']
def __init__(self, start, s... |
stores/apps/core/storage.py | diassor/CollectorCity-Market-Place | 135 | 11045019 | from django.conf import settings
from django.core.files.storage import get_storage_class
from storages.backends.s3boto import S3BotoStorage
STATIC_STORAGE_BUCKET_NAME=getattr(settings, 'AWS_STATIC_BUCKET_NAME', None)
class CachedS3BotoStorage(S3BotoStorage):
"""
S3 storage backend that saves the files locall... |
recipes/Python/501151_Generating_combinations/recipe-501151.py | tdiprima/code | 2,023 | 11045057 | <reponame>tdiprima/code<gh_stars>1000+
from itertools import islice, repeat, izip, cycle
# If PEP 3102 is accepted, the signature would be
#def iterCombinations(*iterables, blocksize=1):
def iterCombinations(*iterables, **kwds):
'''Generates the combinations of the given iterables.
@returns: An iterator o... |
tests/test_backend.py | cnord/pypiserver | 1,257 | 11045067 | <filename>tests/test_backend.py
from pathlib import Path
import pytest
from pypiserver.backend import listdir
def create_path(root: Path, path: Path):
if path.is_absolute():
raise ValueError(
"Only test using relative paths"
" to prevent leaking outside test environment"
... |
dirscan/dirsearch/lib/connection/__init__.py | imfiver/Sec-Tools | 144 | 11045075 | <filename>dirscan/dirsearch/lib/connection/__init__.py<gh_stars>100-1000
from .request_exception import * # noqa: F401
from .requester import * # noqa: F401
from .response import * # noqa: F401
|
napari/_qt/widgets/_slider_compat.py | MaksHess/napari | 1,345 | 11045101 | from qtpy import QT_VERSION
from qtpy.QtWidgets import QSlider # noqa
from superqt import QDoubleSlider
# here until we can debug why labeled sliders render differently on 5.12
if tuple(int(x) for x in QT_VERSION.split(".")) >= (5, 14):
from superqt import QLabeledDoubleSlider as QDoubleSlider # noqa
from su... |
flink-ml-python/pyflink/ml/tests/test_pipeline.py | yunfengzhou-hub/flink-ml | 142 | 11045116 | <reponame>yunfengzhou-hub/flink-ml<filename>flink-ml-python/pyflink/ml/tests/test_pipeline.py
################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with... |
src/tests/web/server_test.py | tomgilbertson/script-server-v1 | 833 | 11045141 | import json
import os
import threading
import traceback
from asyncio import set_event_loop_policy
from unittest import TestCase
from unittest.mock import patch, MagicMock
import requests
from parameterized import parameterized
from tornado.ioloop import IOLoop
from tornado.web import create_signed_value
from auth.aut... |
tests/test_vim_session_oriented_stub.py | zhgcao/pyvmomi | 1,894 | 11045162 | import tests
from pyVim import connect
class SoapAdapterTests(tests.VCRTestBase):
def test_invoke_method_login_session_exception(self):
def login_fail(*args, **kwargs):
raise vim_session.SESSION_EXCEPTIONS[0]()
stub = connect.SoapStubAdapter()
vim_session = connect.VimSession... |
test/cts/tool/CTSConverter/src/nn/specs/V1_0/avg_pool_quant8_4.mod.py | zhaoming0/webml-polyfill | 255 | 11045176 | <gh_stars>100-1000
#
# Copyright (C) 2017 The Android Open Source Project
#
# 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 requir... |
tests/zzz_deprecated_unmaintained/allocmodel/topics/MakeLscorePlots.py | jun2tong/bnp-anomaly | 184 | 11045208 | <gh_stars>100-1000
import os
import numpy as np
import glob
from bnpy.viz import PlotUtil
pylab = PlotUtil.pylab
PlotUtil.ConfigPylabDefaults(pylab)
def makeLscorePlots():
# Load all by name
fNames = glob.glob("Lscore*.txt")
JMap = dict()
JNone = dict()
JByBeta = dict()
for fName in fNames:
shortName = fName.... |
ir_datasets/indices/numpy_sorted_index.py | seanmacavaney/ir_datasets | 149 | 11045228 | <gh_stars>100-1000
import os
import ir_datasets
class NumpySortedIndex:
def __init__(self, path):
self.path = path
self.transaction = None
self.mmap_keys = None
self.mmap_poss = None
self.doccount = None
self.keylen = None
self.np = None
def add(self, k... |
tests/python/cuda/test_sampler.py | jakeKonrad/torch-quiver | 196 | 11045237 | import torch
import numpy as np
import scipy.sparse as sp
import torch_quiver as qv
import time
from ogb.nodeproppred import Evaluator, PygNodePropPredDataset
from scipy.sparse import csr_matrix
import os
import os.path as osp
import quiver
import torch.multiprocessing as mp
from multiprocessing.reduction import Forki... |
tutorial/3.CoupCons3D/plot.py | tenglongcong/amgcl | 504 | 11045256 | #!/usr/bin/env python
from pylab import *
from scipy.io import mmread
A = mmread('CoupCons3D.mtx')
fig, (ax1, ax2) = subplots(2, 1, sharex=True, figsize=(8,10), gridspec_kw=dict(height_ratios=[4,1]))
ax1.spy(A, marker='.', markersize=0.25, alpha=0.2)
zn = 60
x1 = 147071.5
y1 = 63711.5
x2 = 333407.5
y2 = 333407.5
a... |
app/lib/dns/alias_manager.py | grepleria/SnitchDNS | 152 | 11045293 | from app.lib.models.aliases import AliasModel
from app.lib.dns.instances.alias import Alias
from app.lib.dns.helpers.shared import SharedHelper
from sqlalchemy import desc, asc
class AliasManager(SharedHelper):
def __get(self, id=None, user_id=None, ip=None, name=None, order_column=None, order_by=None):
q... |
tests/text/question_answering/test_model.py | Actis92/lightning-flash | 1,457 | 11045330 | # 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... |
examples/rl/scripts/design-2/train.py | ONLYA/RoboGrammar | 156 | 11045335 | <reponame>ONLYA/RoboGrammar
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--save-dir', type = str, default = './trained_models/RobotLocomotion-v0/design-2/')
args = parser.parse_args()
cmd = 'python train/train.py --rule-sequence 0, 6, 20, 14, 2, 18, 10, 4, 21, 5, 9, 4, 19, 10, 11... |
lib/python/parallels_send_key.py | ibizaman/veewee | 1,295 | 11045340 | <reponame>ibizaman/veewee<filename>lib/python/parallels_send_key.py
import sys
import prlsdkapi
if len(sys.argv) != 4:
print "Usage: parallels_send_keycode '<VM_NAME>' '<keyname>' '<press|release>'"
exit()
# Parse arguments
vm_name=sys.argv[1]
# Keycode to use
keyname=sys.argv[2]
# Release or press
state=sys.... |
problems/19/problem_19.py | r1cc4rdo/daily_coding_problem | 158 | 11045370 | <reponame>r1cc4rdo/daily_coding_problem
def coding_problem_19(house_costs):
"""
A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost
while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row an... |
dictionary_graph/schema.py | ankitgc1/django-sozluk-master | 248 | 11045411 | <filename>dictionary_graph/schema.py
from graphene import Field, ObjectType, Schema
from .autocomplete import AutoCompleteQueries
from .category import CategoryMutations
from .entry import EntryMutations, EntryQueries
from .images import ImageMutations
from .messaging import MessageMutations
from .topic import TopicMu... |
tests/unit/test_parser.py | chadell/yangify | 109 | 11045415 | <gh_stars>100-1000
import pathlib
from typing import Any, Dict, Iterator, Tuple, cast
from yangify import parser
from yangson.datamodel import DataModel
BASE = pathlib.Path(__file__).parent
dm = DataModel.from_file(
f"{BASE}/yang/simple/yang-library-data.json", [f"{BASE}/yang/simple/"]
)
test_data = {
"el... |
gpMgmt/bin/gppylib/commands/test/unit/test_unit_base.py | shalamovivan/gpdb | 5,535 | 11045474 | #!/usr/bin/env python3
#
# Copyright (c) Greenplum Inc 2012. All Rights Reserved.
#
import unittest
from gppylib.commands.base import Command, WorkerPool, RemoteExecutionContext, GPHOME, LocalExecutionContext,\
set_cmd_results
class WorkerPoolTestCase(unittest.TestCase):
def tearDown(self):
Command.... |
mj_envs/__init__.py | AllanYangZhou/mj_envs | 102 | 11045526 | import mj_envs.hand_manipulation_suite |
tests/test_visitors/test_ast/test_subscripts/test_slice_assignment.py | cdhiraj40/wemake-python-styleguide | 1,931 | 11045529 | <reponame>cdhiraj40/wemake-python-styleguide
import pytest
from wemake_python_styleguide.violations.consistency import (
AssignToSliceViolation,
)
from wemake_python_styleguide.visitors.ast.subscripts import SubscriptVisitor
usage_template = 'constant[{0}] = [1, 2, 3]'
@pytest.mark.parametrize('expression', [
... |
www-emu/demo_gen.py | isabella232/micropython-unicorn | 124 | 11045546 | import sys
import os
outfile = open('demo_scripts.js', 'w')
for filename in os.listdir():
if filename[-9:] == '_demos.py':
infile = open(filename, 'r')
outfile.write('var ' + filename[:-9] + '_demos = new Map([["CHOOSE A DEMO...", "# Welcome to MicroPython on Unicorn!\\n\\n# The terminal beside thi... |
sleekxmpp/plugins/xep_0084/__init__.py | E-Tahta/sleekxmpp | 499 | 11045550 | <filename>sleekxmpp/plugins/xep_0084/__init__.py
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2012 <NAME>, <NAME>
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.plugins.base import register_plugin
from sleekxmpp.plugins.xep_0084 import stanza
fr... |
problems/string-permutations/string-permutations.py | vidyadeepa/the-coding-interview | 1,571 | 11045600 | import itertools
def permutations(word):
if len(word) < 2:
return word
all_perms = []
for i, start in enumerate(word):
rest = word[:i] + word[i+1:]
curr_perms = [start + p for p in permutations(rest)]
all_perms.extend(curr_perms)
return all_perms
word = "m<PASSWORD>"
# Lazy itertools versio... |
Scripts/Tests/list-available-webhook-events.py | mgreisen/rest-api-fuzz-testing | 246 | 11045605 | <gh_stars>100-1000
import argparse
import json
import os
import pathlib
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),'..', '..', 'cli'))
import raft
from raft_sdk.raft_service import RaftCLI
from raft_sdk.raft_common import RaftJsonDict
def compare_lists(cli):
expected = ['Jo... |
hata/ext/slash/menus/pagination.py | Multiface24111/hata | 173 | 11045617 | __all__ = ('Pagination', )
from ....backend.futures import CancelledError
from ....discord.interaction import ComponentButton, ComponentRow
from .menu import Menu
from .helpers import EMOJI_LEFT_2, EMOJI_LEFT, EMOJI_RIGHT, EMOJI_RIGHT_2, EMOJI_CANCEL, get_auto_check, \
CUSTOM_ID_CANCEL, top_level_check, top_level... |
lfw_aegan.py | Vicent-xd/Residual_autoencoding | 432 | 11045643 | #!/usr/bin/env python
import os
import pickle
import numpy as np
import dataset.lfw
import aegan
def run():
experiment_name = 'lfw'
img_size = 64
epoch_size = 250
batch_size = 64
np.random.seed(1)
train_feed, test_feed = dataset.lfw.feeds(
alignment='landmarks', crop_size=150, resca... |
static/scripts/convertSchema.py | madumlao/gluu-community-edition-setup | 178 | 11045655 | <filename>static/scripts/convertSchema.py<gh_stars>100-1000
#!/usr/bin/env python
"""Script to convert OpenDJ LDIF Schema file to a OpenLDAP *.schema file
"""
import re
org_oid = '1.3.6.1.4.1.48710'
reserved = org_oid + '.0'
published = org_oid + '.1'
# The OID strcturing is copied from the OpenLDAP Project
# Refere... |
bind9/tests/conftest.py | divyamamgai/integrations-extras | 158 | 11045666 | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import mock
import pytest
from .common import HERE, URL
@pytest.fixture(scope='session', autouse=True)
def mock_requests():
with open(os.path.join(HERE, 'fixtures', 'sample_stats.xml'), 'r') as f... |
kaldi/steps/nnet3/xconfig_to_config.py | ishine/asv-subtools | 370 | 11045674 | #!/usr/bin/env python3
# Copyright 2016-2018 Johns Hopkins University (<NAME>)
# 2016 <NAME>
# 2017 Google Inc. (<EMAIL>)
# Apache 2.0.
# This is like xconfig_to_configs.py but with a simpler interface; it writes
# to a single named file.
import argparse
import os
import sys
from collec... |
platypush/plugins/google/maps/__init__.py | BlackLight/platypush | 228 | 11045708 | <reponame>BlackLight/platypush
"""
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from datetime import datetime
from typing import List, Union, Optional
import requests
from platypush.plugins import action
from platypush.plugins.google import GooglePlugin
from platypush.schemas.maps import MapsTravelTimeSchema
from platypus... |
examples/src/dbnd_examples/tests/documentation/orchestration/spark_integration/test_doc_spark_task_configuration.py | busunkim96/dbnd | 224 | 11045712 | <filename>examples/src/dbnd_examples/tests/documentation/orchestration/spark_integration/test_doc_spark_task_configuration.py<gh_stars>100-1000
#### DOC START
from dbnd import output, parameter
from dbnd_spark import SparkTask
class WordCountTask(SparkTask):
text = parameter.data
counters = output
spark_... |
recipes/Python/159462_How_to_Set_Environment_Variables/recipe-159462.py | tdiprima/code | 2,023 | 11045716 | setvar.bat
----------
@echo off
python setvarp.py %1 %2 %3 %4 %5 %6 %7 %8 %9
settmp
del settmp.bat
setvarp.py
----------
import sys, time, math
key = sys.argv[1]
value = eval(' '.join(sys.argv[2:]))
command = 'set %s=%s\n' % (key, value)
open('settmp.bat', 'w').write(command)
sample command line session
------------... |
tools/regraph/launch.py | dmsteck/Fusion360GalleryDataset | 193 | 11045749 | <gh_stars>100-1000
"""
Autmatically run regraph_exporter.py
and handle relaunching Fusion 360 if necessary
Requires regraph_exporter to be set to Run On Startup
inside of Fusion 360
"""
import os
import sys
from pathlib import Path
import subprocess
import json
import time
# Add the common folder to sys.path
COMMO... |
src/pretalx/common/console.py | lili668668/pretalx | 418 | 11045757 | <reponame>lili668668/pretalx<filename>src/pretalx/common/console.py
BOLD = "\033[1m"
RESET = "\033[0m"
UD = "│"
LR = "─"
SEPARATORS = {
(False, True, True, False): "┬",
(True, False, False, True): "┴",
(False, False, True, True): "┤",
(True, True, False, False): "├",
(False, True, False, True): "┼",... |
examples/streaming/helloworld_grpc.py | artificial-aidan/grpclib | 754 | 11045785 | <reponame>artificial-aidan/grpclib
# Generated by the Protocol Buffers compiler. DO NOT EDIT!
# source: streaming/helloworld.proto
# plugin: grpclib.plugin.main
import abc
import typing
import grpclib.const
import grpclib.client
if typing.TYPE_CHECKING:
import grpclib.server
import streaming.helloworld_pb2
clas... |
bindings/python/cntk/contrib/crosstalkcaffe/validation/validcore.py | shyamalschandra/CNTK | 17,702 | 11045801 | <gh_stars>1000+
# ==============================================================================
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ===================================================================... |
odmantic/reference.py | dynalz/odmantic | 486 | 11045804 | from typing import Any, Optional
def Reference(*, key_name: Optional[str] = None) -> Any:
"""Used to define reference fields.
Args:
key_name: name of the Mongo key that stores the foreign key
<!--
#noqa: DAR201
-->
"""
return ODMReferenceInfo(key_name=key_name)
class ODMReferen... |
examples/bluetooth/nimble/blecent/blecent_test.py | lovyan03/esp-idf | 8,747 | 11045805 | <filename>examples/bluetooth/nimble/blecent/blecent_test.py
#!/usr/bin/env python
#
# Copyright 2019 Espressif Systems (Shanghai) PTE LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... |
plugins/suspicious_names/plugin.py | 4k4xs4pH1r3/flashmingo | 124 | 11045834 | # coding: utf-8
# Copyright(C) 2019 FireEye, Inc. All Rights Reserved.
#
# FLASHMINGO! Plugin
# Find suspicious names
import os
import logging
import logging.handlers
class Plugin:
"""
"""
def __init__(self, swf=None, ml=None, names=[]):
self.swf = swf
self.user_names = names
if... |
pypy/tool/ann_override.py | nanjekyejoannah/pypy | 381 | 11045932 | <reponame>nanjekyejoannah/pypy<gh_stars>100-1000
# overrides for annotation specific to PyPy codebase
from rpython.annotator.policy import AnnotatorPolicy
from rpython.flowspace.model import Constant
from rpython.annotator.classdesc import InstanceSource
class PyPyAnnotatorPolicy(AnnotatorPolicy):
def __init__(se... |
examples/ml-audio-content-profiling/perspective_api_function/main.py | ruchirjain86/professional-services | 2,116 | 11045961 | #!/usr/bin/env python3
# Copyright 2019 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.0
#
# Unless required by applicable law o... |
terracotta/handlers/metadata.py | vlro/terracotta | 448 | 11045978 | <filename>terracotta/handlers/metadata.py
"""handlers/metadata.py
Handle /metadata API endpoint.
"""
from typing import Mapping, Sequence, Dict, Any, Union
from collections import OrderedDict
from terracotta import get_settings, get_driver
from terracotta.profile import trace
@trace('metadata_handler')
def metadat... |
label_studio/projects/migrations/0004_auto_20210306_0506.py | mehdibenamorr/label-studio | 8,264 | 11045988 | <gh_stars>1000+
# Generated by Django 3.1.4 on 2021-03-06 05:06
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0003_project_color'),
]
operations = [
migrations.RemoveField(
model_n... |
server/server/test/sync_test.py | yinengp/jianshi | 2,127 | 11046038 | <filename>server/server/test/sync_test.py
#!/usr/bin/python
# coding: utf-8
import server.logic.sync as logic_sync
import time
def test_sync_log():
log_items = [
{
'event_name': 'home_page_impression',
'page_source': None,
'time_created': int(time.time())
},
... |
lib/python/batch_sim/scoring_functions/__init__.py | leozz37/makani | 1,178 | 11046061 | # Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
examples/add_new_modality.py | akolobov/robomimic | 107 | 11046080 | <reponame>akolobov/robomimic
"""
A simple example showing how to add custom observation modalities, and custom
observation networks (EncoderCore, ObservationRandomizer, etc.) as well.
We also show how to use your custom classes directly in a config, and link them to
your environment's observations
"""
import numpy as ... |
packages/opal-common/opal_common/opa/tests/paths_test.py | permitio/opal | 106 | 11046088 | import os
import sys
import pytest
# Add root opal dir to use local src as package for tests (i.e, no need for python -m pytest)
root_dir = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
os.path.pardir,
os.path.pardir,
os.path.pardir,
)
)
sys.path.append(root_dir)
f... |
setup.py | solarkraft/rsocks | 125 | 11046107 | from setuptools import setup, find_packages
with open('README.rst') as readme:
long_description = ''.join(readme).strip()
setup(
name='rsocks',
version='0.3.3',
author='<NAME>',
author_email='<EMAIL>',
description='A SOCKS reverse proxy server.',
long_description=long_description,
ur... |
python/appdash/recorder.py | gururajrkatti/appdash | 1,794 | 11046135 | <filename>python/appdash/recorder.py
import event
import itertools
from spanid import SpanID, Annotation
from basictracer import BasicTracer, SpanRecorder
def create_new_tracer(collector, sampler=None):
"""create_new_tracer creates a new appdash opentracing tracer using an Appdash collector.
"""
return Bas... |
alipay/aop/api/response/AlipayOpenMiniAmpeSceneQueryResponse.py | antopen/alipay-sdk-python-all | 213 | 11046157 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.AmpeSceneResponse import AmpeSceneResponse
class AlipayOpenMiniAmpeSceneQueryResponse(AlipayResponse):
def __init__(self):
super(Alipa... |
codechef/march18a/gcdcnt-gen.py | Ashindustry007/competitive-programming | 506 | 11046167 | <filename>codechef/march18a/gcdcnt-gen.py
#!/usr/bin/env python2
import random
n = random.randint(1, 100)
q = random.randint(1, 100)
print n
print ' '.join([str(random.randint(1, 100000)) for _ in range(n)])
print q
for _ in range(q):
t = random.randint(1, 2)
if t == 1:
x = random.randint(1, n)
... |
packages/pyright-internal/src/tests/samples/tryExcept5.py | sasano8/pyright | 4,391 | 11046194 | # This sample tests a try statement with no except clauses
# but a finally clause.
from typing import Any
import asyncio
class MyJob:
async def do_stuff(self):
try:
while True:
await asyncio.sleep(1)
my_var = 3
finally:
# This should generat... |
text-image-search/src/python/embedding.py | appotry/sample-apps | 167 | 11046208 | import os
import glob
import ntpath
from collections import Counter
from vespa.package import ApplicationPackage, Field, HNSW, RankProfile, QueryTypeField
import torch
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import clip
from tenacity import retry, wait_exponential, stop_after_attempt
imp... |
deep-rl/lib/python2.7/site-packages/OpenGL/raw/GL/SGIS/fog_function.py | ShujaKhalid/deep-rl | 210 | 11046211 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... |
__scraping__/translate.google.com/main.py | whitmans-max/python-examples | 140 | 11046234 |
#
# https://stackoverflow.com/a/47706550/1832058
#
from selenium import webdriver
import time
driver = webdriver.Chrome("E:\Tutorial\Driver\chromedriver.exe")
words = ['girl', 'cat', 'dog', 'bird', 'man']
for word in words:
driver.get("https://translate.google.com.eg/?hl=en&tab=wT#en/fr/" + word)
time.sleep... |
py/kubeflow/kubeflow/ci/notebook_servers/notebook_server_jupyter_tensorflow_tests_runner.py | phvalguima/kubeflow | 9,272 | 11046240 | <filename>py/kubeflow/kubeflow/ci/notebook_servers/notebook_server_jupyter_tensorflow_tests_runner.py
# This file is only intended for development purposes
from kubeflow.kubeflow.ci import base_runner
base_runner.main(component_name="notebook_servers.notebook_server_jupyter_tensorflow_tests",
workflow... |
Mariana/costs.py | tariqdaouda/Mariana | 182 | 11046247 | import theano
import theano.tensor as tt
import Mariana.abstraction as MABS
__all__ = ["Cost_ABC", "Null", "NegativeLogLikelihood", "MeanSquaredError", "CrossEntropy", "CategoricalCrossEntropy", "BinaryCrossEntropy"]
class Cost_ABC(MABS.UntrainableAbstraction_ABC, MABS.Apply_ABC) :
"""This is the interface a Cost... |
dialogue-engine/test/programytest/parser/template/node_tests/test_json.py | cotobadesign/cotoba-agent-oss | 104 | 11046266 | <reponame>cotobadesign/cotoba-agent-oss
"""
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 without limitation
the rights to u... |
ovc5/firmware/sandbox/blink/nmigen/blink.py | alexvonduar/ovc | 174 | 11046268 | from nmigen import *
class Blink(Elaboratable):
def __init__(self):
self.led = Signal()
def elaborate(self, platform):
m = Module()
counter = Signal(24)
m.d.comb += self.led.eq(counter[23])
m.d.sync += counter.eq(counter + 1)
return m
|
ali_speech/constant.py | MatYoshr/alibabacloud-nls-python-sdk | 234 | 11046271 | <reponame>MatYoshr/alibabacloud-nls-python-sdk<filename>ali_speech/constant.py
# -*- coding: utf-8 -*-
"""
* Copyright 2015 Alibaba Group Holding 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 o... |
test/test_custom/test_defaults-location.py | willoucom/nginx-proxy | 12,930 | 11046313 | import pytest
def test_custom_default_conf_does_not_apply_to_unknown_vhost(docker_compose, nginxproxy):
r = nginxproxy.get("http://nginx-proxy/")
assert r.status_code == 503
assert "X-test" not in r.headers
def test_custom_default_conf_applies_to_web1(docker_compose, nginxproxy):
r = nginxproxy.get("h... |
src/anafora/projectSetting.py | weitechen/anafora | 232 | 11046328 | <filename>src/anafora/projectSetting.py
#!/usr/bin/python2.7
import sys, os
from xml.dom.minidom import parseString, Element
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
import itertools
class ProjectSetting(object):
def __init__(self):
"""
@type projectList: dict of ... |
paas-ce/paas/paas/esb/bkcore/migrations/0001_initial.py | renmcc/bk-PaaS | 767 | 11046337 | <filename>paas-ce/paas/paas/esb/bkcore/migrations/0001_initial.py
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the M... |
Paddle_Enterprise_CaseBook/meter_reader/reader_infer.py | wwhio/awesome-DeepLearning | 3,655 | 11046340 | <reponame>wwhio/awesome-DeepLearning
# coding: utf8
# Copyright (c) 2021 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.or... |
Python-3/queue_module/priority_queue_example.py | ghiloufibelgacem/jornaldev | 1,139 | 11046358 | <filename>Python-3/queue_module/priority_queue_example.py<gh_stars>1000+
import queue
q = queue.PriorityQueue()
q.put((1, 'A'))
q.put((3, 'B'))
q.put((2, 'C'))
for i in range(q.qsize()):
print(q.get())
|
src/genie/libs/parser/ios/tests/ShowIpNatTranslations/cli/equal/golden_output_expected.py | balmasea/genieparser | 204 | 11046385 | <gh_stars>100-1000
expected_output = {
"vrf": {
"default": {
"index": {
1: {
"inside_global": "192.168.1.1:514",
"inside_local": "192.168.2.3:53",
"outside_global": "192.168.2.22:256",
"outside_local"... |
pycalphad/core/light_dataset.py | amkrajewski/pycalphad | 162 | 11046408 | <reponame>amkrajewski/pycalphad<filename>pycalphad/core/light_dataset.py
"""Defines a class for internally representing arrays used in equilibrium calculations"""
import numpy as np
from xarray import Dataset
class LightDataset:
"""
Lightweight wrapper around an xarray Dataset.
Attributes
----------... |
src/radish/extensions/timer.py | radish-bdd/radish2 | 182 | 11046422 | <reponame>radish-bdd/radish2
"""
radish
~~~~~~
The root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by <NAME> <<EMAIL>>
:license: MIT, see LICENSE for more details.
"""
from radish.models.timed import Timed
from radish.hookregistry import before, after
def record_starttime(timed_model: Timed):
... |
tests/test_eval.py | jimfhahn/Annif | 121 | 11046425 | <reponame>jimfhahn/Annif<filename>tests/test_eval.py
"""Unit tests for evaluation metrics in Annif"""
import numpy as np
import annif.corpus
import annif.eval
import annif.suggestion
def test_filter_pred_top_k():
pred = np.array([[0, 1, 3, 2], [1, 4, 3, 0]])
filtered = annif.eval.filter_pred_top_k(pred, 2)
... |
tests/test_diff.py | jsoref/lint-review | 271 | 11046428 | import re
from unittest import TestCase
from mock import patch
from . import load_fixture, create_pull_files
from lintreview.diff import DiffCollection, Diff, parse_diff, ParseError
class TestDiffCollection(TestCase):
# Single file, single commit
one_file = load_fixture('diff/one_file_pull_request.txt')
... |
mmdet/core/mask/grid_target.py | Pandinosaurus/Grid-R-CNN | 272 | 11046432 | import torch
import numpy as np
import mmcv
def reduce_vision(x,mask_size):
quater_size = mask_size // 4
base = ((0,quater_size*2),(quater_size,quater_size*3),(quater_size*2,quater_size*4))
layers = [x[:,i:i+1][:,:,base[i%3][0]:base[i%3][1],base[i//3][0]:base[i//3][1]] for i in range(9)]
layers = torch... |
PyTorch/nets/commons.py | edgecm/FUnIE-GAN-1 | 267 | 11046564 | """
> Common/standard network archutectures and modules
> Credit for some functions
* github.com/eriklindernoren/PyTorch-GAN
* pluralsight.com/guides/artistic-neural-style-transfer-with-pytorch
> Maintainer: https://github.com/xahidbuffon
"""
import torch
import torch.nn as nn
from torchvision import models
... |
virtual/lib/python3.6/site-packages/timezone_field/forms.py | lorrainekamanda/NewsRestApi | 263 | 11046576 | <reponame>lorrainekamanda/NewsRestApi
import pytz
from django.core.exceptions import ValidationError
from django import forms
from timezone_field.choices import standard, with_gmt_offset
def coerce_to_pytz(val):
try:
return pytz.timezone(val)
except pytz.UnknownTimeZoneError:
raise Validation... |
tests/bug_fixes/test_alias_to_constructor_skipped.py | wetgi/lagom | 109 | 11046602 | """
https://github.com/meadsteve/lagom/issues/150
"""
from lagom import Container
class Something:
def __init__(self, value="the default"):
self.value = value
class SomethingInterface:
value: str
def test_an_alias_doesnt_skip_a_defined_constructor():
container = Container()
container[Somet... |
astroML/linear_model/linear_regression_errors.py | astroML/astroML | 735 | 11046607 | <gh_stars>100-1000
import numpy as np
import warnings
try:
import pymc3 as pm
import theano.tensor as tt
from distutils.version import LooseVersion
PYMC_LT_39 = LooseVersion(pm.__version__) < LooseVersion("3.9")
except ImportError:
warnings.warn('LinearRegressionwithErrors requires PyMC3 to be inst... |
parsers/NL.py | electricitymap/electricitymap-contrib | 143 | 11046609 | #!/usr/bin/env python3
import logging
import math
from asyncio.log import logger
from copy import copy
from datetime import datetime, timedelta
import arrow
import numpy as np
import pandas as pd
import requests
from electricitymap.contrib.config import ZONES_CONFIG
from parsers.lib.config import refetch_frequency
f... |
monitor.py | jackkum/python-dvr | 149 | 11046620 | <gh_stars>100-1000
#! /usr/bin/python3
from dvrip import DVRIPCam, SomethingIsWrongWithCamera
from signal import signal, SIGINT, SIGTERM
from sys import argv, stdout, exit
from datetime import datetime
from pathlib import Path
from time import sleep, time
import logging
baseDir = argv[3]
retryIn = 5
rebootWait = 10
ca... |
bigflow_python/python/bigflow/future/fields_test.py | advancedxy/bigflow_python | 1,236 | 11046634 | <filename>bigflow_python/python/bigflow/future/fields_test.py<gh_stars>1000+
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Baidu, 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 m... |
outrun/tests/test_main.py | Jacke/outrun | 3,070 | 11046671 | <gh_stars>1000+
from unittest import mock
import logging
import semver
import pytest
from outrun.__main__ import main
from outrun.logger import log
def test_no_args():
with pytest.raises(SystemExit):
main(["outrun"])
def test_protocol_check(caplog):
mismatching_major = semver.VersionInfo.parse("0.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.