content
stringlengths
5
1.05M
palavras = ('viva', 'oi', 'gostar', 'amar', 'mestres', 'escolheste', 'todos', 'viver', 'nascer', 'certo', 'sistema') c1 = c2 = -1 c3 = 0 vogais = [] while len(palavras) > c1 + 1: c1 += 1 while len(palavras[c1]) > c2 + 1: c2 += 1 if palavras[c1][c2] in 'aeiou': vogais += palavras[c1][...
# Copyright 2013-2022 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.package import * class Bgpdump(AutotoolsPackage): """Utility and C Library for parsing MRT files""" ...
data_visits = geopandas.read_file("data/cod_mines_curated_all_opendata_p_ipis.geojson")
__author__ = 'dbaskette' # Download Software # Setup Repos # Make changes for Repo Distribution # Install Ambari-Server import json import argparse import tarfile import os import boto import boto.s3.connection from boto.s3.connection import Location from boto.s3.key import Key from simplethreads.ThreadPool impor...
#!/usr/bin/env python import pandas as pd import numpy as np from pandas import DataFrame, Series df = DataFrame({'int_col' : [1,2,6,8,-1], 'float_col' : [0.1, 0.2,0.2,10.1,None], 'str_col' : ['a','b',None,'c','a']}) print df # Extract just the float_col and int_col #print df.ix[:,['float_col','int_col']] print d...
from django.conf.urls import patterns, url from bespeak_meal import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), # name 用于 template,实现非耦合的 URL url(r'^order/$', views.order, name='order'), #url(r'', views.xx, name=''), #url(r'', views.xx, name=''), #url(r'', views.xx, nam...
from toee import * import char_editor def CheckPrereq(attachee, classLevelled, abilityScoreRaised): #BAB +2 inforaced by the DLL #Barbarian Rage Check if not char_editor.has_feat(feat_stunning_fist): return 0 #Wisdom 15 or greater if char_editor.stat_level_get(stat_wisdom) < 15: return 0 return 1
# *******TWO SUM******* # leetcode # Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # You may assume that each input would have exactly one solution, and you may not use the same element twice. # You can return the answer in any order. # Ex...
# Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import utils import os ANDROID_L_API = '21' VERSIONS = { '1.2.11-dev': { 'deploy': { 'i...
# Generated by Django 3.1.3 on 2020-11-27 15:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0004_assignment_due_date'), ] operations = [ migrations.AddField( model_name='assignment', name='marks', ...
from PhysicsTools.SelectorUtils.centralIDRegistry import central_id_registry import FWCore.ParameterSet.Config as cms # Common functions and classes for ID definition are imported here: from RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_tools \ import ( EleHLTSelection_V1, Isola...
from redis import Redis import constants import random # Redis Connection redis_db = Redis(host=constants.REDIS_HOST, port=constants.REDIS_PORT, password=constants.REDIS_PASSWORD) # Register an endpoint to an application def register_endpoint(app_name, host, port=80): redis_db.sadd(app_name, host + ':' + str(por...
def summarise_single_session(allen_dataset): ## Summary in print print( f"-----------Working on image plane {allen_dataset.ophys_experiment_id}" f"session {allen_dataset.ophys_session_id}------------" ) print(f"\tThis experiment has metadata {allen_dataset.metadata}") cell_specimen_...
import nltk import data_manipulation as dm from collections import Counter import pickle as pkl import os from ngram_model import Ngram from linear_interpolation import LinearInterpolation DATA = "data/sentences.csv" MODEL = "models/" N = 5 UNK_CHAR = '\u0001' WEIGHTS = [0.01, 0.04, 0.15, 0.3, 0.5] LOAD_WILI = True ...
from unittest.mock import patch from tests.test_rrpproxy_base import TestRRPProxyBase class TestRRPProxyModifyContact(TestRRPProxyBase): @patch('rrpproxy.RRPProxy.call') def test_calls_call_correctly(self, call_mock): response = self.proxy.modify_contact(contact='CONTACT-A', city='Amsterdam') ...
""" The MIT License (MIT) Copyright (c) 2016 Izhar Shaikh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,...
# coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlGekleurdWVCode(KeuzelijstField): """Codes voor een gekleurd wegvlak.""" na...
import particle as pr import initialize as ini import force as frc # import matplotlib # matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.animation as animation import random # import string # Defining the Initial condition lx=10 ly=10 par_num=6 max_mass=10 dt=0.04 rc=0.1 max_iter=200 # p...
""" Copyright 2019 Rahul Gupta, Aditya Kanade, Shirish Shevade. Indian Institute of Science. 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...
import os from utility import Catr catr = Catr() input_folder_path = '../StyleGAN2-ada/results/faces' for im in os.listdir(input_folder_path): if im.endswith(('.png', '.jpeg', '.jpg')): print('Processing : ', im) results = catr.evaluate(os.path.join(input_folder_path, im),input_folder_path.split('/...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from promotion.models import JoinApplication admin.site.register(JoinApplication)
from .coil_dataset import CoILDataset from .coil_sampler import BatchSequenceSampler, RandomSampler, PreSplittedSampler from .augmenter import Augmenter from .splitter import select_balancing_strategy
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from pirates.battle import EnemyGlobals from pirates.npc.BossBase import BossBase from pirates.pirate import AvatarTypes from pirates.effects.BossEffect import BossEffect from pirates.effects.BossAura import BossAura from direct.showbase.Dir...
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.core.mail import send_mail from django.db.models import Q from django.db import IntegrityError from django.http import Http404 from django.shortcuts import get_object_or_404 from django.urls im...
import re import collections from end2end.db_ops import MultiWozDB from end2end.utils.common_utils import * ''' Get db information ''' def get_db(dataset= 'multiwoz'): if dataset == 'multiwoz': from end2end.data.multiwoz.ontology import global_ontology as ontology data_config_name = os.path.join( ...
from sentence2vec.utils import glove2w2v from sentence2vec import SIF ######## 转换向量格式 ######## # 由于使用gensim的api进行转换,因此请填写绝对路径 glove_file = 'C:/data/glove.840B.300d.txt' # download from https://nlp.stanford.edu/projects/glove/ w2v_file = 'C:/data/glove_w2v.840B.300d.txt' glove2w2v(glove_file, w2v_file) #############...
from dataclasses import dataclass from dnsimple.struct import Struct @dataclass class Zone(Struct): """ Represents a Zone See https://developer.dnsimple.com/v2/zones """ id = None """The zone ID in DNSimple""" account_id = None """The associated account ID in DNSimple""" name = ...
import salabim as sim left = -1 right = +1 def sidename(side): return 'l' if side == left else 'r' def shortname(ship): s = '' for c in ship.name(): if c != '.': s = s + c return s def shipcolor(side): if side == left: return 'blue' else: return 'red' ...
import connexion import six import datetime import flask from swagger_server.models.query_object import QueryObject # noqa: E501 from swagger_server.models.query_response import QueryResponse # noqa: E501 from swagger_server.models.evaluation import Evaluation from typing import List, Dict # noqa: F401 from swagger_...
# coding: utf-8 """ karix api # Karix API lets you interact with the Karix platform using an omnichannel messaging API. It also allows you to query your account, set up webhooks and buy phone numbers. # noqa: E501 OpenAPI spec version: 2.0 Contact: support@karix.io Generated by: https://github....
# from model.config import Config from src.config import Config from src.data_utils import CoNLLDataset, get_vocabs, UNK, NUM, PAD_TOKEN, PAD_CHAR, \ ELMo_Start, ELMo_End, get_glove_vocab, write_vocab, load_vocab, get_char_vocab, \ export_trimmed_glove_vectors, get_processing_word, \ get_processing_word_elm...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
import os import sys import pickle import pandas as pd import numpy as np import word2vec as wv from tqdm import tqdm def get_new_dataframe_names(df_path): file_name = df_path.rsplit('/')[-1] return 'sentence_' + file_name def create_sentence_df(df): sentences = {} indices = {} classes = {} ...
import numpy as np import open3d as o3d import h5py colors_points = (240 / 255, 183 / 255, 117 / 255) colors_path1 = [0.7, 0.7, 0.7] colors_path2 = [1, 0, 0] def load_h5(path, verbose=False): if verbose: print("Loading %s \n" % (path)) f = h5py.File(path, 'r') cloud_data = np.array(f['data']) ...
from payment_app.apis.payment_api import PaymentOperation, UpdateOperation from django.urls import path, include app_name = 'payment_app' urlpatterns = [ path('payment', PaymentOperation.as_view(), name='payment-chsc-api'), # 创建订单,调用alipay # path('update-order-chsc-api/', UpdateOperation.as_view(), name='upd...
from cryptography import Fernet as fernet import string # The Code from the Cryptography branch will be deleted; it is only here for inspiration while making our own function. # The Code for Fernet is encoded in UTF-8 and as such we should try to create an encoding function first. def write_key(): # This is a key...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
def fields(baseformat, theline, lastfield=False): # by how many bytes does theline exceed the length implied by # base-format (struct.calcsize computes exactly that length) numremain = len(theline)-struct.calcsize(baseformat) # complete the format with the appropriate 's' or 'x' field, then unpack f...
import pytest from aiohttp import ClientSession from updater.github import GhUpdater pytestmark = pytest.mark.asyncio async def test_latest(up: GhUpdater): r = await up.latest() assert r assert r.tag assert r.title async def test_asset(up: GhUpdater): r = await up.latest() assert r a =...
# pylint: disable=unused-variable,unused-argument,redefined-outer-name,expression-not-assigned from datetime import datetime from expecter import expect from .utils import get def describe_navbar(): def for_index(client): html = get(client, "/", minify=True) expect(html).contains('<li>' ...
""" JSON-RPC server framework integrations. """
from unittest import TestCase from unittest import main from number_to_string import to_string class TestNumberToString(TestCase): def test_to_string(self): inp = 123 exp = '123' self.assertEqual(to_string(n=inp), exp) if __name__ == "__main__": main(verbosity=2)
""" Unit-tests for TaskThreads. """ import time from datetime import datetime, timedelta from .base import BaseThreadTest from merethread.samples import ( NoopTaskThread, IdleTaskThread, FailedTaskThread, NoopLimitedTimeTaskThread, IdleLimitedTimeTaskThread, FailedLimitedTimeTaskThread, NoopTimeoutTaskThr...
from marshmallow_jsonapi import fields from starlette.responses import Response from sqlalchemy.orm.exc import NoResultFound from starlette_jsonapi.responses import JSONAPIResponse from starlette_jsonapi.schema import JSONAPISchema from accounts.exceptions import OrganizationNotFound from accounts.models import Organ...
""" Created on 18. 3. 2019 CEEF classifier plugin for ClassMark. :author: Martin Dočekal :contact: xdocek09@stud.fit.vubtr.cz """ from classmark.core.plugins import Classifier, PluginAttribute,PluginAttributeIntChecker,\ PluginAttributeFloatChecker from classmark.core.preprocessing import BaseNormalizer, No...
from .type_set import TypeSet from . import std_types default = TypeSet() default.register(std_types.StdVector) default.register(std_types.StdVectorBool) default.register(std_types.StdArray) default.register(std_types.Pointer) default.register(std_types.Array) default.register(std_types.Double) default.register(std_ty...
from records_mover.records.targets.base import ( SupportsMoveFromRecordsDirectory, MightSupportMoveFromTempLocAfterFillingIt, MightSupportMoveFromFileobjsSource, SupportsMoveFromDataframes, ) from sqlalchemy.engine import Engine, Connection from records_mover.records.prep import TablePrep, TargetTableDe...
import typing as T from typing_extensions import Protocol _Tco = T.TypeVar('_Tco', covariant=True) _U = T.TypeVar('_U') class Functor(Protocol, T.Generic[_Tco]): def __init__(self) -> None: ... def fmap(self, f: T.Callable[[_Tco], _U]) -> 'Functor[_U]': ... def __mul__(self, f: T.Callable[[_Tco], _U]) ...
import os import pickle import threading num_children = 0 import logging l = logging.getLogger("claripy.backends.backend_z3_parallel") from .backend_z3 import BackendZ3 class BackendZ3Parallel(BackendZ3): def __init__(self): BackendZ3.__init__(self) self._child = False self._lock = threa...
cars = 100 # number of cars int space_in_a_car = 4 # number of seats in a car float drivers = 30 # number of drivers passengers = 90 # number of passengers cars_not_driven = cars - drivers # cars that are empty cars_driven = drivers # cars that are used carpool_capacity = cars_driven * space_in_a_car # total numb...
from haystack import indexes from icekit.utils.search import AbstractLayoutIndex from . import models class WorkIndex(AbstractLayoutIndex, indexes.Indexable): def get_model(self): return models.WorkBase class CreatorIndex(AbstractLayoutIndex, indexes.Indexable): def get_model(self): return mod...
import clr def process_input(func, inputs): if isinstance(inputs[1], list) or isinstance(inputs[2], list) or isinstance(inputs[3], list): return None elif isinstance(inputs[0], list): return [func(x, inputs[1], inputs[2], inputs[3]) for x in inputs[0]] else: return func(inputs[0], inputs[1], inputs[2], inputs[3]) ...
# Copyright 2012 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
import os import logging import simplejson import wsgiref.handlers from google.appengine.ext import webapp from google.appengine.ext import db from models import Placebo class MainHandler(webapp.RequestHandler): def get(self): field_names = {'concept': 'concept_words', 'category': 'category_words', 'taxon...
import numpy as np class Equilibrium(): def __init__(self, A, B, strat1, strat2): self.A = A self.B = B self.s1 = strat1 self.s2 = strat2 self.isNE = True def isSustained(self, tolerance_margin=10**(-6)): opt_payoff_1 = self.A @ self.s2 @ self.s1 for i...
from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import RedirectView from django.conf.urls import url from src.tipboard.app.views.api import push_api, project_info, tile_rest from src.tipboard.app.views.flipboard import getDashboardsPaths, demo_controller, rende...
import os import argparse def bt_file_split(filepath): with open(filepath, encoding='utf-8') as f: lines = f.readlines() le_lines = [x for x in lines if x.find(';LE;') != -1] base_lines = [x for x in lines if x.find(';LE;') == -1] if len(os.path.basename(filepath).split('_')) == 1: r...
import uuid from datetime import datetime from . import db from .abc import BaseModel class Installation(db.Model, BaseModel): __tablename__ = 'installation' id = db.Column(db.Integer, primary_key=True, autoincrement=True) app_id = db.Column(db.Integer, db.ForeignKey('push_manager.id'), nullable=False) ...
import py class EventlogPlugin: """ log pytest events to a file. """ def pytest_addoption(self, parser): parser.addoption("--eventlog", dest="eventlog", help="write all pytest events to the given file.") def pytest_configure(self, config): eventlog = config.getvalue("eventlog"...
from .djb_hash import djb_hash from .cdblib import Reader, Reader64, Writer, Writer64 __all__ = ['djb_hash', 'Reader', 'Reader64', 'Writer', 'Writer64']
import os import logging import yaml import numpy as np import scipy from mathtools import utils logger = logging.getLogger(__name__) def drawVocab(fig_dir, vocab): if not os.path.exists(fig_dir): os.makedirs(fig_dir) for i, x in enumerate(vocab): x.draw(fig_dir, i) def main( ou...
# -*- coding: utf-8 -*- # @Author: Song Dejia # @Date: 2018-10-30 19:14:37 # @Last Modified by: Song Dejia # @Last Modified time: 2018-11-22 15:12:36 import os import cv2 import sys import numpy as np from PIL import Image, ImageDraw data_dir = '/home/song/srpn/dataset/vid/ILSVRC2015_VID_train_0000/ILSVRC2015_train...
#!/usr/bin/env python3 import json import os import re import struct import sys parse = re.compile('^([0-9a-f]{8})( [0-9a-f]{8})? [a-zA-Z] (.*)\n$') sym_ofs = {} sym_len = {} for sym_line in sys.stdin.readlines(): m = parse.match(sym_line) if not m: continue sym_ofs[m.group(3)] = int(m.group(1), 16) if m.gr...
from upseto import gitwrapper class Scriptolog: def __init__(self, traverse): self._traverse = traverse def updateAllDependencies(self, gitURL): dependsOn = list(self._dependsOn(gitURL)) script = [ "#!/bin/bash", "set -e", "cd /tmp", "rm...
#!-*-coding:utf-8-*- from functools import reduce class GeometryCollectionGeojson(str): def __new__(cls, *args, **kwargs): features_gen = args[0] concat_features_lbd = lambda x, y: str(x) + ',' + str(y) geometries_str = reduce(concat_features_lbd, features_gen) return str.__new__...
import sys import unittest from shell_script_core import ShellScriptCore class ShellScriptCoreTest(unittest.TestCase): def test_init(self): coreInstance = ShellScriptCore() self.assertTrue(coreInstance.env != None) self.assertTrue(coreInstance.scripts == {}) extensionInstance = Te...
# encoding: utf8 import logging import logging.config import pandas as pd import numpy as np from gmsdk import * class TurtleStrategy(StrategyBase): def __init__(self, *args, **kwargs): super(TurtleStrategy, self).__init__(*args, **kwargs) self.__get_param__() self.__init_data__() de...
from game.entity import Player, Monster , Obstacle , Objective import random GRID_SIZE = 20 def init_grid(): #renvoie une grille carrée de taille GRID_SIZE*GRID_SIZE remplie de None return [[None for i in range(GRID_SIZE)] for j in range(GRID_SIZE)] def player_placement(dynamic_grid, y, x): #place le joueur au débu...
#!/usr/bin/env python # -*- coding: utf-8 -*- """register and setting app""" import logging from flask import request from flask_restful import Api from executor.api.users import UsersApi from executor.api.login import TokenApi from executor.exceptions import FuckerTesterException from executor.api.hooks import HookD...
from .model import Linknet
# re-export from .main import TossBot
import csv import numpy as np import time import json earth_radius = 6378137.0 pi = 3.1415926535897932384626 meter_per_degree = earth_radius * pi / 180.0 GRID_SIZE = 1000.0 # The length of the grid (meter) lng_l, lng_r = -74.03, -73.92 # Boundary of the city lat_b, lat_u = 40.656, 40.80 lat_step = GRID_...
from django.utils.encoding import filepath_to_uri from storages.backends.s3boto3 import S3Boto3Storage class CustomDomainSignedS3Boto3Storage(S3Boto3Storage): """ S3 storage backend with signed support for custom domains """ def url(self, name, parameters=None, expire=None): # Preserve the t...
# clize - automatically generate command-line interfaces from callables # clize -- A command-line argument parser for Python # Copyright (C) 2011-2015 by Yann Kaiser <kaiser.yann@gmail.com> # See COPYING for details. from __future__ import unicode_literals import itertools import inspect import re import six from si...
class Solution: def check(self, nums: List[int]) -> bool: start = nums[0] for i in range(1, len(nums)): # iterate until you find possible point of rotation. if nums[i-1] > nums[i]: # then go through the rest of the elements and # check that the...
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import tensorflow as tf from tensorflow.contrib import antares if tf.version.VERSION.startswith('2.'): tf = tf.compat.v1 tf.disable_eager_execution() x = tf.get_variable('x', [128, 1024], tf.float32, initializer=tf.i...
from MCTS import MCTS from azul.AzulGame import AzulGame from azul.AzulPlayers import HumanAzulPlayer, RandomPlayer from azul.pytorch.NNet import NNetWrapper as NNet from azul.AzulArena import AzulArena import cProfile, pstats, io from pstats import SortKey import numpy as np from utils import * import sqlite3 from d...
# Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. print('-' * 100) print('{: ^100}'.format('EXERCÍCIO 053 - DETECTOR DE PALÍNDROMO')) print('-' * 100) frase = str(input('Digite uma frase: ')).replace(' ','').upper() inverso = frase[::-1] print(f'O inverso de {...
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import DataCodec from hazelcast.protocol.builtin import ListMultiFrameCodec # hex: 0x013B00 _REQUEST_MESSAGE_TYPE = 80640 # hex: 0...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
from ..dialog import * class NameField(DialogInputField): _ref_node = NodePath("reference_node") @classmethod def set_ref_node_pos(cls, pos): cls._ref_node.set_pos(pos) def __init__(self, parent, value_id, handler, connection_index): DialogInputField.__init__(self, parent, Skin.op...
#!/usr/bin/env python # Initial model parameters inParms=[ {'value': 5.1, 'fixed': False, 'parname': 'amp', 'limited': [False, False]}, {'value': 70.0, 'fixed': False, 'parname': 'X0', 'limited': [False, False]}, ...
import zmq from _script import ElectronicLoadWECC eload = ElectronicLoadWECC(0.866, 0.7, 0.7, 20, 10) context = zmq.Context() socket = context.socket(zmq.REP) socket.bind('tcp://*:7000') while True: sim_ins = socket.recv_json() V = sim_ins[0] P, Q = eload.calc_pq(V) sim_ou...
from py2asm.blocks.block import Block class LabeledBlock(Block): template = """{name}: {children} """ def __init__(self, name): self.name = name super().__init__() def render(self): return self.template.format( name=self.name, children=self.render_childre...
from abc import ABC import torch.nn as nn import torch import transformers class VastClassifier(nn.Module, ABC): num_labels = 3 def __init__(self, doc_len, pretrained_model="bert-base-uncased"): super().__init__() self.doc_len = doc_len self.bert_model = transformers.BertModel.from_pr...
# -*- coding: utf-8 -*- import pytest @pytest.fixture def inject_file(): return __file__
""" This module contains implementations relevant to basic stabilizer codes. """ import functools from qecsim import paulitools as pt from qecsim.model import StabilizerCode, cli_description class BasicCode(StabilizerCode): """Implements a basic code defined by its stabilizers and logical operators.""" def...
''' Description: Problem 4. Debugging code (correct errors) Version: 1.0.1.20210118 Author: Arvin Zhao Date: 2021-01-15 09:50:36 Last Editors: Arvin Zhao LastEditTime: 2021-01-18 04:23:57 ''' import random def addition(): num1 = random.randint(5, 20) num2 = random.randint(5, 20) # "randit" is wrong. pri...
# -*- coding: utf-8 -*- import numpy as np import pyqtgraph as pg from qtpy import QtWidgets, QtCore, QtGui import flika from distutils.version import StrictVersion #from .. import global_vars as g flika_version = flika.__version__ if StrictVersion(flika_version) < StrictVersion('0.2.23'): from flika.process.BaseP...
import numpy as np # 元データの作成 n=100 data_x = np.linspace(0, 4*np.pi, n) data_y = 2*np.sin(data_x) + 3*np.cos(2*data_x) + 5*np.sin(2/3*data_x) + np.random.randn(len(data_x)) # 信号を欠損させて部分的なサンプル点を得る missing_value_rate = 0.2 sample_index = np.sort(np.random.choice(np.arange(n), int(n*missing_value_rate), replace=False)) ...
#conditional statements with python... #here we are learning about how to use python if statements with operators having operants. #eg. a = 5 b = 8 if(a > b): print "A is greater than B" #this statement improves that A is greater than B in condition A is greater. else: print"B is greater than A" #this i...
import skopt from skopt import gp_minimize from skopt.space import Real, Integer from skopt.utils import use_named_args import tensorflow as tf import torch import torch.backends.cudnn as cudnn import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision.utils as utils import lib.m...
#!/usr/bin/python # -*- coding: utf-8 -*- from cloudshell.devices.flows.cli_action_flows import RunCommandFlow from cloudshell.devices.networking_utils import command_logging from cloudshell.devices.runners.interfaces.state_runner_interface import StateOperationsInterface class StateRunner(StateOperationsInterface):...
''' MLSS: Machine Learning with Spark Streaming Dataset: Tweet Sentiment Analysis Submission by: Team BD_078_460_474_565 Course: Big Data, Fall 2021 ''' import numpy as np from pyspark.mllib.linalg import Vectors def MultiNBLearning(X, y, spark, classifier, model_version): """ Perform online learning of a Multinomi...
class AlarmClock: def __init__(self, time, alarm_status, alarm_time): self.current_time = time self.alarm_on = alarm_status self.alarm_one = alarm_time def set_time(self): self.current_time = input("What time would you like to sent the current time to be?") print(f'You s...
from gevent import monkey monkey.patch_all() import django django.setup() import logging from django.conf import settings from gevent.pywsgi import WSGIServer from gchatautorespond.lib.chatworker.testworker import TestWorker, app if __name__ == '__main__': worker = TestWorker(settings.TEST_CREDENTIALS) wo...
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """You may copy this file as the starting point of your own model.""" import numpy as np from logging import getLogger from torchvision import datasets, transforms logger = getLogger(__name__) def one_hot(labels, classes): """ ...
import frappe from frappe.permissions import reset_perms def execute(): frappe.reload_doctype("Communication") # set status = "Linked" frappe.db.sql("""update `tabCommunication` set status='Linked' where ifnull(reference_doctype, '')!='' and ifnull(reference_name, '')!=''""") frappe.db.sql("""update `tabCommu...
#import Built-Ins import logging from threading import Thread from queue import Queue, Empty import json import time import hmac import hashlib # Import Third-Party from websocket import create_connection, WebSocketTimeoutException # Import Homebrew from .base import WSSAPI # Init Logging Facilities log = logging.get...
from problems.utils import get_n_primes, get_primes_smaller, PrimeFactorChain def test_get_n_primes(): primes = get_n_primes(5) assert primes == [2, 3, 5, 7, 11] def test_get_primes_smaller(): primes = get_primes_smaller(20) assert primes == [2, 3, 5, 7, 11, 13, 17, 19]