text
stringlengths
2
999k
import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import os figure_number = 0 col_index = 0 row_index = 0 file_path = os.getcwd() + "/../../../ExperimentDataCheck/" ## read files data_q = \ np.genfromtxt(file_path+'q.txt', delimiter=None, dtype=(float)) data_jpos_des = \ np...
# Copyright (C) 2019-2020 Intel Corporation # # SPDX-License-Identifier: MIT import numpy as np from datumaro.components.extractor import Transform, LabelCategories, AnnotationType from datumaro.util import take_by # pylint: disable=no-self-use class Launcher: def __init__(self, model_dir=None): pass ...
import socket UDP_IP = "127.0.0.1" UDP_PORT = 5005 MESSAGE = "Hello, World!" print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "message:", MESSAGE sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
#!/usr/bin/env python3 # coding: utf-8 """A simple python3 script template. """ import random import sys class Solution(object): def __init__(self, nums): """ :type nums: List[int] """ self.orig = nums[:] self.nums = nums[:] self.seed = 1 random.seed(self....
"""Message Generator. Module provides helper methods for the print_utilities module. """ from __future__ import absolute_import try: from . import time_utilities as t_utils except ValueError: import time_utilities as t_utils def _generate(msg, tags=[], pre='', post='', **kwargs): div = False ftag =...
from flask import Flask, jsonify ################################################# # Flask Setup ################################################# app = Flask(__name__) import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session import datetime as dt from sq...
# -*- coding: utf-8 -*- r""" Permutation groups A permutation group is a finite group `G` whose elements are permutations of a given finite set `X` (i.e., bijections `X \longrightarrow X`) and whose group operation is the composition of permutations. The number of elements of `X` is called the degree of `G`. In Sage,...
from SHMArrays import SHMArrays import numpy as np import pdb from collections import OrderedDict n_params = 20 sizes = [int(1e5*np.random.rand()) for i in range(n_params)] arrays = OrderedDict([('id'+str(i),np.random.randn(size)) for i,size in zip(range(n_params),sizes)]) arrays2 = OrderedDict([('id'+str(i),np.random...
import copy import json from dataclasses import dataclass from etrv2mqtt.config import Config @dataclass class AutodiscoveryResult(): topic: str payload: str class Autodiscovery(): _termostat_template = json.loads(""" { "~": "etrv/kitchen", "name":"Kitchen", "unique_id":"000...
import os from pyln.testing.fixtures import * # noqa: F401,F403 plugin_path = os.path.join(os.path.dirname(__file__), "cl-zmq.py") def test_zmq_starts(node_factory): l1 = node_factory.get_node() # Test dynamically l1.rpc.plugin_start(plugin_path) l1.rpc.plugin_stop(plugin_path) l1.rpc.plugin_sta...
"""pca is a python package to perform Principal Component Analysis and to make insightful plots.""" # %% Libraries import colourmap as colourmap from sklearn.decomposition import PCA, SparsePCA, TruncatedSVD # from sklearn import preprocessing from sklearn.preprocessing import StandardScaler from sklearn.metrics.pairw...
""" Q238 Product of Array Except Self Medium /Array/ O(n) time complexity O(n) space complexity Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Note: Please s...
# Generated by Django 2.1.11 on 2019-09-01 15:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0004_recipe'), ] operations = [ migrations.RenameField( model_name='recipe', old_name='ingridients', ne...
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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 t...
#------------------------------------------------------------------------------- # Name: Example # Purpose: # # Author: rf # # Created: 11/08/2015 # Copyright: (c) rf 2015 # Licence: Apache Licence 2.0 #------------------------------------------------------------------------------- import numpy a...
from math import ceil from django.db import connection, models from django.db.models.deletion import ( Collector, ProtectedError, RestrictedError, ) from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import ( B...
# # 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 t...
# TODO test dtype != float32 from __future__ import absolute_import, print_function, division import os try: import pygpu except ImportError: pass import theano import theano.sandbox.multinomial from theano import Apply, config from theano.gof import Op from theano.tensor import NotScalarConstantError, get_s...
import scrapy import json data = None class TedSpider(scrapy.Spider): # read json file urls = [] with open("TED_Talks.json") as json_f: # get url array data = json.load(json_f) for i, url in enumerate(data): if (i >=2500 and i < 2550): urls.append(url["...
#!/usr/bin/env python import getpass from google.appengine.ext.remote_api import remote_api_stub from deploy import Deploy remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api', lambda: (Deploy.GAE_ADMIN, Deploy.GAE_APP_PASSWORD), Deploy.GAE_REMOTE_SERVER) #remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_...
import asyncio from loguru import logger from ariadne import gql, make_executable_schema from ariadne import QueryType, MutationType, SubscriptionType from ariadne.contrib.django.scalars import date_scalar from channels.db import database_sync_to_async from orders.models import Order query = QueryType() mutation =...
# Copyright 2018 The TensorFlow Authors. 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...
# -*- coding:utf-8 -*- import requests import re import codecs import os from lxml import etree from HTMLParser import HTMLParser h = HTMLParser() url_ptn = 'http://www.1juzi.com/new/%s.html' starter_pid = '53377' downloaded = set() pid_ptn = re.compile(r'<a href="/new/(\d+).html">') title_ptn = re.compile(r'<h1>(....
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy.dialects.postgresql import ARRAY, JSONB from ind...
# BSD Licence # Copyright (c) 2010, Science & Technology Facilities Council (STFC) # All rights reserved. # # See the LICENSE file in the source distribution of this software for # the full license text. """ Translate CMIP5 DRS filenames and paths to and from DRS objects with consistency checking against CMIP5 MIP ta...
# Generated by Django 2.1.15 on 2021-05-08 14:29 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0004_tag'), ] operations = [ migrations.CreateModel( ...
"""Data generator generates batches of inputs and outputs/labels for training. The inputs are each made from two parts. The first maxlend words are the original description, followed by `eos` followed by the headline which we want to predict, except for the last word in the headline which is always `eos` and then `emp...
#!/usr/bin/env python3 # Python Stream Deck Library # Released under the MIT license # # dean [at] fourwalledcubicle [dot] com # www.fourwalledcubicle.com # # Example script showing basic library usage - updating key images with new # tiles generated at runtime, and responding to button state c...
""" Django settings for app project. Generated by 'django-admin startproject' using Django 2.1.15. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Bu...
# proposed model implementation import numpy as np import torch from torch import nn import pytorch_lightning as pl from torch import autograd import sys sys.path.append('..') from networks import MnistCNNDecoder, ExprDiffDecoder, ConditionedDecoder, RNNEncoder, FinetunedEncoder from networks import MnistCNNEncode...
# Generated by Django 3.2.7 on 2021-09-19 04:26 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.CreateMode...
#!/usr/bin/env python # encoding: utf-8 """ @author: Alfons @contact: alfons_xh@163.com @file: 1.QuitSort.py @time: 18-6-3 下午3:05 @version: v1.0 """ # 快速排序 from Algorithms.LogDecorator import PrintfDecorator @PrintfDecorator def QuitSorting(srcList: list): if len(srcList) < 2: return srcList mid = ...
""" 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 "License"); you may not use this ...
import nltk nltk.download('twitter_samples') nltk.download('punkt') nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('stopwords')
# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.error import PyAsn1Error from pyasn1.type import constraint from pyasn1.type import namedtype from pyasn1.type import tag from pyasn1.type import univ ...
#!/usr/bin/env python """ Import one or more exported workflows contained within a specified tool shed repository installed into Galaxy. Here is a working example of how to use this script to repair a repository installed into Galaxy. python ./import_workflows_from_installed_tool_shed_repository.py -a 22be3b -l http:/...
from abc import ABCMeta, abstractproperty, abstractmethod class UpdateStrategy(metaclass=ABCMeta): @abstractproperty def case_implementation_class(self): pass def __init__(self, case): self.case = case @classmethod def case_from_case_update(cls, case_update, xformdoc): ""...
""" Tools for installing DC/OS on a provisioned AWS cluster. """ from pathlib import Path from typing import Any, Dict, Optional import click from dcos_e2e.backends import AWS from dcos_e2e_cli.common.create import get_config from dcos_e2e_cli.common.doctor import get_doctor_message from dcos_e2e_cli.common.install ...
# 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 "License"); you may not use ...
'''SSL with SNI-support for Python 2. This needs the following packages installed: * pyOpenSSL (tested with 0.13) * ndg-httpsclient (tested with 0.3.2) * pyasn1 (tested with 0.1.6) To activate it call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3`. This can be done in a ``sitecustomize`` module, or at any ot...
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
# Generated by Django 3.1.7 on 2021-07-03 12:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("record_requests", "0001_initial"), ] operations = [ migrations.AddField( model_name="recordrequest", name="estimated...
import logging from flask import abort, flash, redirect, render_template, request, url_for from flask_login import current_user, login_required, login_user, logout_user from redash import __version__, limiter, models, settings from redash.authentication import current_org, get_login_url, get_next_path from redash.aut...
"""Fixture for static analysis.""" from multimethod import multidispatch class cls: @multidispatch def method(self) -> int: return 0 reveal_type(cls().method()) # noqa: F821
import os import argparse from sys import path path.append(os.getcwd()) from data_utils.task_def import DataFormat from data_utils.log_wrapper import create_logger from experiments.ner.ner_utils import load_conll_chunk, load_conll_ner, load_conll_pos, dump_rows from experiments.common_utils import dump_rows logger = cr...
from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from .models import Profile,Photo,comments,Following from .forms import NewPhotoForm,EditProfileForm from django.contrib.auth.models import User # Create your views here. @login_required(login_url='/accounts/login/') ...
import unittest import numpy as np from spatialmath.base import * # test graphics primitives # TODO check they actually create artists class TestGraphics(unittest.TestCase): def test_plotvol2(self): plotvol2(5) def test_plotvol3(self): plotvol3(5) def test_plot_box(self): plot_b...
import os import socket import subprocess from collections import deque from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException, httplib from logger import info def simplemovingaverage(period): assert period == int(period) and period > 0, "Period must be an integer >0" val = {"summ": 0.0, "n": 0.0...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import unittest from fs_image.find_built_subvol import find_built_subvol class FindBuiltSubvolTestCase(uni...
import json from unittest.mock import Mock, PropertyMock import pytest from flask import Flask from bakedbeans import blueprints, exceptions @pytest.fixture() def app(tmpdir): app = Flask(__name__) app.config['BEANS'] = tmpdir app.register_blueprint(blueprints.beans) return app.test_client() def g...
import numpy as np import pandas as pd import tensorflow_hub as hub import os import joblib # Loads Universal Sentence Encoder locally, from downloaded module embed = hub.load('data/04_models/universal_sentence_encoder/') # Loads Universal Sentence Encoder remotely, from Tensorflow Hub # embed = hub.load("https://tfhu...
# -*- coding: utf-8 -*- """ ==================================== Brainstorm auditory tutorial dataset ==================================== Here we compute the evoked from raw for the auditory Brainstorm tutorial dataset. For comparison, see [1]_ and: http://neuroimage.usc.edu/brainstorm/Tutorials/Auditory Experi...
# Not finished yet
# -*- coding: utf-8 -*- # Copyright 2014, Digital Reasoning # # 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 applica...
import pymel.core as pc from Maya_Rigging.Core import JointStretchNetworkLib as js from Maya_Rigging.Core import BuildWorld as bw from Maya_Rigging.Utils import CharUtilsLib as chUL from Maya_Rigging.Utils import CurveUtilLib as cuUL def buildSpineSetup(name, side, rootJoint, ...
class Solution: def minMoves2(self, nums: List[int]) -> int: nums.sort() middle = 0 if (len(nums) == 1): return 0 if (len(nums) % 2 != 0): middle = nums[int(len(nums)/2)] else: middle = int((nums[int(len(nums)/2)] + nums[int(len(nums)/2) - ...
from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.generics import get_object_or_404 from jobs.models import JobBoard from jobs.serializers import JobBoardSerializer # Create your views here. class JobListCreateApiView(APIView): ...
from ..shared_mocks import * import sys def test_change_to_amigo(mocker): if "board" in sys.modules: del sys.modules["board"] sys.modules["board"] = board_amigo() import board import krux.input importlib.reload(krux.input) import krux.pages importlib.reload(krux.pages) asser...
# MIT License # Copyright (c) 2021 Sergey B <dkc.sergey.88@hotmail.com> from logging import log, DEBUG import time from PIL import Image from enum import Enum class CroppingMode(Enum): """Defines possible image cropping modes. For example, LEFT means that only left part of the image get saved. """ ...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.async_support.base.exchange import Exchange import hashlib import math from ccxt.base.errors import ExchangeError from ccxt.base....
import json import config files = { 'TRAIN_DATA': config.TRAIN_DATA_FILE, 'TEST_DATA' : config.TEST_DATA_FILE, 'VALID_DATA': config.VALID_DATA_FILE } for data_type, json_file in files.items(): data = json.load(open(json_file)) print(data_type, "\t->", list(data.keys())) for key in data.keys(...
from __future__ import absolute_import, division, print_function from .version import __version__ # noqa import numpy as np import h5py as h5 import nibabel as nib
"""Constants for GIOS integration.""" from __future__ import annotations from datetime import timedelta from typing import Final from homeassistant.components.sensor import ATTR_STATE_CLASS, STATE_CLASS_MEASUREMENT from homeassistant.const import CONCENTRATION_MICROGRAMS_PER_CUBIC_METER from .model import SensorDesc...
# Wifi hunter by Clyde Smets <clyde.smets@gmail.com> # # @Desc # Wifi hunter will scan for any available networks and store them into a JSON # file. This is just a fun little tool to find networks around your area. Put it # on a Raspberry Pi and run Strava to find out where the networks are according # to the timestamp...
import logging from django.core.management.base import BaseCommand import mkt from mkt.constants.regions import (REGIONS_CHOICES_ID_DICT, SPECIAL_REGION_IDS) log = logging.getLogger('z.task') class Command(BaseCommand): """ Backfill Webapp Geodata by inferring regional po...
"""bencode.py - common.""" class Bencached(object): __slots__ = ['bencoded'] def __init__(self, s): self.bencoded = s
"""parfaitweb URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
from django.apps import AppConfig class TweetsAppConfig(AppConfig): name = "project.tweets" verbose_name = "Tweets"
#----------------------------------------------------------------------- #Copyright 2019 Centrum Wiskunde & Informatica, Amsterdam # #Author: Daniel M. Pelt #Contact: D.M.Pelt@cwi.nl #Website: http://dmpelt.github.io/foam_ct_phantom/ #License: MIT # #This file is part of foam_ct_phantom, a Python package for generating...
#! /usr/bin/env python """Generate an XML form from Canvas and Autolab csv files that can be uploaded to Canvas. Currently only looks at the total score. Author: Nathan Sprague Version: 1/18/2018 """ import argparse import generate_form class AutoLabForm(generate_form.CanvasForm): def __init__(self, canvas_csv...
import argparse import os import os.path as osp import pickle import shutil import tempfile import mmcv import torch import torch.distributed as dist from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, init_dist, load_checkpoint from mmdet.core import wrap_fp16_m...
import argparse import os import pandas as pd import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import sys sys.path.append('../') from load_paths import load_box_paths import matplotlib.dates as mdates import seaborn as sns from processing_helpers import * mpl.rcParams['pdf.fonttype'] = 42 def p...
""" Testing hrf module """ from os.path import dirname, join as pjoin import numpy as np from scipy.stats import gamma import scipy.io as sio from ..hrf import ( gamma_params, gamma_expr, lambdify_t, spm_hrf_compat, spmt, dspmt, ddspmt, ) from nose.tools import assert_raises from nu...
GAMMA_TABLE = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, ...
# Copyright 2020 Alibaba Group Holding Limited. 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 ...
class ProjectLocationSet(APIObject, IDisposable, IEnumerable): """ An set that contains project locations. ProjectLocationSet() """ def Clear(self): """ Clear(self: ProjectLocationSet) Removes every project location from the set,rendering it empty. """ pass ...
import argparse from parse import parse_markdown, read_args def main(): parser = argparse.ArgumentParser( description='read a markdown string or file' ) parser.add_argument('--string', '-s', type=str, help='a valid markdown string') parser.add_argument('--file', '-f', ...
# import comet_ml in the top of your file from comet_ml import Experiment # Add the following code anywhere in your machine learning file experiment = Experiment(api_key="QCxbRVX2qhQj1t0ajIZl2nk2c", project_name="ml-tools", workspace="hirune924", auto_param_logging=F...
"""Quantum Inspire library Copyright 2019 QuTech Delft qilib is available under the [MIT open-source license](https://opensource.org/licenses/MIT): 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 Softwar...
#!/usr/bin/env python ## # Copyright (C) 2016 University of Southern California and # Nan Hua # # Authors: Nan Hua, Ke Gong, Harianto Tjong, and Hanjun Shin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publi...
import socket from unittest import TestCase from ..subprocess_server_manager import SubprocessServerManager, SubprocessServer from ..exceptions import ImproperlyConfigured class BaseSocketTestCase(TestCase): @ staticmethod def get(host: str, port: int) -> bytes: with socket.socket(socket.AF_INET, sock...
# @Time : 2022-02-22 18:56 # @Author : Phalange # @File : test_ch.py.py # @Software: PyCharm # C'est la vie,enjoy it! :D import os import pandas as pd import torch from d2l import torch as d2l import DataProcess import Module.AttentionModel import Module.evalScript from torch import nn import numpy as np import jieba_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 4 13:03:43 2020 @author: Scientists4Future Leipzig """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import urllib from matplotlib.colors import LinearSegmentedColormap ## Manual entries required: # Enter number of mont...
# Copyright (c) 2021, NVIDIA 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...
# If you have not yet seen the source in paging/main.py, please take a look. # In this sample we modify the query parameters in the MyModelList method to # allow querying with simple equality filters. import endpoints from google.appengine.ext import ndb from protorpc import remote from endpoints_proto_datastore.nd...
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
# read version from installed package from importlib.metadata import version __version__ = version("ffantasy")
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( determine_ext, js_to_json, ) class RTPIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?rtp\.pt/play/p(?P<program_id>[0-9]+)/(?P<id>[^/?#]+)/?' _TESTS = [{ 'url': 'http://www.rtp...
import re import os import requests as rq from bs4 import BeautifulSoup def html_to_bbcode(string): def sub_fun(tag): allowed = { 'i': 'i', 'b': 'b', 'em': 'i', 'strong': 'b' } content = tag.group(1).split(' ') tag_name = content[0] attrs = {} if len(content) > 1: for pair in content[1:]: ...
import sys from PyQt5.QtWidgets import QApplication from gui.main_window import MainWindowApp from migrations.migration_executor import MigrationExecutor if __name__ == '__main__': migration = MigrationExecutor() migration.start() app = QApplication(sys.argv) ex = MainWindowApp() sys.exit(app.ex...
''' Library to handle the manipulation and generation of CWL tool ''' import warnings warnings.warn( "The cwlgen module is deprecated, please use " "cwl-utils >= 0.4: https://github.com/common-workflow-language/cwl-utils", DeprecationWarning, stacklevel=2 ) # Import ------------------------------ ...
# -*- coding: utf-8 -*- """ CenturyLink Cloud Module ======================== .. versionadded:: Oyxgen The CLC cloud module allows you to manage CLC Via the CLC SDK. :codeauthor: Stephan Looney <slooney@stephanlooney.com> Dependencies ============ - clc-sdk Python Module - flask CLC SDK ------- clc-sdk can be i...
# bot implementation import discord from discord.ext import commands # class DndBotClient(discord.Client): class DndBotClient(commands.Bot): async def on_ready(self): print(f"logged in as {self.user} (ID: {self.user.id})") print("------") async def on_member_join(self, member): guil...
# # cache test by moriya@runserver.jp # from pathlib import Path import datetime import responder wd = Path(__file__).parent api = responder.API(templates_dir=wd/'templates') myamya_jpg = Path('static/img/myamya.jpg') def file_timestamp(p): return datetime.datetime.fromtimestamp(p.stat().st_mtime, tz=datetime.tim...
"""Update UserBot code Syntax: .update""" import git from contextlib import suppress import os import sys import asyncio # -- Constants -- # IS_SELECTED_DIFFERENT_BRANCH = ( "looks like a custom branch {branch_name} " "is being used:\n" "in this case, Updater is unable to identify the branch to be updated...
# -*- coding: utf-8 -*- import torch import torch.nn as nn import segmentation_models_pytorch as smp class Generator_with_Refin(nn.Module): def __init__(self, encoder): """Generator initialization Args: encoder: an encoder for Unet generator """ super(Generator_with_R...
""" Parse YAML config file & update JupyterHub config. Config should never append or mutate, only set. Functions here could be called many times per lifetime of a jupyterhub. Traitlets that modify the startup of JupyterHub should not be here. FIXME: A strong feeling that JSON Schema should be involved somehow. """ i...
#!/usr/bin/python3 import logging import re from collections import deque from copy import deepcopy from hashlib import sha1 from typing import Any, Dict, List, Optional, Set, Tuple, Union import solcast import solcx from requests.exceptions import ConnectionError from semantic_version import NpmSpec, Version from so...
import os import re from colicoords import load from addict import Dict def gen_paths(src): for d in os.listdir(src): pth = os.path.join(src, d) if os.path.isdir(pth): yield from gen_paths(pth) else: yield pth def load_dirs_to_dict(src, client, regex=''): file...
r""" Interface to LiE LiE is a software package under development at CWI since January 1988. Its purpose is to enable mathematicians and physicists to obtain on-line information as well as to interactively perform computations of a Lie group theoretic nature. It focuses on the representation theory of complex semisi...