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 |
|---|---|---|---|---|---|---|
generator/database.py | Neotrinost/Neotrinost.ir | 4 | 2000 | import sqlite3
class Database:
def get_connection(self):
return sqlite3.connect("./db.sqlite")
def add_card(self, card_title, card_text, card_link_text, card_link_url):
con = self.get_connection()
cur = con.cursor()
create_table_query = "CREATE TABLE IF NOT EXISTS cards('card... | 3.828125 | 4 |
crits/backdoors/forms.py | frbapolkosnik/crits | 22 | 2001 | <gh_stars>10-100
from django import forms
from django.forms.utils import ErrorList
from crits.campaigns.campaign import Campaign
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_item_names, get_source_names
from crits.core.user_tools import get_user_organizati... | 2.078125 | 2 |
src/aprl/agents/monte_carlo.py | fkamrani/adversarial-policies | 211 | 2002 | <filename>src/aprl/agents/monte_carlo.py
"""Monte Carlo receding horizon control."""
from abc import ABC, abstractmethod
from multiprocessing import Pipe, Process
import gym
from stable_baselines.common.vec_env import CloudpickleWrapper
from aprl.common.mujoco import MujocoState, ResettableEnv
class MujocoResettab... | 2.5 | 2 |
machineLearnInAction/bayes.py | xuwening/tensorflowDemo | 0 | 2003 | <filename>machineLearnInAction/bayes.py
import numpy as np
def loadDataSet():
postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], #[0,0,1,1,1......]
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cu... | 3.140625 | 3 |
py/debug/__init__.py | segrids/arduino_due | 3 | 2004 | <reponame>segrids/arduino_due<filename>py/debug/__init__.py
from .swd import SWD
from .ahb import AHB
from .debugger import Debugger, HaltError, NotHaltedError
try:
from .dwarf import ELFDebugger
except ImportError:
pass
| 1.265625 | 1 |
HAP-NodeJS/Switch3_1.py | cbdunc2/pi-kit | 0 | 2005 | import subprocess
subprocess.Popen(['sh', '../Switches/Switch3_On.sh'])
| 1.53125 | 2 |
src/cicd_sim/artifact/__init__.py | Software-Natives-OSS/cicd_sim | 0 | 2006 | from . artifactory import Artifactory
__all__ = ['Artifactory']
| 1.070313 | 1 |
mandoline/line_segment3d.py | Spiritdude/mandoline-py | 5 | 2007 |
class LineSegment3D(object):
"""A class to represent a 3D line segment."""
def __init__(self, p1, p2):
"""Initialize with two endpoints."""
if p1 > p2:
p1, p2 = (p2, p1)
self.p1 = p1
self.p2 = p2
self.count = 1
def __len__(self):
"""Line segment... | 3.6875 | 4 |
cacheable/adapter/PeeweeAdapter.py | d1hotpep/cacheable | 0 | 2008 | <reponame>d1hotpep/cacheable
import peewee
import playhouse.kv
from time import time
from . import CacheableAdapter
class PeeweeAdapter(CacheableAdapter, peewee.Model):
key = peewee.CharField(max_length=256, unique=True)
value = playhouse.kv.JSONField()
mtime = peewee.IntegerField(default=time)
ttl =... | 2.4375 | 2 |
mmgen/models/architectures/arcface/helpers.py | plutoyuxie/mmgeneration | 0 | 2009 | from collections import namedtuple
import torch
from torch.nn import (AdaptiveAvgPool2d, BatchNorm2d, Conv2d, MaxPool2d,
Module, PReLU, ReLU, Sequential, Sigmoid)
# yapf: disable
"""
ArcFace implementation from [TreB1eN](https://github.com/TreB1eN/InsightFace_Pytorch) # isort:skip # noqa
"""
# ... | 3.109375 | 3 |
createplaylist.py | mahi0601/SpotifyPlaylist | 47 | 2010 | <reponame>mahi0601/SpotifyPlaylist
import os
from spotifyclient import SpotifyClient
def main():
spotify_client = SpotifyClient(os.getenv("SPOTIFY_AUTHORIZATION_TOKEN"),
os.getenv("SPOTIFY_USER_ID"))
# get last played tracks
num_tracks_to_visualise = int(input("How man... | 3.75 | 4 |
tests/contrib/flask/test_request.py | thieman/dd-trace-py | 0 | 2011 | # -*- coding: utf-8 -*-
from ddtrace.compat import PY2
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.contrib.flask.patch import flask_version
from ddtrace.ext import http
from ddtrace.propagation.http import HTTP_HEADER_TRACE_ID, HTTP_HEADER_PARENT_ID
from flask import abort
from . import BaseFl... | 2.4375 | 2 |
ConvDR/data/preprocess_cast19.py | blazejdolicki/CHEDAR | 1 | 2012 | <filename>ConvDR/data/preprocess_cast19.py
import argparse
from trec_car import read_data
from tqdm import tqdm
import pickle
import os
import json
import copy
from utils.util import NUM_FOLD
def parse_sim_file(filename):
"""
Reads the deduplicated documents file and stores the
duplicate passage ids into ... | 2.578125 | 3 |
coord_convert/geojson_utils.py | brandonxiang/example-pyQGIS | 3 | 2013 | __doc__ = 'github: https://github.com/brandonxiang/geojson-python-utils'
import math
from coordTransform_utils import wgs84togcj02
from coordTransform_utils import gcj02tobd09
def linestrings_intersect(line1, line2):
"""
To valid whether linestrings from geojson are intersected with each other.
reference:... | 3.09375 | 3 |
config.py | Rinku92/Mini_Project3 | 0 | 2014 | import os
'''
user = os.environ['POSTGRES_USER']
password = os.environ['<PASSWORD>']
host = os.environ['POSTGRES_HOST']
database = os.environ['POSTGRES_DB']
port = os.environ['POSTGRES_PORT']
'''
user = 'test'
password = 'password'
host = 'localhost'
database = 'example'
port = '5432'
DATABASE_CONNECTION_URI = f'post... | 2.25 | 2 |
10_days_of_statistics_8_1.py | sercangul/HackerRank | 0 | 2015 | <reponame>sercangul/HackerRank
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 19:26:47 2019
@author: sercangul
"""
n = 5
xy = [map(int, input().split()) for _ in range(n)]
sx, sy, sx2, sxy = map(sum, zip(*[(x, y, x**2, x * y) for x, y in xy]))
b = (n * sxy - sx * sy) / (n * sx2 - sx**2)
a = ... | 3.109375 | 3 |
rlutils/gym/envs/reset_obs/hopper.py | vermouth1992/rl-util | 0 | 2016 | import gym.envs.mujoco.hopper as hopper
import numpy as np
class HopperEnv(hopper.HopperEnv):
def _get_obs(self):
return np.concatenate([
self.sim.data.qpos.flat[1:],
self.sim.data.qvel.flat,
])
def reset_obs(self, obs):
state = np.insert(obs, 0, 0.)
qp... | 2.359375 | 2 |
reco_utils/recommender/deeprec/io/iterator.py | yutian-zhao/recommenders | 0 | 2017 | <reponame>yutian-zhao/recommenders
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
# import tensorflow as tf
import abc
class BaseIterator(object):
@abc.abstractmethod
def parser_one_line(self, line):
pass
@abc.abstractmethod
d... | 2.375 | 2 |
HW6/YuliiaKutsyk/3_ unfinished_loop_bug_fixing.py | kolyasalubov/Lv-677.PythonCore | 0 | 2018 | def create_array(n):
res=[]
i=1
while i<=n:
res.append(i)
i += 1
return res
| 3.21875 | 3 |
ncm/api.py | SDhuangao/netease-cloud-music-dl | 0 | 2019 | <reponame>SDhuangao/netease-cloud-music-dl
# -*- coding: utf-8 -*-
import requests
from ncm.encrypt import encrypted_request
from ncm.constants import headers
from ncm.constants import song_download_url
from ncm.constants import get_song_url
from ncm.constants import get_album_url
from ncm.constants import get_artist... | 2.640625 | 3 |
book/trees/binary_search_tree.py | Web-Dev-Collaborative/algos | 153 | 2020 | # -*- coding: utf-8 -*-
"""
The `TreeNode` class provides many helper functions that make the work
done in the `BinarySearchTree` class methods much easier. The
constructor for a `TreeNode`, along with these helper functions, is
shown below. As you can see, many of these helper functions help to
classify a node acco... | 4.125 | 4 |
fire/core.py | adamruth/python-fire | 1 | 2021 | <filename>fire/core.py
# Copyright (C) 2017 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... | 2.921875 | 3 |
app.py | AmirValeev/auto-ml-classifier | 0 | 2022 | <reponame>AmirValeev/auto-ml-classifier<gh_stars>0
import os, ast
import pandas as pd
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import make_column_transformer
from sklearn.pipeline import make_pipeline
import pic... | 3.078125 | 3 |
util/headers.py | giuseppe/quay | 2,027 | 2023 | <gh_stars>1000+
import base64
def parse_basic_auth(header_value):
"""
Attempts to parse the given header value as a Base64-encoded Basic auth header.
"""
if not header_value:
return None
parts = header_value.split(" ")
if len(parts) != 2 or parts[0].lower() != "basic":
return... | 2.96875 | 3 |
indico/core/signals/event/core.py | tobiashuste/indico | 0 | 2024 | <gh_stars>0
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.signals.event import _signals
sidemenu = _signals.signal('sidemenu', """
Ex... | 2.125 | 2 |
cinder/tests/unit/volume/drivers/emc/scaleio/test_delete_volume.py | aarunsai81/netapp | 11 | 2025 | # Copyright (c) 2013 - 2015 EMC Corporation.
# 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
#
# Unle... | 1.914063 | 2 |
example-package/transportation_tutorials/__init__.py | chrisc20042001/python-for-transportation-modeling | 0 | 2026 | # -*- coding: utf-8 -*-
__version__ = '1.0.2'
import os
import appdirs
import osmnx as ox
import joblib
import requests
from .files import load_vars, save_vars, cached, inflate_tar, download_zipfile
from .data import data, list_data, problematic
from .tools.view_code import show_file
from . import mapping
cache_dir ... | 2.359375 | 2 |
common/common.py | czajowaty/curry-bot | 3 | 2027 | <reponame>czajowaty/curry-bot<filename>common/common.py
from requests.models import PreparedRequest
def is_valid_url(url):
prepared_request = PreparedRequest()
try:
prepared_request.prepare_url(url, None)
return True
except Exception as e:
return False
class Timestamp: # a speed... | 2.8125 | 3 |
hendrix/test/test_ux.py | anthonyalmarza/hendrix | 0 | 2028 | import os
import sys
from . import HendrixTestCase, TEST_SETTINGS
from hendrix.contrib import SettingsError
from hendrix.options import options as hx_options
from hendrix import ux
from mock import patch
class TestMain(HendrixTestCase):
def setUp(self):
super(TestMain, self).setUp()
self.DEFAULTS... | 2.25 | 2 |
discord/types/interactions.py | Voxel-Fox-Ltd/Novus | 61 | 2029 | """
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
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
the rights to use, copy, modify, merge, ... | 1.5 | 2 |
local/local_sign.py | EVAyo/chaoxing_auto_sign | 0 | 2030 | # -*- coding: utf8 -*-
import os
import re
import time
import json
import random
import asyncio
from typing import Optional, List, Dict
from aiohttp import ClientSession
from aiohttp.cookiejar import SimpleCookie
from lxml import etree
from bs4 import BeautifulSoup
from config import *
from message import server_chan... | 2.515625 | 3 |
build/scripts-3.6/fit_background_model.py | stahlberggroup/umierrorcorrect | 0 | 2031 | <filename>build/scripts-3.6/fit_background_model.py<gh_stars>0
#!python
import numpy as np
from numpy import inf
from numpy import nan
from scipy.optimize import fmin
from scipy.stats import beta
from scipy.special import beta as B
from scipy.special import comb
import argparse
import sys
def parseArgs():
'''Funct... | 2.234375 | 2 |
caffe2/python/operator_test/partition_ops_test.py | KevinKecc/caffe2 | 585 | 2032 | # Copyright (c) 2016-present, Facebook, 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... | 1.710938 | 2 |
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_fib_common_cfg.py | Maikor/ydk-py | 0 | 2033 | """ Cisco_IOS_XR_fib_common_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR fib\-common package configuration.
This module contains definitions
for the following management objects\:
fib\: CEF configuration
Copyright (c) 2013\-2018 by Cisco Systems, Inc.
All rights reserved.
"""
from ... | 1.789063 | 2 |
action/combo.py | dl-stuff/dl9 | 0 | 2034 | """Series of actions that form a combo chain"""
from __future__ import annotations
from typing import Optional, Sequence, TYPE_CHECKING
from action import Action
from core.utility import Array
from core.constants import PlayerForm, SimActKind, MomentType
from core.database import FromDB
if TYPE_CHECKING:
from ent... | 2.484375 | 2 |
flask_unchained/bundles/session/config.py | achiang/flask-unchained | 0 | 2035 | <filename>flask_unchained/bundles/session/config.py
import os
from datetime import timedelta
from flask_unchained import BundleConfig
try:
from flask_unchained.bundles.sqlalchemy import db
except ImportError:
db = None
class _DefaultFlaskConfigForSessions(BundleConfig):
SESSION_COOKIE_NAME = 'session'
... | 2.21875 | 2 |
sktime/forecasting/base/adapters/_statsmodels.py | tombh/sktime | 1 | 2036 | #!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
__author__ = ["<NAME>"]
__all__ = ["_StatsModelsAdapter"]
import numpy as np
import pandas as pd
from sktime.forecasting.base._base import DEFAULT_ALPHA
from sktime.forecasting.base._sktime import _OptionalForecastingHorizonMixin
from sktime.forecasting.base._sktime ... | 2.640625 | 3 |
melodic/lib/python2.7/dist-packages/gazebo_msgs/srv/_GetLinkProperties.py | Dieptranivsr/Ros_Diep | 0 | 2037 | <gh_stars>0
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from gazebo_msgs/GetLinkPropertiesRequest.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class GetLinkPropertiesRequest(genpy.Message):
_md5s... | 2.25 | 2 |
jupytext/kernels.py | st--/jupytext | 5,378 | 2038 | """Find kernel specifications for a given language"""
import os
import sys
from .languages import same_language
from .reraise import reraise
try:
# I prefer not to take a dependency on jupyter_client
from jupyter_client.kernelspec import find_kernel_specs, get_kernel_spec
except ImportError as err:
find_... | 2.8125 | 3 |
scipy/sparse/_matrix_io.py | dhruv9vats/scipy | 1 | 2039 | import numpy as np
import scipy.sparse
__all__ = ['save_npz', 'load_npz']
# Make loading safe vs. malicious input
PICKLE_KWARGS = dict(allow_pickle=False)
def save_npz(file, matrix, compressed=True):
""" Save a sparse matrix to a file using ``.npz`` format.
Parameters
----------
file : str or file... | 3.578125 | 4 |
src/simulator/services/resources/atlas.py | ed741/PathBench | 46 | 2040 | from typing import Dict, List
from simulator.services.resources.directory import Directory
from simulator.services.services import Services
class Atlas(Directory):
def __init__(self, services: Services, name: str, parent: str, create: bool = False) -> None:
super().__init__(services, name, parent, create... | 2.671875 | 3 |
ingestion/src/metadata/great_expectations/builders/table/row_count_to_equal.py | ulixius9/OpenMetadata | 0 | 2041 | # Copyright 2022 Collate
# 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 writing, software... | 1.929688 | 2 |
tensorflow/bbox/jrieke-tf-parse-v2/jrieke_tf_dataset.py | gustavovaliati/obj-det-experiments | 0 | 2042 | '''
This code is based on https://github.com/jrieke/shape-detection/
'''
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import tensorflow as tf
import datetime
class JriekeBboxDataset:
def generate(self):
print('Generating...')
self.WIDTH = 8
self.HEIGHT = 8
... | 3.0625 | 3 |
src/knownnodes.py | skeevey/PyBitmessage | 1 | 2043 | import pickle
import threading
from bmconfigparser import BMConfigParser
import state
knownNodesLock = threading.Lock()
knownNodes = {}
knownNodesTrimAmount = 2000
def saveKnownNodes(dirName = None):
if dirName is None:
dirName = state.appdata
with knownNodesLock:
with open(dirName + 'knownn... | 2.671875 | 3 |
chroma_agent/action_plugins/manage_node.py | whamcloud/iml-agent | 1 | 2044 | # Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import os
from chroma_agent.lib.shell import AgentShell
from chroma_agent.log import console_log
from chroma_agent.device_plugins.action_runner import CallbackAfterResp... | 2.03125 | 2 |
census_data_downloader/core/tables.py | ian-r-rose/census-data-downloader | 0 | 2045 | #! /usr/bin/env python
# -*- coding: utf-8 -*
"""
A base class that governs how to download and process tables from a Census API table.
"""
import os
import logging
import pathlib
from . import geotypes
from . import decorators
logger = logging.getLogger(__name__)
class BaseTableConfig(object):
"""
Configures... | 2.859375 | 3 |
sgf2ebook.py | loujine/sgf2ebook | 0 | 2046 | <gh_stars>0
#!/usr/bin/env python3
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from uuid import uuid4
from zipfile import ZipFile
import jinja2
import sente # type: ignore
__version__ = (1, 0, 0)
SGF_RENDER_EXECUTABLE = './sgf... | 2.375 | 2 |
vmis_sql_python/evaluation/metrics/popularity.py | bolcom/serenade-experiments-sigmod | 0 | 2047 | class Popularity:
'''
Popularity( length=20 )
Used to iteratively calculate the average overall popularity of an algorithm's recommendations.
Parameters
-----------
length : int
Coverage@length
training_df : dataframe
determines how many distinct item_ids there are in the ... | 3.953125 | 4 |
dandeliondiary/household/urls.py | amberdiehl/dandeliondiary_project | 0 | 2048 | from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^settings$', views.household_dashboard, name='household_dashboard'),
url(r'^myinfo$', views.my_info, name='my_info'),
url(r'^profile$', views.household_profile, name='maintain_household'),
url(r'^members$', views.househ... | 1.875 | 2 |
private/templates/NYC/config.py | devinbalkind/eden | 0 | 2049 | # -*- coding: utf-8 -*-
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import current
from gluon.html import A, URL
from gluon.storage import Storage
from s3 import s3_fullname
T = current.T
settings... | 2.09375 | 2 |
experiments/issue561/v2.py | nitinkaveriappa/downward | 4 | 2050 | <reponame>nitinkaveriappa/downward
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from main import main
main("issue561-v1", "issue561-v2")
| 1.375 | 1 |
q2_qemistree/tests/test_fingerprint.py | tgroth97/q2-qemistree | 0 | 2051 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | 1.6875 | 2 |
chroma-manager/tests/utils/__init__.py | GarimaVishvakarma/intel-chroma | 0 | 2052 | import time
import datetime
import contextlib
@contextlib.contextmanager
def patch(obj, **attrs):
"Monkey patch an object's attributes, restoring them after the block."
stored = {}
for name in attrs:
stored[name] = getattr(obj, name)
setattr(obj, name, attrs[name])
try:
yield
... | 3.390625 | 3 |
tempo/worker.py | rackerlabs/Tempo | 4 | 2053 | <gh_stars>1-10
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Rackspace
# 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.a... | 1.78125 | 2 |
bin/basenji_motifs.py | AndyPJiang/basenji | 1 | 2054 | #!/usr/bin/env python
# Copyright 2017 Calico 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agr... | 2 | 2 |
apps/shop/urls.py | Joetib/jshop | 1 | 2055 | from django.urls import path
from . import views
app_name = "shop"
urlpatterns = [
path('', views.HomePage.as_view(), name="home-page"),
path('shop/', views.ProductListView.as_view(), name="product-list"),
path('shop/<int:category_pk>/', views.ProductListView.as_view(), name="product-list"),
path('sho... | 2 | 2 |
surpyval/parametric/expo_weibull.py | dfm/SurPyval | 0 | 2056 | <gh_stars>0
import autograd.numpy as np
from scipy.stats import uniform
from autograd import jacobian
from numpy import euler_gamma
from scipy.special import gamma as gamma_func
from scipy.special import ndtri as z
from scipy import integrate
from scipy.optimize import minimize
from surpyval import parametric as para
... | 1.976563 | 2 |
tests/test_base_table.py | stjordanis/datar | 110 | 2057 | <filename>tests/test_base_table.py<gh_stars>100-1000
import pytest
from datar import stats
from datar.base import *
from datar import f
from datar.datasets import warpbreaks, state_division, state_region, airquality
from .conftest import assert_iterable_equal
def test_table():
# https://www.rdocumentation.org/pa... | 2.15625 | 2 |
cqlengine/tests/statements/test_update_statement.py | dokai/cqlengine | 0 | 2058 | <reponame>dokai/cqlengine
from unittest import TestCase
from cqlengine.statements import UpdateStatement, WhereClause, AssignmentClause
from cqlengine.operators import *
class UpdateStatementTests(TestCase):
def test_table_rendering(self):
""" tests that fields are properly added to the select statement ... | 2.78125 | 3 |
packages/facilities/diagnostics/py/custom_checkbox.py | Falcons-Robocup/code | 2 | 2059 | <reponame>Falcons-Robocup/code
# Copyright 2020 <NAME> (Falcons)
# SPDX-License-Identifier: Apache-2.0
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
class Checkbox():
def __init__(self, name, position, default=False, label=None, rsize=0.6, enabled=True):
self... | 2.984375 | 3 |
generator.py | Axonny/HexagonalHitori | 0 | 2060 | from hitori_generator import Generator
from argparse import ArgumentParser
def generate(n: int, output_file: str) -> None:
if n < 3 or n > 8:
print("It isn't valid size")
exit(4)
generator = Generator(n)
data = generator.generate()
lines = map(lambda x: ' '.join(map(str, x)), data)
... | 3.375 | 3 |
opaflib/xmlast.py | feliam/opaf | 2 | 2061 | <filename>opaflib/xmlast.py
from lxml import etree
from opaflib.filters import defilterData
#Logging facility
import logging,code
logger = logging.getLogger("OPAFXML")
class PDFXML(etree.ElementBase):
''' Base pdf-xml class. Every pdf token xml representation will
have a span wich indicates where the orig... | 2.671875 | 3 |
course-code/imooc-tf-mnist-flask/mnist/module.py | le3t/ko-repo | 30 | 2062 | <filename>course-code/imooc-tf-mnist-flask/mnist/module.py
import tensorflow as tf
# y=ax+b linear model
def regression(x):
a = tf.Variable(tf.zeros([784, 10]), name="a")
b = tf.Variable(tf.zeros([10]), name="b")
y = tf.nn.softmax(tf.matmul(x, a) + b)
return y, [a, b]
# 定义卷积模型
def convolutional(x, ... | 3.234375 | 3 |
src/sol/handle_metaplex.py | terra-dashboard/staketaxcsv | 140 | 2063 | from common.make_tx import make_swap_tx
from sol.handle_simple import handle_unknown_detect_transfers
def handle_metaplex(exporter, txinfo):
transfers_in, transfers_out, _ = txinfo.transfers_net
if len(transfers_in) == 1 and len(transfers_out) == 1:
sent_amount, sent_currency, _, _ = transfers_out[0]... | 2.171875 | 2 |
dcor/independence.py | lemiceterieux/dcor | 0 | 2064 | """
Functions for testing independence of several distributions.
The functions in this module provide methods for testing if
the samples generated from two random vectors are independent.
"""
import numpy as np
import scipy.stats
from . import _dcor_internals, _hypothesis
from ._dcor import u_distance_correlation_sqr... | 3.609375 | 4 |
cinemasci/cis/__init__.py | cinemascience/cinemasc | 0 | 2065 | <reponame>cinemascience/cinemasc
from . import imageview
from . import cisview
from . import renderer
from . import convert
class cis:
"""Composible Image Set Class
The data structure to hold properties of a Composible Image Set.
"""
def __init__(self, filename):
""" The constructor. """
... | 2.625 | 3 |
applications/spaghetti.py | fos/fos-legacy | 2 | 2066 | <gh_stars>1-10
import numpy as np
import nibabel as nib
import os.path as op
import pyglet
#pyglet.options['debug_gl'] = True
#pyglet.options['debug_x11'] = True
#pyglet.options['debug_gl_trace'] = True
#pyglet.options['debug_texture'] = True
#fos modules
from fos.actor.axes import Axes
from fos import World, Window,... | 1.664063 | 2 |
faceai/gender.py | dlzdy/faceai | 1 | 2067 | #coding=utf-8
#性别识别
import cv2
from keras.models import load_model
import numpy as np
import chineseText
img = cv2.imread("img/gather.png")
face_classifier = cv2.CascadeClassifier(
"d:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml"
)
gray = cv2.cvtColor(img, cv2.CO... | 3.15625 | 3 |
csm_web/scheduler/tests/utils.py | mudit2103/csm_web | 0 | 2068 | from django.test import TestCase
from os import path
from rest_framework import status
from rest_framework.test import APIClient
import random
from scheduler.models import Profile
from scheduler.factories import (
CourseFactory,
SpacetimeFactory,
UserFactory,
ProfileFactory,
SectionFactory,
Att... | 2.203125 | 2 |
coldtype/beziers.py | tallpauley/coldtype | 0 | 2069 | import math
from fontTools.pens.recordingPen import RecordingPen, replayRecording
from fontTools.misc.bezierTools import calcCubicArcLength, splitCubicAtT
from coldtype.geometry import Rect, Point
def raise_quadratic(start, a, b):
c0 = start
c1 = (c0[0] + (2/3)*(a[0] - c0[0]), c0[1] + (2/3)*(a[1] - c0[1]))
... | 2.515625 | 3 |
p1_navigation/train.py | nick0lay/deep-reinforcement-learning | 0 | 2070 | """
Project for Udacity Danaodgree in Deep Reinforcement Learning
This script train an agent to navigate (and collect bananas!) in a large, square world.
A reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect a... | 4.09375 | 4 |
models/model_factory.py | jac99/Egonn | 9 | 2071 | # Warsaw University of Technology
from layers.eca_block import ECABasicBlock
from models.minkgl import MinkHead, MinkTrunk, MinkGL
from models.minkloc import MinkLoc
from third_party.minkloc3d.minkloc import MinkLoc3D
from misc.utils import ModelParams
def model_factory(model_params: ModelParams):
in_channels ... | 2.28125 | 2 |
mdns/Phidget22Python/Phidget22/Phidget.py | rabarar/phidget_docker | 0 | 2072 | import sys
import ctypes
from Phidget22.PhidgetSupport import PhidgetSupport
from Phidget22.Async import *
from Phidget22.ChannelClass import ChannelClass
from Phidget22.ChannelSubclass import ChannelSubclass
from Phidget22.DeviceClass import DeviceClass
from Phidget22.DeviceID import DeviceID
from Phidget22.ErrorEvent... | 2.015625 | 2 |
openprocurement/auctions/geb/tests/blanks/create.py | oleksiyVeretiuk/openprocurement.auctions.geb | 0 | 2073 | def create_auction(self):
expected_http_status = '201 Created'
request_data = {"data": self.auction}
entrypoint = '/auctions'
response = self.app.post_json(entrypoint, request_data)
self.assertEqual(response.status, expected_http_status)
def create_auction_check_minNumberOfQualifiedBids(self):
... | 2.640625 | 3 |
tests/integration/test_celery.py | crossscreenmedia/scout_apm_python | 0 | 2074 | # coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from contextlib import contextmanager
import celery
import pytest
from celery.signals import setup_logging
import scout_apm.celery
from scout_apm.api import Config
# http://docs.celeryproject.org/en/latest/userguide/te... | 1.804688 | 2 |
molly/apps/places/migrations/0001_initial.py | mollyproject/mollyproject | 7 | 2075 | <gh_stars>1-10
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Source'
db.create_table('places_source', (
('id', self.gf('django.db.mo... | 2.078125 | 2 |
sdk/python/pulumi_azure_native/servicebus/v20210601preview/get_subscription.py | polivbr/pulumi-azure-native | 0 | 2076 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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, Union, overload
from ... import _utilities
fro... | 1.59375 | 2 |
py_cfeve/module/CFAF240400E0-030TN-A1.py | crystalfontz/CFA-EVE-Python-Library | 1 | 2077 | <reponame>crystalfontz/CFA-EVE-Python-Library<gh_stars>1-10
#===========================================================================
#
# Crystalfontz Raspberry-Pi Python example library for FTDI / BridgeTek
# EVE graphic accelerators.
#
#-------------------------------------------------------------------------... | 1.96875 | 2 |
quapy/model_selection.py | OneToolsCollection/HLT-ISTI-QuaPy | 0 | 2078 | import itertools
import signal
from copy import deepcopy
from typing import Union, Callable
import numpy as np
import quapy as qp
from quapy.data.base import LabelledCollection
from quapy.evaluation import artificial_prevalence_prediction, natural_prevalence_prediction, gen_prevalence_prediction
from quapy.method.agg... | 2.203125 | 2 |
flasky.py | ZxShane/slam_hospital | 0 | 2079 | # -*- coding: utf-8 -*-
import os
from flask_migrate import Migrate
from app import create_app, db
from app.models import User, Role, PoseToLocation
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(app, db)
# migrate 的新建 我们需要扫描到这些文件我们才能创建
@app.shell_context_processor
def make_shell_conte... | 2.46875 | 2 |
python/day09/smoke_basin.py | aesdeef/advent-of-code-2021 | 2 | 2080 | INPUT_FILE = "../../input/09.txt"
Point = tuple[int, int]
Heightmap = dict[Point, int]
Basin = set[Point]
def parse_input() -> Heightmap:
"""
Parses the input and returns a Heightmap
"""
with open(INPUT_FILE) as f:
heights = [[int(x) for x in line.strip()] for line in f]
heightmap: Heigh... | 4.0625 | 4 |
playground.py | NHGmaniac/voctoconfig | 0 | 2081 | <filename>playground.py
#!/usr/bin/env python3
import signal
import logging
import sys
from gi.repository import GObject
GObject.threads_init()
import time
from lib.args import Args
from lib.loghandler import LogHandler
import lib.connection as Connection
def testCallback(args):
log = logging.getLogger("Test... | 2.46875 | 2 |
tianshou/utils/logger/tensorboard.py | Aceticia/tianshou | 4,714 | 2082 | <reponame>Aceticia/tianshou<filename>tianshou/utils/logger/tensorboard.py
import warnings
from typing import Any, Callable, Optional, Tuple
from tensorboard.backend.event_processing import event_accumulator
from torch.utils.tensorboard import SummaryWriter
from tianshou.utils.logger.base import LOG_DATA_TYPE, BaseLog... | 2.15625 | 2 |
PythonAPI/pythonwrappers/jetfuel/gui/menu.py | InsightGit/JetfuelGameEngine | 4 | 2083 | # Jetfuel Game Engine- A SDL-based 2D game-engine
# Copyright (C) 2018 InfernoStudios
#
# 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... | 2.671875 | 3 |
latent_programmer/decomposition_transformer_attention/train.py | ParikhKadam/google-research | 2 | 2084 | # coding=utf-8
# Copyright 2021 The Google Research 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 applicab... | 1.523438 | 2 |
plot/profile_interpolation/plot_profile.py | ziyixi/SeisScripts | 0 | 2085 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import click
import numba
def prepare_data(data_pd, parameter):
lon_set = set(data_pd["lon"])
lat_set = set(data_pd["lat"])
dep_set = set(data_pd["dep"])
lon_list = sorted(lon_set)
lat_list = sorted(lat_set)
dep_list = sor... | 2.703125 | 3 |
tests/test_heroku.py | edpaget/flask-appconfig | 61 | 2086 | from flask import Flask
from flask_appconfig import HerokuConfig
def create_sample_app():
app = Flask('testapp')
HerokuConfig(app)
return app
def test_herokupostgres(monkeypatch):
monkeypatch.setenv('HEROKU_POSTGRESQL_ORANGE_URL', 'heroku-db-uri')
app = create_sample_app()
assert app.config... | 2.453125 | 2 |
flask/util/logger.py | Dev-Jahn/cms | 0 | 2087 | import logging
"""
Formatter
"""
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d:%H:%M:%S')
"""
Set Flask logger
"""
logger = logging.getLogger('FLASK_LOG')
logger.setLevel(logging.DEBUG)
stream_log = logging.StreamHandler()
stream_log.setFormatter(form... | 2.65625 | 3 |
utils/backups/backup_psql.py | Krovatkin/NewsBlur | 0 | 2088 | #!/usr/bin/python3
import os
import sys
import socket
CURRENT_DIR = os.path.dirname(__file__)
NEWSBLUR_DIR = ''.join([CURRENT_DIR, '/../../'])
sys.path.insert(0, NEWSBLUR_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'newsblur_web.settings'
import threading
class ProgressPercentage(object):
def __init__(self, fil... | 1.875 | 2 |
onap_tests/scenario/solution.py | Orange-OpenSource/xtesting-onap-tests | 0 | 2089 | <reponame>Orange-OpenSource/xtesting-onap-tests<filename>onap_tests/scenario/solution.py
#!/usr/bin/python
#
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/li... | 1.96875 | 2 |
tutorials/Controls4Docs/ControlEventsGraph.py | dominic-dev/pyformsd | 0 | 2090 | <gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
from __init__ import *
import random, time
from PyQt4 import QtCore
cla... | 2.4375 | 2 |
annotation_gui_gcp/orthophoto_view.py | lioncorpo/sfm.lion-judge-corporation | 1 | 2091 | from typing import Tuple
import numpy as np
import rasterio.warp
from opensfm import features
from .orthophoto_manager import OrthoPhotoManager
from .view import View
class OrthoPhotoView(View):
def __init__(
self,
main_ui,
path: str,
init_lat: float,
init_lon: float,
... | 2.40625 | 2 |
tempest/tests/lib/services/compute/test_security_group_default_rules_client.py | mail2nsrajesh/tempest | 254 | 2092 | <reponame>mail2nsrajesh/tempest<filename>tempest/tests/lib/services/compute/test_security_group_default_rules_client.py
# Copyright 2015 NEC Corporation. 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... | 1.953125 | 2 |
main.py | Light-Lens/PassGen | 3 | 2093 | <filename>main.py
# PassGen
# These imports will be used for this project.
from colorama import Fore, Style
from colorama import init
import datetime
import string
import random
import sys
import os
# Initilaze File organizer.
os.system('title PassGen')
init(autoreset = True)
# Create Log Functions.
cl... | 2.96875 | 3 |
memos/memos/models/Memo.py | iotexpert/docmgr | 0 | 2094 | """
The model file for a Memo
"""
import re
import os
import shutil
import json
from datetime import datetime
from flask import current_app
from memos import db
from memos.models.User import User
from memos.models.MemoState import MemoState
from memos.models.MemoFile import MemoFile
from memos.models.MemoSignature i... | 2.6875 | 3 |
course_catalog/etl/conftest.py | mitodl/open-discussions | 12 | 2095 | <filename>course_catalog/etl/conftest.py
"""Common ETL test fixtures"""
import json
import pytest
@pytest.fixture(autouse=True)
def mitx_settings(settings):
"""Test settings for MITx import"""
settings.EDX_API_CLIENT_ID = "fake-client-id"
settings.EDX_API_CLIENT_SECRET = "fake-client-secret"
settings... | 2.046875 | 2 |
juliaset/juliaset.py | PageotD/juliaset | 0 | 2096 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import random
class JuliaSet:
def __init__(self):
"""
Constructor of the JuliaSet class
:param size: size in pixels (for both width and height)
:param dpi: dots per inch (default 300)
"""
... | 3.15625 | 3 |
eye_detection.py | ShivanS93/VAtest_withOKN | 0 | 2097 | <reponame>ShivanS93/VAtest_withOKN
#!python3
# eye_detection.py - detect eyes using webcam
# tutorial: https://www.roytuts.com/real-time-eye-detection-in-webcam-using-python-3/
import cv2
import math
import numpy as np
def main():
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
eyeCas... | 3.484375 | 3 |
scripts/make_gene_table.py | lmdu/bioinfo | 0 | 2098 | <gh_stars>0
#!/usr/bin/env python
descripts = {}
with open('macaca_genes.txt') as fh:
fh.readline()
for line in fh:
cols = line.strip('\n').split('\t')
if cols[1]:
descripts[cols[0]] = cols[1].split('[')[0].strip()
else:
descripts[cols[0]] = cols[1]
with open('gene_info.txt') as fh:
for line in fh:
... | 3.015625 | 3 |
{{cookiecutter.repo_name}}/src/mix_with_scaper.py | nussl/cookiecutter | 0 | 2099 | <filename>{{cookiecutter.repo_name}}/src/mix_with_scaper.py
import gin
from scaper import Scaper, generate_from_jams
import copy
import logging
import p_tqdm
import nussl
import os
import numpy as np
def _reset_event_spec(sc):
sc.reset_fg_event_spec()
sc.reset_bg_event_spec()
def check_mixture(path_to_mix):
... | 2.0625 | 2 |