content
stringlengths
5
1.05M
from fabric.api import run, quiet from braid import succeeds, cacheInEnvironment @cacheInEnvironment def distroName(): """ Get the name of the distro. """ with quiet(): lsb = run('/usr/bin/lsb_release --id --short', warn_only=True) if lsb.succeeded: return lsb.lower() ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_acp-calendar ------------ Tests for `acp-calendar` models module. """ import datetime import os from unittest import mock from django.test import TestCase from django.test import override_settings from acp_calendar.initial_data import get_holiday_type_list, g...
load("//:plugin.bzl", "ProtoPluginInfo") ProtoCompileInfo = provider(fields = { "label": "label object", "plugins": "ProtoPluginInfo object", "descriptor": "descriptor set file", "outputs": "generated protoc outputs", "files": "final generated files", "protos": "generated protos (copies)", ...
import concurrent.futures import urllib.request import time URLS = ['http://www.foxnews.com/', 'http://www.cnn.com/', 'http://europe.wsj.com/', 'http://www.bbc.co.uk/', 'http://some-made-up-domain.com/', 'http://www.nytimes.com', 'http://www.facebook.com', 'http:...
#!/usr/local/uvcdat/bin/python # Functions to convert between representations of energy flux and # water flux (precipitation and evoporation) variables. # TODO: perhaps move the physical constants used here to atmconst.py. # These are: # - latent heat of vaporization (water) # - density (water...
from random import choice #============================================================================== """ Split a String in Balanced Strings Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it in the maximum amount of balanced strings. Return the ...
# -*- coding:utf-8 -*- # author: donttouchkeyboard@gmail.com # software: PyCharm import openpyxl from style.default import ExcelFontStyle from core.base import TableCommon if __name__ == '__main__': """ 二级表头示例 """ wb = openpyxl.Workbook() ws = wb.active wb = TableCommon.excel_write_commo...
#!/usr/bin/env python # coding=utf8 ''' Created on Jul 7, 2012 @author: gf ''' import os import Util import ethtool def GetInfoString(): active_interfaces = ethtool.get_active_devices() all_interfaces = GetInterfaceList() for i in active_interfaces: if ethtool.get_flags('%s' % i) & ethtool.IFF_PO...
''' Created on Jan 24, 2013 @author: mdickson ''' import inworldz.maestro.uuid as genuuid import inworldz.util.user as user import inworldz.util.estate as estate import inworldz.util.properties as DefaultProperties import inworldz.maestro.MaestroStore as store from inworldz.maestro.ServiceBase import ServiceBase fro...
import math import textClasses def title_word_feature(title, processed_text): """ List of values from 0 to 1 rating the number title words that appear in the sentence""" title_word_feature_values = [] # Calculate the number of common words with the title that the sentence has word_intersection = [s...
""" """ import os import numpy as np import pandas as pd import xarray as xr from osgeo import gdal from src.utils.constants import ( REGIONS, LANDCOVER_MAP, LANDCOVER_PERIODS, LANDCOVER_PADDING ) if __name__ == "__main__": # Project's root os.chdir("../..") for region in REGIONS: ...
import fnmatch from functools import wraps def asgi_cors_decorator( allow_all=False, hosts=None, host_wildcards=None, callback=None ): hosts = hosts or [] host_wildcards = host_wildcards or [] # We need hosts and host_wildcards to be b"" hosts = set(h.encode("utf8") if isinstance(h, str) else h f...
from __future__ import division, print_function import numpy as np from scipy.constants import pi from numpy.fft import fftshift from scipy.fftpack import fft, ifft try: import accelerate jit = accelerate.numba.jit autojit = accelerate.numba.autojit complex128 = accelerate.numba.complex128 float64...
class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: c = 0 allowed = set(allowed) for word in words: # word = set(word) for letter in word: if letter not in allowed: break else: ...
#!/usr/bin/python import sys, ctypes """ rdi contains argc rsi contains argv (in reverse) - Note rdi decrements """ def echo_args(): # See function 'echo_args' in echo.asm global rdi, rsi, rdx, stack stack.append(rdi) # "push" stack.append(rsi) # "push" ## Stack alignment?? rsp = index or ...
from abc import ABC, abstractmethod from zpy.api.reponse import Builder from zpy.api.stages import Decrypt from zpy.logger import g_log from zpy.api.errors import ErrorBuilder from flask import Flask from typing import Any from flask.wrappers import Request, Response from zpy.utils.Encryptor import AESEncryptor import ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from maskrcnn_benchmark.modeling.box_coder import BoxCoder from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist from maskrcnn_benchmark.structures.boxlist_ops...
from __future__ import print_function import argparse import shutil import torch import torchvision import random import os import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.tensorbo...
""" These test cover Google searches """ import pytest from pages.result import GoogleResultPage from pages.search import GoogleSearchPage @pytest.mark.parametrize('phrase', ['nintendo', 'xbox', 'steam']) def test_basic_google_search(browser, phrase): search_page = GoogleSearchPage(browser) result_page = Goog...
from modern_greek_accentuation.accentuation import is_accented, where_is_accent, put_accent, count_syllables,\ put_accent_on_the_antepenultimate, put_accent_on_the_penultimate, remove_all_diacritics, put_accent_on_the_ultimate from modern_greek_accentuation.syllabify import modern_greek_syllabify from modern_gree...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import warnings from builtins import str from typing import Any, Dict, Optional, Text from rasa.nlu.extractors.entity_synonyms import EntitySynonymMapper cl...
import numpy as np import torch import random from skimage import io, transform import torch.nn.functional as F from torchvision import transforms torch.manual_seed(17) random.seed(42) class Resize(object): """Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired ou...
import argparse # import paraview modules. from paraview.web import pv_wslink from paraview.web import protocols as pv_protocols from paraview import simple from wslink import server from enlil import EnlilDataset # ============================================================================= # Create custom PVServe...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('all/', views.BlogList.as_view(), name='blog-list'), path('bloggers/',views.BlogAuthorList.as_view(), name='blogauthor-list'), path('bloggers/<int:pk>',views.BlogAuthorDetail.as_view(),name='bloga...
def main(): #fh, abs_path = mkstemp() antImages = 4000 first = 4 second = 4 newFileName = '%s_%s_bench_door_%s'%(first, second, antImages) with open(newFileName + '_local.txt','w') as new_file: with open('4_4_bench_door_4000_final.txt') as old_file: lines = old_file.readlin...
# Generated from Java9.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .Java9Parser import Java9Parser else: from Java9Parser import Java9Parser # This class defines a complete listener for a parse tree produced by Java9Parser. class Java9Listener(ParseTreeListener): ...
import argparse import pysam from ragtag_utilities.utilities import reverse_complement """ Like bedtools getfasta, but use the gff ID attribute as the FASTA header and always force strandedness. """ def main(): parser = argparse.ArgumentParser(description="Get fasta sequences from a GFF file") parser.add_...
"""Runs inference on clips much longer than 1s, by running a sliding window and aggregating predictions.""" from argparse import ArgumentParser from config_parser import get_config import torch import numpy as np import librosa from utils.misc import get_model from tqdm import tqdm import os import glob import json ...
import flask import json import inspect from .handle import Resource from .route import RouteFactory from .utils import Logger from .error import RequestError from .db import TinyBDDatabase class App(object): def __init__(self, base_route, db=None): self.base_route = base_route self.debug = True ...
# Copyright 2016 Google 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 agreed to in writing, ...
from django.test import TestCase from base.models import Comic, Character, Creator, Story from rest_framework.test import APIClient from rest_framework import status from django.urls import reverse class ComicTestCase(TestCase): """Test suite for the api views.""" def setUp(self): """Define the test ...
from collections import OrderedDict def contains_duplicate_extra_space(nums): seen = {} for i, val in enumerate(nums): if val in seen: return True else: seen[val] = i return False def contains_duplicate_2(nums, k): seen = dict() for i, val in enumerate(...
import math from kivy.properties import ObjectProperty, Clock, NumericProperty from cobiv.libs.magnet import Magnet from cobiv.modules.views.browser.eolitem import EOLItem class DraggableItem(Magnet): thumb = ObjectProperty(None, allownone=True) container = ObjectProperty(None) cell_size = NumericPropert...
"""Submodule that handles the generation of periodic table information.""" from __future__ import annotations import typing from .atomic_masses import ATOMIC_MASSES def atomic_symbols_to_mass(atoms: typing.Sequence[str]) -> list[float]: """Converts atomic symbols to their atomic masses in amu. Parameters ...
# # Copyright (C) 2009 Google Inc. 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 conditions and ...
# -*- coding: utf-8 -*- """ Created on Wed Jul 27 10:55:34 2016 The plain vanila implementation of Recurrent Neural Network @author: yaric """ import time import datetime from random import uniform import numpy as np import scipy.io as sio class RNN(object): def __init__(self, n_features, n_outputs, n_neur...
from baiji.serialization import json from baiji.serialization.json import JSONDecoder class BlmathJSONDecoder(JSONDecoder): def __init__(self): super(BlmathJSONDecoder, self).__init__() self.register(self.decode_value) def decode_value(self, dct): from blmath.value import Value ...
class Solution: def nthUglyNumber(self, n): """ :type n: int :rtype: int """ if n < 1: return 0 ugly = [0]*n ugly[0] = 1 i2 = i3 = i5 = 0 nm_2, nm_3, nm_5 = 2, 3, 5 for i in range(1, n): ugly[i] = min(nm_2, nm_3,...
def slices(series, length): if length < 1 or length > len(series): raise ValueError("length too high") i = 0 result = [] while i+length <= len(series): result.append(series[i:i+length]) i+=1 return result
name = input("What is your name?\n") print ("Hello", name)
from keras.datasets import mnist import os from pandas import DataFrame from PIL import Image from autokeras.utils import ensure_dir ensure_dir('mnist/train') ensure_dir('mnist/test') (x_train, y_train), (x_test, y_test) = mnist.load_data() # x_train = x_train.reshape(x_train.shape + (1,)) # x_test = x_test.reshape(...
from django.http import HttpResponse # from django.shortcuts import render # Create your views here. def home(request): return HttpResponse('Olá Django')
import os import subprocess if os.environ.get("HEXA_FEATURE_FLAG_S3FS", "false") == "true": for bucket_name in os.environ.get("AWS_S3_BUCKET_NAMES", "").split(","): path_to_umount = os.path.join(f"/home/jovyan/s3-{bucket_name}") subprocess.run( [ "umount", ...
"""Returns compiled regex from regular expression.""" import re import pytest from mklists.returns import compile_regex # pylint: disable=anomalous-backslash-in-string # These are just tests... def test_compile_regex(): """Returns compiled regex from simple string.""" regex = "NOW" assert isinstance(co...
from __future__ import print_function, division import scipy #Import Require Libraries import matplotlib.pyplot as plt import cv2 import pandas from keras.applications.vgg16 import VGG16 from keras.models import Sequential from keras.layers import Dense,Dropout from keras.layers import LeakyReLU from kera...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright (c) 2019, Digi International, Inc. # # 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 # to use, copy, modify, merge, pu...
#write a function to convert decimal number to binary, octal and Heaxdecimal equivalent n = input("Enter the Decimal") print("BINARY EQUIVALENT",bin(n)) print("OCTAL EQUIVALENT",oct(n)) print("HEXADECIMAL EQUIVALENT",hex(n))
from microbit import * import time while True: temp_c = pin1.read_analog() / 10.23 - 20 temp_f = int(temp_c * 9 / 5 + 32) display.scroll(temp_f) time.sleep(0.5)
from argparse import Namespace, ArgumentParser import os import torch from torch import nn from torch.nn import functional as F from torchvision import datasets import torchvision.transforms as transforms from utils import datautils import models from utils import utils import numpy as np import PIL from tqdm import t...
from flask import Flask , request , jsonify , make_response from flask_cors import CORS import pymysql #import config from config import db_host, db_user, db_passwrd, db_db, config_domain from check_encode import random_token, check_prefix from display_list import list_data from auth import auth shorty_api = Flask(__...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from beanmachine.ppl.experimental.gp.kernels import all_kernels from beanmachine.ppl.experimental.gp.likelihoods import all_likelihoods __...
# 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 u...
from django.urls import path from . import views app_name = 'search' urlpatterns = [ path('theorem', views.SearchTheoremView.as_view(), name='index'), ]
from rest_framework import viewsets from rest_framework.response import Response from rest_framework.decorators import action from rest_framework.authentication import BasicAuthentication from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from databa...
from django.urls import path from . import views urlpatterns = [ path('config-creator/', views.config_creator, name='config_creator'), path('data-generator/', views.data_generator, name='data_generator'), ]
# 导入需要的包文件 from flask import Blueprint, request from flask_restx import Api, Resource """ 创建一个蓝图,相当于创建项目组成的一部分,主要是方便我们管理自己的项目; 比如你的项目由很多个子项目构成,那么把为每一个子项目创建一个蓝图来创建对应的接口,好过于 把所有的接口都放在同一个.py文件吧! 这里创建蓝图Blueprint类还有很多其他的参数可选,大家可以看Blueprint类的源码,里面介绍的很清晰,英文不好的童鞋 请自觉学习英文; """ app_one_api = Blueprint('app_one_api', __name__)...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
import numpy as np import statistics import pandas as pd import time import os from sklearn.metrics import f1_score, accuracy_score from sklearn.multiclass import OneVsRestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix from sklearn.svm import SVC from sklearn...
#!python3 a = (x for x in range(3)) print(next(a)) print(next(a)) print(next(a)) try: print(next(a)) # -> raises StopIteration except StopIteration: print("StopIteration raised")
import torch import torch.nn as nn from torch.autograd import Variable from torch import optim import torch.nn.functional as F class FFNet(nn.Module): def __init__(self, input_size, output_size, hidden_size=64): super(FFNet, self).__init__() # one hidden layer self.fc1 = nn.Linear(input_s...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 解法一:44 ms 13.9 MB import queue class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] ...
from __future__ import annotations import typing as t from functools import wraps from graphql import GraphQLArgument from graphql import GraphQLBoolean from graphql import GraphQLEnumType from graphql import GraphQLField from graphql import GraphQLFloat from graphql import GraphQLID from graphql import GraphQLInputF...
# this_dict={ # "brand":'Ford', # "model":'Mutang', # "year": 1964 # } # print(this_dict) # #### # # Access items # x=this_dict['model'] # print(x) # ## Access items with get method # x=this_dict.get('model') # print(x) # ########### # # Change value in dictionary # this_dict['year']=2019 # print(this_d...
from __future__ import absolute_import, division, print_function, unicode_literals import six import sys from echomesh.util.registry.Registry import Registry def register_module(class_path, *modules, **kwds): module = sys.modules[class_path] registry = Registry(class_path, class_path=class_path, **kwds) ...
# Copyright 2020 Akamai 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 agreed to...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # =========================================================================== # # Project : MLStudio # # Version : 0.1.0 # # File : regression.py ...
from django import forms from django.contrib.auth.models import User class POSTForm(forms.Form): username = forms.CharField( label='Username', max_length=30, help_text='Enter a unique name for your login', widget=forms.TextInput(attrs={ 'required': 'required', 'title': 'Enter a unique name for your...
#!/usr/bin/env python # encoding: utf-8 # # Stylus, Copyright 2006-2009 Biologic Institute # # 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....
from datetime import datetime from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from freezegun import freeze_time from core.models import CoffeType, Harvest from core.serializers...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright 2015 Pascual Martinez-Gomez # # 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 # ...
""" Color definitions for various charts https://htmlcolorcodes.com/color-chart/ """ colors = { 'orange1': '#E74C3C', 'blue1': '#1B4F72', 'blue2': '#2874A6', 'blue3': '#3498DB', 'blue4': '#85C1E9' }
# coding=utf-8 import time import asyncio import logging from asyncio import CancelledError import aiohttp import async_timeout from freehp.extractor import extract_proxies log = logging.getLogger(__name__) class ProxySpider: def __init__(self, config, loop=None): self._proxy_pages = config.get('proxy...
"""open_discussions constants""" from rest_framework import status PERMISSION_DENIED_ERROR_TYPE = "PermissionDenied" NOT_AUTHENTICATED_ERROR_TYPE = "NotAuthenticated" DJANGO_PERMISSION_ERROR_TYPES = ( status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN, ) ISOFORMAT = "%Y-%m-%dT%H:%M:%SZ"
# from apps.ots.event.signal_event import SignalEvent from apps.ots.strategy.risk_manager_base import RiskManagerBase class NaiveRiskManager(RiskManagerBase): def __init__(self): self.refl = '' def get_mkt_quantity(self, signalEvent): return 100
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2018-2021 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # # All Rights Reserved. # """ System Inventory Kubernetes Application Operator.""" import copy import docker from eventlet.green import subprocess import glob import grp import fun...
"""Functions for parsing the measurement data files""" import yaml import pkgutil from flavio.classes import Measurement, Observable from flavio._parse_errors import constraints_from_string, errors_from_string from flavio.statistics import probability import numpy as np from math import sqrt import warnings def _load...
# Generated by Django 2.2.13 on 2020-07-15 13:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("licenses", "0002_import_license_data"), ] operations = [ migrations.AlterModelOptions( name="legalcode", options={"...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import CreateNewEvent, CreateNewParticipant from .models import Event,Attendee from .utils import check_event,generate_event_url, get_event_by_url from creator.tasks import generate_certificates def is_logged_in...
import os import numpy as np from typing import Any, Dict import torch from torch.utils.data import Dataset from core.utils.others.image_helper import read_image class CILRSDataset(Dataset): def __init__(self, root_dir: str, transform: bool = False, preloads: str = None) -> None: self._root_dir = root_d...
# -*- coding: utf-8 -*- """ Contains RabbitMQ Consumer class Use under MIT License """ __author__ = 'G_T_Y' __license__ = 'MIT' __version__ = '1.0.0' import pika from . import settings from .exceptions import RabbitmqConnectionError class Publisher: """Used to publish messages on response queue""" def _...
from .jira.client import JiraClient from .gitlab.client import GitLabClientWrapper as GitLabClient
import sys sys.path.append("../src") import numpy as np import seaborn as sns from scipy.stats import pearsonr from scipy.special import binom import matplotlib.pyplot as plt from matplotlib import gridspec from mpl_toolkits.axes_grid1.inset_locator import inset_axes import gnk_model import C_calculation import utils ...
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2021, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Copyright (c) The Lab of Professor Weiwei Lin (linww@scut.edu.cn), # School of Computer Science and Engineering, South China University of Technology. # A-Tune is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan ...
import os from aws_cdk import ( core, aws_ec2 as ec2, aws_cloudformation as cloudformation, aws_elasticache as elasticache, ) class ElastiCacheStack(cloudformation.NestedStack): def __init__(self, scope: core.Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) se...
import numpy as np from .base import BaseLoop from .utils import EarlyStopping class BaseTrainerLoop(BaseLoop): def __init__(self, model, optimizer, **kwargs): super().__init__() self.model = model self.optimizer = optimizer ## kwargs assignations self.patience = kwargs.g...
# Multiple 1D fibers (monodomain), biceps geometry # This is similar to the fibers_emg example, but without EMG. # To see all available arguments, execute: ./multiple_fibers settings_multiple_fibers_cubes_partitioning.py -help # # if fiber_file=cuboid.bin, it uses a small cuboid test example (Contrary to the "cuboid" e...
import random from io import StringIO import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns sns.set_style("darkgrid") def str_convert_float(df): columns = df.select_dtypes(exclude="number").columns for col_name in columns: unique_values = df[col_name].unique() ...
# Copyright 2013, Mirantis 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 agre...
import json from pyramid.view import view_config @view_config(route_name='home') def home(request): # https://docs.pylonsproject.org/projects/pyramid/en/latest/api/request.html # Response response = request.response response.content_type = 'application/json' response.status_code = 200 # body ...
#!/usr/bin/env python # -*- coding: utf8 -*- def btcSupplyAtBlock(b): if b >= 33 * 210000: return 20999999.9769 else: reward = 50e8 supply = 0 y = 210000 # reward changes all y blocks while b > y - 1: supply = supply + y * reward reward = int(re...
import sys,os import gdal from gdalconst import * # Get georeferencing information from a raster file and print to text file src = sys.argv[1] fname_out = sys.argv[2] ds = gdal.Open(src, GA_ReadOnly) if ds is None: print('Content-Type: text/html\n') print('Could not open ' + src) sys.exit(1) # Get the g...
""" Base functions and classes for linked/joined operations. """ from typing import Mapping, Callable, Union, MutableMapping, Any import operator from inspect import signature from functools import partialmethod EmptyMappingFactory = Union[MutableMapping, Callable[[], MutableMapping]] BinaryOp = Callable[[Any, Any], ...
import os import re import boto3 s3 = boto3.resource('s3') s3_client = boto3.client('s3') def maybe_makedirs(path, exist_ok=True): """Don't mkdir if it's a path on S3""" if path.startswith('s3://'): return os.makedirs(path, exist_ok=exist_ok) def smart_ls(path): """Get a list of files fro...
from sqlalchemy import Column, TIMESTAMP, Float, Integer, ForeignKey, String from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta, declared_attr '''SQLAlchemy models used for representing the database schema as Python objects''' Base: DeclarativeMeta = declarative_base() class Watered(Base): ...
import math from .settings import pi, PI_HALF, nearly_eq from .point import Point from .basic import GeometryEntity class LinearEntity(GeometryEntity): def __new__(cls, p1, p2=None, **kwargs): if p1 == p2: raise ValueError( "%s.__new__ requires two unique Points." % cls.__nam...
''' This program reads the message data from an OVI backup file (sqlite) create for a NOKIA N95 phone and writes them formated as XML to stdout. The backup file is usually located in: C:\Users\<user>\AppData\Local\Nokia\Nokia Suite/ \ Messages/Database/msg_db.sqlite Note: the exported ...
import torch.nn as nn import math class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, stride=1): super().__init__() self.residual_function = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)...
import unittest from parameterized import parameterized as p from solns.karatsubaMultiply.karatsubaMultiply import * class UnitTest_KaratsubaMultiply(unittest.TestCase): @p.expand([ [3141592653589793238462643383279502884197169399375105820974944592, 2718281828459045235360287471352662497757247093699...