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
Zhang2017MultiStyle/test.py
czczup/URST
119
104583
<filename>Zhang2017MultiStyle/test.py import torch import utils import argparse import numpy as np from model import Net from PIL import Image from torch.autograd import Variable import torchvision.transforms as transforms import torch.nn.functional as F from tqdm import tqdm import math import time import os import s...
examples/pytorch/bgnn/run.py
ketyi/dgl
9,516
104605
<reponame>ketyi/dgl import torch from BGNN import BGNNPredictor import pandas as pd import numpy as np import json import os from dgl.data.utils import load_graphs from dgl.nn.pytorch import GATConv as GATConvDGL, GraphConv, ChebConv as ChebConvDGL, \ AGNNConv as AGNNConvDGL, APPNPConv from torch.nn import Dropout,...
pyNastran/gui/gui_objects/alt_geometry_storage.py
luzpaz/pyNastran
293
104616
<gh_stars>100-1000 from copy import deepcopy class AltGeometry: representations = ['main', 'toggle', 'wire', 'point', 'surface', 'bar', 'wire+point', 'wire+surf'] displays = ['Wireframe', 'Surface', 'point', None] def __repr__(self): msg = ('AltGeometry(%r, color=%s, line_wid...
harvesttext/resources.py
buvta/HarvestText
1,524
104619
<filename>harvesttext/resources.py #coding=utf-8 #!/usr/bin/env python # Resources # 褒贬义词典 清华大学 李军 # # 此资源被用于以下论文中: # <NAME> and <NAME>, Experimental Study on Sentiment Classification of Chinese Review using Machine Learning Techniques, in Proceding of IEEE NLPKE 2007 # 李军 中文评论的褒贬义分类实验研究 硕士论文 清华大学 2008 import os im...
plugins/dns/client.py
tgragnato/geneva
1,182
104661
<filename>plugins/dns/client.py """ Client Run by the evaluator, tries to make a GET request to a given server """ import argparse import logging import os import random import socket import sys import time import traceback import urllib.request import dns.resolver import requests import actions.utils from plugins....
tests/test_vim.py
maralla/validator.vim
255
104674
import json from lints.vim import VimVint, VimLParserLint def test_vint_undefined_variable(): msg = ['t.vim:3:6: Undefined variable: s:test (see :help E738)'] res = VimVint().parse_loclist(msg, 1) assert json.loads(res)[0] == { "lnum": "3", "col": "6", "text": "[vint]Undefined var...
api/serializers/subscribers.py
lucasmgana/Pharmacy-Light-weight
192
104675
<reponame>lucasmgana/Pharmacy-Light-weight from rest_framework import serializers from backend.models.subscribers import Subscriber class SubscribersSerializer(serializers.ModelSerializer): class Meta: model = Subscriber fields = ('name', 'contact_method', 'contact_info')
tests/test_tanh_distortion.py
ankitshah009/audiomentations
930
104678
import unittest import numpy as np import pytest from audiomentations import TanhDistortion from audiomentations.core.utils import calculate_rms class TestTanhDistortion(unittest.TestCase): def test_single_channel(self): samples = np.random.normal(0, 0.1, size=(2048,)).astype(np.float32) sample_...
exercises/alphametics/alphametics.py
kishankj/python
1,177
104772
def solve(puzzle): pass
utils/models_utils.py
phygitalism/PTI
345
104778
<reponame>phygitalism/PTI import pickle import functools import torch from configs import paths_config, global_config def toogle_grad(model, flag=True): for p in model.parameters(): p.requires_grad = flag def load_tuned_G(run_id, type): new_G_path = f'{paths_config.checkpoints_dir}/model_{run_id}_{t...
jetbot/camera/__init__.py
geoc1234/jetbot
2,624
104789
<gh_stars>1000+ import os DEFAULT_CAMERA = os.environ.get('JETBOT_DEFAULT_CAMERA', 'opencv_gst_camera') if DEFAULT_CAMERA == 'zmq_camera': from .zmq_camera import ZmqCamera Camera = ZmqCamera else: from .opencv_gst_camera import OpenCvGstCamera Camera = OpenCvGstCamera
streamalert/shared/lookup_tables/utils.py
cninja1/streamalert
2,770
104849
<reponame>cninja1/streamalert """ Copyright 2017-present Airbnb, 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 la...
pymer4/tests/test_utils.py
turbach/pymer4
127
104850
<filename>pymer4/tests/test_utils.py from __future__ import division from pymer4.utils import con2R, R2con, get_resource_path, result_to_table import pandas as pd import numpy as np from pymer4.models import Lm import os def test_con2R(): x = np.array([[-1, 0, 0, 1], [-0.5, -0.5, 0.5, 0.5], [-3 / 3, 1 / 3, 1 / 3,...
DPGAnalysis/Skims/python/valSkim_cff.py
ckamtsikis/cmssw
852
104923
<reponame>ckamtsikis/cmssw from DPGAnalysis.Skims.goodvertexSkim_cff import * ###Tracks selection trackSelector =cms.EDFilter("TrackSelector", src = cms.InputTag("generalTracks"), cut = cms.string('quality("highPurity")') ...
knet/det/knet.py
yinchimaoliang/K-Net
361
104938
<reponame>yinchimaoliang/K-Net import torch import torch.nn.functional as F from mmdet.models.builder import DETECTORS from mmdet.models.detectors import TwoStageDetector from mmdet.utils import get_root_logger from .utils import sem2ins_masks @DETECTORS.register_module() class KNet(TwoStageDetector): def __ini...
examples/wish_export.py
HighnessAtharva/genshinstats
182
104989
<filename>examples/wish_export.py import csv import genshinstats as gs with open("export.csv", "w", newline="", encoding="utf-8") as file: fieldnames = ["time", "name", "type", "rarity", "banner"] writer = csv.DictWriter(file, fieldnames, extrasaction="ignore") writer.writeheader() print("preparing da...
examples/image/cath/util/__init__.py
mariogeiger/se3cnn
170
104991
<reponame>mariogeiger/se3cnn<gh_stars>100-1000 __all__ = [ 'arch_blocks', 'get_mask', 'get_param_groups', 'logger', 'losses', 'lr_schedulers', 'optimizers_L1L2', 'tensorflow_logger', ]
TM1py/Objects/Server.py
adscheevel/tm1py
113
105035
# -*- coding: utf-8 -*- from typing import Dict class Server: """ Abstraction of the TM1 Server :Notes: contains the information you get from http://localhost:5895/api/v1/Servers no methods so far """ def __init__(self, server_as_dict: Dict): self.name = server_as_...
torchsketch/utils/general_utils/get_filenames_and_classes.py
songyzh/torchsketch
182
105040
<reponame>songyzh/torchsketch import os def get_filenames_and_classes(dataset_dir): class_names = [] for filename in os.listdir(dataset_dir): path = os.path.join(dataset_dir, filename) if os.path.isdir(path): class_names.append(filename) class_names_to_ids = ...
slow_tests/attackers_chinese.py
e-tornike/OpenAttack
444
105080
from OpenAttack import substitute import sys, os sys.path.insert(0, os.path.join( os.path.dirname(os.path.abspath(__file__)), ".." )) import OpenAttack def get_attackers_on_chinese(dataset, clsf): triggers = OpenAttack.attackers.UATAttacker.get_triggers(clsf, dataset, clsf.tokenizer) attackers = ...
friendly/runtime_errors/os_error.py
matan-h/friendly
287
105154
"""Only identifying failed connection to a server for now.""" from ..my_gettext import current_lang, no_information def get_cause(_value, _frame, tb_data): tb = "\n".join(tb_data.formatted_tb) if ( "socket.gaierror" in tb or "urllib.error" in tb or "urllib3.exception" in tb or...
python/test/mapreduce/module_test.py
Batterii/appengine-mapreduce
228
105161
<reponame>Batterii/appengine-mapreduce #!/usr/bin/env python # # Copyright 2010 Google Inc. All Rights Reserved. import unittest from google.appengine.api import module_testutil from mapreduce import context from mapreduce import control from mapreduce import datastore_range_iterators from mapreduce import errors ...
sdc/datatypes/sdc_typeref.py
dlee992/sdc
540
105165
# ***************************************************************************** # Copyright (c) 2021, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions ...
models/backbone/__init__.py
briana-jin-zhang/spatial-segmentation
733
105207
from .unet import * from .vae import * from .others import * from .pconv_unet import * from .discriminator import * from .resnet_cls import *
asterioids-pygame-project/source_code_step_5/space_rocks/utils.py
syberflea/materials
3,682
105220
<reponame>syberflea/materials from pygame.image import load from pygame.math import Vector2 def load_sprite(name, with_alpha=True): path = f"assets/sprites/{name}.png" loaded_sprite = load(path) if with_alpha: return loaded_sprite.convert_alpha() else: return loaded_sprite.convert() ...
dataset/make_dataset.py
cdpidan/captcha_trainer_pytorch
182
105281
#!/usr/bin/env python # _*_coding:utf-8_*_ """ @Time : 2020/8/23 0:11 @Author: sml2h3 @File: make_dataset @Software: PyCharm """ from utils.constants import * from utils.exception import * from config import Config from PIL import Image import os import sys import json import time import random class MakeDa...
leet/strings/findAnagrams.py
monishshah18/python-cp-cheatsheet
140
105308
""" time: c*26 + p space: 26 + 26 (1) """ class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: cntP = collections.Counter(p) cntS = collections.Counter() P = len(p) S = len(s) if P > S: return [] ans = [] for i, c in enumerate(s): ...
det/configs/involution/mask_rcnn_red50_neck_fpn_head_1x_coco.py
shikishima-TasakiLab/involution
1,260
105328
_base_ = [ '../_base_/models/mask_rcnn_red50_neck_fpn_head.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_1x_warmup.py', '../_base_/default_runtime.py' ] optimizer_config = dict(grad_clip(dict(_delete_=True, max_norm=5, norm_type=2)))
code_examples/popart/block_sparse/examples/test_block_sparse.py
payoto/graphcore_examples
260
105344
<reponame>payoto/graphcore_examples # Copyright (c) 2020 Graphcore Ltd. All rights reserved. import os import numpy as np from functools import reduce from operator import mul import popart import pytest # range for filling blocks MATRIX_LOW_VALUE = -10 MATRIX_HIGH_VALUE = 10 # library provides support for 3 kinds of...
tests/test_clean_api.py
bsekiewicz/dateparser
1,804
105357
from datetime import date, datetime from pytz import utc from parameterized import parameterized, param import dateparser from tests import BaseTestCase class TestParseFunction(BaseTestCase): def setUp(self): super().setUp() self.result = NotImplemented @parameterized.expand([ param...
vdb/extensions/amd64.py
rnui2k/vivisect
716
105363
<reponame>rnui2k/vivisect import vdb.extensions.i386 as v_ext_i386 import vdb.extensions.i386 as vdb_ext_i386 def vdbExtension(vdb, trace): vdb.addCmdAlias('db','mem -F bytes') vdb.addCmdAlias('dw','mem -F u_int_16') vdb.addCmdAlias('dd','mem -F u_int_32') vdb.addCmdAlias('dq','mem -F u_int_64') v...
sionna/channel/tr38901/lsp.py
NVlabs/sionna
163
105441
<gh_stars>100-1000 # # SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """ Class for sampling large scale parameters (LSPs) and pathloss following the 3GPP TR38.901 specifications and according to a channel simulation scenario...
scripts/irods/test/test_client_hints.py
JustinKyleJames/irods
333
105478
from __future__ import print_function import sys import shutil import os if sys.version_info >= (2, 7): import unittest else: import unittest2 as unittest import os import datetime import socket from .. import test from . import settings from .. import lib from . import resource_suite from ..configuration impo...
presidio-analyzer/tests/test_us_driver_license_recognizer.py
vtols/presidio
1,408
105495
<filename>presidio-analyzer/tests/test_us_driver_license_recognizer.py import pytest from presidio_analyzer.predefined_recognizers import UsLicenseRecognizer from tests import assert_result_within_score_range @pytest.fixture(scope="module") def recognizer(): return UsLicenseRecognizer() @pytest.fixture(scope="...
util/generate_loading_gif.py
Tarsnap/tarsnap-gui
270
105520
#!/usr/bin/env python3 """ Generate a "loading" or "waiting" animated gif. """ import math import PIL.Image import PIL.ImageDraw SIZE = 16 TOTAL_DOTS = 8 VISUAL_DOTS = 4 # how many dots are visible in each frame. DIAMETER = SIZE / 8.0 SECONDS = 1.25 # how long it takes to do a complete cycle. OUTPUT = "loading.gi...
ivy/doc/examples/udp_test_expect.py
b1f6c1c4/cfg-enum
113
105528
<reponame>b1f6c1c4/cfg-enum import pexpect import sys def run(name,opts,res): child = pexpect.spawn('./{}'.format(name)) child.logfile = sys.stdout try: child.expect('>') child.sendline('foo.send(0,1,2)') child.expect(r'< foo.recv\(1,2\)') child.sendline('foo.send(1,0,3)') ...
quickumls/__init__.py
equipe22/QuickUMLS
283
105550
<gh_stars>100-1000 from .core import QuickUMLS from .client import get_quickumls_client from .about import *
mqbench/custom_quantizer/tensorrt_quantizer.py
ModelTC/MQBench
179
105602
import operator from typing import List import torch from torch.fx import GraphModule import mqbench.nn.qat as qnnqat from mqbench.utils.logger import logger from mqbench.utils.registry import register_model_quantizer from mqbench.prepare_by_platform import BackendType from mqbench.custom_quantizer import ModelQuanti...
lib/plugins/1024.py
ikstream/Zeus-Scanner
841
105605
<reponame>ikstream/Zeus-Scanner<filename>lib/plugins/1024.py import re __product__ = "1024-CMS" __description__ = ( "1024 is one of a few CMS's leading the way with " "the implementation of the AJAX technology into " "all its areas. This includes dynamic administration " "and user interaction. 1024 of...
moto/stepfunctions/exceptions.py
gtourkas/moto
5,460
105647
<filename>moto/stepfunctions/exceptions.py<gh_stars>1000+ from moto.core.exceptions import AWSError class ExecutionAlreadyExists(AWSError): TYPE = "ExecutionAlreadyExists" STATUS = 400 class ExecutionDoesNotExist(AWSError): TYPE = "ExecutionDoesNotExist" STATUS = 400 class InvalidArn(AWSError): ...
neurolib/models/bold/__init__.py
leonidas228/neurolib
258
105710
from .model import BOLDModel from .timeIntegration import simulateBOLD
pyqtgraph/parametertree/parameterTypes/colormap.py
hishizuka/pyqtgraph
2,762
105765
<reponame>hishizuka/pyqtgraph from .basetypes import WidgetParameterItem, SimpleParameter from ...Qt import QtCore from ...colormap import ColorMap from ...widgets.GradientWidget import GradientWidget class ColorMapParameterItem(WidgetParameterItem): """Registered parameter type which displays a :class:`GradientW...
submission.py
gengshan-y/expansion
132
105775
from __future__ import print_function import sys import cv2 import pdb import argparse import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data from torch.autograd import Variable import torch.nn.functional as...
Filters/Extraction/Testing/Python/ExtractTensors.py
txwhhny/vtk
1,755
105790
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create tensor ellipsoids # Create the RenderWindow, Renderer and interactive renderer # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() ir...
test/test_slimta_logging_socket.py
nanojob/python-slimta
141
105793
<gh_stars>100-1000 import unittest import errno import logging import socket from testfixtures import log_capture import slimta.logging.socket from slimta.logging import getSocketLogger class FakeSocket(object): def __init__(self, fd, peer=None): self.fd = fd self.peer = peer def fileno(se...
comicolorization_sr/colorization_task/base.py
DwangoMediaVillage/Comicolorization
122
105831
<reponame>DwangoMediaVillage/Comicolorization from abc import ABCMeta, abstractmethod import typing import six from comicolorization_sr.config import Config from comicolorization_sr.data_process import BaseDataProcess @six.add_metaclass(ABCMeta) class BaseColorizationTask(object): def __init__(self, config, load_...
examples/sas_logical_interconnect_groups.py
doziya/hpeOneView
107
105850
# -*- coding: utf-8 -*- ### # (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP # # 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 limi...
src/build_hops_dist.py
talebia/compute.rhino3d
182
105863
# Build yak packages for publishing import os import shutil import sys src_dir = os.path.dirname(os.path.realpath(__file__)) dist_dir = os.path.join(src_dir, 'dist') # clear output dir if os.path.exists(dist_dir): shutil.rmtree(dist_dir) # build hops (inc. self-contained rhino.compute.exe) os.chdir(src_dir) buil...
tensornets/capsulenets.py
mehrdad-shokri/tensornets
1,057
105864
"""Collection of CapsuleNet variants The reference paper: - Dynamic Routing Between Capsules - <NAME>, <NAME>, <NAME> - https://arxiv.org/abs/1710.09829 The reference implementations: 1. TensorFlow CapsNet - https://github.com/naturomics/CapsNet-Tensorflow 2. Keras CapsNet - https://github.com/XifengGuo/CapsNe...
pennylane/numpy/__init__.py
therooler/pennylane
539
105865
<gh_stars>100-1000 # Copyright 2018-2021 Xanadu Quantum Technologies 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 re...
InvenTree/company/migrations/0006_supplierpricebreak_currency.py
ArakniD/InvenTree
656
105866
<gh_stars>100-1000 # Generated by Django 2.2.4 on 2019-09-02 23:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('common', '0003_auto_20190902_2310'), ('company', '0005_auto_20190525_2356'), ] operation...
paddlex/ppcls/utils/metrics.py
xiaolao/PaddleX
3,655
105873
<reponame>xiaolao/PaddleX # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 # # ...
third_party/blink/tools/blinkpy/w3c/pr_cleanup_tool.py
zealoussnow/chromium
14,668
105880
<gh_stars>1000+ """Cleans up PRs that correspond to abandoned CLs in Gerrit.""" import argparse import logging from blinkpy.common.system.log_utils import configure_logging from blinkpy.w3c.wpt_github import WPTGitHub from blinkpy.w3c.gerrit import GerritAPI, GerritError from blinkpy.w3c.common import (read_credentia...
tools/bin/ext/figleaf/annotate_cover.py
YangHao666666/hawq
450
105919
<reponame>YangHao666666/hawq<gh_stars>100-1000 import figleaf import os import re from annotate import read_exclude_patterns, filter_files, logger def report_as_cover(coverage, exclude_patterns=[], ): ### now, output. keys = coverage.keys() info_dict = {} for k in filter_files(keys): try...
project/auth/views.py
infrascloudy/ajax_helpdesk
296
105921
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, redirect, request, current_app, g, flash, url_for from flask_login import login_required, logout_user from flask_babel import gettext as _ from .models import User from ..extensions import db from .forms import SettingsForm auth = Blueprint('auth',...
learnpy_ecourse/class3/ex4_ip_address_valid.py
fallenfuzz/pynet
528
105939
#!/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. Well, with some exceptions (I use try / except below). ...
querybook/server/lib/notify/utils.py
shivammmmm/querybook
1,144
105944
import jinja2 from lib.notify.all_notifiers import get_notifier_class, DEFAULT_NOTIFIER from logic import user as user_logic from app.db import with_session @with_session def notify_user(user, template_name, template_params, notifier_name=None, session=None): if notifier_name is None: notification_prefere...
fountain/resources/builtin.py
tzano/fountain
108
105966
# constants PERCENTAGE_BUILTIN_SLOTS = 0.20 # Time FOUNTAIN_MONTH = 'FOUNTAIN:MONTH' FOUNTAIN_WEEKDAY = 'FOUNTAIN:WEEKDAY' FOUNTAIN_HOLIDAYS = 'FOUNTAIN:HOLIDAYS' FOUNTAIN_MONTH_DAY = 'FOUNTAIN:MONTH_DAY' FOUNTAIN_TIME = 'FOUNTAIN:TIME' FOUNTAIN_NUMBER = 'FOUNTAIN:NUMBER' FOUNTAIN_DATE = 'FOUNTAIN:DATE' # Location F...
flan/utils.py
purn3ndu/FLAN
206
106002
# Copyright 2021 The FLAN Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
m2-modified/ims/common/agentless-system-crawler/crawler/plugins/systems/cpu_host_crawler.py
CCI-MOC/ABMI
108
106060
import logging import psutil from icrawl_plugin import IHostCrawler from utils.features import CpuFeature logger = logging.getLogger('crawlutils') class CpuHostCrawler(IHostCrawler): def get_feature(self): return 'cpu' def crawl(self, **kwargs): logger.debug('Crawling %s' % (self.get_feat...
np_ml/adaboost/adaboost.py
wwwy-binary/NP_ML
237
106096
<reponame>wwwy-binary/NP_ML<filename>np_ml/adaboost/adaboost.py import numpy as np # x > v or x < v # y = 1 or -1 class TrivialClassification: def __init__(self): self.sign = None self.thres = 0 def __str__(self): return self.sign + " than " + str(self.thres) def fit(self,...
dataviva/apps/ask/views.py
joelvisroman/dataviva-site
126
106113
from sqlalchemy import and_, or_, func from datetime import datetime from flask import Blueprint, request, make_response, render_template, flash, g, session, redirect, url_for, jsonify, abort, current_app from flask.ext.babel import gettext from dataviva import db, lm, view_cache # from config import SITE_MIRROR from ...
virtual/lib/python3.6/site-packages/pylint/test/functional/yield_from_iterable_py33.py
drewheathens/The-Moringa-Tribune
463
106145
<filename>virtual/lib/python3.6/site-packages/pylint/test/functional/yield_from_iterable_py33.py """ Check that `yield from`-statement takes an iterable. """ # pylint: disable=missing-docstring def to_ten(): yield from 10 # [not-an-iterable]
insights/tests/client/collection_rules/test_get_conf_update.py
mglantz/insights-core
121
106152
# -*- coding: UTF-8 -*- from .helpers import insights_upload_conf from mock.mock import patch from pytest import raises collection_rules = {"version": "1.2.3"} collection_rules_file = "/tmp/collection-rules" @patch("insights.client.collection_rules.InsightsUploadConf.get_conf_file") @patch("insights.client.collect...
Codeforces/95 Beta Division 2/Problem A/A.py
VastoLorde95/Competitive-Programming
170
106175
<filename>Codeforces/95 Beta Division 2/Problem A/A.py s = raw_input() if s.upper() == s or s[1:].upper() == s[1:]: print s.swapcase() else: print s
fips-files/generators/Shader.py
infancy/oryol
1,707
106176
''' Code generator for shader libraries. ''' Version = 49 import os, platform, json import genutil as util from util import glslcompiler, shdc from mod import log import zlib # only for crc32 if platform.system() == 'Windows' : from util import hlslcompiler if platform.system() == 'Darwin' : from util impor...
deep_qa/layers/backend/collapse_to_batch.py
richarajpal/deep_qa
459
106263
from keras import backend as K from overrides import overrides from ..masked_layer import MaskedLayer class CollapseToBatch(MaskedLayer): """ Reshapes a higher order tensor, taking the first ``num_to_collapse`` dimensions after the batch dimension and folding them into the batch dimension. For example, ...
thumt/utils/utils.py
Demon-JieHao/Modeling-Structure-for-Transformer-Network
145
106323
# coding=utf-8 # Copyright 2018 The THUMT Authors from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf def session_run(monitored_session, args): # Call raw TF session directly return monitored_session._tf_sess().run(args)
torch2trt_dynamic/converters/LayerNorm.py
jinfagang/torch2trt_dynamic
155
106356
<filename>torch2trt_dynamic/converters/LayerNorm.py<gh_stars>100-1000 import numpy as np import tensorrt as trt from ..torch2trt_dynamic import (tensor_trt_get_shape_trt, tensorrt_converter, torch_dim_to_trt_axes, trt_) @tensorrt_converter('torch.nn.LayerNorm.forward') def convert_La...
petl/test/transform/test_maps.py
arturponinski/petl
435
106369
<reponame>arturponinski/petl from __future__ import absolute_import, print_function, division from collections import OrderedDict from petl.test.failonerror import assert_failonerror from petl.test.helpers import ieq from petl.transform.maps import fieldmap, rowmap, rowmapmany from functools import partial def tes...
game_of_life/05_mixed_sorting.py
nicetone/Python
28,321
106407
<reponame>nicetone/Python<gh_stars>1000+ # Mixed sorting """ Given a list of integers nums, sort the array such that: All even numbers are sorted in increasing order All odd numbers are sorted in decreasing order The relative positions of the even and odd numbers remain the same Example 1 Input nums = [8,...
examples/plot_allpsd.py
butala/spectrum
261
106429
<filename>examples/plot_allpsd.py """ Spectral analysis of a two frequencies signal ================================================== """ ########################################################### # Context # ---------- ############################################## # Example # -------- # # In the following examp...
devtools/qcexport/qcexport.py
MolSSI/dqm_server
113
106440
<filename>devtools/qcexport/qcexport.py '''Import/Export of QCArchive data ''' from dataclasses import dataclass import typing from qcexport_extra import extra_children_map from sqlalchemy.orm import make_transient, Load from sqlalchemy import inspect from qcfractal.storage_sockets.models import ( AccessLogORM, ...
core/clients/python/api_bindings/cb2_api/tests/lists_and_gets.py
aledbf/digitalrebar
103
106457
<reponame>aledbf/digitalrebar # Copyright 2014, Dell # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
census_data_downloader/core/__init__.py
JoeGermuska/census-data-downloader
170
106487
<reponame>JoeGermuska/census-data-downloader<filename>census_data_downloader/core/__init__.py import collections # https://www.census.gov/data/developers/data-sets/acs-1year/notes-on-acs-estimate-and-annotation-values.html ESTIMATE_MAP = collections.OrderedDict({ "-999999999": "too few samples", "-888888888":...
orchestra/todos/auth.py
code-review-doctor/orchestra
444
106525
<reponame>code-review-doctor/orchestra from rest_framework import permissions from orchestra.models import Worker from orchestra.models import Todo from orchestra.models import TodoQA class IsAssociatedWithTodosProject(permissions.BasePermission): """ Ensures that a user's worker is accoiated with the todo's...
mead/hash_config.py
sagnik/baseline
241
106613
import argparse from baseline.utils import read_config_stream from mead.utils import hash_config, convert_path def main(): parser = argparse.ArgumentParser(description="Get the mead hash of a config.") parser.add_argument('config', help='JSON/YML Configuration for an experiment: local file or remote URL', typ...
tests/test_00_exports.py
sharuzzaman/PGPy
248
106630
""" check the export list to ensure only the public API is exported by pgpy.__init__ """ import pytest import importlib import inspect modules = ['pgpy.constants', 'pgpy.decorators', 'pgpy.errors', 'pgpy.pgp', 'pgpy.symenc', 'pgpy.types', 'pgpy.packet...
examples/demo_cifar.py
rohanraja/cgt_distributed
698
106636
from example_utils import fmt_row, fetch_dataset import cPickle, numpy as np import cgt from cgt import nn import argparse, time def rmsprop_updates(cost, params, stepsize=0.001, rho=0.9, epsilon=1e-6): grads = cgt.grad(cost, params) updates = [] for p, g in zip(params, grads): acc = cgt.shared(p....
terraform/stacks/iam/lambdas/python/cloud_sniper_iam/cloud_sniper_iam.py
houey/cloud-sniper
160
106641
<reponame>houey/cloud-sniper<gh_stars>100-1000 import boto3 import datetime import os import logging import json import requests ROLE_SPOKE = os.environ['ROLE_SPOKE_CLOUD_SNIPER'] WEBHOOK_URL = os.environ['WEBHOOK_URL_CLOUD_SNIPER'] HUB_ACCOUNT_ID = os.environ['HUB_ACCOUNT_CLOUD_SNIPER'] HUB_ACCOUNT_NAME = os.environ[...
packages/core/minos-microservice-common/minos/common/testing/__init__.py
minos-framework/minos-python
247
106664
<reponame>minos-framework/minos-python<filename>packages/core/minos-microservice-common/minos/common/testing/__init__.py from .database import ( MockedDatabaseClient, MockedDatabaseOperation, MockedLockDatabaseOperationFactory, MockedManagementDatabaseOperationFactory, ) from .testcases import ( Dat...
bibliopixel/commands/run.py
rec/leds
253
106667
""" Run specified project from file or URL """ from .. main import project_flags from .. project import project_runner from .. util import signal_handler def run(args): for i in signal_handler.run(args.pid_filename, project_runner.stop): project_runner.run(args) def add_arguments(parser): parser.se...
src/compas/base.py
XingxinHE/compas
235
106673
""" ******************************************************************************** base ******************************************************************************** .. deprecated:: 1.5 Use `compas.data` instead .. currentmodule:: compas.base Classes ======= .. autosummary:: :toctree: generated/ :n...
pypattyrn/behavioral/chain.py
defianceblack/PyPattyrn
1,499
106692
<reponame>defianceblack/PyPattyrn from abc import ABCMeta, abstractmethod class ChainLink(object, metaclass=ABCMeta): """ Abstract ChainLink object as part of the Chain of Responsibility pattern. - External Usage documentation: U{https://github.com/tylerlaberge/PyPattyrn#chain-of-responsibility-pattern} ...
atlas/foundations_sdk/src/foundations/job_parameters/__init__.py
DeepLearnI/atlas
296
106716
<reponame>DeepLearnI/atlas def load_parameters(log_parameters=True): try: parameters = _parsed_json(_raw_json_from_parameters_file()) if log_parameters: log_params(parameters) return parameters except FileNotFoundError: return {} def flatten_parameter_dictionary(...
lib/discord/constants/general.py
goztrk/django-htk
206
106735
<reponame>goztrk/django-htk<filename>lib/discord/constants/general.py DISCORD_WEBHOOK_URL = 'https://discord.com/api/webhooks/{webhook_id}/{webhook_token}' DISCORD_WEBHOOK_RELAY_PARAMS = [ 'webhook_id', 'webhook_token', 'content', ]
third_party/com_fasterxml_jackson_module.bzl
wix/exodus
186
106762
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "com_fasterxml_jackson_module_jackson_module_paranamer", artifact = "com.fasterxml.jackson.module:jackson-module-paranamer:2.9.6", artifact_sha256 = "dfd66598c0094d9...
Packs/CounterTack/Integrations/CounterTack/CounterTack.py
diCagri/content
799
106766
<reponame>diCagri/content import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * ''' IMPORTS ''' import json import requests import os import os.path # Disable insecure warnings requests.packages.urllib3.disable_warnings() # remove proxy if not set to true in params if no...
openverse_api/catalog/api/migrations/0012_auto_20190102_2012.py
ritesh-pandey/openverse-api
122
106769
# Generated by Django 2.0.8 on 2019-01-02 20:12 import django.contrib.postgres.fields.jsonb from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0011_auto_20181117_0029'), ] operations = [ migrations.AlterUniqueTogether( n...
Contributions/Python/simple-SD.py
OluSure/Hacktoberfest2021-1
215
106772
# Hacktoberfest 2021 # Problem: House Prices # # You are given an array that represents house prices. # Calculate and output the percentage of houses that are within one standard deviation from the mean. # To calculate the percentage, divide the number of houses that satisfy the condition by the total number of h...
oncogemini/gemini_plot.py
fakedrtom/cancer_gemini
221
106784
#!/usr/bin/env python def plot(parser, args): """ To do. """ pass if __name__ == "__main__": plot()
bibliopixel/project/types/spi_interface.py
rec/leds
253
106795
<filename>bibliopixel/project/types/spi_interface.py<gh_stars>100-1000 import functools from ...drivers.spi_interfaces import SPI_INTERFACES USAGE = """ A spi_interface is represented by a string. Possible values are """ + ', '.join(sorted(SPI_INTERFACES.__members__)) @functools.singledispatch def make(c): rais...
codes/models/modules/denoised_LR.py
WestCityInstitute/InvDN
122
106835
import sys sys.path.append('./') import numpy as np import torch import glob import cv2 from skimage import img_as_float32 as img_as_float from skimage import img_as_ubyte import time import os from codes.models.modules.VDN import VDN as DN from codes.data.util import imresize_np def denoise(noisy_path, pretrained_pat...
relation_extraction/core/parser.py
linatal/emnlp2017-relation-extraction
299
106844
<reponame>linatal/emnlp2017-relation-extraction # coding: utf-8 # Copyright (C) 2016 UKP lab # # Author: <NAME> (ukp.tu-darmstadt.de/ukp-home/) # import numpy as np np.random.seed(1) import os import codecs from core import keras_models from core import embeddings class RelParser: def __init__(self, relext_mod...
awxkit/awxkit/api/pages/dashboard.py
Avinesh/awx
11,396
106847
from awxkit.api.resources import resources from . import base from . import page class Dashboard(base.Base): pass page.register_page(resources.dashboard, Dashboard)
data/data_conv/create_lda.py
huonw/nmslib
2,031
106851
<reponame>huonw/nmslib #!/usr/bin/env python import logging, gensim, bz2, sys logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # load id->word mapping (the dictionary), one of the results of step 2 above id2word = gensim.corpora.Dictionary.load_from_text('sparse_wiki_wordids....
json_to_models/dynamic_typing/__init__.py
bogdandm/attrs-api-client
111
106866
<filename>json_to_models/dynamic_typing/__init__.py from .base import ( BaseType, ImportPathList, MetaData, Null, Unknown, get_hash_string ) from .complex import ComplexType, DDict, DList, DOptional, DTuple, DUnion, SingleType, StringLiteral from .models_meta import AbsoluteModelRef, ModelMeta, ModelPtr from .strin...
kili/mutations/user/fragments.py
ASonay/kili-playground
214
106881
<gh_stars>100-1000 """ Fragments of user mutations """ AUTH_PAYLOAD_FRAGMENT = ''' id token user { id } ''' USER_FRAGMENT = ''' id '''
batchflow/models/torch/repr_mixin.py
analysiscenter/dataset
101
106883
<gh_stars>100-1000 """ Mixins for nn.Modules for better textual visualization. """ from textwrap import indent class LayerReprMixin: """ Adds useful properties and methods for nn.Modules, mainly related to visualization and introspection. """ VERBOSITY_THRESHOLD = 10 @property def num_frozen_paramet...
src/enamlnative/widgets/fragment.py
codelv/enaml-native
237
106903
""" Copyright (c) 2017, <NAME>. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on May 20, 2017 @author: jrm """ from atom.api import Typed, ForwardTyped, Bool, observe from enaml.core.declarative import d_ from enaml.core.conditional ...