content
stringlengths
5
1.05M
import pygame import colors from teams import * import os import exceptions import logging pygame.init() SCREEN_WIDTH = pygame.display.Info().current_w SCREEN_HEIGHT = pygame.display.Info().current_h - 50 HEIGHT_OF_SCOREBOARD = 200 SPACE_FROM_SCOREBOARD = 50 BOARD_SIDE = SCREEN_HEIGHT - HEIGHT_OF_SCOREBOARD - SPACE_...
from json import loads from utilities import * from re import sub from modules.constants import GEN_STARTERS, QUOTED_HELP_MSG, JSON_ERROR # This method starts the code running def getApexCode(inputJson): apex = GEN_STARTERS print( type(inputJson) ) try: y = loads(inputJson) except ValueError as...
# ! This file exists entirely to load pytest plugins. Do not add anything else here. pytest_plugins = [ "api_test_utils.fixtures", ]
r""" Biot problem - deformable porous medium with the no-penetration boundary condition on a boundary region. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v}) = 0 \;, \quad \forall \ul{v} \;, \...
'''Write a program to accept a number and check and display whether it is a Niven Number or not. Niven Number is that a number which is divisible by its sum of digits. Input Format a number Constraints n>0 Output Format Yes or No Sample Input 0 126 Sample Output 0 Yes Sample Input 1 10 Sample Output 1 Yes'''...
from database.base import Transfer class TweetphotoTransfer(Transfer): table_name = 'tweet_photo' def process_origin(self): datalist = [] origins = self.collection.find({'status': {'$ne': 'done'}}) # origins = self.collection.find() if origins.count() > 0: ...
""" 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则 """ class Node: def __init__(self, value): self.value = value self.next = None class Solution: def merge_linklists(self, head1, head2): # 创建游标 cur1 = head1 cur2 = head2 # 确定新列表表头 if cur1.value >= cur2.v...
#!/usr/bin/env python3 # Generate the appveyor.yml file used to specify which configurations Appveyor # tests. import yaml MSVC_VERSIONS = [ {"num": 15, "year": 2017, "stds": ["c++17","c++latest"], "boost": "1_69_0"}, ] def get_msvc_nodes_for_version(version): win32_base = { "GENERATOR_NAME": "Visua...
# coding=utf-8 import mock from nose.tools import assert_equal, assert_true from dmapiclient import HTTPError from ...helpers import BaseApplicationTest import pytest @pytest.mark.skipif(True, reason='gcloud out of scope') @mock.patch('app.main.views.g_cloud.search_api_client') class TestErrors(BaseApplicationTest):...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: Example import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class NestedStruct(object): __slots__ = ['_tab'] # NestedStruct def Init(self, buf, pos): self._tab = flatbuffers.table.Tab...
# -*- coding: utf-8 -*- """ Created on Sat Feb 27 23:22:32 2016 @author: Vu """ from __future__ import division import numpy as np #import mayavi.mlab as mlab #from scipy.stats import norm #import matplotlib as plt from mpl_toolkits.mplot3d import Axes3D from prada_bayes_opt import PradaBayOptFn #from p...
from sympy.utilities.pytest import XFAIL, raises from sympy import (S, Symbol, symbols, nan, oo, I, pi, Float, And, Or, Not, Implies, Xor, zoo, sqrt, Rational, simplify, Function, Eq, log, cos, sin) from sympy.core.compatibility import range from sympy.core.relational import (Relational, Equality, Unequality, ...
instructions = [line.strip().split(" ") for line in open("input.txt", "r")] h_pos = 0 depth = 0 aim = 0 for i in instructions: num = int(i[1]) # Structural Pattern Matching only in Python 3.10 - https://www.python.org/dev/peps/pep-0622/ match i[0]: case 'forward': h_pos += num ...
# Once upon a time, in 2020 we discovered that # some texts would be in incorrectly tokenized into words in the UI of Zeeguu. # # The problem was always around an å character # # Turns out that although visually the letter is the same there # are two possibilities of representing the letter in unicode: # 1. latin s...
import numpy as np import sys import matplotlib.pyplot as pl ## returns the predicted y (based on feature dataset (X) and weights (Theta)) def f(X,th): return X.dot(th.T) ## returns the cost (residual error) for predicted y def J(X,y,th): m=X.shape[0] y_hat=X.dot(th.T) cost=np.sum((y_hat-y)**2)/(2*m) ret...
import sys, socket, select, threading def prompt(user) : sys.stdout.write('%s> ' % user) sys.stdout.flush() if __name__ == "__main__": if len(sys.argv) < 3: print('Usage : python %s user host' % sys.argv[0]) sys.exit() (user, host), port = sys.argv[1:3], 5001 server_sock = socket.s...
""" Tests for instructor_task/models.py. """ import copy import time from io import StringIO import pytest from django.conf import settings from django.test import SimpleTestCase, TestCase, override_settings from opaque_keys.edx.locator import CourseLocator from common.test.utils import MockS3BotoMixin from lms.djan...
import typing import numpy import sklearn import _pqkmeans class BKMeans(sklearn.base.BaseEstimator, sklearn.base.ClusterMixin): def __init__(self, k, input_dim, subspace_dim=8, iteration=10, verbose=False): super(BKMeans, self).__init__() self._impl = _pqkmeans.BKMeans(k, input_dim, subspace_dim...
""" pytchat is a lightweight python library to browse youtube livechat without Selenium or BeautifulSoup. """ __copyright__ = 'Copyright (C) 2019, 2020, 2021 taizan-hokuto' __version__ = '0.5.5' __license__ = 'MIT' __author__ = 'taizan-hokuto' __author_email__ = '55448286+taizan-hokuto@users.noreply....
from fastapi import FastAPI,Query from typing import Optional from typing import List app = FastAPI() fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] @app.get("/items/") async def read_item(skip : int = 0, limit:int = 10): return fake_items_db[skip:skip+limit] @app.get("/users...
from unittest import TestCase class YamlRulesTest(TestCase): def test_all_kinds(self): """ Test that we've enumerated all the possible values for kind and kind_detail in the YAML files. """ from vectordatasource.meta import find_yaml_path from vectordatasource.met...
#!/usr/bin/env python3 # Copyright 2021 Alexander Meulemans, Matilde Tristany, Maria Cervera # # 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 ...
"""Creates a module and necessary tools for averaging and aggregating timeline reports.""" from collections import defaultdict import itertools import re from statistics import mean def parse_timeline_events(timeline): """Update the timeline event map from the timeline output. Non-commented timel...
# Generated by Django 2.2 on 2019-04-17 02:13 from django.db import migrations def drop_madison_taproom(apps, schema_editor): venue = apps.get_model("venues.Venue") beer_price = apps.get_model("beers.BeerPrice") beer_price.objects.filter(venue__id=2).delete() venue.objects.filter(id=2).delete() cla...
#!/usr/bin/env python # import modules import rospy import numpy as np from std_msgs.msg import Float64 from sympy import symbols, cos, sin, pi, simplify from sympy.matrices import Matrix from geometry_msgs.msg import Point from kuka_arm.srv import * def handle_calculate_FK_request(req): endPoints = Point...
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@gmail.com', password='pass12345'): return get_user_model().objects.create_user(email, password) class ModelTests(TestCase): def test_creat...
from model_register import State, Country, County, GroundWaterWell, ReclamationPlant, Stream, \ Precipitation, SpreadingGround from django.contrib import admin admin.site.register(State) admin.site.register(County) admin.site.register(Country) admin.site.register(GroundWaterWell) admin.site.register(ReclamationP...
import onmt import onmt.modules class TranslatorParameter(object): def __init__(self, filename): self.model = ""; self.src = "<stdin>"; self.src_img_dir = ""; self.tgt = ""; self.output = "<stdout>"; self.beam_size = 1 self.batch_size = 1 self.max_...
""" Estimation methods for Compatibility Estimation described in Factorized Graph Representations for Semi-Supervised Learning from Sparse Data (SIGMOD 2020) Krishna Kumar P., Paul Langton, Wolfgang Gatterbauer https://arxiv.org/abs/2003.02829 Author: Wolfgang Gatterbauer License: Apache Software License ...
#!/usr/bin/env python import json import torch import pdb import numpy as np import pandas as pd from torch.utils.data import Dataset from .vectorizer import MLPVectorizer, CNNVectorizer class PDataset(Dataset): """ DataSet derived from PyTorch's Dataset class """ def __init__(self, df: pd.DataFrame, vect...
from cereal import car from collections import defaultdict from common.numpy_fast import interp from common.kalman.simple_kalman import KF1D from opendbc.can.can_define import CANDefine from opendbc.can.parser import CANParser from selfdrive.config import Conversions as CV from selfdrive.car.honda.values import CAR, DB...
class Solution: # @param A : head node of linked list # @param B : integer # @return the head node in the linked list def partition(self, A, B): head0 = None tail0 = None head1 = None tail1 = None ptr = A while ptr is not None : ptr2 = ptr.next ...
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URI = 'sqlite:///todolist.sqlite' _engine = create_engine( SQLALCHEMY_DATABASE_URI, connect_args={"check_same_thread": False} ) _session_local = sessionmaker(aut...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Management command entry point for working with migrations """ import sys import django from django.conf import settings INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.admin", "django.contrib.contenttypes", "django.contrib.sites", "adde...
# BOJ 15683 # surveillance from copy import deepcopy import sys sys.setrecursionlimit(100000) dx = (0, 1, 0, -1) dy = (1, 0, -1, 0) dir = [[], [[0], [1], [2], [3]], [[0, 2], [1, 3]], [[1, 0], [1, 2], [3, 0], [3, 2]], [[0, 1, 2], [1, 2, 3], [0, 2, 3],[0, 1, 3]], [[0, 1, 2, 3]]] n, m = map(int, input().split()) offic...
# MINLP written by GAMS Convert at 04/21/18 13:51:42 # # Equation counts # Total E G L N X C B # 215 33 149 33 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
#!/usr/bin/python # -*- coding: utf-8 -*- from searchengine import searchengine import requests class censys(searchengine): def __init__(self): super(censys, self).__init__() def censys_dork_search(self, uid, secret, dork, dorktype, page=1): """query information form censys with api. ...
#!/usr/bin/env python3 def show(): try: raise Exception("foo") except Exception as e: print("caught") finally: print("Finally") try: 3 / 0 except ZeroDivisionError: print("OK") try: raise Exception("foo") except: print("Got it") i...
# -*- coding: utf-8 -*- """ Created on Fri Oct 07 17:56:46 2016 @author: Arenhart """ import PIL.Image as pil import PIL.ImageTk as imagetk import numpy as np import scipy.ndimage as sp import matplotlib.pyplot as plt import skimage as sk import skimage.filters as filters import skimage.morphology as morphology impo...
import pandas as pd def sendMessage(): import requests url = "https://www.fast2sms.com/dev/bulk" payload = "sender_id=FSTSMS&message=The%20model%20have%20been%20trained%20successfully&language=english&route=p&numbers=8126102904" headers = { 'authorization': "OuX3BnsANZWIvpQzT70ikgD4ERwehbyHdV2Ff6MmSL51jCU...
""" Class implementing a simple file browser for Jupyter """ # Author: Guillaume Witz, Science IT Support, Bern University, 2019 # License: BSD3 import ipywidgets as ipw from pathlib import Path class Folders: def __init__(self, rows=10, window_width=300, init_path=None): style = {"description_width":...
from . import views from django.urls import path from django.contrib import admin urlpatterns=[ path("admin/", admin.site.urls), path("",views.index, name="index"), path("maps", views.base, name="base"), path("profile", views.profile, name="profile"), path("add_todo",views.add_todo, nam...
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Christiaan Frans Rademan <chris@fwiw.co.za>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the ...
# encoding: utf-8 from login import LoginHandler # from __all__ = [LoginHandler]
import numpy as np import pandas as pd import gc from multiprocessing import Pool, cpu_count from functools import partial class Globe: """ Globe is used to store and process information about the word and an array of generated agents. """ def __init__(self, df, processes=cpu_count() - 1, splits=1...
# coding=utf-8 # Copyright 2020 The HuggingFace Team All rights reserved. # Copyright 2021 NVIDIA Corporation. 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 # # htt...
from __future__ import print_function import time from html.parser import HTMLParser from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by i...
from typing import Any, Dict, List, Optional, Tuple, Union, TYPE_CHECKING from ..config import Config from ..resource import Resource from ..utils import RichStatus if TYPE_CHECKING: from .ir import IR class IRResource (Resource): """ A resource within the IR. """ @staticmethod def helper_s...
from conans import DEFAULT_REVISION_V1 from conans.model.ref import PackageReference class CommonService(object): def _get_latest_pref(self, pref): ref = self._get_latest_ref(pref.ref) pref = PackageReference(ref, pref.id) tmp = self._server_store.get_last_package_revision(pref) i...
from .functional import RipsDiagram, Rips0Diagram import torch.nn as nn class RipsLayer(nn.Module): """ Define a Rips persistence layer that will use the Rips Diagram function Inpute: maxdim : maximum homology dimension (default=0) reduction_flags : PH computation options from bats ...
from genessa.models.simple import SimpleCell from .mutation import Mutation class SimpleModel(SimpleCell, Mutation): """ Class defines a cell with a single protein state subject to negative feedback. All reaction rates are based on linear propensity functions. Attributes: name (str) - name of co...
import contextlib import numpy as np import torch from torch import nn from transformers import BertForNextSentencePrediction from capreolus import ConfigOption, Dependency from capreolus.reranker import Reranker from capreolus.utils.loginit import get_logger logger = get_logger(__name__) # official weights convert...
from django.core.exceptions import ImproperlyConfigured from django.contrib import messages from django.utils.translation import ugettext_lazy as _, ugettext from django.views.generic.edit import FormMixin, ProcessFormView, DeletionMixin, FormView from django_mongoengine.forms.documents import documentform_factory fr...
class StatesStatus: STATUS_NOT_SET = 0 NEW = 1 ACCEPTED = 2 COMPLETED = 3 DECLINED = 4 CANCELLED = 5 CLOSED = 6 STATE_STATUS_CHOICES = ( (StatesStatus.STATUS_NOT_SET, 'Status Not Set'), (StatesStatus.NEW, 'New'), (StatesStatus.ACCEPTED, 'Accepted'), (StatesStatus.COMPLETED,...
import matplotlib.patches as mpatches import matplotlib.pyplot as plt import warnings from trackintel.geogr.distances import meters_to_decimal_degrees from trackintel.visualization.osm import plot_osm_streets from trackintel.visualization.util import regular_figure, save_fig from trackintel.geogr.distances import chec...
# # -*- coding: utf-8 -*- # # Copyright (c) 2018 Intel Corporation # # 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 app...
import eel import os import re import time import gzip import csv import hashlib import json import shutil from datetime import datetime from random import shuffle from transformers import DistilBertTokenizer, DistilBertForTokenClassification # downloading DistilBERT will take a while the first time import torch i...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Data container """ from __future__ import ( print_function, division, absolute_import, unicode_literals) from six.moves import xrange # ============================================================================= # Imports # ==========================...
GET_USER = """ SELECT * FROM users WHERE user_id={} """ INSERT_USER = """ INSERT INTO users VALUES ({}, '{}', {}, '{}', '{}') """ DELETE_USER = """ DELETE FROM users WHERE user_id={} """ UPDATE_USER = """ UPDATE users SET name = '{}', age = {}, gender = '{}', country = '{}' WHERE user_id = {}...
import RockPaperScissors.game as rps game = rps.Game() game.run(True)
from intent_parser.server.intent_parser_server import IntentParserServer from intent_parser.utils.intent_parser_utils import IPSMatch import intent_parser.utils.intent_parser_utils as intent_parser_utils import unittest class IpsUtilsTest(unittest.TestCase): def setUp(self): """ Configure an insta...
import sys, argparse, csv parser = argparse.ArgumentParser(description='csv to postgres',\ fromfile_prefix_chars="@" ) parser.add_argument('file', help='csv file to import', action='store') args = parser.parse_args() csv_file = args.file with open(csv_file, 'Crime.csv') as csvfile: for line in csvfile.readlines():...
class FileLoader(object): def __init__(self, fname, coltypes = {}, separator = None): self.types = coltypes if type(fname) == str: ofile = open(fname) else: ofile = fname self.rows = [x.split(separator) for x in ofile] def __getitem__(self, *args): ...
#!/usr/bin/python3 import time numbers = [2, 56, 90, 8076, 32, 46, 24, 13, 87, 7, 34, 923] number = 24 start = 0 end = len(numbers) -1 counter = 0 numbers.sort() while True: time.sleep(2) counter += 1 print("\nAttempt:", counter) print("Slice:", numbers[start:end]) idx = len(numbers[start:end]...
from __future__ import unicode_literals from json import dumps, loads import requests from django.db import models from django.utils.translation import ugettext_lazy as _ from solo.models import SingletonModel from installation.models import Installation from lock_manager import Lock, LockError from .literals impo...
from asyncio import BaseEventLoop, WriteTransport, SubprocessTransport, Transport from threading import Thread from concurrent.futures import Future from amino import Dat, List, ADT, Maybe, Nothing, Just, Path from amino.logging import module_log from ribosome.rpc.concurrency import OnMessage, OnError from ribosome.r...
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT """The 'source-git' subcommand for Packit""" import click from packit.cli.update_dist_git import update_dist_git from packit.cli.update_source_git import update_source_git from packit.cli.source_git_init import source_git_init from packit...
import json from oneparams.api.base_diff import BaseDiff from oneparams.utils import create_email, string_normalize class ApiCliente(BaseDiff): items = {} list_details = {} first_get = False def __init__(self): self.url_get_all = "/CliForCols/ListaDetalhesClientes" super().__init__(...
from collections import deque water_quantity = int(input()) names = deque([]) while True: name = input() if name == "Start": break names.append(name) while True: commands = input().split() if commands[0] == "End": print(f"{water_quantity} liters left") break elif ...
from typing import Iterable import matplotlib.axis import matplotlib.pyplot as plt import pandas as pd import seaborn as sns def rename_teachers(data: pd.DataFrame): dic = { "leitner": "Leitner", "forward": "Conservative\nsampling", "threshold": "Myopic", } for k, v in dic.items(...
from pycanlii.legislation import Legislation from pycanlii.enums import Language, LegislationType, DateScheme class TestLegislation: def test__init__(self, legis_en, legis_fr, config): en = Legislation(legis_en, config['key'], Language.en) fr = Legislation(legis_fr, config['key'], Language.fr) ...
#!/usr/bin/env python import sys import zmq import numpy def init_sockets(source, destination): context = zmq.Context() receiver = context.socket(zmq.PULL) receiver.bind(source) sender = context.socket(zmq.PUSH) sender.connect(destination) return receiver, sender def send_array(socket,...
# coding: utf-8 TARGET_DIR = '/app/EMonitor/Script'
""" See: https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types """
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import numpy as np import pytest import torch from common.subsample import RandomMaskFunc @pytest.mark.parametrize("center_fracs, accelera...
from picamera import PiCamera, Color import time import sys camera = PiCamera() camera.annotate_text_size = 32 camera.annotate_background = Color("black") camera.annotate_foreground = Color("white") #camera.resolution = (576, 324) camera.resolution = (1152, 648) #camera.resolution = (1920, 1080) #recordtime = 1795 #1...
""" Apply Thesaurus =============================================================================== >>> from techminer2 import * >>> directory = "data/" >>> create_thesaurus( ... column="author_keywords", ... thesaurus_file="test_thesaurus.txt", ... sep="; ", ... directory=directory, ... ) - INFO - Cr...
# Rahil Mehrizi, Oct 2018 """Saving and Loading Checkpoint""" import os, shutil import torch class Checkpoint(): def __init__(self, opt): self.opt = opt exp_dir = os.path.join(opt.exp_dir, opt.exp_id) if opt.resume_prefix != '': if 'pth' in opt.resume_prefix: tr...
import tensorflow as tf from tensorflow.python.framework import graph_util sess = tf.InteractiveSession() #1 2 2 3 input=tf.constant([[[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]]]) op = tf.pad(input, [3,1,2,0], name='transpose_self') target=op.eval(); print(target) #constant_graph = graph_util.convert_variables_to_con...
import numpy as np import torch from aw_nas.dataset.data_augmentation import Preproc class TrainAugmentation(object): def __init__(self, size, mean, std, norm_factor=255., bias=0.): """ Args: size: the size the of final image. mean: mean pixel value per channel. ""...
from torchquant.qmodule import * from torchquant.utils import * from torchquant.range_observers import *
from unittest.mock import patch import pytest from requests_cache.backends import DynamoDbCache, DynamoDbDict from tests.conftest import AWS_OPTIONS, fail_if_no_connection from tests.integration.base_cache_test import BaseCacheTest from tests.integration.base_storage_test import BaseStorageTest # Run this test modul...
# -*- coding: utf-8 -*- # This work is part of the Core Imaging Library (CIL) developed by CCPi # (Collaborative Computational Project in Tomographic Imaging), with # substantial contributions by UKRI-STFC and University of Manchester. # Licensed under the Apache License, Version 2.0 (the "License"); # you...
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-envelope', version=__import__('envelope').__version__, description='A contact form app for Django', long_description=read('README.rst'), ...
import pandas as pd from scipy.stats import chi2_contingency import random def test_chiquadro(dataset,variabile_target, lista_variabili, index ): """ Data una variabile target e una lista di variabili indipendenti, si ottiene il test del chi2 tra la variabile target e tutte le variabili di interesse e i...
import random import math from typing import List import numpy as np # from hyperLogLogKtob import HyperLogLog # from registersKtob import registers from hashSuggested import hash_A from rhoSuggested import rho m = 256 N = 500000 sigma = 1.04/math.sqrt(m) stdv1plus = N*(1+sigma) stdv1min = N*(1-sigma) stdv2plus = N*(1...
import urllib.request import re import time import os # 流程 # 请求->处理->返回 # 1.获取首页url 2.获取首页url里的图片url 3.获取图片url的值 4.创建文文件夹保存 # 多线程爬取 class Mzimg(object): # 获取html源码 def get_html(self,url): headers = { 'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0' ...
import numpy as np from src.celosia import Celosia from multiprocessing import freeze_support #************************************************************************* # An illustration example as presented in the following paper: # Celosia: A Comprehensive Anomaly Detection Framework for Smart Cities #*******...
​import​ ​time ​import​ ​os ​os​.​system​(​'clear'​) ​time​.​sleep​(​0.5​) ​try​: ​    ​import​ ​mechanize ​except​ ​ModuleNotFoundError​: ​    ​print​ ​'[!] Module >Mechanize< Not Found!​\n​    This module is only available in python 2.x :/​\n​    Please install mechanize (pip install mechanize) ...
# creo uno script per poterlo usare nell'heroku scheduler # ne faccio un base command, così ogni tot heroku lo ranna ed è come se lo runnasse da consolle from django.core.management.base import BaseCommand from pm_lookup.processing.scheduled_processing import save_history_pm from pm_lookup.processing.scheduled_proce...
# command definitions START_FOC = (0x03) ACC_MODE_NORMAL = (0x11) GYR_MODE_NORMAL = (0x15) FIFO_FLUSH = (0xB0) INT_RESET = (0xB1) STEP_CNT_CLR = (0xB2) SOFT_RESET = (0xB6)
from .command import Command from datetime import timedelta, datetime import traceback import asyncio class Task: def __init__(self, callback, delta=True, **units): self.delta = delta self.callback = callback self.units = units self.module = None # Gets filled by bot.add_module ...
# Please also refer to other files in student_contributed for more tests class a(object): a: a = None # members can have the same name as class A: a = None B: [b] = None class b(object): def b(self:b, other:a): # methods can have same name as class A.a = other # assign to member doesn't need global d...
''' each row of created .csv file is of the form: polarity, id, date, query, user, comment, test_or_training ''' import csv import os parent_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) train_file_name = os.path.join(parent_path, 'data', 'raw_data', 'training.csv') training = [] with open(tra...
from typing import List class NumArray: def __init__(self, nums: List[int]): self.sum_till = [0] * (len(nums) + 1) for index, number in enumerate(nums): self.sum_till[index + 1] = self.sum_till[index] + number def sumRange(self, left: int, right: int) -> int: return self....
import cv2 import mediapipe as mp mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands # For webcam input: cap = cv2.VideoCapture(0) with mp_hands.Hands( min_detection_confidence=0.5, min_tracking_confidence=0.5, max_num_hands=1) as hands: while cap.isOpened(): success, image =...
from .community_chat import CommunityChat from .group_community import GroupCommunity from .group_rules import GroupRules from .invite_link import (InviteLink, INVITE_LINK_REGEX, INVITE_LINK_MAX_LENGTH) from .member import Member
# -*- coding: utf-8 -*- import os import flask import functools import dash import pyEX.client as p import json from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html from perspective_dash_component import PerspectiveDash c = p.Client() def peerCorre...
from urllib.parse import urlparse, ParseResult import grpc def create_channel(hostname, port, ca=None, key=None, cert=None): r = _create_tcp_channel(hostname, port) if ca: r = _wrap_tls_channel(r, ca, key, cert) return r def _create_tcp_channel(hostname, port): channel = grpc.insecure_cha...
#!/usr/bin/env python # coding: utf-8 # In[13]: n = int(input()) a = 0 for _ in range(n): a, b, c = a+1, a+2, a+3 print('{} {} {} PUM'.format(a, b, c)) a = c+1