text
stringlengths
8
6.05M
import sys import os import math # from bank_reserves.random_walk import RandomWalker import pandas as pd import random, pickle, time from datetime import datetime # import json random.seed(42) class Consumer(): def __init__(self, unique_id): # initialize the parent class with required parameters # ...
import discord from discord.ext import commands class UnPoof(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def unpoof(self, ctx, *, Name): bans = await ctx.guild.bans() for i in bans: if i.user.name.lower() == Name.lower()...
#!/usr/bin/env python import os import yaml import click @click.command() @click.option( "--jjbfile", type=click.File('r'), required=True, help="Extract dsl from this JJB job") @click.option( "--outdir", type=click.Path(exists=True), required=True, help="Dir to write extracted groovy ...
# r = requests.get("http://www.pythonhow.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/") # r = requests.get("http://www.pyclass.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/", # headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'}) import requests from bs4 impo...
import json import os import logging import logging class JsonConfigReader(object): def __init__(self, config_path, options=None): """Class constructor. Args: config_path (str): configuration folder wihtout trailling '\' or file absolute path with *.json extension. optio...
import unittest from katas.beta.simple_beads_count import count_red_beads class CountRedBeadsTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(count_red_beads(1), 0) def test_equal_2(self): self.assertEqual(count_red_beads(3), 4) def test_equal_3(self): self....
import numpy as np from solver import tsv2arr from math import floor from settings import * def create_sliding_window(data: np.ndarray, window_size: int): """ Converts data to sliding window data :param data: Timeseries data to convert to sliding window data. Columns of data are x1,..,xn,t. :param win...
# decision.py contains the class structure and state behaviour of the mars # rover in the Unity simulator. import numpy as np from rover_commands_2 import Driving, Steering from rover_commands_3 import Navigate from navigable_pixels import NavPixels, NavPixelLimits, NavPixelsInSegment class Decision(): ...
from apel.common import valid_from, valid_until, parse_timestamp, \ iso2seconds from unittest import TestCase import datetime class DateTimeUtilsTest(TestCase): ''' Test case for date/time functions from apel.common ''' def test_valid_from(self): now = datetime.datetime.now() ...
from urllib.parse import urljoin import requests from ex02_bearer import bearer_token_for_namespace import stacksmith def get_apps(namespace, token): endpoint = urljoin(stacksmith.url, 'ns/{ns}/apps'.format(ns=namespace)) response = requests.get( endpoint, headers={'authorization': token}) asse...
import os from Helper import Utils '''Global path variables are set in here.''' '''Be aware that a change of this file might affect several other files.''' # Data directories global_path_to_original_train_data = '../../Resources/TrainingDataSets/train1' global_path_to_original_test_data = '../../Resources/TrainingDat...
import os import sys import cv2 import numpy as np input_file = 'C:/Users/dell/Desktop/niit/niit/3rd semester/letter.data' img_resize_factor = 12 start = 6 end = -1 height, width = 16, 8 with open(input_file, 'r') as f: for line in f.readlines(): data = np.array([255 * float(...
#クイックソート(ピポットは先頭) def sort(A): if len(A) < 2: return A p = A[0] X,Y = divide(p,A[1:]) return sort(X) + [p] + sort(Y) def divide(p,A): if len(A) < 1: return ([],[]) X,Y = divide(p,A[1:]) a = A[0] if a < p: return ([a] + X,Y) else: return (X,[a] + Y)
import requests import re import time from bs4 import BeautifulSoup import sys from operator import itemgetter username_=sys.argv[1] password_=sys.argv[2] timetorun=int(sys.argv[3]) period = int(sys.argv[4]) def get_router_data(param): login_data = { 'username': username_, 'password': password_, 'subm...
'''****************************************** ATHON Programa de Introdução a Linguagem Python Disiplina: Lógica de Programação Professor: Francisco Tesifom Munhoz Data: Primeiro Semestre 2021 ********************************************* Atividade: Lista 2 (Ex 10) Autor: Yuri Pellini Data: 19 de Maio de 2021 Comentário...
import pandas as pd import pickle import re from pymystem3 import Mystem def predict_department(text: str) -> int: """ Predicts target department id for a task Input: text. A string containing task description Output: department_id. Integer value. One of ...
#!/usr/bin/env python # Copyright (c) 2015 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies actions with multiple outputs will correctly rebuild. """ import TestGyp import os import sys if sys.platform == 'win32': p...
# More files from sys import argv from os.path import exists script,from_file,to_file=argv print "Copying files from %s to %s." %(from_file,to_file) in_file=open(from_file) in_data=in_file.read() print "The input file is %d bytes long " %len(in_data) print "Does the output file exists? %r " %exists(to_file) print...
import unittest from katas.kyu_7.a_rule_of_divisibility_by_13 import thirt class ThirtTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(thirt(1234567), 87) def test_equals_2(self): self.assertEqual(thirt(321), 48) def test_equals_3(self): self.assertEqual(thir...
''' 66. Plus One Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. You may assume the integer do not contain any leading zero, except the number 0 itself. The digits are stored such that the most significant digit is at the head of the list. ''' class Solution(object):...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import MapCompose, TakeFirst, Join from w3lib.html import remove_tags import re # 新闻资讯...
import torch import numpy as np import matplotlib.pyplot as pp import copy import pickle import gzip import hashlib import os.path import sklearn.datasets from sklearn.datasets import load_boston def run_exp(meta_seed, nhid, n_train_seeds): torch.manual_seed(meta_seed) np.random.seed(meta_seed) gamma = 0.9...
# utils/models.py # -*- coding: UTF-8 -*- from __future__ import unicode_literals from django.db import models # import urlparse from django.utils.six.moves.urllib.parse import urlparse, urlunparse from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now as timezone_now from django...
from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .models import Notification @receiver(post_save, sender=Notification) def create_notification(sender, instance, created, **kwargs): print("hey") # # def my_handler(sender, insta...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-06 20:20 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('polls', '0003_choice'), ] operations...
from panda3d.core import GeomVertexFormat, Vec3, LTexCoord, NodePath, RenderState, GeomEnums, GeomVertexData, \ GeomVertexWriter, InternalName from .Geometry import Geometry from .PolygonView import PolygonView class MeshVertex: def __init__(self, pos, normal, texcoord): self.pos = pos self.n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 12 12:08:25 2019 @author: xabuka """ # best Identify langauge code from sklearn.datasets import load_files from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.svm import Lin...
import enemy,pygame class Skeleton(enemy.Enemy): frame={} sound={} def __init__(self,position=(0,0),index=0): super(Skeleton, self).__init__(position) self.rect = Skeleton.frame[self.frame_on][self.frame_index].get_rect(topleft=position) self.hit_box = pygame.Rect(position[0], posit...
import pickle reviews = pickle.load(open("data/gameReviewDict.p", "rb")) from clusterGames import * def clusterTestGame(fText): gameName = "Test Game Title.txt" return getGameCluster(reviews, gameName, fText)
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() from dajaxice.core import dajaxice_autodiscover, dajaxice_config dajaxice_autodiscover() urlpatterns = patterns('', # Welcome Page: url(r'^$', 'kit...
# import numpy as np # import matplotlib.pyplot as plt # data_set = np.loadtxt( # fname="amp.csv", # dtype="int", # delimiter=",", # ) # # 散布図を描画 → scatterを使用する # # 1行ずつ取り出して描画 # #plt.scatter(x座標の値, y座標の値) # for data in data_set: # plt.scatter(data) # plt.title("correlation") # plt.xlabel("Average Te...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('query', '0015_auto_20160203_1037'), ] operations = [ migrations.AddField( model_name='term', name='t...
import pytest @pytest.fixture(scope="session") def init_data2(): print("---初始化数据init_data2---")
# -*- encoding: utf-8 -*- import datetime def formata_data(data): data = datetime.datetime.strptime(data, '%d/%m/%Y').date() return data.strftime("%Y%m%d") def formata_valor(valor): return str("%.2f" % valor).replace(".", "")
class Node: def __init__(self,value): self.value = value self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def search(self,value): if self.root is None: return False current_root = self....
# -*- coding: utf-8 -*- from django.contrib.auth.views import REDIRECT_FIELD_NAME from django.shortcuts import redirect, resolve_url def login(request): if request.method == 'GET' and request.user.is_active and request.user.is_staff: return redirect(resolve_url('npcms:dashboard')) from django.contri...
writeFile = open("dict.txt", 'w'); with open("dict1.txt") as file: for line in file: # Checa se todos os caracteres sao uppercase: if(line == line.upper()): continue; # Converte todos os caracteres para lowercase: newWord = line.lower(); # Checa se a...
def funny(s,t): if len(s) != len(t): return False elif len(s) == 0: return True d={} for i in range(len(s)): if s[i] not in d.keys(): d[s[i]] = t[i] else: if d[s[i]] != t[i]: return False ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-23 14:04 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
from script.base_api.service_idea.pay import *
import sys s = "4nt1_D3bugg3rs_4r3nt_So_B4d_Aft3r_All_R1ght?" xor_bytes = [0xd1, 0xee, 0xd9] print "int xor_bytes[%d] = {" % len(s) for i, c in enumerate(s): b = xor_bytes[i % len(xor_bytes)] ^ ord(c) sys.stdout.write("0x{:02x}".format(b) + ", ") if (i + 1) % 16 == 0: print "" print "" print "}...
import pickle import torch import argparse import os import subprocess import matplotlib.pyplot as plt from drivingenvs.vehicles.ackermann import AckermannSteeredVehicle from drivingenvs.envs.driving_env_with_vehicles import DrivingEnvWithVehicles """ Given a path to experiment output, make a video of the policy acti...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # type: ignore import base64 import os from pathlib import Path from typing import List, Set import nox from nox.sessions import Session DEFAULT_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] PYTHON_VERSIONS = os.environ.get( "NOX_PYTHON_VERS...
import envi.qt as envi_qt import envi.bits as e_bits import envi.qt.memory as e_mem_qt import envi.qt.memcanvas as e_mem_canvas import vstruct.qt as vs_qt import vqt.menubuilder as vqt_menu import vivisect.base as viv_base import vivisect.renderers as viv_rend import vivisect.qt.views as viv_q_views import vivisec...
"""Module to create README.md file with basic scaffold.""" import argparse import os import shutil import markdown_generator as mg from readme_generator.scaffold_options import (dbms, frameworks, languages, serving_options, test_options,) from write_me.dep_info import p...
from django import forms from .models import * class QualificationForm(forms.ModelForm): field=forms.CharField(label='Field of Study',widget=forms.TextInput(attrs={"placeholder":"Field of Study"})) institute=forms.CharField(label='Name of Institution',widget=forms.TextInput(attrs={"placeholder":"Name of Colleg...
""" This module lets you practice using Create MOVEMENT and SENSORS, in particular the DISTANCE and ANGLE sensors. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and Muqing Zheng & Jindong Chen. September 2015. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. from saf...
#!/usr/bin/env python2 if __name__ == '__main__': import sys from gdrive import main sys.exit(main(sys.argv))
import numpy as np def normalize(a): a = np.array(a) return a/np.linalg.norm(a) def add_vectors(a,b): c = (a[0]+b[0], a[1]+b[1]) return c
import numpy as np #1. 훈련 데이터 x = np.array(range(1,101)) y = np.array(range(1,101)) #print(x) # x_train, x_val, x_test = np.split(x, [60,80]) # y_train, y_val, y_test = np.split(y, [60,80]) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split( x, y, random_state =...
class MatrixException(Exception): def __init__(self, text=None): self.text=text def __str__(self): if self.text is None: return 'Raised' else: return self.text class RMatrixException(MatrixException): pass class RMatrixArithmeticError(RMatrix...
# Copyright 2010 Alon Zakai ('kripken'). All rights reserved. # This file is part of Syntensity/the Intensity Engine, an open source project. See COPYING.txt for licensing. import os # Offer to interactively set up the settings.json def run(config_filename, template_filename): print print '=================...
# -*- coding: utf-8 -*- """ Created on Fri Mar 1 12:31:14 2019 Update: trial2: >using classes trial 3: >Using factorize for non-numeric data trial 4: >Attempting to use duplicate dataset where factorization is not vital >13/3/19: Ma...
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ previous, result = 0,0 search = {} for next in range(len(s)): if s[next] in search: previous = max(previous,search[s[next]]+1)...
#!/usr/bin/env python # test has been developed by Robert Harakaly and changed for SAM by Victor Galaktionov # get information about a LFC file or directory in the name server (lfc_statgx) # meta: proxy=true # meta: preconfig=../../LFC-config import os, lfc, sys from testClass import _test, _ntest, _testRunner, SAM_R...
import base64 import json import time import urllib.parse import hashlib import hmac import tempfile import threading from django.core.files import File from django.core.files.storage import Storage import requests.exceptions from django.utils.functional import cached_property extra_headers = { 'User-Agent': 'Ba...
import time import json import random from flask import Flask, jsonify from flask_socketio import SocketIO, emit, join_room, leave_room import AnomalyDetector app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, cors_allowed_origins='*') detector = AnomalyDetector.AnomalyDetector() @so...
import requests import json import os import gitlab import sys from namespace_definer import namespace from support import parse_file_variable, parse_file_variable, mask_vars from authorization import gitlab_private_token, gitlab_url def show_vars(namespace): if isinstance(namespace[next(iter(namespace))], gitlab...
from django.core.paginator import Paginator posts = ['1','2','3','4','5'] # this will show two post at a time on the page p = Paginator(posts, 2) print(p.num_pages) #return 3 pages #using page_range will make an interable for page in p.page_range: print("page " + str(page)) # return 1,2,3. these are the page nu...
from django.forms import ModelForm from .models import Produit,Facture from django import forms class ProduitForm(ModelForm): class Meta: model=Produit fields='__all__' class FactureForm(ModelForm): class Meta: model=Facture fields='__all__'
import DFS connection_file = open("connections.txt", "r") # open file for reading only location_file = open("locations.txt", "r") connections_data = connection_file.readlines() # save file into list location_data = location_file.readlines() connection_file.close() # close file location_file.close() #path = DFS.D...
from itertools import chain from datetime import datetime import re from datatypes import TransactionType, TransactionDirection, ParsedBankAccountTransaction, ParsedCreditCardTransaction from datatypes import Account, Bank, Card, UnknownSubject, UnknownWallet from common.parsing import extract_literals, extract_keywo...
from pymongo import MongoClient class DbWorker: def __init__(self): client = MongoClient() self.db = client.test_database self.applications = self.db.applications def add(self, app): if self.applications.find_one({'id': app.get('id')}): self.applications.update({'i...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-07-26 13:33 from __future__ import unicode_literals import django.db.models.deletion import storages.backends.s3boto3 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("elections", "0030_merge_20170424_140...
import xlrd, openpyxl # 1. Read xlsx file self.input_data = [] INPUT_FILE = 'sam.xlsx' input_xls = xlrd.open_workbook(INPUT_FILE) sheet = input_xls.sheet_by_index(0) for row_index in range(0, sheet.nrows): row = [sheet.cell(row_index, col_index).value for col_index in range(sheet.ncols)] self.input_data.append...
import jwt from django.contrib.auth import get_user_model from rest_framework import serializers from residents.models import Lot,Community,Area,Street,Resident,ResidentLotThroughModel,Profile from rest_framework_jwt.compat import Serializer from ivms.models import IPCamera,Boomgate from security_guards.models import S...
#!/usr/bin/env python import rospy from std_msgs.msg import Bool from ackermann_msgs.msg import AckermannDriveStamped import sys, select, termios, tty banner = """ Reading from the keyboard and Publishing to AckermannDriveStamped! --------------------------- Moving around: w a s d anything else : s...
from django.db import models class Todo(models.Model): title = models.CharField('内容', max_length=200) finished = models.BooleanField('完了済み', null=True) created_at = models.DateTimeField('作成日時', auto_now_add=True) updated_at = models.DateTimeField('更新日時', auto_now=True) class Meta: verbose...
#!/usr/bin/env python3 """ Example usage of the ODrive python library to monitor and control ODrive devices """ from __future__ import print_function import odrive from odrive.enums import * from odrive.utils import dump_errors import time import math import sys import fibre from odrive_manager import OdriveManager ...
"""merge 10-fold result""" import codecs lines = {} for i in xrange(10): with codecs.open('test_mapped_' + str(i) + '.csv', 'r', 'utf8') as reader: line_num = 0 for line in reader: lines[line_num * 10 + i] = line line_num += 1 with codecs.open('test_mapped.csv', 'w', 'utf8'...
a = 'hello' b = 1 print(dir(b))
from django.urls import path from . import views app_name='register' urlpatterns=[ path('index',views.index,name='index'), path('submit',views.submitDetails,name='submit') ]
import Queue import time from rabbit_consumer import RabbitConsumerProc, RabbitConsumerThread from abstract_bot import AbstractBot from vibebot.ConsumerCallback import ConsumerCallback class EventBot(AbstractBot): def __build_consumers__(self, exchange_callbacks): self.logger.info("Event bot created v0...
import subprocess, argparse parser = argparse.ArgumentParser(description='A script for running NuGet.') parser.add_argument('config', help='Path to NuGet config file.', type=str) parser.add_argument('slndir', help='Path to VS Solution Dir.', type=str) args = parser.parse_args() print("Installing NuGet packag...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test Twitter developer keys. Usage: python validate_twitter_keys.py Input data files: ../conf/developer.key """ import json from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener from multiprocessing import Queue class...
import pygame as pg import os from sprites import * import animation as ani from settings import Settings class Game: def __init__(self): pg.init() self.screen = ... # Crée un écran pygame de taille Settings.WIDTH x Settings.HEIGHT ... # Donner Settings.TITLE en tire à la fenêtre s...
import json import os import re import base64 from urllib import parse from common.common_util import replace_string def get_cases(path): with open(path, 'r', encoding='utf-8') as file: case_content_json = json.loads(file.read()) entries = case_content_json.get("log").get("entries") step_l...
######################################################################################################################## # LDAP Authentication Settings ######################################################################################################################## import ldap import os from django_auth_ldap.co...
# -*- encoding: utf-8 -*- # Livejournal toolkit, includes some simple caching. import re import urllib2 from urllib import urlencode, addinfourl import httplib import logging from StringIO import StringIO import xml.etree.ElementTree as ElementTree from django.core.cache import cache from django.conf import settings ...
import random class Creat(object): def __init__(self, max_num: int, formula_num: int): self.max_num = max_num # 最大范围 self.formula_num = formula_num # 公式最大条数 self.level = random.randint(2, 4) # 递归层数 self.start_level = 0 # 递归开始层 self.first_level = random.randint(1, self.l...
# Python Text RPG # Underwhelmed Ape import cmd # help use command line import textwrap # wrap text around the console for overflow import sys import os import random # generate pseudo-random numbers import math from collections import OrderedDict from functools import partial from title_screens import title_screen, h...
# Copyright 2014 Google. # # 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, softw...
""" 剑指 Offer 64. 求1+2+…+n 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 """ # 其实就是简单的高斯求和,但是这边做出了诸多限制,所以才让这个题这么难。我的首选肯定是递归,但是递归的结束必须用条件语句,这边直接用逻辑运算的短路效应来搞定应该也可以。 def sumNums(n): return n>=1 and n+sumNums(n-1) or n def sumNums2(n): if n ==1: return 1 return sumNums2(n-1) +n if __na...
################################################################################################### # date_dilemma() # # ----------------------------------------------------------------------------------------------- # # The program takes ...
def append(alist, iterable): for item in iterable: alist.append(item) def extend(alist, iterable): alist.extend(iterable) import timeit print(min(timeit.repeat('lambda: append([], "abcdefghijklmnopqrstuvwxyz")', repeat=20, number=1000000))) print(min(timeit.repeat('lambda: append([], "abcdefghijklmno...
import psutil def compiling(lang,name,filename): if lang =='c++': psutil.Popen('g++ '+name+' -o '+filename+" -O2",shell=True).wait() if lang =='c': psutil.Popen('gcc '+name+' -o '+filename,shell=True).wait() if lang == 'golang': psutil.Popen('go build ' + name + ' -o ' + filename , shell=True).wait()
import os from urllib.parse import urlparse from traitlets import Float, Unicode, Int, List, Instance, Bool, Dict, HasTraits from ipywidgets import Widget, register, widget_serialization from ipywidgets.widgets.trait_types import Color, InstanceDict from ipywidgets.widgets import widget from ._version import EXTENS...
import math import copy import matplotlib.pyplot as plt import numpy as np import Solution as sl import Problem import ParetoUtil as pu import Metrics as met import MRML as mm class NSPSOMMBase(): def __init__(self, problem, popSize: int): super().__init__() self.problem = proble...
import asyncio import time async def client(address): reader, writer = await asyncio.open_connection(*address) while True: writer.write(b'Hello from client') await writer.drain() resp = await reader.read(100000) print(b"got: " + resp) time.sleep(1) asyncio.run(client(('...
# -*- coding: utf-8 -*- """ Created on Thu May 23 08:13:00 2019 @author: Odi """ # ejemplo de uso de Grafo import networkx as nx G = nx.DiGraph() # agegar nodos G.add_node("Inicio") # Ocasion, TiempoDeConocerse, Cuidado, Edad, Color G.add_node("Rosa") # amor, mas, normal, menosDe20, rojo G.add_node("Rosa blanca") #...
#!/usr/bin/python #-*- coding: utf-8 -*- """ """ import os import commands import subprocess import re import httplib import logging import logging.handlers import json import time def json_response(errno, msg=None): resp = {} resp['status'] = errno message = [error.errors[errno]] if msg: mes...
import os import sys import importlib from nab import log _loaded = False def load(): """ Import all plugins in folder. Will only run once. """ global _loaded if _loaded: return log.log.debug("Loading plugins") _loaded = True for folder, sub, files in os.walk("nab/plugins/")...
import os import time from threading import Timer from .transport import protocol from electrum.util import print_stderr, raw_input, _logger IS_ANDROID = True UI_HANDLER = None if "iOS_DATA" in os.environ: from rubicon.objc import ObjCClass UI_HANDLER = ObjCClass("OKBlueManager") IS_ANDROID = False elif "...
""" https://leetcode.com/problems/maximum-subarray/ Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Example 2: Input: nu...
import random from collections import namedtuple from itertools import product, chain from enum import Enum from .tile import Tile Direction = Enum('Direction', "up left down right") Position = namedtuple('Position', "row column") Actions = Enum('Actions', "spawn move merge") class SpawnTileError(Exception): ...
# coding=utf-8 from django.core import serializers import sqlite3 import json from datetime import datetime from django.conf import settings from django.contrib.sites.models import Site from django.utils import feedgenerator from django.shortcuts import render_to_response, get_object_or_404 from django.template.loader ...
from django.contrib.auth.models import AbstractUser from django.core.validators import RegexValidator from django.db import models class User(AbstractUser): email = models.EmailField( 'email address', unique=True, error_messages={ 'unique': "A user with that email already exist...
# Copyright 2020 Pulser Development Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
from django.conf.urls import patterns, include, url from mvhbc import views # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'clubmanager.views.home', name='home'), # url(r'^clubmanager/', include(...
# -*- coding: utf-8 -*- """ Simple NLP Encoding Created on Thu Jan 31 13:51:08 2019 @author: Markus.Meister """ import glob import sys import os import torch import pandas as pd import numpy as np import nltk #from nltk import word_tokenize as tkn import gensim from gensim import corpora, mode...