content
stringlengths
5
1.05M
#!/usr/bin/env python3 """A GraphQL schema for TANGO.""" import os import graphene from tangogql.schema.query import Query from tangogql.schema.subscription import Subscription from tangogql.schema.mutations import DatabaseMutations from tangogql.schema.attribute import ScalarDeviceAttribute from tangogql.schema.att...
def requestAsyncWaveform(outputFormat, tb, te, proj, net, sta, loc, cha, label, JWT): import requests import json import configparser from halo import Halo # input outputFormat = outputFormat tb = tb te = te proj = proj net = net sta = sta loc = loc cha = cha labe...
from .fieldnames import * from pathlib import Path from collections import defaultdict from typing import List class FastCatAnnotation: """asd """ def __init__(self, path: Path, cfg): self.skip_frame_factor = cfg["skip_frame_factor"] self.fast_cat_allowed_labels = cfg["fast_cat_allower_labe...
import os from subprocess import Popen, PIPE, STDOUT import logging import mlflow import mlflow.version from mlflow.utils.file_utils import TempDir, _copy_project from mlflow.utils.logging_utils import eprint _logger = logging.getLogger(__name__) DISABLE_ENV_CREATION = "MLFLOW_DISABLE_ENV_CREATION" _DOCKERFILE_TEMP...
# encoding: utf-8 from setuptools import setup setup(name='platalea', version='0.1', description='Understanding visually grounded spoken language via multi-tasking', url='https://github.com/gchrupala/platalea', author='Grzegorz Chrupała', author_email='g.chrupala@uvt.nl', license='A...
import argparse import json import sys import requests from azureml.core.authentication import ( InteractiveLoginAuthentication, MsiAuthentication, ServicePrincipalAuthentication, ) from environs import Env print("Triggering pipeline...") # --- helper class definitions # parses a dictionary argument cl...
import json from datetime import datetime from django.http import HttpResponse from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.response import Response from rest_framework.views import APIView from ..serializers import ImportSerializer from ..services import...
''' Author: Guanghan Ning E-mail: guanghan.ning@jd.com October 22th, 2018 Load keypoints from existing openSVAI data format and turn these keypoints into Graph structure for GCN N: # of batch_size M: # of instances within a frame (which is # of human candidates) V: # of graph nodes (wh...
# 记录生肖,根据年份来判断生肖 chinese_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊' # print(chinese_zodiac[0:4]) # print(chinese_zodiac[-1]) year = 2018 print(year % 12) print(chinese_zodiac[year % 12]) print('狗' in chinese_zodiac) print(chinese_zodiac + 'abcd') print(chinese_zodiac * 3) # 练习三列表的基本操作 # 定义一个含有5个数字的列表 # 为列表增加一个元素100 # 使用remove()删除一...
#============================================================================ # This is sample Script for diagram #============================================================================ from sysmpy import * root_process = Process("Root Process") p1, p2 = root_process.Condition("한글 컨디션 입니다. 이것은 테스트 ", "P1", "P2"...
import sys import os.path import pprint sys.path.append(os.path.abspath(__file__ + "\..\..")) import ctypes import windows import windows.test from windows.generated_def.winstructs import * remote_code = """ import windows from windows.generated_def.winstructs import * windows.utils.create_console() class YOLOHXBP...
# gene sequence example from @yoch, see # https://github.com/ilanschnell/bitarray/pull/54 from random import choice from timeit import timeit from bitarray import bitarray trans = { "A": bitarray("00"), "T": bitarray("01"), "G": bitarray("10"), "C": bitarray("11") } N = 10000 seq = [choice("ATGC") ...
# * Copyright (c) 2020-2021. Authors: see NOTICE file. # * # * 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 ...
import bpy from .functions import calc_exposure_value, update_exposure_guide from . import ( camera_presets, ) class PHOTOGRAPHER_PT_Panel(bpy.types.Panel): # bl_idname = "CAMERA_PT_Photographer" bl_label = "Photographer" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "data" @classmethod ...
# how to run # python bin2png.py --input_dir="./data/input/validation" --output_dir="./" --data_size 1024 import tensorflow as tf import numpy as np import argparse import os import glob import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt SZ = 1024 parser = argparse.ArgumentParser() parser.add_ar...
import random number = random.randrange(1, 100, 1) n_guesses = 10 print("You have", n_guesses, "guesses") user_num = input("Enter a number between 1 and 100:\n") if user_num.isnumeric(): user_num = int(user_num) if 1 <= user_num <= 100: while n_guesses > 0: if user_num > number: ...
# coding=utf-8 # Copyright 2020 Google 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 ag...
# Copyright (c) Jupyter Development Team. from jupyter_core.paths import jupyter_data_dir import subprocess import os import errno import stat c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.port = 8888 c.NotebookApp.open_browser = False c.NotebookApp.token = '' # Set a password if PASSWORD is set if 'PASSWORD'...
#!/usr/bin/env python # coding: utf-8 # # Alice's Rose # ## Dependencies # # The `import` statement is special... it imports programmer's wisdom! # The common usage is to acquire access to python packages. # In[1]: import sympy import math # ## A Romantic Introduction to Matematical Optimization and to Python #...
# -*- coding: utf-8 -*- # @Time : 2019-08-21 15:53 # @Author : Kai Zhang # @Email : kai.zhang@lizhiweike.com # @File : ex1-IslandNumber_2.py # @Software: PyCharm """ 广度优先 https://leetcode-cn.com/problems/number-of-islands/solution/dfs-bfs-bing-cha-ji-python-dai-ma-java-dai-ma-by-l/ """ from typing import L...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : src/ampel/contrib/hu/examples/t0/ExampleFilter.py # License : BSD-3-Clause # Author : vb <vbrinnel@physik.hu-berlin.de> # Date : 14.12.2017 # Last Modified Date: 22.09.2018 # Last Modified By : vb <vbrinnel@physik.hu-...
# Code generated by lark_sdk_gen. DO NOT EDIT. from pylark.lark_request import RawRequestReq, _new_method_option from pylark import lark_type, lark_type_sheet, lark_type_approval import attr import typing import io @attr.s class GetAttendanceUserAllowedRemedyReq(object): employee_type: lark_type.EmployeeType = a...
from flask import jsonify from flask_testing import TestCase from src.models import db from src.app import create_app from src.models.task import Task class TaskResourceTestCase(TestCase): def create_app(self): return create_app() def setUp(self): db.create_all() # example task ...
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2004-2019 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
def leiaint(msg): ok=False while True: n=str(input(msg)) if n.isnumeric(): valor=int ok=True else: print('\033[0;31mErro! Digite um número inteiro valido:\033[m ') if ok: break return valor n=leiaint('Digite um número: ') print(f'Você ...
"""middlewares used with python social auth.""" from django.conf import settings from cms.models import Page from cms.utils import get_language_from_request from social_django.middleware import ( # isort:skip SocialAuthExceptionMiddleware as BaseSocialAuthExceptionMiddleware, ) SOCIAL_ERROR_REVERSE_ID = getattr...
from django.apps import AppConfig class HqqReportConfig(AppConfig): name = 'hqq_report'
""" [2015-04-24] Challenge #211 [Hard] Hungry puppies https://www.reddit.com/r/dailyprogrammer/comments/33ow0c/20150424_challenge_211_hard_hungry_puppies/ #Description Annie has a whole bunch of puppies. They're lovable but also very rambunctious. One day, spur of the moment, Annie decides to get them all treats. She...
"""Protocol definitions.""" # http://gearman.org/protocol/ import struct REQ = b'\x00REQ' RES = b'\x00RES' CAN_DO = 1 CANT_DO = 2 RESET_ABILITIES = 3 PRE_SLEEP = 4 # unused NOOP = 6 SUBMIT_JOB = 7 JOB_CREATED = 8 GRAB_JOB = 9 NO_JOB = 10 JOB_ASSIGN = 11 WORK_STATUS = 12 WORK_COMPLETE = 13 WORK_FAIL = 14 GET_STATUS ...
from django.shortcuts import render from .models import Image, Location, Category # Create your views here. def home(request): dispimages = Image.objects.all().order_by('id') dispBylocation = Location.objects.all() dispBycategory = Category.objects.all() return render(request, "index.html", {'images'...
"""Tox envlist manipulation.""" import os try: from tox.reporter import warning except ImportError: warning = lambda s: None from tox.config import _split_env as split_env from tox.config import ParseIni, SectionReader, testenvprefix BEFORE = 1 AFTER = 2 class _ParseIniWrapper(ParseIni): def __init__(s...
#!/usr/bin/env python3 """Merge and process CESAR output files. After the CESAR part there would appear numerous files. This script applies parse_cesar_bdb function to each file and then does the following: 1) Bed annotation track for query. 2) Nucleotide and protein fasta files. 3) Saves exons metadata into a tsv fil...
#!/usr/bin/env python3 # Copyright (C) 2017-2019 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
# -*- coding: utf-8 -*- from ExtractFQDNFromUrlAndEmail import extract_fqdn import pytest @pytest.mark.parametrize('input,fqdn', [ # noqa: E501 disable-secrets-detection ('http://this.is.test.com', 'this.is.test.com'), ('https://caseapi.phishlabs.com', 'caseapi.phishla...
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Symlinks to create symlinks = {"Applications": "/Applications"} # Volume icon badge_icon = "icons/kolibri.icns" files = ["dist/Kolibri.app"] # Where to put the icons icon_locations = { "Kolibri.app": (185, 120), "Applications": (550, 120), } ...
""" @author Jacob Xie @time 3/11/2021 """ from typing import Optional from sqlalchemy import Table from sqlalchemy.ext.declarative import declarative_base from .connector import Connector Base = declarative_base() class Loader(object): def __init__(self, connector: Connector) -> None: self._conn = con...
import os import re from enum import Enum from canvasapi.canvas import Course, File from canvasapi.exceptions import ResourceDoesNotExist, Unauthorized from colorama import Back, Fore, Style from config import Config from course_files import CourseFiles from utils import file_regex __all__ = ['FileOrganizer'] file_...
""" pytest_oot ~~~~~~~~~~~~~~~ Helpers for defining a simple format for object-oriented system-level testing The design is implemented taking pytest_yamlwsgi as a reference. :copyright: 2014-2015 Steven LI <steven004@gmail.com> :license: MIT This module is presented as a py.test plugin. I...
# -*- coding: utf-8 -*- # Created by hkh at 2019-02-19 import lucene from java.io import File from org.apache.lucene.analysis.standard import StandardAnalyzer from org.apache.lucene.store import FSDirectory, RAMDirectory from org.apache.lucene.index import IndexWriter from org.apache.lucene.index import IndexW...
import os import sys class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' GOOD = '\033[92m' WARNING = '\033[93m' ERROR = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # Printing With Colors Functions def print_good(text): print bcolors.GOOD + "[*]" + bcolors.ENDC + " " + text...
#!/usr/bin/env python import turbotutils.network import requests import urllib.parse import json def get_grants(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, namespace, api_version): account_list = [] api_method = "GET" api_url = "/api/%s/resources/%s/gr...
from. Udon_classes import * # IGNORE_LINE def _onPlayerJoined(playerApi: VRCSDKBaseVRCPlayerApi): UnityEngineDebug.Log(SystemObject(playerApi))
import botocore import pytest from pytest_mock import MockerFixture from dynamodb_session_web import SessionManager from .utility import get_dynamo_resource, TABLE_NAME @pytest.fixture(scope='function') def dynamodb_table(docker_services): # pylint: disable=unused-argument dynamodb = get_dynamo_resource() #...
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: Irwin Zaid # vispy: gallery 2:40:4 """ Animate an Image ================ Use a timer to trigger updating an image. This example demonstrates a 3D Texture. The volume contains noise that is smoothed in the z-direction. Shown is one slice through that volume to gi...
import tomodachi import uuid from typing import Any from tomodachi import schedule, aws_sns_sqs_publish from tomodachi.protocol import JsonBase @tomodachi.service class ServiceSendMessage(tomodachi.Service): name = 'example_service_send_message' message_protocol = JsonBase options = { 'aws_sns_sq...
from __future__ import absolute_import, division, print_function, unicode_literals __VERSION__ = "0.0.a7"
import six import hashlib def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given.""" if six.PY3 and isinstance(s, bytes): return s.decode(encoding) return s def get_default_id(request, spider): url = request.url return hashlib.md5(url).hexdigest()
# # Dates and Times in Python: Dates & Time # Python Techdegree # # Created by Dulio Denis on 12/24/18. # Copyright (c) 2018 ddApps. All rights reserved. # ------------------------------------------------ # Challenge 4: strftime & strptime # ------------------------------------------------ # Challenge Task 1 of 2...
import logging class NothingExecutor(object): def __init__(self, models, accountId, trader=None, logger=None): if logger is None: logger = logging.getLogger() self.logger = logger pass def handleOpenLong(self, lot): self.logger.warn('Requested opening long position, lot={lot}, ignored.' ...
from urllib.parse import urlencode, parse_qsl import requests from django.http import JsonResponse, HttpResponseForbidden from mozilla_django_oidc.views import OIDCAuthenticationCallbackView, OIDCAuthenticationRequestView, get_next_url, \ OIDCLogoutView def health(request): return JsonResponse({'result': 'OK...
import os from ply import lex, yacc class MyParser(object): """ Base class for a lexer/parser that has the rules defined as methods. Class extracted from PLY examples """ tokens = () precedence = () def __init__(self, **kw): """ constructior for parser lex, can receive a ...
from PIL import Image from io import BytesIO import base64 import cStringIO from subprocess32 import call from tornado.options import options from resizeimage import resizeimage, imageexceptions import os def generate_screenshot(url): call([options.chrome_path, "--headless", "--force-device-scale-factor", "--hide...
import argparse import logging from create_dataset import * if __name__ == '__main__': logging.basicConfig(format='%(asctime)s %(message)s', datefmt='[%Y/%m/%d][%I:%M:%S %p] ', level=logging.INFO) parser = argparse.ArgumentParser(description='Data Loader') parser.add_argument('-name', help='database name'...
# -*- coding: utf-8 -*- """ Created on Fri Nov 23 13:43:02 2018 @author: Florian Ulrich Jehn """ import matplotlib.pylab as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures import pca import read_attributes_signatures import pandas as pd import seaborn as sns i...
import logging from abc import ABC, abstractmethod from copy import deepcopy from time import monotonic from types import MethodType from typing import Optional from board import BOARD_SQUARES, Board, Loc, PlayerColor from solver import solve_game # type: ignore from termcolor import colored """ Definitions and fun...
def longestUniqueSubsttr(string): dic = {} max_len = 0 start = 0 for end in range(len(string)): if string[end] in dic: start = max(start, dic[string[end]] + 1) dic[string[end]] = end max_len = max(max_len, end-start + 1) return max_len
import time import serial from serial.tools import list_ports import BlinkyTape import IcspUtils # reset a strip to the booloader def resetToBootloader(portName): print "Resetting to bootloader on %s"%portName bt = BlinkyTape.BlinkyTape(portName) bt.displayColor(20,0,20) bt.resetToBootloader() # Write the la...
""" Communication Utility """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import io import os import time import random import numpy as np from PIL import Image, ImageFilter # the following two lines are needed because # PIL misidentifies certain jpeg images as MPOs from PIL import Jpe...
import re emailRegex = re.compile(r''' #example : #something-.+_@somedomain.com (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25...
# Author: Ankush Gupta # Date: 2015 """ Entry-point for generating synthetic text images, as described in: @InProceedings{Gupta16, author = "Gupta, A. and Vedaldi, A. and Zisserman, A.", title = "Synthetic Data for Text Localisation in Natural Images", booktitle = "IEEE Conference on...
from django.test import Client from django.urls import reverse def test_index(): client = Client() url = reverse('index') response = client.get(url) assert response.status_code == 200
import requests, responses, unittest, json import lateral.api class ApiTest(unittest.TestCase): def setUp(self): self.url = "http://test.io" self.api = lateral.api.Api("009b64acf288f20816ecfbbd20000000", url=self.url, ignore=[666]) self.jsonX = {"id": 1} self.X = json.d...
from .flow_viz import flow_to_image from .frame_utils import writeFlow
import os import re import pandas as pd import numpy as np import logging import argparse import csv from time import sleep import kfserving import tensorflow as tf from typing import List, Dict from kfserving import storage from prometheus_client import CollectorRegistry, Gauge, push_to_gateway import boto3 from bot...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Oct 16 17:49:18 2016 @author: yannick """ import sys with open(sys.argv[1], "r") as FILE: SEQ = "".join(x.strip("\n\r\t ") for x in FILE.readlines()[1:]) SEQ_INV = SEQ.replace("A","t").replace("C","g").replace("G","c") \ .replace("T","...
""" Application Skeleton """ from flask import Flask from flask_bootstrap import Bootstrap from config import CONFIG BOOTSTRAP = Bootstrap() def create_app(config_name): """ Factory Function """ app = Flask(__name__) app.config.from_object(CONFIG[config_name]) BOOTSTRAP.init_app(app) # call con...
from apps.products.models_mongo import MongoCustomerModel, MongoProductModel, MongoReviewModel from apps.products.models_dto import MongoProduct2DTO from config.settings.config_common import LOGTAIL_SOURCE_TOKEN, PAGE_SIZE_PRODUCT_DETAIL_REVIEW import datetime from logtail import LogtailHandler import logging handler ...
import LevelBuilder from sprites import * from sprite_templates import * def render(name,bg): lb = LevelBuilder.LevelBuilder(name+".plist",background=bg) lb.addObject(Hero.HeroSprite(x=49, y=58,width=42,height=74)) lb.addObject(Bullet.BulletSprite(x=0, y=0,width=10,height=10,angle='0',restitution=0.5,stat...
from collections import OrderedDict from transformers import BertTokenizer, is_tf_available from transformers.modeling_albert import AlbertConfig from transformers.tokenization_albert import AlbertTokenizer from ..model_base import TaskModels, ModelType, ModelTaskType, model_func default_model = model_func(ModelTyp...
# runs one dataset instead of looping through a list of them # this way all of the files can be run at once import CloneSeqAnalysisLibrary from CloneSeqAnalysisLibrary import analyze_clone_seq import os from os import path import sys colony = sys.argv[1] reference_file = "/local/storage/rhlin_to_copy/CloneSeqExample...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' summaryReportMap ---------------- Given a project id this service returns a map image showing the features for that project. ''' from arcpy import mapping, env, Extent, GetParameterAsText, SetParameterAsText from os.path import join, dirname from math import isnan pat...
class Solution: def combinationSum4(self, nums, target): memo = {} def dfs(sm): if sm in memo: return memo[sm] else: if sm >= target: memo[sm] = sm == target return memo[sm] cnt = 0 ...
""" Calculate the probability of encountering a word w, given that it is within the top 1000 most common words. P(r) is given by 0.1/r, where 1 < r < 1000. 1000 words is the limit as beyond that the harmonic series diverges for less frequent words. About 50% of all words in the Oxford English Corpus reside in the top 1...
# -*- coding: utf-8 -*- import random from random import randrange from model.group import Group from model.address import Address import pytest from generator.address import testdata @pytest.mark.parametrize("address", testdata, ids=[repr(x) for x in testdata]) def test_del_address_to_group(app, orm, address, chec...
""" Patches bokeh resources to make it easy to add external JS and CSS resources via the panel.config object. """ from __future__ import absolute_import, division, unicode_literals import glob import json import os from collections import OrderedDict from pathlib import Path from bokeh.resources import Resources fro...
# -*- coding: utf-8 -*- ''' 上海旅游景点客流量爬虫 这个要用到selenium和chromedriver,下载驱动用这个网址: https://sites.google.com/a/chromium.org/chromedriver/downloads 注意驱动版本和chrome版本对应 chrome版本查询: 打开chrome浏览器, chrome://version 爬取网站:https://shanghaicity.openservice.kankanews.com/public/tour/ 给了mysql和mongo两种数据库插入版本 ''' import requests from lxml ...
import smtplib from email.mime.text import MIMEText class Mail(object): """docstring for Mail""" def __init__(self, smtpserver, username, password): super(Mail, self).__init__() self.server = smtplib.SMTP(smtpserver) self.username = username self.password = password def sen...
#!/usr/bin/env python """cron_parser.py: command line utility to check cron expressions and parse all possible outputs for security purposes""" """ method to convert cron piece to 1. check if has wild cards 2. strip them if it does 3. operate via wild ca...
# GENERATED BY KOMAND SDK - DO NOT EDIT import insightconnect_plugin_runtime import json class Component: DESCRIPTION = "Create a new patch scan template" class Input: DESCRIPTION = "description" NAME = "name" PATCHGROUPIDS = "patchGroupIds" PATH = "path" THREADCOUNT = "threadCount" cl...
from PyQt5.QtCore import Qt, pyqtSignal, QPropertyAnimation, QPoint, QAbstractAnimation, QParallelAnimationGroup from PyQt5.QtWidgets import QWidget, QPushButton, QGridLayout, QHBoxLayout class PyQtSwitch(QWidget): toggled = pyqtSignal(bool) def __init__(self): super().__init__() self.__init...
from tkinter import Tk, Frame, Entry, Button, Checkbutton, StringVar from tkinter import END from .cashe_manager import ListCacheManager class MultiSelectPopup: def __init__(self, title, cache_name, starting_selected=None, cache_amount=100): self.tags = [] self.entries = [] self.root = Tk()...
# Databricks notebook source # MAGIC %sql # MAGIC create database hive_database # COMMAND ---------- # MAGIC %sql # MAGIC CREATE TABLE int_i18nRegions (id string, iso_country_code string, region_name string, extractDate date, load_date_time timestamp, # MAGIC countryCode string, load_date date) USING PARQUET LOCATIO...
""" Copyright (c) 2018-2022 Intel 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 wri...
# https://github.com/Cold-Winter/Nattack import time import numpy as np import torch import torch.nn as nn from tqdm import tqdm import cv2 class Normalize(torch.nn.Module): def __init__(self): super(Normalize, self).__init__() self.mean = torch.Tensor([0.485, 0.456, 0.406]) self.std = to...
# Generated by Django 3.2.12 on 2022-03-19 12:55 from django.db import migrations, models class Migration(migrations.Migration): """ Migration file to make the title field of push notification translations required """ dependencies = [ ("cms", "0012_mediafile_file_size"), ] operatio...
from collections import defaultdict, namedtuple from core.timeline import * from core.log import * import random AFFLICT_LIST = ['poison', 'paralysis', 'burn', 'blind', 'bog', 'stun', 'freeze', 'sleep', 'frostbite'] class Dot(object): """ Damage over time; e.g. poison """ def __init__(self, name, co...
#!/usr/bin/env python2.4 """ Code to solve tests at http://www.willmcgugan.com/blog/tech/2009/12/21/python-developer-programming-tests/ """ words = [ w.rstrip() for w in open('/usr/share/dict/words') ] an = {} for w in words: key = "".join(sorted(w)) #if key == "opst": # print w # print an.get...
# -*- coding: utf-8 -*- """ Web API ~~~~ ref: web_api.yaml :copyright: (c) 2017 by Baidu, Inc. :license: Apache, see LICENSE for more details. """ from __future__ import absolute_import, print_function from flask import g from .base_api import Resource from ..service import DataService class Da...
def LI(): return list(map(int, input().split())) import sys sys.setrecursionlimit(10 ** 9) ''' 思ったこと これグラフで,ダイクストラで求められるのでは?(なんとなく) ダイクストラでは無理そう.(始点が決まっていないから) N≤10だし普通に全探索?BFS? 見落としてたけど実行制限 5 secだった. PyPy: 2341 ms Python: TLE 実装に20分くらいかかったけど解けた. 解説: https://twitter.com/e869120/status/1390074137192767489 permuta...
import jsonschema class GeneratorBase(object): def __init__(self): self.schema = None def _get_schema(self): if self.schema is not None: return self.schema self.schema = self.get_schema() validator = jsonschema.validators.validator_for(self.schema) self.sc...
# NeoPixel library strandtest example # Author: Tony DiCola (tony@tonydicola.com) # # Direct port of the Arduino NeoPixel library strandtest example. Showcases # various animations on a strip of NeoPixels. import time import math import requests import json import time #hue var hue1 = "http://192.168.0....
from rest_framework import serializers from django_quill.fields import FieldQuill __all__ = ( "QuillFieldMixin", "QuillHtmlField", "QuillPlainField", ) class QuillFieldMixin: pass class QuillHtmlField(QuillFieldMixin, serializers.Field): def to_representation(self, value: FieldQuill): ...
# # Copyright (C) 2008, 2009 Loic Dachary <loic@dachary.org> # Copyright (C) 2009 Johan Euphrosine <proppy@aminche.com> # # This software's license gives you freedom; you can copy, convey, # propagate, redistribute and/or modify this program under the terms of # the GNU Affero General Public License (AGPL) as published...
from transformers import pipeline unmasker = pipeline('fill-mask', model='bert-base-uncased') unmasker("Hello I'm a [MASK] model.") [{'sequence': "[CLS] hello i'm a fashion model. [SEP]", 'score': 0.1073106899857521, 'token': 4827, 'token_str': 'fashion'}, {'sequence': "[CLS] hello i'm a role model. [SE...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
from __future__ import annotations import toolcli import toolsql def get_command_spec() -> toolcli.CommandSpec: return { 'f': migrate_upgrade_command, 'help': 'create migrations', 'args': [ {'name': '--message'}, {'name': '--noedit', 'action': 'store_true'}, ...
from flask_restplus import Resource, reqparse, Api from flask.json import jsonify from restplus import api as api from database.models import Monografia from database import db from database.operations import save_to, delete_data from flask import request from flask import make_response from flask_jwt import jwt_requi...
import subprocess import pandas as pd import tempfile import os __all__ = ['runRscript'] def runRscript(Rcmd, inDf=None, outputFiles=0, removeTempFiles=None): """Runs an R cmd with option to provide a DataFrame as input and file as output. Params ------ Rcmd : str String containing the R-...
# split off into its own module for aliasing without circrefs from cgi import escape from DocumentTemplate.ustr import ustr def html_quote(v, name='(Unknown name)', md={}): return escape(ustr(v), 1)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from urllib.request import urlretrieve, Request, urlopen from urllib.parse import urlencode, quote from bs4 import BeautifulSoup def replace_all(text): rep = { "&lt": "", "&amp": "", "&apos": "", "&quot": "", ";": "", "<b>": "", "</b>": "", "&g...