content
stringlengths
5
1.05M
from flask import Flask, render_template, request import requests app = Flask(__name__) ## "GET" Method corresponds to page reload ## "POST" Method corresponds to api call using submit buttn @app.route('/', methods=["POST", "GET"]) def index(): city = "Howrah" url = 'https://api.openweathermap.org/data/2.5/we...
from builtins import chr, str def decode(b): """ Decode bytes as MUTF-8 See https://docs.oracle.com/javase/6/docs/api/java/io/DataInput.html#modified-utf-8 for more information :param b: bytes to decode :rtype: unicode (py2), str (py3) """ res = u"" b = iter(bytearray(b)) for...
# coding=utf-8 import math import torch from torch.nn.parameter import Parameter from .. import functional as F from .module import Module from .utils import _single, _pair, _triple class _ConvNd(Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, trans...
from uuid import uuid4 from app.database import DB class JsonBlob(DB.Model): blob_id = DB.Column(DB.CHAR(36), primary_key=True) payload = DB.Column(DB.Text()) def __repr__(self) -> str: return "<JsonBlob {blob_id}>".format(blob_id=self.blob_id) @staticmethod def add(payload): b...
# Copyright 2016 Cloudbase Solutions Srl # 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 r...
# Copyright (c) MONAI Consortium # 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, so...
# A plugin's setup symbol is supposed to be a function # which returns the plugin type. # # This plugin's setup symbol is not such a function. setup = 9
# -*- coding: utf-8 -*- """ 登录 2019.5.19 """ import pika import wx import doctor import patient class LoginFrame(wx.Frame): def __init__(self, parent, title): super(LoginFrame, self).__init__(parent, title=title, size=(250, 150)) self.InitUI() self.Centre() self.SetMinSize((250, 1...
# Natural Language Toolkit: Unit Tests # # Copyright (C) 2001-2012 NLTK Project # Author: Edward Loper <edloper@gradient.cis.upenn.edu> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT # # $Id$ """ Unit tests for the NLTK modules. These tests are intended to ensure that changes that we make to...
#!/usr/bin/env python import Skype4Py import time # class with Skype4Py event handlers class SkypeEvents: # message status event handler def SmsMessageStatusChanged(self, sms, status): print '>Sms', sms.Id, 'status', status, \ skype.Convert.SmsMessageStatusToText(status) ...
from random import randint from selenium.common.exceptions import NoSuchElementException import bot_util from .api_db import * from .bot_util import getIfUserWantsToUnfollow from .like_util import get_links_for_tag, check_link, get_links_for_location from .like_util import like_image from .unfollow_util import custom...
# Copyright (c) 2013 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditi...
grade = int(input('Enter a grade: ')) while grade > 10: grade = int(input('Invalid grade, enter a grade less than or equal to 10: ')) print('Grade entered: {}'.format(grade))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from https://github.com/rpi-ws281x/rpi-ws281x-python/tree/master/examples import time from rpi_ws281x import PixelStrip, Color class ledControl(): def __init__(self, *args, **kwargs): # LED strip configuration: self.LED_COUNT = 12 # Number of LED pixels. ...
from askapdev.rbuild.builders import Ant as Builder builder = Builder(".") builder.add_install_file("files", "config") builder.build()
# # 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...
# -*- encoding: utf-8 -*- # @Time : 2020/12/21 # @Author : Xiaolei Wang # @email : wxl1999@foxmail.com # UPDATE # @Time : 2020/12/22 # @Author : Xiaolei Wang # @email : wxl1999@foxmail.com from crslab.download import DownloadableFile resources = { 'nltk': { 'version': '0.3', ...
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' Analytical nuclear gradients of CASCI excited state. ''' from pyscf import gto from pyscf import scf from pyscf import mcscf mol = gto.M( atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. ,-0.757 , 0.587)], [1 , (0...
import django_filters from .models import Product class ProductFilter(django_filters.rest_framework.FilterSet): """ 业务线过滤类 """ pid = django_filters.NumberFilter(name="pid") class Meta: model = Product fields = ['pid']
#-*- encoding:UTF-8 -*- #!/usr/bin/python3 from xml.dom import minidom import os,sys import xlrd import xlwt import string from Config import FRONT from Config import BACKEND from Config import IGNORE from Config import MARK_INDEX from Config import DATA_START_INDEX from core.IExportor import IExportor as IExpor...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from phoneauto.helpers.uiautomator_device_wrapper import DeviceWrapper @pytest.fixture def wdev(mocks): device_wrap = DeviceWrapper(mocks.device) return device_wrap def test_selector(mocks, wdev): wdev(text='abc', className=...
# -*- coding: utf-8 -*- import logging from bs4.element import Tag from lncrawl.core.crawler import Crawler logger = logging.getLogger(__name__) search_url = 'https://www.worldnovel.online/wp-json/writerist/v1/novel/search?keyword=%s' chapter_list_url = "https://www.worldnovel.online/wp-json/novel-id/v1/dapatkan_cha...
from roglick.engine.ecs import ComponentBase class AttributesComponent(ComponentBase): _properties = (('st', 10), ('dx', 10), ('iq', 10), ('pe', 10))
import logging from enum import Enum from typing import Union from xml.etree.ElementTree import Element from jmeter_api.basics.assertion.elements import BasicAssertion from jmeter_api.basics.utils import Renderable, tree_to_str, Scope class TestField(Enum): FULL = "SizeAssertion.response_network_size" HEADE...
import sys class Atom: def __init__(self, vmd_index, chain, resname, resid, name, element, icode=''): """ Construct a new atom with the values, check the element (potentially infer from name) and set van der Waals radius based on it. Parameters ---------- vmd_inde...
"""  Created on Mon Apr 22 2019   Copyright (c) 2019 João Eduardo Montandon """ import requests from .filters import Filter class Query: def __init__(self, timeout=60): self.filters = [] self.timeout = timeout def __add__(self, filter): if isinstance(filter, Filter): ...
from oscar.apps.catalogue import config class CatalogueConfig(config.CatalogueConfig): name = 'blousebrothers.catalogue'
from setuptools import (setup, find_packages) from observable.config import PACKAGE_NAME setup(name=PACKAGE_NAME, packages=find_packages(), version='0.0.0', author='Azat Ibrakov', author_email='azatibrakov@gmail.com', install_requires=[ 'aiohttp>=2.2.5',...
# # This file is part of m.css. # # Copyright © 2017, 2018, 2019, 2020, 2021, 2022 # Vladimír Vondruš <mosra@centrum.cz> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Softwar...
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompany...
import cv2 import numpy as np import os def dilate_image(file_name):# 通过graph生成缓冲区,最后进行分割结果合并用的 osm = cv2.imread(file_name, 0) kernels = np.ones((15, 15)) dilated_img = cv2.dilate(osm, kernels) return dilated_img def merge_result(tiny_mask_file, large_mask_file, dilated_osm): tiny_p...
class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: graph = {i:[] for i in range(n)} for edge in edges: graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) visited = [False] * n num_components = 0 def dfs(node)...
from datetime import datetime, timedelta import numpy as np import pandas as pd import xarray as xr import ahlive as ah CONTAINERS = [list, tuple, np.array, pd.Series, xr.DataArray] XS = [] XS.append(0) XS.append([0, 0]) XS.append([0, 1]) XS.append([-1]) XS.append(["1", "2"]) XS.append([datetime(2017, 1, 2), dateti...
# 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...
_base_ = ['../OWN_PGC/pgc_video_compressed_vqa_res18_basemodel_nr.py'] # 关于数据的配置 data = dict( dataset_name="ImageVideoGeneralDataset", # 选择使用的dataset类加载数据,具体看datasets/ is_fr=False, # 是否有参,跟model的fr参数保持一致 data_roots=["./data/IVQA/own_games_compression-frames/"], # 视频/图片数据的根目录,如果有多个数据集请在list里依次填写 d...
# Copyright 2017 Red Hat, Inc. # 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...
''' Author: hdert Date: 23/5/2018 ''' #--Librarys-- import random import string #--Variables-- guesses = 0 guess = 0 answer = "" global score score = 0 #--Functions-- def checkAnswer(a, b, c): if a == b: return("c") elif a == c: return("c") else: retur...
import torch import torch.nn as nn import torch.nn.functional as F from libcity.model.abstract_traffic_state_model import AbstractTrafficStateModel class GCNLayer(nn.Module): def __init__(self, num_of_features, num_of_filter): """ One layer of GCN Arguments: num_of_features ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v6/resources/product_bidding_category_constant.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.p...
from .byte_range import ByteRange from .mp4_muxing_information import MP4MuxingInformation from .muxing_information_audio_track import MuxingInformationAudioTrack from .muxing_information_video_track import MuxingInformationVideoTrack from .progressive_ts_information import ProgressiveTSInformation
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(3, 256, kernel_size=3) # change the input channels to 3 since cifar is colored self.conv_bn_1 = nn.BatchNorm2d(256) self.conv2 = n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This file contains functions relevant only to the visualization. """ ### # generateMeetings part ### import numpy as np import OpenGL.GL.shaders from OpenGL.GL import GL_VERTEX_SHADER, GL_FRAGMENT_SHADER def compile_shader(): VERTEX_SHADER = """ ...
import cv2 from numpy import array, zeros, uint8 from random import random from calculations import x_angle from fileMananager import resource_path from immageProcessing import get_screen, show_immage, scaleImage, filter_orange, filter_orange2, filter_blue, equalize from numpy import where #things that i dont have t...
__author__ = 'Lionel Brouyere' __copyright__ = not 'DreamWall' __license__ = 'MIT' import re import maya.cmds as mc from dwmaya.attributes import get_attr, set_attr TARGETWEIGHT_ATTR = { "blendShape": "inputTarget[{0}].inputTargetGroup[{0}].targetWeights[{1}]", "cluster": "weightList[{0}].weights[{1}]" } ...
# -*- coding: utf8 -*- from numpy import * import json def GenerateRectangular(N, sph_size, scale, filename): try: f = open(filename, "w+") except Exception as e: return str(e) data = {} data["FileType"] = "LatticeGenerator" data["Dimensions"] = 2 data["SpheresNumber"] = 0 data["SphereSize"] = s...
# pylint: disable=E1120 # pylint: disable=E1101 import ppscore as pps import lazypredict import numpy as np import pandas as pd from uuid import UUID from typing import List, Optional from pandas import DataFrame from lazypredict.Supervised import LazyRegressor from lazypredict import Supervised from sklearn.pipeline i...
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # 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 la...
"""# LRU""" def LRU(cap, req): # request list requests = req # Cash capacity capacity = cap # List of current pages in cash cash = [] pageFaults = 0 for i in requests: # If i is not present in cash if i not in cash: # Check if the list can hold equal pages if(len(cash) == capacity): cash.r...
import os import boto3 region = os.environ['AWS_DEFAULT_REGION'] ssm = boto3.client('ssm', region) def get_since_id(mode): key = 'll-now-tweet-since-id-{}'.format(mode) params = get_ssm_params(key) since_id = params[key] return since_id def get_ssm_params(*keys): response = ssm.get_parameters...
# *args **kwards def super_func(*args): print(*args) return sum(*args) super_func(1,2,3,4,5)
from termcolor import colored from performbooksearch import search_books from performaddreadinglist import add_to_reading_list from printlists import print_reading_list class BookApp: """The BookApp object contains the implementation of the command-line application and is used to start the app.""" def __...
# -*- coding: utf-8 -*- """ created by huash06 有一个地铁线路图,给出以下信息: 1. 每条线路上每一站之间的运行时间; 2. 换乘通道以及通过换乘通道的时间; 3. 乘客在上车之前需要等待,给出了每条线路的等待时间 计算给定的起始站到目的站所需要的最短时间 一开始想到用BFS计算最短路径,由于有些站需要等待,处理起来非常困难。 下面是我一开始的不正确解法: initialize(Q) Q <- departStation while Q is not empty: S <- first elemet of Q update time of stations ...
import time from decimal import Decimal from django.test import TestCase from article.models import ArticleType from money.models import Cost from order.models import Order, OrderLine from stock.models import Stock, StockChangeSet from stock.stocklabel import OrderLabel from stock_count.models import TemporaryCounter...
import os import json import click from opaque.locations import TEST_DATA_LOCATION from opaque.simulations.prevalence import PrevalenceSimulation @click.command() @click.option('--n_jobs', default=1, type=int, show_default=True) @click.option('--n_trials', default=10000, type=int, show_default=True) def main(n_jobs, ...
# -*- coding: utf-8 -*- # @Time : 2019/10/3 22:02 # @Author : Run # @File : operators.py # @Software : PyCharm """ Notes: 1. np.math == scipy.math == math """ from typing import List from functools import reduce import math from RunToolkit.for_list import flatten_iterable def clamp_number(num, a, b...
import numpy as np import time def Fuzzy(error): sign = np.sign(error) error =abs(error) k1 = 0.35 x = 50 k2 = 0.55 angle = 0 if error<x: angle = k1*error else: angle = (error-x)*k2+k1*x if angle>60: angle = 60 return -angle*sign error_arr = np.zeros(5) ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .constants import LAYER_NORM_EPS # noqa: F401 from .functions import ( # noqa: F401 create_embeddings, cre...
"""Initialization for `paccmann.models` submodule.""" __version__ = '0.0.4'
from django.urls import path import tesseractfield.views urlpatterns = [ path('api/tesseract/', tesseractfield.views.TesseractView.as_view()), ]
import sys import pickle import copy import inspect import random import os def pv(name): record=inspect.getouterframes(inspect.currentframe())[1] frame=record[0] val=eval(name,frame.f_globals,frame.f_locals) print('{0}: {1}'.format(name, val)) def self_dG_FN(seq): energy = float(os.popen('hybrid-ss...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ```````` `````` ``````` ``` ```` ``` `````` # ` ``` ` `` ``` ``` ``` ``` ```` `` `` ``` # ``` ``````` ``` ```` ``` ```````` `````` # ``` `` `` `````` ``` `` ````` ``` `` # ``` ``` ``` ``` ``` ``` ``` ```` ``` `...
# Copyright (c) 2020-present, Baidu, Inc. # All rights reserved. # # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # # Acknowledgement: The code is modified based on Facebook AI's XLM. import sys from src.data.dictionary import Diction...
"""Template helpers used by watsons search.""" from __future__ import unicode_literals from django import template from django.contrib.contenttypes.models import ContentType register = template.Library() @register.simple_tag(takes_context=True) def search_results(context, search_results): """Renders a list of...
from rest_framework import serializers from .models import * from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): transactions = serializers.PrimaryKeyRelatedField(many=True, queryset=Transaction.objects.all()) class Meta: model = User fields = ['id',...
from unittest import TestLoader, TextTestRunner suite = TestLoader().discover('..') runner = TextTestRunner() runner.run(suite)
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import atexit import glob import json import logging import os import random from collections import Counter from functo...
import base64 from flask import Flask, render_template, request app = Flask(__name__) @app.route("/") def home(): return render_template("index.html") @app.route("/api/files/upload", methods=["POST"]) def api_files_upload(): payload = request.get_json() # `contents` is encoded as a data URL: # h...
#!/usr/bin/env python3 from setuptools import setup def long_description(): """ Attempt to read README.rst (which is generated during deploy-time), otherwise, use README.md. """ try: return open('README.rst').read() except IOError: return open('README.md').read() setup( ...
#!/usr/bin/python3 """ Exploit Title: Bludit <= 3.9.2 - Bruteforce Mitigation Bypass Author: ColdFusionX (Mayank Deshmukh) Author website: https://coldfusionx.github.io Date: 2020-10-19 Vendor Homepage: https://www.bludit.com/ Software Link: https://github.com/bludit/bludit/archive/3.9.2.tar.gz Version: <= 3.9...
""" This example could be run and the results printed from the `examples/util` directory in Disco: python query_ddb.py <query> <input> ... """ import sys from disco.core import Job, Disco, result_iterator from disco.worker.classic.func import nop_map from disco.schemes.scheme_discodb import input_stream class Query(...
from . import util from . import logger import matplotlib.pyplot as plt import numpy as np class Plotter: def __init__(self, date_list, weight_list): self.weight_list = weight_list self.date_list = date_list self._plt = None def plot(self): y, X = self._prepare_data(self.weigh...
#!/usr/bin/env python3 """Classes and methods for working with Turing machine configurations.""" import collections class TMConfiguration(collections.namedtuple( 'TMConfiguration', ['state', 'tape'] )): """A Turing machine configuration.""" def __repr__(self): """Return a string representati...
#!/usr/bin/env python3 # ============================================================================== # CSE 824 # Created on: November 25th, 2021 # Authors: Chris Nosowsky (nosowsky@msu.edu), # Hamzeh Alzweri (alzwerih@msu.edu) # # Main script to run our application # ========================================...
n = int(input()) nums = [0, 1] for i in range(2, n+1): nums.append(nums[i-1]+nums[i-2]) print(nums.pop())
import ode import math import redis import uwsgi import gevent class Box(object): def __init__(self, name, world, weight, size): self.body = ode.Body(world.world) M = ode.Mass() M.setBox(2500, size, size, size) M.mass = weight self.body.setMass(M) self.geom = ode.Ge...
# -*- coding:utf-8 -*- from datetime import datetime datetime_formates = [ '%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S', '%Y%m%dT%H%M%S', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M:%S', '%d.%m.%Y %H:%M:%S', '%Y-%m-%dT%H:%M', '%Y%m%d', '%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%d.%m.%Y...
#!/usr/bin/python #-*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from xlrd import open_workbook from pylab import * x_data=[] y_data=[] x_data1=[] y_data1=[] x_data2=[] y_data2=[] x_data3=[] y_data3=[] x_volte=[] temp=[] plt.annotate('The favorite close loop point',size=16, xy=(1, 0.1), x...
"""Align polynomials.""" import numpy import numpoly def align_polynomials(*polys): """ Align polynomial such that dimensionality, shape, etc. are compatible. Alignment includes shape (for broadcasting), indeterminants, exponents and dtype. Args: polys (numpoly.ndpoly): Polyn...
from transformer.validator.validator_config import ValidatorConfig, ValidatorFieldConfig from transformer.validator.validator import NricValidator, NaNValidator, RegexValidator, RefValidator
from fidesops.schemas.masking.masking_configuration import ( RandomStringMaskingConfiguration, ) from fidesops.service.masking.strategy.masking_strategy_random_string_rewrite import ( RandomStringRewriteMaskingStrategy, ) def test_mask_with_value(): request_id = "123432" config = RandomStringMaskingCo...
"""Tanium Sensor/Package parameter helper.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import os import pprint THIS_FILE = os.path.abspath(__file__) THIS_SCRIPT = os.path.basename(THIS...
import pytest from django.conf import settings from django.test import override_settings import tracker from tests.base.case import BaseTest @pytest.mark.tracker_mark class TrackerTest(BaseTest): def test_default_backend_tracker(self): backend = tracker.get_tracker_backend() assert backend == '...
# Generated by Django 3.2 on 2021-04-17 16:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('devices', '0004_device_is_main'), ('camera', '0008_auto_20210417_1643'), ] operations = [ migrations....
n = int(input('Digite um número inteio: ')) base = int(input('Pada mudar a base, escolha: 1 binário, 2 octal e 3 hexadecimal: ')) if base == 1: print(f'{n} na base 2 = {n:b}') elif base == 2: print(f'{n} na base 8 = {n:o}') else: print(f'{n} na bade 16 = {n:h}')
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of Python Challenge Solutions # https://github.com/scorphus/PythonChallengeSolutions # Licensed under the BSD-3-Clause license: # https://opensource.org/licenses/BSD-3-Clause # Copyright (c) 2018-2020, Pablo S. Blum de Aguiar <scorphus@gmail.com> # ht...
# -*- coding: utf-8 -*- from selenium import webdriver import time, unittest from group import Group def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False class test_add_group(unittest.TestCase): def setUp(self): self.wd = webdriver.Fir...
from user import User class Admin(User): """添加属性""" def __init__(self,first_name,last_name): super().__init__(first_name,last_name) self.privileges = Privileges() #self.privileges = ['can add post','can delete post','can ban user','can grent owner'] #def show_privileges(self): #for item in self.privileges: ...
''' Set of function used for the Minami & Komatsu birefringence likelihood Relevant paper is https://arxiv.org/pdf/2006.15982.pdf (here after MK) And the doc https://github.com/simonsobs/PSpipe/blob/master/project/Planck_pspy/doc/birefringence.pdf which is mostly a copy of the MK papers. ''' import pickle import sys ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch from .stage0 import Stage0 from .stage1 import Stage1 from .stage2 import Stage2 from .stage3 import Stage3 class AlexNetStraightSplit(torch.nn.Module): def __init__(self): super(AlexNetStraightSplit, self).__init__() ...
import re from django.core.exceptions import ValidationError from django.core.validators import validate_ipv4_address, validate_ipv6_address, MaxLengthValidator from django.utils.translation import ugettext_lazy as _ from pdns.models import Record re_record_name_valid_chars = re.compile(r'^((([a-z\d_])|(\*\.))(-*[a-...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- def main(): from onnxruntime.training.ortmodule.torch_cpp_extensions...
import tensorflow as tf import torch import utils class BaseGAttN(torch.nn.Module): def loss(logits, labels, nb_classes, class_weights): sample_wts = (utils.one_hot(labels,nb_classes)*class_weights).sum(dim=-1) xentropy = torch.nn.functional.cross_entropy(input=logits,target=labels,reduction="none...
#============================================================================== # IMPORT NECESSARY MODULES #============================================================================== # C:\temp>abaqus viewer -noGUI (this requires a CAE license) # C:\temp>abaqus python (this does not require a license) ...
import rospy import message_filters from sensor_msgs.msg import Image, CameraInfo from geometry_msgs.msg import PoseWithCovarianceStamped, Pose from tf.transformations import quaternion_matrix from sel_map_mapper import Pose, Mapper, SaveOptions from sel_map_mesh import TriangularMesh from sel_map_segmentation import C...
def omp_single(): nr_threads_in_single = 0 result = 0 nr_iterations = 0 LOOPCOUNT = 1000 if 'omp parallel': for i in range(LOOPCOUNT): if 'omp single': 'omp flush' nr_threads_in_single += 1 'omp flush' nr_iterations...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: reformulator.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _...
import json async def handler(event): # get an image from your origin server or somewhere else resp = await event.fetch(url='https://www.example.com/example.jpg') # call duedge ai result = await event.ai.censor.terror_censor(resp.body) if result['error_code'] > 0: #some errors occured ...
#!/usr/bin/env python import os, sys sys.stdout = open('pom.xml', 'w') print( """<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</mod...
#!/usr/bin/env python3 # Copyright 2017 The Chromium OS 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 unittest from unittest import mock from cros.factory.goofy import goofy from cros.factory.goofy.plugins import device_manag...
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Clione Software # Copyright (c) 2010-2013 Cidadania S. Coop. Galega # # 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.or...