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 |
|---|---|---|---|---|
Python3/131.py | rakhi2001/ecom7 | 854 | 94215 | <gh_stars>100-1000
__________________________________________________________________________________________________
sample 56 ms submission
class Solution:
def partition(self, s: str) -> List[List[str]]:
def make_results(index,pallindromes, result, results):
if index >= len(s):
... |
incomplete/rasterizer/rasterizer/shape.py | choosewhatulike/500lines | 26,185 | 94289 | <gh_stars>1000+
from color import Color
from itertools import product
from geometry import Vector
import random
class SceneObject:
def draw(self, image):
raise NotImplementedError("Undefined method")
class Shape(SceneObject):
def __init__(self, color=None):
self.color = color if color is not N... |
Chapter03/email_spam.py | karim7262/Python-Machine-Learning-By-Example | 106 | 94307 | from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import names
from nltk.stem import WordNetLemmatizer
import glob
import os
import numpy as np
file_path = 'enron1/ham/0007.1999-12-14.farmer.ham.txt'
with open(file_path, 'r') as infile:
ham_sample = infile.read()
print(ham_sample)
fil... |
MIDI_CLUE_BLE_Glove/code.py | gamblor21/Adafruit_Learning_System_Guides | 665 | 94354 | <reponame>gamblor21/Adafruit_Learning_System_Guides
"""
CLUE BLE MIDI
Sends MIDI CC values based on accelerometer x & y and proximity sensor
Touch #0 switches Bank/Preset patches
Touch #1 picks among the three CC lines w A&B buttons adjusting CC numbers
Touch #2 starts/stops sending CC messages (still allows Program Ch... |
axelrod/player.py | nandhinianandj/Axelrod | 596 | 94397 | import copy
import inspect
import itertools
import types
import warnings
from typing import Any, Dict
import numpy as np
from axelrod import _module_random
from axelrod.action import Action
from axelrod.game import DefaultGame
from axelrod.history import History
from axelrod.random_ import RandomGenerator
C, D = Acti... |
models/necks/utils.py | AlexandreDh/ACAR-Net | 162 | 94437 | <filename>models/necks/utils.py
import numpy as np
def bbox_jitter(bbox, num, delta):
w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
if num == 1:
jitter = np.random.uniform(-delta, delta, 4)
bboxes = [[max(bbox[0] + jitter[0] * w, 0.), min(bbox[1] + jitter[1] * h, 1.),
max... |
scripts/data_analysis/active_areas.py | lixiny/ContactPose | 199 | 94460 | <reponame>lixiny/ContactPose<filename>scripts/data_analysis/active_areas.py
# Copyright (c) Facebook, Inc. and its affiliates.
# Code by <NAME>
"""
Discovers 'active areas' i.e. areas on the object surface most frequently
touched by a certain part of the hand. See Figure 7 in the paper
https://arxiv.org/pdf/2007.09... |
sparse_merkle_tree/new_bintrie_hex.py | kevaundray/research | 1,351 | 94477 | from ethereum.utils import sha3, encode_hex
class EphemDB():
def __init__(self, kv=None):
self.reads = 0
self.writes = 0
self.kv = kv or {}
def get(self, k):
self.reads += 1
return self.kv.get(k, None)
def put(self, k, v):
self.writes += 1
self.kv[k... |
rltime/policies/torch/distributions/distribution_layer.py | frederikschubert/rltime | 147 | 94503 | import torch
class DistributionLayer(torch.nn.Module):
"""A distribution layer for action selection (e.g. for actor-critic)"""
def __init__(self, action_space, input_size):
"""Initializes the distribution layer for the given action space and
input_size (i.e. the output size of the model)
... |
notes_index.py | PrajvalRaval/PlainNotes | 300 | 94510 | # -*- coding: utf-8 -*-
import sublime, sublime_plugin
import os, fnmatch, re
TAB_SIZE = 2
COL_WIDTH = 30
def settings():
return sublime.load_settings('Notes.sublime-settings')
def get_root():
project_settings = sublime.active_window().active_view().settings().get('PlainNotes')
if project_settings:
... |
tests/archive/__init__.py | ZabeMath/pywikibot | 326 | 94519 | <gh_stars>100-1000
"""THIS DIRECTORY IS TO HOLD TESTS FOR ARCHIVED SCRIPTS."""
|
tests/transformer/test_import.py | rahulbahal7/restricted-python | 236 | 94550 | <gh_stars>100-1000
from RestrictedPython import compile_restricted_exec
import_errmsg = (
'Line 1: "%s" is an invalid variable name because it starts with "_"')
def test_RestrictingNodeTransformer__visit_Import__1():
"""It allows importing a module."""
result = compile_restricted_exec('import a')
as... |
autobahn/wamp/gen/wamp/proto/PublisherFeatures.py | rapyuta-robotics/autobahn-python | 1,670 | 94563 | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: proto
import flatbuffers
class PublisherFeatures(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsPublisherFeatures(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
... |
samples/nta_enable_disable_cbqos_sources.py | john-westcott-iv/orionsdk-python | 177 | 94564 | <reponame>john-westcott-iv/orionsdk-python
from __future__ import print_function
import re
import requests
import pprint
from orionsdk import SwisClient
def main():
# Connect to SWIS
server = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(server, username, password)
# Disable/E... |
Examples/AppKit/CocoaBindings/ControlledPreferences/FontNameToDisplayNameTransformer.py | Khan/pyobjc-framework-Cocoa | 132 | 94578 | <gh_stars>100-1000
#
# FontNameToDisplayNameTransformer.py
# ControlledPreferences
#
# Converted by u.fiedler on 04.02.05.
# with great help from <NAME> - Thank you Bob!
#
# The original version was written in Objective-C by <NAME>
# at http://homepage.mac.com/mmalc/CocoaExamples/controllers.html
from Foundation... |
analysis/tensorflow/fast_em.py | LinziJay/rappor | 797 | 94629 | #!/usr/bin/python
"""
fast_em.py: Tensorflow implementation of expectation maximization for RAPPOR
association analysis.
TODO:
- Use TensorFlow ops for reading input (so that reading input can be
distributed)
- Reduce the number of ops (currently proportional to the number of reports).
May require new Tens... |
tests/generic_relations/migrations/0001_initial.py | daleione/django-rest-framework | 17,395 | 94631 | from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Bookmark',
fields=[
('id', models... |
docs/examples/viz_fiber_odf.py | iamansoni/fury | 149 | 94653 | <gh_stars>100-1000
"""
====================================
Brain Fiber ODF Visualisation
====================================
This example demonstrate how to create a simple viewer for fiber
orientation distribution functions (ODF) using fury's odf_slicer.
"""
# First, we import some useful modules and methods.
impo... |
doc/samples/uptodate_callable.py | m4ta1l/doit | 1,390 | 94721 |
def fake_get_value_from_db():
return 5
def check_outdated():
total = fake_get_value_from_db()
return total > 10
def task_put_more_stuff_in_db():
def put_stuff(): pass
return {'actions': [put_stuff],
'uptodate': [check_outdated],
}
|
stochastic/processes/__init__.py | zaczw/stochastic | 268 | 94736 | from stochastic.processes.continuous import *
from stochastic.processes.diffusion import *
from stochastic.processes.discrete import *
from stochastic.processes.noise import *
|
samcli/commands/delete/__init__.py | torresxb1/aws-sam-cli | 2,959 | 94739 | """
`sam delete` command
"""
# Expose the cli object here
from .command import cli # noqa
|
scripts/compute_rmse.py | yarny/gbdt | 335 | 94750 | <filename>scripts/compute_rmse.py
#!/usr/bin/python
import math
import sys
def ComputeMse(scores, responses):
return math.sqrt(sum([(s-r)*(s-r) for s, r in zip(scores, responses)]) / len(scores))
def main():
scores = [float(line) for line in open(sys.argv[1]).readlines() if not line.startswith('#')]
resp... |
tools/calculate_weights.py | swafe/DeepSegmentor | 150 | 94802 | <gh_stars>100-1000
# -*- using: utf-8 -*-
# Author: <NAME> <<EMAIL>>
import os
import glob
import cv2
import numpy as np
import statistics
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', default='',
help='/path/to/segmentation')
args = parser.parse_args()
def get_weights(la... |
mainapp/migrations/0033_auto_20180817_1413.py | sndp487/rescuekerala | 657 | 94808 | <gh_stars>100-1000
# Generated by Django 2.1 on 2018-08-17 08:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("mainapp", "0032_auto_20180817_0444"),
]
operations = [
migrations.CreateModel(
name="Announcements",
... |
cloudconvert/environment_vars.py | claudep/cloudconvert-python | 153 | 94814 | """Environment Variables to be used inside the CloudConvert-Python-REST-SDK"""
CLOUDCONVERT_API_KEY = "API_KEY"
"""Environment variable defining the Cloud Convert REST API default
credentials as Access Token."""
CLOUDCONVERT_SANDBOX = "true"
"""Environment variable defining if the sandbox API is used instead of the l... |
leetcode/10.regular-expression-matching.py | geemaple/algorithm | 177 | 94816 | # f[i][j] = f[i - 1][j - 1] where s[i - 1] == p[j - 1] || p[j - 1] == '.' case p[j - 1] != '*'
# f[i][j] = f[i][j - 2] or f[i - 1][j] where s[i - 1] == p[j - 2] || p[j - 2] == '.' case p[j - 1] == '*'
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:r... |
server/bsdfs/models.py | paulu/opensurfaces | 137 | 94823 | import math
import json
from colormath.color_objects import RGBColor
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from common.models import UserBase, ResultBase
from common.utils import save_obj_attr_base64_image, get_content_... |
example/paywall/apps.py | prog32/django-getpaid | 220 | 94855 | from django.apps import AppConfig
class Config(AppConfig):
name = "paywall"
verbose_name = "paywall simulator"
label = "paywall"
|
tests/modules/matrix_attention/cosine_matrix_attention_test.py | MSLars/allennlp | 11,433 | 94860 | import torch
from numpy.testing import assert_almost_equal
import numpy
from allennlp.common import Params
from allennlp.common.testing.test_case import AllenNlpTestCase
from allennlp.modules.matrix_attention import CosineMatrixAttention
from allennlp.modules.matrix_attention.matrix_attention import MatrixAttention
... |
forge/blade/systems/recipe.py | jarbus/neural-mmo | 1,450 | 94872 | from forge.blade import lib
class Recipe:
def __init__(self, *args, amtMade=1):
self.amtMade = amtMade
self.blueprint = lib.MultiSet()
for i in range(0, len(args), 2):
inp = args[i]
amt = args[i+1]
self.blueprint.add(inp, amt)
|
server/www/packages/packages-windows/x86/ldap3/version.py | zhoulhb/teleport | 640 | 94889 | <filename>server/www/packages/packages-windows/x86/ldap3/version.py
# THIS FILE IS AUTO-GENERATED. PLEASE DO NOT MODIFY# version file for ldap3
# generated on 2018-08-01 17:55:24.174707
# on system uname_result(system='Windows', node='ELITE10GC', release='10', version='10.0.17134', machine='AMD64', processor='Intel64... |
Python/OOP/InitClass.py | piovezan/SOpt | 148 | 94917 | <filename>Python/OOP/InitClass.py
class A(object):
def __init__(self):
print("init")
def __call__(self):
print("call ")
a = A() #imprime init
A() #imprime call
#https://pt.stackoverflow.com/q/109813/101
|
transfer_model/losses/losses.py | ribeiro-hugo/smplx | 776 | 94920 | <filename>transfer_model/losses/losses.py
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use ... |
backend/projects/models.py | LucasSantosGuedes/App-Gestao | 142 | 94932 | <gh_stars>100-1000
from boards.models import Board
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils import timezone
from users.models import User
class Project(models.Model):
owner = models.ForeignKey(
User, on_delete=models.CASCADE, related_nam... |
Python/ch5-3.py | andjor/deep-learning-with-csharp-and-cntk | 120 | 94978 |
import os
import sys
try:
base_directory = os.path.split(sys.executable)[0]
os.environ['PATH'] += ';' + base_directory
import cntk
os.environ['KERAS_BACKEND'] = 'cntk'
except ImportError:
print('CNTK not installed')
import keras
import keras.utils
import keras.datasets
import keras.models
import ... |
function/python/brightics/function/transform/test/sample_test.py | parkjh80/studio | 202 | 94988 | """
Copyright 2019 Samsung SDS
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 ... |
fs/expose/wsgi/serve_home.py | jwilk-forks/pyfilesystem | 314 | 94993 | from wsgiref.simple_server import make_server
from fs.osfs import OSFS
from wsgi import serve_fs
osfs = OSFS('~/')
application = serve_fs(osfs)
httpd = make_server('', 8000, application)
print "Serving on http://127.0.0.1:8000"
httpd.serve_forever()
|
source/oleTypes.py | marlon-sousa/nvda | 1,592 | 95008 | # typelib <unable to determine filename>
_lcid = 0 # change this if required
from ctypes import *
WSTRING = c_wchar_p
from comtypes import IUnknown
LONG_PTR = c_int
from comtypes import GUID
from comtypes import IUnknown
from ctypes import HRESULT
from comtypes import helpstring
from comtypes import COMMETHOD... |
vnpy/gateway/comstar/comstar_gateway.py | funrunskypalace/vnpy | 19,529 | 95069 | <filename>vnpy/gateway/comstar/comstar_gateway.py
from datetime import datetime
from typing import Optional, Sequence, Dict
from enum import Enum
import pytz
from vnpy.event import EventEngine
from vnpy.trader.gateway import BaseGateway
from vnpy.trader.constant import (
Exchange,
Product,
Offset,
Orde... |
niftynet/layer/rand_flip.py | elias-1/NiftyNet | 1,403 | 95131 | <filename>niftynet/layer/rand_flip.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import warnings
import numpy as np
from niftynet.layer.base_layer import RandomisedLayer
warnings.simplefilter("ignore", UserWarning)
warnings.simplefilter("ignore", RuntimeWarning)
class RandomFli... |
tests/toranj/test-704-multi-radio-scan.py | AdityaHPatwardhan/openthread | 2,962 | 95140 | <gh_stars>1000+
#!/usr/bin/env python3
#
# Copyright (c) 2020, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the abov... |
test/test_registry.py | wangjunyan305/homura | 102 | 95250 | <reponame>wangjunyan305/homura<gh_stars>100-1000
import pytest
from homura.register import Registry
def test_registry():
MODEL_REGISTRY = Registry('model')
MODEL_REGISTRY2 = Registry('model')
assert MODEL_REGISTRY is MODEL_REGISTRY2
@MODEL_REGISTRY.register
def something():
return 1
... |
tests/io/inputs/test_token_parser.py | Ivoz/cleo | 859 | 95309 | import pytest
from cleo.io.inputs.token_parser import TokenParser
@pytest.mark.parametrize(
"string, tokens",
[
("", []),
("foo", ["foo"]),
(" foo bar ", ["foo", "bar"]),
('"quoted"', ["quoted"]),
("'quoted'", ["quoted"]),
("'a\rb\nc\td'", ["a\rb\nc\td"]),
... |
test/modules/losses/test_commitment.py | facebookresearch/multimodal | 128 | 95312 | # Copyright (c) Meta Platforms, Inc. and 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 unittest
import torch
from test.test_utils import assert_expected
from torchmultimodal.modules.losses.v... |
silver/views.py | DocTocToc/silver | 222 | 95320 | <gh_stars>100-1000
# Copyright (c) 2016 Presslabs SRL
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
src/shared/constants.py | CaliberAI/neutralizing-bias | 169 | 95331 | <filename>src/shared/constants.py
"""
just a lil global variable so everybody knows whether
we have a gpu or not
"""
import torch
CUDA = (torch.cuda.device_count() > 0)
|
support/check_python_prereqs.py | kishorerv93/spinnaker-terraform | 116 | 95365 | #!/usr/bin/env python
import sys
import imp
import re
def main(argv):
cloud_provider = sys.argv[1]
reqd_module_names_and_versions = {}
reqd_module_names_and_versions['requests'] = '2.2.1'
reqd_module_names_and_versions['json'] = '2.0.9'
reqd_module_names_and_versions['docopt'] = '0.6.2'
if ... |
MicropolisCore/src/pyMicropolis/micropolisEngine/micropolisdrawingarea.py | mura/micropolis | 775 | 95379 | <reponame>mura/micropolis<gh_stars>100-1000
# micropolisdrawingarea.py
#
# Micropolis, Unix Version. This game was released for the Unix platform
# in or about 1990 and has been modified for inclusion in the One Laptop
# Per Child program. Copyright (C) 1989 - 2007 Electronic Arts Inc. If
# you need assistance with ... |
sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/__init__.py | rsdoherty/azure-sdk-for-python | 207 | 95423 | <reponame>rsdoherty/azure-sdk-for-python
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsof... |
bin/api_connector_splunk/jsl/fields/util.py | CyberGRX/api-connector-splunk | 237 | 95425 | # coding: utf-8
import re
import sre_constants
from ..roles import Resolvable
def validate_regex(regex):
"""
:param str regex: A regular expression to validate.
:raises: ValueError
"""
try:
re.compile(regex)
except sre_constants.error as e:
raise ValueError('Invalid regular ex... |
Chapter10/c10_13_fig.py | John-ye666/Python-for-Finance-Second-Edition | 236 | 95447 | <reponame>John-ye666/Python-for-Finance-Second-Edition
# -*- coding: utf-8 -*-
"""
Name : c10_13_fig.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : <NAME>
Date : 6/6/2017
email : <EMAIL>
<EMAIL>
"""
from scipy import exp,sqrt,stats,arange,on... |
gui_cvs/event.py | Misaka17032/AidLearning-FrameWork | 5,245 | 95460 | <filename>gui_cvs/event.py<gh_stars>1000+
from cvs import *
class MyApp(App):
def __init__(self, *args):
super(MyApp, self).__init__(*args)
def main(self):
container = gui.VBox(width=120, height=100)
self.lbl = gui.Label('Hello world!')
self.bt = gui.Button('Hello name!')
... |
align/pdk/finfet/transistor_array.py | pretl/ALIGN-public | 119 | 95517 | <reponame>pretl/ALIGN-public
import math
from itertools import cycle, islice
from align.cell_fabric import transformation
from align.schema.transistor import Transistor, TransistorArray
from . import CanvasPDK, MOS
import logging
logger = logging.getLogger(__name__)
logger_func = logger.debug
class MOSGenerator(Canv... |
assembly/scaffold/views/views.py | chermed/assembly | 176 | 95519 | # -*- coding: utf-8 -*-
"""
Assembly: %MODULE_NAME%.py
"""
from assembly import (Assembly,
asm,
models,
request,
response,
HTTPError)
# -----------------------------------------------------------------------... |
Funções Analíticas/Virtualenv/Lib/site-packages/setuptools/tests/textwrap.py | Leonardo-Maciel/PSO_Maciel | 1,744 | 95580 | <reponame>Leonardo-Maciel/PSO_Maciel<gh_stars>1000+
import textwrap
def DALS(s):
"dedent and left-strip"
return textwrap.dedent(s).lstrip()
|
tests/api/v1/test_fields.py | omertuc/CTFd | 3,592 | 95597 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from CTFd.models import Fields, TeamFieldEntries, Teams, UserFieldEntries, Users
from tests.helpers import (
create_ctfd,
destroy_ctfd,
gen_field,
gen_team,
login_as_user,
register_user,
)
def test_api_custom_fields():
app = create_ctfd()
... |
zeus/testutils/pytest.py | conrad-kronos/zeus | 221 | 95605 | <gh_stars>100-1000
import os
import pytest
import responses
from sqlalchemy import event
from sqlalchemy.orm import Session
from sqlalchemy.testing import assertions, assertsql
from zeus import auth, config
from zeus.storage.mock import FileStorageCache
class CountStatementsWithDebug(assertsql.AssertRule):
def ... |
train.py | bckim92/sequential-knowledge-transformer | 135 | 95617 | import os
import math
from pprint import PrettyPrinter
import random
import numpy as np
import torch # Torch must be imported before sklearn and tf
import sklearn
import tensorflow as tf
import better_exceptions
from tqdm import tqdm, trange
import colorlog
import colorful
from utils.etc_utils import set_logger, set... |
share/lib/python/neuron/expect_hocerr.py | niltonlk/nrn | 203 | 95622 | <filename>share/lib/python/neuron/expect_hocerr.py<gh_stars>100-1000
import sys
from io import StringIO
import inspect
from neuron import h
pc = h.ParallelContext()
nhost = pc.nhost()
quiet = True
def set_quiet(b):
global quiet
old = quiet
quiet = b
return old
def printerr(e):
if not quiet:
... |
modules/nltk_contrib/lpath/treecanvasnode.py | h4ck3rm1k3/NLP-project | 123 | 95624 | from qt import *
from qtcanvas import *
from lpathtree_qt import *
class Point:
def __init__(self, *args):
if len(args) == 2 and \
(isinstance(args[0],int) or isinstance(args[0],float)) and \
(isinstance(args[1],int) or isinstance(args[0],float)):
self.x = float(args[0])
... |
autogl/module/nas/space/single_path.py | THUMNLab/AutoGL | 824 | 95625 | <filename>autogl/module/nas/space/single_path.py
from autogl.module.nas.space.operation import gnn_map
import typing as _typ
import torch
import torch.nn.functional as F
from . import register_nas_space
from .base import apply_fixed_architecture
from .base import BaseSpace
from ...model import BaseModel
from ....util... |
uncalled/sim_utils.py | skovaka/nanopore_aligner | 489 | 95636 | <gh_stars>100-1000
#!/usr/bin/env python
import sys, os
import numpy as np
import argparse
from uncalled.pafstats import parse_paf
from time import time
from collections import Counter
SAMP_RATE = 4000
CHS = np.arange(512)+1
NCHS = len(CHS)
NTICKS = 32
TICK_MOD = NCHS / NTICKS
PROG = " progress "
SP = '-'*( (NTICKS ... |
Python/Algorithms/SearchingAlgorithms/SequentialSearch.py | m-payal/AlgorithmsAndDataStructure | 195 | 95669 | <filename>Python/Algorithms/SearchingAlgorithms/SequentialSearch.py
# Implementation of SequentialSearch in python
# Python3 code to sequentially search key in arr[].
# If key is present then return its position,
# otherwise return -1
# If return value -1 then print "Not Found!"
# else print position at which element ... |
tests/requests/valid/028.py | bojiang/gunicorn | 6,851 | 95682 | <reponame>bojiang/gunicorn
from gunicorn.config import Config
cfg = Config()
cfg.set("strip_header_spaces", True)
request = {
"method": "GET",
"uri": uri("/stuff/here?foo=bar"),
"version": (1, 1),
"headers": [
("CONTENT-LENGTH", "3"),
],
"body": b"xyz"
} |
angr/engines/pcode/arch/ArchPcode_PIC_17_LE_16_PIC_17C7xx.py | matthewpruett/angr | 6,132 | 95696 | <reponame>matthewpruett/angr
###
### This file was automatically generated
###
from archinfo.arch import register_arch, Endness, Register
from .common import ArchPcode
class ArchPcode_PIC_17_LE_16_PIC_17C7xx(ArchPcode):
name = 'PIC-17:LE:16:PIC-17C7xx'
pcode_arch = 'PIC-17:LE:16:PIC-17C7xx'
description ... |
ursina/scripts/chunk_mesh.py | DropBear586/ursina | 1,431 | 95705 | <reponame>DropBear586/ursina<filename>ursina/scripts/chunk_mesh.py<gh_stars>1000+
from ursina import *
from math import floor
app = Ursina()
t = time.time()
application.asset_folder = application.asset_folder.parent.parent
terrain = Entity(model=Terrain('grass_fields_heightmap', skip=8), texture='grass', texture_scal... |
metadata-ingestion/src/datahub/ingestion/extractor/mce_extractor.py | pramodbiligiri/datahub | 3,586 | 95723 | from typing import Iterable, Union
from datahub.emitter.mce_builder import get_sys_time
from datahub.emitter.mcp import MetadataChangeProposalWrapper
from datahub.ingestion.api import RecordEnvelope
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.source import Extractor, WorkUnit
fr... |
uliweb/contrib/datadict/commands.py | timgates42/uliweb | 202 | 95745 | from uliweb.core.commands import Command, CommandManager, get_commands
from optparse import make_option
class DataDictCommand(CommandManager):
#change the name to real command name, such as makeapp, makeproject, etc.
name = 'datadict'
#help information
help = "Data dict tool, create index, validate mod... |
lib/layers/diffeq_layers/__init__.py | arnabgho/ffjord | 518 | 95752 | from .container import *
from .resnet import *
from .basic import *
from .wrappers import *
|
var/spack/repos/builtin/packages/libestr/package.py | kkauder/spack | 2,360 | 95757 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libestr(AutotoolsPackage):
"""C library for string handling (and a bit more)."""
home... |
smartnlp/custom/layer/attention.py | msgi/nlp-tour | 1,559 | 95758 | # coding=utf-8
# created by msgi on 2020/4/1 7:23 下午
import tensorflow as tf
# simple attention mechanism
class BahdanauAttention(tf.keras.layers.Layer):
def __init__(self, units):
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.De... |
tests/test_mailjet_backend.py | bhumikapahariapuresoftware/django-anymail | 1,324 | 95763 | <filename>tests/test_mailjet_backend.py<gh_stars>1000+
import json
from base64 import b64encode
from decimal import Decimal
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from django.core import mail
from django.core.exceptions import ImproperlyConfigured
from django.test import SimpleTest... |
src/application-insights/azext_applicationinsights/vendored_sdks/applicationinsights/models/events_exception_info_py3.py | Mannan2812/azure-cli-extensions | 2,728 | 95771 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
tools/turbinia_job_graph.py | sa3eed3ed/turbinia | 559 | 95772 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 requi... |
examples/fci/10-spin.py | robert-anderson/pyscf | 501 | 95789 | <reponame>robert-anderson/pyscf
#!/usr/bin/env python
#
# Author: <NAME> <<EMAIL>>
#
'''
Assign spin state for FCI wavefunction.
By default, the FCI solver will take Mole attribute spin for the spin state.
It can be overwritten by passing kwarg ``nelec`` to the kernel function of FCI
solver. The nelec argument is a ... |
django_linter/transformers/models.py | enefeq/django_linter | 101 | 95795 | from __future__ import (absolute_import, division,
print_function, unicode_literals)
from astroid import MANAGER, Class, Instance, Function, Arguments, Pass
def transform_model_class(cls):
if cls.is_subtype_of('django.db.models.base.Model'):
core_exceptions = MANAGER.ast_from_modu... |
4_Classification/Classification_Comparison/classification_Comparison.py | labaran1/100DaysofMLCode | 236 | 95804 | <reponame>labaran1/100DaysofMLCode<filename>4_Classification/Classification_Comparison/classification_Comparison.py
# Classification Comparison
# Importing the libraries
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score... |
Data Structure/Matrix/Addition of Two Matrices/SolutionByRiya.py | rajethanm4/Programmers-Community | 261 | 95830 | <filename>Data Structure/Matrix/Addition of Two Matrices/SolutionByRiya.py
rows= int(input("Enter the number of rows: "))
cols= int(input("Enter the number of columns: "))
matrixA=[]
print("Enter the entries rowwise for matrix A: ")
for i in range(rows):
a=[]
for j in range(cols):
a.append(int(input())... |
pingo/examples/pushbutton_led/pushbutton_led.py | pingo-io/pingo-py | 116 | 95904 | <gh_stars>100-1000
"""Pushbutton led.
The led comes on when you press the button.
Connections example found on ./button.png
"""
# -*- coding: utf-8 -*-
import pingo
import sys
try:
print("Loading board...")
board = pingo.detect.get_board()
print("Its ok...")
except Exception as e:
print("Error on g... |
examples/datasets/plot_vertex.py | mvdoc/pycortex | 423 | 95909 | """
================
Plot Vertex Data
================
This plots example vertex data onto an example subject, S1, onto a flatmap
using quickflat. In order for this to run, you have to have a flatmap for
this subject in the pycortex filestore.
The cortex.Vertex object is instantiated with a numpy array of the same si... |
Training Utility/somatictrainer/gestures.py | ZackFreedman/Somatic | 328 | 95925 | <reponame>ZackFreedman/Somatic<gh_stars>100-1000
import logging
import os
import time
from typing import List
import numpy as np
import uuid
import pickle
import bisect
standard_gesture_length = 50 # Length of (yaw, pitch) coordinates per gesture to be fed into ML algorithm
_log_level = logging.DEBUG
class Gesture... |
agents/ppo2_agent.py | christopherhesse/retro-baselines | 134 | 95943 | #!/usr/bin/env python
"""
Train an agent on Sonic using PPO2 from OpenAI Baselines.
"""
import tensorflow as tf
from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
import baselines.ppo2.ppo2 as ppo2
import baselines.ppo2.policies as policies
import gym_remote.exceptions as gre
from sonic_util import make... |
analysis_engine/load_algo_dataset_from_file.py | virdesai/stock-analysis-engine | 819 | 95949 | """
Helper for loading datasets from a file
**Supported environment variables**
::
# to show debug, trace logging please export ``SHARED_LOG_CFG``
# to a debug logger json file. To turn on debugging for this
# library, you can export this variable to the repo's
# included file with the command:
e... |
statsforecast/core.py | Nixtla/statsforecast | 483 | 95973 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/core.ipynb (unless otherwise specified).
__all__ = ['StatsForecast']
# Cell
import inspect
import logging
from functools import partial
from os import cpu_count
import numpy as np
import pandas as pd
# Internal Cell
logging.basicConfig(
format='%(asctime)s %(name)... |
src/pymap3d/mathfun.py | scivision/pymap3d | 108 | 95979 | """
import from Numpy, and if not available fallback to math stdlib
"""
try:
from numpy import (
sin,
cos,
sqrt,
exp,
log,
inf,
isnan,
radians,
tan,
arctan as atan,
hypot,
degrees,
arctan2 as atan2,
arcs... |
recipes/Python/577867_Make_Class_Available_its_Own/recipe-577867.py | tdiprima/code | 2,023 | 95989 | class InwardMeta(type):
@classmethod
def __prepare__(meta, name, bases, **kwargs):
cls = super().__new__(meta, name, bases, {})
return {"__newclass__": cls}
def __new__(meta, name, bases, namespace):
cls = namespace["__newclass__"]
del namespace["__newclass__"]
for na... |
esphome/helpers.py | OttoWinter/esphomeyaml | 249 | 96001 | import codecs
from contextlib import suppress
import logging
import os
from pathlib import Path
from typing import Union
import tempfile
_LOGGER = logging.getLogger(__name__)
def ensure_unique_string(preferred_string, current_strings):
test_string = preferred_string
current_strings_set = set(current_strings... |
PhysicsTools/JetExamples/test/printJetFlavour.py | ckamtsikis/cmssw | 852 | 96002 | <reponame>ckamtsikis/cmssw
import FWCore.ParameterSet.Config as cms
process = cms.Process("testJET")
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True)
)
process.load("FWCore.MessageService.MessageLogger_cfi")
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
process.maxEvents =... |
components/detector.py | awesome-archive/FooProxy | 235 | 96078 | # coding:utf-8
"""
@author : linkin
@email : <EMAIL>
@date : 2018-10-07
"""
import time
import asyncio
import logging
from components.dbhelper import Database
from config.DBsettings import _DB_SETTINGS
from config.DBsettings import _TABLE
from config.config import DETECT_HIGH_AM... |
reactivated/widgets.py | silviogutierrez/reactivated | 178 | 96081 | from typing import Any, Dict, Optional, cast
from django import forms
from django.core.exceptions import ValidationError
from django.forms.models import ModelChoiceIterator
class Autocomplete(forms.Select):
template_name = "reactivated/autocomplete"
def get_context(
self, name: str, value: Any, attr... |
cupcake2/ice2/IceArrowAll2.py | ArthurDondi/cDNA_Cupcake | 205 | 96128 | <filename>cupcake2/ice2/IceArrowAll2.py
from cupcake2.tofu2.ToFuOptions2 import add_sge_arguments, \
add_tmp_dir_argument, add_cluster_summary_report_arguments, \
add_ice_post_arrow_hq_lq_arguments2, \
add_cluster_root_dir_as_positional_argument, \
add_fofn_arguments
from cupcake2.ice2.IceArrow2 import... |
examples/image/cath/datasets/to_ignore/modelnet/modelnet.py | mariogeiger/se3cnn | 170 | 96130 | <reponame>mariogeiger/se3cnn
# pylint: disable=E1101,R,C
import glob
import os
import numpy as np
import torch
import torch.utils.data
import shutil
from functools import partial
from scipy.ndimage import affine_transform
from se3cnn.SO3 import rot
def get_modelnet_loader(root_dir, dataset, mode, size, data_loader_... |
TopQuarkAnalysis/TopJetCombination/python/TtFullLepHypKinSolution_cfi.py | ckamtsikis/cmssw | 852 | 96166 | <reponame>ckamtsikis/cmssw
import FWCore.ParameterSet.Config as cms
#
# module to make the kinematic solution hypothesis
#
ttFullLepHypKinSolution = cms.EDProducer("TtFullLepHypKinSolution",
electrons = cms.InputTag("selectedPatElectrons"),
muons = cms.InputTag("selectedPatMuons"),
jets = cms.Inpu... |
tests/guinea-pigs/unittest/test_changes_name.py | Tirzono/teamcity-messages | 105 | 96167 | <filename>tests/guinea-pigs/unittest/test_changes_name.py
import unittest
from teamcity.unittestpy import TeamcityTestRunner
class Foo(unittest.TestCase):
a = 1
def test_aa(self): pass
def shortDescription(self):
s = str(self.a)
self.a += 10
return s
unittest.main(testRunner... |
pyats-to-netbox/netbox_utils.py | fallenfuzz/netdevops_demos | 104 | 96172 | """Library of functions used to work with netbox.
"""
import pynetbox
import os
# Common mappings for device types and roles
device_roles = {
"CSR1000v": "router",
"ASAv": "firewall",
"NX-OSv 9000": "switch",
"IOSvL2": "switch",
"OTHER": "other",
}
# Constants for Interface Form Factor IDs
FF_100... |
gpytorch/variational/unwhitened_variational_strategy.py | jrg365/gpytorch | 188 | 96175 | #!/usr/bin/env python3
import math
import torch
from gpytorch.variational.cholesky_variational_distribution import CholeskyVariationalDistribution
from .. import settings
from ..distributions import MultivariateNormal
from ..lazy import (
CholLazyTensor,
DiagLazyTensor,
PsdSumLazyTensor,
RootLazyTen... |
docs/tutorial_data-6.py | ankitshah009/dcase_util | 122 | 96202 | import dcase_util
data = dcase_util.utils.Example.feature_container()
data_aggregator = dcase_util.data.Aggregator(
recipe=['flatten'],
win_length_frames=10,
hop_length_frames=1,
)
data_aggregator.aggregate(data)
data.plot() |
foliant/backends/base.py | foliant-docs/foliant | 105 | 96208 | from importlib import import_module
from shutil import copytree
from datetime import date
from logging import Logger
from foliant.utils import spinner
class BaseBackend():
'''Base backend. All backends must inherit from this one.'''
targets = ()
required_preprocessors_before = ()
required_preprocess... |
deps/cndict/bundle_friso.py | rrelledge/RediSearch | 2,098 | 96230 | <gh_stars>1000+
#!/usr/bin/env python
"""
This script gathers settings and dictionaries from friso (a chinese
tokenization library) and generates a C source file that can later be
compiled into RediSearch, allowing the module to have a built-in chinese
dictionary. By default this script will generate a C source file o... |
textract/async-form-table/lambda-process-response/helper/parser.py | srcecde/aws-tutorial-code | 105 | 96243 | <reponame>srcecde/aws-tutorial-code
"""
-*- coding: utf-8 -*-
========================
AWS Lambda
========================
Contributor: <NAME> (<NAME>)
========================
"""
import uuid
class Parse:
def __init__(self, page, get_table, get_kv, get_text):
self.response = page
self.word_map =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.