max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
responsibleai/tests/databalanceanalysis/test_distribution_balance_measures.py | imatiach-msft/responsible-ai-toolbox | 0 | 40200 | <reponame>imatiach-msft/responsible-ai-toolbox<filename>responsibleai/tests/databalanceanalysis/test_distribution_balance_measures.py
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
import pandas as pd
from responsibleai.databalanceanalysis import DistributionBalanceMeasures
from ..common_uti... | 2.140625 | 2 |
examples/example3.py | axju/socialpy | 1 | 40201 | <filename>examples/example3.py
from socialpy import Gateway
import json
def plot(LastJson):
try:
print(json.dumps(LastJson, indent=4, sort_keys=True))
except Exception as e:
pass
gateway = Gateway()
#gateway.load_from_file('.env')
gateway['instagram'].setup(user='...', pw='...')
id = gateway... | 2.515625 | 3 |
src/vivarium/interface/cli.py | ihmeuw/vivarium | 41 | 40202 | <reponame>ihmeuw/vivarium
"""
===========================
Vivarium Command Line Tools
===========================
``vivarium`` provides the tool :command:`simulate` for running simulations
from the command line. It provides three subcommands:
.. list-table:: ``simulate`` sub-commands
:header-rows: 1
:widths:... | 2.203125 | 2 |
univt-fonts/convert_univt.py | AOSC-Dev/scriptlets | 5 | 40203 | <filename>univt-fonts/convert_univt.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import warnings
import bdflib
def convert_bdf(bdffont):
for i in range(0x10000):
if i in bdffont.glyphs_by_codepoint:
glyph = bdffont.glyphs_by_codepoint[i]
data = glyph.data.copy()
... | 2.828125 | 3 |
checker.py | nautilusPrime/howdy_checker | 0 | 40204 | <reponame>nautilusPrime/howdy_checker<filename>checker.py
# coding: utf-8
# author: <NAME>
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expe... | 2.578125 | 3 |
seat_reservation/bus_seats.py | wrightdj99/wrightdj99.github.io | 0 | 40205 | #This application is supposed to mimics
#a seat reservation system for a bus company
#or railroad like Amtrak or Greyhound.
class Seat:
def __init__(self):
self.first_name = ''
self.last_name = ''
self.paid = False
def reserve(self, fn, ln, pd):
self.first_name = fn
se... | 4.15625 | 4 |
src/airflow_fs/sensors.py | Sergfalt/airflow-fs | 16 | 40206 | """Module containing file system sensors."""
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
from airflow_fs.hooks import LocalHook
class FileSensor(BaseSensorOperator):
"""Sensor that waits for files matching a given file pattern.
:pa... | 2.578125 | 3 |
pkg/tests/test_range.py | arita37/pyvtreat | 1 | 40207 | import vtreat.util
import pandas
import numpy
def test_range():
# https://github.com/WinVector/pyvtreat/blob/master/Examples/Bugs/asarray_issue.md
# https://github.com/WinVector/pyvtreat/issues/7
numpy.random.seed(2019)
arr = numpy.random.randint(2, size=10)
sparr = pandas.arrays.SparseArray(arr, ... | 2.1875 | 2 |
src/config.py | robertmetcalf/chia-log | 0 | 40208 | <reponame>robertmetcalf/chia-log
# system packages
from pathlib import Path
from typing import Any, Dict, List
#import pprint
# third party packages
import yaml
# local packages
from src.logger import Logger
class Config:
def __init__ (self) -> None:
# CLI options
self._option_config:str = '' # --config f... | 2.265625 | 2 |
nipype/interfaces/ants/tests/test_auto_KellyKapowski.py | sebastientourbier/nipype | 0 | 40209 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..segmentation import KellyKapowski
def test_KellyKapowski_inputs():
input_map = dict(args=dict(argstr='%s',
),
convergence=dict(argstr='--convergence "%s"',
usedefault=True,
),
cortical_thicknes... | 2 | 2 |
lib/two/evalctx.py | erkyrath/tworld | 38 | 40210 | <gh_stars>10-100
"""
The context object for evaluating script code. Most of the implementation
of TworldPy lives in the EvalPropContext module.
"""
import re
import random
import ast
import operator
import itertools
import tornado.gen
import bson
from bson.objectid import ObjectId
import motor
import twcommon.misc
f... | 2.671875 | 3 |
setup.py | matwey/django-eremaea2 | 0 | 40211 | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-eremaea2',
version='2.0.17',
package... | 1.304688 | 1 |
GOP/utility/__init__.py | viebboy/PyGOP | 17 | 40212 | <reponame>viebboy/PyGOP
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Author: <NAME>
Email: <EMAIL>, <EMAIL>
github: https://github.com/viebboy
"""
from . import gop_utils
from . import gop_operators
from . import misc
| 1.234375 | 1 |
sample_project/users/models.py | CorrDyn/django-bulk-user-upload | 1 | 40213 | from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
# https://wsvincent.com/django-custom-user-model-tutorial/
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from users.managers import... | 2.15625 | 2 |
ansys/dpf/core/operators/logic/identical_fc.py | TheGoldfish01/pydpf-core | 11 | 40214 | <reponame>TheGoldfish01/pydpf-core
"""
identical_fc
============
"""
from ansys.dpf.core.dpf_operator import Operator
from ansys.dpf.core.inputs import Input, _Inputs
from ansys.dpf.core.outputs import Output, _Outputs, _modify_output_spec_with_one_type
from ansys.dpf.core.operators.specification import PinSpecificatio... | 2.578125 | 3 |
tests/test_allure_reporter.py | nikitanovosibirsk/vedro-allure-reporter | 1 | 40215 | <reponame>nikitanovosibirsk/vedro-allure-reporter
from unittest.mock import Mock, call
import pytest
from baby_steps import given, then, when
from vedro.core import Dispatcher
from vedro.events import (
ArgParsedEvent,
ScenarioFailedEvent,
ScenarioPassedEvent,
ScenarioRunEvent,
ScenarioSkippedEvent... | 2.0625 | 2 |
tests/test_utils.py | JorgeGarciaIrazabal/cf-scripts | 33 | 40216 | <gh_stars>10-100
import os
import json
import pickle
from conda_forge_tick.utils import LazyJson, dumps
def test_lazy_json(tmpdir):
f = os.path.join(tmpdir, "hi.json")
assert not os.path.exists(f)
lj = LazyJson(f)
assert os.path.exists(lj.file_name)
with open(f) as ff:
assert ff.read() ==... | 2.3125 | 2 |
genomicode/quantnorm.py | jefftc/changlab | 9 | 40217 | <filename>genomicode/quantnorm.py<gh_stars>1-10
"""
Functions:
normalize
normalize_binreg Requires binreg
"""
import os
def normalize(X, which_columns=None):
# X is a Matrix of the data. which_columns is a list of the
# columns used to calculate the quantiles. If None, then will use
# every column. ... | 2.859375 | 3 |
main.py | Grads2Career-Python/eliaseraphim_password_confirmation | 0 | 40218 | # author: <NAME>
# date 6/4/21
#
# simple password confirmation program that confirms a password of size 12 to 48, with at least: one lower-case letter
# one upper-case letter, one number, and one special character.
# constants
MIN_LENGTH, MAX_LENGTH = 8, 48 # min and max length of password
# dictionaries
LOWER_... | 4.25 | 4 |
1929.py | asa-leholland/puzzle_practice | 0 | 40219 | from timing import timing
@timing
def concat(nums):
ans = list(range(2*len(nums)))
for i, value in enumerate(nums):
ans[i] = value
ans[i + len(nums)] = value
return ans
@timing
def concat2(nums):
ans = nums
for i in range(len(nums)):
ans.append(nums[i])
return ... | 3.640625 | 4 |
tests/test_timeset.py | GFlorio/pytimeset | 0 | 40220 | from datetime import datetime, timedelta
from random import sample, choice, randrange
from unittest import TestCase
import tests.test_timeinterval as ti
from tests.factories import make_sets, make_moments
from timeset import TimeSet
t0 = datetime(2019, 7, 19)
t6 = datetime(2019, 7, 25)
t = make_moments(20, t0, t6)
se... | 3.046875 | 3 |
Collections-a-installer/community-general-2.4.0/tests/unit/plugins/become/test_doas.py | d-amien-b/simple-getwordpress | 22 | 40221 | <reponame>d-amien-b/simple-getwordpress
# (c) 2012-2014, <NAME> <<EMAIL>>
# (c) 2020 Ansible Project
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
imp... | 1.867188 | 2 |
src/server_CFD/definitions.py | robertpardillo/Funnel | 1 | 40222 | <filename>src/server_CFD/definitions.py<gh_stars>1-10
import os
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
SERVER = 'CFD'
IS_MULTITHREADING = 0
| 1.320313 | 1 |
problems/A/LevelStatistics.py | deveshbajpai19/CodeForces | 55 | 40223 | <reponame>deveshbajpai19/CodeForces<filename>problems/A/LevelStatistics.py<gh_stars>10-100
__author__ = '<NAME>'
'''
https://codeforces.com/problemset/problem/1334/A
Solution: Its easy to deduce that even for one player, it is impossible to clear more levels than the plays done. This
also is true when multiple player... | 3.21875 | 3 |
src/base.py | mchange/gitlab-migrator | 2 | 40224 | # -*- coding: utf-8 -*-
import json
def storage(name, data):
with open('tmp/%s.json' % name, 'w', encoding = 'UTF-8') as f:
json.dump(data, f, sort_keys = False, indent = 2, ensure_ascii = False)
| 2.890625 | 3 |
python_start/remove_ad_text.py | ftconan/python3 | 1 | 40225 | <filename>python_start/remove_ad_text.py
# coding=utf-8
import os
def remove_ad_text(dir2, ad_text):
"""
delete ad text funtion
1. search file and dir, serarch sub_dir, until sub_dir not exist
2. remove ad_text from file
@params: dir2: str dir
ad_text: str content
"""
# dir2 ... | 3.671875 | 4 |
modesolverpy/design.py | maederan201/modesolverpy | 48 | 40226 | import numpy as np
def directional_coupler_lc(wavelength_nm, n_eff_1, n_eff_2):
'''
Calculates the coherence length (100% power transfer) of a
directional coupler.
Args:
wavelength_nm (float): The wavelength in [nm] the
directional coupler should operate at.
n_eff_1 (float... | 3.046875 | 3 |
PySDDP/newave/script/confhd.py | tscher/PySDDP | 9 | 40227 | import os
from typing import IO
from PySDDP.newave.script.templates.confhd import ConfhdTemplate
from matplotlib import pyplot as plt
import numpy as np
from random import randint
from mpl_toolkits.mplot3d import Axes3D
class Confhd(ConfhdTemplate):
def __init__(self):
super().__init__()
self.li... | 2.71875 | 3 |
RainbowFileReaders/MathHelpers.py | RainbowRedux/RainbowSixFileConverters | 6 | 40228 | """ This module contains a number of useful math related functions that are used throughout this project """
from __future__ import annotations
import math
from typing import List, Union, Tuple
from deprecated import deprecated # type: ignore
AnyNumber = Union[int, float]
FloatIterable = Union[List[float], Tuple[flo... | 3.109375 | 3 |
cloudshell/snmp/snmp_parameters.py | QualiSystems/cloudshell-snmp | 0 | 40229 | import warnings
class SnmpParameters(object):
class SnmpVersion:
def __init__(self):
pass
V1 = "1"
V2 = "2"
V3 = "3"
def __init__(self, ip, port=161, context_engine_id=None, context_name=""):
self.ip = ip
self.port = port
self.context_engin... | 2.734375 | 3 |
core/rest/authentication.py | macdaliot/Osmedeus | 1 | 40230 |
import os
import json
import glob
import datetime
from flask_restful import Api, Resource, reqparse
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity
)
from .decorators import local_only
import utils
'''
Check authentication
'''
current_path = os.path.dirname(... | 2.515625 | 3 |
Python2/runEmu.py | johnofleek/OctaveOrp | 1 | 40231 | import os
from json import dumps
import logging
from platform import platform
from psutil import cpu_percent, virtual_memory
from serial import Serial
from time import sleep
from sb_serial import Sensor, SbSerial
# Change the serial port to suit the machine that this running on
# and the OS
#DEV = os.getenv('DEV', '/... | 2.390625 | 2 |
srxray.py | dfex/srxray | 0 | 40232 | <filename>srxray.py
#!/usr/bin/env python3
import logging
import argparse
def flattenJunosConfig(JunosConfig):
"""Take a Junos configuration file in bracketed format and flattens it into set format"""
JunosSetConfig=[]
JunosSetLine=['set ']
for line in JunosConfig:
if (line.endswith("{")):
if (line.lstrip(... | 3.171875 | 3 |
tests/conftest.py | mariushelf/sa2django | 0 | 40233 | <gh_stars>0
import django
import pytest
@pytest.fixture(scope="function")
def django_db_setup(django_db_blocker):
""" Prevent creation of a test db (because we do that with sqlalchemy) """
yield
with django_db_blocker.unblock():
django.db.connections.close_all()
| 1.820313 | 2 |
client/test.py | Blockchain-Simplified/Blockchain-Simplified | 9 | 40234 | <filename>client/test.py
import configFileControl
import uuid
def check_and_get_uid():
status, uid = configFileControl.getUid()
if status:
return uid
else:
uid = uuid.uuid4()
configFileControl.setUid(str(uid))
return uid
uid = check_and_get_uid()
print(uid) | 2.546875 | 3 |
hanse_ros/xsens_driver/nodes/mtdef.py | iti-luebeck/HANSE2012 | 0 | 40235 | """Constant and messages definition for MT communication."""
class MID:
"""Values for the message id (MID)"""
## Error message, 1 data byte
Error = 0x42
ErrorCodes = {
0x03: "Invalid period",
0x04: "Invalid message",
0x1E: "Timer overflow",
0x20: "Invalid baudrate",
0x21: "Invalid parameter"
}
# Stat... | 1.890625 | 2 |
geosquizzy/fsm/selection.py | LowerSilesians/geo-squizzy | 3 | 40236 | # TODO selection percentage pattern works, but run and done methods really slow down
# TODO whole computation when we traverse really big data
# TODO in order to achieve better performance EconomizeFiniteStateMachine class was provided
import math
class SelectionFiniteStateMachine:
def __init__(self, *args, **k... | 2.8125 | 3 |
Machine learning Intermediate/Multiclass classification-75.py | vipmunot/Data-Analysis-using-Python | 0 | 40237 | ## 1. Introduction to the data ##
import pandas as pd
cars = pd.read_csv("auto.csv")
unique_regions = cars['origin'].unique()
print(unique_regions)
## 2. Dummy variables ##
dummy_cylinders = pd.get_dummies(cars["cylinders"], prefix="cyl")
cars = pd.concat([cars, dummy_cylinders], axis=1)
print(cars.head())
dummy_yea... | 3.328125 | 3 |
fedml-server/executor/conf/__init__.py | MichaelLee-ceo/FedSAUC | 1 | 40238 | <gh_stars>1-10
# -*- coding: utf-8 -*-n
import os
from fedml_mobile.server.executor.conf.env import EnvWrapper
ENV = EnvWrapper(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), True, 'TrainingExecutor')
| 1.117188 | 1 |
fatima/utils/viz.py | AmrMKayid/fatima | 0 | 40239 | import glob
import os
import subprocess
import time
import matplotlib.pyplot as plt
import numpy
import torch
def viz(
batch: torch.Tensor,
episodes=1000,
video=True,
folder='output',
) -> None:
## Visualize GoodAI Breakout Dataset
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.set_title("B... | 2.140625 | 2 |
scripts/cutadapt.py | CollinJ0/NNK | 0 | 40240 | from Bio import SeqIO
from subprocess import Popen, PIPE
adapters = [str(s.seq) for s in SeqIO.parse(open(snakemake.input[1], 'r'), 'fasta')]
adapters = '-b ' + ' -b '.join(adapters)
cutadapt_cmd = f"cutadapt -o {snakemake.output[0]} {adapters} {snakemake.input[0]}"
p = Popen(cutadapt_cmd, stdout=PIPE, stderr=PIPE, ... | 2.09375 | 2 |
packages/SwingSet/misc-tools/mint-gca.py | danwt/agoric-sdk | 4 | 40241 | #!/usr/bin/env python3
import sys, json, time, hashlib, base64
from collections import defaultdict
# vat-mint (v5) .getCurrentAmount is a really simple method: it looks up a
# Presence in a WeakMap, and returns the value. The only syscall it makes is
# the resolve. There are four timestamps of interest:
# A: delivery ... | 2.5 | 2 |
tweetbot-d.py | mc3k/tweetbot | 0 | 40242 | <filename>tweetbot-d.py
#!/usr/bin/env python
import sys, os, logging, urllib
import xml.etree.ElementTree
from twython import TwythonStreamer, Twython
from daemon3x import daemon
# Logging
logging.basicConfig(filename='tweetbot.log',
filemode='a',
format='[%(asctime)s] %(message)s',... | 2.84375 | 3 |
inheritance/demo_inheritance.py | Minkov/python-oop-2020-06 | 3 | 40243 | from mixins.debug_attributes_setter_mixin import DebugAttributesSetterMixin
class Person(DebugAttributesSetterMixin):
def __init__(self, name, age):
self.name = name
# validate age
self.age = age
def __repr__(self):
return f'Name: {self.name}, Age: {self.age}'
... | 3.109375 | 3 |
src/program/migrations/0079_eventinstance_uuid.py | lgandersen/bornhack-website | 7 | 40244 | <reponame>lgandersen/bornhack-website<filename>src/program/migrations/0079_eventinstance_uuid.py
# Generated by Django 3.0.3 on 2020-02-22 13:59
import uuid
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("program", "0078_auto_20200214_2100"),
]
... | 1.546875 | 2 |
scripts/download_sandana_datasets.py | ohsu-comp-bio/cycIF-DB | 0 | 40245 | """ Download datasets from SANDANA samples from Galaxy server.
python scripts/download_sandana_datasets.py --help
"""
import argparse
import logging
from cycif_db.galaxy_download import download_sandana
parser = argparse.ArgumentParser()
parser.add_argument(
'--server', '-s', type=str, dest='server', required=F... | 2.515625 | 3 |
diffxpy/unit_test/test_single.py | SabrinaRichter/diffxpy | 0 | 40246 | <gh_stars>0
import unittest
import logging
import numpy as np
import pandas as pd
import scipy.stats as stats
from batchglm.api.models.glm_nb import Simulator
import diffxpy.api as de
class TestSingleNull(unittest.TestCase):
def test_null_distribution_wald(self, n_cells: int = 2000, n_genes: int = 100):
... | 2.453125 | 2 |
decode/PNG_CRC32.py | SkyLined/headsup | 1 | 40247 | # Copyright 2010 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 agreed to ... | 2.3125 | 2 |
buildz/toolchain/gcc.py | patrykbajos/buildz | 0 | 40248 | import os.path
import re
import platform
import subprocess
from copy import deepcopy
from pathlib import Path
from schema import Optional, Schema, SchemaError, Or
from buildz.toolchain.generic import GenericToolchain
from buildz.utils import find_re_it_in_list, get_cmd_matches, merge, merge_envs, resolve_rel_paths_li... | 1.929688 | 2 |
app/src/models/calculation.py | beerjoa/flask-restplus-skeleton | 1 | 40249 | from .. import db
from .base import Base, BaseSchema
from typing import Dict, Union
from datetime import datetime
class Calculation(Base):
__table_name__ = 'calculation'
calc_id = db.Column(db.Integer, primary_key=True)
num1 = db.Column(db.Integer, nullable=False)
num2 = db.Column(db.Integer, nullable... | 2.65625 | 3 |
isic_grabber/src/web_helper.py | stamas02/isic_grabber | 0 | 40250 | <filename>isic_grabber/src/web_helper.py
import requests
import os
from tqdm import tqdm
import sys
def get_json(url):
"""
Gets a json response from the given url.
:param url: URL.
:return: the received Json data.
"""
resp = requests.get(url=url)
return resp.json()
def get_file(url, out... | 2.96875 | 3 |
fuyuzi/artword.py | godontop/python-work | 0 | 40251 | # coding=utf-8
import random
import sys
import pygame
from pygame.color import THECOLORS
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
for i in range(0, 100):
width = random.randint(0, 250)
height = random.randint(0, 100)
top = random.randint(0, 400)
left =... | 3.53125 | 4 |
lesson10/qiangshihong/users/forms.py | herrywen-nanj/51reboot | 0 | 40252 | <filename>lesson10/qiangshihong/users/forms.py
#!/usr/bin/python
# author: qsh
from django import forms
from django.contrib.auth.models import Group, Permission
from .models import UserProfile
import re
# 添加用户表单验证
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
# fields = "... | 2.90625 | 3 |
lgbm_plugin.py | truelatysh/unsorted_python_staff | 1 | 40253 | """
Tool for 'leave-one-out' testing features in dataset.
Adds use_column parameter for lightgbm CLI, which works
like an opposite one to ignore_columns.
Example usage
--------------
>>> python lgbm_tool.py --use_column=column1,column2,column3 \
>>> config=path_to_config data=path_to_data valid=pat... | 2.71875 | 3 |
kive/portal/apps.py | cfe-lab/Kive | 2 | 40254 | <gh_stars>1-10
import logging
import sys
from django.apps import AppConfig
from django.conf import settings
logger = logging.getLogger(__name__)
class PortalConfig(AppConfig):
name = 'portal'
def ready(self):
is_manage_py = sys.argv and sys.argv[0].endswith('manage.py')
if is_manage_py and ... | 2 | 2 |
setup.py | getyourguide/image-quality-assessment | 0 | 40255 | import setuptools
setuptools.setup(
name="image-quality-assessment",
version="0.0.1",
author="gdp",
author_email="<EMAIL>",
description="TBD",
long_description_content_type="text/markdown",
url="https://github.com/getyourguide/image-quality-assessment",
packages=setuptools.find_package... | 1.539063 | 2 |
seq2seq-translation/model.py | StanleyLsx/practical-pytorch | 0 | 40256 | import torch.nn.functional as F
from torch import nn, zeros, cat, bmm
from data import MAX_LENGTH
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_si... | 2.78125 | 3 |
lib/utils/convert.py | lin-zju/descriptor-space | 0 | 40257 | import torch
import numpy as np
import cv2
def tonumpyimg(img):
"""
Convert a normalized tensor image to unnormalized uint8 numpy image
For single channel image, no unnormalization is done.
:param img: torch, normalized, (3, H, W), (H, W)
:return: numpy: (H, W, 3), (H, W). uint8
"""
... | 2.953125 | 3 |
setup.py | radionets-project/vipy | 0 | 40258 | <gh_stars>0
from setuptools import setup, find_packages
setup(
name="vipy",
version="0.0.3",
description="Simulate radio interferometer observations and visibility generation.",
url="https://github.com/radionets-project/vipy",
author="<NAME>, <NAME>, <NAME>",
author_email="<EMAIL>",
license... | 1.601563 | 2 |
nicos/devices/taco/axis.py | ess-dmsc/nicos | 1 | 40259 | # -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | 1.773438 | 2 |
rings/1round/rings.py | dendaxD/QAOA-MaxCut-amplitudes | 0 | 40260 | import subprocess
from os import system, remove, chdir
from tabulate import tabulate
def edges(n):
location = 0
edges = [[0,n-1]]
for i in range(n-1):
edges.append([location, location+1])
location += 1
return edges
def cut(state, edges):
cut = 0
for edge in edges:
cut += 1 if state[edge[0]] == state[ed... | 3.078125 | 3 |
SNMP/pycopia/SNMP/Stripcharts.py | kdart/pycopia | 89 | 40261 | <reponame>kdart/pycopia
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.or... | 1.84375 | 2 |
src/views/constants_view.py | philherrmann/httpchallenge | 0 | 40262 | FORMAT_MSG_HIGH_ALERT = "High traffic generated an alert - hits = %s, triggered at %s"
FORMAT_MSG_RECOVERED_ALERT = "Traffic recovered - hits = %s, triggered at %s"
HIGHEST_HITS_HEADER = "Highest hits"
ALERTS_HEADER = "Alerts"
| 1.117188 | 1 |
base_model.py | pomonam/Self-Tuning-Networks | 44 | 40263 | from abc import ABCMeta
from layers.linear import *
from layers.conv2d import *
import torch.nn as nn
# Add custom layers here.
_STN_LAYERS = [StnLinear, StnConv2d]
class StnModel(nn.Module, metaclass=ABCMeta):
# Initialize an attribute self.layers (a list containing all layers).
def get_layers(self):
... | 2.6875 | 3 |
mnist.py | huisedenanhai/Torch-Baker | 3 | 40264 | <filename>mnist.py
from torchvision import datasets
import torchbaker as tb
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, ToTensor, Normalize
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init_... | 3.015625 | 3 |
pvapy/pvaPyProblem.py | mrkraimer/testPvaPy | 0 | 40265 | from pvapy import Channel, CA, PvTimeStamp, PvAlarm
print('DBRdouble')
channel = Channel('DBRdouble')
timestamp = PvTimeStamp(10, 100)
alarm = PvAlarm(1,1,"mess")
print(channel.get('value'))
print('here 1')
channel.put(alarm,'record[process=false]field(alarm)')
print('here 2')
print(channel.get('value'))
channel.put(ti... | 2.265625 | 2 |
Balsn_CTF_2019/Need_some_flags/solution/Need_some_flags_2_exp.py | sces60107/My-CTF-Challenges | 3 | 40266 | from pwn import *
import hashlib
r=remote("172.16.17.32",10122)
## pow
temp=r.recvuntil("sha256( ")
prefix=r.recvline().split()[0]
i=0
while True:
data=prefix+str(i)
Hash=hashlib.sha256(data)
if Hash.hexdigest()[:5]=="0"*5:
r.sendline(str(i))
break
i+=1
## get flag
r.sendline("0")
r.sendline("system... | 2.09375 | 2 |
hnn/src/apps/training_utils.py | anlewy/mt-dnn | 2,075 | 40267 | #
# Author: <EMAIL>
# Date: 01/25/2019
#
""" Utils for training and optimization
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import utils
logger=utils.get_logger()
import numpy as np
import torch
from bert.optimization import BertAdam
def zero_grad... | 2.375 | 2 |
setup.py | SomeHybrid/mineid | 0 | 40268 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import mineid
import pathlib
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name=mineid.__name__,
version=mineid.__version__,
description="A small Python library for gettin... | 1.328125 | 1 |
alyBlog/apps/news/templatetags/__init__.py | Hx-someone/aly-blog | 1 | 40269 | <reponame>Hx-someone/aly-blog
# -*- coding: utf-8 -*-
"""
@Time : 2020/3/2 14:38
@Author : 半纸梁
@File : __init__.py.py
""" | 0.964844 | 1 |
sdk2-src/src/azure-ml/azure/ml/_schema/job/base_job.py | DamovisaOrg/azureml-v2-preview | 1 | 40270 | <filename>sdk2-src/src/azure-ml/azure/ml/_schema/job/base_job.py
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from marshmallow import fields
from typing import Dict, Optional, Any
... | 1.9375 | 2 |
CCICApp/models.py | kiddhmh/DjangoSpiders | 2 | 40271 | from django.db import models
# 微博Model
class vvebo(models.Model):
id = models.IntegerField(primary_key=True)
keyword = models.TextField(max_length=1000, default="")
user_id = models.TextField(max_length=1000, default="")
user_name = models.TextField(max_length=1000, default="")
time = models.CharFi... | 2.09375 | 2 |
mpids/utils/__init__.py | edgargabriel/mpids | 1 | 40272 | <filename>mpids/utils/__init__.py
from .ParallelIO import *
| 1.117188 | 1 |
stats/offense.py | itsjessie/Python-Baseball | 0 | 40273 | import pandas as pd
import matplotlib.pyplot as plt
from data import games
plays = games[games['type']=='play']
plays.columns= ['type','inning','team', 'player', 'count','pitches','event', 'game_id', 'year']
#print (plays)
hits = plays.loc[plays['event'].str.contains('^(?:S(?!B)|D|T|HR)'), ['inning','event']]
#print... | 3.5625 | 4 |
app.py | nunezraf/Web_Scraping_and_Document_Databases | 0 | 40274 | # import necessary libraries
from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo
import scrape_marsdata
from pymongo import MongoClient
# create instance of Flask app
app = Flask(__name__)
# Use flask_pymongo to set up mongo connection
# conn = "mongodb://localhost:27017"
# client = p... | 3.015625 | 3 |
src/python/backends/py/sprite/__init__.py | andyjost/Sprite | 1 | 40275 | <filename>src/python/backends/py/sprite/__init__.py
'''Python wrappers for libsprite.so.'''
from ._sprite import *
import itertools, six
from six.moves import range
def Fingerprint__iter__(self):
for i in range(self.capacity):
v = self.get(i)
if v != UNDETERMINED:
yield i, v
def Fingerprint__repr__(s... | 2.421875 | 2 |
source/appModules/msimn.py | SWEN-712/screen-reader-brandonp728 | 0 | 40276 | #appModules/msimn.py - Outlook Express appModule
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2012 NVDA Contributors
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import winUser
import controlTypes
import displayModel
import textInfos
import api
impo... | 1.585938 | 2 |
week6/w6e1.py | melphick/pybasics | 0 | 40277 | <filename>week6/w6e1.py
#!/usr/bin/python
"""
A function that returns the multiplication product of three parameters--x, y,
and z has a default value of 1.
a. Call the function with all positional arguments.
b. Call the function with all named arguments.
c. Call the function with a mix of positional and named argumen... | 4.59375 | 5 |
bert/gelu.py | deepdialog/tf2bert | 0 | 40278 | <gh_stars>0
import math
import tensorflow as tf
def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
cdf = 0.5 * (1.... | 3.1875 | 3 |
calorimeter/plot.py | jevandezande/dsc | 0 | 40279 | <filename>calorimeter/plot.py
import numpy as np
from itertools import cycle
import matplotlib
import matplotlib.pyplot as plt
from .tools import y_at_x
def plotter(
scans,
title=None, style=None,
baseline_subtracted=False, set_zero=False, normalized=False, smoothed=False, peaks=None,
derivative=No... | 2.875 | 3 |
currency/__init__.py | p4l1ly/currency | 0 | 40280 | # -*- coding: utf-8 -*-
from .fetcher import from_all
| 1.023438 | 1 |
lista_ex1.py/exercicio5.py | robinson-1985/mentoria_exercises | 0 | 40281 | <filename>lista_ex1.py/exercicio5.py
''' 5.Faça um programa que receba o salário de um funcionário e o percentual de aumento,
calcule e mostre o valor do aumento e o novo salário. '''
salario = float(input("Digite o valor do salário: R$ "))
percentual_de_aumento = float(input("Digite a porcentagem de aumento do salari... | 3.265625 | 3 |
src/hobbits-plugins/analyzers/KaitaiStruct/ksy_py/hardware/mifare/mifare_classic.py | SabheeR/hobbits | 304 | 40282 | <gh_stars>100-1000
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
from pkg_resources import parse_version
import kaitaistruct
from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO
import collections
if parse_version(kaitaistruct.__version__) < parse_version(... | 1.992188 | 2 |
umbra/common/protobuf/umbra_grpc.py | serial-coder/umbra | 19 | 40283 | <gh_stars>10-100
# Generated by the Protocol Buffers compiler. DO NOT EDIT!
# source: umbra.proto
# plugin: grpclib.plugin.main
import abc
import typing
import grpclib.const
import grpclib.client
if typing.TYPE_CHECKING:
import grpclib.server
import google.protobuf.struct_pb2
import google.protobuf.timestamp_pb2
... | 1.734375 | 2 |
year2019/day2/solve.py | TheAnarchoX/AdventOfCode | 0 | 40284 | """ 2019 Day 2 Solver"""
import os
import sys
from typing import Tuple, List
from multiprocessing import Manager, Process
from multiprocessing.managers import ValueProxy
INPUT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input.txt")
def solve():
""" Solve https://adventofcode.com/2019/day/2"... | 3.296875 | 3 |
configs_custom/mmcls/dog-vs-cat/resnet50_b32x8.py | apulis/ApulisVision | 1 | 40285 | <reponame>apulis/ApulisVision
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000... | 1.859375 | 2 |
client-server-chatroom/server.py | crista/swarch | 0 | 40286 | from network import Listener, Handler, poll
handlers = {} # map client handler to user name
class MyHandler(Handler):
def on_open(self):
pass
def on_close(self):
pass
def on_msg(self, msg):
print msg
port = 8888
server = Listener(port, MyHandler)
while... | 2.9375 | 3 |
setup.py | monim67/django-sslcommerz | 0 | 40287 | <filename>setup.py
import setuptools
def get_long_description():
with open("README.md") as file:
return file.read()
setuptools.setup(
name="django-sslcommerz",
version="1.0.0",
description="Sslcommerz for django.",
long_description=get_long_description(),
url="https://github.com/moni... | 1.6875 | 2 |
gdsfactory/gdsdiff/gdsdiff.py | tvt173/gdsfactory | 0 | 40288 | import itertools
import pathlib
from pathlib import Path
from typing import Union
import gdspy
from gdsfactory.component import Component
from gdsfactory.import_gds import import_gds
COUNTER = itertools.count()
def xor_polygons(A: Component, B: Component, hash_geometry: bool = True):
"""Given two devices A and... | 2.5 | 2 |
vos/vos.py | astro-datalab/datalab | 13 | 40289 | """A set of Python Classes for connecting to and interacting with a VOSpace
service.
Connections to VOSpace are made using a SSL X509 certificat which is
stored in a .pem file.
"""
#from contextlib import nested
import copy
import errno
import fnmatch
import hashlib
import requests
from requests.exceptions i... | 2.453125 | 2 |
src/init.py | sheepsushis/reddit-karma-farming-bot | 0 | 40290 | import sys
from logs.logger import log
from utils import check_internet , get_public_ip
import bot
if __name__ == "__main__":
if check_internet() is True:
try:
log.info(f'Internet connection found : {get_public_ip()}')
bot.run()
except KeyboardInterrupt:
# quit
... | 2.65625 | 3 |
python_for_absolute_beginners/20_string_type.py | leonardo-gallegos/Python | 0 | 40291 | float_num = 3.14159265 # float_num is a variable which has been assigned a float
print(type(float_num)) # prints the type of float_num
print(str(float_num) + " is a float") # prints "3.14159265 is a float"
print("\"Hello, I'm Leonardo, nice to meet you!\"")
| 4.25 | 4 |
model_and_simulate/road_traffic_microscopic/traffic_simulation.py | tomtuamnuq/model_and_simulate | 1 | 40292 | <filename>model_and_simulate/road_traffic_microscopic/traffic_simulation.py
"""Module with microscopic traffic simulation class and additional features."""
from dataclasses import dataclass
from typing import Tuple
import random
import math
from .section import Section
from .vehicle import Vehicle
from model_and_simula... | 3.265625 | 3 |
make_cubes.py | cebarbosa/splus-fornax | 0 | 40293 | <reponame>cebarbosa/splus-fornax
# -*- coding: utf-8 -*-
"""
Created on 03/09/2020
Author : <NAME>
"""
from __future__ import print_function, division
import os
import itertools
import warnings
import numpy as np
from astropy.io import fits
from astropy.table import Table
import astropy.units as u
import astropy.c... | 1.65625 | 2 |
docter/server.py | istommao/docter | 0 | 40294 | <reponame>istommao/docter
"""docter server."""
import os
import sys
import mimetypes
from datetime import datetime
from wsgiref import simple_server
import falcon
from jinja2 import Environment, FileSystemLoader
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(os.path.dirname(os.... | 2.3125 | 2 |
robotidy/transformers/SplitTooLongLine.py | bollwyvl/robotframework-tidy | 0 | 40295 | from robot.api.parsing import ModelTransformer, Token
try:
from robot.api.parsing import InlineIfHeader
except ImportError:
InlineIfHeader = None
from robotidy.disablers import skip_section_if_disabled
from robotidy.utils import ROBOT_VERSION
EOL = Token(Token.EOL)
CONTINUATION = Token(Token.CONTINUATION)
c... | 2.859375 | 3 |
core/api/mixins/common.py | martbln/django-service-boilerplate | 18 | 40296 | <filename>core/api/mixins/common.py
from rest_framework import status
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
class BulkCreateModelMixin(CreateModelMixin):
"""
Either create a single or many model instances in bulk by using the
Serializers ``many=Tru... | 2.421875 | 2 |
prompt_toolkit/contrib/repl.py | mfussenegger/python-prompt-toolkit | 0 | 40297 | """
Utility for creating a Python repl.
::
from prompt_toolkit.contrib.repl import embed
embed(globals(), locals(), vi_mode=False)
"""
# Warning: don't import `print_function` from __future__, otherwise we will
# also get the print_function inside `eval` on Python 2.7.
from __future__ import unicod... | 2.859375 | 3 |
zerorobot/task/utils.py | PeterNashaat/0-robot | 3 | 40298 | <reponame>PeterNashaat/0-robot<filename>zerorobot/task/utils.py<gh_stars>1-10
from js9 import j
from . import (PRIORITY_NORMAL, PRIORITY_RECURRING, PRIORITY_SYSTEM,
TASK_STATE_ERROR, TASK_STATE_NEW, TASK_STATE_OK,
TASK_STATE_RUNNING)
from .task import Task
def _instantiate_task(task, se... | 2.53125 | 3 |
features/editops.py | snukky/yarescorer | 0 | 40299 | from base import FeatureBase
from difflib import SequenceMatcher
class FeatureEdits(FeatureBase):
name = 'edits'
desc = 'counts of word-based edit operations'
def run(self, trg, src):
matcher = SequenceMatcher(None, src.split(), trg.split())
ops = [tag for tag, _, _, _, _ in matcher.get_o... | 2.5625 | 3 |