content
stringlengths
5
1.05M
import unittest #import env from canvas import Canvas from color import Color class TestCanvas(unittest.TestCase): def test_canvas(self): c = Canvas(10, 20) self.assertEqual(c.width, 10) self.assertEqual(c.height, 20) def test_write_pixel(self): c = Canvas(10, 2...
""" Collect email information """ import os import subprocess import json import base64 from flask import current_app from pathlib import Path from ..functions import get_python_path class Email: """ Set up an email """ config_path = None __addresses = [] __ccs = [] __files = ...
__version__ = "0.0.10" from .core import *
""" Program to classify the snps based on the following: 1. whether are at stop codons 2. where are located on a functional gene sequence 4. whether are synonymous (S) or non-synonymous (N) 5. whether are fourfold degenerate sites (S) or non-degenerate sites (N) and count the number the number for each of the class, an...
from typing import List def _get_data_array(filename: str) -> List[int]: lines = open(filename, 'r').readlines() ints = [int(i.strip()) for i in lines] return ints def _validate(factors: List[int], target: int) -> bool: sorted_factors = sorted(factors) left = 0 right = len(sorted_factors) - 1 ...
class Solution: @lru_cache(None) def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]: if n % 2 == 0: return [] if n == 1: return [TreeNode(0)] ans = [] for leftCount in range(n): rightCount = n - 1 - leftCount for left in self.allPossibleFBT(leftCount): for...
from pypy.lang.smalltalk import objspace space = objspace.ObjSpace() def ismetaclass(w_cls): # Heuristic to detect if this is a metaclass. Don't use apart # from in this test file, because classtable['w_Metaclass'] is # bogus after loading an image. return w_cls.w_class is space.classtable['w_Metaclas...
import numpy as np import pandas as pd df = pd.DataFrame(np.arange(5*4).reshape(5,4)) df sampler = np.random.permutation(5) sampler df.take(sampler) sampler_col = np.random.permutation(4) sampler_col sampler_col = np.random.permutation(4) sampler_col df[sampler_col] df.sample(3) df.sample(3, axis=0) df.sample(3, axis=...
'''save/load from S3 routines ------- ''' from __future__ import print_function, division, unicode_literals from .omas_utils import * from .omas_core import save_omas_pkl, load_omas_pkl, ODS def _base_S3_uri(user): return 's3://omas3/{user}/'.format(user=user) # -------------------------------------------- #...
""" Pascal sections to be inserted in code. Copyright (C) 2019, Guillaume Gonnet This project is under the MIT license. """ from typing import List, Text def gen_bird_array(envs: List, name: Text): "Generate a static array for bird directions / species." upper = name.capitalize() count = sum(int("sam...
from __future__ import annotations from typing import TYPE_CHECKING, Optional from ._base import TelegramObject if TYPE_CHECKING: # pragma: no cover from .photo_size import PhotoSize class VideoNote(TelegramObject): """ This object represents a video message (available in Telegram apps as of v.4.0). ...
import datetime from django.db import models from django.utils import timezone #My comments: #Each model is represented by a class that subclasses django.db.models.Model. #Each model has a number of class variables, each of which represents a database field in the model. #Each field is represented by an instance of...
''' Class to access documents and links stored in the hdf5 file. ''' import h5py class CorpusHDF5(): def __init__(self, path): self.f = h5py.File(path, 'r') def get_article_text(self, article_id): return self.f['text'][article_id] def get_article_title(self, article_id): retur...
str1 = 'Hello' print(str1.endswith('e', 0, 2)) print(str1.endswith('o', 0, 4)) #True (substring 'He' (0 to 1 index) ends with 'e') #False (substring 'Hell' (0 to 3 index) does not end with 'o')
# # Copyright 2015, 2016 Human Longevity, 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 agr...
# coding=utf-8 """ OneForAll默认配置 """ import pathlib import warnings # 禁用所有警告信息 warnings.filterwarnings("ignore") # 路径设置 relative_directory = pathlib.Path(__file__).parent.parent # OneForAll代码相对路径 module_dir = relative_directory.joinpath('modules') # OneForAll模块目录 third_party_dir = relative_directory.joinpath('thir...
import logging import math import sys from datetime import timedelta from typing import TextIO, Sequence, Tuple, NoReturn import attr import httpx from cached_property import cached_property from fire import Fire @attr.s(auto_attribs=True, kw_only=True) class BaseCommand: stream: TextIO = sys.stdout def _pr...
#!/usr/bin/python3 import rospy from std_msgs.msg import Int16MultiArray, String, Bool import numpy as np import pickle import os import yaml import h5py from utils.audio import get_mfcc from utils.model import get_deep_speaker from utils.utils import batch_cosine_similarity, dist2id n_embs = 0 X = [] y = [] def sav...
#!/user/bin/env python '''containsAlternativeLocations.py This filter return true if this structure contains an alternative location ''' __author__ = "Mars (Shih-Cheng) Huang" __maintainer__ = "Mars (Shih-Cheng) Huang" __email__ = "marshuang80@gmail.com" __version__ = "0.2.0" __status__ = "Done" class ContainsAlte...
import cv2 import gym import numpy as np from gym import spaces from PIL import Image from gym.wrappers.monitoring.video_recorder import VideoRecorder # https://github.com/chris-chris/mario-rl-tutorial/ class MyDownSampleWrapper(gym.ObservationWrapper): def __init__(self, env, image_size): super(MyDownSam...
from CameraOrMarker import * class Scenarios: def __init__(self, scenario): self.num_generated_samples = 217 self.std_corners_f_image = 0.3 self.marker_len = 0.162717998 # generate_solve_pnp_inputs options self.use_sigma_points = False self.use_dist_params = True...
"""Test SQL database migrations.""" from pathlib import Path from typing import Generator import pytest import sqlalchemy from pytest_lazyfixture import lazy_fixture # type: ignore[import] from robot_server.persistence.database import create_sql_engine from robot_server.persistence.tables import ( migration_tabl...
# coding: utf8 from __future__ import unicode_literals from ...symbols import LEMMA, PRON_LEMMA MORPH_RULES = { "PRON": { "jeg": {LEMMA: PRON_LEMMA, "PronType": "Prs", "Person": "One", "Number": "Sing", "Case": "Nom"}, "mig": {LEMMA: PRON_LEMMA, "PronType": "Prs", "Person": "...
# vim: set sw=4 ts=4 expandtab : from const import * import math from scipy import stats def teller(state, nstate): nchain = nstate['chain'] # mimic network unpredictability using random variable df = int(math.log10(nchain['txpending'] + 10)) rv = stats.chi2(df) #lazy_txs = int(0.01 * nchain['txp...
from mechanize import Browser from bs4 import BeautifulSoup import sys import re br = Browser() br.set_handle_robots(False) br.addheaders = [("User-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4275.0 Safari/537.36")] def product_search(keyword): br.open("ht...
from .test_languages import TestLanguages from .test_translator import TestTranslator
from setuptools import setup, find_packages PACKAGES = find_packages() with open("README.md", "r") as fh: long_description = fh.read() setup(name='python-neurostore', version='0.1', description='NeuroStore API wrapper', long_description=long_description, long_description_content_type="text...
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Pyglet GLSL Demo Dot3 Bumpmap Shader on http://www.pythonstuff.org # pythonian_at_inode_dot_at (c) 2010 # # based on the "graphics.py" batch/VBO demo by # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights re...
""" The wntr.metrics.hydraulic module contains hydraulic metrics. """ import wntr.network from wntr.network.graph import _all_simple_paths #from wntr.metrics.misc import _average_attribute import numpy as np import pandas as pd import networkx as nx import math from collections import Counter import logging logger = ...
import asyncio from typing import Union from pynput.keyboard import Key, KeyCode, Listener from core_modules.macro_handler import MacroHandler from core_modules.tray import Tray from global_modules import logs class KeyboardHandler: def __init__(self, macro_handler: MacroHandler, tray: Tray, loop: asyncio.Abstr...
import requests from slack.web.classes import messages def webhook_response(response_url: str, json=None): return requests.post(response_url, json=json) def basic_responder_response(text: str) -> messages.Message: return messages.Message(text=text)
from sly import Lexer, Parser from os import path from defs import * global curr_file, curr_text, error_occurred, curr_namespace, reserved_names def syntax_error(line, msg=''): global error_occurred error_occurred = True print() if msg: print(f"Syntax Error in file {curr_file} line {line}:")...
#!/usr/bin/env python # coding: utf-8 # # ML Pipeline Preparation # Follow the instructions below to help you create your ML pipeline. # ### 1. Import libraries and load data from database. # - Import Python libraries # - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/g...
#!/usr/bin/python # The templating engine and the parser for the dllup markup language are hereby # released open-source under the MIT License. # # Copyright (c) 2015 Daniel Lawrence Lu # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files ...
import argparse from datetime import datetime, timedelta import logging import os import pprint import random from config import DATETIME_FORMAT, EXPORT_PATH, GENDER_PREF_FUNCTIONS, AGE_PREF_FUNCTIONS,\ AGE_YOUNG_MID, AGE_MID_OLD, DEPARTMENTS, VENDORS, CATEGORIES, CATEGORIES_UNIQUE, DEVELOPMENT from converters.sum...
from pathlib import Path class DocsTranslateBaseException(Exception): pass class UnknownServiceError(DocsTranslateBaseException): def __init__(self, service_name: str) -> None: super().__init__(f'{service_name} service is unknown') class ConfigurationError(DocsTranslateBaseException): def __in...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import os, sys import numpy as np from cntk.device import set_default_device abs_p...
from __future__ import absolute_import, unicode_literals import logging import os import pytest from psd_tools.psd.filter_effects import (FilterEffects, FilterEffect, FilterEffectChannel, FilterEffectExtra) from ..utils import check_write_read, check_read_write, TEST_ROOT logger = logging.getLogger(__name__) @pyt...
from django import template from backoffice.models import * register = template.Library() @register.simple_tag def number_of_authors(request): qs = Author.objects.all() return qs.count() @register.simple_tag def number_of_questions(request): qs = Question.objects.all() return qs.count() @register....
#/usr/bin/python3 # -*- coding: utf-8 -*- import sys import getopt import re from itertools import * import time import json import csv import codecs import random as r import time import random import pandas as pd ##此程序用来将csv文件转成json格式
import logging import typing import ckan.plugins.toolkit as toolkit logger = logging.getLogger(__name__) @toolkit.side_effect_free def dcpr_request_list(context: typing.Dict, data_dict: typing.Dict) -> typing.List: logger.debug("Inside the dcpr_request_list action") access_result = toolkit.check_access( ...
""" Unit testing ============ Note: Tests for `ensemble.control.operational.reference` """ # ============================================================================ # STANDARD IMPORTS # ============================================================================ import pytest import numpy as np fr...
"""Test parallel deployment.""" # pylint: disable=redefined-outer-name from __future__ import annotations import platform import shutil from pathlib import Path from typing import TYPE_CHECKING, Generator import pytest from runway._cli import cli if TYPE_CHECKING: from click.testing import CliRunner, Result CU...
import unittest from mock import patch from todo import Todo, TodoManager class TestTodo(unittest.TestCase): def test_default(self): todo = Todo('foo') self.assertEqual(todo.task, 'foo') self.assertFalse(todo.done) def test_default_done(self): todo = Todo('bar', True) ...
from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences import os import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from tqdm import tqdm import math from sklearn.model_selection import train_test_split import pickle...
import scrapy from scrapy.crawler import CrawlerProcess class VersionSpider(scrapy.Spider): name = 'versions' custom_settings = { "FEED_FORMAT": "json", "FEED_URI": "data/%(name)s/%(time)s.json" } start_urls = ['https://docs.hortonworks.com/HDPDocuments/HDP3/HDP-3.1.0/release-notes...
from typing import Dict, Optional, Union from pyspark.sql import SparkSession, Column, DataFrame # noinspection PyUnresolvedReferences from pyspark.sql.functions import col from pyspark.sql.types import ( ArrayType, LongType, StringType, StructField, StructType, TimestampType, DataType, ) ...
""" The MIT License (MIT) Originally in 2020, for Python 3.x Copyright (c) 2021 Panos Achlioptas (ai.stanford.edu/~optas) & Stanford Geometric Computing Lab """ import torch import numpy as np import pandas as pd from PIL import Image from torch.utils.data import Dataset, DataLoader from ..evaluation.emotion_alignment...
""" Last edited: November 12 2020 |br| @author: FINE Developer Team (FZJ IEK-3) """ from FINE.component import Component, ComponentModel from FINE import utils from tsam.timeseriesaggregation import TimeSeriesAggregation import pandas as pd import numpy as np import pyomo.environ as pyomo import pyomo.opt as opt impor...
""" qstode.searcher ~~~~~~~~~~~~~~~ Whoosh search engine support. :copyright: (c) 2013 by Daniel Kertesz :license: BSD, see LICENSE for more details. """ import os import json import redis from whoosh.fields import ID, TEXT, KEYWORD, Schema from whoosh.analysis import RegexTokenizer, LowercaseFilt...
################################################################################ ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your op...
import math from PyQt5 import QtCore from PyQt5.QtCore import QUrl, QObject, pyqtSignal from PyQt5.QtGui import QMouseEvent, QColor from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import QDialog, QVBoxLayout, QWidget, QSlider, QGraphics...
# -*- coding: utf-8 -*- import abc from inspect import isfunction, signature from types import FunctionType from watson import di from watson.common.contextmanagers import suppress from watson.common import imports from watson.di.types import FUNCTION_TYPE class Base(di.ContainerAware, metaclass=abc.ABCMeta): ""...
from __future__ import print_function import json as json_lib from threading import Lock import requests.adapters import py42.settings as settings from py42._internal.compat import str from py42._internal.compat import urljoin from py42._internal.compat import urlparse from py42.exceptions import raise_py42_error fr...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2015-2018 by ExopyHqcLegacy Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ------...
import sys import SocketServer import ssl import struct import socket import comms def parse_table(): ret = {} ret["major"] = "bloodnok" ret["harry"] = "seagoon" return ret class listener(SocketServer.BaseRequestHandler): CMD_QUERY_ALL = 0 CMD_TRIGGER = 1 CMD_EXIT = 2 CMD_DISPLAY_SH...
from __future__ import absolute_import import blosc try: import cPickle as pickle_ except ImportError: import pickle as pickle_ import os import collections from . import report from . import object as object_ from . import path from os.path import join from os.path import isdir class PickleByName(object): ...
#!/usr/bin/python # -*- coding: utf-8 -* """ The MIT License (MIT) Copyright (c) 2015 Christophe Aubert 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 limit...
class BinarTree: def __init__(self,e): self._root = Node(e) pass def add_left(self, e): pass def add_roght(self, e): pass def replace(self, p, e): pass def delete(self, p): pass def attach(self,t1, t2): pass class Node: def __ini__(self,element, parent = None, left = None, right = None): ...
# Import libraries import numpy as np from flask import Flask, request, jsonify import nltk nltk.download('vader_lexicon') from nltk.sentiment.vader import SentimentIntensityAnalyzer app = Flask(__name__) @app.route('/api',methods=['GET', 'POST']) def predict(): # Get the data from the POST request. data = re...
def gcd(a, b): while b: t = b b = a % b a = t return a def f(): limit = 3000 print('computing GCD of all pairs of integers in [1, ' + repr(limit) + ']^2') x = limit while x > 0: y = limit while y > 0: gcd(x, y) # a = x # b = y # while b: # t = b # ...
import os import sys import random import tensorflow as tf import matplotlib.pyplot as plt import skimage from samples.sunrgbd import sun, dataset, sun_config from mrcnn.model import log import mrcnn.model as modellib from mrcnn import visualize ROOT_DIR = os.path.abspath("./") sys.path.append(ROOT_DIR) # To find l...
import csv import sqlite3 import os from HoundSploit.searcher.engine.utils import check_file_existence def create_db(): """ Create the database used by HoundSploit and hsploit """ init_path = os.path.abspath(os.path.expanduser("~") + "/.HoundSploit") db_path = os.path.abspath(init_path + "/hound_d...
import asyncio import logging import os import sys from argparse import SUPPRESS, ArgumentParser from typing import Callable, Dict, Mapping import yaml from aioregistry import ( AsyncRegistryClient, ChainedCredentialStore, DockerCredentialStore, default_credential_store, ) from tplbuild.cmd.base_build...
import logging import time import pytest import os from stepfunctions.workflow import Workflow from tests import config from tests.integration_tests.utils import VersionChecker, LineageChecker from tests.integration_tests.workflows import simple_pipeline,\ diff_output_workflow, \ condition_workflow, \ para...
#!/usr/bin/python3 # coding: utf-8 ################################################################################ # Apple PiのLCDとLEDへAmbientの状態を表示する # # 準備: # AmbientのKeyを(https://ambidata.io)で取得し、ambient_chidとambient_rkeyへ代入 # # Copyright (c) 2018-2019 Wataru KUNINO #########...
import numpy as np signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) fourier = np.fft.fft(signal) print(fourier) print(signal.size) freq = np.fft.fftfreq(signal.size, d=0.1) print(freq)
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-02-07 22:39 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mars', '0010_teammember_role'), ] operations = [ migrations.AlterModelOptions( ...
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ OEMC integrator for hybrid MC/MD simulations DESCRIPTION This module provides OEMC integrators for OpenMM. EXA...
import discord import random from discord.ext import commands from gameConfig import * import os coin = [0, 1] @bot.command() async def coinflip(ctx): embed = discord.Embed( title = "Coinflip💰", description = 'React with the emoji below to choose heads or tails \nHeads: 💸 \nTails: �...
# -*- coding: utf-8 -*- # cython: language_level=3 # Tanjun Examples - A collection of examples for Tanjun. # Written in 2021 by Lucina Lucina@lmbyrne.dev # # To the extent possible under law, the author(s) have dedicated all copyright # and related and neighboring rights to this software to the public domain worldwide...
import random import pandas as pd import numpy as np import matplotlib.pyplot as plt #%matplotlib inline import tensorflow as tf import keras.backend as K from keras.utils import to_categorical from keras import metrics from keras.models import Model, load_model from keras.layers import Input, BatchNormalizat...
""" convert prepared resnet model into tflite model run this python script in server root """ import argparse import os import tensorflow as tf from models import mobilenet, resnet50 from tensorflow import lite as tf_lite TFLITE_MODEL_DIR = '../client/app/src/main/assets' def convert_resnet() -> None: CHECKPOINT_...
# Copyright 1996-2018 Cyberbotics 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 in...
from __future__ import print_function import sys import os import runpy import traceback import contextlib import argparse from tracestack.handler import ExceptionHandler from tracestack.console import TracestackConsole def run(): """Runs the script provided by the arguments, using the tracestack exception ha...
""" Django settings for app project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ # pylint: disable...
""" Tyk API Management. """ from diagrams import Node class _Tyk(Node): _provider = "tyk" _icon_dir = "resources/tyk" fontcolor = "#2d3436"
# -*- encoding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict from h2o.utils.compatibility import * # NOQA from .model_base import ModelBase from .metrics_base import * # NOQA import h2o from h2o.expr import ExprNode class H2OWordEm...
from pymongo import MongoClient def mongo_client(): return MongoClient("database", 27017)
from msgpack import Packer COMMAND_SET_VERSION = 3 class CommandType: JumpToMain = 1 CRCRegion = 2 Erase = 3 Write = 4 Ping = 5 Read = 6 UpdateConfig = 7 SaveConfig = 8 ReadConfig = 9 GetStatus = 10 def encode_command(command_code, *arguments): """ Encodes a command of...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pylab as plt from utility.webdl import WebDLUtility from service.webdl import WebDLService from postprocessing.tools import plot_utility_model, utility_grid, save_model from postprocessing.cfg import * #%% df = pd...
XSym 0033 19e4fe6b5fba275cfa63817605c40e9f /anaconda2/lib/python2.7/types.py ...
import unittest import shutil import SimpleITK as sitk import numpy as np from typing import Union, Sequence from mnts.scripts.dicom2nii import * from mnts.scripts.normalization import * from mnts.filters import MNTSFilterGraph from mnts.filters.intensity import * from mnts.filters.geom import * from pathlib import Pa...
# -*- coding: utf-8 -*- from click.testing import CliRunner from simmate.command_line.workflows import workflows def test_database(): # make the dummy terminal runner = CliRunner() # list the workflows result = runner.invoke(workflows, ["list-all"]) assert result.exit_code == 0 # list the c...
# Copyright 2017 The BerryDB Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os BASE_FLAGS = [ '-Wall', '-Wextra', '-Werror', '-DUSE_CLANG_COMPLETER', # YCM needs this. '-xc++', # YCM needs this to avoid c...
# -*- coding: utf-8 -*- from twisted.internet.defer import Deferred from twisted.internet.protocol import ClientFactory, ServerFactory from twisted.internet import reactor from twisted.protocols.basic import LineReceiver from Screens.MessageBox import MessageBox from Tools import Notifications from GrowleeConnection ...
import unicodedata from django import forms from django.contrib.auth import authenticate, get_user_model, password_validation from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher from django.contrib.auth.tokens import default_token_generator from django.contrib.sites.shortcuts import get_c...
from typing import Union from requests import session, Session import json import os from models import ChallengeResult, ChallengeError BASE_URL = os.getenv('API_URL', 'https://soallpeach-api-soroosh.fandogh.cloud') session = Session() def get_session() -> Session: session.headers.update({ 'Authoriza...
#!/data2/zhangshuai/anaconda3/bin # -*- coding: utf-8 -*- import os import wave from pydub import AudioSegment import json wav_path = "/home/zhangshuai/kaldi-master/egs/biendata/Magicdata/audio/test" trans_path = "/home/zhangshuai/kaldi-master/egs/biendata/Magicdata/transcription/test_no_ref_noise" wav_segments_path ...
# encoding: utf-8 # 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")...
import os ## FIXME most of the path variables should come from env vars PWD = os.getcwd() OUTPUT_PATH= os.path.join(PWD, "CodeComb_Outputs") #FORMATS = ['.cpp'] DATA_PATH = os.path.join(PWD, "CodeComb_Data") DF_FILE = "df_corpus" DOC_EMB_PATH = os.path.join(OUTPUT_PATH, "doc_emb_" + DF_FILE) ANN_INDEX_PATH = os.pat...
import scrapy import re from .mirkcolorselector import sampler_function class DecjubaSpider(scrapy.Spider): name = "decjuba_products" start_urls = [ 'https://www.decjuba.com.au/collections/women/dresses', 'https://www.decjuba.com.au/collections/women/jackets', 'https://www.decjuba.com.a...
from cloudshell.devices.runners.autoload_runner import AutoloadRunner from vyos.flows.autoload import VyOSAutoloadFlow class VyOSAutoloadRunner(AutoloadRunner): def __init__(self, resource_config, cli_handler, logger): """ :param resource_config: :param cli_handler: :param logger...
""" Dada uma String "str", retorne true se nela possuir o mesmo número de ocorrências das strings "cat" e "dog". Ex.:(('catdog') → True; ('1cat1cadodog') → True; ('catcat') → False). """ def cat_dog(str): return str.count("cat") == str.count("dog") print(cat_dog("catdog"))
""" This file implements a general purpose best-first planner. --------------HOW TO INITIALIZE IT ------------- An instance of the planner is created using planner = Planner(s) where s is the initial state in the planning process. The planner needs five functions/methods to work properly. These functions can either...
import cv2 import apriltag # Функция для вывода изображения на экран def viewImage(image, window_name='window name'): cv2.imshow(window_name, image) cv2.waitKey(0) cv2.destroyAllWindows() # Считываем изображение и преобразуем его в grayscale tag = cv2.imread('/home/administrator/PycharmProjects/trial/si...
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import pytest from ezdxf.math import BSpline, global_bspline_interpolation, rational_bspline_from_arc, Vec3 def test_from_nurbs_python_curve_to_ezdxf_bspline(): from geomdl.fitting import interpolate_curve curve = interpolate_curve([(0, 0), (0, 10), ...
import itertools import numpy from matplotlib import pyplot from typing import Dict, Sequence, Tuple from warg import Number __all__ = [ "plot_errors", "masks_to_color_img", "plot_prediction", "bounding_box_from_mask", ] def plot_errors(results_dict: Dict, title: str) -> None: """ Args: ...
# -*- coding: utf-8 -*- import numpy import os from os.path import join import shutil import time import sys import math import json import utilities import matplotlib.pyplot as plt def get_num_antennas(ms): """.""" tb.open(ms + '/ANTENNA', nomodify=True) num_stations = tb.nrows() tb.close() retu...
# coding=utf-8 import datetime import json import time import redis import scrapy from pymongo import MongoClient from scrapy.http import Request from scrapy_redis.spiders import RedisSpider from biliob_spider.items import TagListItem from biliob_tracer.task import SpiderTask from db import db class TagAdderSpider...