content
stringlengths
5
1.05M
# SPDX-FileCopyrightText: 2009 Fermi Research Alliance, LLC # SPDX-License-Identifier: Apache-2.0 # # Project: # glideinWMS # # File Version: # # Description: # This module implements the functions needed to keep the # required number of idle glideins # plus other miscelaneous functions # # Author: # Igor Sf...
import cv2 import os from PIL import Image from tqdm import tqdm import numpy as np #图片路径 def change_label(): img_str='E:\Oppo_Game\pytorch-semantic-segmentation-master/data/dataset/gtFine' out_str='E:\Oppo_Game\pytorch-semantic-segmentation-master/data/dataset/label255' list_img=os.listdir(img_str) fo...
from ansible.module_utils.basic import AnsibleModule import os.path class Line: ATTRS = ( "device", "path", "fs", "options", "dump", "fsck" ) def __init__(self, raw): self.raw = raw self.attrs = None self.parse() def parse(self): self.has_mount = False ...
# https://www.w3.org/TR/filter-effects/#funcdef-hue-rotate # https://www.w3.org/TR/SVG/filters.html#TransferFunctionElementAttributes import numpy as np from . import rgb_clamp CONST_PART = np.array([[0.213, 0.715, 0.072], [0.213, 0.715, 0.072], [0.213, 0.715, 0.072]]) ...
from django.core.urlresolvers import reverse from django.forms.models import ModelForm from django.views.generic import ListView, CreateView, UpdateView, DeleteView from website.models import User from website.view.account import UserIsAdminMixin, user_is_admin # model from website.models import Unit # forms class Un...
#!/usr/bin/env python import copy from studious import utils # Stores all users all_users = None class User: key = 1 name = "UsEr" def __str__(self): return self.name def __init__(self, key, name): self.key = key self.name = name def add(username): utils.sql("INSERT...
# coding=utf-8 """ pyCity_Calc: Python package addon for pyCity The MIT License Copyright (C) 2015-2019 Jan Schiefelbein 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, incl...
from .movingAverageStrategyNode import MovingAverageStrategyNode from .portExpMovingAverageStrategyNode import PortExpMovingAverageStrategyNode from .xgboostStrategyNode import XGBoostStrategyNode __all__ = ["MovingAverageStrategyNode", "PortExpMovingAverageStrategyNode", "XGBoostStrategyNode"]
# accounts/urls.py from django.urls import path from .views import SignUpView, LoginView, LogoutView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), ]
from .pcdet_nms_utils import ( nms_gpu as pcdet_nms_gpu, nms_normal_gpu as pcdet_nms_normal_gpu) __all__ = ['pcdet_nms_gpu', 'pcdet_nms_normal_gpu']
import os as _os from glob import glob as _glob import numpy as _np import pandas as _pd import rawpy as _rawpy from astroscrappy import detect_cosmics as _detect_cosmics from exiftool import ExifTool as _ExifTool def open_raw(fname, band_list="RGB"): print(f"Opening '{fname}'") raw = _rawpy.imread(fname) ...
import argparse import math parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--deploy', action='store_true') group.add_argument('--test', action='store_true') def solver(inputString, verbose=False): def move(point, event): if event[0] == "R"...
import os def get_config(args): config = [ ('conv2d', [64, 1, 3, 3, 2, 0]), ('relu', [True]), ('bn', [64]), ('conv2d', [64, 64, 3, 3, 2, 0]), ('relu', [True]), ('bn', [64]), ('conv2d', [64, 64, 3, 3, 2, 0]), ('relu', [True]), ('bn', [64]), ...
import os import sys import time import json import csv from jinja2 import Environment, PackageLoader, select_autoescape, FileSystemLoader import torch from random import choice # Files used in various operation modes TOPOLOGY_PATH = "MulVAL_P/" LOGICAL_ATTACK_TOPOLOGY = "logical_topology_1.P" GENERATION_TOPOLOGY_TEMP...
# -*- coding: utf-8 -*- """ Created on Sun Jan 20 13:50:45 2019 @author: Corey """ # d8b db d88888b d888888b db d8b db .d88b. d8888b. db dD .d8888. # 888o 88 88' `~~88~~' 88 I8I 88 .8P Y8. 88 `8D 88 ,8P' 88' YP # 88V8o 88 88ooooo 88 88 I8I 88 88 88 88oobY' 88,8P `8bo. # ...
import requests import json from selenium import webdriver headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36', 'Cookie': '', 'Connection': 'keep-alive', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, sdch',...
class Solution: def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ lookup = {} for i, num in enumerate(nums): if num not in lookup: lookup[num] = i else: i...
# python import lx import snapUtil lx.eval('file.open {%s}' % snapUtil.filePath())
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class HdfsRecoverJobParams(object): """Implementation of the 'HdfsRecoverJobParams' model. Contains any additional hdfs environment specific params for the recover job. Attributes: hdfs_exclude_pattern (list of string): Any path/Glob pa...
from consts import * from utils import * from kaggle_environments.envs.football.helpers import * from sklearn.ensemble import RandomForestClassifier import math def get_distance(pos1,pos2): return ((pos1[0]-pos2[0])**2+(pos1[1]-pos2[1])**2)**0.5 def get_heading(pos1,pos2): raw_head=math.atan2(pos1[0]-pos2[0],...
import logging import sys import re import time from datetime import datetime def run(ctx): # Get the ticket data from the context ticket = ctx.config.get('data').get('ticket') currentTime = round(time.time() * 1000) now = datetime.now() dateStamp = now.strftime("%Y-%m-%dT%H:%M:%S") # Create G...
from . import data_checking from . import plotting_callbacks from . import tfbinding_generator from . import additional_metrics from . import bam_dataset_generator from . import MACS_Import from . import MACS_dataset_gen
import pandas as pd import numpy as np import datetime import requests from bs4 import BeautifulSoup class AirStation: ''' 측정소정보 조회 서비스 클래스 ''' def __init__(self, serviceKey): ''' 서비스키 초기화 ''' self.serviceKey = serviceKey def GetNearby(self, tmX, tmY, ver):...
# https://leetcode.com/problems/diameter-of-binary-tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import defaultdict class Solution: def __init__(self): self.graph = d...
from .inspired import * from .kbrd import * from .kgsf import * from .redial import * from .tgredial import *
import asyncio from unittest import mock import distributed from distributed.core import CommClosedError from distributed.utils_test import _LockedCommPool, gen_cluster, inc, slowinc async def wait_for_state(key, state, dask_worker): while key not in dask_worker.tasks or dask_worker.tasks[key].state != state: ...
import os import discord from dotenv import load_dotenv load_dotenv() ID = os.getenv("CLIENT_ID") TOKEN = os.getenv("ACCESS_TOKEN") DISCORD = os.getenv("DISCORD_TOKEN")
import pandas as pd from matplotlib import pyplot as plt import numpy as np import os import traceback from tensorboard.backend.event_processing.event_accumulator import EventAccumulator from collections import defaultdict # Extraction function def tflog2pandas(path: str) -> pd.DataFrame: """convert single tensor...
from sklearn.metrics import * import torch import torch.nn as nn import torch.nn.functional as F from keras.utils import to_categorical import sys # Utility to return predictions def return_classes(logits, dim=-1): #print(logits.shape) _, predicted = torch.max(logits,dim) #print(predicted.shape) return...
#!/usr/bin/python3 """ Contains the TestReviewDocs classes """ from datetime import datetime import inspect from models import review from models.base_model import BaseModel import pep8 import unittest Review = review.Review class TestReviewDocs(unittest.TestCase): """Tests to check the documentation and style o...
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth import get_user_model from dashboard.models import Roles, UserRoles, AclPermissions from dashboard.serializers import create_aclpermissions_for_role class Command(BaseCommand): help = 'Creates Admin and SuperAdmin' def ...
def data_reverse(data): """ Picks the stream of data and converts it into bits, then reverses the input :param data: :return: """ # byte store byte_store = [] reversed_bytes = [] # length of 8/16/32/64/ multiple of 8 data_len = len(data) count = 0 while count < data_len...
"""add language to posts Revision ID: ca67f903eea1 Revises: 6b4e7aacf65e Create Date: 2020-03-13 21:52:32.279490 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ca67f903eea1' down_revision = '6b4e7aacf65e' branch_labels = None depends_on = None def upgrade()...
import bpy, os from glob import glob def load_shapes(fdir,input_pattern,crs,scale=(1,1,1)): #function to load building shapefiles files = glob(fdir+input_pattern) dir_name = os.path.basename(fdir) if not bpy.data.collections.get(dir_name): #create collection collection = bpy.data...
# to read model and to guess input images given out of database of mnist # written by Banic # partly referred from mnist_eval import tensorflow as tf import numpy as np import os from PIL import Image import mnist_inference import mnist_train PICS_PATH = "./pictures" PIC_NAME = "7.png" def read_pic(): image_raw...
# Copyright 2019 DeepMind Technologies Limited. 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 ...
# Copyright 2015 Ufora 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 i...
############################################################################### # # Copyright 2012 Pants Developers (see AUTHORS.txt) # # 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 # # h...
import os import numpy as np import logging from qcodes.instrument.base import Instrument from qcodes.instrument.parameter import ManualParameter from qcodes.utils import validators as vals import ctypes try: from ctypes.wintypes import MAX_PATH except ValueError: logging.log(1, 'MAX_PATH in ctypes.wintypes n...
from targ import CLI def add(a: int, b: int): """ Add the two numbers. :param a: The first number. :param b: The second number. """ print(a + b) if __name__ == "__main__": cli = CLI() cli.register(add) cli.run(solo=True)
import unittest import operator from importlib import import_module component = import_module('run.helpers.merge') class merge_dicts_Test(unittest.TestCase): # Tests def test(self): self.assertEqual( component.merge_dicts( {'a': 1}, {'b': 2}), ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Genetic Algorithm from scratch Jason Brownlee, Machine Learning Algorithms in Python, Machine Learning Mastery, Available from https://machinelearningmastery.com/machine-learning-with-python/, accessed April 15th, 2018. """ # genetic algorithm search for continuous fun...
import os.path as path import argparse def validate(ARGS): """ Validate command line arguments Parameters ---------- ARGS : Namespace Command line arguments """ # check for files existing nonex_files = [b for b in ARGS.bed if not path.exists(b)] if len(nonex_files) != 0: ...
import numpy as np import tensorflow as tf ip_tensor_8x8 = np.array([[-0.8520309,-0.8490718, 1.129514,-1.3910682,-1.3713549,-1.2450725,-0.64018744, -0.58683217], [0.61351526,-0.7573147,-1.0944875,-1.3194267,-1.0564152,-1.0523492,-0.8647979, -0.5105319], [-1....
from ipaddress import IPv6Address from mld.utils import TYPE_CHECKING from .. import mld_globals from mld.packet.PacketMLDHeader import PacketMLDHeader from mld.packet.ReceivedPacket import ReceivedPacket from . import NoListenersPresent, ListenersPresent, CheckingListeners if TYPE_CHECKING: from ..RouterState imp...
class Solution: def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: def Preorder(root,cursum): nonlocal ans if not root:return cursum += root.val if cursum == targetSum: ans += 1 ans += h[cursum-targetSum] h[cursum]+=1 ...
import math from .. import command from .. import misc from .menu import Menu class Message(Menu): """ Show a static message. """ def __init__(self, parent, options): Menu.__init__(self, parent, options) self.text = "" # def setText(self, text): # self.text = text ...
import os import time import argparse import numpy as np import matplotlib.pyplot as plt from matplotlib import animation from sklearn.datasets import make_blobs from sklearn.preprocessing import StandardScaler from models.k_nearest_neighbors import KNearestNeighbors plt.style.use('seaborn') def getArguments(): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import blog.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_auto_20141231_0859'), ] operations = [ migrations.AlterField( ...
#!/usr/bin/env python # -*- coding:UTF-8 -*- import fnmatch pattern='fnmatch_*.py' print'Pattern :',pattern print'Regex :',fnmatch.translate(pattern)
#!/usr/bin/env python3 import datetime import logging import os import time import json from logging.handlers import RotatingFileHandler import requests import sns import secret from kafka import KafkaProducer import kafka_producer logger = logging.getLogger() logger.setLevel('INFO') log_path = os.path.basename(__fi...
number_of_workers = 4 config_SAC = { # "gamma": 0.5, # === Model === # Use two Q-networks (instead of one) for action-value estimation. # Note: Each Q-network will have its own target network. "twin_q": True, # Use a e.g. conv2D state preprocessing network before concatenating the # result...
from zope.interface import Interface class IDutchAuction(Interface): """ Dutch Auction """
from datetime import timedelta import pytest from django.conf import settings from django.contrib.auth.models import Group from guardian.shortcuts import get_perms from grandchallenge.workstations.models import Session, Workstation from tests.factories import SessionFactory, UserFactory, WorkstationFactory from tests...
from flask import Flask, render_template, request from werkzeug.utils import secure_filename import os from pdf import read_liver_pdf from body_models import model_liver clf = model_liver() UPLOAD_FOLDER = os.getcwd() ALLOWED_EXTENSIONS = set(['pdf']) template_dir = os.getcwd()+'/docs/' app = Flask(__name__, template...
#!/usr/bin/python # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later...
from typing import List, DefaultDict from collections import defaultdict from datetime import date, datetime from pathlib import Path import plotly.express as px from config import PLOTLY_IMAGES_PATH def convert_str_to_date(str_date) -> date: if isinstance(str_date, date): return str_date if isinstan...
import os, sys, time, datetime import biothings, config biothings.config_for_app(config) from config import DATA_ARCHIVE_ROOT from biothings.dataload.dumper import HTTPDumper from biothings.utils.common import gunzipall class Geno2MPDumper(HTTPDumper): SRC_NAME = "geno2mp" SRC_ROOT_FOLDER = os.path.join(DA...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
from pnc_cli import makemead import random import string def test_eap(): makemead.make_mead(config="cfg/eap.cfg", product_name="Test pnc-cli eap", product_version="7.1", suffix=get_suffix(), external=True) def test_sso(): makemead.make_mead(config="cfg/sso.cfg", product_name="Test pnc-cli sso", product_versio...
#----------------------------------------------------------------------------- # Title : PyRogue CameraLink Channel #----------------------------------------------------------------------------- # Description: # PyRogue CameraLink module #----------------------------------------------------------------------------...
""" Add tables to support user and globally restricted searchtags. Revision ID: a49795aa2584 Revises: 882fe6ace5c7 Create Date: 2016-10-01 03:00:22.859648 """ # revision identifiers, used by Alembic. revision = 'a49795aa2584' down_revision = '882fe6ace5c7' from alembic import op # lgtm[py/unused-import] import sq...
import sys import requests import random from html.parser import HTMLParser import html from urllib.parse import unquote from datetime import datetime class MyHTMLParser(HTMLParser): def __init__(self, title): HTMLParser.__init__(self) self.house_codes = list() self.sale_status = list() ...
""" This is the entry module to the Cnc-Calculator GUI application """ from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.config import Config from kivy.lang import Builder Config.set('graphics', 'resizable', False) Config.set('graphics', 'width', '800') Config.set('graphics', 'height', '600'...
# -*- coding: utf-8 -*- """ Created on Tue Jan 25 09:37:08 2022 @author: Juliano """ from time import sleep import os import winsound def menu1():# tela inicial de entrada os.system('cls') print('*'*52) print('*'*52) print('*'*10," "*30,"*"*10) print('*'*10," "*30,"*"*10) print('*'*10," ...
""" This file contains the logic for loading data for all typing tasks. # TODO license """ import os import json, csv from abc import ABC, abstractmethod from collections import defaultdict, Counter from typing import * from transformers.tokenization_utils import SPECIAL_TOKENS_MAP_FILE from openprompt.utils.logging...
#!/usr/bin/python # -*- coding:utf-8 -*- from setuptools import setup setup( name='kucoin-python', version='v1.0.5', packages=['kucoin', 'kucoin/base_request', 'kucoin/margin', 'kucoin/market', 'kucoin/trade', 'kucoin/user', 'kucoin/websocket', 'kucoin/ws_token'], license="MIT", aut...
"""Module for generic model operations mixin.""" from app import db class ModelOperations(object): """Mixin class with generic model operations.""" def save(self): """ Save a model instance """ db.session.add(self) db.session.commit() return self def upda...
# -*- coding: utf-8 -*- """ =============================== Computing source space SNR =============================== This example shows how to compute and plot source space SNR as in :footcite:`GoldenholzEtAl2009`. """ # Author: Padma Sundaram <tottochan@gmail.com> # Kaisu Lankinen <klankinen@mgh.harvard.edu...
import sys sys.path.append("../") from makerbean import 数据机器人 # 加载数据 原始订单 = 数据机器人.加载内置数据('商品订单数据') # 查看订单列名称 # 查看合并统计不同订单状态 # 筛选已付款订单 付款完成订单 = 原始订单.文字筛选('订单状态', '已付款') # 查看下单时间列 # 筛选2020年以后的订单 二零年度订单 = 付款完成订单.数据筛选('下单时间', 最小值=20200101) # 整理地点格式,截取到省级 地点格式整理 = 二零年度订单.文字裁剪('地点', 截止字符=['北京市', '天津市', '上海市', '重庆市', '自治区',...
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2017, Dorian Soergel # # 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 th...
import numpy as np import networkx as nx import cPickle as cp import random import ctypes import os import sys from tqdm import tqdm sys.path.append( '%s/mvc_lib' % os.path.dirname(os.path.realpath(__file__)) ) from mvc_lib import MvcLib sys.path.append( '%s/../memetracker' % os.path.dirname(os.path.realpath(__file__...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
from __future__ import absolute_import from sqlalchemy import Column, Integer, ForeignKey, Float, LargeBinary, Boolean from sqlalchemy.orm import relationship, backref from .. import Base from .. import creator from ..dictionary import DictionaryItem from ..halo import Halo class HaloLink(Base): __tablename__ = ...
import os import platform import unittest from conans.client import tools from conans.model.ref import ConanFileReference, PackageReference from conans.paths import CONANFILE from conans.test.unittests.util.tools_test import RunnerMock from conans.test.utils.conanfile import MockConanfile from conans.test.utils.tools ...
#!/usr/bin/python3 # Imports import xml.etree.ElementTree as ET from tkinter import * from tkinter import ttk import numpy as np import numpy.polynomial.polynomial as poly import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk import tkinter as tk # Variab...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Results Parser import os import sys import getopt from pprintpp import pprint if __name__ == '__main__': from py_sources import ( parseNDJSON, pandasJsonNormalizeDaily, exportResultsCSV, exportResultsHTML, exportResultsExc...
#!/usr/bin/python import os from shutil import copyfile class ProjectGenerator: project = 'application' conf = 'ansible.cfg' env_000 = '000_cross_env_vars.yml' tasks_file = ['tasks_pre.yml', 'tasks_post.yml'] project_conf = '' tmp_conf = '' role_dir = ['defaults', 'files', 'tasks', 'templa...
""" Copyright 2014 Rackspace 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 dist...
# coding=utf-8 # Copyright 2021 The Robustness Metrics 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
import textwrap import numpy as np from bio_test_artifacts._loader import Load FASTA_SUFFIX = ".fasta" FASTA_HEADER = "biotestartifact{n}" DEFAULT_NUCLEOTIDE_ALPHABET = "ATGC" DEFAULT_PROTEIN_ALPHABET = "ACDEFGHIKLMNPQRSTVWY" def fasta_generate(num_records=20, record_length=100, random_seed=42, target_file=None, ...
import urllib.request import json cltjson = {"$class": "com.devb.consolidated.Client", "clientId": "9998", "name": "trial"} prtjson = {"$class": "com.devb.consolidated.Portfolio", "portfolioId": "9998", "jsonAsset": '{"agencyCaseNumber": "00137689", "amortizationTypeDescription": "Mortgage", "amount": 200000.5...
from django.db import models from django.contrib.auth.models import User from events.models import Event from conversation.models import ConvoWall def getPath(instance, filename): path = 'course_' + str(instance.id) + '/' + filename return path class Course(models.Model): course_users = models.ManyToMan...
""" # SocialDistancingNet This program helps the fight against recent pandemic caused by the corona virus. To prevent the spread of the virus its important that all of us follow the social distancing guidelines proposed by the World Health Organization. This program is capable of identifying violations of social distan...
# coding=utf-8 # Copyright 2020 The Meta-Dataset 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
"""Create initial tables Revision ID: 000000000000 Create Date: 2019-09-12 17:18:07.401658 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '000000000000' down_revision = None branch_labels = None depends_on = None de...
import matplotlib as mpl import matplotlib.pyplot as plt import random import numpy as np from .quadtree import QuadTree class World(object): """ Create a new world for the simulation. Create a new world for pedestrians and obstacles. Args: height: height (meters in y) of this world widt...
#!/usr/bin/env python3 """ udp_client: Allows to chat with one other udp client. It first connects to a udp_server and register itself and requests the connection information from a peer. When the server response with valid connection-info then you can start chatting. """ import argparse impor...
"""NDB -- A new datastore API for the Google App Engine Python runtime.""" __version__ = '0.9.3'
from functools import partial import pytest from caio import python_aio_asyncio from aiofile import AIOFile, async_open try: from caio import thread_aio_asyncio except ImportError: thread_aio_asyncio = None try: from caio import linux_aio_asyncio except ImportError: linux_aio_asyncio = None class...
import rdflib, sys def get_labels_count (rdf): d = {} for s,p,o in rdf: d[p] = d.get(p,0) + 1 sorted_d = [(k, v) for k, v in sorted(d.items(), key=lambda item: item[1])] sorted_d.reverse() return sorted_d def print_config(lst, path_to_config): i = 0 with open(path_to_co...
import csv import logging import multiprocessing import sys from cgi import test import hydra import numpy as np import torch import torch.nn as nn import torch.optim as optim from omegaconf import OmegaConf from sklearn.metrics import accuracy_score from torch_geometric.nn import Node2Vec import wandb from models.FF...
import csv import random import time from datetime import datetime from pathlib import Path import geopandas from matplotlib import pyplot as plt from tqdm import tqdm import python_tools as pt import switzerland_db # if True neither checks the websites nor logs the data debug_mode = False def main(): # dictio...
# -*- coding: utf-8 -*- import re import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours class MerkurSpider(scrapy.Spider): name = "merkur" item_attributes = {"brand": "Merkur", "brand_wikidata": "Q1921857"} allowed_domains = ["merkurmarkt.at"] start_urls...
import os import logging from confluent_kafka import Producer, Consumer logger = logging.getLogger(__name__) CONFIG = {'bootstrap.servers': os.getenv('KAFKA_TOPIC_SERVER')} class KafkaUtil: def __init__(self, conf=None): self.conf = conf or CONFIG self.producer = Producer(self.conf) ...
# Take cache counters for various datasets, orderings and algorithms # Output Latex table of cache-miss rates # ----- Example of input ----- # 3407283.482795 task-clock (msec) # 1.000 CPUs utilized # 9,540,291,508,200 cpu-cycles # 2.800 GHz # 4,038,838,258,530 instruct...
#!/usr/bin/env python import os from setuptools import setup, find_packages this_file = os.path.dirname(__file__) setup( name="gpytorch", version="0.1", description="An implementation of Gaussian Processes in Pytorch", url="https://github.com/cornellius-gp/gpytorch", author="Jake Gardner, Geoff Pl...
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/master/COPYING """Tests for the pylint checker in :mod:`pylint.extensions.check_docstring """ import os.path as osp import unittest from pylint import checkers from pylint.extensions.d...
from flask import Flask, jsonify, request, render_template from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///twitter_app.db" db = SQLAlchemy(app) migrate = Migrate(app, db) class User(db.Model): """Gets the user in...
salario = float(input('Digite o salário: R$')) base = salario imposto = 0 if base > 3000: imposto = imposto + ((base - 3000) * 0.35) base = 3000 if base > 1000: imposto = imposto + ((base - 1000) * 0.20) print(f'Salário: R${salario:6.2f} | Impostos a pagar: R${imposto:6.2f}')