text stringlengths 50 981k | source stringlengths 5 120 | license stringclasses 125
values |
|---|---|---|
import requests
import csv
import json
root_address = "https://netrunnerdb.com/api/2.0/"
# For pulling from next rotation (AKA Mumbad-Gateway)
valid_codes = [
"sansan",
"honor-and-profit",
"order-and-chaos",
"data-and-destiny",
"mumbad",
"flashpoint",
"red-sand",
"kitara",
"reign-a... | Chemscribbler/Netrunner | MIT |
# coding: utf-8
#########################################################################
# 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> #
# author yeeku.H.lee kongyeeku@163.com #
# #
# version 1.0 ... | CypHelp/TestNewWorldDemo | Apache-2.0 |
import os
import itertools
import numpy as np
from PIL import Image
import torchvision.transforms as transforms
from torch.utils.data.sampler import Sampler
NO_LABEL = -1
def cifar10():
channel_stats = dict(mean=[0.4914, 0.4822, 0.4465],
std=[0.2470, 0.2435, 0.2616])
tra... | shenlong95/SSL-NAG | MIT |
import sys
import os
import random
import time
import pygame
import math
from constants import *
from pygame.locals import *
from pynput.keyboard import Key, Controller
class Square:
"""One tetris square"""
def __init__(self, xcoord, ycoord):
"""Initialize the square
Args:
xcoord... | hakosaj/PygameAI | MIT |
import attr
@attr.dataclass(slots=True)
class DataKeyDoc:
key: str
doc_count: float
| hexatester/covid19-id | MIT |
#!/usr/bin/env python
"""
Demos of real-time time encoding and decoding algorithms that use
IAF neurons.
"""
# Copyright (c) 2009-2015, Lev Givon
# All rights reserved.
# Distributed under the terms of the BSD license:
# http://www.opensource.org/licenses/bsd-license
import sys
import numpy as np
# Set matplotlib b... | bionet/ted.python | BSD-3-Clause |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: HJK
@file: test_addon_migu2.py
@time: 2019-06-10
"""
import sys
sys.path.append("..")
from music_dl import config
config.init()
from music_dl.addons import migu2
def test_migu2():
songs_list = migu2.search("丢了你","井胧")
print(songs_list)
assert songs... | WuZhiChengHF/music-dl | MIT |
import json, inspect
from helper.cEmbed import granted_msg, denied_msg
from helper.cLog import elog
config = json.load(open('config.json', 'r'))
path = __file__.split(config['split_path'])
file = path[len(path) - 1][:-3]
# ------------------ [ is_admin_only() ] ------------------ #
# Anybody can use this command... | aub-cp-training/Discord-Bot | MIT |
from .rule import Rule
from abc import ABC, abstractmethod
class CSVRule(Rule):
'''el_id can be either id of a node or of a resource'''
def __init__(self, name_in_csv, el_id):
self.id = el_id
self.name_in_csv = name_in_csv
super().__init__()
def get_name_in_csv(self):
... | ER-Visualizer/Visualizer | MIT |
#!/usr/bin/env python
# encoding: utf-8
"""
A module for scheduling jobs
Includes spawning, terminating, checking, and troubleshooting various jobs
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
import time
import os
import datetime
import numpy as np
import math
import shuti... | yunsiechung/ARC | MIT |
from typing import Any, Callable
import pytest
from pydantic import BaseModel
from moona.http.context import HTTPContext
from moona.http.handlers import HTTPHandler, end
from moona.http.response_body import negotiate, set_json, set_raw, set_text
class TestInnerBaseModel(BaseModel): # noqa
address: str
phon... | katunilya/mona | MIT |
"""REST API for accessing log files."""
from django.core.exceptions import ObjectDoesNotExist
from django.utils.decorators import method_decorator
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import generics, status
from rest_framework.decorators import (
api_view... | FairphoneMirrors/hiccup-server | Apache-2.0 |
# anagram.py -- find the case-insensitive anagrams of input words.
# Copyright (c) 2015 Scott Cheloha. All rights reserved.
# See LICENSE for complete licensing details.
from itertools import permutations
import argparse
wordSet = set()
# Strip whitespace from a string and lowercase it
def strip_and_lower(s):
r... | skotchandsoda/yay-anagrams | BSD-3-Clause |
"""
Тестируется реакция кнопок меню на нажатия в их области и вне их области
"""
from state import *
COUNT = 200
PAUSE = 1
RUN_TIME = 2
class PressChecker:
def __init__(self, state, x, y, width, height, num):
self.state = state
self.xs = list(np.random.rand(num) * width + x)
self.ys = li... | ficrus/battle-for-indent | MIT |
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='Flask-PAM',
version='0.1',
description='Flask authentication using PAM',
author='Kacper Kołodziej',
author_email='kacper@kolodziej.in',
url='https://github.com/KujiraProject/Flask-PAM',
packages=['flask_pam', 'flask_pa... | UnicronNL/vyos-rest-api | MIT |
import io
import pytest
from requests import get
from urllib.parse import urljoin
def test_my_uploads_page(wait_for_api, login_user):
"""
GIVEN a user has logged in (login_user)
WHEN the '/my/uploads' page is navigated to (GET)
THEN check the response is valid and page title is correct
"""
requ... | jounile/nollanet | MIT |
class Field(object):
def __init__(self, name=None, default=None, data_type=None):
self.name = name
self.default = default
self.required = self.default is None
self.type = data_type
def build(self):
result = {key: value for key, value in self.__dict__.items() if value is... | maxpowel/mapped_config | MIT |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from app.api import gas_price_prediction, airbnb_predict
app = FastAPI(
title='RESFEBER CARTER DS API',
description=""" Awesome Data Science Team.
\n**INSTRUCTIONS**
\n- To use the API, click on a *post* met... | EvidenceN/travel-price-predictions-api | MIT |
from tool.runners.python import SubmissionPy
class DivSubmission(SubmissionPy):
def run(self, s):
values = (int(x) for x in s.splitlines())
return sum((x//3-2) for x in values)
| SilvestrePerret/adventofcode-2019 | MIT |
"""
# @Time : 2020/12/17
# @Author : Jimou Chen
"""
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# 得到模型的评估指标,F1-分数,召回率,ROC曲线,PR曲线
from sklearn.metrics import classific... | JimouChen/machine-learning | Apache-2.0 |
from labjack import ljm
import time
import atexit, math, sys, getopt
from array import array
TARGET_POSITION_REG = 46080
CURRENT_POSITION_REG = 46082
ENABLE_REG = 46180
ESTOP_REG = 46181
HOLD_REG = 46182
RE_ZERO_TARGET_REG = 46183
def closeFunc():
print("Closing")
ljm.eWriteName(handle, "LUA_RUN", 0)
wai... | ggodlewski/labjack_kiplin | MIT |
# coding=utf-8
# Copyright 2020 The Trax 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 a... | MelodiousThonk/trax | Apache-2.0 |
###############################################################
# Copyright (c) 2017 taseer94@gmail.com and others.
#
# All rights reserved. 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
# ht... | hashnfv/hashnfv-qtip | Apache-2.0 |
"""Certbot main entry point."""
from __future__ import print_function
import atexit
import functools
import logging.handlers
import os
import sys
import time
import traceback
import zope.component
from acme import jose
from acme import messages
from acme import errors as acme_errors
import certbot
from certbot impo... | XieXianbin/ssl-api | Apache-2.0 |
from pydantic import BaseModel
from typing import Optional
class ContactBookResSchema(BaseModel):
id: int
name: str
email: str
class Config:
orm_mode = True
schema_extra = {
"example": {
"id": 1,
"name": "sample_name",
"email... | TheDesTrucToRR/Hacktoberfest-2021 | MIT |
import pytest
from joffrey import CLI
cli = CLI() | supposedly/kizbra | MIT |
def print_package_name():
return "This is Lib number 2"
| piqueen314/pythonMultipleProjectsOneRepoExample | MIT |
import os.path as op
import pytest
from click.testing import CliRunner
from jenskipper.cli import sweep
HERE = op.dirname(__file__)
@pytest.mark.parametrize('setup_cli_env_vars',
[(op.join(HERE, 'data'), 'good-repos')],
indirect=True)
def test_sweep(setup_cli_env_... | flupke/jenskipper | Apache-2.0 |
# [剑指 Offer 第 2 版第 51 题] “数组中的逆序对”做题记录
# 第 51 题:数组中的逆序对
# 传送门:数组中的逆序对,牛客网 online judge 地址。
# 在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
# 输入一个数组,求出这个数组中的逆序对的总数。
# 样例:
# 输入:[1,2,3,4,5,6,0]
# 输出:6
def mergeCount(nums,l,mid,r,temp):
for i in range(l,r+1):
temp[i] = nums[i]
i,j,res = l,mid+... | ZhengyangXu/Algorithm-Daily-Practice | MIT |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Modifications for Guinet et al.
import io
import warnings
import numpy as np
import argparse
from utils import *
from query_aux import *
#Disable warnings for Meta-features
warnings.filterwarnings("ignore")
# to use bool for parsing
def str2bool(v):
"""Parse Str... | Gguinet/semisupervised-alignment | MIT |
################# LocoDrone Python Control ##################
# Written by: Joey Orduna
# Filename: drone_control.py
##############################################################
# Import LocoRobo Libraries For Communication with Robot
from locorobo import LocoRobo
from locorobo import Data
from locorobo import Moto... | CobraPi/Gesture-Controled-Drone | CC0-1.0 |
# -*- coding: utf-8 -*-
import abc
import re
import selenium.common
from . import exceptions
class Marshaller(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def marshall(self, object_):
"""
Convert from one type to another.
Parameters
----------
obj... | dnguyen0304/room-list-watcher | MIT |
from dataframe_expressions.utils import DataFrameTypeError, _term_to_ast
import pytest
import ast
@pytest.mark.parametrize("the_term, the_type", [
(1, ast.Num),
(1.5, ast.Num),
((-1.0, 50.0), ast.Tuple),
([1, 2], ast.List),
])
def test_term_to_ast_type_check(the_term, the_type):
assert isinsta... | gordonwatts/dataframe_expressions | MIT |
import config.Text
from model.WavePatternFinder.WavePattern import WavePattern
def find_correction(df, idx_start):
name = config.Text.zigzag
waves = find_zigzag(df, idx_start)
correction = WavePattern(waves, name)
return correction
def find_zigzag(wave_list, idx_start):
waveA = wave_list[idx_s... | GigliOneiric/ElliotWave | Apache-2.0 |
from OpenGL.GL import *
import PIL.Image as Image
#----------------------------------------------texture development-----------
def loadTexture(imageName):
texturedImage = Image.open(imageName)
try:
imgX = texturedImage.size[0]
imgY = texturedImage.size[1]
img = texturedImage.t... | Felicia35/CS4182-course-project | MIT |
import model
from sklearn.externals import joblib
import itertools
if __name__ == "__main__":
corpus_root = "/Users/thisismattmiller/Downloads/gmb-2.2.0/"
reader = model.read_gmb_ner(corpus_root)
all_classes = ['O', 'B-per', 'I-per', 'B-gpe', 'I-gpe',
'B-geo', 'I-geo', 'B-org', 'I-org', 'B-tim',... | SemanticLab/DADAlytics-docker-nltk | MIT |
from .base import * # noqa
from .base import env
SECRET_KEY = env("SECRET_KEY")
ALLOWED_HOSTS = env.str("ALLOWED_HOSTS", "").split(",")
# Configure Sentry Logging
INSTALLED_APPS += ("raven.contrib.django.raven_compat",)
RAVEN_DSN = env.str("RAVEN_DSN", "")
RAVEN_CONFIG = {"dsn": RAVEN_DSN} if RAVEN_DSN else {}
| praekeltfoundation/Momkhulu | BSD-3-Clause |
import zmq
import time
import threading
import json
name = 'bob'
def cluster_manager (context, join_uri):
nodes = [name]
join_sock = context.socket (zmq.REP)
join_sock.bind (join_uri)
while True:
message = join_sock.recv ()
req = json.loads (message)
if 'type' in req and req['... | jpbarto/cluster_python_eval | MIT |
import math
import torch
class MaternCovariance(torch.autograd.Function):
@staticmethod
def forward(ctx, x1, x2, lengthscale, nu, dist_func):
if any(ctx.needs_input_grad[:2]):
raise RuntimeError("MaternCovariance cannot compute gradients with " "respect to x1 and x2")
if lengthsca... | llguo95/gpytorch | MIT |
from __future__ import annotations
from ..typecheck import *
from ..import core
from ..import ui
from ..debugger import dap
from ..views.input_list_view import InputListView
from ..import commands
from ..import settings
from .import util
import re
import threading
class LLDBTransport(dap.SocketTransport):
def ... | ta946/sublime_debugger | MIT |
# DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS songplays;"
user_table_drop = "DROP TABLE IF EXISTS users;"
song_table_drop = "DROP TABLE IF EXISTS songs;"
artist_table_drop = "DROP TABLE IF EXISTS artists;"
time_table_drop = "DROP TABLE IF EXISTS time;"
# CREATE TABLES
songplay_table_create = ("""
CRE... | amosvoron/udacity-data-modeling | MIT |
from django.utils import timezone
from rest_framework.response import Response
from rest_framework.views import APIView
from LoginManage.models import User
from UserManage.models import UserInfo
from UserManage.serializer import OneUser, LoginInfo
class LoginManageView(APIView):
def get(self, request, id=None):
... | fox-ahri/ahri-auth | MIT |
import logging as log
import numpy as np
from unittest import TestCase
from datumaro.components.project import Dataset
from datumaro.components.extractor import (Extractor, DatasetItem,
Mask, Polygon, PolyLine, Points, Bbox, Label,
LabelCategories, MaskCategories, AnnotationType
)
import datumaro.util.mask_too... | hazenai/cvat | MIT |
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.browser = QWebEngineView()
self.browser.setUrl(QUrl('https://duckduckgo.com'))
self.... | Programgenix/Basic-web-browser-python- | CC0-1.0 |
# -*- coding: utf-8 -*-
# 列表元素之和-递归写法
def sum(list):
if list == []:
return 0
return list[0] + sum(list[1:])
| youaresherlock/PythonPractice | Apache-2.0 |
import os
from .utils import DUMMY_GIT_URL, LibTestCase, TEST_EXTERNAL_LIBRARIES_ROOT
from .. import git
class CloneTestCase(LibTestCase):
def test_clone_ok(self):
path = os.path.join(TEST_EXTERNAL_LIBRARIES_ROOT, "dummy")
self.assertFalse(os.path.isdir(path))
self.assertEqual(0, git... | PremierLangage/sandbox | MIT |
#!/usr/bin/env python3
###########################################################
# Use of this file is strictly forbidden !!!!!!!!!!!!!!!!!#
# Copyright Yann Chemin, Freelancer, France, 2016 #
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
import xml.etree.ElementTree as ET
from osgeo import gd... | YannChemin/distRS | Unlicense |
# import required modules
import os
def getParams(params,case):
for mydict in params:
if mydict['id'] == case:
return mydict
raise(Exception("~~~~~ ERROR: CASE NOT FOUND ~~~~~"))
# # initialize `params` dictionary
# params = {}
# # stringlist = ['wingtype','batterytype','w... | rymanderson/Drone-Models | MIT |
"""
Created on Tue May 17 22:45:18 2020
@author: Maya Bohora
"""
import pandas as pd
# Defining global variables
path = './input/itcont_2020_20010425_20190426.txt'
path_out = './output/results.txt'
#Percentile
percentile = .3
data = pd.read_csv(path, sep="|", header=None)
#Inserting columns'name.
data.columns = ["... | bohoramaya/de-challenge-four | MIT |
import numpy as np
from os import listdir
from os.path import isfile, join
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import torch
import seaborn as sns
mypath = '../weights_sin2Reg/'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
layers = []
for each in sorted(onlyfi... | he-actlab/waveq.code | CNRI-Python |
from flask import Blueprint
report = Blueprint('report', __name__, template_folder='templates',
static_folder='static')
from . import views
| mbp76/restful-flask | Apache-2.0 |
"""
The purpose of this file is to allow instancemethods to be pickable.
This is needed in setup.py only and not installed anywhere, thus is not
a library file. It solves the issue from #11874.
"""
import types, copy_reg, copy
# The following four methods are taken from twisted.persisted.styles
# into sage.misc.fpic... | switzel/sage | BSL-1.0 |
#!/usr/bin/python
import pwd
import os
import re
import glob
import time
PROC_TCP = "/proc/net/nf_conntrack"
def _load():
''' Read the table of tcp connections & remove header '''
with open(PROC_TCP,'r') as f:
#content = f.readlines()
#content.pop(0)
content = f.read()
return con... | vtill/SecyrIT | MIT |
# flake8: noqa
from unittest.mock import Mock
from experiencecloudapis import Analytics
def test_authentication():
class FakeResponse:
status_code = 200
def json(self):
return {"test": "test"}
mock_auth_client = Mock()
mock_session = Mock()
mock_session.get = Mock(return... | DHLWebAnalytics/adobemarketingcloud | MIT |
# -*- coding: utf-8 -*-
"""
A number of useful functions for dealing with graphs
Created on Sun Dec 8 17:46:29 2013
@author: Graham
"""
import numpy as np
import scipy
import scipy.interpolate
def derivative(x,y,order=1):
"""Given the x any y arrays will return the derivative of this array, optionally higher d... | trigfa/mpUtilities | MIT |
from mock import patch
from tests import BaseTestCase
from redash.query_runner.big_query import BigQuery
class TestBigQuery(BaseTestCase):
def test_get_table_sample_returns_expected_result(self):
SAMPLES_RESPONSE = {
"rows": [
{
"f": [
... | jasonthomas/redash | BSD-2-Clause |
__version__ = "1.1.1"
#Import standard elements
import re
import os
import sys
import warnings
import traceback
import threading
import subprocess
# #Import communication elements for talking to other devices such as printers, the internet, a raspberry pi, etc.
import usb
import types
import bisect
import select
impo... | JoshMayberry/Communication_API | MIT |
# Copyright 2021 Invana
# #
# 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 ... | invanalabs/gremlin-driver | CNRI-Python |
from . import config
from . config_manager import ConfigManager
import subprocess
import os
# this class takes care of starting up a ROM
class GameRunner:
def __init__(self, platform, file_name):
self.platform = platform
self.file_name = file_name
self.RUN_SCRIPT_PATH = config.RPG_ROOT + "... | Blackweather/rpg-station | MIT |
import tensorflow as tf
import numpy as np
from branch_code_data import BranchCodeLoader
from sklearn.preprocessing import MinMaxScaler
import vae
import os
import pickle
'''
From a branch code generate its latent vector.
'''
test_data = "C:/Users/Administrator/Desktop/neuron_factor_tree_test/test/data/L4... | zzhmark/vaa3d_tools | MIT |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import compas.data
from compas_convert import register_converter
@register_converter([str], compas.data.Data)
def json_str_to_compas_obj(json_str): # type: (str) -> compas.data.Data
"""Convert JSON stri... | tetov/compas_convert | MIT |
import os
import re
import sys
import optparse
MARKER_START_FUNCS = "// EMSCRIPTEN_START_FUNCS"
MARKER_END_FUNCS = "// EMSCRIPTEN_END_FUNCS"
FUNCTION_CODE_RE = re.compile(
r"function (?P<name>[a-zA-Z0-9_]+)(?P<defn>.*?)((?=function)|(?=$))"
)
def analyze_code_size(fileobj, opts):
funcs = {}
name_re = Non... | WebDevCaptain/pypyjs | MIT |
from abc import ABC, abstractmethod
import random
import torch
"""
Policy Class
Returns an action from the action space based on policy
"""
class Policy(ABC):
def __init__(self, n_observations: int, n_actions: int, device: str):
self.n_observations = n_observations
self.n_actions = ... | Luca-Mueller/drl-transfer | MIT |
# -*- coding: utf-8 -*-
"""
Mimics parts of Qt signals implementation.
"""
import asyncio
from collections.abc import Awaitable
from typing import Callable, Optional
class Signal:
class _SignalInstance:
def __init__(self, signal):
self.connections = set()
self._signal = signal
... | mistotebe/examples | Unlicense |
from . import ttnClient
#ttnClient.mqtt_client.connect()
#ttnClient.mqtt_client.start() | borisfoko/IoTLoRaWanFahradSchloss | MIT |
#!/usr/bin/python3
""" Represents a map of TransAmerica """
import queue
import features
class Board:
"""
Represent the Trans America map. The key here is to keep
an array of costs from each node to each other node.
See features for a little more description of the mathematical
representa... | oscardssmith/Trans-America | MIT |
"""
This is an important test because it confirms that tcrdist2 reproduces
the metric results used in the paper described as the 'tcr-dist'.
There is one point that requires additional clarification.
The original tcr-dist pipeline acknowledged uncertainty in v-gene alpha
v-gene beta inferences. In some cases multipe ... | agartland/tcrdist2 | MIT |
# Goal: create a cPickle'd python dictionary
# containing the strand of each ensembl gene
#m mouse
import csv
import cPickle
if __name__ == "__main__":
mapping = {}
with open('../gtex/gtex_mouse/refGene_mouse.txt', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
for row in reader:
gene... | joshim5/CRISPR-Library-Designer | BSD-3-Clause |
# coding: utf-8
# Copyright Luna Technology 2015
# Matthieu Riviere <mriviere@luna-technology.com>
from __future__ import absolute_import
import os
from celery import Celery
# Set the default Django settings module for the 'celery' program
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pype.settings')
from djan... | h2020-westlife-eu/VRE | MIT |
import time
import logging
from collections import abc
class QueryError(Exception):
pass
class CondorPoolView(abc.Mapping):
"""
View on information in an HTCondor pool
:param pool: the pool to query for information
:param max_age: maximum age of information before refreshing
:param channel_... | maxfischer2781/cobald_condor_limits | MIT |
import os
from dropbox.client import DropboxOAuth2Flow
from flask import Flask
from flask import session
from flask import request
from flask import redirect
from flask import make_response
from flask import render_template
app = Flask(__name__)
app.secret_key = os.environ['SESSION_KEY']
app.config['DEBUG'] = True
D... | projectweekend/Pi-Box-Dropbox-Auth-Site | MIT |
from .base import BaseNextcloudObject
from ..managers import NextcloudGroupManager, related
# TODO check if groupfolders is installed!!
class NextcloudGroup(BaseNextcloudObject, manager=NextcloudGroupManager):
synced_attributes = ['name']
synced_relations = ['users', 'subadmins', 'folders']
... | donhauser/nextcloud-orm | Apache-2.0 |
from tkinter import *
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
import numpy as np
#commandline
import argparse
#visualization
import matplotlib.pyplot as plt
#font
import matplotlib.font_manager as fm
# import pyglet
#... | sayeedk06/Bertender | MIT |
from abc import ABC
import torch
import torch.nn as nn
import warnings
class PairLossSampler(nn.Module, ABC):
"""
A base class for TripletLossSampler and ContrastiveLossSampler.
Parameters
----------
criterion : nn.Module
A criterion module to compute the loss, followed by pairs sampling... | dizcza/pytorch-mighty | BSD-3-Clause |
from distalg import Process, DelayedChannel, Message, Simulation, dispatch, main
import networkx as nx
import asyncio
import logging
from enum import Enum
logging.basicConfig(level=logging.DEBUG)
class GoToken(Message):
def __init__(self):
super(GoToken, self).__init__()
class BackToken(Message):
def... | charlesemurray/DistributedProgramming | MIT |
"""
converts xml saved by 'opensim scene backup tool', in naali when used
with opensim/lludp, to tundra txml (pure naali EC attr style).
potentially useful for taiga->tundra migration, when the creators have
the original .mesh & .material files, but the scene is only in
opensim.
USAGE: requires python 2.7 (which has... | antont/tundra | Apache-2.0 |
from docx import Document # pip install python-docx
from docx.shared import Inches,Pt,RGBColor
from PIL import Image
import json
import os
import math
import argparse
class project_creator:
max_img_width = 700
def __init__(self,info_file,new_page_new_question = False):
# file name saved
... | rishabhjainfinal/class_automations | MIT |
# 正则表达式
# Python re 模块
import re
s = 'ABC\\-001'
s1 = r'ABC\-001'
match = re.match(s1, '010-12345')
match1 = re.match(s, 'ABC-001')
if match:
print('match yes')
else:
print('match not')
if match1:
print('match1 yes')
else:
print('match1 no')
print(match1)
# 切分字符串
valid = re.split(r'[\s\,\;]+', '... | FLYKingdom/CodeSeeker | MIT |
import sys, os
import pytest
import pandas as pd
# import numpy as np
import subprocess, multiprocessing
import matplotlib.pyplot as plt
### go 2 levels up and add to path
python_modules_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(os.path.realpath(__file__))), "../../"))
sys.path.insert(0, pytho... | RadjaHachilif/agotool | MIT |
import argparse
import os
import sys
sys.path.insert(1, os.getcwd())
from gits_sync import gits_sync
from mock import patch, Mock
def parse_args(args):
parser = argparse.ArgumentParser()
return parser.parse_args(args)
@patch("argparse.ArgumentParser.parse_args",
return_value=argparse.Namespace(sour... | oaaky/GITS | MIT |
# Copyright 2017 QuantRocket - 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 ... | quantrocket-llc/quantrocket-client | Apache-2.0 |
"""Newton-CG trust-region optimization."""
from __future__ import division, print_function, absolute_import
import math
import numpy as np
import scipy.linalg
from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
__all__ = []
def _minimize_trust_ncg(fun, x0, args=(), jac=None, hess=None, hess... | anthowen/duplify | MIT |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from queue import PriorityQueue
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# O(nlogk) time and O(n) space
# minPriori... | stuti-rastogi/leetcode-python-solutions | MIT |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as et
import sys
def usage():
print(f"Usage: {sys.argv[0]} <base_output.xml> <new_output.xml>")
try:
base = et.parse(sys.argv[1])
new = et.parse(sys.argv[2])
except:
usage()
sys.exit(1)
def get_results(data):
test... | antmicro/verilator-dynamic-scheduler-tests | Apache-2.0 |
import os
import glob
import logging
import argparse
import math
import torch
import torch.multiprocessing as mp
import torch.distributed as dist
from torch.utils.data import DataLoader
from typing import List
from subprocess import call
from utils.tools import read_data, write_data, load_transformer, load_model
from... | cordercorder/NMT | MIT |
import sys
import os
import glob
import logging
import operator
import time
import pickle
import multiprocessing as mp
import numpy as np
from datetime import datetime
from Bio.PDB import *
import copy
import gc
# python 3 compatibility
from functools import reduce
from past.builtins import map
sys.path.append('../..... | ucfcbb/RNAMotifContrast | MIT |
import GRT
import sys
import argparse
def main():
'''GRT KMeansQuantizer Example
This examples demonstrates how to use the KMeansQuantizer module.
The KMeansQuantizer module quantizes the N-dimensional input vector to a 1-dimensional discrete
value. This value will be between [0 K-1], where K ... | torydebra/grt | MIT |
"""
DoH JSON client in Python
"""
import json
import urllib3
import sys
import argparse
import socket
import signal
import random
# noinspection PyShadowingBuiltins, PyUnusedLocal
def handler(sgn, frame):
"""
:param sgn:
:param frame:
:return:
"""
sys.exit(0)
# noin... | farfella/pydoh | MIT |
""" Neuronal Avalanches parameters
This script contains the parameters for the Neuronal Avalanche experiment.
"""
import os
import numpy as np
import utils
par = utils.Bunch()
aux = utils.Bunch()
################################################################################
# SORN main ... | carolinscholl/SORN | MIT |
import html
import io
from functools import singledispatch
from django.conf import settings
from django.http import HttpResponseServerError, HttpResponse
@singledispatch
def render_response(obj):
"""
Convert arbitrary Python objects to http responses.
By default, it tries to render object using :func:`r... | pencil-labs/django-boogie | BSD-3-Clause |
# Quicksilver.py - Agnostic project analyzer that generates resourceful diagrams. WIP
# Copyright (C) 2018 Logan Campos - @binaryflesh
| binaryflesh/quicksilver | MIT |
'''
Copyright 2018 MyHeritage Inc.
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, publish, distribute,... | erlichya/signature | MIT |
def auto_str(cls):
"""Annotation that provides a default __str__ method for objects.
Example:
Annotating a class with the ``@auto_str`` annotation::
>>> @auto_str
class Dummy(object):
def __init__(self, a):
self.a = a... | trochumski/teamscale-client-python | Apache-2.0 |
"""
Our own implementation of an abstract syntax tree (AST).
The convert function recursively converts a Python AST (from the module `ast`)
to our own AST (of the class `Node`).
"""
import ast
from logging import debug
from typy.builtin import data_types
from typy.exceptions import NotYetSupported, NoSuchAttribute, ... | Procrat/typy | MIT |
"""Remove RoomAttribute.is_required
Revision ID: 4f98f2f979c7
Revises: 7e03b2262e9e
Create Date: 2018-11-23 10:36:14.406211
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '4f98f2f979c7'
down_revision = '7e03b2262e9e'
branch_labels = None
depends_on = None
de... | bpedersen2/indico | MIT |
# File name: __init__.py
# Author: Jordan Juravsky
# Date created: 27-07-2018
# TODO: should I import the entire module, or just the relevant functions?
from . import chemical, recipe, make, help | jordan-benjamin/buf | MIT |
# Author: Dominik Bauer
# Vision for Robotics Group, Automation and Control Institute (ACIN)
# TU Wien, Vienna
import torch
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
import numpy as np
import sys
sys.path.append("./3rdparty/DenseFusion")
sys.path.append("./3rdparty/DenseFusi... | dornik/verefine | MIT |
import os
from conans import ConanFile, tools
from conans.errors import ConanInvalidConfiguration
class CxxOptsConan(ConanFile):
name = "cxxopts"
homepage = "https://github.com/jarro2783/cxxopts"
url = "https://github.com/conan-io/conan-center-index"
description = "Lightweight C++ option parser librar... | dvirtz/conan-center-index | MIT |
import sqlalchemy as sa
meta = sa.MetaData()
comments = sa.Table(
'comments_comments', meta,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('content', sa.String, nullable=False),
)
comments_tree = sa.Table(
'comments_tree', meta,
sa.Column('id', sa.Integer, primary_key=True),
sa.Col... | vyacheslav-bezborodov/dvhb | MIT |
import zlib, marshal
def encrypt(src):
s = ""
for i in xrange(len(src)):
c = src[i]
t = ord(c)
m = i % 9
a = abs(m - 9) + 1
t = t + m * a
t = t % 256
s += chr(t)
print(s)
encryptstr = marshal.dumps(s)
print(encryptstr)
encryptstr = zlib.compress(encryptstr, 9)
return encryptstr
def decrypt(src):
... | jellyfishgh/swlog | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.