content
stringlengths
5
1.05M
# ==================================================================== # 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 re...
# Changed News to Research from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class ResearchConfig(AppConfig): name = "bootcamp.research" # changed from name = "bootcamp.news" verbose_name = _("Research")
#encoding: utf-8 # to many string concatenation here, run with pypy import sys def buildngram(wd,n): lwd=len(wd) ngt="__ngram"+str(n)+"__" prs=[wd[ind:ind+n] for ind in xrange(lwd-n+1)] rs=[ngt+u for u in prs] return rs, prs def buildunig(wd): return ["__char__"+wdu for wdu in wd] def colngrams(wd): rs=buil...
import logging from typing import TYPE_CHECKING from gunicorn.app.base import Application from simple_di import Provide, inject from ..configuration.containers import BentoMLContainer logger = logging.getLogger(__name__) if TYPE_CHECKING: # make type checkers happy from .model_app import ModelApp class Guni...
import math from mathutils import Euler import bpy from .left4dead2_entity_classes import * from .halflife2_entity_classes import entity_class_handle as hl2_entity_classes from .halflife2_entity_handler import HalfLifeEntityHandler local_entity_lookup_table = HalfLifeEntityHandler.entity_lookup_table.copy() local_ent...
import asyncio import logging import os import platform import re import shutil import string import random from functools import wraps __all__ = [ 'REMOTE_RE', 'REMOTE_VMID_RE', 'SPICE_VIEWER_PATHS', 'parse_key_value_string', 'get_vmid_resource', 'is_cygwin', 'find_path', 'randstring'...
import requests from lxml import etree profile_url = "https://anipython.com/user/profile/" # 下面设置的 sessionid 以你自己实际获取的为准 headers = { "Cookie": "sessionid=f11pwkldxclkjx3kt5tzixl4uyf5d3y2" } # headers -> Cookie -> sessionid # dajngo 后端通过 sessionid 检验用户 response = requests.get(url=profile_url, headers=headers) ele...
from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command from django.conf import settings from django.db import connection from django.db.models import Max, Min from contactnetwork.distances import * from contactnetwork.models import * from protein.models import...
__all__ = ['interpolation_slicing_default_param'] def interpolation_slicing_default_param(key): """ Returns the default parameters with the specified key. """ if key in default_parameters: return default_parameters[key] else: raise ValueError('The parameter with key : ' + str(key) + ...
"""Python wrapper for the Advent of Code leaderboard API""" from datetime import datetime from typing import Dict from marshmallow_dataclass import dataclass import requests @dataclass class Timestamp: get_star_ts: int def as_datetime(self) -> datetime: return datetime.utcfromtimestamp(self.get_star...
"""Module for exposing valid functions for nodes.""" import fatd.transform.data # use a dict lookup here so you can't just execute arbitrary code funcs = { 'fatd.transform.data.mean': fatd.transform.data.mean, 'fatd.transform.data.median': fatd.transform.data.median, 'fatd.transform.data.threshold': lambd...
import json class Menu: def __init__(self, data): self.children = [] self.cls = '' self.inject(data) def inject(self, data): for key in data: setattr(self, key, data[key]) def add_child(self, child): self.children.append(child) def has_children(sel...
""" Tests for filip.semantics.ontology_parser.parser """ import collections import unittest from pathlib import Path from filip.semantics.vocabulary import Vocabulary, DatatypeType from filip.semantics.vocabulary_configurator import VocabularyConfigurator class TestModels(unittest.TestCase): """ Test class ...
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyMarkupsafe(PythonPackage): """MarkupSafe is a library for Python that implements a unico...
from appdirs import * from decouple import AutoConfig, config import os import shutil from os.path import exists #DATASTORE setup file for .env and hosts.csv files. def create_config_files(path: str): cwd = os.getcwd()#curr working dir if '\\' in path: path += '\\' platform = 'putty-windows' ...
#-*- utf-8 -*- """ Its not my origin code , i found it somewhere on stackoverflow """ import os import time from PIL import Image def fullpage_screenshot(driver, file): print("Starting chrome full page screenshot workaround ...") total_width = driver.execute_script("return document.body.offsetWidth"...
import torch from torchvision import datasets, transforms from .datagen import DataGenerator import params def get_svhn(train): """Get USPS dataset loader.""" # image pre-processing if train: transform = transforms.Compose([ transforms.RandomCrop((28)), transforms.ToTe...
# -*- coding: utf-8 -*- # flake8: noqa __title__ = 'Jindanlicai' __version__ = '1.0.0' __author__ = 'WEI HAITONG' __license__ = 'MIT License' __copyright__ = 'Copyright 2017 WEI HAITONG'
from __future__ import absolute_import from xml.etree import ElementTree from . import plexserver from . import plexresult from . import http from . import util class PlexRequest(http.HttpRequest): def __init__(self, server, path, method=None): server = server or plexserver.dummyPlexServer() htt...
import numpyro numpyro.enable_x64() import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) import argparse import covid.util as util import configs import numpy as onp # Get the path of this script basepath = os.path.abspath(os.curdir) if __name__ == "__main__": p...
""" support.py Convenience functions for X12 Processing. """ import datetime import functools import os from typing import Union, Dict from pydantic import validator, BaseModel from .config import IsaDelimiters # maps a X12 transaction implementation version to the latest version in the "major" version X12_IMPLEMEN...
import pygame import sys import ball import random import graphics.render as render from ball import Ball # TODO: Make it so you can select, edit, delete planets def check_event(running): for event in pygame.event.get(): # Check for mouse input if event.type == pygame.MOUSEBUTTONDOWN: ...
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved. from fractions import Fraction from typing import Any, List import torch from ego4d.features.config import FeatureExtractConfig, get_transform, Video from pytorchvideo.data import UniformClipSampler from pytorchvideo.data.encoded_video import E...
from django.urls import path from . import views # localhost:8000/noteables/ urlpatterns = [ path('', views.index, name='index'), path('logout', views.logout, name='logout'), path('note/<int:id>', views.open_note, name='open_note'), path('update_note/<int:id>', views.update_note, name='update_note'), ...
# MySQL Workbench Plugin from wb import * import grt import mforms ModuleInfo = DefineModule("ModelDocumentation", author="TheOwls", version="1.0.2", description="Generate Markdown documentation from a model for DevOps") # This plugin takes no arguments @ModuleInfo.plugin("info.theowls.wb.documentation", caption="Ge...
import os import numpy as np from tqdm import tqdm import torch from torch import nn from torch.quantization import get_default_qconfig from torch.quantization.quantize_fx import convert_fx, prepare_fx from torch.quantization import QuantStub, DeQuantStub from torch.utils.mobile_optimizer import optimize_for_mobile MO...
# プライオリティキューの利用 import heapq n, m = map(int, input().split()) a = list(map(int, input().split())) # 最大の値段を取り出すために、全て(-1)を掛ける a = list(map(lambda x: x * (-1), a)) heapq.heapify(a) # 割引券を使い切るまで行う while m != 0: # 最大の値段を取り出す price = heapq.heappop(a) * (-1) # 割引 price //= 2 m -= 1 # プライオリティキューへ戻す ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jun 5 13:40:00 2017 @author: zqwu """ import os import pandas as pd import numpy as np import joblib import csv from pnet.data import SequenceDataset from pnet.data import merge_datasets def load_sequence(path, load_pdb=False): """ Load sequence cs...
import re from common.utils import plex_find_lib, text_format from common.dictionary import translate_text, convert_chinese_number def replace_episode(plex, plex_title, language="", input_summary=""): show = plex_find_lib(plex, 'show', plex_title) if input_summary: with open(input_summary, 'r') as fi...
import tensorflow as tf from .basedist import Distribution from ..utils import sum_except_batch class Uniform(Distribution): """Uniform distribution. """ def __init__(self, min=0., max=1.): """Initializer, assume the range [min, max). Args: min: tf.Tensor, [tf.float32; [B, ......
# Crie um codigo em Python que teste se o site Pudim # está acessivel pelo computador usado import urllib import urllib.request try: s = urllib.request.urlopen('http://www.pudim.com.br') except (urllib.error.URLError): print('O site Pudim não esta acessivel.') else: print('Consegui acessar o site Pudim com...
import toppra as ta import toppra.constraint as constraint import toppra.algorithm as algo import numpy as np import matplotlib.pyplot as plt import time import openravepy as orpy ta.setup_logging("INFO") def main(): # openrave setup env = orpy.Environment() env.Load("robots/barrettwam.robot.xml") en...
from setuptools import setup, find_packages setup( name='ipinfo', version='0.1.0', description='A package to to get information on an IP address using whatismyipaddress.com', author='Julien de la Bruère-Terreault', author_email='drgfreeman@tuta.io', url='https://github.com/DrGFreeman/IP-Info', ...
match x: case (1 | 2 | 3, [1 | 2, 3, ], Class(1 | 2, 3) ): pass
import cv2 from RastreioDoOlhar import InformacoesDaImagem olhar = InformacoesDaImagem() webcam = cv2.VideoCapture(0) webcam.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) webcam.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) while True: # Coletando cada uma das imagens que a webcam fornece _, imagem = webcam.read() # Enviand...
# coding=utf-8 """ Common methods for index integration tests. """ import itertools import multiprocessing import os import re from pathlib import Path from time import sleep import pytest import boto3 import datacube.scripts.cli_app import datacube.utils import fsspec from click.testing import CliRunner from datacube...
#!/usr/bin/env python2.7 #run: ./generator.py -f dataset.csv -n 100 import csv import random import argparse import string chars = [char for char in string.ascii_lowercase] parser = argparse.ArgumentParser(description='user daily frofiles') parser.add_argument("-f", "--outfile", dest="outfile", help="Output file", re...
#Dada la lista: #lista2 = [1,3, 'cadena', 4, 'vvvv', 7, 'bamboo', 0, 'ratones', 'celular'] #Mostrar los elementos siguiendo las reglas: #Si el elemento es de tipo cadena mostrar “Es una cadena y vale {valor de la #cadena}” #Si el elemento es un número mostrar el elemento correspondiente al valor del #elemento. Por ejem...
# -*- coding: utf-8 -*- """ Created on Wed Jun 07 16:33:11 2017 http://v.youku.com/v_show/id_XMjc2OTI4MzMxNg==.html?from=s1.8-1-1.2&spm=a2h0k.8191407.0.0 @author: sunhz """ from urllib2 import urlopen import re url = 'http://jandan.net/duan' req = urlopen(url) html = req.read() html_str = html.decode('...
import socket alert = 'test' stomp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) stomp.connect(('localhost', 61613)) stomp.send('CONNECT\n\n\x00') recv = stomp.recv(4096) if 'CONNECTED' in recv: stomp.send('SEND\ndestination:%s\n\n' % '/queue/test') stomp.send(alert) stomp.send('\x00') else: pr...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"Field_on_grid": "field_on_grid.ipynb", "NTHREAD": "field_on_grid.ipynb", "EPS": "field_on_grid.ipynb"} modules = ["field_on_grid.py"] doc_url = "https://{saitosmst}.github.io/two_point_cl...
""" | Copyright (C) 2017 Johannes Schlatow | TU Braunschweig, Germany | All rights reserved. | See LICENSE file for copyright and license details. :Authors: - Johannes Schlatow """ from pycpa import * def run(s, paths=list(), plot_in=list(), chains=list()): # graph the system to visualize the architect...
# region Imports # ========================================================================== # Uncomment this patch if running the example within of the pipelayer project # import app._path_patch # NOQA F401 import json from typing import Any, Tuple from pipelayer import Pipeline from app.filter.create_response im...
# -*- coding: utf-8 -*- """ Created on Wed Jan 22 12:45:01 2020 @author: Raj """ ''' Script to constantly poll a folder of data and generate an image from that USAGE: Open Anaconda prompt Navigate to folder where this file is located python polling.py "FOLDER WHERE DATA ARE BEING SAVED" '...
import re import os import os.path as osp import torchvision.datasets as datasets from torchvision.datasets.folder import has_file_allowed_extension, default_loader, IMG_EXTENSIONS def make_dataset_with_annopath(directory, annotation_path, extensions, is_valid_file=None): instances = [] directory = os.path.e...
import numpy as np def get_tst_mats(shape, ncol=3, seed=None): """ Returns test matrices/vectors for a matrix M. M.dot(V) M.dot(v1) M.dot(v2) M.T.dot(U) M.T.dot(u1) M.T.dot(u2) V/U are matrices, v1/u1 are arrays with one dimension (e.g. shape (5,)) and v2/u2 are arrays with t...
import argparse from pathlib import Path import time from glob import glob import os from tqdm import tqdm import shutil import torch import wandb import yaml from torch.nn.utils import clip_grad_norm_ from torch.optim import Adam, Adamax, AdamW, RAdam, NAdam from torch.optim.lr_scheduler import ReduceLRO...
DEBUG = False colors = ['\x1b[0m', '\x1b[6;30;42m', '\x1b[2;30;41m', '\x1b[2;33;44m'] def network_log(s, color_idx=None): if DEBUG: if color_idx is None: print(s) else: print(colors[color_idx]+s+colors[0]) ################### import torch import torch.nn as nn import torch.nn...
# Copyright (c) 2017-present, Facebook, 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. # ############################################################################## # # Based on: # Copyright (c) 2017-present, Faceb...
# Generated by Django 3.0.4 on 2020-04-08 02:07 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('team', '0006_profile_owner'), ] operations = [ migrations.AlterModelOptions( name='membership', options={'ordering': ['year'...
import os from collections import defaultdict def read_sentences_context(directory): """ For contextual probing tasks Reads the train, dev and test files of a directory and returns the sentences and the indices of the words which are used in the probing tasks. :param directory: :return: dict with ...
import json from pathlib import Path from collections import OrderedDict from collections.abc import Callable import torch from kyoto_reader import BasePhrase def read_json(fname): if isinstance(fname, str): fname = Path(fname) with fname.open('rt') as handle: return json.load(handle, object_...
#!/usr/bin/env python3 """Run pre-commit checks on the repository.""" import argparse import enum import os import pathlib import subprocess import sys class Step(enum.Enum): REFORMAT = "reformat" MYPY = "mypy" PYLINT = "pylint" TEST = "test" DOCTEST = "doctest" CHECK_INIT_AND_SETUP_COINCIDE =...
# -*- coding: utf-8 -*- # This script takes a csv with: country names,country adjectives,inhabitant names # and adds them to the lexicon with the proper relations if they do not exist already, # for example, # - country_name "Germany" noun, massNoun, hypernym "country" # - country_adjective "German" adjective, pertai...
#!/usr/bin/env python3 #### PYTHON IMPORTS ################################################################################ import csv import os import sys from pathlib import Path from shutil import copyfile #### PACKAGE IMPORTS ############################################################################### from s...
"""This module contains BayesianOptimization- and BOLFI-classes.""" __all__ = ['BayesianOptimization', 'BOLFI'] import logging import matplotlib.pyplot as plt import numpy as np import elfi.methods.mcmc as mcmc import elfi.visualization.interactive as visin import elfi.visualization.visualization as vis from elfi.l...
import unittest from foo import * class TestFoo(unittest.TestCase): def test_named(self): self.assertEqual(get_foo(), 'Foo!') class TestFibonacci(unittest.TestCase): def test_fibonacci(self): self.assertEqual(fibonacci(0), 1) self.assertEqual(fibonacci(1), 1) self.assertEqual(fibonacci(2), 2) self.asser...
# Copyright 2017 The Chromium 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 json import unittest import mock from dashboard.services import buildbucket_service _BUILD_PARAMETERS = { 'builder_name': 'dummy_builder', ...
""" Tests if vtk and numpy have been loaded """ import time import numpy as np import vtkInterface def ShowWave(fps=30, frequency=1, wavetime=3, interactive=False): """ Plot a 3D moving wave in a render window. Parameters ---------- fps : int, optional Maximum frames pe...
import torch.nn as nn class SpanExtractor(nn.Module): pass
# -*- coding: utf-8 -*- """ Created on Mon Feb 1 22:07:15 2021 @author: m-lin """ ''' アンサンブル ''' # ライブラリのインポート import pandas as pd # 提出用サンプルの読み込み sub = pd.read_csv('./data/sample_submission.csv') # 予測データの読み込み lgb_sub = pd.read_csv('./submit/houseprices_LightGBM.csv') xgb_sub = pd.read_csv('./su...
# main app file, simple bottle app from bottle import route, run, request, static_file from ladder_bot import LadderBot from cat_macro_bot import CatMacroBot # instances to be used bots = (LadderBot(), CatMacroBot()) # 8080 was already taken on my host PORT = 8081 # returns static page with basic info @route("/") d...
from django.db import models class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Place(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(se...
#!/usr/bin/env python3 import sys import os import socket import time from argparse import ArgumentParser import json import math import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D parser = ArgumentParser() parser.add_argument("-p", type=int, help="port No.", default=0x94...
# Program no. 1 # Laboratory Practice-I # contact@mitu.co.in import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris iris = load_iris() data_set = pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['tar...
import org.transcrypt.autotester import basic_tests autoTester = org.transcrypt.autotester.AutoTester () autoTester.run( basic_tests, "basic_tests" ) autoTester.done()
import datetime import pytest from app.internal.celebrity import get_today_month_and_day CELEBRITY_PAGE = "/celebrity" FAKE_TIME = datetime.date(2018, 9, 18) BAD_DATES = [ datetime.date(2021, 1, 1), datetime.date(1789, 7, 14), datetime.date(1776, 7, 4), datetime.date(1945, 1, 27), datetime.date(...
import tensorflow as tf import gym import numpy as np # Same as 05 file, just no training, just loads the pre-trained model. ########################## ### VARIABLES ########### ######################## num_inputs = 4 num_hidden = 4 num_outputs = 1 learning_rate = 0.01 initializer = tf.contrib.layers.variance_sca...
import matplotlib.pyplot as plt import mahotas photo = mahotas.demos.load('luispedro') photo = mahotas.colors.rgb2sepia(photo) plt.imshow(photo) plt.axis('off') plt.show()
import argparse import logging import os import sys import re import base64 import ConfigParser import json import uuid import time import yaml import copy import subprocess import pexpect import tempfile import tarfile import hashlib import shutil import traceback import urlparse import threading import psutil from co...
from django.http import HttpResponseRedirect from django.shortcuts import render from django.forms import formset_factory from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView, FormView from django.views.generic.detail import SingleObjectMixin from accounts.models import ...
from matplotlib import pyplot as plt import numpy as np data = np.random.random((10,10)) plt.pcolormesh(data**4) plt.show() np.savetxt('tiles.txt', data)
""" Defines the connection to the database for the MovR app. """ from cockroachdb.sqlalchemy import run_transaction from sqlalchemy import create_engine from sqlalchemy.dialects import registry from sqlalchemy.orm import sessionmaker from .transactions import (add_user_txn, add_vehicle_txn, end_ride_txn, ...
from django.test import TestCase import json # Create your tests here. from django.test import override_settings @override_settings(DEBUG=True) class TestSearch(TestCase): @classmethod def setUpTestData(cls): # Set up data for the whole TestCase cls.user_from = {} cls.user_from["fir...
from __future__ import absolute_import from ...measurers.base import CpuTicks from ...obj.meta import SnapshotRegistrar __author__ = 'rotem' class CpuTicksUser(CpuTicks): """ Cpu usage user space (in ticks) """ __metaclass__ = SnapshotRegistrar def __init__(self): pass def name(self...
from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import check_password from .models import User, ID class AuthBackend(BaseBackend): def get_user(self, user_id): try: return User.objects.get(gid=user_id) except User.DoesNotExist: return No...
####### Global Variables ###### global webhook webhook = "" global webhook_on_browser webhook_on_browser = True global webhook_on_order webhook_on_order = True global webhook_on_failed webhook_on_failed = True global browser_on_failed browser_on_failed = True global dont_buy dont_buy = False global headless_brows...
# 1. Increase awareness of different types of biases that can manifest in model data. # 2. Explore feature data to proactively identify potential sources of bias before training a model. # 3. Evaluate model performance by subgroup rather than in aggregate. # # The data set is the Adult Census Income dataset, which is c...
import pandas as pd import sys from sentence_transformers import SentenceTransformer, InputExample from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator, BinaryClassificationEvaluator # Get the label as the value in the second place of the string (e.g., '(0, 5)' returns 0) def get_lab(x): retur...
import uuid from django.conf import settings from django.contrib.auth.hashers import check_password from .models import User from helpers.response import Response from helpers.generate_otp import get_otp from helpers.cache_manager import CacheManager from rest_framework_simplejwt.tokens import RefreshToken from noti...
import sys from unittest import TestCase import urllib3 class IdentifyTests(TestCase): def test_no_connection(self): import thola_client import thola_client.api.identify_api as identify import thola_client.rest as rest sys.stderr = None ansible_host = "demo-snmp.thola.io...
from django.db import models from django.contrib.auth.models import User from recipes.models import Recipe class Day(models.Model): dinner = models.ForeignKey(Recipe, related_name='dinner') supper = models.ForeignKey(Recipe, related_name='supper') def __unicode__(self): return self.dinner.name + ...
from email.message import EmailMessage import unittest from io import BytesIO from typing import List from pymisp.tools import EMailObject from pathlib import Path class TestEmailObject(unittest.TestCase): def test_mail_1(self): email_object = EMailObject(Path("tests/email_testfiles/mail_1.eml")) ...
#!/root/anaconda3/envs/envname/bin/python2.7 from plyfile import PlyData import random import os import sys import numpy as np import math from sem_seg import batch_inference from sem_seg import Predict # from sem_seg import batch_inference2 # from sem_seg import batch_inference3 import PointCloudUtils from struct im...
# Copyright (C) 2019 Vasiliy Sheredeko # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. from __future__ import annotations import itertools import logging from typing import Mapping, Callable from llvmlite import ir, binding from orcinus.colle...
#!/usr/bin/python import requests import pyquery import urllib3 import json class AutomatedWeb: # Initialize the class with browser opening #------------------------------------------------------------------------------------------------------------------ def __init__(self, simulatePage=None, debug=None): ...
import numpy as np import scipy from tqdm import tqdm import csv import os import re from sys import exit, argv import time import torch import imageio import cv2 from PIL import Image import matplotlib.pyplot as plt from lib.model_test import D2Net from lib.utils import preprocess_image from lib.pyramid import proce...
''' Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the l...
import discord import math from discord.ext import commands from typing import List class EmbedEntry: def __init__(self, title, content): self.title = title self.content = content class EmbedChain: # Should pass a list of lists? def __init__(self, data: List[EmbedEntry], *, limit: int, c...
#!/bin/python3 # author: Jan Hybs import os from typing import List from loguru import logger from pathlib import Path import cihpc.core.db as db from cihpc.core.parsers.schedule_parser import parse_args from cihpc.core.processing.project import ProcessProject from cihpc.core.utils import iter_project_definition from ...
from tools import get_nth_s_gonal, is_s_gonal def solve(): pentagonals = [get_nth_s_gonal(5, x) for x in range(1, 3001)] not_found = True i = 0 length = len(pentagonals) while not_found: j = i + 1 p = pentagonals[i] dif_not_found = True while j < length and dif_not_...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from unittest import TestCase from tests.utils import assert_equal_layers from polyaxon_schemas.initializations import GlorotUniformInitializerConfig, ZerosInitializerConfig from polyaxon_schemas.layers.local import LocallyConne...
"""Simple mechanism to register admin menu entries.""" # Standard Library import typing as t from collections import OrderedDict # Pyramid from pyramid.renderers import render from pyramid.request import Request # Websauna from websauna.system.core.traversal import Resource class Menu: """Menu is a collection o...
import socket import json class Exchange: def __init__(self, test, team_name='CHARLIETHEUNICORN', port=25000): if test: host_name = "test-exch-" + team_name else: host_name = "production" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host...
#!/usr/bin/env python import torch import torch.nn as nn class MLP(nn.Module): def __init__(self, input_dim, dropout_rate=0., num_classes=10): super(MLP, self).__init__() self.fc1 = nn.Linear(input_dim, 200) self.fc2 = nn.Linear(200, num_classes) self.relu = nn.ReLU(inpla...
#! /usr/bin/python3.6 import re import numpy import os from collections import defaultdict def getBelowIODef(rtl_path): if (not os.path.isfile(rtl_path)): print(f'[getBelowIODef] no file found for {rtl_path}') return None, None print(f'[getBelowIODef] process {rtl_path}') fp = open(rtl_path, 'r') pre...
#!/usr/bin/env python3 from os import getenv from pathlib import Path from shutil import rmtree from subprocess import run from subprocess import call import time import sys import yaml profile_folder = Path(getenv("PROFILES", "./profiles")).absolute() def die(msg: str): """Quit script with error message m...
""" homeassistant.components.notify.xmpp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Jabber (XMPP) notification service. Configuration: To use the Jabber notifier you will need to add something like the following to your config/configuration.yaml notify: platform: xmpp sender: YOUR_JID password: YOUR_JABBER_ACCOUNT_P...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.feature_selection...
import requests from bs4 import BeautifulSoup # post要傳的資料 payload = { 'from': '/bbs/Gossiping/index.html', 'yes': 'yes' } # 用session紀錄此次使用的cookie rs = requests.session() # post傳遞資料 response = rs.post("https://www.ptt.cc/ask/over18", data=payload) # 再get一次PTT八卦板首頁 response = rs.get("https://www.ptt.cc/bbs/Goss...