content
stringlengths
5
1.05M
# WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4 import enum import winsdk _ns_module = winsdk._import_ns_module("Windows.Devices.Printers") try: import winsdk.windows.foundation except Exception: pass try: import winsdk.windows.foundation.collections except Except...
# Generated by Django 2.0.5 on 2018-05-28 02:37 from django.db import migrations, models import django.db.models.deletion import djstripe.fields class Migration(migrations.Migration): dependencies = [ ('djstripe', '0025_auto_20180528_0237'), ] operations = [ migrations.CreateModel( ...
import FreshProxyList as proxy proxy.init_proxy_list(5) proxy.write_to_file() print('\n\nFresh proxies:\n') for proxy in proxy.proxyList: print(proxy)
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import itertools from fvcore.common.benchmark import benchmark from tests.test_cameras_alignment import TestCa...
# -*- coding: utf-8 -*- # @Author: aadityac15 # @Date: 2019-10-15 22:03:53 # @Last Modified by: aadityac15 # @Last Modified time: 2019-11-18 15:53:06
#!/usr/bin/python # -'''- coding: utf-8 -'''- import sys import os import time from random import randint from PySide2 import QtCore, QtWidgets, QtGui from PySide2.QtCore import Signal from resources import * import traceback class ProgramImageButton(QtWidgets.QAbstractButton): def __init__(self, program, size, sin...
import numpy from ReID_net.Log import log def shift_im(im, offset): return shift(im, offset, "reflect", None) def shift_lab(lab, offset, void_label): return shift(lab, offset, "constant", void_label) def generate_video(im, lab, n_frames, max_speed, void_label): speed = (numpy.random.rand() * 2 - 1.0) * max_...
# Kelas Node class Node: # Konstruktor kelas def __init__(self, name:str, parent:str): self.name = name self.parent = parent self.g = 0 # Distance to start node self.h = 0 # Distance to goal node self.f = 0 # Total cost # Pengecekan node yang sama def __eq__(self...
# fzz2fz # convert one or multiple Fritzing files from fzz to fz format # Author: Andrea Bianchi, 2019 # Usage # python fzz2fz.py -f file[s] -o outputDir import argparse, sys, os, os.path, re, zipfile, shutil def moveAllFz (newBaseName, fromDir, toDir): # move fz to output id= 0 for root, dirs, fi...
from django.test import TestCase, RequestFactory from product.views import products_paginated # Create your tests here. class ProductTestClass(TestCase): def test_generic(self): self.assertEquals("h","h")
import math def even(num: int = 2) -> bool: # Чётное ли чесло if (num % 2) == 0: return True return False def min_cal(l: list) -> int: # Минимальное значение на графике - 2 или 1 # в зависимости от чётно ли чесло return min(l) # min_num = min(l) if even(min_num): return ...
from dataclasses import dataclass from typing import Any, Optional from commanderbot_lib.options.abc.cog_options import CogOptions @dataclass class FaqOptions(CogOptions): database: Optional[Any] = None prefix: Optional[str] = None
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2021, Cisco Systems # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r""" --- module: network short_description: Manage Network objects of NetworkSettings description: - API to get DHCP and DNS cente...
from distutils.core import setup def readme(): try: with open('README.rst') as f: return f.read() except IOError: return '' setup( name='empiricaldist', version='0.5.0', author='Allen B. Downey', author_email='downey@allendowney.com', packages=['empiricaldist']...
import prettytable table = prettytable(['No', 'Name', 'ARC', 'Date', 'Phone']) table.align = '1' table.add_row(['1', 'Naing', '0909', 'Friday', '0909']) print(table)
""" Automatic Init file """ from app.logic.mailing.models.StackedMailModel import StackedMailEntry
""" API Server """ import logging from typing import List from fastapi import FastAPI import pydantic as pdt import uvicorn import yaml from sni.conf import CONFIGURATION as conf from sni.utils import object_from_name app = FastAPI() class RouterConfig(pdt.BaseModel): """ Basic router configuration ""...
import re from .core import _capabilities, current_session, send as _send, send_and_recv as _send_and_recv def is_native(): return bool(current_session(False)) def alert(message, title=None, strict=False): session = current_session(strict) if session: _send(dst=session['src'], type='alert', tit...
# -*- coding: utf-8 -*- from __future__ import absolute_import import copy import re import six from bson import DBRef, ObjectId from pymongo import MongoClient as Connection from .collection import DummyCollection from .exceptions import DoesNotExist from .options import _Options class ModelBase(type): """Met...
from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfdevice import PDFDevice from pdfminer.layout import LAParams from pdfminer.con...
# Generated by Django 2.2.15 on 2020-10-22 10:57 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone def delete_existing_fetch_intentions(apps, schema_editor): FetchIntention = apps.get_model('scheduler', 'FetchIntention') Fe...
import abc import datetime as dt import logging from time import sleep from typing import Generator, List import config import queries from elastic import ElasticsearchLoader from models import Film, Genre, Person, ShortFilm, ShortGenre, ShortPerson from postgres import PostgresProducer from state import State from ut...
from datetime import datetime, timedelta, timezone from enum import Enum import os from io import BytesIO import sys import socket import argparse import netrc import getpass import logging import time import ssl import paho.mqtt.client from PIL import Image import ascii_magic from requests import exceptions from we...
import json import numpy as np import os import cv2 def loadLabel(path): path = path + 'label/' + 'label.json' with open(path,'r') as load_f: load_dict = json.load(load_f) dataLabel = [] for i in range(len(load_dict)): dataLabel.append(load_dict[str(i)]) dataLabel = np.array(da...
from consoleInterpreter import * from server import DispatchServer from sockethelpers.packet import Packet HOST = "localhost" # HOST to listen on PORT = 2000 # PORT to listen on ds = DispatchServer(HOST, PORT) cc = CommandConsole() @cc.command(["help"]) def chelp(x): return str(cc) @cc.command(["list"],...
from GitHubClient import GitHubClient def test_create_valid_class(): user = 'user-id' client = GitHubClient(user) assert client.user == user def test_valid_contribution(): user = 'jersson' client = GitHubClient(user) contributions = client.contributions() assert contributions is not Non...
from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler from tornado.web import StaticFileHandler, HTTPError from tornado import gen import os import json class JuliaPackageAssetServer(IPythonHandler, StaticFileHandler): def initialize(self, *args): self.root = "" ...
import xml.etree.ElementTree as ETree from collections import OrderedDict escaped_symbol_patterns = OrderedDict([ ('|=', '_ior_op_'), ('&=', '_iand_op_'), ('+=', '_iadd_op_'), ('-=', '_isub_op_'), ('*=', '_imul_op_'), ('/=', '_idiv_op_'), ('::', '_namespace_'), (':', '_col_'), ('<=', '_le_'), ('>=', '_ge_')...
def print_sign(n): """ Prints the sign of the input number :param n: the input integer :return: None """ if n < 0: print(f'The number {n} is negative.') elif n > 0: print(f'The number {n} is positive.') else: print(f'The number {n} is zero.') if __name__ == '__m...
# coding=utf-8 from betamax import Betamax from functools import wraps def configure_betamax(api, **additional_apis): with Betamax.configure() as config: config.cassette_library_dir = 'tests/fixtures/cassettes' config.default_cassette_options['match_options'] = ['method', 'uri', 'body'] ...
# helpers to quickly gather information out of the configuration # database, other sources can be used as well. def get_public_ip(devs, devname, interface_name, interface_number): """ quick helper for getting a devices public interface address """ type = devs[devname].device_type.cli.ned_id.split(':')...
# Don't forget to support cases when target_text == '' def calc_cer(target_text, predicted_text) -> float: # TODO: your code here raise NotImplementedError() def calc_wer(target_text, predicted_text) -> float: # TODO: your code here raise NotImplementedError()
import random def roll_1d4(): return roll_dice(4) def roll_1d6(): return roll_dice(6) def roll_1d8(): return roll_dice(8) def roll_1d10(): return roll_dice(10) def roll_1d12(): return roll_dice(12) def roll_1d20(): return roll_dice(20) def roll_1d100(): return roll_dice(100) def ...
import os from pathlib import Path # Absolute path to the parent directory of this Python package ROOT_PATH = Path(os.path.abspath(__file__)).parent.parent # Path to the directory in which the user outputs will be saved OUTPUT_PATH = ROOT_PATH / 'user-outputs' # Create the output dir in advance os.makedirs(OUTPUT_PATH...
from __future__ import absolute_import, division from __future__ import print_function import autograd.numpy as np import autograd.numpy.random as npr from autograd import grad from autograd.misc.optimizers import adam import autograd.scipy.linalg as ss import scipy.linalg def compute_barycenter(means, kerns, T=1000, ...
# container-service-extension # Copyright (c) 2018 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause from collections import namedtuple import datetime import logging from logging.handlers import RotatingFileHandler from pathlib import Path from container_service_extension.common.constants.ser...
import pyrogram from pyrogram import Client, filters from pyrogram.types import User, Message import os import requests @Client.on_message(filters.command("handwrite")) async def text(bot, message): text = str(message.text) chat_id = int(message.chat.id) file_name = f"{message.chat.id}.jpg" length = ...
from gym.spaces import Box, Discrete, MultiDiscrete import logging import ray import ray.experimental.tf_utils from ray.rllib.agents.ddpg.ddpg_tf_policy import ComputeTDErrorMixin, \ TargetNetworkMixin from ray.rllib.agents.dqn.dqn_tf_policy import postprocess_nstep_and_prio from ray.rllib.agents.sac.sac_ensemble_...
""" tn3270.emulator ~~~~~~~~~~~~~~~ """ from enum import Enum from itertools import chain import struct import logging from .datastream import Command, WCC, Order, AID, parse_outbound_message, \ format_inbound_read_buffer_message, \ format_inbound_read_modified_message,...
#!/usr/bin/python # -*- coding: utf-8 -*- # 通联数据机密 # -------------------------------------------------------------------- # 通联数据股份公司版权所有 © 2013-2019 # # 注意:本文所载所有信息均属于通联数据股份公司资产。本文所包含的知识和技术概念均属于 # 通联数据产权,并可能由中国、美国和其他国家专利或申请中的专利所覆盖,并受商业秘密或 # 版权法保护。 # 除非事先获得通联数据股份公司书面许可,严禁传播文中信息或复制本材料。 # # DataYes CONFIDENTIAL # ------...
# File Transfer model #2 # # In which the client requests each chunk individually, thus # eliminating server queue overflows, but at a cost in speed. from __future__ import print_function import os from threading import Thread import zmq from zhelpers import socket_set_hwm, zpipe CHUNK_SIZE = 250000 PIPELINE = 10 ...
from avidaspatial import * import pytest from matplotlib.testing.decorators import image_comparison @pytest.mark.mpl_image_compare def test_visualize_environment(): fig = plt.figure() env = "tests/example_environment.cfg" environment = parse_environment_file(env, (11, 5)) environment = convert_world_t...
r1 = float(input('Insira o valor da primeira reta: ')) r2 = float(input('Insira o valor da segunda reta: ')) r3 = float(input('Insira o valor da terceira reta: ')) if r1 <= 0 or r2 <= 0 or r3 <= 0: print('Os valores não podem ser negativos!!!') elif r1 >= r2+r3 or r2 >= r1+r3 or r3 >= r1+r2: print('Os valores ...
from getrealty import settings, sqlConnect import os config = settings.config myPath = os.path.dirname(os.path.abspath(__file__)) def test_sqlwherewithpercents(): config['defaults']['SQL_WHERE'] = 'WHERE OwnerAddr LIKE "%C/O%"' config['defaults']['WORK_DIR'] = myPath + \ '/test_files/test_sql_where_...
# YouTube Scraper # Setting up the directory import os os.getcwd() # present directory os.chdir("....\\Web Scraping\\YouTube") # changing the directory # Importing the libraries import pandas as pd from selenium import webdriver # Enter the search keywords search_keyword = input('Enter your search keyword:...
def longest_consec(arr: list, k: int) -> str: if not arr or k > len(arr) or k <= 0: return '' consecutive_strings: list = [] for i in range(len(arr) - k + 1): consecutive_strings.append(f'{"".join(arr[i:k+i])}') return max(consecutive_strings, key=len)
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'about_widget.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_AboutForm(object): def setupUi(self, AboutForm): AboutFor...
# pylint: disable=line-too-long """ Handles docker compose """ import sys from sh import ErrorReturnCode from lib.docker_tools import docker_compose from lib.tools import show_status def set_up(pg_version, es_version): """ Start containers """ compose = docker_compose(pg_version, es_version) show_sta...
import pytest from app import aws_pinpoint_client from flask import current_app def test_send_sms_successful_returns_aws_pinpoint_response(notify_api, mocker): boto_mock = mocker.patch.object(aws_pinpoint_client, '_client', create=True) mocker.patch.object(aws_pinpoint_client, 'statsd_client', create=True) ...
#! /usr/bin/env python #This script will plot the historical, mri, and ncar outputs # for a single vegetation variable from a regional run. Each specified # PFT will have a subplot, and the standard deviation will be displayed as # a translucent range around the average (mean) line. import subprocess import netCDF4 a...
""" Utililty objects for the polynomial modules. This module provides: error and warning objects; a polynomial base class; and some routines used in both the `polynomial` and `chebyshev` modules. Error objects ------------- - `PolyError` -- base class for this sub-package's errors. - `PolyDomainError` -- raised when ...
#!/usr/bin/env python """ Transform financial symbol listings from the FinnHub format to Fuse.js format. """ import sys import json if (len(sys.argv) < 2): print(f"usage: {sys.argv[0]} filename") sys.exit() with open(sys.argv[1]) as infile: data = infile.read() data = json.loads(data) for chunk in data: ...
import pytest # noqa from django.test import TestCase import common.blocks.centered_text as common class CenteredTextBlockTests(TestCase): def setUp(self): """ Sets up necessary variables """ super(CenteredTextBlockTests, self).setUp() self.block = common.CenteredTextBlock() def tes...
from django.apps import AppConfig class FlyConfig(AppConfig): name = 'fly'
# Covid Statistics Parser by @Hageru-Ray from requests import get from bs4 import BeautifulSoup as bs4 class Coronavirus: def __init__(self): self.url = 'https://www.worldometers.info/coronavirus/' self.data = '' self.date_update = '' self.total_cases = '' s...
try: from setuptools import setup except: from distutils.core import setup config = { 'description': 'Moncli, a pythonic/DDD client for Monday.com', 'author': 'Andrew Shatz, Trix Solutions', 'url': r'https://github.com/trix-solutions/moncli', 'download_url': r'https://github.com/trix-solutions/...
def test_sm_gazneftetorg_include_eic_yestoday(app): app.testhelpersm.refresh_page() app.session.open_SM_page(app.smPurchases) app.session.ensure_login_sm(app.username, app.password) app.session.ensure_login_sm(app.username, app.password) app.session.open_SM_page(app.smPurchases) app.testHelpe...
#!/usr/bin/env python ############################################################################ ## ## Copyright (C) 2004-2005 Trolltech AS. All rights reserved. ## ## This file is part of the example classes of the Qt Toolkit. ## ## This file may be used under the terms of the GNU General Public ## License version ...
# -*- coding: utf-8 -*- """Utility functions.""" import csv import logging import os import sys import turicreate as tc csv.field_size_limit(sys.maxsize) LOGGER = logging.getLogger(__name__) def condense_csv(in_file, out_file, columns, header=True): """copying only columns from in_file to out_file""" if...
import time import pandas as pd from pdtimeout.timeout.time_decorator import time_apply def test_time_apply(): df = pd.DataFrame({'number': [1, 0.5, 0.2, 2, 0.3]}, index=[0, 2, 4, 6, 8]) expected_result = pd.Series([1, 0.5, 0.2, 2, 0.3], index=[0, 2, 4, 6, 8]) @time_apply() def sleep_and_triple(row)...
import cc3d.CompuCellSetup as CompuCellSetup from .CellInitializerSteppables import CellInitializer CompuCellSetup.register_steppable(steppable=CellInitializer(frequency=100)) CompuCellSetup.run()
from jax.lax import while_loop from jax import custom_jvp from optimism.JaxConfig import * from optimism.material.MaterialModel import MaterialModel from optimism.material import Hardening from optimism import TensorMath from optimism import ScalarRootFind from jax.scipy.linalg import solve, expm # props PROPS_E ...
# ***************************************************************** # Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description: Section class # # # Modifications: # Date Name Modification # ---- ---- ...
""" ******************************************************************************** objects ******************************************************************************** .. currentmodule:: compas_rhino.objects .. rst-class:: lead Objects provide a high-level way to interact with both COMPAS and Rhino objects in ...
/* Hi, this is my first multi line comment */ from io import BytesIO from pdfdocument.document import PDFDocument import requests import json import datetime import os dir = os.getcwd() /* Since, we are using api provided by CIRCL.lu, querying the REST API via python lib requests. Then, we load the result to json s...
from flask import Flask, render_template, jsonify, request from backend.model_bilstm import BILSTM_Controller from backend.model_generator import LSTMG_Controller from backend.model_nb import MultiNB_Controller from flask_cors import CORS import json app = Flask(__name__, template_folder="./dist", ...
import logging from pathlib import Path from pygls.server import LanguageServer from pygls.lsp.methods import ( TEXT_DOCUMENT_DID_OPEN, TEXT_DOCUMENT_DID_CHANGE, ) from pygls.lsp.types import ( Diagnostic, DiagnosticSeverity, Range, Position, DidOpenTextDocumentParams, DidChangeTextDocu...
from PIL import Image, ImageEnhance import cv2 im = Image.open("pi.png") enhancer = ImageEnhance.Sharpness(im) enhanced_im = enhancer.enhance(16) enhanced_im.save("done1.png") # import cv2 # import numpy as np # img = cv2.imread('enhanced.opencv_frame_0.png',0) # equ = cv2.equalizeHist(img) # res = np.hstack((img,e...
import tkinter as tk import tkinter.ttk as ttk from ttkthemes import ThemedStyle class Main(): def __init__(self,master): master.geometry('500x500') master.title('DioCar Controller') self.button_1 = ttk.Button(root,text='Start Car !',takefocus = False,command=self.start_car).grid(ro...
def unique(data) -> list: res = [] for x in data: if x not in res: res.append(x) return res def repeat(x,n) -> list: res=[] for i in range(n): res.append(x) return res def frequency_sort(items) -> list: elements = unique(items) freq = [items.count(e) f...
from __future__ import absolute_import, unicode_literals from abc import ABCMeta from six import add_metaclass from virtualenv.create.creator import Creator from virtualenv.create.describe import Describe @add_metaclass(ABCMeta) class VirtualenvBuiltin(Creator, Describe): """A creator that does operations itse...
### # Copyright (c) 2002-2004, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of co...
""" jupyter convert """ from __future__ import print_function import sys import re from nbconvert import HTMLExporter def main(asset_dir, jupyter_file, inc_height): """ convert jupyter file to html :params jupyter_file: juptyer file path """ html_exporter = HTMLExporter(template_name='classic') ...
from adapters.on_off_switch_adapter import OnOffSwitchAdapter from adapters.contact_adapter import ContactAdapter from devices.sensor.door_contact import DoorContactSensor from adapters.generic.motion_sensor import MotionSensorAdapter from adapters.dimmable_bulb_adapter import DimmableBulbAdapter from adapters.dimmable...
import gym import numpy as np from kalah.kalahboard import KalahBoard from kalah.kalahagentfactory import KalahAgentFactory class KalahEnv(gym.Env): """ A Kalah environment for OpenAI gym """ metadata = {'render.modes': ['human']} _board = None def __init__(self): pass def _get...
# coding=utf-8 from src.data_structure.data_structure import ListNode class Solution: """ 求两个单链表之和 """ def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode: """ Time: O(n), Space: O(1) :param l1: :param l2: :return: """ p = dummy = ...
import nltk import re nltk.download('punkt') REPLACEMENTS = { u"\u2018": "", # Start smart quotes u"\u2019": "", u"\u201c": '', u"\u201d": '', u"\u2014": ' - ', # Em dashes '"': '', } REJECTS = ['-'] class Tokenizer: EOS = "<eos>" EOS_EQUIVALENT = r'^[\.!?]$' SINGLE_CHAR = r'^[\W_-]$' def tok...
import lab as B import numpy as np from .data import AbstractGenerator, DataGenerator from .. import _dispatch __all__ = ["MixtureGenerator"] class MixtureGenerator(AbstractGenerator): """A mixture of data generators. Args: *gens (:class:`.data.DataGenerator`): Components of the mixture. se...
from unittest import TestCase from gcexport import resolve_path class Tests(TestCase): def test_resolve_path_1(self): actual = resolve_path("root", "sub/{YYYY}", "2018-03-08 12:23:22") self.assertEqual("root/sub/2018", actual) actual = resolve_path("root", "sub/{MM}", "2018-03-08 12:23:22...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Zoe Agent Manager - https://github.com/RMed/zoe_agent_manager # # Copyright (c) 2014 Rafael Medina García <rafamedgar@gmail.com> # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated...
from passlib.hash import bcrypt from sqlalchemy import select from app.database.core import db_session from app.users.entities import User class UserRepo: @classmethod def get_user(cls, user_id: int) -> User | None: """ Get an user with the given ID. :param user_id: The user's ID. ...
# -*- coding: utf-8 -*- # Copyright 2021 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) """Feature matching loss modules.""" import torch import torch.nn.functional as F class FeatureMatchLoss(torch.nn.Module): """Feature matching loss module.""" def __init__( self, av...
import sc2,random from sc2 import run_game,maps,Race,Difficulty from sc2.player import Bot,Computer from sc2.constants import * class Main(sc2.BotAI): async def on_step(self,iteration): await self.distribute_workers() await self.chain() await self.chain_0() await self.chai...
""" This module has all the helper functions for atlas """ import json, yaml, ast import sys, traceback, os import memcache import threading import logging import datetime from threading import Lock import collections from collections import defaultdict class AtlasHelper: def __init__(self): self.output_...
# -*- coding: utf-8 -*- from .adqltranslator import ADQLQueryTranslator __all__ = ["ADQLQueryTranslator"]
''' 1 - Crie uma função que exibe uma saudação com os parametros saudação e nome. 2 - Crie uma função que recebe 3 numeros como parametros e exiba a soma entre eles. 3 - Crie uma funçao que receba 2 números. O primeiro é um número o segundo um percentual (ex. 10%). Retorne (Return) o valor do primerio número somando ...
from rest_framework import serializers from core.models import Project, ActivityJournal, Registry from django.contrib.auth.models import User class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('project_name', 'description', 'user') class ActivityJournalS...
from __future__ import unicode_literals from .responses import SimpleServiceCatalogResponse url_bases = ["https?://servicecatalog.(.+).amazonaws.com", "https?://servicecatalog.(.+).amazonaws.com.cn"] url_paths = {"{0}/$": SimpleServiceCatalogResponse.dispatch}
import numpy as np from numpy import dot def init_matvec(N, local_N, T): local_A = np.empty((local_N, N), T) Ax = np.empty(N, T) local_Ax = np.empty(local_N, T) return local_A, Ax, local_Ax def init_vecvec(local_N, T): local_a = np.empty(local_N, T) local_b = np.empty(local_N, T) return ...
# -*- coding: utf-8 -*- from lambdaz import _ def test_mod(): """Ensures that add works correctly.""" mod = (_ % 3)._ assert mod(25) == 1 def test_rmod(): """Ensures that add works correctly.""" mod = (_ % 3)._ rmod = (25 % _)._ assert mod(25) == rmod(3)
# -*- coding: utf-8 -*- # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
import builtins import functools import operator __all__ = ['_1', '_2', '_3', '_'] class Lambda(object): def __init__(self, func, name=None): self.func = func if name is None: self.__name__ = repr(self.func) else: self.__name__ = name def __repr__(self): ...
# This script creates the competition intensity values for the weighted total trade networks # Importing required modules import numpy as np import pandas as pd # Reading in the data main_data = pd.read_csv('C:/Users/User/Documents/Data/Pollution/pollution_data.csv') # Creating a list of all nations ...
from typing import Optional, Callable, List from confident.config_source import ConfigSource from confident.loaders.source_loader_base import SourceLoader class LoaderManager: def __init__( self, settings_obj: object, source_priority: List[str], init_settings_calla...
import torch from torch import nn #, cuda, backends, FloatTensor, LongTensor, optim #from torch.autograd import Variable import torch.nn.functional as F from sacapp import app out_sz = 1 class SACModel(nn.Module): def __init__(self, emb_szs, n_cont, out_sz, szs, drops, emb_drop, y_range): super().__init_...
import json import re from enum import Enum from tradingbot.components.broker import IG_API_URL # Set global variables used in fixtures TEST_DATA_IG = "test/test_data/ig" TEST_DATA_AV = "test/test_data/alpha_vantage" TEST_DATA_YF = "test/test_data/yfinance" IG_BASE_URI = IG_API_URL.BASE_URI.value.replace("@", IG_API_...
import os import time from osgeo import ogr from osgeo import osr #import pandas as pd def reprojectShp2Shp(inShapefile, outLayerPath, OutPutProjection=3035, LayerName="DummyLayerName", ReturnProjectionTransform=False): # set geometry type before you ...
# -*- coding: utf-8 -*- """Management command to create DKIM keys.""" from __future__ import print_function, unicode_literals import os from django.core.management.base import BaseCommand from django.utils.encoding import smart_text from modoboa.lib import sysutils from modoboa.parameters import tools as param_too...
# Standard import argparse import time # 3rd Party import zmq # Local import DataModel # Create arg parser parser = argparse.ArgumentParser() parser.add_argument('--id', required=True, type = int, default=1, help='Publisher ID') # Parse the args args = vars(parser.parse_args()) context = zmq.Context() socket = c...
from __future__ import print_function import os import sys print(sys.path) sys.path.append(os.path.dirname(os.getcwd())) print(sys.path) from show3d_balls import showpoints import argparse import numpy as np import torch import torch.nn.parallel import torch.utils.data from torch.autograd import Variable from pointnet...