text
stringlengths
3.07k
12.6k
# Copyright 2021 <NAME> <EMAIL> # # 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 writin...
# 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 from .. import _utilitie...
import sys class Sort: def __new__(self, array, algo, reverse=False): ''' args: :array: (list) : a python list :algo: (str): sorting algorithm type values supported are: 1.bubble 2.merge ...
# -*- coding: utf-8 -*- import re import os from collections import defaultdict from .graph import Graph problems_class = { 'b' : {'max' : 18}, 'c' : {'max' : 20}, 'd' : {'max' : 20}, 'e' : {'max' : 20}, 'others' : ['dv80.txt', 'dv160.txt', 'dv320.txt'] } ...
from bs4 import BeautifulSoup import pandas as pd import gspread from oauth2client.service_account import ServiceAccountCredentials from datetime import date episodeList = pd.read_csv('sg1-eps.csv') episodeList.columns = ['Episode Num', 'Title'] def get_filters(): # use creds to create a client to interact with...
import random from itertools import repeat import time as t #functions def m10maker(n): maker = True qwerty = 0 while maker == True: if qwerty == int((n - 1)/10) - 1: maker = False qwerty += 1 multiples_of_10.append((qwerty * 10)-1) def getplayersname...
import numpy as np import tensorflow as tf #сверточный слой def conv2d_layer(i, tensor, filter_shape, activation = tf.nn.relu, stride=1, zero_biases=False, zero_weights=False): with tf.variable_scope('conv-%d' % i): #размер весов [число строк, число столбцов, число входных каналов, число выходных каналов]...
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import authenticate, get_user_model from django import forms from .utils import should_disable_login, get_client_ip, is_researcher from easyaudit.models import LoginEvent from . import settings from .models import Partic...
from langid.langid import LanguageIdentifier, model from googletrans import Translator from limpieza import remover_acentos def detectar_lenguaje(texto, devolver_proba=False): """ Identifica el lenguaje en el que está escrito el texto de entrada. :param texto: Texto de entrada. :type texto: str :...
########################################################################## # # Copyright (c) 2012, <NAME>. All rights reserved. # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the f...
# # Copyright (c) 2019, 2021 by Delphix. All rights reserved. # import compileall import logging import os import py_compile import subprocess import sys from dlpx.virtualization._internal import file_util, package_util from dlpx.virtualization._internal.exceptions import SubprocessFailedError from dlpx.virtualizatio...
""" """ import os import sys import qute import fracture import functools # ------------------------------------------------------------------------------ # noinspection PyUnresolvedReferences,PyPep8Naming class FractureTray(qute.QSystemTrayIcon): def __init__(self, project_path, ...
# 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 # d...
"""Implementation of the intermediary layer between Shapely and GEOS This is layer number 2 from the list below. 1) geometric objects: the Python OO API. 2) implementation map: an abstraction that permits different backends. 3) backend: callable objects that take Shapely geometric objects as arguments and, with GE...
# Copyright 2010-2018 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 agreed to in writing...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : Ampel-plot/ampel-plot-app/AmpelPlot.py # License : BSD-3-Clause # Author : vb <<EMAIL>> # Date : 16.11.2021 # Last Modified Date: 19.11.2021 # Last Modified By : vb <<EMAIL>> import os, warnings, sys, psutil, PySimpl...
""" Command-line interface. """ # MIT License # Copyright (c) 2021-2022 <NAME> # 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 the rights ...
root = '/opt/pypractice/upload/' testers = {} # task/name.yaml def newtask(path): global testers import testmaker, yaml print('try',path) with open(path) as f: p = yaml.safe_load(f) t = testmaker.Tester(p) name = path.rsplit('/', 1)[-1].rsplit('.', 1)[0] testers[name] = t print('loade...
#!/usr/bin/env python3 import copy # Povolene knihovny: copy, math, collections # IB002 Domaci uloha 12. # # S relacemi se vetsina z vas setkala na predmetu Matematicke zaklady # informatiky. Relace na mnozine intuitivne popisuje vztah mezi prvky # teto mnoziny. Mejme treba relaci "byt kamaradem", kdy prvky A a B # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Name: PyAnime4K acwrapper Author: TianZerL Editor: K4Yt3X """ import ctypes import os import platform ac_lib = { "Windows": "ac.dll", "Linux": "libac.so", "Darwin": "libac.dylib", } curr_path = os.path.dirname(os.path.realpath(__file__)) if platform.sys...
from twisted.web2.test.test_server import BaseCase, BaseTestResource from twisted.web2 import resource from twisted.web2 import vhost from twisted.web2 import http, responsecode from twisted.web2 import iweb from twisted.web2 import stream from twisted.web2 import http_headers class HostResource(BaseTestResource): ...
import torch from torch import nn import math def create_mask(seq_len, device): """ Helper function to create a square mask Parameters ---------- seq_len : int length of the edge Returns ------- 2d tensor of the following shape 0 1 1 ... 1 0 0 1 ... 1 ... 0...
# # Copyright © 2020 Ingram Micro Inc. All rights reserved. # from copy import copy from numbers import Number from dj_rql.constants import FilterLookups, RQL_NULL, RQL_ORDERING_OPERATOR, RQL_SEARCH_PARAM, \ FilterTypes class RQLFilterDescriptionTemplate: BASE_TEMPLATE = '**{description}**\n\nlookups: {loo...
from zorro.di import has_dependencies, dependency from .xcb import Core, Rectangle from .commands import CommandDispatcher class Drag(object): start_distance = 5 def __init__(self, win, x, y): self.win = win if self.win.frame: self.win = self.win.frame self.drag_started ...
#!/usr/bin/env python # # Copyright (c) 2008 <NAME> # 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 ...
import cv2 import os import numpy as np import pickle from dataset_preparation import mean_method,load_pickle from tqdm import tqdm # ----- grid size adjusting ----- # def grid_adjust(init_grid, im_shape): h_im, w_im = im_shape if len(init_grid) == 1: grid = (init_grid[0], init_grid[0]) ret...
import typing import uuid from datetime import datetime class SetType: _all: typing.Set = set() def __init__(self, api_name: str, desc: str): self.name = str(api_name) self.desc = desc SetType._all.add(self) def __eq__(self, other): if not isinstance(other, Se...
from __future__ import absolute_import from thrift.protocol.TJSONProtocol import TJSONProtocol, JTYPES, CTYPES from thrift.Thrift import TType try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: import simplejson as json except ImportError: import json class TFastJSONP...
import sys import shutil import ruamel.yaml from ruamel.yaml.comments import CommentedSeq from pathlib import Path from collections import Mapping from ..__init__ import __rootdir__, __system__, __pyinstall__ yaml = ruamel.yaml.YAML() __ydoc = None def __dig_mapping(path): path = path.split('/') parent_maps...
# Copyright (c) 2021 Microsoft Corporation. Licensed under the MIT license. # Reimplemtened by <NAME> (<EMAIL>) # Adapted from https://github.com/jwyang/graph-rcnn.pytorch (<NAME>) and https://github.com/yikang-li/MSDN (Yikang Li) import numpy as np import torch import torch.nn as nn import torch.nn.functional as F fr...
# Code written entirely by <NAME> # Email: <EMAIL> # GitHub: https://github.com/EricAlcaide # Import modules/dependencies import random from copy import deepcopy # Create TicTacToe Class (OOP) class TicTacToe(): dims = 3 ends = [-1, 0, 1] # -1 if User wins, 0 if Draw, +1 if Computer wins exchange = {-1: "You W...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from textwrap import dedent from difflib import unified_diff from pathlib import Path from typing import Any import pytest from hydra.utils import get_class, instantiate from omegaconf import OmegaConf from configen.config import ConfigenConf, M...
# Copyright 2006 <NAME> and contributors # Copyright (C) 2009 <NAME> <<EMAIL>> # Copyright (C) 2010 <NAME> <<EMAIL>> # # 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....
from __future__ import division from __future__ import print_function import sys import os # disable autotune os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0' # add module path sys.path.append(os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, os.pardir))) import argparse import glob import logging logging.b...
#!/user/bin/env python from __future__ import print_function from __future__ import unicode_literals from getpass import getpass from pprint import pprint from napalm import get_network_driver from jinja2 import FileSystemLoader, StrictUndefined from jinja2.environment import Environment # from my_devices import d...
import re def validate_user_data(user): """ this funtion validates the user data """ user['username'] = user['username'].lower() if user['username'] == '': return {'warning': 'username is a required field'}, 400 # Check for empty email elif user['email'] == '': return {'warning'...
# Copyright (c) 2012 OpenStack Foundation. # 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...
# Copyright (c) 2020 PaddlePaddle 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 appli...
import pcre import re def print_removable_blocks(removable_line_blocks): print('[', end='') for i in removable_line_blocks: print('[', i[0], '-', i[-1], ']', end='') print(']') def get_non_overlapping_blocks_indexes(removable_line_blocks): # get only the outside for's and if's size = len(re...
import sys import os ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) sys.path.append(ROOT_PATH) from marko import Markdown from marko.renderer import Renderer from contextlib import contextmanager import time from Translator.TxyTranslator import TencentTranslate translator = TencentTransla...
import unittest from pychord import Chord from pychord.analyzer import get_all_rotated_notes, find_chords_from_notes, notes_to_positions class TestNotesToPositions(unittest.TestCase): def test_one(self): pos = notes_to_positions(["C"], "C") self.assertEqual(pos, [0]) def test_power(self): ...
""" A mini-implementation of an automatic serialiser-deserialiser for nested dataclass like class based on type annotations. Example:: In [14]: from dataclasses import dataclass ...: from typing import Optional, Union, List ...: Note that Author and Reviewer are isomorphic even if totally u...
# -*- coding: utf-8 -*- """ **中文文档** 此模块解决了什么问题? 回想一下, 每次你执行 ``aws cloudformation deploy`` 命令时, 你所做的是将 Template 中 定义的 Resource, 和上一次 Deploy 时 定义的 Resource 做比较, 得到 Change Set, 然后 实现这些 Changes. 而你在一次性将整个架构部署到多个环境中时, 你需要经历哪些步骤呢? 1. 或许, 你需要首先部署 dev 环境, 然后再部署 test / prod 环境. 2. 或许, 你的 dev 环境需要执行多次 ``aws cloudformation...
# -*- coding: utf-8 -*- # Copyright (c) 2017 <NAME>. # License: MIT, see LICENSE for more details. # ICMP packet construction, parsing, checksumming blatantly taken from # python-ping import array import socket import struct import sys import time import pyev ICMP = socket.getprotobyname('icmp') ICMP_ECHO_REPLY = ...
import os #import matplotlib import numpy as np import pykitti #matplotlib.use('Agg') #import matplotlib.pyplot as plt import yaml import cv2 import cmapy import math #import concurrent.futures from joblib import Parallel, delayed kitti_basedir = '/home/sa001/workspace/dataset/semantic_kitti/dataset/' #basedir = ...
import glob import os import sys import ftrace import argparse from ftrace import Ftrace, Interval from pandas import Series, DataFrame, MultiIndex, Timestamp from pandas.tseries.offsets import Micro LITTLE_CLUSTER_MASK = 0x0F BIG_CLUSTER_MASK = 0xF0 LITTLE_CPUS = ftrace.common.unpack_bitmap(LITTLE_CLUSTER_MASK) BIG...
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import os import ipdb import cmasher as cmr from scipy import stats from sklearn.metrics import precision_recall_curve, auc INPUT_SEC_PREFIX = 'input_seq_step_' PRED_SEC_PREFIX = 'prediction_at_output_step_' COLOR_CODE = ['r','g','b'] create_...
#!/usr/bin/env python3 import json import os import sys import optparse import xlsxwriter from docx import Document prog_VERSION = "0.1.0-dev" def parse_options(args=None, values=None): """ Define and parse `optparse` options for command-line usage. """ usage = """%prog -d docxs_in_FOLDER -o OUTPUT_...
""" <NAME> 10 April 2012 dan dot newman at mtbaldy dot us Altshell is a script to cause the outside perimeter of an object to be printed with the valve closed. The purpose is to allow downstream processing to identify gcode for the outside shells of an object by spotting segments to be printed with a closed valve sta...
# # This source file is part of appleseed. # Visit https://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2018 The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this softw...
#!/usr/bin/python3 import os import sys from optparse import OptionParser test_py = \ '''import os import time import struct import wallet import eosapi import initeos from eosapi import N from tools import cpp2wast from common import prepare, producer import debug as _debug print('please make sure you are running...
import datetime from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union from django.http import HttpResponse from django.utils.functional import Promise from typing_extensions import NotRequired, TypedDict ViewFuncT = TypeVar("ViewFuncT", bound=Callable[..., Htt...
# -*- coding: utf-8 -*- from collections import OrderedDict from django.utils import timezone from django.utils.translation import gettext as _ import pandas as pd import plotly.offline as plotly import plotly.graph_objs as go from core.utils import duration_string from reports import utils def sleep_pattern(inst...
import os import sys from docx.api import Document import openpyxl from shutil import copyfile from tkinter import filedialog from tkinter import * from tkinter import ttk import tkinter as tk templates = [] forms = [] forms_dir = "asdfghj" templates_dirs = [] alias_vals = {} conflicts = {} labels = [] def check_al...
import os import pytest from protean.domain import Domain from protean.domain.config import Config # config keys used for the TestConfig TEST_KEY = "foo" SECRET_KEY = "config" non_key = "not-a-key" def common_object_test(domain): assert domain.secret_key == "config" assert domain.config["TEST_KEY"] == "foo...
#!/usr/bin/env python3 # -*-coding: utf-8-*- # Neviim - 2017 # from pymongo import MongoClient import pymongo import datetime import hashlib import shutil import json import time import os # Kernel. class MonitoraPasta(object): """docstring para MonitoraPasta. Parametros: drOrigem = Diretorio ...
import numpy as np import torch from torch import nn from torch.utils.data import DataLoader from torch.nn.functional import softmax from torchvision import datasets, utils, transforms import matplotlib.pyplot as plt import os import time from models import NeuralNetwork, CNN from attack import attack from args import...
""" convert the data for "Uncertainty-Driven 6D Pose Estimation of Objects and Scenes from a Single RGB Image" @author: <NAME> <https://github.com/paroj> """ import os.path import glob import numpy as np import cv2 import read RENDER_OBJCOORDS = True # convert from the lineMOD coordinate system to the OpenCV CS t_...
import datetime from distutils import dir_util import os import pandas as pd import shutil import warnings def copytree(src, dst, symlinks=False, ignore=None): ''' Function to copy directories. ''' if not os.path.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = os.pa...
import atexit import glob import logging import os import random import re import signal import subprocess import sys import time import irc.client PYTHON = os.getenv('PYTHON', "python3") class Client(irc.client.SimpleIRCClient): def __init__(self): irc.client.SimpleIRCClient.__init__(self) self....
""" functions with "_static_" in name - correct proven examples of input output for knapsack problem So, for debugging funcs.py I used it for checking correct behavior, because output of "_static_" functions write in docstrings and we can compare strings with construction: .. code:: python from operator import at...
from copy import deepcopy import datetime import logging import re from .utilities import chunks LOG = logging.getLogger("logmole.types") class TimeType(object): """ given a string the class will generate a datetime.time object Object will automatically detect a time signature under specific conditions ...
import discord from discord.ext import commands import variables as var from functions import get_prefix import database as db class Extras(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def ping(self, ctx): await ctx.send( f"Pong 🏓! Response...
#!/usr/bin/env python # -*- coding: utf-8 import logging import re import tempfile from collections import namedtuple from datetime import datetime from threading import Thread from .image import Image LOG = logging.getLogger(__name__) FROM_PATTERN = re.compile(r"FROM\s+(?P<name>[\w./-]+)(:(?P<tag>[\w.-]+))?(\s+(?:A...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import json import time from argparse import ArgumentParser import numpy as np from collections import namedtuple from tqdm import tqdm TR_UPPER = {ord('i'): 'İ'} TR_LOWER = {ord('I'): 'ı'} Vocab = namedtuple('Vocab', ['idx_to_term',...
""" A module for loading tracks .pklz files and converting them to some formats """ from zipfile import ZipFile, ZIP_DEFLATED from os import remove from glob import glob import click from tracking import DetTrack from tracking_world import WorldTrack, WorldTrackingConfig from storage import load from folder import ru...
# -*- coding: utf-8 -*- """AiiDAlab basic widgets.""" from threading import Timer import ipywidgets as ipw import traitlets from aiidalab.app import AppRemoteUpdateStatus as AppStatus from aiidalab.config import AIIDALAB_REGISTRY from .themes import ThemeDefault as Theme class _StatusWidgetMixin(traitlets.HasTrait...
#!/usr/bin/env python3 """ kepler_uv.py - solve Kepler's problem using universal variables """ import pdb import warnings import numpy as np from astromath.overloads import astro_2norm from orbits.stumpff import stumpff_c, stumpff_s class OutputKepUV(object): """ Output data storage class for kep_uv rv (...
import warnings from collections import deque from typing import Dict, List, NamedTuple, Optional, Union import astroid class Interface: pass class PossibleInterfaceReference(str): pass TYPE_MAP: Dict[str, str] = { "bool": "boolean", "str": "string", "int": "number", "float": "number", ...
# -*- coding: utf-8 -*- # Vutils for Network import os, mechanize try: import cookielib except ImportError: import http.cookiejar as cookielib # --- # https://mechanize.readthedocs.io/en/latest/ # Example: # browser = Network.Browser() # browser.open("http://viclab.biz/") # print(browser.title()) # for fo...
#!/usr/bin/python from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.helpers import ModuleRes, CartridgeException, cartridge_errcodes from ansible.module_utils.helpers import get_control_console import os argument_spec = { 'restarted': {'required': False, 'type': 'bool'}, 'contro...
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.module import Module from torch.nn.parameter import Parameter class GraphConvolution(Module): """ Simple GCN layer, similar to https://arxiv.org/abs/1609.02907 """ def __init__(sel...
# Copyright (c) 2017-2018 Uber Technologies, 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 ...
"""collection of useful tools that help with setting up a pipeline Author: <NAME>""" import time import functools import numpy as np from scipy.io import loadmat from .stats import rm_outliers def compute_relatives(cond1, cond2, **kwargs): """Computes the relative changes. Parameters ---------- cond...
import re import os import pendulum from share import tasks from share.bin.util import command from share.harvest.scheduler import HarvestScheduler from share.models import SourceConfig def get_sourceconfig(name): try: return SourceConfig.objects.get(label=name) except SourceConfig.DoesNotExist: ...
import socket import struct import threading import signal import sys import os.path from manager.base import CONNECTION_TYPE_DATA, PACKAGE_TYPE_DATA, base DEFAULT_FILENAME = 'samples.txt' class DataThread(threading.Thread): """ Recieves data and writes to the given filehandle """ meta_info_size = ...
# import curses and GPIO import curses import os # Added so we can shut down OK import time # Import time module import threading # If we want things to happen after a button press, and carry on listening, we need threads. import RPi.GPIO as GPIO #set GPIO numbering mode and define output pins GPIO.setmode(GPIO.BOARD)...
import json import os import tensorflow as tf from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split data = load_iris() features = data['data'] labels = data['target'] X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=.3) def build_inputs(features...
# ============================================================================== # File : Korg.py # Author : <NAME> and <NAME> # Authored : 30 November 2019 - 13 March 2020 # Purpose : Primary runner for Korg tool # How to run: see docs/Korg.md for instructions # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!...
from typing import Dict, Union, Tuple, List from flask import current_app from flask_security import current_user from werkzeug.exceptions import Unauthorized, Forbidden PERMISSIONS = ["create-children", "read", "read-children", "update", "delete"] ADMIN_ROLE = "admin" ADMIN_READER_ROLE = "admin-reader" # constant...
### # Patched version of DEAP's creator, for better pickling of creator objects. # https://github.com/cmd-ntrf/deap-1/blob/metacreator/deap/creator.py # # Addresses open issue: # https://github.com/DEAP/deap/pull/76 # Hopefully DEAP will incorporate this soon. ### # This file is part of DEAP. # # DEAP i...
import tensorflow as tf import tensorflow_probability as tfp import numpy as np def get_latent_representation(image, encoder, decoder): """Optimise the latent represantation of an image to minimise the decoder reconstruction error""" # Set the starting point for optimization task z = tf.Variable(...
""" local settings, include settings from C++ code and fast transitions """ from collections import OrderedDict def get_local_settings(): """ local settings for C++ codes """ setting = { # end time "end_t": 0.763449999652352496, # critical time, after which print out more data ...
import glob import os import numpy as np import pytest from numpy.testing import assert_array_almost_equal, assert_equal from landlab import RasterModelGrid from terrainbento import BasicSt, BasicStTh, Clock, NotCoreNodeBaselevelHandler _th_params = { "water_erosion_rule__threshold": 1e-9, "infiltration_capa...
#!/usr/bin/env python # -*- coding: utf-8 -*- """MBLLEN: Multi-Branch Low-Light Enhancement Network. Fkey idea is to extract rich features up to different levels, so that we can apply enhancement via multiple subnets and finally produce the output image via multi-branch fusion. In this manner, image quality is improve...
import numpy as np from argparse import ArgumentParser from devito.logger import info from devito import Constant, Function, smooth, configuration from examples.seismic.acoustic import AcousticWaveSolver from examples.seismic import demo_model, AcquisitionGeometry def acoustic_setup(shape=(50, 50, 50), spacing=(15.0...
import sys import os from copy import copy, deepcopy import numpy as np import scipy as sp import scipy.sparse as spsparse import time class Timer(): def __init__(self, name='', start=True): self.name = name if start: self.start() def start(self): self.vals = [] se...
from keras.models import * from keras.layers import * from keras.optimizers import * import tensorflow as tf from keras import initializers from keras import regularizers from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras import backend as keras def mbLSTM(pretrained_weights=None, i...
""" Main application module. """ import sys import logging from argparse import ArgumentParser from weatherapp.core import config from weatherapp.core.formattermanager import FormatterManager from weatherapp.core.commandmanager import CommandManager from weatherapp.core.providermanager import ProviderManager class A...
from mpi4pyve import MPI import mpiunittest as unittest import arrayimpl def create_topo_comms(comm): size = comm.Get_size() rank = comm.Get_rank() # Cartesian n = int(size**1/2.0) m = int(size**1/3.0) if m*m*m == size: dims = [m, m, m] elif n*n == size: dims = [n, n] el...
# -*- coding: utf-8 -*- import os import random import pygame import carla from auto_ctrl import HUD, World, KeyboardControl from agents.navigation.basic_agent import BasicAgent HOST = '127.0.0.1' PORT = 2000 DATASET_NUM = 1 MAX_FRAMES = 500000 #max frmaes for each dataset # imgae must be small !! IMG_LENGTH = 600 IMG...
#!/usr/bin/env python3 import os import sys import json import argparse from urllib.request import urlopen from urllib.parse import urlencode from urllib.error import HTTPError def parse_args(): categories = ['business', 'entertainment', 'general', 'health', 'science', 'sports', 'technology'] ...
import os import sys import tempfile import uuid import zipfile from collections import Iterable import requests from defusedxml.lxml import fromstring from lxml import etree from docmaker.hooks import Hook def obfuscateTtf(fontstream, guid): outstream = bytearray(fontstream) _guid = uuid.UUID(guid) fo...
#!/usr/bin/env python3 import argparse import os import platform import shlex import subprocess PLUGIN_PATH=f'{os.getcwd()}/Packages/com.haphazard/Plugins' TENSORFLOW_PATH='' def run_cmd(cmd): args = shlex.split(cmd) subprocess.call(args, cwd=TENSORFLOW_PATH) def copy(from_tf, to_unity): subprocess.call...
import threading import socket import random from scapy.all import DNS, DNSQR, DNSRR, DNSRROPT TYPE = { 'ANY': 0, 'A': 1, 'NS': 2, 'MD': 3, 'MF': 4, 'CNAME': 5, 'SOA': 6, 'MB': 7, 'MG': 8, 'MR': 9, 'NULL': 10, 'WKS': 11, 'PTR': 12, 'HINFO': 13, 'MINFO': 14, ...
#!/usr/bin/env python3 """Program to publish a directory to an ftp target.""" import argparse import ftplib import logging import os import urllib.parse def _parse_and_validate_url(urlstr): url = urllib.parse.urlparse(urlstr, allow_fragments=False) if url.scheme != 'ftps': raise RuntimeError("Only f...
# Copyright 2014 Diamond Light Source 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 t...
#!/usr/bin/env python # # utilities.py - General utility functions # # February 2017, <NAME> # Copyright (c) 2015-2017, 2019 the COT project developers. # See the COPYRIGHT.txt file at the top-level directory of this distribution # and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt. # # This file is ...
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 11:28:33 2015 @author: Alberto """ import os import sys import numpy as np from collections import OrderedDict # TODO: # - Support "file" types parameters... How? # - Check value against provided lo and hi # - Handle the cases where one or both lo/hi are not provided...
from __future__ import print_function import os import sys import pyspark from pyspark import SparkContext from pyspark.sql import SparkSession from pyspark.sql.functions import udf from pyspark.sql.types import * sc = SparkContext() spark = SparkSession.builder.appName("Python Spark SQL basic example").getOrCreate...