content stringlengths 5 1.05M |
|---|
class Item:
def __init__(self, name, tag, desc, intro):
self.name = name
self.tag = tag
self.desc = desc
self.intro = intro
def __str__(self):
return f"=> {self.name} - {self.desc}"
def getItem(self, player):
player.inventory.append(self)
def getIntro(self):
return self.intro
# so t... |
# pylint: skip-file
|
# Copyright 2020 Google LLC. 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 a... |
import logging
def get_logger(log_filename=None, module_name=__name__, level=logging.INFO):
# select handler
if log_filename is None:
handler = logging.StreamHandler()
elif type(log_filename) is str:
handler = logging.FileHandler(log_filename, 'w')
else:
raise ValueError("log_f... |
from view import View
from tkinter import Tk
class Controller:
def __init__(self, model):
self.model = model
self.view = View(self.model.graph.width(),
self.model.graph.height(),
self.model.graph_path)
def run(self):
self.view.draw_mode... |
#! /usr/bin/env python
# -*- Mode: Python -*-
# -*- coding: ascii -*-
"""
Dump layer name list
layer containing the mesh
"""
import lwsdk
__lwver__ = "11"
class HistoryData():
def __init__(self):
self.string = ''
self.select_contains = False
self.select_others = False
class DumpLayerN... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import os
import unittest
from unittest.mock import Mock, call, patch
from ci_workflow.ci_check_manifest_component import CiCh... |
from plugins.adversary.app.operation.operation import Step, OPVar, OPHost, OPRat, OPSoftware
from plugins.adversary.app.commands import *
from plugins.adversary.app.custom import *
class WebServerInstall(Step):
""" Description:
This step prepares the installation of a PHP webserver.
Requi... |
from django.apps import AppConfig
from django.db.models.signals import post_save, post_delete
from django.conf import settings
class SyncConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'sync'
def ready(self):
try:
from .signals import init_signals
... |
# -*- coding: utf-8 -*-
"""Launch small HTTP server for TimeoutTest test case
Should work with Python 2 and 3.
"""
import sys
import time
try:
from SimpleHTTPServer import SimpleHTTPRequestHandler as RequestHandler
except ImportError:
from http.server import CGIHTTPRequestHandler as RequestHandler
try:
... |
"""
PPO with tensorflow implementation
The goal of RL is to find an optimal behavior strategy for the agent to obtain
optimal rewards. The policy gradient methods target at modeling and optimizing
the policy directly. The policy loss is defined as
L = E [log pi (a|s)] * AF
where, 'L' is the policy loss, 'E' is the... |
#!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Licen... |
import math as m
import numpy as np
from matplotlib import pyplot as plt
from BDPoisson1D import dirichlet_non_linear_poisson_solver_amr
from BDFunction1D import Function
from BDFunction1D.Functional import Functional
class TestFunction(Function):
"""
Some known differentiable function
"""
def evalu... |
#!/usr/bin/env python
import glob
for name in glob.glob('dir/*'):
print name
|
"""
Image conversion functions.
"""
# Copyright (c) 2020 Ben Zimmer. All rights reserved.
from typing import Tuple
import numpy as np
from PIL import Image
# Some functions for colorizing single channel black and white image (PIL "L" mode)
# or the alpha channels of text_scala output.
# ~~~~ function from text_... |
import pandas as pd
def generate_train(playlists):
# define category range
cates = {'cat1': (10, 50), 'cat2': (10, 78), 'cat3': (10, 100), 'cat4': (40, 100), 'cat5': (40, 100),
'cat6': (40, 100),'cat7': (101, 250), 'cat8': (101, 250), 'cat9': (150, 250), 'cat10': (150, 250)}
cat_pids = {}
... |
'''
Copyright (C) 2018 PyElo.
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, sublice... |
# -*- coding: utf-8 -*-
import unittest
from gilded_rose import Item, GildedRose
class GildedRoseTest(unittest.TestCase):
def test_foo_quality_never_below_zero(self):
items = [Item("foo", 0, 0)]
gilded_rose = GildedRose(items)
gilded_rose.update_quality()
self.assertEqual("foo", it... |
#!/usr/bin/env python
import gpt_2_simple as gpt2
import sys
if len(sys.argv) > 1:
prompt = sys.argv[1]
else:
prompt = "prompt: So, what's new around here?"
print(prompt)
sys.exit(1)
sess = gpt2.start_tf_sess()
gpt2.load_gpt2(sess)
single_text = gpt2.generate(
sess,
return_as_list=True,
... |
# Please refrain from specifying a micro version if possible.
# --------------------------------------------------------------------------- #
VERSION = (1, 1)
# --------------------------------------------------------------------------- #
def _get_version(vt): ... |
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# ... |
# Make sure to have CoppeliaSim running, with followig scene loaded:
#
# scenes/messaging/ikMovementViaRemoteApi.ttt
#
# Do not launch simulation, then run this script
from zmqRemoteApi import RemoteAPIClient
print('Program started')
client = RemoteAPIClient()
sim = client.getObject('sim')
tipHandle = sim.getObject... |
import attr
from .document import Document
from .has_settings import HasSettings
from .templated import Templated
import exam_gen.util.logging as logging
log = logging.new(__name__, level="DEBUG")
@attr.s
class GradeData():
points = attr.ib(default=None)
children = attr.ib(factory=dict)
comment = attr.... |
import sys
def op(arg1, arg2):
if (len(sys.argv) != 3):
raise Exception("InputError: only numbers\n\n")
if (arg1.isdigit() and arg2.isdigit()):
arg1 = int(arg1)
arg2 = int(arg2)
else:
raise Exception("InputError: only numbers\n\n")
print("Sum: ", arg1 + arg2)
print("Difference: ", arg1 - arg2)
print("Pr... |
def xprop(layout, data, prop, enabled=True, **kwargs):
attrs = getattr(data.bl_rna, prop)[1]
name = attrs.get('name', prop)
lay = layout.row().split(percentage=0.33)
lay.label(name + ':')
lay = lay.row(align=True)
lay_l = lay.row(align=True)
lay_r = lay
if not enabled:
lay = lay.... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='pyledsign',
version='1.01',
description='pyledsign - control led signs from python',
author='Kerry Schwab',
author_email='sales@brightsigns.com',
url='http://www.python.org/tbd/',
packages=['pyledsign'],
)
|
from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect, render
from .models import Link
def redirect_(request, key):
try:
link = Link.find_by_key(key.lower())
except Link.DoesNotExist:
raise Http404("Link does not exist.")
return redirect(... |
# Generated by Django 2.1 on 2018-08-08 04:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(... |
"""Tests the DNC class implementation."""
import sonnet as snt
import tensorflow as tf
import unittest
from numpy.testing import assert_array_equal
from .. dnc import dnc
def suite():
"""Create testing suite for all tests in this module."""
suite = unittest.TestSuite()
suite.addTest(DNCTest('test_const... |
# Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
# Author : henrytine
# Date : 2020-08-19
#####################################################################################################
#
# Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tr... |
import pymysql
import urllib.request
from bs4 import BeautifulSoup
import requests
def connectDatabase():
"""Create database connection"""
global db
db = pymysql.connect(host='localhost', user='root', password='',
db='vg_dapi', cursorclass=pymysql.cursors.DictCursor,charset='utf8')... |
from mycroft import MycroftSkill, intent_file_handler
class RoomBooking(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('booking.room.intent')
def handle_booking_room(self, message):
amount = message.data.get('amount')
building = message.data.ge... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class DialogEvent:
def __init__(self, bubble: bool = False, name: str = "", value: object = None):
self.bubble = bubble
self.name = name
self.value: object = value
|
import traceback
from twisted.internet import reactor
def stack():
print("The Python Stack.")
traceback.print_stack()
reactor.callWhenRunning(stack)
reactor.run()
|
import os
import sys
import codecs
import difflib
sys.path.insert(0, os.path.dirname(__file__))
from logger import log
def restore_file_case(text_file, orig_file, debug=False):
text_io = codecs.open(text_file, 'r', encoding='utf8')
orig_io = codecs.open(orig_file, 'r', encoding='utf8')
for line in text... |
"""Test for our weighted graph."""
# {'A': {'B': 7, 'C': 9}, 'B': {'D': 2, 'E': 4}, 'C': {'F':6}}
"""Test our graph implementation."""
import pytest
from weighted_graph import Weighted
@pytest.fixture
def new_weighted_graph():
"""Graph for testing."""
from weighted_graph import Weighted
empty_graph = Weig... |
import os.path
from unittest import TestCase
from pkg_resources import require, DistributionNotFound
from subprocess import call
from sys import platform, executable, exit
from src.info import AppInfo
try:
REQUIRED = open(os.path.join(AppInfo.root_dir, "requirements.txt")).read()
except Exception as e:
raise E... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
#!/usr/bin/env python
import discord
import configparser
from libs import raid_combat
# Setup the config and Discord client
config = configparser.RawConfigParser()
config.read('config.conf')
client = discord.Client()
# create the dict of combat managers for each server
combat_managers = {}
@client.event
async def ... |
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
apikey = 'mykey'
secretkey = 'mysecret'
Driver = get_driver(Provider.AURORACOMPUTE)
conn = Driver(key=apikey, secret=secretkey)
|
# Copyright 2019 Atalaya Tech, 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 in writing, ... |
# app/chats/forms.py
|
from django.views.generic import UpdateView, ListView
import pyperclip
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.http.response import Http404
from django.shortcuts import render
from .models import Image, Categories, Location
# modal window settings
class Moda... |
from os import environ
def assert_in(file, files_to_check):
if file not in files_to_check:
raise AssertionError("{} does not exist in the list".format(str(file)))
return True
def assert_in_env(check_list: list):
for item in check_list:
assert_in(item, environ.keys())
return True
|
from django.contrib import messages
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from misago.admin.views import generic
from misago.users.forms.admin import RankForm
from misago.users.models import Rank
class RankAdmin(generic.AdminBase... |
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
#!/usr/bin/python
"""
This work targets for emulating fog computing infrastructure and fog service and network evaluation.
Original author Tzu-Chiao Yeh (@tz70s), 2017@National Taiwan University, Dependable Distributed System and Network Lab.
Checkout the License for using, modifying and publishing.
"""
import docker... |
# Generated by Django 3.2.4 on 2021-09-09 13:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("accounts", "0005_add_field_last_modified_20210621_1058"),
]
operations = [
migrations.AddField(
model_name="govdepartment",
... |
# -*- coding: utf-8 -*-
"""Shared utility functions for interacting with the data model."""
import logging
logger = logging.getLogger(__name__)
import os
from binascii import hexlify
def generate_random_digest(num_bytes=28, urandom=None, to_hex=None):
"""Generates a random hash and returns the hex digest as a u... |
#CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户端HTML页面的接口
'''
开启apache: sudo apachectl start
重启apache: sudo apachectl restart
关闭apache: sudo apachectl stop
'''
#http://localhost/cgi-bin/hello.py
#/private/etc/apache2/httpd.conf apache服务器的配置路径
#/资源库/WebServer/Documents apache服务器访问路径
#/资... |
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
idx = len(nums1) - 1
hi1, hi2 = m -... |
"""Manages plotting, provides a single interface
for different plots with different backends."""
from __future__ import print_function, absolute_import
import os
import sys
import importlib
import traceback
import numpy
from matplotlib.colors import LinearSegmentedColormap
from vcs.colors import matplotlib2vcs
import ... |
# -*- coding: utf-8 -*-
"""
@author: Aditya Intwala
Copyright (C) 2016, Aditya Intwala.
Licensed under the Apache License 2.0. See LICENSE file in the project root for full license information.
"""
import cv2
from Core.Math.Point2 import Point2
class Eraser():
@staticmethod
def ErasePixel(img, pixel):
... |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-25 15:27
from __future__ import unicode_literals
import calaccess_raw.annotations
import calaccess_raw.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('calaccess_raw', '0007_auto_20160831_0132'... |
import numpy as np
import matplotlib.pyplot as plt
import struct
import os, sys
import re
import copy
class Matrix:
"""
Class to Read and Hangle Matrix files
"""
def __init__(self,Path): # Give the Path of the folder containing all the mtrx files
# Read PATH and open file
self.Path = Pa... |
import os
import sys
import logging
import json
import typing
import collections
from ConfigSpace.configuration_space import ConfigurationSpace, Configuration
from ConfigSpace.hyperparameters import FloatHyperparameter, IntegerHyperparameter
__author__ = "Marius Lindauer"
__copyright__ = "Copyright 2016, ML4AAD"
__li... |
#!/usr/bin/env python3
# This is run by the "run-tests" script.
import unittest
import signal
import socket
class TestTimeout(unittest.TestCase):
def test_timeout(self):
port = 12346
s = socket.socket()
s.connect(("0.0.0.0", port))
# Assumes the server has --timeout 1
signal... |
import numpy as np
matrizquadrada = int(input("Definir o tamanho Matriz: "))
Geracoes = int(input("Definir quantas geracoes: "))
# Considerando 1 como celula viva e 0 como celula morta.
# Rodar o jogo no terminal
# A cada geração irá aplicar as condições do jogo, criando assim uma nova matriz atualizada.
def atual... |
import itertools
def reduce_undefined(obj):
if isinstance(obj, dict):
r = {}
for k, v in obj.items():
if v == UNDEFINED:
pass
else:
r[k] = reduce_undefined(v)
return r
elif isinstance(obj, (tuple, list)):
r = []
for ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import abc
import time
import datetime
import importlib
from pathlib import Path
from typing import Type, Iterable
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import pandas as pd
from tqdm import tqdm
from loguru impo... |
#!/usr/bin/env python
## This file comes from Jennifer Fourquier's excellent ghost-tree project
## Some modifications by Lela Andrews to fit within akutils framework
##
## Ghost-tree is provided under BSD license
##
## Copyright (c) 2015--, ghost-tree development team.
## All rights reserved.
##
"""
This file can be do... |
from distutils import log
from setuptools import setup
try:
from setuptools.command import egg_info
egg_info.write_toplevel_names
except (ImportError, AttributeError):
pass
else:
def _top_level_package(name):
return name.split('.', 1)[0]
def _hacked_write_toplevel_names(cmd, basename, file... |
import sys
from collections import OrderedDict
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as functional
from ptsemseg.models._util import try_index
from modules import IdentityResidualBlock, ABN, GlobalAvgPool2d
from modules.bn import ABN, InPlaceABN, InPlaceABNSync
... |
import logging
from flask import Flask
from flask.logging import default_handler
from flask_logging_decorator import trace
app = Flask(__name__)
app.logger.setLevel(logging.WARN)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
default_handler.setFormatter(formatter)
@app.rout... |
import logging
import os
import torch
from transformers import BertTokenizer
from .data_cls import BertDataBunch
from .learner_cls import BertLearner
from .modeling import (
BertForMultiLabelSequenceClassification,
XLNetForMultiLabelSequenceClassification,
RobertaForMultiLabelSequenceClassification,
Dis... |
"""
handles logging for:
- auth
- contact
- msg
- label
- report
- att
modules
"""
import csv
from datetime import datetime
import os
import shutil
from config import config
log_dir = config.data["log"]["log_dir"]
logfiles = config.data["log"]["logfiles"]
def get_logpath(logtype):
filen... |
import io
import json
import unittest
from datetime import datetime
from unittest.mock import Mock
import boto3
from botocore.response import StreamingBody
from botocore.stub import Stubber, ANY
from redis import StrictRedis
from s3_log_shipper.parsers import ParserManager, Parser
from s3_log_shipper.shipper import R... |
from pyramid.config import Configurator
from pyramid.static import static_view
import kinto.core
def includeme(config):
config.scan("kinto.tests.core.testapp.views")
# Add an example route with trailing slash (here to serve static files).
# This is only used to test 404 redirection in ``test_views_errors... |
class BaseFilter:
"""
This is the reference implementation for all filters/hooks.
Just passes the data as-is without changing it.
"""
def register(self, kernel, shell):
self.kernel = kernel
self.shell = shell
shell.events.register('post_run_cell', self.post_run_cell)
... |
"""
常见的颜色名称
"""
color_dict={
"almond":(239,222,205),
"amaranth":(229,43,80),
"amazon":(59,122,87),
"amber":(255,191,0),
"sae":(255,126,0),
"amethyst":(153,102,204),
"ao":(0,128,0),
"apricot":(251,206,177),
"aqua":(0,255,255),
"aquamarine":(127,255,212),
"arsenic":(59,68,75),
"artichoke":(143,151,121),
"asparagus":(135,... |
import argparse, operator
from collections import defaultdict
from gpToDict import gpToDict, makeEntities
from utility import readFromFile
def run(target):
fileType = target.split('.')[-1]
if fileType == 'data':
entities = makeEntities(gpToDict(target)[0])
elif fileType == 'json':
entities ... |
from modules.discriminator import MultiScaleDiscriminator, RandomWindowDiscriminator
from modules.generator import Aligner, Decoder, Encoder
from modules.mel import MelSpectrogram
|
from django_roa.remoteauth.models import User
from django.contrib.auth.backends import ModelBackend
class RemoteUserModelBackend(ModelBackend):
"""
Authenticates against django_roa.remoteauth.models.RemoteUser.
"""
def authenticate(self, username=None, password=None, **kwargs):
try:
... |
"""
Mountain Car environment adapted from OpenAI gym [1].
* default reward is 0 (instead of -1)
* reward in goal state is 1 (instead of 0)
* also implemented as a generative model (in addition to an online model)
* render function follows the rlberry rendering interface.
[1] https://github.com/openai/gym/blob/m... |
from django.conf import settings
from django.conf.urls import patterns, url, include
from views import login, logout, connect
urlpatterns = patterns('',
url(r'^login/$', login,
{'template_name': 'registration/login.html'}, name='fb_login'),
url... |
from django.contrib import admin
from .models import Category, Product, LaptopsCategory, SmartPhonesCategory
from django import forms
from django.forms import ValidationError
from PIL import Image
# Настройка изображения
class AdminForm(forms.ModelForm):
MIN_RESOLUTION = (400, 400)
def __init__(self, *args, ... |
'''
Created on Nov 13, 2017
@author: khoi.ngo
'''
# /usr/bin/env python3.6
import sys
import asyncio
import json
import os.path
import logging.handlers
# import shutil
import time
import random
from indy import signus, wallet, pool, ledger
from indy.error import IndyError
import abc
sys.path.append(os.path.join(os.pat... |
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... |
from os import read
import sys
import argparse
import numpy as np
import shlex
import subprocess
import numpy as np
from operator import itemgetter
def init_chrom_list():
chrom_list = []
for i in range(1, 23):
chrom_list.append(str(i))
chrom_list.append('X')
chrom_list.append('Y')
return(ch... |
from itertools import takewhile
import os
import setuptools
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
long_description = str.join('', takewhile(lambda l: not l.startswith('Installation'), f.readlines()[15:]))
setuptools.setup(
name = 'OverloadingFixed',
version = '1.11',
... |
# -*- coding: utf-8 -*-
# Copyright 2014 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import os
import unittest
from splinter import Browser
from .base import BaseBrowserTests
from .fake_webapp import app, EXAMPLE_APP
fro... |
import pandas as pd
from ggplot import *
import sys
def data_clean():
dat = pd.read_csv(sys.argv[1], header=False)
dat1 = dat
dat = dat.drop(['q1','lambda1','mu1'], axis=1)
dat1 = dat1.drop(['q0','lambda0','mu0'], axis=1)
dat['Parity'] = 'Viviparity'
dat1['Parity'] = 'Oviparity'
dat.columns = ['Lambda','Mu','Q'... |
#python program to reverse the array
array = [10,20,30,40,50];
print("Array in reverse order: ");
#Loop through the array in reverse order
for i in range(len(array)-1, -1, -1):
print(array[i])
|
# pylint: disable=missing-function-docstring, missing-module-docstring/
def ones():
print(22)
from numpy import ones
g = ones(6)
print(g)
|
#!/usr/bin/env python
import sys, os
import pprint
""" Hardlink UCI History oral histories files for loading into Nuxeo """
raw_dir = u"/apps/content/raw_files/UCI/UCIHistory/OralHistories/ContentFiles/"
new_path_dir = u"/apps/content/new_path/UCI/UCIHistory/OralHistories/"
pp = pprint.PrettyPrinter()
def main(argv=... |
import argparse
import yaml
import logging
import numpy as np
import glob
from astropy.coordinates import SkyCoord, Angle
from astropy import units as u
from astropy.convolution import Tophat2DKernel, Gaussian2DKernel
from os import path
from copy import deepcopy
from fermiAnalysis.batchfarm import utils
from simCRprop... |
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 us... |
from toykoin.daemon.messages import _verify_headers, add_headers
import pytest
def test_headers():
_verify_headers(add_headers("version", b""))
_verify_headers(add_headers("version", b"\x01"))
_verify_headers(add_headers("a" * 12, b"\x01"))
with pytest.raises(Exception, match="Wrong payload length"):... |
from django.conf.urls import patterns, include, url
from django.views.generic.base import TemplateView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r... |
import os
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
app.secret_key = app.config.get('SECRET_KEY')
db = SQLAlchemy(app)
from . import routes |
import pytest
from dredis.commands import REDIS_COMMANDS
# got the list from a real redis server using the following code:
"""
import pprint
import redis
r = redis.StrictRedis()
commands = r.execute_command('COMMAND')
pprint.pprint({c[0]: int(c[1]) for c in commands})
"""
EXPECTED_ARITY = {
'append': 3,
'aski... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'threading_design.ui'
#
# Created: Thu Aug 6 13:47:18 2015
# by: PyQt4 UI code generator 4.10.4
from PyQt5 import QtCore, QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt5.QtWidgets impor... |
# global
import torch
from typing import Union, Optional, Tuple, List
def argsort(x: torch.Tensor,
axis: int = -1,
descending: bool = False,
stable: bool = True)\
-> torch.Tensor:
return torch.argsort(x, dim=axis, descending=descending)
|
#!/usr/bin/env python
import os, sys
temp=list();
header=1;
sys.path.append('../../Libs/Python')
from BiochemPy import Reactions, Compounds, InChIs
CompoundsHelper = Compounds()
Compounds_Dict = CompoundsHelper.loadCompounds()
Structures_Dict = CompoundsHelper.loadStructures(["InChI"],["ModelSEED"])
diff_file = open... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-10 19:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GreenSh... |
import shutil
import os
from dataclasses import dataclass
from typing import Generator
import pytest
import fabsite
from test import path
@dataclass
class Pages:
blog_path: str
undated_path: str
dated_path: str
normal_post_path: str
md_post_path: str
no_md_post_path: str
@pytest.fixture
de... |
"""
Configuration utils.
Author: Henrik Thostrup Jensen <htj@ndgf.org>
Copyright: Nordic Data Grid Facility (2009, 2010)
"""
import ConfigParser
import re
from sgas.ext.python import ConfigDict
# configuration defaults
DEFAULT_AUTHZ_FILE = '/etc/sgas.authz'
DEFAULT_HOSTNAME_CHECK_DEPTH = '2'
# serve... |
# -*- coding: utf-8 -*-
'''utility module for package rankorder.'''
import numpy as np
def rankdata(a, method):
'''assigns ranks to values dealing appropriately with ties.
ranks start at zero and increase with increasing value.
the value np.nan is assigned the highest rank.
Parameters... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# imaparchiver/__main__.py
#
# imaparchiver package start
#
# This file is part of imaparchiver.
# See the LICENSE file for the software license.
# (C) Copyright 2015-2019, Oliver Maurhart, dyle71@gmail.com
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.