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 |
|---|---|---|---|---|
utilities/Hive_metastore_migration/src/export_from_datacatalog.py | xy1m/aws-glue-samples | 925 | 12735043 | # Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from __future__ import print_function
from awsglue.context import GlueContext
from hive_metastore_migration import *
CONNECTION_TYPE_NAME = 'com.amazonaws.services.glue.connections.DataCatalogConnectio... |
mindinsight/explainer/encapsulator/evaluation_encap.py | fapbatista/mindinsight | 216 | 12735050 | <filename>mindinsight/explainer/encapsulator/evaluation_encap.py<gh_stars>100-1000
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www... |
tools/deep_memory_profiler/subcommands/upload.py | kjthegod/chromium | 231 | 12735094 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import subprocess
import tempfile
import zipfile
from lib.subcommand import SubCommand
from lib.symbol import SymbolDataSources
L... |
LeetCode/python3/122.py | ZintrulCre/LeetCode_Archiver | 279 | 12735097 | <filename>LeetCode/python3/122.py
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
size = len(prices)
bought = False
profit = 0
price = 0
for i in range(0, size - 1):
if not bought:
... |
vnpy/gateway/sopttest/__init__.py | funrunskypalace/vnpy | 19,529 | 12735112 | <reponame>funrunskypalace/vnpy
from .sopttest_gateway import SopttestGateway
|
SSR-Net/data/TYY_XSDATA_create_db.py | bleakie/MaskInsightface | 269 | 12735141 | <reponame>bleakie/MaskInsightface
import numpy as np
import cv2
import os
import argparse
import csv
def get_args():
parser = argparse.ArgumentParser(description="This script cleans-up noisy labels "
"and creates database for training.",
... |
leo/unittests/test_doctests.py | thomasbuttler/leo-editor | 1,550 | 12735170 | # -*- coding: utf-8 -*-
#@+leo-ver=5-thin
#@+node:ekr.20210926044012.1: * @file ../unittests/test_doctests.py
#@@first
"""Run all doctests."""
import doctest
import glob
import os
import unittest
from leo.core import leoGlobals as g
unittest_dir = os.path.dirname(__file__)
leo_dir = os.path.abspath(os.path.join(unitte... |
tests/bytecode/mp-tests/if2.py | LabAixBidouille/micropython | 303 | 12735204 | <reponame>LabAixBidouille/micropython
def f(x):
if x:
return
if x:
return
elif y:
return
if x:
return
else:
return
if x:
return
elif y:
return
else:
return
if x:
return
elif y:
return
elif z:
... |
338 Counting Bits.py | ChiFire/legend_LeetCode | 872 | 12735227 | <gh_stars>100-1000
"""
Given a non negative integer number num. For every numbers i in the range 0 <= i <= num calculate the number of 1's in
their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run t... |
tests/unit/small_text/utils/test_data.py | chschroeder/small-text | 218 | 12735301 | import unittest
import numpy as np
from small_text.utils.data import list_length
class DataUtilsTest(unittest.TestCase):
def test_list_length(self):
self.assertEqual(10, list_length(list(range(10))))
self.assertEqual(10, list_length(np.random.rand(10, 2)))
|
avionics/network/network_yaml_test.py | leozz37/makani | 1,178 | 12735307 | # 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... |
tests/python_slices/list.py | hixio-mh/plugin-python | 362 | 12735326 | <gh_stars>100-1000
a[-1]
a[-2:]
a[:-2]
a[::-1]
a[1::-1]
a[:-3:-1]
a[-3::-1]
point_coords = coords[i, :]
main(sys.argv[1:])
|
nbdt/data/pascal_context.py | XAVILLA/nbdt | 536 | 12735348 | <gh_stars>100-1000
###########################################################################
# Created by: <NAME>
# Email: <EMAIL>
# Copyright (c) 2017
###########################################################################
from PIL import Image, ImageOps, ImageFilter
import os
import math
import random
import n... |
api-inference-community/tests/test_normalizers.py | mlonaws/huggingface_hub | 362 | 12735350 | <reponame>mlonaws/huggingface_hub
from unittest import TestCase
import torch
from api_inference_community.normalizers import speaker_diarization_normalize
class NormalizersTestCase(TestCase):
def test_speaker_diarization_dummy(self):
tensor = torch.zeros((10, 2))
outputs = speaker_diarization_nor... |
components/test/data/autofill/automated_integration/task_flow.py | zealoussnow/chromium | 14,668 | 12735357 | <filename>components/test/data/autofill/automated_integration/task_flow.py<gh_stars>1000+
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Chrome Autofill Task Flow
Execute a set of autofill tasks in a ... |
capstone/cite/templatetags/redaction.py | rachelaus/capstone | 134 | 12735370 | from django import template
register = template.Library()
@register.filter()
def redact(text, case):
return case.redact_obj(text)
@register.filter()
def elide(text, case):
return case.elide_obj(text) |
Python/OOP/Constructor.py | piovezan/SOpt | 148 | 12735371 | class A(object):
def A():
print('factory')
return A()
def __init__(self):
print('init')
def __call__(self):
print('call')
print('chamar o construtor')
a = A()
print('chamar o construtor e a função')
b = A()()
print('chamar a função')
c = A.A()
#https://pt.stackoverflow.com/q... |
unittest/scripts/auto/py_shell/scripts/mysqlsh_module_norecord.py | mueller/mysql-shell | 119 | 12735375 |
#@<> Setup
testutil.deploy_sandbox(__mysql_sandbox_port1, "root")
#@<> Setup cluster
import mysqlsh
mydba = mysqlsh.connect_dba(__sandbox_uri1)
cluster = mydba.create_cluster("mycluster")
cluster.disconnect()
#@<> Catch error through mysqlsh.Error
try:
mydba.get_cluster("badcluster")
testutil.fail("<red>F... |
migrations/normalize_user_course_ratings.py | noryb009/rmc | 164 | 12735404 | <reponame>noryb009/rmc
import rmc.models as m
import rmc.shared.constants as c
import mongoengine as me
def normalize_user_course_ratings():
"""Normalize user course ratings to be 0/1 for Yes/No. Before it was
0.2,0.4,0.6,0.8.1.0 OR possible 0.0,0.25,0.5,0.75,1.0"""
num_changes = [0]
def normalize(... |
receiver/parse/data/carbon_pb2.py | dvanders/go-carbon | 722 | 12735417 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: carbon.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflec... |
lsassy/dumpmethod/mirrordump.py | scopedsecurity/lsassy | 1,212 | 12735432 | <reponame>scopedsecurity/lsassy
import logging
import os
import time
import base64
import random
import string
from lsassy.impacketfile import ImpacketFile
from lsassy.dumpmethod import IDumpMethod
class DumpMethod(IDumpMethod):
def __init__(self, session, timeout):
super().__init__(session, timeout)
... |
src/api-service/__app__/onefuzzlib/versions.py | tonybaloney/onefuzz | 2,692 | 12735480 | <reponame>tonybaloney/onefuzz<filename>src/api-service/__app__/onefuzzlib/versions.py
#!/usr/bin/env python
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
from typing import Dict
import semver
from memoization import cached
from onefuzztypes.responses import Version
from .__vers... |
incomplete/rasterizer/rasterizer/examples/__init__.py | adlerliu/500lines | 26,185 | 12735487 | import e1
import e2
import e3
import destijl
|
artemis/general/test_nondeterminism_hunting.py | peteroconnor-bc/artemis | 235 | 12735498 | import numpy as np
import pytest
from artemis.general.nondeterminism_hunting import delete_vars, assert_variable_matches_between_runs, variable_matches_between_runs, \
reset_variable_tracker
def _runs_are_the_same(var_gen_1, var_gen_2, use_assert = False):
delete_vars(['_test_random_var_32r5477w32'])
for... |
PGGAN/utils.py | MingtaoGuo/DCGAN_WGAN_WGAN-GP_LSGAN_SNGAN_TensorFlow | 149 | 12735504 | <reponame>MingtaoGuo/DCGAN_WGAN_WGAN-GP_LSGAN_SNGAN_TensorFlow
import scipy.io as sio
import numpy as np
def read_data(path):
for i in range(1, 6):
if i == 1:
data_mat = sio.loadmat(path + "data_batch_" + str(i) + ".mat")
data = np.transpose(np.reshape(data_mat["data"], [... |
vel/rl/algo/distributional_dqn.py | galatolofederico/vel | 273 | 12735562 | <gh_stars>100-1000
import torch
import torch.nn.utils
from vel.api import ModelFactory
from vel.api.metrics.averaging_metric import AveragingNamedMetric
from vel.rl.api import OptimizerAlgoBase
class DistributionalDeepQLearning(OptimizerAlgoBase):
""" Deep Q-Learning algorithm """
def __init__(self, model_f... |
LeetCode/0371_sum_of_two_integers.py | LenartBucar/PythonAlgorithms | 144 | 12735629 | class Solution:
def getSum(self, a: int, b: int) -> int:
# 32 bits integer max and min
MAX = 0x7FFFFFFF
MIN = 0x80000000
mask = 0xFFFFFFFF
while b != 0:
carry = a & b
a, b = (a ^ b) & mask, (carry << 1) & mask
ret... |
src/show_results.py | jimkon/Deep-Reinforcement-Learning-in-Large-Discrete-Action-Spaces | 154 | 12735635 | <filename>src/show_results.py
#!/usr/bin/python3
import numpy as np
from util.data_process import *
def show():
folder = 'saved/'
episodes = 10000
actions = 100
k = 10
experiment = 'InvertedPendulum-v1'
v = 3
id = 0
name = 'results/obj/{}data_{}_Wolp{}_{}{}k{}#{}.json.zip'.format(fold... |
alipay/aop/api/response/AlipayIserviceCcmInstanceGetResponse.py | antopen/alipay-sdk-python-all | 213 | 12735645 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayIserviceCcmInstanceGetResponse(AlipayResponse):
def __init__(self):
super(AlipayIserviceCcmInstanceGetResponse, self).__init__()
self._create_time = None
... |
pipsi/scripts/find_scripts.py | mitsuhiko/pipsi | 1,841 | 12735661 | <reponame>mitsuhiko/pipsi
import os
import sys
import pkg_resources
pkg = sys.argv[1]
prefix = sys.argv[2]
dist = pkg_resources.get_distribution(pkg)
if dist.has_metadata('RECORD'):
for line in dist.get_metadata_lines('RECORD'):
print(os.path.join(dist.location, line.split(',')[0]))
elif dist.has_metadata('... |
core/visualize/visualizer.py | hyunynim/DIST-Renderer | 176 | 12735681 | import os, sys
import time
import torch
import numpy as np
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from vis_utils import get_vis_depth, get_vis_mask, get_vis_normal
import copy
import cv2
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from PIL impo... |
main.py | vasujain/wfh-ninja | 196 | 12735702 | from flask import *
from flask.json import JSONEncoder
from flask.ext.cors import CORS
from flask.ext.login import LoginManager, login_user , logout_user , current_user , login_required
from werkzeug.contrib.fixers import ProxyFix
import simplejson as json
import os, sys
import datetime
app = Flask(__name__, static_u... |
examples/example-protobuf-client.py | hessu/carbon | 961 | 12735731 | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" Copyright 2013 <NAME>
Copyright 2017 The Graphite 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... |
pylayers/antprop/examples/ex_vsh3.py | usmanwardag/pylayers | 143 | 12735751 | from pylayers.antprop.antenna import *
from numpy import *
from matplotlib.pylab import *
kf = 30
A = Antenna('S2R3.vsh3','ant')
phi = linspace(0,2*pi,180)
theta=array([1.57])
Fth,Fph = A.pattern(theta,phi)
polar(phi,abs(Fth[kf,0,:]),phi,abs(Fph[kf,0,:]))
B = Antenna('S2R3.mat','ant/UWBAN/Matfile')
polar(B.phi,abs(B.F... |
daisy_workflows/image_import/suse/suse_import/on_demand/validate_chroot.py | zoran15/compute-image-tools | 186 | 12735828 | # Copyright 2020 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 applicable law or agree... |
pygrim/formulas/gaussian_quadrature.py | mezzarobba/fungrim | 102 | 12735847 | # -*- coding: utf-8 -*-
from ..expr import *
def_Topic(
Title("Gaussian quadrature"),
Section("Gauss-Legendre quadrature"),
SeeTopics("Legendre polynomials"),
Entries(
"0745ee", # Legendre polynomial zeros
"ea4754", # weights
"47b181", # -1,1
"545987", # a,b
... |
notebook/pandas_index_columns_select.py | vhn0912/python-snippets | 174 | 12735857 | import pandas as pd
df = pd.read_csv('data/src/sample_pandas_normal.csv', index_col=0)
print(df)
# age state point
# name
# Alice 24 NY 64
# Bob 42 CA 92
# Charlie 18 CA 70
# Dave 68 TX 70
# Ellen 24 CA 88
# Frank 30 NY 5... |
accounts/social_connect.py | annevandalfsen/screenbird | 121 | 12735870 | <reponame>annevandalfsen/screenbird
import settings
import tweepy
import base64
import hashlib
import hmac
import simplejson as json
from facepy import SignedRequest, GraphAPI
from django.http import HttpResponse, HttpResponseRedirect
from social_auth.models import UserSocialAuth
def twitter_get_auth_url(request):
... |
datasets/iuv_crop2full.py | google/retiming | 152 | 12735871 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
main.py | SJHBXShub/Center_Loss | 813 | 12735874 | import os
import sys
import argparse
import datetime
import time
import os.path as osp
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from torch.optim import lr_scheduler
import torch.backends.cudnn as cudnn
import datasets
import mod... |
hardware/chip/rtl872xd/hal/hal_test/ucube.py | wstong999/AliOS-Things | 4,538 | 12735877 | src = Split('''
hal_test.c
''')
component = aos_component('hal_test', src)
component.add_cflags('-Wall')
component.add_cflags('-Werror')
|
08-def-type-hints/messages/hints_2/messages_test.py | SeirousLee/example-code-2e | 990 | 12735878 | from pytest import mark
from messages import show_count
@mark.parametrize('qty, expected', [
(1, '1 part'),
(2, '2 parts'),
(0, 'no parts'),
])
def test_show_count(qty: int, expected: str) -> None:
got = show_count(qty, 'part')
assert got == expected
# tag::TEST_IRREGULAR[]
@mark.parametrize('q... |
blog/migrations/0002_auto_20150226_2305.py | geminibleep/myblog | 274 | 12735883 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='blogcategory',
... |
spacy/tests/lang/el/test_noun_chunks.py | snosrap/spaCy | 22,040 | 12735885 | <gh_stars>1000+
import pytest
def test_noun_chunks_is_parsed_el(el_tokenizer):
"""Test that noun_chunks raises Value Error for 'el' language if Doc is not parsed."""
doc = el_tokenizer("είναι χώρα της νοτιοανατολικής")
with pytest.raises(ValueError):
list(doc.noun_chunks)
|
tests/unit/core/providers/aws/s3/_helpers/test_parameters.py | avosper-intellaegis/runway | 134 | 12735889 | <filename>tests/unit/core/providers/aws/s3/_helpers/test_parameters.py
"""Test runway.core.providers.aws.s3._helpers.parameters."""
# pylint: disable=no-self-use
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List
import pytest
from pydantic import ValidationError
from runway.core.pr... |
inselect/gui/views/boxes/__init__.py | NaturalHistoryMuseum/inselect | 128 | 12735896 | <reponame>NaturalHistoryMuseum/inselect<filename>inselect/gui/views/boxes/__init__.py
from .boxes_view import BoxesView # noqa
from .graphics_item_view import GraphicsItemView # noqa
|
corehq/apps/api/migrations/0002_alter_permissions.py | dimagilg/commcare-hq | 471 | 12735932 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# Generated by Django 1.11.27 on 2020-02-10 20:26
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
... |
docs_src/advanced_usage/adv_usage_003.py | cdpath/fastapi_login | 318 | 12735935 | <filename>docs_src/advanced_usage/adv_usage_003.py
@app.post('/login')
def login(response: Response):
...
token = manager.create_access_token(
data=dict(sub=user.email)
)
manager.set_cookie(response, token)
return response |
src/tequila/quantumchemistry/encodings.py | dwierichs/tequila | 214 | 12735950 | """
Collections of Fermion-to-Qubit encodings known to tequila
Most are Interfaces to OpenFermion
"""
from tequila.circuit.circuit import QCircuit
from tequila.circuit.gates import X
from tequila.hamiltonian.qubit_hamiltonian import QubitHamiltonian
import openfermion
def known_encodings():
# convenience for testi... |
tests/test_webdataset.py | neuroailab/ffcv | 1,969 | 12735954 | <gh_stars>1000+
from os import path
from glob import glob
import tempfile
import numpy as np
from tempfile import TemporaryDirectory, NamedTemporaryFile
import torch as ch
from torch.utils.data import Dataset
import webdataset as wds
from ffcv import DatasetWriter
from ffcv.reader import Reader
from ffcv.fields impor... |
self_learn.py | cclauss/nonauto-nmt | 262 | 12735992 | <gh_stars>100-1000
# Copyright (c) 2018, salesforce.com, inc.
# All rights reserved.
# Licensed under the BSD 3-Clause license.
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import torch
import numpy as np
from torchtext import data
from torchtext impor... |
samples/virtual_gallery_tutorial/reset_tutorial_folder.py | jkabalar/kapture-localization | 118 | 12736018 | #!/usr/bin/env python3
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
import os.path as path
import path_to_kapture_localization # noqa: F401
import kapture_localization.utils.path_to_kapture # noqa: F401
from kapture.utils.paths import safe_remove_any_path
HERE_PATH = path.normpath(path.dirname(__f... |
tools/perf/core/oauth_api.py | zipated/src | 2,151 | 12736089 | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""API for generating OAuth2 access tokens from service account
keys predeployed to Chrome Ops bots via Puppet.
"""
import contextlib
import os
import subpr... |
contrib/cookiecutter/ckan_extension/{{cookiecutter.project}}/ckanext/{{cookiecutter.project_shortname}}/logic/action.py | gg2/ckan | 2,805 | 12736103 | <filename>contrib/cookiecutter/ckan_extension/{{cookiecutter.project}}/ckanext/{{cookiecutter.project_shortname}}/logic/action.py<gh_stars>1000+
import ckan.plugins.toolkit as tk
import ckanext.{{cookiecutter.project_shortname}}.logic.schema as schema
@tk.side_effect_free
def {{cookiecutter.project_shortname}}_get_su... |
examples/optimizers/swarm/create_ssa.py | anukaal/opytimizer | 528 | 12736129 | <reponame>anukaal/opytimizer
from opytimizer.optimizers.swarm import SSA
# Creates a SSA optimizer
o = SSA()
|
condensa/compressor.py | stormymcstorm/condensa | 153 | 12736131 | <filename>condensa/compressor.py<gh_stars>100-1000
# Copyright 2019 NVIDIA 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
#
# U... |
script/lib/sccache.py | LaudateCorpus1/libchromiumcontent | 315 | 12736134 | import os
import subprocess
import sys
from config import TOOLS_DIR
VERSION = 'aad2120'
SUPPORTED_PLATFORMS = {
'cygwin': 'windows',
'darwin': 'mac',
'linux2': 'linux',
'win32': 'windows',
}
def is_platform_supported(platform):
return platform in SUPPORTED_PLATFORMS
def get_binary_path():
platform = ... |
tests/functional/test_index.py | zuiko42/picobrew_pico | 142 | 12736155 | <gh_stars>100-1000
from app import create_app
def test_home_page():
"""
GIVEN a Flask application configured for testing
WHEN the '/' page is requested (GET)
THEN check that the response is valid
"""
flask_app = create_app('flask_test.cfg')
# Create a test client using the Flask applicatio... |
tests/integration/test_user_feed.py | sourcery-ai-bot/tiktokpy | 324 | 12736177 | import pytest
from loguru import logger
from tiktokpy import TikTokPy
from tiktokpy.models.feed import FeedItem
@pytest.mark.asyncio()
async def test_user_feed(bot: TikTokPy):
feed = await bot.user_feed(username="@mileycyrus")
logger.info(feed)
assert len(feed) == 50
assert isinstance(feed[0], FeedI... |
benchmark/plot.py | sail-sg/envpool | 330 | 12736186 | <filename>benchmark/plot.py<gh_stars>100-1000
#!/usr/bin/env python3
# Copyright 2022 Garena Online Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.... |
open/core/betterself/models/__init__.py | lawrendran/open | 105 | 12736225 | <reponame>lawrendran/open
from open.utilities.importing_models import import_submodules
__all__ = import_submodules(__name__)
|
equip/visitors/classes.py | neuroo/equip | 102 | 12736254 | # -*- coding: utf-8 -*-
"""
equip.visitors.classes
~~~~~~~~~~~~~~~~~~~~~~
Callback the visit method for each encountered class in the program.
:copyright: (c) 2014 by <NAME> (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
class ClassVisitor(object):
"""
A class visitor that is trigg... |
mermaid/libraries/modules/stn_nd.py | HastingsGreer/mermaid | 120 | 12736257 | <filename>mermaid/libraries/modules/stn_nd.py
"""
This package implements spatial transformations in 1D, 2D, and 3D.
This is needed for the map-based registrations for example.
.. todo::
Implement CUDA version. There is already a 2D CUDA version available (in the source directory here).
But it needs to be extended... |
src/postClass.py | iamshnoo/TerminusBrowser | 104 | 12736278 | <filename>src/postClass.py
class Post():
def __init__(self, userIden, content, timestamp, image=None, score='0', replies=None):
self.userIden = userIden
self.content = content
self.timestamp = timestamp
self.image = image
self.score = score
self.replies = [] if not re... |
homeassistant/components/siren/const.py | mtarjoianu/core | 30,023 | 12736284 | <gh_stars>1000+
"""Constants for the siren component."""
from enum import IntEnum
from typing import Final
DOMAIN: Final = "siren"
ATTR_TONE: Final = "tone"
ATTR_AVAILABLE_TONES: Final = "available_tones"
ATTR_DURATION: Final = "duration"
ATTR_VOLUME_LEVEL: Final = "volume_level"
class SirenEntityFeature(IntEnum)... |
script/testing/artifact_stats/__main__.py | pmenon/noisepage | 971 | 12736293 | #!/usr/bin/env python3
import argparse
import logging
import sys
from ..reporting.report_result import report_artifact_stats_result
from ..util.constants import LOG, PERFORMANCE_STORAGE_SERVICE_API
from .base_artifact_stats_collector import BaseArtifactStatsCollector
from .collectors import * # Import necessary for _... |
tests/pipupgrade/test_exception.py | shidevil/pipupgrade | 517 | 12736325 | # imports - module imports
from pipupgrade.exception import (
PipupgradeError
)
# imports - test imports
import pytest
def test_pipupgrade_error():
with pytest.raises(PipupgradeError):
raise PipupgradeError |
vaeseq/codec.py | charlesincharge/vae-seq | 161 | 12736339 | # Copyright 2018 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 or agreed to in writin... |
examples/whileloop.py | quynhanh-ngx/pytago | 206 | 12736391 | <reponame>quynhanh-ngx/pytago<filename>examples/whileloop.py
def main():
i = 0
while True:
print(i)
i += 1
if i > 5:
break
j = 10
while j < 100:
print(j)
j += 10
while 1:
print(j + i)
break
while 0.1:
print(j + i)
... |
alg/knockoffgan/KnockoffGAN.py | loramf/mlforhealthlabpub | 171 | 12736434 | '''
KnockoffGAN Knockoff Variable Generation
<NAME> (9/27/2018)
'''
#%% Necessary Packages
import numpy as np
from tqdm import tqdm
import tensorflow as tf
import logging
import argparse
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
#%% KnockoffGAN Function
'''
Inputs:
x_train: Training data
lamd... |
src/inference.py | artem-oppermann/Deep-Autoencoders-For-Collaborative-Filtering | 111 | 12736435 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 13:39:52 2019
@author: <NAME>
"""
import tensorflow as tf
import os
from model.inference_model import InferenceModel
tf.app.flags.DEFINE_string('checkpoints_path', os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'checkpoints/')),
... |
carbontracker/components/cpu/intel.py | leondz/carbontracker | 186 | 12736457 | <filename>carbontracker/components/cpu/intel.py
import os
import re
import time
from carbontracker.components.handler import Handler
# RAPL Literature:
# https://www.researchgate.net/publication/322308215_RAPL_in_Action_Experiences_in_Using_RAPL_for_Power_Measurements
RAPL_DIR = "/sys/class/powercap/"
CPU = 0
DRAM =... |
plotdevice/lib/io.py | plotdevice/plotdevice | 110 | 12736469 | import objc, os, re
import cIO
for cls in ["AnimatedGif", "Pages", "SysAdmin", "Video"]:
globals()[cls] = objc.lookUpClass(cls)
### Session objects which wrap the GCD-based export managers ###
class ExportSession(object):
def __init__(self):
# state flags
self.running = True
self.canc... |
model/multitask_v1/tdnn.py | LCF2764/tf-kaldi-speaker | 154 | 12736473 | # Build the speaker and phone networks.
# In this framework, they are both TDNN with different settings.
# The speaker network is a hard-coded TDNN and the phone network is specified by the parameters.
# Of course, the speaker network can be modified (e.g. to a larger network). Meanwhile, the parameters for the
# phone... |
Maths_And_Stats/Number_Theory/Sieve_of_Eratosthenes/prime_and_base.py | arslantalib3/algo_ds_101 | 182 | 12736501 | #include<bits/stdc++.h>
using namespace std;
char letterconverter(int number)
{
return 'A' + (number-10);
}
int main()
{
vector<int> primes;
int num, flag, x, base2, i, upto;
// Take input from user
cout << "Find prime numbers upto : ";
cin >> upto;
for(num = 2; num <= upto; num++)
{... |
criterion/ResponseMap/bbox_regression/L1.py | zhangzhengde0225/SwinTrack | 143 | 12736507 | <gh_stars>100-1000
import torch.nn as nn
from criterion.common.reduction.default import build_loss_reduction_function
from data.operator.bbox.spatial.vectorized.torch.cxcywh_to_xyxy import box_cxcywh_to_xyxy
def l1_loss_data_adaptor(pred, label, _):
predicted_bbox = pred['bbox']
if label is None:
retu... |
pygam/tests/test_terms.py | pjk645/pyGAM | 714 | 12736530 | # -*- coding: utf-8 -*-
from copy import deepcopy
import numpy as np
import pytest
from pygam import *
from pygam.terms import Term, Intercept, SplineTerm, LinearTerm, FactorTerm, TensorTerm, TermList
from pygam.utils import flatten
@pytest.fixture
def chicago_gam(chicago_X_y):
X, y = chicago_X_y
gam = Pois... |
test/SIM_alloc_test/RUN_test/input.py | gilbertguoze/trick | 647 | 12736576 | <gh_stars>100-1000
# Creates a local class. The class is destructed/deleted when the function returns.
def create_local_alloc_test():
test = trick.AllocTest()
# Creates a class that is controlled by the Memory Manager (MM). It is not freed when the function returns.
# TMM_declare_var returns a void *. We can ca... |
geoviews/models/__init__.py | pmav99/geoviews | 172 | 12736593 | <reponame>pmav99/geoviews<gh_stars>100-1000
from .custom_tools import ( # noqa
CheckpointTool, ClearTool, PolyVertexDrawTool, PolyVertexEditTool,
RestoreTool
)
|
util/heap/__init__.py | EarthCompass/patchkit | 631 | 12736692 | <gh_stars>100-1000
import os
import functools
from util import read
"""
Replace a custom heap with dlmalloc
Usage:
from util import heap
heap.declare(pt.linker)
pt.patch(addr, sym='dlmalloc')
pt.patch(addr, sym='dlcalloc')
pt.patch(addr, sym='dlfree')
pt.patch(addr, sym='dlrealloc')
"""
__all__ = ["appl... |
dizoo/gfootball/model/bots/__init__.py | sailxjx/DI-engine | 464 | 12736696 | from .kaggle_5th_place_model import FootballKaggle5thPlaceModel
from .rule_based_bot import FootballRuleBaseModel |
src/hammer-vlsi/par/nop.py | XiaoSanchez/hammer | 138 | 12736714 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# nop.py
# No-op place and route tool.
#
# See LICENSE for licence details.
from hammer_vlsi import HammerPlaceAndRouteTool, DummyHammerTool
from typing import List, Optional
from decimal import Decimal
class NopPlaceAndRoute(HammerPlaceAndRouteTool, DummyHammerToo... |
utils/data_gen.py | ShenLeixian/data2vis | 103 | 12736725 | <reponame>ShenLeixian/data2vis<gh_stars>100-1000
import data_utils
import json
# Generate training data splits.
# input source_directory - path to directory containing vegalite examples
# data_split_params - train/text/dev data split configuration
# output_directory - path to directory containing g... |
test/restful/test_rooms.py | thenetcircle/dino | 150 | 12736749 | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
test.py | Truth0906/PTTLibrary | 260 | 12736753 | import sys
import os
import time
import json
import random
import traceback
import threading
from PyPtt import PTT
def get_password(password_file):
try:
with open(password_file) as AccountFile:
account = json.load(AccountFile)
ptt_id = account['id']
password = account... |
finetuning/train_val.py | shubhaankargupta/FractalDB-Pretrained-ResNet-PyTorch | 126 | 12736816 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 05 23:55:12 2018
@author: <NAME>, <NAME>
"""
import sys
import numpy as np
import torch
import torch.nn as nn
# Training
def train(args, model, device, train_loader, optimizer, epoch, iteration):
model.train()
criterion = nn.CrossEntropyLoss(size_average=True) # previ... |
src/pretix/base/exporters/mail.py | fabm3n/pretix | 1,248 | 12736906 | <reponame>fabm3n/pretix
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License ... |
tests/test_example_001.py | benediktkr/python-terrascript | 507 | 12736942 | import terrascript
import terrascript.provider
import terrascript.resource
import tests.shared
def test_example_001():
config = terrascript.Terrascript()
config += terrascript.provider.aws(region="us-east-1", version="~> 2.0")
config += terrascript.resource.aws_vpc("example", cidr_block="10.0.0.0/16")
... |
torch_dreams/transforms.py | Tiamat-Tech/torch-dreams | 214 | 12736973 | import torchvision.transforms as transforms
import torch.nn as nn
import random
from .image_transforms import resize_4d_tensor_by_factor, resize_4d_tensor_by_size
imagenet_transform = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std= [0.229, 0.224, 0.225]
)
class random_resize(nn.Module):
def __ini... |
webservices/common/models/elections.py | 18F/openFEC | 246 | 12736986 | from .base import db
from webservices import docs
class ElectionResult(db.Model):
__tablename__ = 'ofec_election_result_mv'
election_yr = db.Column(db.Integer, primary_key=True, doc=docs.ELECTION_YEAR)
cand_office = db.Column(db.String, primary_key=True, doc=docs.OFFICE)
cand_office_st = db.Column(d... |
test/test_ops.py | pytorch/functorch | 423 | 12737024 | # Copyright (c) Facebook, Inc. and its affiliates.
# 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.
import itertools
from torch.testing._internal.common_utils import TestCase, run_tests, is_iterable_of_tensors
im... |
Recycled/collector/stock_fina_tushare.py | lifg2000/StockAnalysisSystem | 138 | 12737068 | <reponame>lifg2000/StockAnalysisSystem
import tushare as ts
import config
class StockFinancialDataFromTuShare:
def __init__(self):
ts.set_token(config.TS_TOKEN)
self.__pro = ts.pro_api()
def init(self) -> bool:
pass
def inited(self) -> bool:
pass
# Validate this Coll... |
tests/testapp/forms.py | cursive-works/wagtailmedia | 176 | 12737069 | <reponame>cursive-works/wagtailmedia
from django.forms import ModelForm
from django.forms.widgets import Widget
class OverridenWidget(Widget):
pass
class AlternateMediaForm(ModelForm):
class Meta:
widgets = {
"tags": OverridenWidget,
"file": OverridenWidget,
"thum... |
software/fpga/ov3/ovhw/leds.py | twam/ov_ftdi | 247 | 12737085 | <gh_stars>100-1000
from migen import *
from misoc.interconnect.csr import AutoCSR, CSRStorage
from itertools import zip_longest
# Basic programmable LED module
class LED_outputs(Module, AutoCSR):
def __init__(self, leds_raw, leds_muxes=None, active=1):
"""
leds_raw: output IOs for the LEDs
... |
benchmarks/django-workload/uwsgi/files/django-workload/django_workload/urls.py | jonasbn/cloudsuite | 103 | 12737107 | <reponame>jonasbn/cloudsuite<gh_stars>100-1000
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',... |
sbuild/sbuild/__init__.py | IMULMUL/static-binaries | 2,049 | 12737136 | <gh_stars>1000+
__author__ = '<NAME> <<EMAIL>>'
__version__ = '0.0.1'
|
tlslite/utils/python_eddsakey.py | tomato42/tlslite-1 | 121 | 12737145 | # Author <NAME>, copyright 2021
from .eddsakey import EdDSAKey
from ecdsa.keys import BadSignatureError
from ecdsa.der import UnexpectedDER
from .cryptomath import numBits
from .compat import compatHMAC
class Python_EdDSAKey(EdDSAKey):
"""
Concrete implementation of EdDSA object backed by python-ecdsa.
... |
suplemon/linelight/php.py | johnmbaughman/suplemon | 912 | 12737176 | <gh_stars>100-1000
from suplemon.linelight.color_map import color_map
class Syntax:
def get_comment(self):
return ("//", "")
def get_color(self, raw_line):
color = color_map["white"]
line = raw_line.strip()
keywords = ("if", "else", "finally", "try", "catch", "foreach",
... |
amazon_paapi/models/variations_result.py | frenners/python-amazon-paapi | 121 | 12737189 | <filename>amazon_paapi/models/variations_result.py
from typing import List
from .item_result import Item
from ..sdk.models import VariationsResult, VariationSummary
class ApiPrice:
amount: float
currency: str
display_amount: str
class ApiVariationDimension:
display_name: str
name: str
values:... |
vk_api__examples/wall_post__images.py | gil9red/SimplePyScripts | 117 | 12737192 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
"""
Скрипт ищет картинки в инете и помещает на стену пользователя vk.com
"""
import sys
import random
from urllib.request import urlopen
from typing import List
from vk_api.upload import VkUpload
from root_config import DIR
from root_common... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.