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 |
|---|---|---|---|---|
venv/lib/python3.8/site-packages/kivy/tools/changelog_parser.py | felipesch92/projeto_kivy | 13,889 | 12600268 | <filename>venv/lib/python3.8/site-packages/kivy/tools/changelog_parser.py<gh_stars>1000+
"""
Changelog parser
================
This generates a changelog from a json file of the PRs of a given milestone,
dumped to json, using the [GitHub CLI](https://github.com/cli/cli).
First, in the command line, create the followi... |
crabageprediction/venv/Lib/site-packages/numpy/typing/tests/data/pass/warnings_and_errors.py | 13rianlucero/CrabAgePrediction | 20,453 | 12600318 | <filename>crabageprediction/venv/Lib/site-packages/numpy/typing/tests/data/pass/warnings_and_errors.py
import numpy as np
np.AxisError("test")
np.AxisError(1, ndim=2)
np.AxisError(1, ndim=2, msg_prefix="error")
np.AxisError(1, ndim=2, msg_prefix=None)
|
src/GridCal/Engine/Devices/groupings.py | mzy2240/GridCal | 284 | 12600325 | # This file is part of GridCal.
#
# GridCal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GridCal is distributed in the hope that... |
tests/test_fuzzing.py | odidev/cmaes | 134 | 12600333 | <reponame>odidev/cmaes
import hypothesis.extra.numpy as npst
import unittest
from hypothesis import given, strategies as st
from cmaes import CMA, SepCMA
class TestFuzzing(unittest.TestCase):
@given(
data=st.data(),
)
def test_cma_tell(self, data):
dim = data.draw(st.integers(min_value=2,... |
src/aihwkit/experiments/experiments/base.py | todd-deshane/aihwkit | 133 | 12600357 | <reponame>todd-deshane/aihwkit
# -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/L... |
test/hlt/pytest/python/com/huawei/iotplatform/client/dto/NotifyRuleEventDTO.py | yuanyi-thu/AIOT- | 128 | 12600379 | <filename>test/hlt/pytest/python/com/huawei/iotplatform/client/dto/NotifyRuleEventDTO.py<gh_stars>100-1000
from com.huawei.iotplatform.client.dto.ActionResult import ActionResult
from com.huawei.iotplatform.client.dto.ConditionReason import ConditionReason
class NotifyRuleEventDTO(object):
reasons = ConditionReas... |
examples/howto/ipywidgets/ipyvolume_camera.py | goncaloperes/bokeh | 15,193 | 12600384 | import ipyvolume as ipv
import ipywidgets as ipw
import numpy as np
from ipywidgets_bokeh import IPyWidget
from bokeh.layouts import column, row
from bokeh.models import Slider
from bokeh.plotting import curdoc
x, y, z = np.random.random((3, 1000))
ipv.quickscatter(x, y, z, size=1, marker="sphere")
plot = ipv.current... |
src/exabgp/configuration/l2vpn/__init__.py | pierky/exabgp | 1,560 | 12600388 | # encoding: utf-8
"""
l2vpn/__init__.py
Created by <NAME> on 2015-06-04.
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
from exabgp.configuration.l2vpn.vpls import ParseVPLS
from exabgp.bgp.message.update.nlri import VPLS
from exabgp.bgp.message.update.... |
inltk/__init__.py | Shubhamjain27/inltk | 814 | 12600416 | <reponame>Shubhamjain27/inltk
name = "inltk" |
homeassistant/components/apple_tv/browse_media.py | MrDelik/core | 22,481 | 12600422 | """Support for media browsing."""
from homeassistant.components.media_player import BrowseMedia
from homeassistant.components.media_player.const import (
MEDIA_CLASS_APP,
MEDIA_CLASS_DIRECTORY,
MEDIA_TYPE_APP,
MEDIA_TYPE_APPS,
)
def build_app_list(app_list):
"""Create response payload for app lis... |
btalib/meta/groups.py | demattia/bta-lib | 352 | 12600469 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 <NAME>
# Use of this source code is governed by the MIT License
######################################################################... |
park/spaces/tuple_space.py | utkarsh5k/park | 180 | 12600470 | from park import core
class Tuple(core.Space):
"""
A tuple (i.e., product) of simpler spaces
Example usage:
self.observation_space = spaces.Tuple((spaces.Discrete(2), spaces.Discrete(3)))
"""
def __init__(self, spaces):
self.spaces = spaces
core.Space.__init__(self, None, None... |
shellpython/__init__.py | wujuguang/shellpy | 706 | 12600476 | <reponame>wujuguang/shellpy
import sys
from shellpython.importer import PreprocessorImporter
_importer = PreprocessorImporter()
def init():
"""Initialize shellpython by installing the import hook
"""
if _importer not in sys.meta_path:
sys.meta_path.insert(0, _importer)
def uninit():
"""Unin... |
burun/0007/codes/coupon_code_generator.py | saurabh896/python-1 | 3,976 | 12600554 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Date: 23-02-15
# Author: Liang
import random
import string
coupon_number = 200
coupon_size = 12
for i in range(coupon_number):
coupon = ''.join(
random.sample(string.digits + string.ascii_uppercase, coupon_size))
print(coupon)
|
srcs/python/kungfu/tensorflow/policy/__init__.py | Pandinosaurus/KungFu | 291 | 12600560 | <filename>srcs/python/kungfu/tensorflow/policy/__init__.py
from .base_policy import BasePolicy
from .policy_hook import PolicyHook
|
m2-modified/ims/common/agentless-system-crawler/crawler/plugins/systems/metric_vm_crawler.py | CCI-MOC/ABMI | 108 | 12600574 | <filename>m2-modified/ims/common/agentless-system-crawler/crawler/plugins/systems/metric_vm_crawler.py
import logging
import time
import psutil
from icrawl_plugin import IVMCrawler
from utils.features import MetricFeature
try:
import psvmi
except ImportError:
psvmi = None
logger = logging.getLogger('crawlut... |
migrations/versions/394f85935d21_.py | eleweek/WatchPeopleCode | 200 | 12600584 | """empty message
Revision ID: 394f85935d21
Revises: 186a4a79b60e
Create Date: 2015-03-20 20:21:01.792691
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '186a4a79b60e'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please ... |
DQM/TrackingMonitorSource/python/TrackingSourceConfig_Tier0_HeavyIons_cff.py | malbouis/cmssw | 852 | 12600586 | import FWCore.ParameterSet.Config as cms
# TrackingMonitor ####
from DQM.TrackingMonitor.TrackerHeavyIonTrackingMonitor_cfi import *
TrackMon_hi = TrackerHeavyIonTrackMon.clone(
FolderName = 'Tracking/TrackParameters',
BSFolderName = 'Tracking/TrackParameters/BeamSpotParameters',
TrackProducer = "hiGeneral... |
test/test_pushsafer.py | linkmauve/apprise | 4,764 | 12600620 | <reponame>linkmauve/apprise
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 <NAME> <<EMAIL>>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to d... |
machine_learning/python/eval_metrics/performance_metrics.py | CarbonDDR/al-go-rithms | 1,253 | 12600632 | # You must estimate the quality of a set of predictions when training a machine learning model. Performance metrics like classification accuracy and root mean squared error can give you a clear objective idea of how good a set of predictions is, and in turn how good the model is that generated them.
# This is importan... |
quant/collect.py | vincent87lee/alphahunter | 149 | 12600655 | <reponame>vincent87lee/alphahunter
# -*- coding:utf-8 -*-
"""
行情采集模块
Project: alphahunter
Author: HJQuant
Description: Asynchronous driven quantitative trading framework
"""
import sys
from collections import defaultdict
from quant import const
from quant.state import State
from quant.utils import tools, logger
fr... |
sfepy/terms/terms_th.py | clazaro/sfepy | 510 | 12600682 | <reponame>clazaro/sfepy<gh_stars>100-1000
import numpy as nm
from sfepy.base.base import Struct
from sfepy.terms.terms import Term
class THTerm(Term):
"""
Base class for terms depending on time history (fading memory
terms).
"""
def eval_real(self, shape, fargs, mode='eval', term_mode=None,
... |
moya/context/dataindex.py | moyaproject/moya | 129 | 12600744 | <filename>moya/context/dataindex.py
from __future__ import unicode_literals
from __future__ import print_function
from ..compat import implements_to_string, text_type, string_types, implements_bool
from operator import truth
@implements_bool
@implements_to_string
class ParseResult(object):
"""An immutable list ... |
1000-1100q/1037.py | rampup01/Leetcode | 990 | 12600759 | <reponame>rampup01/Leetcode
'''
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.
Example 1:
Input: [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]]
Output: false
Note... |
frameworks/Python/pyramid/setup.py | efectn/FrameworkBenchmarks | 5,300 | 12600801 | from setuptools import setup, find_packages
requires = [
"pyramid",
"pyramid_chameleon",
"sqlalchemy[postgresql]",
"gunicorn",
"orjson",
]
tests_require = ["webtest"]
setup(
name="frameworkbenchmarks",
version="0.0",
description="FrameworkBenchmarks",
classifiers=[
"Progra... |
benchmarks/distributed/rpc/parameter_server/data/__init__.py | Hacky-DH/pytorch | 60,067 | 12600806 | from .DummyData import DummyData
data_map = {
"DummyData": DummyData
}
|
src/c3nav/mapdata/migrations/0033_auto_20170807_1423.py | johnjohndoe/c3nav | 132 | 12600891 | <reponame>johnjohndoe/c3nav<filename>src/c3nav/mapdata/migrations/0033_auto_20170807_1423.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-07 12:23
from __future__ import unicode_literals
import c3nav.mapdata.fields
from django.db import migrations
class Migration(migrations.Migration):
depend... |
tests/test_long_tablename.py | Steff94190/sqlalchemy-redshift | 177 | 12600897 | from rs_sqla_test_utils import models
def test_long_tablename(redshift_session):
session = redshift_session
examples = [models.LongTablename(metric=i) for i in range(5)]
session.add_all(examples)
rows = session.query(models.LongTablename.metric)
assert set(row.metric for row in rows) == set([0, 1... |
pygithub3/services/repos/hooks.py | teamorchard/python-github3 | 107 | 12600921 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from . import Service
class Hooks(Service):
""" Consume `Hooks API
<http://developer.github.com/v3/repos/hooks>`_
.. warning::
You must be authenticated and have repository's admin-permission
"""
def list(self, user=None, repo=None):
... |
codigo/Live76/fake_exemplo.py | cassiasamp/live-de-python | 572 | 12600922 | <filename>codigo/Live76/fake_exemplo.py
"""Exemplo do dublê Fake."""
class Pedido:
def __init__(self, valor, frete, usuario):
self.valor = valor
self.frete = frete
self.usuario = usuario
@property
def resumo(self):
"""Informações gerais sobre o pedido."""
return f'... |
boto3_type_annotations_with_docs/boto3_type_annotations/eks/client.py | cowboygneox/boto3_type_annotations | 119 | 12600949 | <reponame>cowboygneox/boto3_type_annotations<filename>boto3_type_annotations_with_docs/boto3_type_annotations/eks/client.py
from typing import Optional
from botocore.client import BaseClient
from botocore.waiter import Waiter
from typing import Union
from typing import Dict
from botocore.paginate import Paginator
cla... |
lingua_franca/lang/common_data_de.py | NeonDaniel/lingua-franca | 191 | 12601009 | _DE_NUMBERS = {
'null': 0,
'ein': 1,
'eins': 1,
'eine': 1,
'einer': 1,
'einem': 1,
'einen': 1,
'eines': 1,
'zwei': 2,
'drei': 3,
'vier': 4,
'fünf': 5,
'sechs': 6,
'sieben': 7,
'acht': 8,
'neun': 9,
'zehn': 10,
'elf': 11,
'zwölf': 12,
'dreiz... |
03-machine-learning-tabular-crossection/09 - Balanceamento/solutions/solution_09.py | abefukasawa/datascience_course | 331 | 12601010 | <reponame>abefukasawa/datascience_course<gh_stars>100-1000
plt.figure(figsize=(12,10)) # on this line I just set the size of figure to 12 by 10.
p=sns.heatmap(diabetes_data_copy.corr(), annot=True,cmap ='RdYlGn') |
dataset/psenet/check_dataloader.py | doem97/PSENet | 1,213 | 12601022 | from psenet_ctw import PSENET_CTW
import torch
import numpy as np
import cv2
import random
import os
torch.manual_seed(123456)
torch.cuda.manual_seed(123456)
np.random.seed(123456)
random.seed(123456)
def to_rgb(img):
img = img.reshape(img.shape[0], img.shape[1], 1)
img = np.concatenate((img, img, img), axis... |
__scraping__/listado.mercadolibre.com.pe/main.py | whitmans-max/python-examples | 140 | 12601037 | <filename>__scraping__/listado.mercadolibre.com.pe/main.py<gh_stars>100-1000
#!/usr/bin/env python3
# date: 2020.04.23
# https://stackoverflow.com/questions/61376200/i-dont-get-all-the-product-description-data-with-scrapy/61377436#61377436
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spid... |
mantraml/core/management/commands/upload.py | rohan1790/mantra | 330 | 12601040 | <gh_stars>100-1000
import os
import shutil
import uuid
import subprocess
import mantraml
from mantraml.core.hashing.MantraHashed import MantraHashed
from mantraml.core.management.commands.BaseCommand import BaseCommand
import tempfile
from pathlib import Path
import sys
import getpass
import itertools
import requests
f... |
ssod/utils/signature.py | huimlight/SoftTeacher | 604 | 12601045 | <gh_stars>100-1000
import inspect
def parse_method_info(method):
sig = inspect.signature(method)
params = sig.parameters
return params
|
mmf/datasets/builders/ocrvqa/dataset.py | anas-awadalla/mmf | 3,252 | 12601105 | # Copyright (c) Facebook, Inc. and its affiliates.
from mmf.datasets.builders.textvqa.dataset import TextVQADataset
class OCRVQADataset(TextVQADataset):
def __init__(self, config, dataset_type, imdb_file_index, *args, **kwargs):
super().__init__(config, dataset_type, imdb_file_index, *args, **kwargs)
... |
tests/validation/response/test_produces_validation.py | maroux/flex | 160 | 12601107 | import pytest
from flex.exceptions import ValidationError
from flex.validation.response import (
validate_response,
)
from flex.error_messages import MESSAGES
from tests.factories import (
ResponseFactory,
SchemaFactory,
)
from tests.utils import assert_message_in_errors
#
# produces mimetype validati... |
Lib/objc/_VoiceShortcutClient.py | snazari/Pyto | 701 | 12601115 | <reponame>snazari/Pyto
"""
Classes from the 'VoiceShortcutClient' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
VCWidgetWorkflow = _Class... |
bandicoot/tests/test_spatial.py | Seabreg/bandicoot | 209 | 12601144 | # The MIT License (MIT)
#
# Copyright (c) 2015-2016 Massachusetts Institute of Technology.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation ... |
multitask.py | neulab/RIPPLe | 130 | 12601226 | import torch.nn as nn
from pytorch_transformers import (
BertForSequenceClassification, BertTokenizer
)
class BertForMultitaskClassification(BertForSequenceClassification):
def __init__(self, config):
assert hasattr(config, "num_labels_per_task")
assert sum(config.num_labels_per_task) == config... |
datasketch/__init__.py | sergiiz/datasketch | 1,771 | 12601260 | <reponame>sergiiz/datasketch<filename>datasketch/__init__.py
from datasketch.hyperloglog import HyperLogLog, HyperLogLogPlusPlus
from datasketch.minhash import MinHash
from datasketch.b_bit_minhash import bBitMinHash
from datasketch.lsh import MinHashLSH
from datasketch.weighted_minhash import WeightedMinHash, Weighted... |
src/starkware/air/rescue/rescue_hash_test.py | ChihChengLiang/ethSTARK | 123 | 12601268 | <reponame>ChihChengLiang/ethSTARK<filename>src/starkware/air/rescue/rescue_hash_test.py
from .rescue_hash import rescue_hash
def test_rescue_hash():
# The list of constants being compared to the result of rescue_hash was generated by performing
# the hash on [1, 2, 3, 4, 5, 6, 7, 8] with the marvellous_hash f... |
BitTornado/tests/test_bencode.py | crossbrowsertesting/BitTornado | 116 | 12601280 | import unittest
from ..Meta.bencode import bencode, bdecode, Bencached
class CodecTests(unittest.TestCase):
def test_bencode(self):
"""Test encoding of encodable and unencodable data structures"""
self.assertEqual(bencode(4), b'i4e')
self.assertEqual(bencode(0), b'i0e')
self.asser... |
notebooks-text-format/linreg_hierarchical_non_centered_pymc3.py | arpitvaghela/probml-notebooks | 166 | 12601289 | <reponame>arpitvaghela/probml-notebooks
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python [default]
# language: python
# name: python3
# ---
# + [m... |
sqllineage/io.py | treff7es/sqllineage | 238 | 12601329 | <reponame>treff7es/sqllineage<filename>sqllineage/io.py
from typing import Any, Dict, List
from networkx import DiGraph
def to_cytoscape(graph: DiGraph, compound=False) -> List[Dict[str, Dict[str, Any]]]:
"""
compound nodes is used to group nodes together to their parent.
See https://js.cytoscape.org/#no... |
python/tests/testdata/region_AD.py | rodgar-nvkz/python-phonenumbers | 2,424 | 12601332 | """Auto-generated file, do not edit by hand. AD metadata"""
from phonenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_AD = PhoneMetadata(id='AD', country_code=376, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='\\d{6}', possible_length=(6,)... |
bindings/python/test_m68k.py | columbia/egalito-capstone | 5,220 | 12601344 | #!/usr/bin/env python
# Capstone Python bindings, by <NAME> <<EMAIL>>
from __future__ import print_function
from capstone import *
from capstone.m68k import *
from xprint import to_hex, to_x
M68K_CODE = b"\x4c\x00\x54\x04\x48\xe7\xe0\x30\x4c\xdf\x0c\x07\xd4\x40\x87\x5a\x4e\x71\x02\xb4\xc0\xde\xc0\xde\x5c\x00\x1d\x80\... |
pylayers/em/openems/test/Horn_Antenna.py | usmanwardag/pylayers | 143 | 12601345 | """
Tutorials / horn antenna
Description at:
http://openems.de/index.php/Tutorial:_Horn_Antenna
(C) 2011,2012,2013 <NAME> <<EMAIL>>
Python Adaptation : ESIR Project 2015
"""
from pylayers.em.openems.openems import *
import scipy.constants as cst
import numpy as np
# setup the simulation
unit = 1e-3 # all length i... |
apps/user/views.py | crazypenguin/devops | 300 | 12601358 | from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from .models import User, LoginLog, Group, Permission
from server.models import RemoteUserBindHost
from .forms import LoginForm
from util.tool import login_required, hash_code, event_log
import django.utils.timezone as time... |
neo/VM/VMState.py | BSathvik/neo-python | 387 | 12601376 |
NONE = 0
HALT = 1 << 0
FAULT = 1 << 1
BREAK = 1 << 2
def VMStateStr(_VMState):
if _VMState == NONE:
return "NONE"
state = []
if _VMState & HALT:
state.append("HALT")
if _VMState & FAULT:
state.append("FAULT")
if _VMState & BREAK:
state.append("BREAK")
return ... |
code/utils.py | bsun0802/Zero-DCE | 106 | 12601464 | <reponame>bsun0802/Zero-DCE
import os
import shutil
import sys
from datetime import datetime
from pathlib import Path
import numpy as np
import cv2
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
def alpha_total_variation(A):
'''
Links: https://remi.flamary.com/demos/proxtv.htm... |
flybirds/core/plugin/plugins/default/ui_driver/poco/poco_position.py | LinuxSuRen/flybirds | 183 | 12601470 | <filename>flybirds/core/plugin/plugins/default/ui_driver/poco/poco_position.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Element position api
"""
import time
from poco.exceptions import PocoNoSuchNodeException
import flybirds.core.plugin.plugins.default.ui_driver.poco.poco_ele as poco_ele
from flybirds.core.plugi... |
plugins/dbnd-test-scenarios/src/dbnd_test_scenarios/test_common/complex_package_structure/complex_package/__init__.py | busunkim96/dbnd | 224 | 12601474 | from .complex_structure_pipeline import complex_structure_pipeline
|
.venv/lib/python3.8/site-packages/rules/contrib/models.py | taharh/label-studio | 1,356 | 12601548 | from django.core.exceptions import ImproperlyConfigured
from django.db.models import Model
from django.db.models.base import ModelBase
from ..permissions import add_perm
class RulesModelBaseMixin:
"""
Mixin for the metaclass of Django's Model that allows declaring object-level
permissions in the model's ... |
datadog_checks_dev/datadog_checks/dev/tooling/templates/integration/jmx/{check_name}/tests/conftest.py | mchelen-gov/integrations-core | 663 | 12601558 | <gh_stars>100-1000
{license_header}
import pytest
@pytest.fixture(scope='session')
def dd_environment():
yield {{}}, {{'use_jmx': True}}
|
pegasus/ops/text_encoder_utils_test.py | akhilbobby/pegasus | 1,270 | 12601566 | # Copyright 2020 The PEGASUS 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... |
py_feature/316_replacement.py | weiziyoung/instacart | 290 | 12601585 | <filename>py_feature/316_replacement.py<gh_stars>100-1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 5 22:36:10 2017
@author: konodera
nohup python -u 316_replacement.py &
"""
import pandas as pd
import gc
import numpy as np
from tqdm import tqdm
from collections import defaultdict
fro... |
String_or_Array/Sorting/Bubble_Sort.py | Amanjakhetiya/Data_Structures_Algorithms_In_Python | 195 | 12601586 | # bubble sort function
def bubble_sort(arr):
n = len(arr)
# Repeat loop N times
# equivalent to: for(i = 0; i < n-1; i++)
for i in range(0, n-1):
# Repeat internal loop for (N-i)th largest element
for j in range(0, n-i-1):
# if jth value is greater than (j+1) value
... |
demo/mpi-ref-v1/ex-3.03.py | gmdzy2010/mpi4py | 533 | 12601635 | <filename>demo/mpi-ref-v1/ex-3.03.py
execfile('ex-3.02.py')
assert dtype.size == MPI.DOUBLE.size + MPI.CHAR.size
assert dtype.extent >= dtype.size
dtype.Free()
|
test/test-girvan-newman.py | ruth-ann/snap-python | 242 | 12601749 | import sys
import unittest
import snap
class TestCommunityGirvanNeuman(unittest.TestCase):
def test_CommunityGirvanNewman(self):
Rnd = snap.TRnd(42)
Graph = snap.GenPrefAttach(100, 10, Rnd)
exp_val = 0.00963802805072646
Vec = snap.TCnComV()
act_val = snap.CommunityGirvan... |
descarteslabs/workflows/result_types/unmarshal.py | carderne/descarteslabs-python | 167 | 12601764 | registry = {}
def unmarshal(typestr, x):
try:
unmarshaller = registry[typestr]
except KeyError:
raise TypeError("No unmarshaller registered for '{}'".format(typestr))
return unmarshaller(x)
def register(typestr, unmarshaller):
if typestr in registry:
raise NameError(
... |
cme/protocols/smb/remotefile.py | hantwister/CrackMapExec | 6,044 | 12601778 | <reponame>hantwister/CrackMapExec<gh_stars>1000+
from impacket.smb3structs import FILE_READ_DATA, FILE_WRITE_DATA
class RemoteFile:
def __init__(self, smbConnection, fileName, share='ADMIN$', access = FILE_READ_DATA | FILE_WRITE_DATA ):
self.__smbConnection = smbConnection
self.__share = share
... |
base/base_model.py | caisarl76/TADE-AgnosticLT | 175 | 12601783 | import torch.nn as nn
import numpy as np
from abc import abstractmethod
class BaseModel(nn.Module):
"""
Base class for all models
"""
@abstractmethod
def forward(self, *inputs):
"""
Forward pass logic
:return: Model output
"""
raise NotImplementedError
|
tests/test_houston_configmap.py | syamasakigoodrx/astronomer | 314 | 12601797 | import yaml
from tests.helm_template_generator import render_chart
import pytest
import tempfile
from subprocess import check_call
def common_test_cases(docs):
"""Test some things that should apply to all cases."""
assert len(docs) == 1
doc = docs[0]
assert doc["kind"] == "ConfigMap"
assert doc[... |
tests/ut/scripts/test_start.py | mindspore-ai/mindinsight | 216 | 12601806 | <gh_stars>100-1000
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
tests_obsolete/extension/dataflow_/reduceadd_valid/test_dataflow_reduceadd_valid.py | akmaru/veriloggen | 232 | 12601827 | from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import dataflow_reduceadd_valid
expected_verilog = """
module test
(
);
reg CLK;
reg RST;
reg [32-1:0] xdata;
reg xvalid;
wire xready;
wire [32-1:0] zdata;
wire zvalid;
reg zready;
wire [1-1:0] vdata;
... |
Python/Tests/TestData/TestExecutor/test_stack_trace.py | techkey/PTVS | 404 | 12601852 | import unittest
class StackTraceTests(unittest.TestCase):
def test_bad_import(self):
obj = Utility()
obj.instance_method_a()
def test_not_equal(self):
self.assertEqual(1, 2)
def global_func():
def local_func():
import not_a_module # trigger exception
local_func()
clas... |
Python/136.SingleNumber.py | nizD/LeetCode-Solutions | 263 | 12601955 | <reponame>nizD/LeetCode-Solutions<filename>Python/136.SingleNumber.py
#in this problem we used the Counter object which when we pass a list to it, it returns a dictionnary that has the lists's elemnts as keys and their
# occurences as values
from collections import Counter
class Solution(object):
def singleNumbe... |
WebMirror/management/rss_parser_funcs/feed_parse_extractBinggoCorp.py | fake-name/ReadableWebProxy | 193 | 12601958 | def extractBinggoCorp(item):
"""
# Binggo & Corp Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if '<NAME>' in item['title'] and 'Chapter' in item['title']:
return buildReleaseMessageWithType(it... |
utils/bboxes.py | sloppyjuicy/ssd_detectors | 316 | 12601974 | <filename>utils/bboxes.py
import numpy as np
from numpy.linalg import norm
eps = 1e-10
def rot_matrix(theta):
s, c = np.sin(theta), np.cos(theta)
return np.array([[c, -s],[s, c]])
def polygon_to_rbox(xy):
# center point plus width, height and orientation angle
tl, tr, br, bl = xy
# length of t... |
arduino/__init__.py | mraje/tempcontrol | 146 | 12601983 | #!/usr/bin/env python
from arduino import *
|
src/aioflask/ctx.py | miguelgrinberg/aioflask | 189 | 12602084 | <filename>src/aioflask/ctx.py<gh_stars>100-1000
import sys
from greenletio import async_
from flask.ctx import *
from flask.ctx import AppContext as OriginalAppContext, \
RequestContext as OriginalRequestContext, _sentinel, _app_ctx_stack, \
_request_ctx_stack, appcontext_popped
class AppContext(OriginalAppCo... |
examples/librosa_example.py | akhambhati/pytorch-NMF | 123 | 12602091 | <reponame>akhambhati/pytorch-NMF
import torch
import librosa
import numpy as np
import matplotlib.pyplot as plt
from librosa import display, feature
from torchnmf.nmf import NMFD
if __name__ == '__main__':
y, sr = librosa.load(librosa.util.example_audio_file())
y = torch.from_numpy(y)
windowsize = 2048
... |
CMSIS/DSP/SDFTools/examples/example4/main.py | DavidLesnjak/CMSIS_5 | 2,293 | 12602096 | import sched as s
import matplotlib.pyplot as plt
from custom import *
# Only ONE FileSink can be used since the data will be dumped
# into this global buffer for display with Matplotlib
# It will have to be cleaned and reworked in future to use better
# mechanism of communication with the main code
DISPBUF = np.zero... |
l10n_br_point_of_sale/models/account_journal.py | kaoecoito/odoo-brasil | 181 | 12602105 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# © 2016 <NAME> <<EMAIL>>, Trustcode
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
metodos = [
('01', u'Dinheiro'),
('02', u'Cheque'),
('03', u'Cartão de Crédito'),
('04', u'Cartão de Débito'),
('... |
doc/test_functions.py | tasugi/nnabla | 2,792 | 12602142 | #! /usr/bin/env python
from __future__ import print_function
import yaml
from collections import OrderedDict
def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
... |
deep_recommenders/keras/models/nlp/__init__.py | LongmaoTeamTf/deep_recommenders | 143 | 12602186 | <filename>deep_recommenders/keras/models/nlp/__init__.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from deep_recommenders.keras.models.nlp.multi_head_attention import MultiHeadAttention
from deep_recommenders.keras.models.nlp.transformer import Transformer
|
chapter_9/pub_sub/pub_sub_sendclient.py | LifeOfGame/mongodb_redis | 183 | 12602217 | import redis
import json
import datetime
client = redis.Redis()
while True:
message = input('请输入需要发布的信息:')
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data = {'message': message, 'time': now_time}
client.publish('pubinfo', json.dumps(data))
|
stonesoup/deleter/base.py | Red-Portal/Stone-Soup-1 | 157 | 12602233 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
from abc import abstractmethod
from typing import Set
from ..base import Base, Property
from ..types.track import Track
from ..types.update import Update
class Deleter(Base):
"""Deleter base class.
Proposes tracks for deletion.
"""
delete_last_pred: bool =... |
Behavioral/Memento/python/memento.py | jerryshueh/design-patterns | 294 | 12602327 | <gh_stars>100-1000
class Originator:
_state = None
class Memento:
def __init__(self, state):
self._state = state
def setState(self, state):
self._state = state
def getState(self):
return self._state
def __init__(self, state = None):
sel... |
6/master/src/openea/modules/base/optimizers.py | smurf-1119/knowledge-engeneering-experiment | 102 | 12602364 | <reponame>smurf-1119/knowledge-engeneering-experiment<filename>6/master/src/openea/modules/base/optimizers.py
import tensorflow as tf
def generate_optimizer(loss, learning_rate, var_list=None, opt='SGD'):
optimizer = get_optimizer(opt, learning_rate)
grads_and_vars = optimizer.compute_gradients(loss, var_list... |
examples/Kane1985/Chapter2/Ex3.10.py | nouiz/pydy | 298 | 12602377 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exercise 3.10 from Kane 1985."""
from __future__ import division
from sympy import cancel, collect, expand_trig, solve, symbols, trigsimp
from sympy import sin, cos
from sympy.physics.mechanics import ReferenceFrame, Point
from sympy.physics.mechanics... |
tutorials/tutorial_LabelImage.py | xemio/ANTsPy | 338 | 12602381 | """
# A tutorial about Label Images in ANTsPy
In ANTsPy, we have a special class for dealing with what I call
"Label Images" - a brain image where each pixel/voxel is associated with
a specific label. For instance, an atlas or parcellation is the prime example
of a label image. But `LabelImage` types dont <i>just</... |
sodapy/__init__.py | johnclary/sodapy | 349 | 12602388 | from sodapy.socrata import Socrata
from sodapy import version
__all__ = [
"Socrata",
]
__version__ = version.__version__
|
notebook/while_usage.py | vhn0912/python-snippets | 174 | 12602415 | i = 0
while i < 3:
print(i)
i += 1
# 0
# 1
# 2
i = 0
while i < 3:
print(i)
if i == 1:
print('!!BREAK!!')
break
i += 1
# 0
# 1
# !!BREAK!!
i = 0
while i < 3:
if i == 1:
print('!!CONTINUE!!')
i += 1
continue
print(i)
i += 1
# 0
# !!CONTINUE!!
# ... |
test/Parallel/failed-build/fixture/myfail.py | jcassagnol-public/scons | 1,403 | 12602449 | import os
import sys
import time
import http.client
sys.path.append(os.getcwd())
from teststate import Response
WAIT = 10
count = 0
conn = http.client.HTTPConnection("127.0.0.1", port=int(sys.argv[3]))
def check_test_state():
conn.request("GET", "/?get_mycopy_started=1")
response = conn.getresponse()
re... |
test/test_plugins/test_wiki.py | fenwar/limbo | 369 | 12602486 | <gh_stars>100-1000
# -*- coding: UTF-8 -*-
import os
import sys
import vcr
DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(DIR, '../../limbo/plugins'))
from wiki import on_message
def test_basic():
with vcr.use_cassette('test/fixtures/wiki_basic.yaml'):
ret = on_message... |
tests/SampleApps/python/python2-rest-framework-app/snippets/tests.py | samruddhikhandale/Oryx | 403 | 12602505 | from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from .models import Snippet
class SnippetAdminTests(TestCase):
def test_snippet_admin_can_create_snippets(self):
user = User.objects.create_superuser(
"superuser", '<EMAIL>', '<PASSWO... |
pygrametl/drawntabletesting/formattable.py | ssrika17/pygrametl | 259 | 12602548 | <gh_stars>100-1000
"""Script that automatically format a drawn table testing table."""
# Copyright (c) 2021, Aalborg University (<EMAIL>)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redis... |
src/admin/widgets/boolean.py | aimanow/sft | 280 | 12602557 | <gh_stars>100-1000
import wtforms
from godmode.widgets.base import BaseWidget
class BooleanWidget(BaseWidget):
field = wtforms.BooleanField()
def render_list(self, item):
value = getattr(item, self.name, None)
if value:
return "<i class='icon-ok' style='color: #0c0;'></i>"
... |
examples/warren_buffet.py | Mahesh-Salunke/financial_fundamentals | 122 | 12602577 | <filename>examples/warren_buffet.py
'''
Created on Sep 24, 2013
@author: akittredge
'''
from zipline.algorithm import TradingAlgorithm
from datetime import datetime
import pytz
from financial_fundamentals import sqlite_fundamentals_cache,\
mongo_fundamentals_cache, mongo_price_cache
from financial_fundamentals.acc... |
sdk/python/pulumi_kubernetes/helm/v3/_inputs.py | polivbr/pulumi-kubernetes | 277 | 12602611 | <filename>sdk/python/pulumi_kubernetes/helm/v3/_inputs.py
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Uni... |
tests/clients/test_client_interceptor.py | willtsai/python-sdk | 125 | 12602612 | # -*- coding: utf-8 -*-
"""
Copyright 2021 The Dapr 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... |
src/masonite/validation/providers/ValidationProvider.py | cercos/masonite | 1,816 | 12602613 | """A Validation Service Provider."""
from ...providers import Provider
from .. import Validator, ValidationFactory, MessageBag
from ..commands.MakeRuleEnclosureCommand import MakeRuleEnclosureCommand
from ..commands.MakeRuleCommand import MakeRuleCommand
class ValidationProvider(Provider):
def __init__(self, appl... |
EmmetNPP/emmet/context.py | chcg/npp | 192 | 12602623 | # coding=utf-8
import sys
import os
import os.path
import codecs
import json
import gc
import imp
import re
from file import File
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
is_python3 = sys.version_info[0] > 2
core_files = ['emmet-app.js', 'python-wrapper.js']
def should_use_unicode():
"""
WinXP unable... |
214 Shortest Palindrome.py | ChiFire/legend_LeetCode | 872 | 12602628 | <reponame>ChiFire/legend_LeetCode
"""
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the
shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
__a... |
exoplanet-ml/experimental/beam/transit_search/prediction_fns.py | ritwik12/exoplanet-ml | 286 | 12602665 | <gh_stars>100-1000
# Copyright 2018 The Exoplanet ML 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 applica... |
run_mnist.py | odeonus/example_forgetting | 125 | 12602701 | from __future__ import print_function
import argparse
import numpy as np
import numpy.random as npr
import time
import os
import sys
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
# Format time for printing pu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.