content stringlengths 5 1.05M |
|---|
import bpy
dir = r"C:\Users\Ahzam Ahmad\Documents\year4\cmput414\code"
f = open(dir+ "\extractions.txt", "r")
arr = {}
num=0
lines = f.readlines()
for line in lines:
#frame number before a, coorindates after a
a=line.find("(")
temp = line[a:].replace(")(", ").(")
temp = temp.split(".")
for i in rang... |
# imports
# imports
import discord
from dotenv import load_dotenv
from googletrans import LANGUAGES, Translator
load_dotenv()
def translations(nexttrans, author, msgID):
# Setting up the translator service
translator = Translator(service_urls=['translate.googleapis.com'])
texttotranslate = str(nexttrans)... |
from sys import maxsize
class Contact:
def __init__(self, firstname=None, middlename=None, lastname=None, nickname=None, photo=None, title=None,
company=None, address_company=None, telephone_home=None, telephone_mobile=None, telephone_work=None,
fax=None, email1=None, email2=Non... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils import FieldTracker
from waldur_core.core import models as core_models
from waldur_core.structure import models as structure_models
class VirtualMachineMixin(models.Model):
class Meta:
abstract = True
... |
import numpy as np
import torch
from torch.utils.data import Dataset
class LungDataset(Dataset):
def __init__(self, points_path, labels_path, npoints=2500, data_augmentation=True):
self._npoints = npoints
self._data_path = list()
self.data_augmentation = data_augmentation
for p, ... |
from credentials import dsn, consumer_key, consumer_secret, access_token, access_token_secret
import tweepy
import sentry_sdk
def get_api():
sentry_sdk.init(dsn)
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth, w... |
from API.db import db
from datetime import datetime
from passlib.apps import custom_app_context as pwd_context
class User(db.Model):
__tablename__ = "users"
def __init__(self, username, password):
self.username = username
self.password = pwd_context.hash(password)
self.limit = 0
... |
"""
Copyright 2019 ShipChain, 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, softwar... |
from dataclasses import dataclass
@dataclass
class MlfcoreTemplateStruct:
"""
First section declares the variables that all template have in common
"""
mlf_core_version: str = "" # Version of mlf-core, which was used for creating the project
domain: str = "" # Domain of the template
languag... |
import sublime
import sublime_plugin
import os
from hyperhelpcore.common import log
from hyperhelpcore.core import help_index_list
###----------------------------------------------------------------------------
class HyperhelpAuthorReloadIndexCommand(sublime_plugin.TextCommand):
"""
If the current view is... |
from .mmd import mmd
from .cg import cg
from .safe_div import safe_div
from .log_sum_exp import log_sum_exp
|
from django.test.testcases import SimpleTestCase
from django.conf import settings
from ..utils import get_zone_profile
class GetZoneProfileTestCase(SimpleTestCase):
def test_invalid_zone_name(self):
zone_profile = get_zone_profile("invalid_zone")
self.assertEqual(zone_profile, None)
def test... |
import re
import exceptions as error
import immediates as imm
import opcodes as opc
import registers as reg
import trim
def process_commands(commands):
binary_strings = []
create_binary = 1
commands = reg.replace_special_register_names(commands)
commands = trim.trim_word_gap(commands)
for line, com... |
import cv2
def use_ellipse(*axis):
'''
Ellipse Implementation
----------------------
- param : *axis : (frame, xmin, ymin, xmax, ymax, color)
- frame : continuos frame stream
- ellipse: image, ((center_coordinates), (axesLength), angle), startAngle, endAngle, color, thickness
'''
axes_1... |
from __future__ import print_function
import logging
import grpc
import darts_match_pb2 as darts_match_pb2
import darts_match_pb2_grpc as darts_match_pb2_grpc
from domain.visit import Visit
def run():
""" What would be ideal is a list of live matches to choose from. Instead, this just sends and empty request f... |
#/usr/bin/python
import unittest
from cvmfsreplica.utils import date2seconds, check_disk_space
class TestDate2Seconds(unittest.TestCase):
def test_date2seconds_edt(self):
self.assertEqual(date2seconds("Fri Apr 15 11:32:19 EDT 2016"), 1460734339)
def test_date2seconds_utc(self):
sel... |
from pyapacheatlas.core import PurviewClient, AtlasException
import requests
import time
import json
class ExtendedPurviewClient(PurviewClient):
"""
Provides communication between your application and the Azure Purview
service. Simplifies the requirements for knowing the endpoint url and
requires only t... |
YARRRML_MAPPING = '''mappings:
awayTeam:
predicateobjects:
- [a, 'http://dbpedia.org/ontology/SportsTeam']
- [a, 'http://dbpedia.org/ontology/Organisation']
- [a, 'http://schema.org/SportsTeam']
- ['http://www.w3.org/2000/01/rdf-schema#label', $(away_team)]
source: dataset-source
s... |
#!/usr/bin/env python3
from bitbots_test.decorators import error2failure
from bitbots_test.test_case import WebotsTestCase
from transforms3d.euler import euler2quat
import math
import geometry_msgs.msg
class TestSimulationSupervisorControls(WebotsTestCase):
@error2failure
def test_wait_for_simulator(self):
... |
import onnx
from onnx.helper import ModelProto
from furiosa_sdk_quantizer.interfaces.transformer import Transformer
from furiosa_sdk_quantizer.frontend.onnx.transformer import utils
from furiosa_sdk_quantizer.frontend.onnx.utils.check_model import check_model
from onnxruntime_tools.transformers.onnx_model import Onnx... |
import maya.cmds as cmds
import time
import datetime
def topOfHeirarchy(sourceNodes):
topNode = []
#print sourceNodes
for node in sourceNodes:
listAttrs = listAttrModes(node,'connection')
#print node,listAttrs
amountCheck = []
for attr in listAttrs:
if cmds.conn... |
# coding: utf-8
import pytest
from pytest import approx
import numpy as np
from ....types.angle import Bearing
from ....types.array import StateVector, CovarianceMatrix
from ....types.detection import Detection
from ....types.state import State
from ..linear import LinearGaussian
from ..nonlinear import (
Combined... |
import copy
import os
import torch
import wandb
from torch import device
from armor_py.utils import fix_random, aggregate, wandb_init, local_test_on_all_clients
from armor_py.options import args_parser
from armor_py.sampling import load_data, sample_user, create_model
from armor_py.update import LocalUpdate
def train... |
# Generated by Django 3.2.4 on 2021-07-02 14:24
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contacts', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='cont... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 ComputerGraphics Tuebingen. 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/... |
# Generated by Django 4.0.3 on 2022-03-08 09:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
import json
import aiohttp
from dadvisor.config import TRACKER, PREFIX, CADVISOR_URL
from dadvisor.datatypes.encoder import JSONCustomEncoder
from dadvisor.log import log
# # # # # # # # # # # # # # # # # # # # # # # # #
# Communication with nodes
# # # # # # # # # # # # # # # # # # # # # # # # #
async def ge... |
#Assignment to a module field can only at the constructor
from polyphony import module
class Statefull:
def __init__(self, v):
self.v0 = v
def func(self):
if self.v0 == 0:
self.v0 = 1
elif self.v0 == 1:
self.v0 = 2
else:
self.v0 = 0
... |
# -*- coding: utf-8 -*-
"""Day 79 - Dr Semmelweis Handwashing Discovery.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Iz5g2S6sYxlncIMVlJQh6ga4yMCv2UHl
# Setup and Context
<img src="https://i.imgur.com/gugIA5r.png" width=700>
### Introduction... |
#!/usr/bin/env python
#
# CS224W Fall 2019-2020
# @Jason Zheng
#
import argparse
from logger_utils import Logger
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold
from sklearn.metrics import roc_curve, confusion_matrix, recall_score, f1_score, auc, accur... |
# this is for creating a minimal uefi tree for testing
##
# Copyright (c) Microsoft Corporation
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
import os
import tempfile
import json
class uefi_tree:
'''
This class represents a minimal UEFI tree that you can setup
It is configurable and offers options to... |
# vim: set encoding=utf-8
from lxml import etree
from regparser.notice import sxs
from unittest import TestCase
class NoticeSxsTests(TestCase):
def test_find_page(self):
xml = """<ROOT>
<P />
Text
<P />
<PRTPAGE P="333" />
<P />
<PRTP... |
from banditpylib.data_pb2 import Context, Actions, Feedback, ArmPull, \
ArmFeedback
from banditpylib.learners import Goal, MaximizeTotalRewards
from .contextual_bandit_utils import ContextGenerator
from .utils import Bandit
class ContextualBandit(Bandit):
r"""Finite-armed contextual bandit
Arms are indexed f... |
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from project.config import settings
# reference : https://fastapi.tiangolo.com/tutorial/sql-databases/#create-the-sqlalchemy-engine
engine = create... |
import socket
import json
import os
import sys
class Moneda:
def __init__(self,id,name,value1,value2):
self.id=id
self.name = name
self.value1 = value1
self.value2 = value2
class Model:
def __init__(self):
self.prices = []
def updateData(self,data):
print... |
import sys
import os
OPS = ["bvand", "bvor", "bvxor"]
#GRANULARITIES = range(1, 9) #actually 1..8
GRANULARITIES = range(1, 5) #actually 1..4
skeleton = """
(set-logic <logic>)
(synth-fun <F> ((s Int) (t Int)) Int
(
(I Int) (Ic Int) (B Bool)
)
(
(I Int (
Ic
s
t
<addition>
<multi... |
import hev
import json
import logging
from flask import abort
from hev.api import DatadogAPI, DialogFlowRequest
from hev.constants import KIND_DIASTOLIC, KIND_SYSTOLIC
from hev.exceptions import ConfigException, NotAuthorized, BadRequest
def entrypoint(request):
"""Cloud Function entrypoint.
Args:
... |
__author__ = 'mangalbhaskar'
__version__ = '2.0'
"""
## Description:
# --------------------------------------------------------
# Annotation Parser Interface for Annotation work flow.
# It uses the annotations created by VGG VIA tool v2.03 (not tested), v2.05 (tested).
# -----------------------------------------------... |
n = float(input())
whole = int(n)
fractional = int(round((n % 1), 2) * 100)
print(whole, fractional)
|
#!/usr/bin/env python3
""" Solving the Atori problem on Kattis """
# I'm not happy with this, but I think it meets requirements
# There are too many edge cases going on here, it feels like.
import sys
data = sys.stdin.read().strip()
authors = data.split("-")
result = ""
for name in authors:
result = result+nam... |
from . import aws_lambda
lam = aws_lambda.core.l # boto3 lambda client passthrough
test = aws_lambda.test
create = aws_lambda.create_function
publish = aws_lambda.publish
|
import re
from DbxSync.CodeTransformer.LineTransformer.ImportLine import ImportLine
class LocalBootstrapRemover:
def transform(self, parsedLines: list):
def filterLines(parsedLine):
return isinstance(parsedLine, ImportLine) and parsedLine.getFrom() == 'DataSentics.local_bootstrap'
ret... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# 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 with... |
from django.db.models.signals import post_init, post_save
from alert.models import AlertPreference
from alert.signals import preference_updated
from alert.utils import ALERT_TYPE_CHOICES, ALERT_BACKEND_CHOICES, ALERT_TYPES, ALERT_BACKENDS
def alertpref_post_init(instance, **kwargs):
instance._current_pref = instan... |
#!/usr/bin/env python3
#import matplotlib.pyplot as plt
import argparse as ap
import numpy as np
import cv2 as cv
import os
import sys
class CustomFormatter(ap.HelpFormatter):
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, ... |
import torch
import numpy as np
from torch import nn
from offlinerl.utils.net.common import BasePolicy, MLP
from typing import Any, Dict, Tuple, Union, Optional, Sequence
from offlinerl.utils.function import soft_clamp
SIGMA_MIN = -20
SIGMA_MAX = 2
class Actor(nn.Module, BasePolicy):
"""Simple actor network wi... |
"""Define the abstract class for Information Retrieval From Index"""
class InformationRetrieval:
""" Information retrieval handles getting list of closest indexed vectors for the query vector"""
def get(self, query_vector):
pass
def refresh_index(self, search_index):
pass
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 16 22:56:22 2017
@author: Arpan
Description: Use MBH Features and ImageNetShuffle Features
"""
import json
import os
import utils
import numpy as np
import h5py
import pandas as pd
import collections
import cPickle
from sklearn import svm
from skl... |
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2020 www.open3d.org
#
# Permission is her... |
import logging
import datetime
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.shortcuts import render
from django.forms.models import model_to_dict
from django.contrib import messages
from django.core.mail import EmailMessage
from django.template.loader import render_to_s... |
# Copyright 2017 Battelle Energy Alliance, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
from jinja2 import Template, Environment, DictLoader
from sql_gen.docugen.template_filler import TemplateFiller
from sql_gen.docugen.env_builder import EnvBuilder
from sql_gen.sqltask_jinja import globals as globals_module
from sql_gen.sqltask_jinja import filters as filters_package
class _TestPromptBuilder(object):
... |
import re
valid_name_re = re.compile("^[a-zA-Z0-9_]+$")
name_tmpl = '({}) \'{}\''
def get_clock(clocks, clock_name):
return next((clock for clock in clocks if clock.name == clock_name), None)
def validate_clocks(clocks):
valid = True
clock_list = []
for i, clock in enumerate(clocks):
clock_na... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) ==... |
# Generated by Django 3.2 on 2021-04-30 00:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('waterspout_api', '0029_auto_20210428_1715'),
]
operations = [
migrations.AddField(
model_name='mo... |
import torch
import matplotlib.pyplot as plt
def logging(model, mode, c_dict, loss_dict):
# plot regularization
if model.reg:
model.log(f"{mode}/f0_loss", loss_dict["f0"])
model.log(f"{mode}/lo_loss", loss_dict["lo"])
idx = model.train_idx if mode == "train" else model.val_idx
# pl... |
# 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
# distributed under the Li... |
"""The tests for the Tomato device tracker platform."""
from unittest import mock
import pytest
import requests
import requests_mock
import voluptuous as vol
from homeassistant.components.device_tracker import DOMAIN
import homeassistant.components.tomato.device_tracker as tomato
from homeassistant.const import (
... |
import io
import struct
from pathlib import Path
from typing import Any
class PeekObject:
def __init__(self, handle: Any, *seek_args: Any) -> None:
self._handle = handle
self._seek_args = seek_args
self._old_pos = 0
def __enter__(self) -> None:
self._old_pos = self._handle.tel... |
'''
Created on 17 Sep 2016
@author: yc
'''
class Ar2He(object):
'''
Arabic -> Hebrew transcriber
'''
__Ar2HeNormalizedTranslitTbl = {
"\N{ARABIC LETTER HAMZA}": "\N{HEBREW LETTER ALEF}",
"\N{ARABIC LETTER ALEF WITH MADDA ABOVE}": "\N{HEBREW LETTER ALEF}\N{HEBREW POINT PATAH}\N{HEBRE... |
def validate_required_field(field_value, field_name, action):
assert field_value, f'{field_name} is required to {action}'
def validate_required_fields(action, **kwargs):
for item in kwargs.items():
validate_required_field(item[1], item[0], action=action)
def validate_names(action, **kwargs):
fo... |
"""
@author: Jim
@project: DataBrain
@file: __init__.py.py
@time: 2020/10/5 11:18
@desc:
""" |
# Generated by Django 3.1.1 on 2020-09-05 19:32
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
# coding=utf-8
from bika.lims.utils import t
from operator import itemgetter
from Products.Archetypes.config import REFERENCE_CATALOG
from Products.CMFCore.utils import getToolByName
import plone
import plone.protect
import json
class GetServices():
""" When a Category is selected in the add_analyses search scre... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
import streamlit as st
import defs
def app(data, geofile,):
st.header('Portfolio Density')
if not st.checkbox('Use full dataset'):
data = data.sample(500)
selection = st.radio('Map Type', ['Portfolio', 'Density Price per Region', 'Price Map'])
if selection == 'Portfolio':
defs.portfol... |
# -*- coding: utf-8 -*-
"""
Pyppeteer-based async python wrapper to convert html to pdf
"""
__forked_from__ = 'Golovanov Stanislav'
__author__ = 'Shivansh Saini'
__version__ = '1.0.5'
__license__ = 'MIT'
import pdfgen.api_sync as sync
from .api_async import from_file, from_sources, from_string, from_url
from .config... |
"""Contour plots with streamlines superimposed of the in-plane velocity
(i.e. xy-velocity) on the xy-slice. The slices are obtained by slicing the CFD
datasets (vtu format) with the xy-plane at z = 0 mm.
"""
import os
import vtk
import numpy as np
import matplotlib.pyplot as plt
from utils import iolib
fro... |
class Hands :
def __init__(self,
method,
set_joints_function,
get_joints_function):
self._method = method
self._motion_managers = [None,None]
self._set_joints_function = set_joints_function
self._get_joints_function = get_joint... |
from tinydb import TinyDB
from ezrpy.error import RequestError
class Database(object):
def query_object(self, collection_name):
raise NotImplementedError()
class QueryObject(object):
def all(self):
"""
Gets all documents in this collection.
:return: a list of documents.
... |
"""
Тестируется способность отрисовать анимацию 200 рыцарей (1600 объектов) одновременно
"""
from tests.animation_tests.base_animation import *
RUN_TIME = 10
def test_simple_animation():
window = SimpleAnimationTest(count_knights=200)
window.setup()
window.test(60 * RUN_TIME)
assert (window.time >= R... |
import json
import os
import random
input_path = "/data"
output_path = "/output/result.txt"
if __name__ == "__main__":
result = {}
for filename in os.listdir(input_path):
data = []
for line in open(os.path.join(input_path, filename), "r", encoding="utf8"):
data.append(json.loads(li... |
# coding:utf-8
# Written on Jul 12 2020 by Xuzhen Chen onboard Saltire.
# The script will crawl geojson file from usgs and save it as json/csv files
import requests
import csv
import time
import json
def data(yr):
s = requests.session()
url = 'https://earthquake.usgs.gov/fdsnws/event/1/query.geojson?starttime... |
import random
import string
from django.test import TestCase
from accounts.models import User
class SignupTest(TestCase):
def __init__(self, methodName: str = ...) -> None:
super().__init__(methodName)
def setUp(self) -> None:
"""Sets up test data"""
return super().setUp()
de... |
from __future__ import absolute_import
import sys, os
import numpy as np
from Bio.PDB.Polypeptide import d1_to_index
from ..seqStep.SeqFeatComputer import SeqFeatComputer, FeatureComputerException
from utils import myMakeDir, myMakeDirUnique, tryToRemove, tryToCopy #utils is at the root of the package
from bigExcept... |
"""
Usage: k-send.py <hostname>
"""
from kafka import SimpleProducer, KafkaClient
import logging
import sys
logging.basicConfig()
topic = b'my-topic'
if len(sys.argv) > 2:
topic = sys.argv[2]
kafka = KafkaClient(sys.argv[1] + ':9092')
#kafka.ensure_topic_exists(topic)
producer = SimpleProducer(kafka)
produce... |
from django.db import models
from django.utils import timezone
FOOD_TYPE_CHOICES = (
(0, '水'),
(1, '食料品'),
(2, 'おかず'),
(3, 'その他')
)
FOOD_GENRE_CHOICES = (
(0, '水'),
(1, '麺'),
(2, 'おかゆ'),
(3, 'その他')
)
class FoodModel(models.Model):
title = models.CharField(max_length=50)
type =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Usage: %(scriptName) <repository_path> <bug_reports.json> <data_prefix>
"""
import datetime
import json
import pickle
import subprocess
import sys
from joblib import Parallel, delayed
from date_utils import convert_commit_date
from multiprocessing import Pool
from o... |
from collections import namedtuple
from glob import glob
from pprint import pprint
from time import time
import pygame as pg
import numpy as np
import pygame.image
from win32api import GetSystemMetrics
from typing import Union
from PIL import Image
from pathlib import Path
import os
def screen_maker(func):
"""Dec... |
#copyright 2017 Lukasz Kostrzewa
import sys, os, PyPDF2
from PyQt4 import QtGui, QtCore, uic
import operator
from item import *
PdfFilesList = []
idNumber = 0
lastOrdinalNumber = 0;
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
uic.loadUi('merger_gui... |
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt, mpld3
from pandas import DataFrame
#----------------------------------------------------------------------------------------------------------------------#
#Load the data into a DF
with open(r"C:/Users/Pathtoyourdata", 'r', encod... |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 requir... |
import click
from .game_commands import game
from .meta_role_commands import meta_role
@click.group()
@click.pass_context
def guild(context):
"""Manage guild operations"""
pass
guild.add_command(game)
guild.add_command(meta_role)
__all__ = [
'guild'
]
|
import random
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
NUMBER = "0123456789"
Symbol = "@#$%{}[]()/\~,;.<>"
all = lower + upper + NUMBER + Symbol
length = 16
password = "".join(random.sample(all, length))
print("Your New Password: ", password)
|
b=' Huan Qiao Zhi Ying Xi Qiao Ji Zheng Huang Yu Zou Mei Sheng Quan Jiang He Tong He Wen Yi Pang Weng Qian Li Yi Chuang Xu Wei Ge Yu Zhai Gan Qian Kang Li Shen Guan Piao Gai Li Hu Tu Shun Hu Li Lou Dang Zuo Shan She Feng Ju Tong Jiao Qiao Gao Zi Huang Shan Tan... |
# -*- coding: utf-8 -*-
"""xman
Module for extracting cross sections and solving for flow using Manning's
equation.
Author: Alan D Snow, 2017.
License: BSD 3-Clause
"""
|
# -*- coding: utf-8 -*-
"""
pytests for resource extractors
"""
from click.testing import CliRunner
import numpy as np
import os
import pandas as pd
from pandas.testing import assert_frame_equal
import pytest
import tempfile
import traceback
from rex.resource_extraction.wind_cli import main
from rex.resource_extractio... |
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from corehq.apps.indicators.admin.crud import BaseDynamicIndicatorCRUDManager, CouchIndicatorCRUDManager
class MVPActiveCasesCRUDManager(CouchIndicatorCRUDManager):
@property
def properties_in_row(self):
... |
import json
from .fleetmanager import CoordinatorStrategyBehaviour
from .customer import CustomerStrategyBehaviour
from .transport import TransportStrategyBehaviour
from .secretary import SecretaryStrategyBehaviour
from .station import StationStrategyBehaviour
from .utils import TRANSPORT_WAITING, TRANSPORT_WAITING_FO... |
print("Let's talk about numbers!")
print()
num_text = input("What's your favorite whole number? ")
num = int(num_text)
if num % 2 == 0:
print(f"What a sweet number, {num:,} is even!")
else:
print(f"That's odd. Yeah, I mean {num:,} is an odd number mathematically.")
# Note:
# {num:,} does digit grouping: 1010... |
from unittest import mock
from django.core.exceptions import ObjectDoesNotExist
from .manager_case import ManagerTestCase
from .factories import (
IEDocFactory, GazetteItemFactory,
EntityFactory, EntityKindFactory,
)
from iepy.data.models import GazetteItem, Entity
from iepy.data.db import EntityOccurrenceMan... |
a = 1
b = 2
c = 3
state = a
text = ''
path_in = input('文件的绝对路径: ')
path_out = input('输出的绝对路径: ')
with open(path_in, 'r') as f: #打开srt字幕文件,并去掉文件开头的\ufeff
for line in f.readlines(): #遍历srt字幕文件
if state == a: #跳过第一行
state = b
elif state == b: #跳过第二行
state = c
elif state == c: ... |
import tensorflow as tf
from . import utils
from . import base
from . import tf_utils
class RNNStep(object):
"""
more general abstraction for RNN's than tf.contrib.rnn.RNNCell
- allows keeping multiple states
- eg. both cell and hidden in LSTM
"""
def state_specification(self):
""... |
# This is a script that you should run on Discovery,
# as part of a Slurm Array job, with 1000 jobs.
import numpy as np
import os
from model import max_vehicle_power
big_parameter_list = np.loadtxt("parameter_values.txt")
header = open("parameter_values.txt").readline()
header = header.strip('#\n ') # remove the '#', s... |
class Solution:
def XXX(self, root: TreeNode) -> int:
if not root: return 0
stack,ans = [(root,1)],0
while stack:
p, lv = stack.pop()
ans = max(lv,ans)
if p.left:
stack.append((p.left,lv+1))
if p.right:
stack.app... |
import os
import re
from optparse import Values
from collections import defaultdict
import urllib
from copy import copy
from six import iteritems
from lxml import etree as ET, objectify
from scour import scour
import jinja2
from ..helpers import parseDim, f2str
from .base import Image
from .png impo... |
from PySide2.QtWidgets import QDialog
from project import ui
class PasswordPrompt(QDialog):
def __init__(self, password, *args, **kwargs):
super(PasswordPrompt, self).__init__(*args, **kwargs)
self.ui = ui.PasswordPrompt()
self.ui.setupUi(self)
self.password = password
... |
from django.conf import settings
from django.utils.translation.trans_real import language_code_prefix_re
__all__ = (
'strip_language_from_path',
)
def strip_language_from_path(
path: str
) -> str:
"""
Return current path from request, excluding language code
"""
regex_match = language_cod... |
from rest_framework import serializers
from fileupload.models import File, FileGroup
from uuid import UUID
# Serializer는 복잡한 데이터형식에서 데이터 추출을 도와준다. DB에 저장되어있는 데이터 <=> 필요한 데이터 추출!
# 간단히 말하자면 파이썬 객체와 JSON/XML 변환기를 Serializer라고 생각하면 된다.
class FileSerializer(serializers.ModelSerializer):
filename = serializers.Serial... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.