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 |
|---|---|---|---|---|
python/cuml/test/test_prims.py | Nicholas-7/cuml | 2,743 | 117391 | <gh_stars>1000+
# Copyright (c) 2019-2020, 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
#
# Unless required by applic... |
neural_parts/models/__init__.py | naynasa/neural_parts_fork | 137 | 117392 | <gh_stars>100-1000
import torch
try:
from radam import RAdam
except ImportError:
pass
from .flexible_primitives import FlexiblePrimitivesBuilder, \
train_on_batch as train_on_batch_with_flexible_primitives, \
validate_on_batch as validate_on_batch_with_flexible_primitives
class OptimizerWrapper(objec... |
utils/clean_json5.py | rw1nkler/prjxray | 583 | 117445 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import pyjson5
import simplejson
impo... |
inference/centernet.py | donnyyou/centerX | 350 | 117457 | <reponame>donnyyou/centerX<filename>inference/centernet.py
import torch
import torch.nn as nn
from typing import List
import cv2
from .utils import batch_padding
from modeling.backbone import build_backbone
from modeling.layers import *
__all__ = ["CenterNet"]
class CenterNet(nn.Module):
"""
Implement CenterN... |
cvzone/SerialModule.py | mulakkalfaizal/cvzone | 412 | 117463 | """
Serial Module
Uses "pySerial" Package
By: Computer Vision Zone
Website: https://www.computervision.zone/
"""
import serial
import time
import logging
import serial.tools.list_ports
class SerialObject:
"""
Allow to transmit data to a Serial Device like Arduino.
Example send $255255000
"""
def _... |
kedro/pipeline/__init__.py | daniel-falk/kedro | 2,047 | 117466 | """``kedro.pipeline`` provides functionality to define and execute
data-driven pipelines.
"""
from .modular_pipeline import pipeline
from .node import node
from .pipeline import Pipeline
__all__ = ["pipeline", "node", "Pipeline"]
|
blesuite/replay/btsnoop/bt/l2cap.py | jreynders/BLESuite-1 | 198 | 117479 | """
Parse L2CAP packets
"""
import struct
from . import hci_acl
"""
Fixed channel ids for L2CAP packets
References can be found here:
* https://www.bluetooth.org/en-us/specification/adopted-specifications - Core specification 4.1
** [vol 3] Part A (Section 2.1) - Channel identifiers
"""
L2CAP_CID_NUL = 0x000... |
thermo/property_package_constants.py | RoryKurek/thermo | 380 | 117506 | <filename>thermo/property_package_constants.py
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2018, 2019 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation f... |
tests/test_codec.py | xkortex/ulid | 303 | 117534 | <reponame>xkortex/ulid
"""
test_codec
~~~~~~~~~~
Tests for the :mod:`~ulid.codec` module.
"""
import datetime
import time
import pytest
from ulid import base32, codec, ulid
UNSUPPORTED_TIMESTAMP_TYPE_EXC_REGEX = (r'Expected datetime, int, float, str, memoryview, Timestamp'
... |
python/triton/language/random.py | h-vetinari/triton | 146 | 117541 | import triton
from . import core as tl
PHILOX_KEY_A: tl.constexpr = -1640531527 # 0x9E3779B9
PHILOX_KEY_B: tl.constexpr = -1150833019 # <KEY>
PHILOX_ROUND_A: tl.constexpr = -766435501 # 0xD2511F53
PHILOX_ROUND_B: tl.constexpr = -845247145 # 0xCD9E8D57
N_ROUNDS_DEFAULT = 10 # Default number of rounds for philox
#... |
__scraping__/myaccount.umn.edu/main.py | whitmans-max/python-examples | 140 | 117543 | <reponame>whitmans-max/python-examples
#!/usr/bin/env python3
# date: 2020.02.26
# https://stackoverflow.com/questions/60406035/how-to-scrape-the-details-from-a-website-based-on-the-details-in-spread-sheet
# https://pastebin.com/evjdtpuA
# https://pastebin.com/J1UaYVzt
import selenium.webdriver
def scrape1(... |
TimeWrapper_JE/venv/Lib/site-packages/setuptools/_distutils/debug.py | JE-Chen/je_old_repo | 207 | 117552 | <gh_stars>100-1000
import os
# If DISTUTILS_DEBUG is anything other than the empty string, we run in
# debug mode.
DEBUG = os.environ.get('DISTUTILS_DEBUG')
|
src/data/orthofoto/tile_loader.py | grischard/OSMDeepOD | 156 | 117555 | from src.base.tile import Tile
class TileLoader:
def __init__(self, bbox=None, image_api=None):
self.bbox = bbox
self.image_api = image_api
self.tile = None
def load_tile(self):
image = self.image_api.get_image(self.bbox)
self.tile = Tile(image, self.bbox)
retu... |
deeppy/expr/nnet/spatial.py | purushothamgowthu/deeppy | 1,170 | 117593 | <reponame>purushothamgowthu/deeppy
import cudarray as ca
from ...base import ParamMixin
from ...parameter import Parameter
from ..base import Unary
def padding(win_shape, border_mode):
if border_mode == 'valid':
def pad_fun(win_size): return 0
elif border_mode == 'same':
def pad_fun(win_size):... |
notebooks/test.py | vishalbelsare/LocalGraphClustering | 106 | 117597 | <gh_stars>100-1000
from localgraphclustering import *
import time
import numpy as np
# Read graph. This also supports gml and graphml format.
g = GraphLocal('./datasets/senate.edgelist','edgelist',' ')
# Call the global spectral partitioning algorithm.
eig2 = fiedler(g)
# Round the eigenvector
output_sc = sweep_cut... |
models/methods/SwinTrack/modules/encoder/cross_attention_fusion/builder.py | zhangzhengde0225/SwinTrack | 143 | 117600 | <reponame>zhangzhengde0225/SwinTrack
from .cross_attention_fusion import FeatureFusion, FeatureFusionEncoder
from ....positional_encoding.untied.absolute import Untied2DPositionalEncoder
from ....positional_encoding.untied.relative import generate_2d_relative_positional_encoding_index, \
RelativePosition2DEncoder
... |
examples/http/http_players.py | timgates42/netius | 107 | 117607 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... |
cpgf/samples/irrlicht/02.quake3map.py | mousepawmedia/libdeps | 187 | 117619 | def start() :
driverType = irr.driverChoiceConsole();
if driverType == irr.EDT_COUNT :
return 1;
device = irr.createDevice(driverType, irr.dimension2d_u32(640, 480));
if device == None :
return 1;
driver = device.getVideoDriver();
smgr = device.getSceneManager();
device.getFileSystem().addZi... |
metrics/metric_monitor.py | apple/ml-cvnets | 209 | 117622 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from typing import Optional, Tuple, Any
from torch import Tensor
from utils.tensor_utils import tensor_to_python_float
from .topk_accuracy import top_k_accuracy
from .intersection_over_union import compute_miou_ba... |
sendWhatsappMessage.py | systemquant/DeFi_PanCakeSwapBot | 142 | 117627 | import pywhatkit as py
import keyboard
import time
from datetime import datetime
def sendMessage(numbers, message, price):
for number in numbers:
py.sendwhatmsg(number, "{}: {:.10f}".format(message, price), datetime.now().hour,
datetime.now().minute + 2)
keyboard.press_and_r... |
tests/test_tokenization.py | jayten42/pororo | 1,137 | 117633 | """Test Tokenization module"""
import unittest
from pororo import Pororo
class PororoTokenizerTester(unittest.TestCase):
def test_modules(self):
mecab = Pororo(task="tokenize", lang="ko", model="mecab_ko")
mecab_res = mecab("안녕 나는 민이라고 해.")
self.assertIsInstance(mecab_res, list)
... |
examples/rl/train/evaluation.py | ONLYA/RoboGrammar | 156 | 117655 | import numpy as np
import torch
import time
import gym
from a2c_ppo_acktr import utils
from a2c_ppo_acktr.envs import make_vec_envs
from common.common import *
import pyrobotdesign as rd
def evaluate(args, actor_critic, ob_rms, env_name, seed, num_processes, device):
eval_envs = make_vec_envs(env_name, seed + nu... |
tracardi/domain/settings.py | bytepl/tracardi | 153 | 117660 | from typing import Any
from pydantic import BaseModel
from tracardi.domain.enum.yes_no import YesNo
class Settings(BaseModel):
enabled: bool = True
hidden: bool = False
@staticmethod
def as_bool(state: YesNo):
return state.value == state.yes
class SystemSettings(BaseModel):
label: str
... |
maml/apps/symbolic/tests/__init__.py | anooptp/maml | 161 | 117666 | <reponame>anooptp/maml
"""
Tests for symbolic package.
"""
|
metakernel/magics/get_magic.py | StephanRempel/metakernel | 276 | 117673 | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic
class GetMagic(Magic):
def line_get(self, variable):
"""
%get VARIABLE - get a variable from the kernel in a Python-type.
This line magic is used to get a v... |
data_structures/bst/bt_to_bst.py | Inquis1t0r/python-ds | 1,723 | 117687 | <filename>data_structures/bst/bt_to_bst.py<gh_stars>1000+
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def store_inorder(root, inorder):
if root is None:
return
store_inorder(root.left, inorder)
inorder.append(root.data)
s... |
yabgp/message/attribute/largecommunity.py | mengjunyi/yabgp | 203 | 117734 | <filename>yabgp/message/attribute/largecommunity.py
# Copyright 2015 Cisco Systems, 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.ap... |
test/python/importer/jit_ir/node_import/utils.py | burntfalafel/torch-mlir-internal | 213 | 117743 | # -*- Python -*-
# This file is licensed under a pytorch-style license
# See LICENSE.pytorch for license information.
# Helpers for the other tests.
import torch
from torch._C import CompilationUnit
# RUN: %PYTHON %s
# Import TorchScript IR string as ScriptFunction.
def create_script_function(func_name, ts_ir_str):... |
openff/toolkit/utils/__init__.py | ijpulidos/openff-toolkit | 120 | 117752 | <gh_stars>100-1000
# General utilities for force fields
from openff.toolkit.utils.utils import * # isort:skip
from openff.toolkit.utils.toolkits import *
|
b01lersbootcampctf2020/goodbye_mr_anderson/exploit.py | nhtri2003gmail/ctf-write-ups | 101 | 117766 | #!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./leaks')
context.log_level = 'INFO'
if not args.REMOTE:
context.log_file = 'local.log'
p = process(binary.path)
else:
context.log_file = 'remote.log'
p = remote('chal.ctf.b01lers.com', 1009)
p.recvuntil('goodbye, Mr. Anderson.\n')
# binsh... |
utils/misc.py | niqbal996/ViewAL | 126 | 117772 | <gh_stars>100-1000
import numpy as np
from utils.colormaps import map_segmentation_to_colors
import constants
import os
import torch
def get_learning_rate(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
def visualize_point_cloud(world_coordinates):
import open3d as o3... |
lib/sandbox/python/check_all_process_names.py | Azh4rR31gn5/Winpayloads | 1,382 | 117810 | <filename>lib/sandbox/python/check_all_process_names.py
#
# Checks all loaded process names, Python
# Module written by <NAME>
# Website: arvanaghi.com
# Twitter: @arvanaghi
# Edited for use in winpayloads
import win32pdh
import sys
EvidenceOfSandbox = []
sandboxProcesses = "vmsrvc", "tcpview", "wireshark", "visu... |
deep_qa/training/losses.py | richarajpal/deep_qa | 459 | 117812 | <gh_stars>100-1000
from keras import backend as K
from ..tensors.backend import VERY_NEGATIVE_NUMBER, VERY_LARGE_NUMBER
def ranking_loss(y_pred, y_true):
"""
Using this loss trains the model to give scores to all correct elements in y_true that are
higher than all scores it gives to incorrect elements in ... |
dpwn/models/semantic_cnn.py | macdaliot/deep-pwning | 557 | 117821 | <filename>dpwn/models/semantic_cnn.py
import tensorflow as tf
import utils.utils as utils
class SemanticCNN:
def __init__(self, config,
sequence_length, vocab_size, embedding_size, num_filters):
self.config = config
self.sequence_length = sequence_length
self.vocab_size = vocab_si... |
tests/test_config.py | nikhil153/codecarbon | 346 | 117822 | import os
import unittest
from textwrap import dedent
from unittest import mock
from unittest.mock import patch
from codecarbon.core.config import (
clean_env_key,
get_hierarchical_config,
parse_env_config,
parse_gpu_ids,
)
from codecarbon.emissions_tracker import EmissionsTracker
from tests.testutils ... |
tests/bitcoin/gen_test_inputs.py | febuiles/two1-python | 415 | 117867 | import json
import os
import random
import requests
import sys
import time
CHAIN_API_KEY = os.environ.get('CHAIN_API_KEY', None)
CHAIN_API_SECRET = os.environ.get('CHAIN_API_SECRET', None)
def get_from_chain(url_adder):
url = 'https://api.chain.com/v2/bitcoin/%s' % (url_adder)
ok = False
while not ok:
... |
HybridHaskellPythonCorefAnaphoraResolution/python_coreference_anaphora_resolution_server/test_client.py | vojkog/haskell_tutorial_cookbook_examples | 170 | 117874 | from __future__ import print_function
from urllib.request import Request, urlopen
import urllib
base_uri = 'http://127.0.0.1:8000?text='
def coref(text, no_detail=False):
def get_raw_data_from_web(a_uri):
req = Request(a_uri, headers={'User-Agent': 'PythonBook/1.0'})
http_response = urlopen(req)
data ... |
BERT_pairwise_text_classification/model/data.py | rheehot/nlp_implementation | 181 | 117885 | import pandas as pd
import torch
from torch.utils.data import Dataset
from typing import Tuple, List, Callable
class Corpus(Dataset):
"""Corpus class"""
def __init__(self, filepath: str, transform_fn: Callable[[str], List[int]]) -> None:
"""Instantiating Corpus class
Args:
filepat... |
tools/perf/contrib/vr_benchmarks/shared_android_vr_page_state.py | zipated/src | 2,151 | 117977 | # 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.
import os
from core import path_util
from devil.android.sdk import intent # pylint: disable=import-error
path_util.AddAndroidPylibToPath()
from pylib.utils ... |
recipes/Python/87369_Priority_Queue/recipe-87369.py | tdiprima/code | 2,023 | 117997 | <gh_stars>1000+
import Queue
class PriorityQueue(Queue.Queue):
def _put(self, item):
data, priority = item
self._insort_right((priority, data))
def _get(self):
return self.queue.pop(0)[1]
def _insort_right(self, x):
"""Insert item x in list, and keep it sorted assu... |
client/verta/verta/_swagger/_public/uac/model/UacAction.py | CaptEmulation/modeldb | 835 | 118087 | # THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class UacAction(BaseType):
def __init__(self, service=None, role_service_action=None, authz_service_action=None, modeldb_service_action=None):
required = {
"service": False,
"role_service_action": False,
"a... |
chrome/common/extensions/docs/server2/future.py | kjthegod/chromium | 2,151 | 118089 | # Copyright (c) 2012 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 sys
import traceback
_no_value = object()
def _DefaultErrorHandler(error):
raise error
def All(futures, except_pass=None, ex... |
hsctf7/got_it/base.py | nhtri2003gmail/ctf-write-ups | 101 | 118104 | #!/usr/bin/python3
from pwn import *
def scanit(t):
p = process('./got_it')
#p = remote('pwn.hsctf.com', 5004)
p.recvuntil('Give me sumpfink to help me out!\n')
p.sendline(t)
_ = p.recvuntil('worked').split()[-2].split(b'"')[1]
p.close()
return _
for i in range(1,20):
t = '%' + str(i).rjust(2,'0') + '$018... |
Dragon/python/dragon/tools/summary_writer.py | neopenx/Dragon | 212 | 118113 | <gh_stars>100-1000
# --------------------------------------------------------
# Dragon
# Copyright(c) 2017 SeetaTech
# Written by <NAME>
# --------------------------------------------------------
from dragon.core.tensor import Tensor
import dragon.core.workspace as ws
import os
class ScalarSummary(object):
"""Wri... |
thingsboard_gateway/connectors/rest/ssl_generator.py | ferguscan/thingsboard-gateway | 1,123 | 118117 | import datetime
from thingsboard_gateway.tb_utility.tb_utility import TBUtility
try:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography import x509
from cryptog... |
users/token_api.py | Jordzman/explorer | 917 | 118156 | import requests
import json
from tokens.settings import BLOCKCYPHER_API_KEY
def register_new_token(email, new_token, first=None, last=None):
assert new_token and email
post_params = {
"first": "MichaelFlaxman",
"last": "TestingOkToToss",
"email": "<EMAIL>",
"token": new_token... |
tests/torch/_C/csrc/test_fused_layer_norm_rms.py | lipovsek/oslo | 249 | 118158 | # from oslo.torch._C import FusedLayerNormBinder
import torch
import unittest
import itertools
import oslo.torch.nn as onn
class TestFusedRMSNorm(unittest.TestCase):
dtype = torch.float
elementwise_affine = False
normalized_shape = [32, 16]
rtol, atol = None, None
fwd_thresholds = dict(rtol=None,... |
packages/core/minos-microservice-saga/minos/saga/executions/repositories/database/impl.py | minos-framework/minos-python | 247 | 118166 | <gh_stars>100-1000
from __future__ import (
annotations,
)
from typing import (
Optional,
)
from uuid import (
UUID,
)
from minos.common import (
DatabaseMixin,
ProgrammingException,
)
from ....exceptions import (
SagaExecutionNotFoundException,
)
from ...saga import (
SagaExecution,
)
fr... |
scripts/listen_input.py | Dobbie03/orw | 204 | 118175 | #!/usr/bin/env python
from pynput.keyboard import Key, Listener
def on_press(key):
if key == Key.enter:
return False
with Listener(on_press=on_press) as listener:
listener.join()
|
2021/day_11.py | salt-die/Advent-of-Code | 105 | 118229 | <reponame>salt-die/Advent-of-Code
from itertools import count
import numpy as np
from scipy.ndimage import convolve
import aoc_helper
OCTOPI = aoc_helper.utils.int_grid(aoc_helper.day(11))
KERNEL = np.ones((3, 3), dtype=int)
def step(octos):
octos += 1
flashed = np.zeros_like(octos, dtype=bool)
while ... |
tools/ops/test_policylambda.py | al3pht/cloud-custodian | 2,415 | 118231 | <reponame>al3pht/cloud-custodian
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import jmespath
from c7n.config import Config
from c7n.loader import PolicyLoader
from policylambda import dispatch_render
def test_config_rule_policy():
collection = PolicyLoader(Config.empty()).load... |
pylama/libs/__init__.py | rzuckerm/pylama | 463 | 118266 | <reponame>rzuckerm/pylama
""" Support libs. """
|
instances/migrations/0002_permissionset.py | NGXTDN/webvirtcloud | 1,246 | 118288 | # Generated by Django 2.2.12 on 2020-05-27 07:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instances', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PermissionSet',
fields=[
... |
LeetCode/python3/213.py | ZintrulCre/LeetCode_Archiver | 279 | 118292 | class Solution:
def Rob(self, nums, m, n) -> int:
prev, curr = nums[m], max(nums[m], nums[m + 1])
for i in range(m + 2, n):
prev, curr = curr, max(prev + nums[i], curr)
return curr
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
... |
exceptions/intro_objects.py | hugmyndakassi/hvmi | 677 | 118300 | #
# Copyright (c) 2020 Bitdefender
# SPDX-License-Identifier: Apache-2.0
#
import struct
import re
from abc import ABCMeta, abstractmethod
import excfg
import crc32
# Note: We cannot use os.path here since it's os specific and we must be able to run
# this both on windows & linux
DEFAULT_FLAGS = {
"SignatureFlag... |
examples/lp_train/models/__init__.py | drcut/QPyTorch | 172 | 118317 | <gh_stars>100-1000
from .vgg import *
from .vgg_low import *
from .preresnet import *
from .preresnet_low import *
|
library/shared/content_providers/content_detectors/source1_common.py | REDxEYE/SourceIO | 199 | 118335 | <gh_stars>100-1000
from pathlib import Path
from typing import Dict, Type
from .source1_base import Source1DetectorBase
from ..content_provider_base import ContentDetectorBase, ContentProviderBase
from .....library.utils.path_utilities import backwalk_file_resolver
from ..source1_content_provider import GameinfoConte... |
cape_webservices/app/app_core.py | edwardmjackson/cape-webservices | 164 | 118342 | # Copyright 2018 BLEMUNDSBURY AI 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
pyabc/external/__init__.py | ICB-DCM/pyABC | 144 | 118365 | <filename>pyabc/external/__init__.py
"""
External simulators
===================
This module can be used to easily interface pyABC with model simulations,
summary statistics calculators and distance functions written in arbitrary
programming languages, only requiring a specified command line interface
and file input a... |
Easy/Please like me (PLSLYKME)/PLEASE LIKE ME.py | sakayaparp/CodeChef | 127 | 118379 | N=int(input("Enter the number of test cases:"))
for i in range(0,N):
L,D,S,C=map(int,input().split())
for i in range(1,D):
if(S>=L):
S+=C*S
break
if L<= S:
print("ALIVE AND KICKING")
else:
print("DEAD AND ROTTING") |
tests/test_cross_entropy.py | KaiyuYue/torchshard | 265 | 118381 | from typing import Optional, List, Callable, Tuple
import torch
import random
import sys
import torch.nn.functional as F
import torch.multiprocessing as mp
import torch.nn.parallel as paralle
import unittest
import torchshard as ts
from testing import IdentityLayer
from testing import dist_worker, assertEqual, set_s... |
armi/materials/magnesium.py | celikten/armi | 162 | 118383 | <filename>armi/materials/magnesium.py
# Copyright 2019 TerraPower, 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 b... |
contrib/integration/session/python/cppcmstest/tester/views.py | gatehouse/cppcms | 388 | 118391 | <gh_stars>100-1000
from django.http import HttpResponse
from django.conf import settings
import cppcms
#
# Create the session pool - note it is thread safe and should be one per projects
# Provide a path to configuration file
#
pool=cppcms.SessionPool(settings.BASE_DIR + '/config.js')
def bin2hex(val):
return ''.j... |
InvenTree/stock/migrations/0024_auto_20200405_2239.py | ArakniD/InvenTree | 656 | 118392 | <gh_stars>100-1000
# Generated by Django 2.2.10 on 2020-04-05 22:39
import InvenTree.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stock', '0023_auto_20200318_1027'),
]
operations = [
migrations.AlterField(
model_name='stoc... |
gcp_variant_transforms/transforms/densify_variants_test.py | tsa87/gcp-variant-transforms | 113 | 118431 | # Copyright 2017 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... |
cpmpy/building_a_house.py | tias/hakank | 279 | 118464 | <reponame>tias/hakank
"""
Building a house, simple scheduling problem in cpmpy.
This model is adapted OPL model sched_intro.mod (examples).
'''
This is a basic problem that involves building a house. The masonry,
roofing, painting, etc. must be scheduled. Some tasks must
necessarily take place before others, and thes... |
Python-3/basic_examples/strings/string_isidentifier.py | ghiloufibelgacem/jornaldev | 1,139 | 118470 | s = 'xyzABC'
print(f'{s} is a valid identifier = {s.isidentifier()}')
s = '0xyz' # identifier can't start with digits 0-9
print(f'{s} is a valid identifier = {s.isidentifier()}')
s = '' # identifier can't be empty string
print(f'{s} is a valid identifier = {s.isidentifier()}')
s = '_xyz'
print(f'{s} is a valid id... |
fuxi/common/thirdparty/wydomain/common.py | cocobear/fuxi | 731 | 118478 | <filename>fuxi/common/thirdparty/wydomain/common.py
# encoding: utf-8
import re
from .config import *
import json
import subprocess
import logging
import requests as requests
import requests as __requests__
# from tldextract import extract, TLDExtract
from .utils.fileutils import FileUtils
import requests.packag... |
autoPyTorch/utils/benchmarking/benchmark_pipeline/set_ensemble_config.py | mens-artis/Auto-PyTorch | 1,657 | 118504 | <filename>autoPyTorch/utils/benchmarking/benchmark_pipeline/set_ensemble_config.py
from hpbandster.core.result import logged_results_to_HBS_result
from autoPyTorch.pipeline.base.pipeline_node import PipelineNode
from autoPyTorch.utils.config.config_option import ConfigOption, to_bool
from autoPyTorch.utils.benchmarking... |
orchestra/migrations/0082_task_tags.py | code-review-doctor/orchestra | 444 | 118515 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-10-02 18:47
from __future__ import unicode_literals
from django.db import migrations
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('orchestra', '0081_step_todolist_templates_to_apply'),
]
operations... |
test/programytest/parser/template/node_tests/test_conditiontype3.py | cdoebler1/AIML2 | 345 | 118558 | <reponame>cdoebler1/AIML2<gh_stars>100-1000
from unittest.mock import patch
import xml.etree.ElementTree as ET
from programy.parser.template.nodes.base import TemplateNode
from programy.parser.template.nodes.condition import TemplateConditionListItemNode
from programy.parser.template.nodes.condition import TemplateCond... |
opendeep/optimization/rmsprop.py | vitruvianscience/OpenDeep | 252 | 118573 | <gh_stars>100-1000
"""
Generic implementation of RMSProp training algorithm.
"""
# standard libraries
import logging
# third party libraries
import theano.tensor as T
from theano.compat.python2x import OrderedDict # use this compatibility OrderedDict
# internal references
from opendeep.utils.constructors import shared... |
positional_encodings/tf_positional_encodings.py | tatp22/multidim-positional-encoding | 145 | 118578 | import tensorflow as tf
import numpy as np
class TFPositionalEncoding2D(tf.keras.layers.Layer):
def __init__(self, channels:int, return_format:str="pos", dtype=tf.float32):
"""
Args:
channels int: The last dimension of the tensor you want to apply pos emb to.
Keyword Args:
... |
sandbox/jorvis/correct_RNAs_missing_genes.py | senjoro/biocode | 355 | 118581 | #!/usr/bin/env python3
"""
This housekeeping script reads a GFF3 file and writes a new one, adding a 'gene'
row for any RNA feature which doesn't have one. The coordinates of the RNA will
be copied.
The initial use-case here was a GFF file dumped from WebApollo which had this issue.
In this particular use case, the... |
tests/test_line.py | themiwi/ggplot | 1,133 | 118617 | <gh_stars>1000+
from ggplot import *
import pandas as pd
import numpy as np
import random
x = np.arange(100)
random.shuffle(x)
df = pd.DataFrame({
'x': x,
'y': np.arange(100)
})
print ggplot(df, aes(x='x', y='y')) + geom_line()
print ggplot(df, aes(x='x', y='y')) + geom_path()
|
chainercv/links/model/mobilenet/mobilenet_v2.py | Manny27nyc/chainercv | 1,600 | 118652 | <filename>chainercv/links/model/mobilenet/mobilenet_v2.py
import numpy as np
import chainer
from chainer.functions import average_pooling_2d
from chainer.functions import clipped_relu
from chainer.functions import softmax
from chainer.functions import squeeze
from chainercv.links.model.mobilenet.expanded_conv_2d impo... |
what_is_the_mixin/demo2_1.py | NightmareQAQ/python-notes | 106 | 118673 |
class HelloMixin:
def display(self):
print('HelloMixin hello')
class SuperHelloMixin:
def display(self):
print('SuperHello hello')
class A(SuperHelloMixin, HelloMixin):
pass
if __name__ == '__main__':
a = A()
a.display()
|
benchmarks/ud_benchmark/scripts/copy_files.py | apjanco/projects | 823 | 118685 | <gh_stars>100-1000
import typer
from pathlib import Path
import glob
import shutil
def main(stem: str, ext: str, input_dir: Path, output_dir: Path):
output_dir.mkdir(parents=True, exist_ok=True)
for filename in glob.glob(str(input_dir.resolve()) + f"/*-{stem}*.{ext}"):
shutil.copy(filename, str(output... |
Tools/cython-epydoc.py | smok-serwis/cython | 6,663 | 118721 | #! /usr/bin/env python
# --------------------------------------------------------------------
import re
from epydoc import docstringparser as dsp
CYTHON_SIGNATURE_RE = re.compile(
# Class name (for builtin methods)
r'^\s*((?P<class>\w+)\.)?' +
# The function name
r'(?P<func>\w+)' +
# The paramete... |
tests/unit/test_check_source_has_all_columns.py | jtalmi/pre-commit-dbt | 153 | 118726 | <reponame>jtalmi/pre-commit-dbt
import pytest
from pre_commit_dbt.check_source_has_all_columns import get_catalog_nodes
from pre_commit_dbt.check_source_has_all_columns import main
# Input schema, valid_catalog, expected return value
TESTS = (
(
"""
sources:
- name: catalog
tables:
- name: wi... |
deep-rl/lib/python2.7/site-packages/OpenGL/raw/GL/ARB/shader_image_load_store.py | ShujaKhalid/deep-rl | 210 | 118743 | '''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
_... |
babybuddy/migrations/0002_add_settings.py | Gitoffomalawn/babybuddy | 922 | 118771 | <reponame>Gitoffomalawn/babybuddy
# -*- coding: utf-8 -*-
from django.db import migrations
def add_settings(apps, schema_editor):
Settings = apps.get_model("babybuddy", "Settings")
User = apps.get_model("auth", "User")
for user in User.objects.all():
if Settings.objects.filter(user=user).count() =... |
ops.py | HAHA-DL/MLDG | 109 | 118777 | import torch.autograd as autograd
import torch.nn.functional as F
from torch.autograd import Variable
def linear(inputs, weight, bias, meta_step_size=0.001, meta_loss=None, stop_gradient=False):
if meta_loss is not None:
if not stop_gradient:
grad_weight = autograd.grad(meta_loss, weight, cre... |
Nasdaq Evolved Network/evolve-feedforward.py | ag88/Test-stock-prediction-algorithms | 385 | 118813 |
# https:github.com/timestocome
# take xor neat-python example and convert it to predict tomorrow's stock
# market change using last 5 days data
# uses Python NEAT library
# https://github.com/CodeReclaimers/neat-python
from __future__ import print_function
import os
import neat
import visualize
import pan... |
SearchService2/appscale/search/query_converter.py | loftwah/appscale | 790 | 118814 | """
Code for turning a GAE Search query into a SOLR query.
"""
import logging
from appscale.search.constants import InvalidRequest
from appscale.search.models import SolrQueryOptions, SolrSchemaFieldInfo
from appscale.search.query_parser import parser
logger = logging.getLogger(__name__)
def prepare_solr_query(gae_... |
src/platform/tomcat/fingerprints/Tomcat33.py | 0x27/clusterd | 539 | 118834 | from src.platform.tomcat.interfaces import AppInterface
class FPrint(AppInterface):
def __init__(self):
super(FPrint, self).__init__()
self.version = "3.3"
self.uri = "/doc/readme"
|
rltime/acting/actor_wrapper.py | frederikschubert/rltime | 147 | 118861 | from .acting_interface import ActingInterface
class ActorWrapper(ActingInterface):
"""Wrapper for a created actor
Allows overriding only specific actor methods while passing through the
rest, similar to gym wrappers
"""
def __init__(self, actor):
super().__init__(*actor.get_spaces())
... |
py/vision/blob_detector.py | wx-b/dm_robotics | 128 | 118863 | # Copyright 2020 DeepMind Technologies 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
dynaconf/vendor/ruamel/yaml/reader.py | sephiartlist/dynaconf | 2,293 | 118884 | from __future__ import absolute_import
_F='\ufeff'
_E='\x00'
_D=False
_C='ascii'
_B='\n'
_A=None
import codecs
from .error import YAMLError,FileMark,StringMark,YAMLStreamError
from .compat import text_type,binary_type,PY3,UNICODE_SIZE
from .util import RegExp
if _D:from typing import Any,Dict,Optional,List,Union,Text,T... |
myia/operations/prim_record_setitem.py | strint/myia | 222 | 118915 | <filename>myia/operations/prim_record_setitem.py
"""Definitions for the primitive `record_setitem`."""
from .. import lib, xtype
from ..lib import MyiaAttributeError, MyiaTypeError, standard_prim, typecheck
from . import primitives as P
@standard_prim(P.record_setitem)
async def infer_record_setitem(
self, engin... |
SimPEG/utils/curv_utils.py | prisae/simpeg | 358 | 118929 | <reponame>prisae/simpeg<gh_stars>100-1000
from discretize.utils import volTetra, indexCube, faceInfo
|
cords/utils/data/dataloader/SSL/adaptive/retrievedataloader.py | krishnatejakk/AUTOMATA | 185 | 118941 | <reponame>krishnatejakk/AUTOMATA
from .adaptivedataloader import AdaptiveDSSDataLoader
from cords.selectionstrategies.SSL import RETRIEVEStrategy
import time, copy
# RETRIEVE
class RETRIEVEDataLoader(AdaptiveDSSDataLoader):
def __init__(self, train_loader, val_loader, dss_args, logger, *args, **kwargs):
... |
src/debugpy/_vendored/pydevd/tests_python/resources/_debugger_case4.py | r3m0t/debugpy | 695 | 118957 | <filename>src/debugpy/_vendored/pydevd/tests_python/resources/_debugger_case4.py
import time
class ProceedContainer:
proceed = False
def exit_while_loop():
ProceedContainer.proceed = True
return 'ok'
def sleep():
while not ProceedContainer.proceed: # The debugger should change the proceed to True... |
gffutils/test/expected.py | aswarren/gffutils | 171 | 118992 | <gh_stars>100-1000
# expected data for tests using FBgn0031208.gff and FBgn0031208.gtf files
# list the children and their expected first-order parents for the GFF test file.
GFF_parent_check_level_1 = {'FBtr0300690':['FBgn0031208'],
'FBtr0300689':['FBgn0031208'],
... |
wouso/core/scoring/models.py | AlexandruGhergut/wouso | 117 | 119003 | import logging
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
from wouso.core.common import Item, CachedItem
from wouso.core.decorators import cached_method, drop_cache
from wouso.core.game import get_games
from wouso.core.game.models import Game
class Coin(Cach... |
dmb/modeling/__init__.py | jiaw-z/DenseMatchingBenchmark | 160 | 119004 | from .flow.models import _META_ARCHITECTURES as _FLOW_META_ARCHITECTURES
from .stereo.models import _META_ARCHITECTURES as _STEREO_META_ARCHITECTURES
_META_ARCHITECTURES = dict()
_META_ARCHITECTURES.update(_FLOW_META_ARCHITECTURES)
_META_ARCHITECTURES.update(_STEREO_META_ARCHITECTURES)
def build_model(cfg):
met... |
application/main/routers/image_classifier.py | willuvbb/test_fastapi_template | 128 | 119037 | <gh_stars>100-1000
from fastapi import File, UploadFile
from fastapi.routing import APIRouter
from application.initializer import LoggerInstance
from application.main.services.image_classification_service import ImageClassificationService
from application.main.utility.manager.image_utils import BasicImageUtils
image_... |
jump_bot/jumpbot/settings.py | beatyou/wechat_jump_game | 17,238 | 119056 | # Wechat Jump Bot (iOS)
# ----------------------------------------------------------------------------
import os
CURRENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(CURRENT_DIR)
PROJECT_DIR = "jumpbot/"
# -----------------------------------------------------------... |
skfda/misc/metrics/_angular.py | jiduque/scikit-fda | 147 | 119088 | from __future__ import annotations
from typing import Optional, TypeVar, Union
import numpy as np
from typing_extensions import Final
from ...representation import FData
from ...representation._typing import NDArrayFloat
from .._math import cosine_similarity, cosine_similarity_matrix
from ._utils import pairwise_met... |
jam/langs.py | pubmania/jam-py | 384 | 119111 | import os
import sqlite3
import json
import datetime
from shutil import copyfile
from werkzeug._compat import iteritems, to_bytes, to_unicode
from jam.third_party.filelock import FileLock
import jam
LANG_FIELDS = ['id', 'f_name', 'f_language', 'f_country', 'f_abr', 'f_rtl']
LOCALE_FIELDS = [
'f_decimal_point', 'f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.