content
stringlengths
5
1.05M
import requests #open cmd as administrator, #then type "python -m pip install -U pip requests (new)" to install pip #Get response from API endpoint. a = input("please enter") #in a browser, input [REDACTED] response = requests.get("redacted_link" + a) data = response.json() print(data['result']) #dat...
#!/usr/bin/python3 """ Blueprint for API ------------------ URL_prefix: /card_validator/api/v1.0 """ from flask import Blueprint prefix = "/card_validator/api/v1.0" app_views = Blueprint('app_views', __name__, url_prefix=prefix) from api.v1.views.index import * from api.v1.views.cards import *
import pytest from feed.factory import create_web_app @pytest.fixture def app(): return create_web_app()
#!/usr/bin/python3 # -*- coding: utf-8 -*- # DBエンジン指定のため from sqlalchemy import create_engine # ORMに必要なインポート from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.schema import UniqueConstraint # セッション作成に必要 from sqlalchemy.orm import sessionmaker # ...
from gtts import gTTS import os import requests import config import logging # from pydub import AudioSegment class Quiz: '''To download quizlet data and save it as an mp3 file.''' def __init__(self): '''Creates a new quiz using config file.''' # setup set self.set = sel...
from typing import Any import tornado.httpclient # type: ignore import tornado.testing # type: ignore from openapi_core import create_spec # type: ignore from openapi_core.spec.paths import SpecPath # type: ignore from tornado_openapi3.responses import ResponseValidator class AsyncOpenAPITestCase(tornado.testin...
"""empty message Revision ID: ccde635499c4 Revises: b905e88b5cb0 Create Date: 2016-07-04 09:45:11.687369 """ # revision identifiers, used by Alembic. revision = 'ccde635499c4' down_revision = 'b905e88b5cb0' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): ### ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
from django.contrib.auth.decorators import login_required from django.shortcuts import redirect, render from company.forms import CompanyCreationForm from company.models import Company, JoinRequest @login_required def company_view(request): if request.user.profile.company: return redirect('project_index')...
import cv2 as cv import numpy as np import os os.chdir(os.path.dirname(os.path.abspath(__file__))) def findObjectCentre(target_img_path, sample_img_path, threshold=0.8, graphic=None): sample_img = cv.imread(sample_img_path, cv.IMREAD_UNCHANGED) target_img = cv.imread(target_img_path, cv.IMREAD_UNCHANGED) ...
# Generated by Django 4.0.2 on 2022-02-23 10:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0005_hose_hosestatic_hosedynamic'), ] operations = [ migrations.AddField( model_name='hosedynamic', name='nu...
# enter your own api key and api secret from your binance account API_KEY = 'quoYMl0sL********************Lir8BXW1H8C1Qg******pXTeWhU9wKy' API_SECRET = 'oI72****************LhIlh66BZpiVWwEZ2R2*******zRGD'
import csv import glob import multiprocessing as mp import os import signal import time import pytricia import requests import ujson as json from artemis_utils import get_ip_version from artemis_utils import get_logger from artemis_utils.constants import CONFIGURATION_HOST from artemis_utils.constants import DATABASE_...
from abc import ABC, abstractmethod, ABCMeta from domain.models.paths import Paths class AbstractPathService(ABC): __metaclass__ = ABCMeta @abstractmethod def get_paths(self) -> Paths: raise NotImplementedError
import logging import sys import traceback from django.shortcuts import render logger = logging.getLogger(__name__) def custom_500(request, exception=None): exception, value, tb = sys.exc_info() ftb = traceback.format_exception(exception, value, tb) logger.debug(ftb) return render(request, "500.html"...
""" Generic function utilities to test type of function """ from builtins import str from future.utils import raise_ import numpy as num from anuga.fit_interpolate.interpolate import Modeltime_too_early from anuga.fit_interpolate.interpolate import Modeltime_too_late import warnings #warnings.filterwarnings('default'...
from django.urls import path from blog.views import * app_name = 'blog' urlpatterns = [ path('',Blog_index,name='index'), path('<int:pid>',Blog_single,name='single'), path('author/<str:author_username>',Blog_index,name='author'), path('search/',Blog_search,name='search'), path('category/<str:cat_nam...
""" This script finds a PSD matrix that is closest to a given symmetric, real matrix, as measured by the Frobenius norm. That is, for a given matrix P, it solves: minimize || Z - P ||_F subject to Z >= 0 Adapted from an example provided in the SeDuMi documentation and CVX examples. Unlike those examples, the d...
import os,sys,commands,socket os.system("iptables -F") os.system("systemctl stop firewalld") os.system("setenforce 0") #################################################################################################################################################### def gen_coresite(name_node_ip,port=10001): #A fun...
from salabsutils import DynamicRobotApiClass from robot.api.deco import keyword import sys import os import requests import socket import errno from furl import furl from time import time as now from time import sleep from subprocess import Popen, DEVNULL class GuiStatusKeywords(DynamicRobotApiClass): def __init_...
print("Please think of a number between 0 and 100!") low, high = 0, 100 guess = int((low + high) / 2) while True: print("Is your secret number",guess ,"?") print("Enter 'h' to indicate the guess is too high. Enter 'l'", end="") y = input("to indicate the guess is too low. Enter 'c' to indicate I guess...
import pandas import matplotlib import numpy import scrapy import scipy import sklearn print("Hello")
"""Module to build the xiRT-network.""" import os import numpy as np import pandas as pd import tensorflow as tf import tensorflow_addons as tfa import yaml from tensorflow.keras import backend as K from tensorflow.keras import losses from tensorflow.keras import regularizers, optimizers from tensorflow.keras.callback...
# metaclass. from logistics.plugins.metaclass import Meta # imports all data types. from logistics.plugins.types import * # import all relevant contents from the associated module. from vandal.objects.montecarlo import ( MonteCarlo, MCapp, ) from vandal.objects.eoq import( EOQ, EOQapp, ...
# # Copyright (c) SAS Institute 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 w...
#coding=utf8 """抓取知乎话题结构的爬虫 使用多线程优化 """ import os import re import json import time import requests import lxml import lxml.html from lxml import etree from zhihuSpider.config.Config import URL from zhihuSpider.config.Config import DATA_DIR from zhihuSpider.config.Config import HEADERS,TIMEOUT from zhihuSpider.con...
from datetime import datetime from time import mktime from sqlalchemy import \ MetaData, Table, Column, \ Integer, DateTime, String, Text, Boolean, Sequence, \ ForeignKey, \ PrimaryKeyConstraint, UniqueConstraint, \ create_engine, \ desc from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm ...
from kungfu._utils import map_maybe from kungfu.tensorflow.ops import (all_reduce, counter, current_cluster_size, current_rank, fuse, global_noise_scale, group_all_reduce) from kungfu.tensorflow.optimizers.core import (_create_kungfu_optimizer, ...
# -*- coding: utf-8 -*- import abc import random import socket import six import structlog from statsd.client.timer import Timer from statsd.client.udp import Pipeline logger = structlog.get_logger(__name__) class StatsDTelegrafClientBase(object): """ Telegraf compatible statsd client base. This base cl...
import asyncio import functools as ft import logging import os from django.conf import settings from django.utils.module_loading import import_string from aiohttp.web import WebSocketResponse, HTTPForbidden, Application from redis_pubsub import REDIS_PUBSUB from redis_pubsub.util import get_async_redis, Subscription...
# Import modules import numpy as np import pickle from pybann import Layer from pybann import GradientDescent class Model: def __init__(self, name:str="New model")->None: self.name = name self.layers = [] def __repr__(self)->None: return "Model(name={})".format(self.name) def __s...
import os import re def rename_files(dir_path, pattern, replacement): cwd = os.chdir(dir_path) file_list = os.listdir(dir_path) new_file_list = [] for fl in file_list: print('change {} name'.format(fl)) new_fl = re.sub(pat, replacement, fl) new_file_list.append(new_fl) ...
"""Create a powder diffraction figure""" import matplotlib.pyplot as plt import sys sys.path.append('..') from plot_diffraction_patterns import powder_diffr_fig measured_patterns_dir = "../../../results/intermediate/integrated_1D/PS_1p3V_b" reference_peaks_dir = "../../../results/intermediate/peaks_references" figure...
from floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.plot import plot_water_levels from floodsystem.flood import stations_highest_rel_level import datetime def run(): stations = build_station_list() update_water_le...
from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from django import forms from django.db.models import Count from dcim.models import Device from utilities.forms import BootstrapMixin, BulkImportForm, CSVDataField, SlugField from .models import Secret, SecretRole, UserKey def validate_rsa_key(k...
# coding: utf-8 def get_class(obj): return type(obj).__name__ if __name__ == '__main__': class bar(object): def __init__(self): print(get_class(self)) class foo(bar): pass foo()
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import datasets from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import pickle import joblib iris = datasets.load_iris() df = pd.Dat...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from abc import ABC from typing import Awaitable, Callable from botbuilder.core import TurnContext, InvokeResponse from botbuilder.schema import Activity class StreamingActivityProcessor(ABC): """ Process streaming...
def get_most_and_least_frequencies(first_char: str, input: dict): char_occurrences = {} for source, frequency in input.items(): if source[-1] in char_occurrences.keys(): char_occurrences[source[-1]] += frequency else: char_occurrences[source[-1]] = frequency char_occu...
from git_guardrails.cli.color import strip_ansi from git_guardrails.cli.value_format import TOTAL_RESET, format_branch_name, format_remote_name from git_guardrails.cli.value_format import format_cli_command, format_commit, format_integer, format_sha from colorama import Fore, Back from git_guardrails_test_helpers impor...
import os PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) SCREENSHOT_PATH = None OPENGL = { "version": (3, 3), } WINDOW = { "class": "demosys.context.pyqt.Window", "size": (1280, 720), "aspect_ratio": 16 / 9, "fullscreen": False, "resizable": True, "title": "Examples", "vsync...
import numpy from scipy.interpolate import UnivariateSpline from sklearn.base import BaseEstimator, RegressorMixin, TransformerMixin, \ ClassifierMixin, MultiOutputMixin from sklearn.exceptions import NotFittedError from sklearn.utils.validation import check_X_y, check_is_fitted, column_or_1d from sklearn.utils.multic...
"""Test utilities """ import os import shutil from pathlib import Path import boto3 import dotenv TEST_DIR = Path(__file__).parent BASE_DIR = Path(__file__).parent.parent def load_test_environment(): """Set environment variables for testing """ test_env_file = str((BASE_DIR / '.env.test').resolve()) d...
import pytest @pytest.mark.migration def test_marked_with_migration_marker(): pass
import pymysql from scrapy.utils.project import get_project_settings class db(): def __init__(self): self.settings = get_project_settings() # 获取settings配置,设置需要的信息 self.host = self.settings['MYSQL_HOST'] self.port = self.settings['MYSQL_PORT'] self.user = self.settings['MYSQL_USER...
from motor_typing import TYPE_CHECKING def options(opt): # type: (Options.OptionsContext) -> None gr = opt.get_option_group('SDK paths and options') gr.add_option( '--macosx-sdk-min', action='store', default='', dest='macosx_sdk_min', help='Minimum version of the Ma...
# This file is a part of Arjuna # Copyright 2015-2020 Rahul Verma # Website: www.RahulVerma.net # 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...
# Generated by Django 3.0.6 on 2020-06-05 10:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0013_auto_20200603_0724'), ] operations = [ migrations.RemoveField( model_name='kvstore...
import os import cv2 import time import glob import torch import argparse import numpy as np import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torchvision.transforms as transforms from srnet import SRCNN from PIL import Image, ImageFile from function import RecurrentSampler from a...
""" Video handling library """ def get_test_video_filename(): return './lcp_video/test_data/test_video_clip.mov' def get_video_info(filename): """ returns information about video file in a dictionary format Parameters ---------- filename :: (string) full filename including root R...
#!/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys import math import tikzplotlib import os buffer = "" with open("rosc.cir") as fi: for line in fi: if(line.startswith("VDD")): buffer += "VDD VDD VSS dc {vdd}\n" else: buf...
import _ast import ast from typing import Dict, Union import os from pychecktext import teamcity, teamcity_messages class CheckTextVisitor(ast.NodeVisitor): def __init__(self, aliases: Dict[str, str] = {}): self.literal_calls = [] self.expression_calls = [] self.aliases = aliases s...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from django.forms.utils import ValidationError from institution.models import (Candidate, Position, Student, VotedElection, StudentVote, Faculty, User) class ECOfficerSignUpForm(UserCreationForm): cl...
from __future__ import annotations # forward declaration from typing import Optional, Iterable, Tuple, Dict, Any, Union import os import re import io class ConfigSection(): DEFAULT_OPT_SEPARATOR = ' = ' def __init__(self, text_before: Optional[str] = None, text_aft...
import os os.environ["KERAS_BACKEND"] = "tensorflow" from sklearn.preprocessing import MinMaxScaler import pickle import csv from math import sqrt from tensorflow import keras import keras import tensorflow as tf from keras.callbacks import EarlyStopping, CSVLogger from keras.callbacks import TerminateOnNaN tn = T...
from typing import Union, Iterable from live_plotter.base.Graph import Curve, DistributedCurve, SmoothedCurve from live_plotter.proxy.Proxy import Proxy from live_plotter.proxy.ProxyPlotter import ProxyPlotter from live_plotter.proxy.Task import CreateTask, UpdateTask class ProxyGraph(Proxy): def __init__(self):...
#!/bin/python3 import os # Complete the appendAndDelete function below. def appendAndDelete(s, t, k): common_length = 0 for chr in range(min(len(s), len(t))): if s[chr] == t[chr]: common_length+=1 else: break if len(s) + len(t) - 2 * common_length > k: ...
# # Advanced Lane Finding Project # # The goals / steps of this project are the following: # # * Compute the camera calibration matrix and distortion coefficients given a set of chessboard images. # * Apply a distortion correction to raw images. # * Use color transforms, gradients, etc., to create a threshold binary im...
from raypipe import logger from raypipe.core import rpipe from raypipe.core.data_model import LearningConfig from raypipe.core.rpipe.utils import build_ray_trainer from raypipe.core.train_template import keras_train_template @rpipe.init class ModelProxy: def __init__(self, model_strategy_func,data_generator_f...
import argparse shared_options = { 'fn': {'driverattr': 'fn', 'dest': 'infile', 'type': 'file', 'clarg': '-i', 'help': 'Input file of {} format'}, 'outfile': {'driverattr': 'outfile', 'dest': 'outfile', 'type': str, 'clarg': '-o', 'help': 'Output file', 'required': False}, 'outdi...
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('devilry_group', '0009_auto_20160107_1100'), ] operations = [ migrations.RemoveField( model_name='groupcomment', name='part_of_grading', ...
import cv2 import numpy as np import math from pynput.keyboard import Key, Controller cap = cv2.VideoCapture(0) keyboard = Controller() while 1: try: # an error comes if it does not find anything in window as it cannot find contour of max area # therefore this try error statement ret, frame = cap...
"""Support for HomematicIP Cloud climate devices.""" import logging from homematicip.group import HeatingGroup from homeassistant.components.climate import ClimateDevice from homeassistant.components.climate.const import ( STATE_AUTO, STATE_MANUAL, SUPPORT_TARGET_TEMPERATURE) from homeassistant.const import ATTR_...
def getHighFrequencyRetweeters(party , database): Query = 'Create table IF NOT EXISTS '+party+'retweeterFreq as Select retweeterId, count(*) as freq from ' + party+'retweeters ' \ 'group by retweeterId' print(Query) database.execute(Que...
from typing import Optional, List, ForwardRef, Union from pydantic import BaseModel Node = ForwardRef("Node") class Node(BaseModel): """ This abstract object represents a DOM Node. """ tag: str """ Name of the DOM element. """ attrs: Optional[dict] """ Optional. Attributes of the DOM element """...
## SETUP ## ## dependencies import pandas as pd ## logging sys.stdout = open(snakemake.log[0], 'w') sys.stderr = open(snakemake.log[0], 'w') ## input files input_dict = { 'taxlist' : snakemake.input['taxlist'], 'slvmap' : snakemake.input['slvmap'], 'dups' : snakemake.input['dups'], } ## output files ou...
import msvcrt, os, sys, re, WildcardSearch, VisitFiles def GetArg( argName, ifAtEnd='' ): for i in range( 1, len( sys.argv ) ): if argName.upper() == sys.argv[i].upper(): if i+1 >= len( sys.argv ): return ifAtEnd else: return sys.argv[i+1] return None def PrintUsage(): print r'port_models.py -sr...
""" ---- Don't change this file ---- Here're all the standard env you can use! If you want to customize, please add your own in local_env_list.py file Just do: >>> import gym_sandbox >>> gym.make("xxx-v0") Note: Gym will defaultly use many wrappers to limit the env, like timestep_limit by TimeLimit """ from gym.envs...
import pandas as pd from .ModuleInterface import Module from .dash import BioequivalenceDashboard from .models import BioquivalenceMathsModel class BioequivalenceModule(Module, BioequivalenceDashboard): def _prepare_data(self): if self.settings['design'] == 'parallel': df_test = pd.read_exce...
from time import time from datetime import datetime, timedelta from django.conf import settings from django.contrib import auth class IdleTimeout(object): def process_request(self, request): if request.user.is_authenticated(): last_visit = request.session.get('last_visit') if last...
""" Parse the log files of MatchZoo to draw the learning curves of deep learning model training process to observe the training loss and metrics on train/dev/test data. With these curves, we can do a better job in model debugging @author: Liu Yang (yangliuyx@gmail.com / lyang@cs.umass.edu) @author: Thiziri Belkacem (be...
# Convert GB CEL to WS Tile import struct import argparse from . import __version__ def main(): print("cel2wst - {ver}".format(ver=__version__)) parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", required=True, type=str, help="Input file") parser.add_argument("-o", "--output", typ...
import atexit import aiohttp import json import logging import sys from urllib.parse import urlencode as _encode_query from .errors import HTTPException, HTTPUnauthorized, HTTPForbidden, HTTPNotFound from . import __version__ log = logging.getLogger(__name__) class HTTPClient: """Represents an HTTP client that c...
import csv with open("persons.csv", mode="w+") as db_file: # writer = csv.writer(db_file) writer = csv.DictWriter(db_file, fieldnames=["name", "age"]) writer.writeheader() # writer.writerow(["Victor", 10]) # writer.writerow(["Kiki", 20]) writer.writerow({ "name": "Victor", "age": 23 }) wri...
from django.urls.base import reverse_lazy from rest_framework import status from auth_app.urls import app_name from core.tests.utils import BaseCaller from core.utils import generate_email VERIFYCODE_CREATE_URL = reverse_lazy(f"{app_name}:verify-code-list") VERIFYCODE_CHECK_URL = reverse_lazy(f"{app_name}:verify-code...
import uuid from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.dialects.postgresql import ARRAY from api import app, db, bcrypt from api.models.user import User from api.models.recipe import Recipe class Rating(db.Model): __tablename__ = ...
# -*- coding: utf-8 -*- """Helpers for XML processing.""" from __future__ import annotations from .exceptions import MultipleMatchingXmlElementsError from .exceptions import NoMatchingXmlElementError if ( 6 < 9 ): # pragma: no cover # Eli (5/18/20): can't figure out a better way to stop zimports from deleting th...
from .user import UserCreate, UserUpdate, UserResponse from .auth import LoginInput, LoginOutput
from random import shuffle from time import sleep #suits = ['H','C','D','S'] # These are the text suits suits = [u'\u2665',u'\u2663',u'\u2666',u'\u2660'] # These are the unicode suits ranks = ['A',2,3,4,5,6,7,8,9,10,'J','Q','K'] # These are the card ranks used to build the deck # The function that deals the cards an...
import numpy as np from .surrogate_problem import SurrogateProblem from .utils import Timer, find_pareto_front, calc_hypervolume from .factory import init_from_config from .transformation import StandardTransform import gc import scipy, random ''' Main algorithm framework for Multi-Objective Bayesian Optimization ''' ...
""" Module for plotting analyses """ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from copy import deepcopy import pickle, json import os plt.ion() try: basestring except NameError: basestring = str colorList = [[0.42, 0.67, 0.84], [0.90, 0.76, 0.00], [0.42, 0.83, 0.59], [0....
import asyncio import json import random import uuid from funcx.sdk.asynchronous.funcx_future import FuncXFuture from funcx.sdk.asynchronous.ws_polling_task import WebSocketPollingTask from funcx.sdk.executor import AtomicController def _start(): pass def _stop(): pass def test_close_with_null_ws_state(m...
#coding=utf-8 import re from django import template from django.core.urlresolvers import reverse from django.shortcuts import render_to_response, get_object_or_404 from django.template.loader import render_to_string from proftpd.ftpadmin.lib.common import initlog from proftpd.ftpadmin.lib.view_common import ...
from .models import __all__ from .models import * def init_model(model_name, num_classes, feature_extract, use_pretrained=True): """ :param model_name: :type model_name: :param num_classes: :type num_classes: :param feature_extract: :type feature_extract: :param use_pretrained: :t...
# (c) 2017 Gregor Mitscha-Baude import numpy as np from nanopores.tools.polygons import Ball, Polygon, MultiPolygon, MultiPolygonPore from nanopores.geometries.cylpore import MultiPore from nanopores import user_params params = user_params( R = 100., R0 = 60., H0 = 70., H = 150., x0 = [0, 0, 46], ...
# -*- coding: utf-8 -*- """ Created on Fri Dec 29 09:35:12 2017 @author: User """ L = [[1,2], [35,4,78], [7,8,1,10],[2,3], [9,1,45]] def testA(L): for m in L: for ind, element in enumerate(m): if element == 1: m.pop(ind) return L print(testA(L))
''' @Author: your name @Date: 2020-04-15 17:01:43 @LastEditTime: 2020-04-15 17:01:43 @LastEditors: Please set LastEditors @Description: In User Settings Edit @FilePath: /DeepCTR/practice/ranking.py '''
#!/usr/bin/env/python2 # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from farnsworth.models import CBTesterJob, CBPollPerformance, ChallengeSet import meister.creators LOG = meister.creators.LOG.getChild('cb_tester') class CBTesterCreator(meister.creators.BaseCreator): MIN_TE...
import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Fonts adding') WHITE = (255, 255, 255) GREEN = (0, 255, 0) BLUE = (0, 0, 128) fontObj = pygame.font.Font('freesansbold.ttf', 32) textSurfaceObj = fontObj.render('Hello world!', T...
import sys import numpy as np def init_observations(f_name): dataset = [] f = open(f_name, 'r') num_obs = int(f.readline().strip()) for seq in range(num_obs): seq_len = int(f.readline().strip()) sequence = f.readline().strip().split(' ') dataset.append(sequence) f....
import os def login(username, password='123456'): if os.name == 'net': print(1) elif os.name == 'linux': print(2) else: print('macOS') return os.name def logout(): if os.name == 'net': print(1) elif os.name == 'linux': print(2) else: pri...
import logging import celery from admin.app import app, db from admin.models.articles import tag_to_article_text, Article from admin.models.articles_es import ArticleTextEs from admin.models.tag_rules_es import TagRuleEs logger = logging.getLogger(__name__) @celery.task(queue='clasterization') def apply_tags_task...
from .callbacks import Validation
from django.urls import path from django.conf.urls import url from . import views from rider.models import ride app_name = 'driver' urlpatterns = [ path('' , views.driverHome , name = "driverHome"), path('driverInfo' , views.driverInfo , name = "driverInfo"), path('driveProcess' ,views.searchRider , name = "searc...
# -*- coding: utf-8 -*- """Custom error handlers. Registers error handlers for the most common errors. """ from flask import flash, redirect, render_template, url_for from flask_babel import gettext as _ def render_error(errorcode, errormessage): """Renders the error handler template and explicitely sets th...
""" Executors Directory """
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from oauth2_provider.models import Application import json class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=mode...
# Resolve the problem!! import string import random SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~') def generate_password(): longitud = random.randint(8,16) password = [] def generate_list_caracter(longitud,password): bCaracter0 = False bCaracter1 = False bCaracter2 = False ...
#!/usr/bin/env pythion3 import socket RHOST = '127.0.0.1' RPORT = 4545 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((RHOST,RPORT)) while True: cmd = input("shell > ") s.send((cmd+"\n").encode()) recv_len = 1 response = b'' while recv_len: data = s.recv(100) ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0019_auto_20151103_1131'), ] operations = [ migrations.RemoveField( model_name='article', ...