content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
#author feardonn@ie.ibm.com
"""Castor API sample program.
/*
* 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 th... | python |
"""Create vpn_payload table
Revision ID: 9dd4e48235e3
Revises: e5840df9a88a
Create Date: 2017-05-19 19:59:55.582629
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9dd4e48235e3'
down_revision = 'e5840df9a88a'
branch_labels = None
depends_on = None
def upgrad... | python |
"""
module for downloading file
"""
import re
from django.http import StreamingHttpResponse, FileResponse
from utils.params import ParamType
from utils.file import file_iterator
from file.models import VideoHelper
def video(package):
"""method for download video
"""
params = package.get('params')
vid... | python |
# -*- coding: utf-8 -*-
"""
Created on 29/07/2020
Author : Carlos Eduardo Barbosa
Checking average correlation between parameters in NGC 3311.
"""
from __future__ import print_function, division
import os
import itertools
import numpy as np
from astropy.table import Table
from scipy.stats.distributions import chi2... | python |
import common.ibc.handle
import common.ibc.processor
from luna2.config_luna2 import localconfig
from luna2 import constants as co
from settings_csv import LUNA2_LCD_NODE
def process_txs(wallet_address, elems, exporter):
for elem in elems:
process_tx(wallet_address, elem, exporter)
def process_tx(wallet... | python |
from .session import Session
from .requests import *
class Client(object):
def __init__(self):
self.s = Session()
self.email = None
self.password = None
self.hash = None
self.computers = None
self.computer = None
self.userid = None
self.computerid = None
self.token = None
self.client_token = N... | python |
# -*- coding:utf-8 -*-
import struct,os,fnmatch,re,zlib
#遍历文件夹,返回文件列表
def walk(adr):
mylist=[]
for root,dirs,files in os.walk(adr):
for name in files:
adrlist=os.path.join(root, name)
mylist.append(adrlist)
return mylist
#将4字节byte转换成整数
def byte2int(byte):
long_tuple=st... | python |
from model.address import Address
import string
import random
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits+ string.punctuation + " "*10
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
def random_number(prefix, maxlen):
symbols... | python |
print('Calcule o seu amumento anual!')
salario = float(input('Qual o seu salário? €'))
if salario > 1250:
aumento = salario + (salario * 10) / 100
print('O seu salario é de {:.2f}€ terá um aumento de 10% e passará para {:.2f}€'.format(salario, aumento))
else:
aumento = salario + (salario * 15) / 100
pri... | python |
import os
import numpy as np
from to_nwb.neuroscope import get_lfp_sampling_rate, get_channel_groups
from pynwb.ecephys import ElectricalSeries, LFP
from pynwb import NWBFile, NWBHDF5IO, TimeSeries
from dateutil.parser import parse as parse_date
from pytz import timezone
"""
Time simply increments by 1
"""
session_... | python |
"""
byceps.services.shop.order.sequence_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from typing import Optional
from sqlalchemy.exc import IntegrityError
from ....database... | python |
# Generated by Django 3.1.5 on 2021-01-15 22:21
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("clubs", "0070_clubvisit_ip"),
]
operations = [
migrations.AddField(
model_name="badge",
... | python |
from typing import Protocol, Optional, runtime_checkable
@runtime_checkable
class Formatter(Protocol):
def __call__(self, x: float, pos: Optional[float]) -> str:
... # pragma: no cover
def default_formatter(x: float, pos: Optional[float]) -> str:
return str(x)
def thousands_formatter(x: float, po... | python |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='index'),
path('profile/<id>/',views.profile, name='profile'),
path('my_profile/',views.my_profile, name='my_profile'),
path('create_po... | python |
from charts.bar import HorizontalBarChart, VerticalBarChart
from charts.line import LineChart
from charts.pie import PieChart
from charts.scatter import ScatterplotChart
from charts.stackedbar import StackedVerticalBarChart, StackedHorizontalBarChart
CHART_TYPES = (
VerticalBarChart,
HorizontalBarChart,
Li... | python |
# Generated by Django 2.2.1 on 2019-05-26 20:38
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('index', '0002_auto_20190524_0033'),
]
operations = [
migrations.CreateModel(
... | python |
import argparse
import sys
p = argparse.ArgumentParser(
prog='ampush',
description="Active Directory Automount Pusher, v0.32",
)
p.add_argument('-V', '--version',
action='version',
version='ampush 0.32, 18-Sep-2017')
p.add_argument('-d', '--debug',
dest='debug',
... | python |
#!/usr/bin/env python
from __future__ import division
import tweepy, time, pprint, re
from flask import Flask, render_template, session, redirect, url_for, request
from datetime import datetime
import collections
#Create the application
app = Flask(__name__)
# TwitListed's API key and secret
# (copy-paste into code b... | python |
"""
An example of a 64-bit *echo* client.
Example of a client that can be executed by a 64-bit Python interpreter that sends
requests to the corresponding :mod:`.echo32` module which is executed by a
32-bit Python interpreter.
:class:`~.echo32.Echo32` is the 32-bit server class and :class:`~.echo64.Echo64` is
the 64-... | python |
#!/usr/bin/python3
#coding:utf8
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def cv2ImgAddText(image, text, x, y, textColor=(0, 255, 0), textSize=20):
image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(image)
fontText = ImageFont.truetype("... | python |
#Synchronize processes with managers – Chapter 3: Process Based Parallelism
import multiprocessing
def worker(dictionary, key, item):
dictionary[key] = item
if __name__ == '__main__':
mgr = multiprocessing.Manager()
dictionary = mgr.dict()
jobs = [ multiprocessing.Process\
(targ... | python |
import torch
import torch.nn.functional as F
import numpy as np
from itertools import product
import matplotlib.pyplot as plt
def compute_accuracy(model, data_loader, device):
model.eval()
with torch.no_grad():
correct_pred, num_examples = 0, 0
for i, (features, targets) in enumerate(data_load... | python |
import maya.cmds as mc
import glTools.utils.blendShape
import glTools.utils.stringUtils
def createFromSelection(origin='local',deformOrder=None,prefix=None):
'''
Create basic blendShape from selection.
@param origin: Create a local or world space belndShape deformer. Accepted values - "local" or "world".
@type or... | python |
import os
import time
import json
import logging
from crizzle import patterns
from crizzle.envs.base import Feed as BaseFeed
from crizzle.services.binance import INTERVALS
logger = logging.getLogger(__name__)
class Feed(BaseFeed):
def __init__(self, symbols: list = None, intervals: list = None):
super(F... | python |
#!/usr/bin/env python3
import sys
import csv
import pprint
print(sys.argv[1])
data = list(csv.reader(open(sys.argv[1],'r')))
bases = [x for x in data if x[0] == 'csr_base']
regs = [x for x in data if x[0] == 'csr_register']
mem_map = []
for _, name, loc, size, rw in regs:
mem_map.append((int(loc, 16), int(size)... | python |
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
Ed25519PublicKey, Ed25519PrivateKey
)
from authlib.jose.rfc7515 import JWSAlgorithm, JsonWebSignature
from .okp_key import OKPKey
class EdDSAAlgorithm(JWSAlgorithm):
name = 'EdDSA'
descript... | python |
import math
from .EmbFunctions import *
from .EmbMatrix import EmbMatrix
class Transcoder:
def __init__(self, settings=None):
if settings is None:
settings = {}
self.max_stitch = settings.get("max_stitch", float('inf'))
self.max_jump = settings.get("max_jump", float... | python |
import numpy as np
from .points import get_fractions, interpolate_along_axis
def prepare(start: np.ndarray, stop: np.ndarray):
# handling a possible flip
diff = np.linalg.norm(start[[0, -1]] - stop[[0, -1]], axis=1).sum()
rev_diff = np.linalg.norm(start[[-1, 0]] - stop[[0, -1]], axis=1).sum()
if rev_d... | python |
# Copyright 2008-2018 Univa Corporation
#
# 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... | python |
"""
Test of reading and plotting the CUSP coastline.
Data source:
shoreline.noaa.gov/data/datasheets/cusp.html
Spatial Reference: Geographic coordinate system (decimal degrees);
Horizontal Datum – North American Datum of 1983 (NAD83)
Tidal Datum: Where applicable, CUSP will reference a mean-high water shoreline
base... | python |
#!/usr/bin/env python
#author: wowdd1
#mail: developergf@gmail.com
#data: 2015.01.03
from spider import *
sys.path.append("..")
from utils import Utils
class TorontoSpider(Spider):
def __init__(self):
Spider.__init__(self)
self.school = "toronto"
self.subject = "computer-science"
de... | python |
from django.apps import apps
from guardian.shortcuts import get_objects_for_user
from api.addons.views import AddonSettingsMixin
from api.actions.views import get_actions_queryset
from api.actions.serializers import ActionSerializer
from api.base import permissions as base_permissions
from api.base.exceptions import ... | python |
import numpy as np
import os
import sys
import math
import time
import random
import datetime
import pickle
from keras.utils.generic_utils import Progbar
from PIL import Image
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import keras
from keras import backend as K
from keras.datasets import cifar1... | python |
from __future__ import annotations
import random
from typing import List
import numpy as np
import paddle
from paddle import nn
from paddle.fluid.framework import Parameter
def freeze_module(module: nn.Layer):
"""Freeze all parameters in the moudle"""
parameters: List[Parameter] = module.parameters()
fo... | python |
'''
wrapper for evaluating Model(ABC particle)
'''
import env
import sys
from abcee import model_ABCparticle
#restart = int(sys.argv[1])
#if restart == 0:
# ABC run name
abcrun = sys.argv[1]
print 'Run ', abcrun
# iterations number
Niter = int(sys.argv[2])
print 'N_iterations = ', Niter
# plus some hardcoded k... | python |
import os
import sqlite3 as sqlite
from openpyxl import Workbook
from openpyxl.styles import Font
import datetime
import tkinter.filedialog
import tkinter.messagebox
import gc
font = Font(color="00FF3300")
runningFile = ""
# 写入Excel头
def sqlite_to_workbook_with_head(i, cur, table, select_sql, workbook, errorPut):
... | python |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | python |
def min_max_scaler(value, min_value, max_value):
'''
takes value, calculated max value (pulled from dictionary
of maxes) and min value; and scales using min-max scaler method.
'''
try:
return (value - min_value)/(max_value - min_value)
except ZeroDivisionError:
return 0
| python |
from django.apps import AppConfig
class SitemapConfig(AppConfig):
"""
This is the basic configuration for the sitemap app
"""
name = "sitemap"
| python |
from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
self.cars_list = []
self.speed = STARTING_MOVE_DISTANCE
def create_car(self):
random_choice = ... | python |
from ..core import BlockParser
def _parse_epsilon(line, lines):
"""Parse Energy [eV] Re_eps_xx Im_eps_xx Re_eps_zz Im_eps_zz"""
split_line = line.split()
energy = float(split_line[0])
re_eps_xx = float(split_line[1])
im_eps_xx = float(split_line[2])
re_eps_zz = float(split_line[3... | python |
# Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | python |
# Copyright 2020 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
ADAMSLegacyDict = {'PLACENAME': 38653, 'GISACRES': 0, 'CONAME': 38657, 'SUFFIX': 0, 'STREETTYPE': 22335, 'TAXPARCELID': 38657, 'PARCELID': 38657, 'ZIPCODE': 29356, 'PARCELSRC': 38657, 'PARCELFIPS': 38657, 'LOADDATE': 38657, 'PREFIX': 5999, 'AUXCLASS': 5245, 'NETPRPTA': 0, 'SCHOOLDISTNO': 38653, 'UNITID': 697, 'LNDVALUE... | python |
import torch
import numpy as np
def find_distance(X_n, X_o):
"""
:param X_n: tensor [[x_0, y_0, t_0], ..., [x_j, y_j, t_j]], containing all manipulatable nodes for a given leg
:param X_o: tensor [[x_s, y_s, t_s], ..., [x_e, y_e, t_e]] points of sim contact
:return d_s: distance vector to first object,... | python |
from pal.writer.access_mechanism.access_mechanism \
import AccessMechanismWriter
from pal.logger import logger
class RustLibpalAccessMechanismWriter(AccessMechanismWriter):
def declare_access_mechanism_dependencies(self, outfile, register,
access_mechanism):
pass... | python |
import sys
import os
import subprocess
from shutil import copyfile, rmtree
def find_and_split_inputs(input_env_data, output_dir, number_of_inputs):
## Generate the environment file (by splitting inputs)
## Find the input file name
input_env_lines = input_env_data.split('\n')
input_vars = [line.split('... | python |
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
import dgl
import torch
import numpy as np
import dgl.function as fn
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import obspy
import ... | python |
import random
with open('num.txt', 'w') as arq:
for i in range(1000000):
arq.write(str(random.randint(0, 10)) + '\n')
| python |
from flask_sqlalchemy import SQLAlchemy
from database.connection_profile import ConnectionProfile
from __init__ import app
import configuration
database_engine = SQLAlchemy(app)
def connect_if_required():
"""
Checks if the server should connect to a database and optionally does so.
This function automa... | python |
from .idol import Idol
from .skills import Skill, LeadSkill
from .enums import enum, attributes
from .errors import CategoryNotFound
class Card:
"""
Represents a Card and its data
Attributes
----------
card_id : int
The card's card id
album_id : int
The card's album id
ty... | python |
def foo(x):
def bar(z):
return z + x
return bar
f = foo(9)
g = foo(10)
print(f(2))
print(g(2))
| python |
#!/usr/bin/env python
'''
FILE: compile.py
Author: Chris Piech with additions from Nick Troccoli
----------------
Template compiler that compiles all .html template files in the TEMPLATE_DIR
directory below (excluding .ptl files, which are partial templates), and outputs
with the same filenames to the OUTPUT_DIR direc... | python |
import matplotlib.pyplot as plt
import numpy as np
import math
values = [1,5,8,9,7,13,6,1,8]
fig = plt.figure(facecolor="skyblue")
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], xlabel='keys', ylabel='values')
x = np.arange(0, math.pi * 2.5, 0.05)
y = np.sin(x) * 5 + 5
ax.grid()
ax.plot(values, color='red', marker='o')... | python |
import numpy as np
from collections import OrderedDict
import os
import glob
import cv2
import pandas as pd
import torch.utils.data as data
import torchvision.transforms as transforms
rng = np.random.RandomState(2020)
def np_load_frame(filename, resize_height, resize_width):
"""
Load image path and convert i... | python |
# Copyright (c) 2021, PublicSpaces and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
import spoelkeuken.utils
class ScanTool(Document):
def before_save(self):
print("On before save ScanTool")
# self.score_open = spoelkeuken.utils.calc_... | python |
# Edgar Barrera / Github: https://github.com/EdgarCastillo101/EdgarCastillo101
# Copyright (c) 2021 Edgar Barrera
# This program is an example for sequential search
def sequentialSearch(target, List):
'''This function returns the position of the target if found else returns -1'''
position = 0
global itera... | python |
import ctypes
from math import sqrt
from operator import itemgetter
def _norm_tau(x, R):
return sqrt(productRS_c(x, x, R.values()))
def _rank_tau(r, s):
L = tuple(range(0, len(r)))
S = [None]*len(r)
for i, item in enumerate(S):
S[i] = (L[i], r[i], s[i])
S = sorted(S, key=itemgetter(1, 2)... | python |
#!/usr/bin/env python
"""
Woob main Python wrapper
This file is a wrapper around Woob, which is spawned by Kresus backend and
prints fetched data as a JSON export on stdout, so that it could be imported
easily in Kresus' NodeJS backend.
..note:: Useful environment variables are
- ``WOOB_DIR`` to specify the path... | python |
import json
import sys
import os
from flask import request, Response
skyenv = os.environ.get('SKYENV', '/home/skyenv/')
sys.path.append(skyenv)
from skyScanner.searchingEngine import app
from skyScanner.parsers.ProxyParser import ProxyParser
from skyScanner.parsers.UserAgentParser import UserAgentParser
from skyScan... | python |
def add_native_methods(clazz):
def getVMTemporaryDirectory____():
raise NotImplementedError()
clazz.getVMTemporaryDirectory____ = staticmethod(getVMTemporaryDirectory____)
| python |
# Copyright 2021, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | python |
import sys
n, k, s = map(int, sys.stdin.readline().split())
def main():
m = 10 ** 9
a = [None] * n
for i in range(k):
a[i] = s
for i in range(k, n):
if s < m:
a[i] = m
else:
a[i] = 1
return a
if __name__ == '__main__':
ans = mai... | python |
# Copyright 2002-2011 Nick Mathewson. See LICENSE for licensing information.
"""mixminion.TLSConnection
Generic functions for wrapping bidirectional asynchronous TLS connections.
"""
#XXXX implement renegotiate
import sys
import time
import mixminion._minionlib as _ml
from mixminion.Common import LOG, stringCont... | python |
# ========================================================================================
# The code below has been adapted and tailored for this project.
# The original version can be found at: https://github.com/ChrisRimondi/VulntoES
# =================================================================================... | python |
from prime.bot.command import Command
from prime.bot.decorators import arg, reply_with_exception
from prime.bot.exceptions import InvalidEntity
from prime.bot.constants import ADMIN_GROUP
usermod = Command.create(
'usermod',
description='Adds/Removes user(s) to/from group.'
)
@usermod.register
@arg('-g', '--g... | python |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x06\x52\
\x3c\
\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\
\x30\x22\x20\x... | python |
'''
Created on 18 Jan 2013
@author: Kieran Finn
'''
import time
beginning=time.time()
import urllib2
import sys
import json
from functions import *
import time
import pickle
from math import pi
from scipy.integrate import quad
import numpy as np
from collections import defaultdict
import os
in_fnam... | python |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views.generic.detail import DetailView
from django.views.generic.edit impor... | python |
#!/usr/bin/env python
#--------Include modules---------------
from copy import copy
import rospy
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import PointStamped
import tf
from numpy import array,vstack,delete
from function... | python |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Siklu.EH.get_inventory
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------... | python |
import pygame
from .animatable import Animatable
from .shared_objects import SharedObjects
from . import constants as c
class TextField(Animatable):
def __init__(self, x, y, width, text_color=c.LOBBY_TEXT_COLOR, active_color=c.LOBBY_ACTIVE_COLOR, inactive_color=c.LOBBY_INACTIVE_COLOR, placeholder=None):
... | python |
# built-in
from contextlib import suppress
from pathlib import Path, PurePath
from typing import List, Optional, Set
# external
import attr
# app
from ._cached_property import cached_property
def _dir_list(filelist: List[str]) -> Set[str]:
# paths starting with '/' or containing '.' are not supported
dir_li... | python |
def main(*args, **kwargs):
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings")
django.setup()
from .fixtures import make_objects
factor = (args[0] if len(args) > 0 else kwargs.get('factor')) or 5
make_objects(factor)
| python |
import os
from PySide2.QtCore import QDir
from qt_material.resources import ResourseGenerator
# ----------------------------------------------------------------------
def generate_icons() -> None:
""""""
source = os.path.join(os.path.dirname(__file__), 'source')
resources = ResourseGenerator(primary=os.g... | python |
# Generated by Django 2.0.7 on 2018-08-08 03:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portal', '0005_project_personnel'),
]
operations = [
migrations.RemoveField(
model_name='project',
name='personnel',
... | python |
import asyncio
import pytest
from procrastinate import app
from procrastinate import worker as worker_module
@pytest.mark.asyncio
async def test_wait_for_activity(aiopg_connector):
"""
Testing that a new event interrupts the wait
"""
pg_app = app.App(connector=aiopg_connector)
worker = worker_mo... | python |
"""
import from core
"""
from holland.core.backup.base import BackupError, BackupRunner, BackupPlugin
| python |
def flatten_generator(list_to_flatten):
"""Child method to flatten multi-dimension lists into a single list
Args:
list_to_flatten (list): List of lists to flatten
Returns:
list()
"""
for elem in list_to_flatten:
if isinstance(elem,(list, tuple)):
for x in flatt... | python |
#!bin/env python
import subprocess
import os.path
import unittest, re
class TestSafety(unittest.TestCase):
@classmethod
def setUpClass(self):
# clean up, just in case
subprocess.call('rm -rf remote local 2>> /dev/null', shell=True)
# Create "local" and "remote" repositories
... | python |
from django.contrib import admin
from .models import Game, GameShort, SimilarGameConnection, SimilarGameConnectionWeighted
admin.site.register(Game)
admin.site.register(GameShort)
admin.site.register(SimilarGameConnection)
admin.site.register(SimilarGameConnectionWeighted) | python |
'''
MIT License
Name cs225sp20_env Python Package
URL https://github.com/Xiwei-Wang/cs225sp20_env
Version 1.0
Creation Date 26 April 2020
Copyright(c) 2020 Instructors, TAs and Some Students of UIUC CS 225 SP20 ZJUI Course
Instructorts: Prof. Dr. Klaus-Dieter Schewe
TAs: Tingou Liang, Run Zhang, Enyi Jiang, Xiang Li... | python |
from mcpy import primative, serializer
PacketSerializer = serializer.PacketSerializer
class LoginDisconnectPacket():
def __init__(self, reason):
self.reason = reason
class LoginDisconnectPacketSerializer(PacketSerializer):
def __init__(self):
self.id = 0
self.fields = [["reason", prim... | python |
"""Global API configuration."""
from os import environ
from urlparse import urlparse
# This module is both imported from and executed. In the former case only
# relative imports are supported, in the latter only absolute.
try:
from schemas import facility_schema, request_schema, resource_schema, \
service... | python |
import csv
import numpy as np
import time
from collections import OrderedDict
from .containers import Question, Word, WordTrial, QuestionTrial
def load_20questions_question_array(fname,
time_window_lower_bound=None,
time_window_length=None,
... | python |
import codecs
import io
import os
import re
import time
import zipfile
import numpy as np
import requests
import tensorflow as tf
from keras_preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
BATCH_SIZE = 128
MAX_LENGTH = 40
... | python |
'''
Provides XOX class which is a subclass of gym.Env.
Start using it via
```
x = XOX()
state, reward, done = x.step(2)
```
Locations are:
|0|1|2|
|3|4|5|
|6|7|8|
Opponent step is taken by uniform random, let's assume
it took action 0, board becomes:
|o| |x|
| | | |
| | | |
The state is the flattened version of the... | python |
#!/usr/bin/env python
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
elif len(nums) == 1:
return [[], nums]
elif len(nums) == 2:
return [[], [nums... | python |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# from instance.config import RANDOM_QUOTES_URL
class Config ():
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', '').replace(
'postgres://', 'postgresql://') or... | python |
# -*- coding: utf-8 -*-
__all__ = [
'UserGroupService', 'PermissionService', 'UserGroupMemberService',
'UserGroupPermissionService', 'VerificationService',
'SuperAdminService',
]
from . import user_group as UserGroupService
from . import permission as PermissionService
from . import user_group_member as U... | python |
def make_rxnorm_wordlists():
import pandas as pd
import os
import os.path
dataloc = '../../../data/'
filz = os.listdir(dataloc)
normfilz = [xx for xx in filz if xx.startswith('RxNorm_full')]
normfilz.sort()
most_current = normfilz[-1]
rxfile = os.path.join(dataloc,most_current,'r... | python |
__all__ = ["data", "functions"] | python |
import copy
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta_name = ['^', '<', 'v', '>']
def adjacent_cells(grid,row,col):
yMax = len(grid)-1
xMax = len(grid[0])-1
ret = []
if row-1 >= 0 and grid[row-1][col] != 1:
... | python |
#!/usr/bin/env python3
import argparse
from typing import Optional, List, Tuple, Dict
import json
import sys
import requests
def get_library(*, cookies):
# apparently returns all at once and pagination isn't necessary??
return requests.get(
'https://www.blinkist.com/api/books/library',
cookies=... | python |
import json
import asyncio
import sqlite3
import discord
from discord.ext import commands
from discord.ext.commands.errors import *
import time
DB = 'AudreyAnnouncement.db'
# spin off of permissions that makes announcements at time given in RoBot.py
class AudreyAnnouncement(commands.Cog):
def __init__(self, c... | python |
def return_if_error(
errors=(
KeyError,
TypeError,
),
default_value=None,
):
def decorator(func):
def new_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except errors as e:
return default_value
... | python |
from enum import Enum
__NAMESPACE__ = "foo"
class GlobalAddressTypeValues(Enum):
MA = "MA"
PH = "PH"
class GlobalNameTypeValues(Enum):
LG = "LG"
DB = "DB"
class GlobalSimpleStatusType(Enum):
VALUE_0 = "0"
VALUE_1 = "1"
class GlobalYesNoType(Enum):
Y = "Y"
N = "N"
| python |
class LocationPoint(Location,IDisposable):
""" Provides location functionality for all elements that have a single insertion point. """
def Dispose(self):
""" Dispose(self: APIObject,A_0: bool) """
pass
def ReleaseManagedResources(self,*args):
""" ReleaseManagedResources(self: APIObject) """
pass
de... | python |
from django.conf.urls import patterns
from jobs.models import Slug
urlpatterns = patterns('jobs.views',
(r'^$', 'list_jobs'),
(r'^delete/$', 'delete_jobs'),
(r'^(%s)/$' % Slug.regex, 'show_results'),
(r'^(%s)/delete/$' % Slug.regex, 'delete_job'),
(r'^(%s)/rename/$' % Slug.regex, 'rename_job'),
... | python |
import core.job
import core.implant
import uuid
class SLUIJob(core.job.Job):
def create(self):
if self.session_id == -1:
self.error("0", "This job is not yet compatible with ONESHOT stagers.", "ONESHOT job error", "")
return False
if (int(self.session.build) < 9600 or int(se... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.