content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow....
from django.conf import settings from django.core.files.storage import FileSystemStorage from django.shortcuts import redirect, render from urllib3 import request from tcgen.forms import DocumentForm from tcgen.generator import generate def create_tc(request): if request.method == 'POST': form = Document...
WORD="tHIS IS ANUDEEP"; lister=WORD.spit(); print(lister);
from typing import List import numpy as np import pandas as pd import math """ lagrange is a mathematical interpolation methods that approximate a polynomial of degree n given n-1 points """ def lagrange(X,Y) -> List: """ the lagrange method that takes n points as input and return a pa...
from admin_honeypot.signals import honeypot from django.conf import settings from django.core.mail import mail_admins from django.urls import reverse from django.template.loader import render_to_string def notify_admins(instance, request, **kwargs): path = reverse('admin:admin_honeypot_loginattempt_change', args=...
import re from datetime import datetime from src.consts import * def avg_sentence_length(text): """ Averages the number of words in a sentence of `text` :param text: The text to analyze (str) :return: average_words (float) """ sentences = [s.strip() for s in re.split(r'[\.\?!]', text) if s] return sum...
import click from mattermostdriver import Driver import json from dynaconf import Dynaconf from pathlib import Path from os import getenv settings = Dynaconf( settings_files=[ Path(getenv("HOME")) / ".oda/settings.toml", Path(getenv("HOME")) / ".oda/private.toml", ], ...
# coding=utf-8 from celery import Celery app = Celery() app.config_from_object("clambda.options")
"""Extract all quiz environments from quiz.do.txt to a separate document.""" import re pattern = r'^!bquiz.+?^!equiz\n' f = open('quiz.do.txt') text = f.read() f.close() quizzes = re.findall(pattern, text, flags=re.MULTILINE|re.DOTALL) f = open('pure_quiz.do.txt', 'w') f.write("""\ TITLE: Demo of quizzes AUTHOR: HPL DA...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: mappedTree = [] def BFS(node): mappedTree.append(node.val) ...
#coding: utf-8 from Tkinter import * class Application(Frame): def __init__(self,master=None): Frame.__init__(self,master,height=100, width=250) self.master.title('Pack Three Labels') #First Label la = Label(self,text='Hello everybody. How are you?', bg='yellow',relief=RIDGE,bd=2) la.place(relx=0.02, rely=...
""" Time: O(N) Space: O(N) `counter1` counts the char in `s1` `counter2` counts the char is `s2[i:j+1]` Create a sliding window with length `len(s1)`, l. From i to j. Move the sliding window (`s2[i:j+1]`) from left to right while maintaining counter2. Each iteration, add s2[j] to the sliding window. At the end of ite...
from multiprocessing import Pool, cpu_count try: _pools = cpu_count() except NotImplementedError: _pools = 4 def chop(list_, n): "Chop list_ into n chunks. Returns a list." # could look into itertools also, might be implemented there size = len(list_) each = size // n if each == 0: ...
# -*- coding: utf-8-*- import time import math from pyicloud import PyiCloudService from pyicloud.exceptions import PyiCloudFailedLoginException from lessons.base.plugin import JenniferResponsePlugin from lessons.base.exceptions import JenniferUserWantsToCancelException class JenniferFindMyIphonePlugin(JenniferResp...
# Standard Library Imports # Third Party Imports # Local Application Imports from classes.block import Block from classes.gameobject import Enemy class EnemyBlock(Block): DESTROYED_ENEMY_SLOT = -1 def __init__( self, top_left, bottom_right, NODES_PER_COLUMN=Block.DEFAULT_PA...
import torch import torch.nn as nn from torch.utils.data import DataLoader import torch.nn.functional as F import torch.optim as optim import torch.nn.init as init import torchvision from torch.autograd import Variable import torchvision.transforms as transforms import argparse from torchvision import datasets import v...
import ipaddress import pytest from boardfarm.exceptions import BftIfaceNoIpV4Addr, BftIfaceNoIpV6Addr from boardfarm.lib.bft_interface import bft_iface class Dummy: def check_output(self, cmd): pass out_str1 = '''(venv3) testuser@sree-VirtualBox:~/Sreelekshmi/boardfarm/unittests/boardfarm/lib$ ip a sh...
maths_data={ "tuto1": "https://drive.google.com/file/d/11gS82G5nsvjWtHGmO3rs9dzQFNTihR0a/view?usp=sharing", "tuto2": "https://drive.google.com/file/d/11x5FTbsEH2HA3qQFyX4K-q6aFkS4MDx-/view?usp=sharing", "tuto3":"https://drive.google.com/file/d/122IOVikDeO6rllWn7RfdL9KT1-vHMOWu/view?usp=sharing" } cheat_data={ ...
from paypalrestsdk import Order import logging logging.basicConfig(level=logging.INFO) order = Order.find("<ORDER_ID>") response = order.authorize({ "amount": { "currency": "USD", "total": "0.08" } }) if order.success(): print("Authorized[%s] successfully" % (order.id)) else: print(or...
import subprocess import os import operator import re import typing from urllib.parse import urljoin from qutebrowser.api import interceptor, message from PyQt5.QtCore import QUrl # Autogenerated config.py # # NOTE: config.py is intended for advanced users who are comfortable # with manually migrating the config file...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-11 17:02 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields class Migration(migrations.Migration): initial = True ...
import fedml if __name__ == "__main__": fedml.run_hierarchical_cross_silo_client()
""" Copyright 2015 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...
from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration import os import functools required_conan_version = ">=1.43.0" class DrogonConan(ConanFile): name = "drogon" description = "A C++14/17/20 based HTTP web application framework running on Linux/macOS/Unix/Windows" ...
''' Created on 11 Jan 2020 @author: lordmike ''' import setup_apps #import app_source_handler from setup_apps import util #import json #import app_source_handler import logging import sys import LMToyBoxPython from datetime import datetime import traceback from config import Config def conf_root_logger(): # Defa...
from sanic import Sanic from sanic.response import json from prometheus_sanic import monitor app = Sanic() async def ping(_request): return json({'success': 'you are home'}) async def hone(_request): return json({'success': 'you are home'}) async def user(_request): return json({'success': 'you are ...
from extra_envs.intervener.base import Intervener from extra_envs.intervener.point import (PointIntervenerRollout, PointIntervenerNetwork) from extra_envs.intervener.half_cheetah import (HalfCheetahMpcIntervener, HalfCheetahHeurist...
"""Custom errors.""" class ConfigurationError(Exception): """ This exception is raised if a user has misconfigured Flask-Stormpath. """ pass
from abc import ABC from qrogue.game.logic.actors import StateVector from qrogue.game.logic.collectibles import Collectible, Coin from .enemy import Enemy class Boss(Enemy, ABC): """ A special Enemy with specified target and reward. """ def __init__(self, target: StateVector, reward: Collectible):...
from django import template from allauth.account.utils import user_display from allauth.account.models import UserProfile register = template.Library() """ Display profile: - Avartar - Full Name - Email - Like - Dislike - Comment/Idioms Stat - Rank """ def profile_tag(parser, token ): try: tag_...
#kpbocheneke@gmail.com import re VOWELS = "AEIOUY" CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ" def is_alternating(word): prev, other = VOWELS, CONSONANTS if word[0].upper() in VOWELS: prev, other = CONSONANTS, VOWELS for w in word: if w.upper() not in other: return False prev,...
import arcpy import os class Toolbox(object): def __init__(self): """Define the toolbox (the name of the toolbox is the name of the .pyt file).""" self.label = "Create Points Along Lines" self.alias = "alonglines" # List of tool classes associated with this toolbo...
import datetime from django.views.decorators.csrf import csrf_exempt from tropo_webapi.views import TropoView from .models import CallBox ENTRY_CODE_GREETING = 'Please enter the entry code or press star to call residents.' ENTRY_CODE_INVALID = 'Invalid entry code.' CALL_TRANSFER = 'Calling residents.' GATE_OPEN_MES...
# Las dependencias: from logging import NullHandler import pandas as pd import spacy as sp import os import PySimpleGUI as sg import webview as wv from spacy.matcher import DependencyMatcher as match from spacy.lang.es.stop_words import STOP_WORDS from spacy import displacy import stanza import spacy_stanza from string...
import numpy as np import pandas as pd class DataFrameSchema: def __init__(self, name, primary_keys=None, row_monatonic_increasing=None): self.name = name self.primary_keys = primary_keys self.columns = {} self.required_columns = [] self.row_monatonic_increasing = row_monat...
from builtins import str import dmri_segmenter.dmri_brain_extractor as dbe import dmri_segmenter.make_comparisons as mc import nibabel as nib #import numpy as np import os def test_get_version_info(): vinfo = dbe.get_version_info() assert "\ncommit " in vinfo assert "\nDate:" in vinfo assert "version"...
#!/usr/bin/env python # coding: utf-8 import os import requests import time from bs4 import BeautifulSoup import json def log(type, msg): print("[B2-dl] [%s] : %s" % (type, msg)) def getInput(soup, name): el = soup.find('input', { 'name': name }) if el is not None: return el['value']...
# 该文件是用来尝试输出decoder的 import argparse from numpy import mod import torch import os import yaml # Mixing tracing and scripting import sys import onnx import onnxruntime import numpy as np from wenet.transformer.asr_model import init_asr_model from wenet.utils.checkpoint import load_checkpoint def to_numpy(tensor): r...
from collections import deque from itertools import islice from problem0005 import product def sliding_window(iterable, n): d = deque([next(iterable, None) for _ in range(n)], maxlen=n) yield d for e in iterable: d.append(e) yield d if __name__ == '__main__': number_series = map(int, ...
import agentlogging def demo(): """ Demo the logging functionality. """ print("=== Development Logging ===") dev_logger = agentlogging.get_logger("dev") dev_logger.debug("This is a DEBUG statement") dev_logger.info("This is an INFO statement") dev_logger.warning("This is a WARNING s...
# + from ase.io import read, Trajectory import sys import os def reduce_traj(traj, x): if traj.endswith('.traj'): if os.path.isfile(traj): reduced = traj.replace('.traj', f'_r{x}.traj') new = Trajectory(reduced, 'w') for atoms in read(traj, f'::{x}'): ne...
# Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and # other Shroud Project Developers. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (BSD-3-Clause) from distutils.core import setup, Extension strings = Extension( 'strings', sources = ['strings-binding.cpp', ...
from my_package._module1 import A print(A)
""" Contains type definitions for :py:class:`encomp.units.Quantity` objects. If ``encomp.settings.SETTINGS.type_checking`` is ``True``, these types will be enforced everywhere. The dimensionalities defined in this module can be combined with ``*`` and ``/``. Some commonly used derived dimensionalities (like density) a...
# Parts or the whole documentation of this module # are copied from the respective module: # libcloud/compute/drivers/nephoscale.py # see also: # https://github.com/apache/libcloud/tree/trunk/libcloud/compute/drivers/nephoscale.py # # Apache Libcloud is licensed under the Apache 2.0 license. # For more information, ple...
# Copyright (C) 2016 Ross Wightman. 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 # =================================...
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from .otBase import BaseTTXConverter # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6prop.html class table__p_r_o_p(BaseTTXConverter): pass
from pylabnet.utils.helper_methods import load_device_config, get_ip from pylabnet.network.core.service_base import ServiceBase from pylabnet.network.core.generic_server import GenericServer from pylabnet.network.core.client_base import ClientBase import os class Dummy: pass class Client(ClientBase): pass ...
import unittest import os import copy import sys from time import sleep from appium import webdriver from helpers import report_to_sauce, ANDROID_BASE_CAPS, EXECUTOR from selenium.common.exceptions import WebDriverException # Run standard unittest base. class TestAndroidCreateSession(unittest.TestCase): def te...
# from enum import Enum, auto __all__ = [ # 'TokenKind', # 'TK_UNEXPECTED', # 'TK_NONE', # 'TK_EOF', # 'TK_LITERAL_INT', # 'TK_LITERAL_FLOAT', # 'TK_OP_PLUS', # 'TK_OP_MINUS', # 'TK_OP_MULT', # 'TK_OP_DIV', # 'TK_OP_MOD', # 'TK_UNAOP_POS', # 'TK_UNAOP_NEG', # 'TK...
n=int(input()) games=input() a = 0 d = 0 for i in games: if "A" in i: a += 1 else: d+=1 if a>d: print("Anton") elif a==d: print("Friendship") else: print("Danik")
# Beispielprogramm für das Buch "Python Challenge" # # Copyright 2020 by Michael Inden def remove_all_inplace(values, item): try: while True: values.remove(item) except ValueError: pass def remove_all_inplace_improved(list, value): while value in list: list.remove(val...
from model.contact import Contact import re from model.functions import clear_double_space class ContactHelper: def __init__(self, app): self.app = app def sumbmit_creation(self): wd = self.app.wd wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click() def creat...
#!/usr/bin/env python3 import inf_common as IC import hyperparams as HP import torch torch.set_num_threads(1) torch.set_num_interop_threads(1) from torch import Tensor import time from typing import Dict, List, Tuple, Optional from collections import defaultdict from collections import ChainMap import sys,rando...
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2019 all rights reserved # import random from PointCloud import PointCloud class Mersenne(PointCloud): """ A point generator implemented using the Mersenne Twister random number generator that is available as part of the python stan...
# backup-1.py import os #==================================================================== cwd = os.getcwd() prefix = cwd.split('/')[-1] # get current folder's name; not all stuff leading to it # visit the current directory and every one within it, recursively for dir_listing in os.walk(cwd): here = dir_li...
#!/usr/bin/env python3 from src.main.utils.Logger import Logger from src.test.base.BaseTest import BaseTest from src.main.base.pages.LoginPage import LoginPage from src.main.exceptions.PageException import PageException import unittest class TestRecoverPasswordPage(BaseTest, unittest.TestCase): global logger ...
from pathlib import Path from unittest import mock from tests.cli_test_case import CliTestCase class MinitestTest(CliTestCase): test_files_dir = Path(__file__).parent.joinpath('../data/minitest/').resolve() result_file_path = test_files_dir.joinpath('record_test_result.json') @mock.patch('requests.reque...
import os import sys import unittest import warnings from .. import cpu_matcher from autocnet.examples import get_path from autocnet.graph.network import CandidateGraph sys.path.append(os.path.abspath('..')) """class TestMatcher(unittest.TestCase): def setUp(self): im1 = cv2.imread(get_path('AS15-M-029...
from selenium import webdriver import pandas as pd import time from Scripts.params import * website = 'http://www.nasdaq.com/symbol/' + ticker + '/news-headlines' def getText(someList): returnList = [] for i in someList: returnList.append(i.text) return returnList dr = webdriver.Chrome('/usr/local...
"""Schema calibration set""" from pydantic import BaseModel class CalibrationSet(BaseModel): calibration_set_identifier: str calibration_factor: float class Config: orm_mode = True
"""python emulator""" from PySide2.QtWidgets import QHBoxLayout, QLabel, QLineEdit, QWidget from PySide2.QtGui import QFont class RegisterWidget(QWidget): """Register widget""" def __init__(self, text): QWidget.__init__(self) self.label = QLabel() if text: self.label.set...
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings class Contact(models.Model): projects = models.ManyToManyField( "project.Project", through="ProjectContact", related_name="contacts" ) business = models.CharField(_("Business"), m...
#Contains machine learning pipeline methods #Based on Chiang et. al, 2014 import numpy as np import cPickle from scipy.linalg import norm from sklearn.linear_model import LogisticRegression import random #Split data into folds for cross-validation #Input: edges in dataset [list of 2-tuples] # Number of folds (k...
import cupy as cp def to_periodogram(signal): """ Returns periodogram of signal for finding frequencies that have high energy. :param signal: signal (time domain) :type signal: cudf.Series :return: CuPy array representing periodogram :rtype: cupy.ndarray """ # convert cudf series to ...
from django.contrib import admin from commit_month.models import CommitMonth # Register your models here. admin.site.register(CommitMonth)
""" Lasso """ from blackbox_selectinf.usecase.Lasso import LassoClass from blackbox_selectinf.learning.learning import learn_select_prob, get_weight, get_CI import numpy as np import argparse import pickle from scipy.stats import norm import matplotlib.pyplot as plt import torch from selectinf.distributions.discrete_f...
# -*- coding:utf-8 -*- from PIL import Image import os def cut(image_path, save_path, vx, vy): count = 0 im_name = os.listdir(image_path) paths = [] for name in im_name: path = os.path.join(image_path, name) paths += [path] for i, path in enumerate(paths): name = (path.sp...
matrix=[] row=int(input('Enter size of row: ')) column=int(input('enter size of column: ')) for i in range(row): a=[] for j in range(column): j=int(input(f'enter elements of the matrix at postion row({i})column({j}): ')) a.append(j) print() matrix.append(a) print('Elements of matrix: ') for i in rang...
def buildModel_LSTM_64_16(inputshape, outputs, options, softmax=True): import tensorflow as tf tf_recall=tf.keras.metrics.Recall() model = tf.keras.Sequential() model.add(tf.keras.layers.Bidirectional(tf.keras.layers.GRU( 64, name="BiDiIn", return_sequences=True, input_...
import torch import numpy as np def camera_ringnet(cam): camera_params = {'c': cam[1:3], 'k': np.zeros(5), 'f': cam[0] * np.ones(2)} camera_params['t'] = np.zeros(3) camera_params['r'] = np.zeros(3) return camera_params def camera_dynamic(h_w, translation): ...
from spike import App app = App() app.play_sound('Cat Meow 1')
# -*- coding: utf-8 -*- from __future__ import absolute_import from subprocess import PIPE import salt.modules.openscap as openscap from tests.support.unit import skipIf, TestCase from tests.support.mock import ( Mock, MagicMock, patch, NO_MOCK, NO_MOCK_REASON ) @skipIf(NO_MOCK, NO_MOCK_REASON)...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import setuptools PATH = 'src/specminers/version.py' PATH = os.path.join(os.path.dirname(__file__), PATH) with open(PATH, 'r') as fh: exec(fh.read()) setuptools.setup(version=__version__)
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages from codecs import open from os import path from aws_shelltools import __version__ here = path.abspath(path.dirname(__file__)) # Get...
supported_currencies = ('USD', 'EUR', 'ILS')
# coding=utf-8 import logging import six from fakturownia import core log = logging.getLogger(__name__) class BaseEndpoint(object): def __init__(self, api_client): self.api_client = api_client def create(self, **kwargs): return self.model(self.api_client, **kwargs).post() def __getite...
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import generics from rest_framework.permissions import IsAuthenticatedOrReadOnly from .models import Comment from .serializers import CommentSerializer from authors.apps.articles....
# Copyright (c) 2015 Red Hat, 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 in wri...
""" Services utils. """ from . import ( api, jwt, )
from ceph_deploy.hosts import util from mock import Mock class TestInstallYumPriorities(object): def setup(self): self.distro = Mock() self.patch_path = 'ceph_deploy.hosts.centos.install.pkg_managers.yum' self.yum = Mock() def test_centos_six(self): self.distro.release = ('6'...
# Generated by Django 3.1.2 on 2020-11-04 10:42 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ("eveonline", "0012_index_additions"), ...
#!/usr/bin/python from setuptools import setup, find_packages from cloudfiles.consts import __version__ setup(name='python-cloudfiles', version=__version__, description='CloudFiles client library for Python', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment ::...
#!/usr/bin/env python # coding: utf-8 # ## Configurations for Colab # In[1]: import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: get_ipython().system('apt-get install -y xvfb python-opengl > /dev/null 2>&1') get_ipython().system('pip install gym pyvirtualdisplay > /dev/null 2>&1') get_ipyt...
import click from flask import current_app from flask.cli import with_appcontext @click.group() def cli(): pass @cli.command() @with_appcontext def delete_expired(): ''' Deletes expired uploads ''' click.echo('Deleting expired uploads') try: current_app.flask_tus.repo.delete_expired() ex...
# Check Python Version import sys import scipy import numpy import matplotlib import pandas import sklearn print('Python: {}'.format(sys.version)) print('scipy: {}'.format(scipy.__version__)) print('numpy: {}'.format(numpy.__version__)) print('matplotlib: {}'.format(matplotlib.__version__)) print('pandas: {}'.format(p...
import os import sys import math import copy from binary_tree import BinaryTreeNode, BinaryTree, BinarySearchTree from graph import GraphNode, Graph # 4.6 find the next node (in-order) of a given node in a Binary Tree # -> back to root and using in-order travelsal until meet the current node. get the next def get_ne...
number_one = int(input()) number_two = int(input()) symbol = str(input()) if symbol == "+": result = number_one + number_two if result % 2 == 0: print(f"{number_one} + {number_two} = {result} - even") else: print(f"{number_one} + {number_two} = {result} - odd") elif symbol == "-": resu...
import os import pandas as pd from bs4 import BeautifulSoup from Utility import fetchGradeCard, isResultOut def generateRanks(clgCode, rolldobList): flag = False sem = None course = None invalids = [] rankData = {'Exam Roll Number':[], 'Name':[], 'CGPA':[]} for rollNo,dob in rolldobLi...
from app import db class TestSuite(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True) def __repr__(self): return '<TestSuite {}>'.format(self.name) class Test(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.C...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import autoslug.fields class Migration(migrations.Migration): dependencies = [ ('questions', '0004_multiplechoiceoption_other'), ] operations = [ migrations.AlterField( m...
#!/usr/bin/env python import haas.api from haas import config, model, server config.setup('/etc/haas.cfg') server.init() from haas.rest import app as application
class Entity: """ The entity class is the definition of an object in the game. Door, frame, enemy,.. Every thing the the player can interact with. """ def __init__(self, position: tuple[int, int], sprite: list[str], color: str = ""): self.position = position self.sprite = sprit...
#!/Users/wzf/PycharmProjects/Eat_or_not/venv/bin/python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
"""Provides classes for interacting with iTerm2 sessions.""" import asyncio import iterm2.api_pb2 import iterm2.app import iterm2.capabilities import iterm2.connection import iterm2.keyboard import iterm2.notifications import iterm2.profile import iterm2.rpc import iterm2.screen import iterm2.selection import iterm2.u...
import os import numpy as np import torch from gym_robothor.envs.robothor_env import RoboThorEnv, env_generator def reset(env, state_shape, device): state, bear = env.reset() mask_t = torch.tensor(0., dtype=torch.float32).to(device) prev_a = torch.tensor(0, dtype=torch.long).to(device) obs_t...
from scipy import * from pylab import * img = imread("img/me1.jpg")[:, :, 0] gray() figure(1) imshow(img) print("original size:" + str(img.shape[0] * img.shape[1])) m, n = img.shape U, S, Vt = svd(img) S = resize(S, [m, 1])*eye(m,n) k = 10 figure(2) imshow(dot(U[:,1:k], dot(S[1:k, 1:k], Vt[1:k, :]))) ...
import sys import logging import base64 import inspect import subprocess def stream(): while True: data = sys.stdin.readline() if not data: break exec(data) def main(target, python): code = inspect.getsource(stream) b64c = base64.b64encode(code.encode()) cmd = ['s...
from pymongo import MongoClient MONGO_DB_HOST = 'localhost' MONGO_DB_PORT = '27017' DB_NAME = 'tap-news' class MongoDBClient: def __init__(self, host=MONGO_DB_HOST, port=MONGO_DB_PORT): self.client = MongoClient("%s:%s" % (host, port)) def get_db(self, db=DB_NAME): db = self.client[db] ...
from django.utils.translation import ugettext_lazy as _ from enumfields import Enum class NotificationType(Enum): RELATIONSHIP_CONFIRMATION_NEEDED = "relationship_confirmation_needed" RELATIONSHIP_CONFIRMED = "relationship_confirmed" class Labels: RELATIONSHIP_CONFIRMATION_NEEDED = _( ...