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 |
|---|---|---|---|---|
netrd/__init__.py | sdmccabe/netrd | 116 | 12698 | """
netrd
-----
netrd stands for Network Reconstruction and Distances. It is a repository
of different algorithms for constructing a network from time series data,
as well as for comparing two networks. It is the product of the Network
Science Insitute 2019 Collabathon.
"""
from . import distance # noqa
from . impo... |
pytorch/GPT.py | lyq628/NLP-Tutorials | 643 | 12699 | from transformer import Encoder
from torch import nn,optim
from torch.nn.functional import cross_entropy,softmax, relu
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
import torch
import utils
import os
import pickle
class GPT(nn.Module):
def __init__(self, model_d... |
src/main/python/smart/smartplots3_run.py | cday97/beam | 123 | 12724 | import pandas as pd
import smartplots3_setup
def createSetup(name,expansion_factor,percapita_factor,plot_size,settings):
plt_setup_smart={
'name': name,
'expansion_factor':expansion_factor,
'percapita_factor':percapita_factor,
'scenarios_itr': [],
'scenarios_id':[],
... |
contrib/libs/cxxsupp/libsan/generate_symbolizer.py | HeyLey/catboost | 6,989 | 12726 | import os
import sys
def main():
print 'const char* ya_get_symbolizer_gen() {'
print ' return "{}";'.format(os.path.join(os.path.dirname(sys.argv[1]), 'llvm-symbolizer'))
print '}'
if __name__ == '__main__':
main()
|
utils/save_atten.py | xiaomengyc/SPG | 152 | 12745 | <reponame>xiaomengyc/SPG
import numpy as np
import cv2
import os
import torch
import os
import time
from torchvision import models, transforms
from torch.utils.data import DataLoader
from torch.optim import SGD
from torch.autograd import Variable
idx2catename = {'voc20': ['aeroplane','bicycle','bird','boat','bottle','... |
color_extractor/cluster.py | hcoura/color-extractor | 276 | 12748 | <filename>color_extractor/cluster.py
from sklearn.cluster import KMeans
from .exceptions import KMeansException
from .task import Task
class Cluster(Task):
"""
Use the K-Means algorithm to group pixels by clusters. The algorithm tries
to determine the optimal number of clusters for the given pixels.
... |
notebooks/datasets.py | jweill-aws/jupyterlab-data-explorer | 173 | 12749 | <reponame>jweill-aws/jupyterlab-data-explorer
#
# @license BSD-3-Clause
#
# Copyright (c) 2019 Project Jupyter Contributors.
# Distributed under the terms of the 3-Clause BSD License.
import IPython.display
import pandas
def output_url(url):
IPython.display.publish_display_data(
{"application/x.jupyter.r... |
src/lib/others/info_gathering/finder/finding_comment.py | nahuelhm17/vault_scanner | 230 | 12752 | #! /usr/bin/python
import requests
import re
from bs4 import BeautifulSoup
import colors
class FindingComments(object):
def __init__(self, url):
self.url = url
self.comment_list = ['<!--(.*)-->']
self.found_comments = {}
def get_soure_code(self):
resp_text = requests.get(sel... |
micro-benchmark-key-errs/snippets/dicts/type_coercion/main.py | WenJinfeng/PyCG | 121 | 12753 | d = {"1": "a"}
d[1]
d["1"]
|
torchrec/metrics/rec_metric.py | xing-liu/torchrec | 814 | 12794 | #!/usr/bin/env python3
# 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.
#!/usr/bin/env python3
import abc
import math
from collections import defaultdict, dequ... |
homeassistant/components/eight_sleep/binary_sensor.py | andersop91/core | 22,481 | 12805 | <reponame>andersop91/core
"""Support for Eight Sleep binary sensors."""
from __future__ import annotations
import logging
from pyeight.eight import EightSleep
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.core import HomeAssistant
from ... |
nautobot/circuits/__init__.py | psmware-ltd/nautobot | 384 | 12847 | <reponame>psmware-ltd/nautobot
default_app_config = "nautobot.circuits.apps.CircuitsConfig"
|
installer/core/terraform/resources/variable.py | Diffblue-benchmarks/pacbot | 1,165 | 12849 | from core.terraform.resources import BaseTerraformVariable
class TerraformVariable(BaseTerraformVariable):
"""
Base resource class for Terraform tfvar variable
Attributes:
variable_dict_input (dict/none): Var dict values
available_args (dict): Instance configurations
variable_type... |
第12章/program/Requester/Launcher.py | kingname/SourceCodeOfBook | 274 | 12871 | import os
scrapy_project_path = '/Users/kingname/book/chapter_12/DeploySpider'
os.chdir(scrapy_project_path) #切换工作区,进入爬虫工程根目录执行命令
os.system('scrapyd-deploy')
import json
import time
import requests
start_url = 'http://45.76.110.210:6800/schedule.json'
start_data = {'project': 'DeploySpider',
'spider':... |
glacier/glacierexception.py | JeffAlyanak/amazon-glacier-cmd-interface | 166 | 12891 | import traceback
import re
import sys
import logging
"""
**********
Note by wvmarle:
This file contains the complete code from chained_exception.py plus the
error handling code from GlacierWrapper.py, allowing it to be used in other
modules like glaciercorecalls as well.
**********
"""
class GlacierException(Except... |
Lib/async/test/test_echoupper.py | pyparallel/pyparallel | 652 | 12897 | <reponame>pyparallel/pyparallel
import async
from async.services import EchoUpperData
server = async.server('10.211.55.3', 20007)
async.register(transport=server, protocol=EchoUpperData)
async.run()
|
lldb/examples/summaries/cocoa/NSException.py | bytesnake/Enzyme | 427 | 12956 | <filename>lldb/examples/summaries/cocoa/NSException.py
"""
LLDB AppKit formatters
part of The LLVM Compiler Infrastructure
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
"""
# summary provider for class NSException
import lldb.runtime.objc.objc_runtime
impor... |
RecoBTag/PerformanceDB/python/measure/Pool_mistag110118.py | ckamtsikis/cmssw | 852 | 13021 | <gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
from CondCore.DBCommon.CondDBCommon_cfi import *
PoolDBESSourceMistag110118 = cms.ESSource("PoolDBESSource",
CondDBCommon,
toGet = cms.VPSet(
#
# working points
#
cms.PSet(
recor... |
get_vocab.py | Amir-Mehrpanah/hgraph2graph | 182 | 13037 | <gh_stars>100-1000
import sys
import argparse
from hgraph import *
from rdkit import Chem
from multiprocessing import Pool
def process(data):
vocab = set()
for line in data:
s = line.strip("\r\n ")
hmol = MolGraph(s)
for node,attr in hmol.mol_tree.nodes(data=True):
smiles =... |
tests/test_sql.py | YPlan/django-perf-rec | 148 | 13048 | <reponame>YPlan/django-perf-rec<gh_stars>100-1000
from __future__ import annotations
from django_perf_rec.sql import sql_fingerprint
def test_empty():
assert sql_fingerprint("") == ""
assert sql_fingerprint("\n\n \n") == ""
def test_select():
assert sql_fingerprint("SELECT `f1`, `f2` FROM `b`") == "... |
clearml/backend_interface/setupuploadmixin.py | arielleoren/clearml | 2,097 | 13053 | from abc import abstractproperty
from ..backend_config.bucket_config import S3BucketConfig
from ..storage.helper import StorageHelper
class SetupUploadMixin(object):
log = abstractproperty()
storage_uri = abstractproperty()
def setup_upload(
self, bucket_name, host=None, access_key=None, sec... |
var/spack/repos/builtin/packages/autoconf/package.py | LiamBindle/spack | 2,360 | 13076 | <reponame>LiamBindle/spack
# 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)
import re
class Autoconf(AutotoolsPackage, GNUMirrorPackage):
"""Autoconf -- system confi... |
seg/segmentor/tools/module_runner.py | Frank-Abagnal/HRFormer | 254 | 13079 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: <NAME>(<EMAIL>)
# Some methods used by main methods.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
from collections import OrderedDict
import torch
import to... |
lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py | medismailben/llvm-project | 2,338 | 13092 | <gh_stars>1000+
class myIntSynthProvider(object):
def __init__(self, valobj, dict):
self.valobj = valobj
self.val = self.valobj.GetChildMemberWithName("theValue")
def num_children(self):
return 0
def get_child_at_index(self, index):
return None
def get_child_index(sel... |
custom_components/waste_collection_schedule/waste_collection_schedule/wizard/stadtreinigung_hamburg.py | UBS-P/hacs_waste_collection_schedule | 142 | 13112 | #!/usr/bin/env python3
from html.parser import HTMLParser
import inquirer
import requests
# Parser for HTML input
class InputParser(HTMLParser):
def __init__(self, input_name):
super().__init__()
self._input_name = input_name
self._value = None
@property
def value(self):
... |
autosa_tests/large/mm_int16/unroll.py | mfkiwl/AutoSA-SystolicArray | 102 | 13118 | import math
# Modify the parameters here
UNROLL_FACTOR = 32
DATA_T = 'unsigned short'
# Generate the code
data_type = DATA_T
level = int(math.log2(UNROLL_FACTOR))
for layer in range(level - 1, -1, -1):
pair = int(math.pow(2, layer))
for i in range(pair):
# data_t tmp_[layer]_[pair] = tmp_[layer+1]_[pa... |
skfda/exploratory/__init__.py | jiduque/scikit-fda | 147 | 13120 | from . import depth
from . import outliers
from . import stats
from . import visualization
|
MuonAnalysis/MuonAssociators/test/L1MuonMatcher/test.py | ckamtsikis/cmssw | 852 | 13129 | <reponame>ckamtsikis/cmssw
import FWCore.ParameterSet.Config as cms
process = cms.Process("PAT")
# initialize MessageLogger and output report
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cerr.threshold = 'INFO'
process.MessageLogger.cerr.INFO = cms.untracked.PSet(
default ... |
market_sim/_agents/risk_model.py | quanttrade/rl_trading | 247 | 13148 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Implement different methods to hedge positions and measure the risk of a Zero
cupon bond portfolio
REFERENCE: <NAME>; <NAME>.; <NAME>., "Interest Rate Risk
Modeling, the fixed Income Valuation course". Wiley, 2005
@author: ucaiado
Created on 12/22/2016
"""
import numpy... |
Python-3/basic_examples/strings/python_str_to_datetime.py | ghiloufibelgacem/jornaldev | 1,139 | 13163 | <filename>Python-3/basic_examples/strings/python_str_to_datetime.py<gh_stars>1000+
from datetime import datetime
# string to datetime object
datetime_str = '09/19/18 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
print(datetime_object) # printed in defa... |
Binary Search Tree/235. Lowest Common Ancestor of a Binary Search Tree.py | beckswu/Leetcode | 138 | 13176 | """
235. Lowest Common Ancestor of a Binary Search Tree
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
... |
waliki/acl.py | sckevmit/waliki | 324 | 13177 | from functools import wraps
from collections import Iterable
from django.conf import settings
from django.shortcuts import render
from django.core.exceptions import PermissionDenied
from django.utils.decorators import available_attrs
from django.utils.encoding import force_str
from django.utils.six.moves.urllib.parse i... |
deepchem/feat/molecule_featurizers/coulomb_matrices.py | deloragaskins/deepchem | 3,782 | 13183 | """
Generate coulomb matrices for molecules.
See Montavon et al., _New Journal of Physics_ __15__ (2013) 095003.
"""
import numpy as np
from typing import Any, List, Optional
from deepchem.utils.typing import RDKitMol
from deepchem.utils.data_utils import pad_array
from deepchem.feat.base_classes import MolecularFeat... |
pymagnitude/third_party/allennlp/tests/data/dataset_readers/snli_reader_test.py | tpeng/magnitude | 1,520 | 13200 | # pylint: disable=no-self-use,invalid-name
from __future__ import division
from __future__ import absolute_import
import pytest
from allennlp.data.dataset_readers import SnliReader
from allennlp.common.util import ensure_list
from allennlp.common.testing import AllenNlpTestCase
class TestSnliReader(object):
@py... |
tests/test_swagger_registry.py | niall-byrne/flask-restful-swagger | 667 | 13218 | from flask import Flask
from flask_restful_swagger.swagger import SwaggerRegistry
try:
from unittest.mock import patch
except ImportError:
from mock import patch
@patch("flask_restful_swagger.swagger._get_current_registry")
@patch("flask_restful_swagger.swagger.render_homepage")
def test_get_swagger_registr... |
components/mpas-seaice/testing_and_setup/testcases/advection/plot_testcase.py | Fa-Li/E3SM | 235 | 13265 | from netCDF4 import Dataset
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import matplotlib.cm as cm
import numpy as np
#-------------------------------------------------------------
def plot_subfigure(axis, array, nCells, n... |
examples/python/bunny_pieline.py | Willyzw/vdbfusion | 119 | 13272 | <reponame>Willyzw/vdbfusion
#!/usr/bin/env python3
# @file cow_pipeline.py
# @author <NAME> [<EMAIL>]
#
# Copyright (c) 2021 <NAME>, all rights reserved
import argh
from datasets import BunnyGeneratedDataset as Dataset
from vdbfusion_pipeline import VDBFusionPipeline as Pipeline
def main(
data_source... |
freezer/storage/fslike.py | kwu83tw/freezer | 141 | 13294 | <reponame>kwu83tw/freezer
# (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P.
#
# 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... |
samples/create_project.py | zuarbase/server-client-python | 470 | 13298 | ####
# This script demonstrates how to use the Tableau Server Client
# to create new projects, both at the root level and how to nest them using
# parent_id.
#
#
# To run the script, you must have installed Python 3.6 or later.
####
import argparse
import logging
import sys
import tableauserverclient as TSC
def cre... |
tests/test_threading.py | nmandery/rasterio | 1,479 | 13299 | <filename>tests/test_threading.py
from threading import Thread
import time
import unittest
import rasterio as rio
from rasterio.env import get_gdal_config
class TestThreading(unittest.TestCase):
def test_multiopen(self):
"""
Open a file from different threads.
Regression test for issue #... |
src/basset_sick_loss.py | shtoneyan/Basset | 248 | 13318 | <filename>src/basset_sick_loss.py
#!/usr/bin/env python
from __future__ import print_function
from optparse import OptionParser
import os
import random
import subprocess
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
import pysam
from scipy.stats import binom
from scipy.sta... |
tests/test_vtable.py | matthewpruett/angr | 6,132 | 13335 | import os
import angr
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')
def test_vtable_extraction_x86_64():
p = angr.Project(os.path.join(test_location, "x86_64", "cpp_classes"), auto_load_libs=False)
vtables_sizes = {0x403cb0: 24, 0x403cd8: 1... |
examples/map.py | jlsajfj/NBT | 241 | 13339 | <filename>examples/map.py
#!/usr/bin/env python
"""
Prints a map of the entire world.
"""
import os, sys
import math
from struct import pack
# local module
try:
import nbt
except ImportError:
# nbt not in search path. Let's see if it can be found in the parent folder
extrasearchpath = os.path.realpath(os.p... |
desktop/core/ext-py/josepy-1.1.0/src/josepy/json_util.py | kokosing/hue | 5,079 | 13360 | """JSON (de)serialization framework.
The framework presented here is somewhat based on `Go's "json" package`_
(especially the ``omitempty`` functionality).
.. _`Go's "json" package`: http://golang.org/pkg/encoding/json/
"""
import abc
import binascii
import logging
import OpenSSL
import six
from josepy import b64,... |
src/triage/component/results_schema/alembic/versions/5dd2ba8222b1_add_run_type.py | josephbajor/triage_NN | 160 | 13406 | """add run_type
Revision ID: 5dd2ba8222b1
Revises: 079a74c15e8b
Create Date: 2021-07-22 23:53:04.043651
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '5dd2ba8222b1'
down_revision = '079a74c15e8b'
branch_labels = None
... |
projects/PanopticFCN_cityscapes/panopticfcn/__init__.py | fatihyildiz-cs/detectron2 | 166 | 13407 | from .config import add_panopticfcn_config
from .panoptic_seg import PanopticFCN
from .build_solver import build_lr_scheduler
|
txdav/common/datastore/upgrade/test/test_migrate.py | backwardn/ccs-calendarserver | 462 | 13409 | <filename>txdav/common/datastore/upgrade/test/test_migrate.py
##
# Copyright (c) 2010-2017 Apple 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.apach... |
tower_cli/resources/job.py | kedark3/tower-cli | 363 | 13456 | <reponame>kedark3/tower-cli
# Copyright 2015, Ansible, Inc.
# <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
ares/attack/bim.py | KuanKuanQAQ/ares | 206 | 13464 | <reponame>KuanKuanQAQ/ares
import tensorflow as tf
import numpy as np
from ares.attack.base import BatchAttack
from ares.attack.utils import get_xs_ph, get_ys_ph, maybe_to_array, get_unit
class BIM(BatchAttack):
''' Basic Iterative Method (BIM). A white-box iterative constraint-based method. Require a differenti... |
test/test_oneview_hypervisor_cluster_profile_facts.py | nabhajit-ray/oneview-ansible | 108 | 13467 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2020) Hewlett Packard Enterprise Development LP
#
# 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/licen... |
gammapy/data/tests/test_pointing.py | Rishank2610/gammapy | 155 | 13469 | <gh_stars>100-1000
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from numpy.testing import assert_allclose
from astropy.time import Time
from gammapy.data import FixedPointingInfo, PointingInfo
from gammapy.utils.testing import assert_time_allclose, requires_data
@requires_data()
class TestFixedPoin... |
kenlm_training/cc_net/tokenizer.py | ruinunca/data_tooling | 435 | 13472 | <reponame>ruinunca/data_tooling
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import time
from typing import Dict, Optional
import sacremoses # type: ignore
from cc_net import jsonql,... |
cresi/net/augmentations/functional.py | ankshah131/cresi | 117 | 13483 | import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import numpy as np
import math
from functools import wraps
def clip(img, dtype, maxval):
return np.clip(img, 0, maxval).astype(dtype)
def clipped(func):
"""
wrapper to clip results of transform to image dtype value range
"""
... |
src/django_otp/conf.py | jaap3/django-otp | 318 | 13501 | <filename>src/django_otp/conf.py
import django.conf
class Settings:
"""
This is a simple class to take the place of the global settings object. An
instance will contain all of our settings as attributes, with default values
if they are not specified by the configuration.
"""
defaults = {
... |
tensorboard/acceptance/__init__.py | DeepLearnI/atlas | 296 | 13503 | from .test_tensorboard_rest_api import TestTensorboardRestAPI
from .test_tensorboard_server import TestTensorboardServer
from .test_tensorboard_endpoints import TestTensorboardEndpoint |
tests/test_add_option_backtrace.py | ponponon/loguru | 11,391 | 13505 | <reponame>ponponon/loguru<gh_stars>1000+
from loguru import logger
# See "test_catch_exceptions.py" for extended testing
def test_backtrace(writer):
logger.add(writer, format="{message}", backtrace=True)
try:
1 / 0
except Exception:
logger.exception("")
result_with = writer.read().str... |
tests/pytorch_pfn_extras_tests/training_tests/extensions_tests/test_print_report_notebook.py | yasuyuky/pytorch-pfn-extras | 243 | 13563 | import io
import pytest
import pytorch_pfn_extras as ppe
from pytorch_pfn_extras.training.extensions import _ipython_module_available
from pytorch_pfn_extras.training.extensions.log_report import _pandas_available
@pytest.mark.skipif(
not _ipython_module_available or not _pandas_available,
reason="print rep... |
angr/storage/memory_mixins/hex_dumper_mixin.py | Kyle-Kyle/angr | 6,132 | 13585 | import string
from ...errors import SimValueError
from . import MemoryMixin
class HexDumperMixin(MemoryMixin):
def hex_dump(self, start, size, word_size=4, words_per_row=4, endianness="Iend_BE",
symbolic_char='?', unprintable_char='.', solve=False, extra_constraints=None,
inspe... |
src/greplin/scales/formats.py | frenzymadness/scales | 273 | 13586 | # Copyright 2011 The scales 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 w... |
Kerning/Steal Kerning Groups from Font.py | justanotherfoundry/Glyphs-Scripts | 283 | 13590 | #MenuTitle: Steal Kerning Groups from Font
"""Copy kerning groups from one font to another."""
from __future__ import print_function
import vanilla
class GroupsCopy(object):
"""GUI for copying kerning groups from one font to another"""
def __init__(self):
self.w = vanilla.FloatingWindow((400, 70), "Steal kerning ... |
scripts/idapython/idapy_detect_exitats.py | felkal/fuzzware | 106 | 13592 | import idaapi
from idaapi import *
inifinite_loops = [
b"\x00\xbf\xfd\xe7", # loop: nop; b loop
b"\xfe\xe7", # loop: b loop
]
whitelist = [
"Reset_Handler",
"main"
]
def detect_noret_funcs():
exit_locs_name_pairs = []
for func_addr in Functions():
if get_func_flags(func_addr) & idaapi... |
jaqs/util/dtutil.py | WestXu/JAQS | 602 | 13594 | # encoding: utf-8
import datetime
import numpy as np
import pandas as pd
def get_next_period_day(current, period, n=1, extra_offset=0):
"""
Get the n'th day in next period from current day.
Parameters
----------
current : int
Current date in format "%Y%m%d".
period : str
Inter... |
env/Lib/site-packages/Algorithmia/acl.py | Vivek-Kamboj/Sargam | 142 | 13606 | class Acl(object):
def __init__(self, read_acl):
self.read_acl = read_acl
@staticmethod
def from_acl_response(acl_response):
'''Takes JSON response from API and converts to ACL object'''
if 'read' in acl_response:
read_acl = AclType.from_acl_response(acl_response['read']... |
launch/test_motion.launch.py | RoboJackets/robocup-software | 200 | 13622 | import os
from pathlib import Path
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, SetEnvironmentVariable, Shutdown
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.a... |
snakewm/apps/games/pong/bat.py | sigmaister/snakeware_os | 1,621 | 13632 | <filename>snakewm/apps/games/pong/bat.py
import pygame
from pygame.locals import *
class ControlScheme:
def __init__(self):
self.up = K_UP
self.down = K_DOWN
class Bat:
def __init__(self, start_pos, control_scheme, court_size):
self.control_scheme = control_scheme
self.move_u... |
mimic/model/rackspace_image_store.py | ksheedlo/mimic | 141 | 13633 | <filename>mimic/model/rackspace_image_store.py
"""
An image store representing Rackspace specific images
"""
from __future__ import absolute_import, division, unicode_literals
import attr
from six import iteritems
from mimic.model.rackspace_images import (RackspaceWindowsImage,
... |
glue/viewers/table/qt/data_viewer.py | HPLegion/glue | 550 | 13642 | <gh_stars>100-1000
import os
from functools import lru_cache
import numpy as np
from qtpy.QtCore import Qt
from qtpy import QtCore, QtGui, QtWidgets
from matplotlib.colors import ColorConverter
from glue.utils.qt import get_qapp
from glue.config import viewer_tool
from glue.core import BaseData, Data
from glue.utils... |
psq/queue.py | Tomesco/bookshelf-demo-project | 210 | 13644 | <gh_stars>100-1000
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
tests/test_utils_project.py | FingerCrunch/scrapy | 41,267 | 13667 | <gh_stars>1000+
import unittest
import os
import tempfile
import shutil
import contextlib
from pytest import warns
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.project import data_path, get_project_settings
@contextlib.contextmanager
def inside_a_project():
prev_dir = os.getcwd()
... |
trainer/__init__.py | Greeser/gate-decorator-pruning | 192 | 13668 | from trainer.normal import NormalTrainer
from config import cfg
def get_trainer():
pair = {
'normal': NormalTrainer
}
assert (cfg.train.trainer in pair)
return pair[cfg.train.trainer]()
|
google/datalab/commands/_datalab.py | freyrsae/pydatalab | 198 | 13670 | # 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 agre... |
env/lib/python3.8/site-packages/plotly/validators/waterfall/_connector.py | acrucetta/Chicago_COVI_WebApp | 11,750 | 13724 | import _plotly_utils.basevalidators
class ConnectorValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="connector", parent_name="waterfall", **kwargs):
super(ConnectorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
preprocess/step1.py | wenhuchen/KGPT | 119 | 13738 | import json
import regex
import nltk.data
from nltk.tokenize import word_tokenize
import sys
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
def tokenize(string):
return word_tokenize(string)
def split_paragraphs(text):
"""
remove urls, lowercase all words and separate paragraphs
""... |
gluon/packages/dal/pydal/adapters/sap.py | GeorgesBrantley/ResistanceGame | 408 | 13747 | <reponame>GeorgesBrantley/ResistanceGame<filename>gluon/packages/dal/pydal/adapters/sap.py<gh_stars>100-1000
import re
from .._compat import integer_types, long
from .base import SQLAdapter
from . import adapters
@adapters.register_for("sapdb")
class SAPDB(SQLAdapter):
dbengine = "sapdb"
drivers = ("sapdb",)
... |
apps/molecular_generation/JT_VAE/src/mol_tree.py | agave233/PaddleHelix | 454 | 13756 | <reponame>agave233/PaddleHelix
# Copyright (c) 2021 PaddlePaddle Authors. 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... |
alphamind/benchmarks/data/neutralize.py | rongliang-tech/alpha-mind | 186 | 13765 | # -*- coding: utf-8 -*-
"""
Created on 2017-4-25
@author: cheng.li
"""
import datetime as dt
import numpy as np
from sklearn.linear_model import LinearRegression
from alphamind.data.neutralize import neutralize
def benchmark_neutralize(n_samples: int, n_features: int, n_loops: int) -> None:
pr... |
grappelli/settings.py | theatlantic/django-grappelli-old | 285 | 13774 | <filename>grappelli/settings.py
# coding: utf-8
# DJANGO IMPORTS
from django.conf import settings
# Admin Site Title
ADMIN_HEADLINE = getattr(settings, "GRAPPELLI_ADMIN_HEADLINE", 'Grappelli')
ADMIN_TITLE = getattr(settings, "GRAPPELLI_ADMIN_TITLE", 'Grappelli')
# Link to your Main Admin Site (no slashes at start a... |
DockerHubPackages/code/analyzer/analyzers/python_packages.py | halcyondude/datasets | 283 | 13776 | from ..utils import run
import logging
logger = logging.getLogger(__name__)
def process_one_package(path, package, python_version="3"):
"""Get details about one precise python package in the given image.
:param path: path were the docker image filesystem is expanded.
:type path: string
:param pa... |
tests/gold_tests/redirect/redirect_actions.test.py | cmcfarlen/trafficserver | 1,351 | 13793 | <gh_stars>1000+
'''
Test redirection behavior to invalid addresses
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# t... |
auth0/v3/test/management/test_stats.py | akmjenkins/auth0-python | 340 | 13797 | <filename>auth0/v3/test/management/test_stats.py
import unittest
import mock
from ...management.stats import Stats
class TestStats(unittest.TestCase):
def test_init_with_optionals(self):
t = Stats(domain='domain', token='<PASSWORD>', telemetry=False, timeout=(10, 2))
self.assertEqual(t.client.opt... |
cdlib/algorithms/internal/COACH.py | xing-lab-pitt/cdlib | 248 | 13802 | # Author: <NAME> <<EMAIL>>
# A core-attachment based method to detect protein complexes in PPI networks
# <NAME>, Kwoh, Ng (2009)
# http://www.biomedcentral.com/1471-2105/10/169
from collections import defaultdict
from itertools import combinations
import functools
# return average degree and density for a graph
de... |
python/GafferSceneUI/LightToCameraUI.py | ddesmond/gaffer | 561 | 13810 | ##########################################################################
#
# Copyright (c) 2016, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... |
custom_components/blitzortung/geohash_utils.py | Nag94/HomeAssistantConfig | 163 | 13818 | <filename>custom_components/blitzortung/geohash_utils.py
import math
from collections import namedtuple
from . import geohash
Box = namedtuple("Box", ["s", "w", "n", "e"])
def geohash_bbox(gh):
ret = geohash.bbox(gh)
return Box(ret["s"], ret["w"], ret["n"], ret["e"])
def bbox(lat, lon, radius):
lat_de... |
libweasyl/libweasyl/alembic/versions/eff79a07a88d_use_timestamp_column_for_latest_.py | akash143143/weasyl | 111 | 13880 | """Use TIMESTAMP column for latest submission
Revision ID: eff<PASSWORD>0<PASSWORD>
Revises: <PASSWORD>
Create Date: 2017-01-08 22:20:43.814375
"""
# revision identifiers, used by Alembic.
revision = 'eff<PASSWORD>'
down_revision = '<PASSWORD>'
from alembic import op # lgtm[py/unused-import]
import sqlalchemy as ... |
regression/testplan/firmware_small.py | sld-columbia/nvdla-sw | 407 | 13895 | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... |
airflow/providers/amazon/aws/example_dags/example_hive_to_dynamodb.py | npodewitz/airflow | 8,092 | 13908 | <gh_stars>1000+
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"... |
algocoin/__init__.py | dendisuhubdy/algo-coin | 252 | 13915 | <filename>algocoin/__init__.py
from .main import main as run # noqa: F401
__version__ = '0.0.3'
|
mmrazor/models/architectures/components/backbones/__init__.py | HIT-cwh/mmrazor | 553 | 13916 | <gh_stars>100-1000
# Copyright (c) OpenMMLab. All rights reserved.
from .darts_backbone import DartsBackbone
from .searchable_mobilenet import SearchableMobileNet
from .searchable_shufflenet_v2 import SearchableShuffleNetV2
__all__ = ['DartsBackbone', 'SearchableShuffleNetV2', 'SearchableMobileNet']
|
serve/api/predict.py | HalleyYoung/musicautobot | 402 | 13952 | import sys
from . import app
sys.path.append(str(app.config['LIB_PATH']))
from musicautobot.music_transformer import *
from musicautobot.config import *
from flask import Response, send_from_directory, send_file, request, jsonify
from .save import to_s3
import torch
import traceback
torch.set_num_threads(4)
data = ... |
tests/test_user.py | meisnate12/trakt.py | 147 | 13953 | from __future__ import absolute_import, division, print_function
from tests.core import mock
from trakt import Trakt
from httmock import HTTMock
import pytest
def test_likes():
with HTTMock(mock.fixtures, mock.unknown):
with Trakt.configuration.auth('mock', 'mock'):
likes = Trakt['users'].li... |
ott/examples/fairness/models.py | MUCDK/ott | 232 | 13957 | <gh_stars>100-1000
# coding=utf-8
# Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
reikna/core/__init__.py | ringw/reikna | 122 | 13959 | <gh_stars>100-1000
from reikna.core.signature import Type, Annotation, Parameter, Signature
from reikna.core.computation import Computation
from reikna.core.transformation import Transformation, Indices
|
nngen/onnx/shape.py | RyusukeYamano/nngen | 207 | 13961 | <filename>nngen/onnx/shape.py
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def Shape(visitor, node):
input = visitor.visit(node.input[0])
shape = input.shape
if (input.get_layout() is not None and input.get_onnx_layout() is not None and
... |
Burp/lib/data.py | wisdark/HUNT | 1,628 | 13965 | <reponame>wisdark/HUNT
from __future__ import print_function
import json
import os
class Data():
shared_state = {}
def __init__(self):
self.__dict__ = self.shared_state
self.set_checklist(None)
self.set_issues()
def set_checklist(self, file_name):
is_empty = file_name is N... |
Src/StdLib/Lib/test/xmltests.py | cwensley/ironpython2 | 2,293 | 14005 | # Convenience test module to run all of the XML-related tests in the
# standard library.
import sys
import test.test_support
test.test_support.verbose = 0
def runtest(name):
__import__(name)
module = sys.modules[name]
if hasattr(module, "test_main"):
module.test_main()
runtest("test.test_minidom... |
memcnn/experiment/tests/test_factory.py | classner/memcnn | 224 | 14006 | import pytest
import os
import memcnn.experiment.factory
from memcnn.config import Config
def test_get_attr_from_module():
a = memcnn.experiment.factory.get_attr_from_module('memcnn.experiment.factory.get_attr_from_module')
assert a is memcnn.experiment.factory.get_attr_from_module
def test_load_experiment_... |
pyquil/api/__init__.py | stjordanis/pyquil | 677 | 14015 | <filename>pyquil/api/__init__.py
##############################################################################
# Copyright 2016-2017 Rigetti Computing
#
# 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 ... |
notebook/datetime_fromisoformat.py | vhn0912/python-snippets | 174 | 14024 | <gh_stars>100-1000
import datetime
s = '2018-12-31'
d = datetime.date.fromisoformat(s)
print(d)
# 2018-12-31
print(type(d))
# <class 'datetime.date'>
# print(datetime.date.fromisoformat('2018-12'))
# ValueError: Invalid isoformat string: '2018-12'
print(datetime.date.fromisoformat('2018-01-01'))
# 2018-01-01
# p... |
pandas/main.py | monishshah18/python-cp-cheatsheet | 140 | 14032 | <gh_stars>100-1000
"""
Summarize a column total cases column and total deaths column
Country by country data in columns, sum up and match global totals
"""
import csv
import pandas
pandas.set_option("display.max_rows", None, "display.max_columns", None)
col_list = ["Total Cases", "Country/ Other", "Total Deaths", "#... |
Problem009/Python/solution_1.py | drocha87/ProjectEuler | 167 | 14035 | <reponame>drocha87/ProjectEuler
#!/usr/bin/env python
# coding=utf-8
# Python Script
#
# Copyleft © <NAME>
#
#
from __future__ import print_function
"""
Special Pythagorean triplet
Problem 9
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a² + b² = c²
For example, 3² + 4² = 9 + 16 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.