content
stringlengths
5
1.05M
import pytest from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from openslides.core.config import config from openslides.motions.models import ( Category, Motion, MotionBlock, MotionChangeRecommend...
# -*- coding: utf-8 -*- from django.contrib.admin import site from bviewer.profile.admin import profile from bviewer.core.models import Album from bviewer.profile.admin import ProfileModelAdmin from bviewer.slideshow.models import SlideShow class SlideShowAdmin(ProfileModelAdmin): list_select_related =...
import pickle import random if __name__ == '__main__': with open("comp_strategy.pkl", "rb") as pkl_file: strategy = pickle.load(pkl_file) # Assuming (1, 1) is initial state of dfa print(strategy[((2, 1, 4), (1, 1))]) print(strategy[((2, 1, 3), (1, 1))]) # for key in strategy.keys(): # ...
import random from math import exp, log, sqrt from typing import List, Tuple Tensor2D = List[List[float]] Shape2D = Tuple[int, int] def matrix_multiply(A: Tensor2D, B: Tensor2D) -> Tensor2D: A_shape = shape(A) B_shape = shape(B) assert A_shape[1] == B_shape[0], \ "matrix shapes {} and {} are inco...
# Author: Prabhu Ramachandran # Copyright (c) 2008, Enthought, Inc. # License: BSD Style.
from pycoin.networks.bitcoinish import create_bitcoinish_network network = create_bitcoinish_network( symbol="BTX", network_name="BitCore", subnet_name="mainnet", wif_prefix_hex="80", sec_prefix="BTXSEC:", address_prefix_hex="03", pay_to_script_prefix_hex="7D", bip32_prv_prefix_hex="0488ADE4", bip32_pub_pr...
from .abfn_neck import ABFNNeck from .abfn_neck_scale import ABFNNeckScale from .abfn_neck_spatial import ABFNNeckSpatial from .abfn_neck_scale_spatial import ABFNNeckScaleSpatial __all__ = ['ABFNNeck', 'ABFNNeckScale', 'ABFNNeckSpatial', 'ABFNNeckScaleSpatial']
# -*- coding: utf-8 -*- import numpy as np import sympy as sp def get_Slm(l, m): """ return the sympy real solid harmonic gaussian S_{lm}(r) as presented in table 6.3 of Helgaker, Jørgensen and Olsen (page 211) """ x,y,z = sp.symbols("x y z") r = sp.sqrt(x**2 + y**2 + z**2) ...
class RevisionSettings(Element,IDisposable): """ Provides access to project-wide settings related to revisions. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def GetAlphanumericRevisionSettings(self): """ GetAlphanumericRevisionSettings(self: RevisionSettings) -> AlphanumericRev...
from rest_framework import serializers from training import models class SetSerializer(serializers.ModelSerializer): """ Serializer for Set object """ class Meta: model = models.Set fields = ( 'id', 'user_id', 'exercise', 'reps', 'reps_unit', 'weight', ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import os import xml.etree.ElementTree as ET from logzero import logger from pathlib import Path def getPathToVivado()->Path: with open(os.path.expanduser("~/.vivado_hls_create_project")) as f: return Path(json.load(f)["path_to_vivado"]) def get...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^price-catalog/$', views.price_catalog, name="price-catalog"), url(r'^price-catalog/(?P<service_type>[^\/]*)/$', views.all_prices, name="all-prices"), url(r'^price-catalog/(?P<service_type>[^\/]*)/(?P<page>\d+)/$', views.all_prices,...
from functools import partial from urllib.parse import urlencode from geopy.exc import GeocoderServiceError from geopy.geocoders.base import DEFAULT_SENTINEL, ERROR_CODE_MAP, Geocoder from geopy.location import Location from geopy.util import logger __all__ = ("Geokeo", ) class Geokeo(Geocoder): """Geocoder usi...
from django.conf.urls import url from . import views urlpatterns = [ url( r'^(?P<username>[\w.@+-]+)/$', views.profile, name="profile"), ]
import json from kraken.core.maths import * vec3 = Vec3() vec3.x = 3.0 print "vec3:" + str(vec3) print "length:" + str(vec3.length()) vec3 = Vec3(1.0, 0.0, 2.0) print "vec3:" + str(vec3) print "length:" + str(vec3.length()) print "clone:" + str(vec3.clone()) vec1 = Vec3() vec2 = Vec3(0, 1, 0) print "equal:" + str(...
import click def universal_options(f): """Options required by every command.""" f = click.option('--genotype', type=click.Path(exists=True), required=True, help='Genotype file path.')(f) f = click.option('--verb', is_flag=True)(f) return f def param_options(f): """Options to...
#!/usr/bin/env python # -*- coding: utf-8 -*- largest = None smallest = None while True: snum = input("Enter a number: ") if snum == "done" : break try : inum = int(snum) except: print('Invalid input') continue if largest is None or inum > largest : largest =...
# # PySNMP MIB module NOVELSAT-COMMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOVELSAT-COMMON-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:24:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
#!/usr/bin/env python import sys import random import time import numpy as np import xbox import BlinkyTape as bt # COLORS class Col(object): BLACK = (0, 0, 0) CYAN = (0, 189, 189) GREEN = (0, 255, 0) ORANGE = (255, 80, 0) RED = (255, 0, 0) WHITE = (255, 255, 255) YELLOW = (255, 200, 0) ...
class Card(object): def __init__(self, number): """ Three attributes: Value is 1->A, 2->2, ... 10->10, 11->Jack, 12->Queen, 13-> King Type is 1->Spades, 2->Hearts, 3->Diamonds, 4->Clubs point is A->4, King->3, Queen->2, Jack->1 """ self.value ...
#!/usr/bin/python # -*- coding: utf-8 -*- from modules.logging import logging_decorator from telegram.ext import PrefixHandler from datetime import datetime from zalgo_text import zalgo def module_init(gd): commands = gd.config["commands"] for command in commands: gd.dp.add_handler(PrefixHandler("...
import tensorflow as tf import numpy as np import scipy.misc import threading from torch.utils.tensorboard import SummaryWriter try: from StringIO import StringIO # Python 2.7 except ImportError: from io import BytesIO # Python 3.x class Logger: def __init__(self, log_interval=50, ...
#!/usr/bin/env python # coding: utf-8 # # Collaboration and Competition # # --- # # In this notebook, you will learn how to use the Unity ML-Agents environment for the third project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893) program. ...
# Copyright 2018 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://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
# Generated by Django 2.1.2 on 2018-10-31 15:17 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CatalogType', fields=[ ('id', models.AutoFi...
import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.utils import model_zoo from torchvision import models class SegNetEnc(nn.Module): def __init__(self, in_channels, out_channels, num_layers): super().__init__() layers = [ nn.Ups...
from django.urls import resolve def appname(request): return {'app_name': resolve(request.path).app_name}
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import sys from os import path from setuptools import setup sys.path.insert(0, path.join(path.curdir, 'lib')) from tsdesktop import version desc = """tsadm desktop client - docker based environments for running web sites locally""" install_requires = [ 'bottle>=0...
#import sys, os, serial, time,re,datetime #import matplotlib.pyplot as plt #import numpy as np from tkinter import ttk import tkinter as tk from PIL import ImageTk, Image ''''********Global Variables**********''' picname='default.png' #This function gets a picture and puts it in a format that can be stuck in a label...
import os import typing as T import warnings import fsspec # type: ignore import numpy as np import pandas as pd # type: ignore import rioxarray # type: ignore import xarray as xr from xarray_sentinel import conventions, esa_safe def open_calibration_dataset(calibration_path: esa_safe.PathType) -> xr.Dataset: ...
import pickle import nltk import numpy as np import pandas as pd import pymongo from mongoengine import connect from sklearn import metrics, preprocessing from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer from sklearn.metrics import plot_confusion_matrix, accuracy_score fro...
# -*- coding: utf-8 -*- from __future__ import division, absolute_import, print_function import os import datetime import pytz from decimal import Decimal from django.core.files import File from django.core.files.images import ImageFile from django.db import models from django.db.models.fields.files import FieldFile...
""" Example: Julia ------- >>> import numpy as np >>> from ChaosFunctions.fractals import FractalBuilder, julia_iter,\ >>> p0_julia >>> ns, itermax, c = (1000, 1000), 100, complex(-0.768662, 0.0930477) >>> limits = np.array([[-2., 2.], [-2., 2.]]) >>> fb = FractalBuilder(julia_iter, lambda x, y: p0_julia(x, y, c))...
import os from flask import Flask, request, jsonify from flask_cors import CORS from mollufy.mollufy import mollufy as mollufy_internal server = Flask("mollufier") CORS(server, origins=["*" if not "FE_DEPLOY_HOST" in os.environ else os.environ["FE_DEPLOY_HOST"]]) @server.route("/mollufy", methods=["POST"]) def molluf...
#coding:utf-8 from __future__ import division import xml.etree.cElementTree as ET import os from collections import Counter import shutil import numpy as np import cv2 import pickle import sys import matplotlib.pyplot as plt import pylab as pl from sklearn.metrics import precision_recall_curve from itertools import c...
pkgname = "clang-rt-cross" pkgver = "13.0.0" pkgrel = 0 build_style = "cmake" configure_args = [ "-DCMAKE_BUILD_TYPE=Release", "-Wno-dev", f"-DCMAKE_INSTALL_PREFIX=/usr/lib/clang/{pkgver}", "-DCOMPILER_RT_USE_BUILTINS_LIBRARY=YES", # only build that target "-DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON", ...
import base64 import json import urllib import httplib2 import socket import time import lib.logger from lib.couchbase.document import DesignDocument, View from lib.memcached.helper.kvstore import KVStore from exception import ServerAlreadyJoinedException, ServerUnavailableException, InvalidArgumentException from lib.m...
import re from modules.globals import Globals from modules.pluginbase import PluginBase class Plugin(PluginBase): # plugin specific def __init__(self): super().__init__() self.type = PluginBase.PluginType.UNCORE self.name = 'Answers' self.add_trigger('on_message', 'answer', T...
# Библиотеки для сариализации from rest_framework import serializers, viewsets # Модели данных from workprogramsapp.models import Profession, SkillsOfProfession, Role, SkillsOfRole from dataprocessing.models import Items # Другие сериализаторы from dataprocessing.serializers import ItemSerializer class SkillsOfPr...
import numpy as np import pandas as pd # from pyta.helper import highest, lowest, hlc3 from pyta.overlays.exponential_moving_average import exponential_moving_average as ema # TODO incomplete def chop_zone(h: pd.Series, l: pd.Series, c: pd.Series, n: int = 30, n_ema: int = 34): period_high = highest(h, n) per...
import serial from serial.tools import list_ports import threading import time import datetime from dynamikontrol.Protocol import Module2PC, PC2Module from dynamikontrol.LED import LED from dynamikontrol.BaseLED import BaseLED from dynamikontrol.Motor import Motor from dynamikontrol.Switch import Switch from dynamiko...
import numba as nb import numpy as np @nb.njit def fast_intersection_append(xy, xz, yz, intersection): for ii in range(len(xy)): x, y_check, _ = xy[ii] idx = np.where(xz[:, 0] == x)[0] if len(idx) > 0: for jj in range(len(idx)): z = xz[idx[jj], 1] ...
#!/usr/bin/python # # * Overview # # This short Python example illustrates how to build a simple PRTG custom sensor to monitor # Pure Storage FlashArrays. The Pure Storage Python REST Client is used to query the FlashArray # to get the basic performance counters. # # * Installation # # The script should be copied in...
# Created by Ivan Matveev at 01.05.20 # E-mail: ivan.matveev@hs-anhalt.de # Methods for image preprocessing import cv2 import logging logger = logging.getLogger('detect.pre_processing') class PreprocessImg(object): def __init__(self, config): # Background subtraction parameters self.bgs_method_...
import serial import logging logging.basicConfig(level=logging.DEBUG) port = '/dev/ttyUSB0' class RobotHandler: def init_bot(self, port): try: connection = serial.Serial(port, baudrate=115200, timeout=1) print "Connected!" except: print "Failed." global robot ...
import sys import os.path sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)))) import os import playbooks from playbooks import infrastructure playbook = playbooks.TaintNode( infrastructure.KubernetesClient(), os.environ.get('TAINT_KEY', 'falco/alert'), os.environ.get('TAINT_VALUE', ...
from asciimatics.widgets import Frame, Layout, Widget, Label, Text, TextBox from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.event import KeyboardEvent from asciimatics.exceptions import ResizeScreenError, StopApplication, NextScene import sys import os PRICE = { 'Small Ca...
# Author: Ruthger from .app.app import create_app # Create an app instance to be executed by the ASGI framework (e.g. daphne) app = create_app()
""" Package with trace validation utility. """
from article import init_scrap from termcolor import colored def fetch_art(url,key_wrd): article=init_scrap(url) heads=["h1","h2","h3","h4"] all_posts=[] for art in article.find_all(heads): if art.text=="Forbidden": print(colored("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%","red")) ...
from numpy.linalg import matrix_power import numpy as np def snakes_and_ladders_matrix(): n = 101 T = np.zeros((n, n)) for i in range(n - 1): for j in range(i + 1, np.min([n, i + 7])): T[i, j] = 1 / 6 for i in range(n - 6, n): T[i, i] = (i - n + 7) / 6 snakes_and_ladde...
from probes.probe import * from notifiers.notifier import * import csv, sys def str_to_class(classname): return getattr(sys.modules[__name__], classname) FILE = 'subscriptions.csv' sender = '' password = '' smtp_address = 'smtp.gmail.com' smtp_port = '465' smtp_ssl = True receiver = '' reader = {} with open(FIL...
adminUser = raw_input('Enter the admin username, without the domain (e.g. dhay):') adminPassword = raw_input('Enter the admin password: ') print "\n" * 80 #clear screen csvFile = 'schoolDomains.csv' import time import csv import gdata.apps.organization.client totalRows = sum(1 for row in open(csvFile, 'rb')) #count h...
import getopt import sys import tensorflow as tf import os import json import numpy as np import file_utils from datetime import datetime import matplotlib.pyplot as plt import h5py from bert.tokenization.bert_tokenization import FullTokenizer from bert import BertModelLayer from bert.loader import StockBertConfig, map...
try: print('try') except Exception as e: print('except') else: print('else') raise Exception('else内で例外発生!') finally: print('finally')
from .string import string, String from .iterator import iterator, Iterator, iteratorOf from .sequence import sequence, Sequence, sequenceOf from .mapping import mapping, Mapping, mappingOf
from setuptools import setup import re with open('aiotengiohy/__init__.py') as f: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) with open("README.md", "r") as f: long_description = f.read() setup( name = 'aiotengiphy', packages = ['aiotengiphy'], versio...
# -*- coding: utf-8 -*- __author__ = 'CubexX' import shelve class Storer: def __init__(self, filename): self.filename = filename def store(self, key, obj): db = shelve.open(self.filename) db[key] = obj db.close() def restore(self, key): db = shelve.open(self.file...
from jinja2 import Template from jinja2 import Environment, PackageLoader if __name__ == '__main__': env = Environment(loader=PackageLoader('test_pack', 'templates')) template = env.get_template('template.html') r = template.render(name='Jesse') generate = 'generate.html' f = open(generate, 'w') ...
from django.http import HttpResponse, Http404 from email import message from unicodedata import category from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render from urllib import request from.models import Image, Category, Location # Create your views here. def gen_landing(request):...
import unittest import yaml from flask import render_template_string from tests.app import app from tests.fixtures.wtf_widgets_example_form import ExampleForm class FlaskWtfMacroTestBase(unittest.TestCase): """Test the flask-wtf -> govuk widgets Test the output of passing flask-wtf form elements throug...
from terra_sdk.core import Dec from ._base import BaseAsyncAPI, sync_bind __all__ = ["AsyncMintAPI", "MintAPI"] class AsyncMintAPI(BaseAsyncAPI): async def inflation(self) -> Dec: """Fetches the current inflation. Returns: Dec: inflation """ return Dec(await self._c....
def quick_sort(a_list): if len(a_list) < 2: return a_list else: pivot = a_list[0] less = quick_sort([i for i in a_list if i < pivot]) greater = quick_sort([i for i in a_list if i > pivot]) return less + [pivot] + greater print(quick_sort([7,6,3,99]))
def selection_4(): # Library import import numpy import matplotlib import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # Library version matplotlib_version = matplotlib.__version__ numpy_version = numpy.__version__ # Histo binning xBinning = numpy.lin...
from typing import List from hypothesis import given from hypothesis import strategies as st from hypothesis.extra.numpy import arrays import numpy as np from numpy import ndarray from numpy.testing import assert_almost_equal, assert_array_equal from scvelo.core import clipped_log, invert, prod_sum, sum class Test...
# https://www.hackerrank.com/challenges/np-mean-var-and-std/problem import numpy as np n,m = map(int, input().split()) b = [] for i in range(n): a = list(map(int, input().split())) b.append(a) b = np.array(b) np.set_printoptions(legacy='1.13') print(np.mean(b, axis = 1)) print(np.var(b, axis = 0)) print(np...
""" Computes the rational approximation of (alpha*x^s + beta*x^t)^(-1) on interval [0, bound]: * -1 <= s,t <= 1 * upper bound of x, should be an upper bound of lambda_max(A), e.g. l_infty norm of A """ import numpy as np from baryrat import aaa import haznics def rational_approx_haznics(x, f, AAA_tol): # ...
import clay def test_new_cwd(dst): dest = dst / "demo" clay.cli.new(dest) assert (dest / "static").is_dir() assert (dest / "clay.yaml").is_file()
#!/usr/bin/env python """Detect indices in x of sequential data identical to value.""" import numpy as np __author__ = 'Marcos Duarte, https://github.com/demotu/BMC' __version__ = 'detect_seq.py v.1.0.0 2019/03/17' def detect_seq(x, value=np.nan, index=False, min_seq=1, max_alert=0, show=False, ax=N...
import shutil import dill from zipfile import ZipFile import os import glob import abc import re from dps.utils import zip_root class ObjectFragment(object, metaclass=abc.ABCMeta): def __init__(self): pass @abc.abstractmethod def combine(self, *others): raise Exception("NotImplemented") ...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from models import build_model from datagen import genxy from utils import genanchors, loc2box2d from datetime import datetime np.set_printoptions(threshold=np.inf, linewidth=np.inf) anno_file_path = '...
from typing import List, Dict from ts.c_syntax import CSyntax from ts import Tree from cfa import CFANode, CFA, CFAEdge from cfa import LocalisedCFA, LocalisedNode from .tweet_handler import TweetHandler from .decoration_strategy import StandardDecorationStrategy, DecorationStrategy from .conversion_strategy import Co...
"""Core functions.""" import hashlib import re from pathlib import Path from typing import Any from typing import Iterable from typing import Optional from typing import Tuple from nox.sessions import Session from nox_poetry.poetry import DistributionFormat from nox_poetry.poetry import Poetry Session_install = Ses...
from django.db.models import Manager, QuerySet from .constants import NONCONNECTABLE_IFACE_TYPES class InterfaceQuerySet(QuerySet): def connectable(self): """ Return only physical interfaces which are capable of being connected to other interfaces (i.e. not virtual or wireless). ...
from __future__ import absolute_import # flake8: noqa # import apis into api package from openapi_genclient.api.market_api import MarketApi from openapi_genclient.api.operations_api import OperationsApi from openapi_genclient.api.orders_api import OrdersApi from openapi_genclient.api.portfolio_api import PortfolioApi...
#!/usr/bin/env python # _*_ coding:UTF-8 _*_ import rospy import signal from std_msgs.msg import String from webots_ros.srv import set_float from webots_ros.srv import set_int from geometry_msgs.msg import Twist TIME_STEP = 32 MAX_SPEED = 5.0 controllerName = "" v_x = 0 w_z = 0 motorNames = ["wheel1", "wheel2", "wheel...
#!/usr/bin/env python3 import wikileaks with open('dnc.session.aria2', 'w') as f: for id in range(1, wikileaks.COUNT_DNC + 1): print(f'# --- {id} ---', file=f) print(f'https://wikileaks.org/dnc-emails/get/{id}', file=f) print(' dir=dnc-emails', file=f) print(' max-tries=0', file=...
import pandas as pd def pandas_excel_write(save_dir_path: str): data1 = """ class precision recall <18 0.0125 12 18-24 0.0250 16 25-34 0.00350 4 """ data2 = """ sample values <18 0 18-24 0.25 25-34 0.35 ...
# -*- coding: utf-8 -*- import numpy as np import tensorflow as tf a = tf.constant(2) b = tf.constant(3) x = tf.add(a, b) with tf.Session() as sess: writer = tf.summary.FileWriter('./graphs', sess.graph) print(sess.run(x)) writer.close() a = tf.constant([2, 2], name='a') b = tf.constant([[0, 1], [2, 3]], name...
import os import warnings from setuptools import setup, Extension import numpy try: from pathlib import Path home = str(Path.home()) except ImportError: home = os.path.expanduser("~") # This is the switch for ALM developement. Always True for general cases. compile_with_sources = True # Configurations to ...
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from .models import Article class ArticleUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ArticleUpdateForm, self).__init__(*args, **kwargs) self.helper = FormHelper(...
# coding=utf-8 import pytest from configobj import ConfigObj from configobj.validate import Validator @pytest.fixture def empty_cfg(): return ConfigObj() @pytest.fixture def val(): return Validator()
# 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 enum import Enum class TextCompressionLevel(Enum): none = 0 low = 1 high = 2 class TextCompressor(object): def __init...
""" Read each other's minds """ import asyncio import discord import json import random from collections import deque from chowder import chowder with open("games/telewave/telewave_config.json", "r") as read_file: config = json.load(read_file) class TelewaveTeam: def __init__(self, players, name, score, ...
import os filepath = "../metadata/list_of_html.txt" template_path = "../metadata/templates/template_code.html" replace_above_cw = "<!-- Page Header -->" replace_below_cw = "<!-- Footer -->" def get_middle (filename): middle = [] with open(filename, "r", encoding= 'utf-8') as fp: line = fp.readline() while(replac...
# -*- coding: utf-8 -*- from string import Template from textwrap import dedent # This file contains templates used to generate HandleProcess file ''' The following template is based on Part 4 (Section ParseHandleBuffer()) ''' handle_process_template = Template(dedent("""\ #include "Tpm.h" #include "In...
#!/usr/bin/python # -*- coding: utf-8 -*- import Skype4Py from Skype4Py.chat import * class skype_api: instance = None def __init__(self): self.skype = Skype4Py.Skype() self.current_user = self.skype.CurrentUser if self.skype.AttachmentStatus != 0: self.skype.Attach() ...
#!/usr/bin/python import os os.chdir('/tmp') #sapnwrfc - A Python interface to SAP NetWeaver R/3 systems using the RFC protocol #SAP RFC Connector using the SAP NW RFC SDK for Python http://www.piersharding.com/blog/ #https://github.com/piersharding/python-sapnwrfc import sapnwrfc import sys if len(sys.argv) <> 4: ...
import datetime import os import requests import trello import vk from vk.photos import Photo import config def is_image_file(attachment_url): _, file_extension = os.path.splitext(attachment_url) if file_extension not in ('.jpg', '.gif', '.png'): return False return True def download_attachm...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import random from IMLib.utils import * #import tensorflow.compat.v1 as tf #tf.disable_v2_behavior() import tensorflow as tf class Dataset2(object): def __init__(self, config): super(Dataset2, s...
# -*- coding: utf-8 """ @File : normalrdmbased.py @Author : Zitong Lu @Contact : zitonglu1996@gmail.com @License : MIT License """ ' a module for calculating Cross-Temporal Similarities based on normal RDMs ' import numpy as np from neurora.rdm_corr import rdm_correlation_spearman, rdm_correl...
import os import tkinter import dlg_add_user import sign import pygubu from db_ctrl import get_all_users, del_user class WinManager(pygubu.TkApplication): def _create_ui(self): self.builder = builder = pygubu.Builder() builder.add_from_file('conf/win_ui/manager.ui') self.mainwindow = build...
import numpy as np class Param(object): def __init__(self, name): self.name = name def sample(self): pass def mutate(self, value): pass class CategoricalParam(Param): def __init__(self, name, categories, prior=None): super(CategoricalParam, self).__init__(name) ...
from time import sleep class Receita: def __init__(self, ovo, leite, farinha, manteiga) -> None: self.ovo = ovo self.leite = leite self.farinha = farinha self.manteiga = manteiga def misturar(self): if self.ovo == 2: return 'Bolo sendo misturado' els...
# -*- coding: utf-8 -*- """ @Time : 2021/6/22 10:54 @Author : 物述有栖 @File : webp_converter.py @DES : webp转换器 """ from PIL import Image import sys import os def file_convert(filepath): # for file in os.listdir(path): # fileName = path + "/" + file im = Image.open(filepath).convert('RGB') save...
''' Python3 needed for requests ''' from matplotlib.animation import FuncAnimation import matplotlib.pyplot as plt import requests # Change this address to your settings macaddr = 'E8:C7:D7:F2:4B:47' hostname = 'raspberrypi3' port = '5000' # http-link generation link = 'http://' + hostname + ':' + port + '/data/' + ...
# Copyright 2012 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. """Tests lid switch functionality.""" import datetime import os import time from cros.factory.test import event_log # TODO(chuntsen): Deprecate event l...
import setting import os from pyspark.mllib.evaluation import RegressionMetrics from src.spark_session import spark from src.features import build_features from src.models import train_model from src.utils import log_config logger = log_config.get_logger(__name__) def evaluate_model(): """ will read train an...
# Copyright 2018 U.C. Berkeley RISE Lab # # 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 agree...
import grpc import inference_pb2_grpc import management_pb2 import management_pb2_grpc def get_inference_stub(): channel = grpc.insecure_channel('localhost:9090') stub = inference_pb2_grpc.InferenceAPIsServiceStub(channel) return stub def get_management_stub(): channel = grpc.insecure_channel('local...