text
stringlengths
8
6.05M
from django.urls import path, include from acc import views ############################api############################# #from rest_framework.urlpatterns import format_suffix_patterns ############################################################# from rest_framework import routers ##################################...
# Generated by Django 3.0.3 on 2020-08-06 12:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Agents', fields=[ ...
import requests as rq import time from random import shuffle with open('auth_token', 'r') as f: auth_token = f.read().strip() API_ENDPOINT = 'https://api.spotify.com/v1/' HEADERS = { 'Accept': 'application/json', 'Authorization': 'Bearer ' + auth_token } POPULARITY_THRESHOLD = 50 def get_playlists(q): ...
class Control: angle_min = 0 angle_max = 180 def __setStep(self): return self.__min + (self.__max - self.__min) * 0.7 def __init__(self, pw_min=1500, pw_max=1500): """ New control element Args: pw_min: pulse width in microseconds, corresponding to the mini...
from __future__ import annotations from typing import List, Optional from .package import Package class Label(object): """ Representation of a package and/or target, following bazel's Labels [1]. Not a full or even accurate re-implementation of bazel's Labels. Examples:: // //apps/...
import FWCore.ParameterSet.Config as cms source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_100_1_u9l.root', '/store/user/skaplan/noreplica/MinBiasBeamSpotPhi225R8_HISTATS/outfile14TeVSKIM_101_1_91u.root', '/store/...
# -*- coding: utf-8 -*- """Tests for the similarity measure. MIT License Copyright (c) 2021-2022, Daniel Nagel All rights reserved. """ import os.path import numpy as np import pytest from beartype.roar import BeartypeException import mosaic # Current directory HERE = os.path.dirname(__file__) TEST_FILE_DIR = os.p...
""" Lazy evaluation常被译为“延迟计算”或“惰性计算”,指的是仅仅在真正需要执行的时候才计算表达式的值。 充分利用Lazy evaluation的特性带来的好处主要体现在以下两个方面: 1)避免不必要的计算,带来性能上的提升。对于Python中的条件表达式if x and y, 在x为false的情况下y表达式的值将不再计算。而对于if x or y, 当x的值为true的时候将直接返回,不再计算y的值。因此编程中应该充分利用该特性。 """ """ 2)节省空间,使得无限循环的数据结构成为可能。Python中最典型的使用延迟计算的例子就是生成器表达式了,它仅在每次需要计算的时候才通过yield产生所需要的元素...
#Komputer ma za zadanie zgadnąć liczbę import random #Welcome and intruct print("HELLO!!! \nPlease think about some number in range from 1 to 100. Computer will try to guess the number") print("Give a clues to computer if guess number is higher or lower than your\n\n") # Function which takes tries counter ...
import itertools import datetime import calendar def find_december_monday(currentYear): month = 12 dates = [] for year in range(currentYear, 2008, -1): day = 1 if calendar.weekday(year, month, day) == calendar.MONDAY: day += 7 dates.append(str(year) + '/' + str...
""" Unlike ReqMgr1 defining Request and RequestSchema classes, define just 1 class. Derived from Python dict and implementing necessary conversion and validation extra methods possibly needed. TODO/NOTE: 'inputMode' should be removed by now (2013-07) since arguments validation #4705, arguments which are later...
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='pyrunjs', version='1.0.3', description='Python PyV8 JS wrapper', author='Sergey V. Sokolov', author_email='sergey.sokolov@air-bit.eu', url='https://github.com/sokolovs/pyrunjs', packages=find_packages(exclude=['e...
# -*- encoding: utf-8 -*- import netsvc import pooler, tools import math from tools.translate import _ from osv import fields, osv import wizard import decimal_precision as dp import time class conai_cod(osv.osv): _name = "conai.cod" _description = "Codici CONAI" _columns = { 'name':fields...
import matplotlib.pyplot as plt import numpy as np import math import scipy from scipy import stats filename = 'airbnb_msoa' def my_hist(data, n): plt.hist(data, n) plt.show() def my_plot(data): plt.plot(data) plt.show() msoa_cd_nm_map = {} with open('all_msoas', 'r') as infile: for line in infile: if len(l...
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtGui import * import shutil import os class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(437, 387) MainWindow.setFixedSize(MainWindow.size()...
def leap(year): if ((year % 100) %4 == 0): return 1 if((year % 1000) - ((year % 100) % 4 == 0) and (year % 100)==0): return 1 return 0 #print(leap(2019)) def MDYToNumDay(date): #-> int month= date[0] day = date[1] year = date[2] monthDays = [31,28+leap(year),31,30...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ˅ from tkinter import * from behavioral_patterns.mediator.colleague import Colleague # ˄ class ColleagueTextField(Colleague): # ˅ # ˄ def __init__(self, text_field): self.__text_field = text_field # ˅ super().__init__() s...
#!/usr/bin/env python import os import json import argparse import sys import termtables from .property_reader import PropertyReader from .generator import Generator from .renderer import Renderer def list_projects(config): print("Available generators:") rows = [] for gen, props in config.items(): ...
import numba import numpy as np # import must stay here even if it's not used directly! import pycuda.autoinit import pycuda.driver as cuda from pycuda.compiler import SourceModule import pycuda.gpuarray as gpuarray import nufft_cims import nufft_ref import time import pyfftw import multiprocessing import skcuda impor...
from typing import Optional, List from orun.db import models from orun.utils.translation import gettext_lazy as _ class MailServer(models.Model): name = models.CharField(128, null=False, unique=True) active = models.BooleanField(default=True, label=_('Active')) sequence = models.IntegerField() smtp_ho...
# # Some plotting routes to show off the learning agent for the "driverless car" using Tensorflow # # @scottpenberthy # November 1, 2016 # import tensorflow as tf import numpy as np from learning import * import matplotlib import matplotlib.mlab as mlab import matplotlib.cm as cm import matplotlib.pyplot as plt import...
from __future__ import (absolute_import, division, print_function, unicode_literals) import datetime # For datetime objects import os.path # To manage paths import sys # To find out the script name (in argv[0]) # Import the backtrader platform import backtrader as bt from custom_indicators ...
from agents import ExpectiMaxAgent from game import * import numpy as np GAME_SIZE = 4 SCORE_TO_WIN = 2048 eposide = 4000 game_train = Game(size=GAME_SIZE, score_to_win=SCORE_TO_WIN) agent = ExpectiMaxAgent(game_train) txt_dir = "./dataset2/data0.txt" index = 0 file = open(txt_dir, mode='w') for ep in rang...
l1 = [1, 2, 2, 2, 3, 3, 4, 56, 61, 78] l2 = [] for i in l1: if i not in l2: l2.append(i) print(l2)
import torch from torchvision.datasets import Omniglot import albumentations as albu from albumentations.core.transforms_interface import DualTransform from albumentations.augmentations import functional as F from albumentations.pytorch.transforms import ToTensorV2 import cv2 import numpy as np class RandomResize(Dua...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import os import logging import lmdb import msgpack from ..util import time_uuid from ..runtime import environ from .errors import DataNotFoundError, DataError from .service import IStore, ICursor _DATA_FILE_DIR = b'dat...
# -*- coding: utf-8 -*- """ Created on Wed Jun 28 14:38:04 2017 @author: Martin """ from textblob import TextBlob wiki = TextBlob("I like to eat pizza") wiki.tags
import ipfsapi import asyncio import aiohttp import logging from nulsexplorer.modules.register import register_tx_type, register_tx_processor LOGGER = logging.getLogger('ipfs_module') async def add_file(fileobject, filename): async with aiohttp.ClientSession() as session: from nulsexplorer.web import app...
import sys for linea in sys.stdin: n = int(linea) if n == 0: print('error') else: ini = 4 res = 2 for j in range(n-1): print(ini, end=' ') ini = (ini*3) - res res = res+2 print(ini, end='') print()
# Python imports # Tornado imports import tornado.auth import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options from tornado.web import url # Sqlalchemy imports from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session,...
from django.urls import path from .views import allblogs, detailed_blog urlpatterns = [ path('', allblogs, name='allblogs'), path('<int:blog_id>/', detailed_blog, name='detailed_blog'), ]
sum = 0 for i in range(0,100): sum+=(i+1); print(sum) # print(sum(range(1,101)))
import telepot import datetime as datetime from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time def EnviaTextoTe...
import praw from pprint import pprint import config from sqlconfig import cursor,cnx,add_submission,retrieve_submissions,update_submission,delete_submissions,purge_table import string import hashlib import time punctuation = string.punctuation.replace(">","").replace("=","").replace("!","").replace("/","") #A list of...
from django.shortcuts import render from citizen_reporting_webapp.settings import MAPBOX_API_KEY # Create your views here. def index(request): context = {'mapbox_access_token': MAPBOX_API_KEY } return render(request, 'dashboard/index.html', context) def login(request): return redirect("authenticate:login"...
i=input("Enter the Num") if i.isalpha(): if i in("a","e","i","o","u",): print "Vowels" else: print "Consonant" else: print "Invalid"
from ..DGFit_Models import DGFit_MRN def test_mrn_initialize(): dgmod = DGFit_MRN() assert dgmod.type == 'MRN'
""" BINARY TREE Definitions: 1. Full: every node has 0 or 2 children. 2. Complete: Every level filled except last which is left. 3. Perfect: All internal nodes have 2 children. 4. Balanced: Height is O(log(n)). 5. Degenerate: Each node has one child. """ class Node: def ...
from rv.modules import Behavior as B from rv.modules import Module from rv.modules.base.filter import BaseFilter class Filter(BaseFilter, Module): behaviors = {B.receives_audio, B.sends_audio}
from twitter.common.threading.periodic_thread import PeriodicThread from twitter.common.threading.stoppable_thread import StoppableThread __all__ = [ 'PeriodicThread', 'StoppableThread' ]
import pandas as pd class MarketOnClosePortfolio(object): def __init__(self, symbol, bars, initial_capital, strategy, n_shares=100): self.symbol = symbol self.initial_capital = initial_capital self.n_shares = n_shares self.strategy = strategy self.bars = bars self.ma...
## Convert celsius temp to fahrenheit def celsius_to_fahrenheit(value): if value is None: return 0 else: return (value * (9/5)) + 32
import matplotlib.pyplot as plt import networkx as nx class GraphPlot: def __init__(self, G=None, scale=[1,10,1,10], node_size = 500, node_color = [0.2,0.2,0.2], edge_color = [0,0,1], font_size = 16, ...
"""Contains files for handling allStar APOGEE files and converting them into numpy arrays of observed spectra""" import apogee.tools.read as apread import apogee.tools.path as apogee_path from apogee.tools import bitmask from apogee.spec import continuum import numpy as np filtered_bits = [bitmask.apogee_pixmask_int(...
my_list = [] my_list = [x*y for x in [20, 40, 60] for y in [2, 4, 6]] print(my_list)
from game.items.item import Pickaxe from game.skills import SkillTypes class SacredClayPickaxe(Pickaxe): name = 'Sacred Clay Pickaxe' value = 21333 skill_requirement = {SkillTypes.mining: 40} equip_requirement = {SkillTypes.attack: 1} damage = 24 accuracy = 110 weight = 2
import warnings import ansible import ansible.constants import ansible.utils import ansible.errors from ansible.runner import Runner from pytest_ansible.module_dispatcher import BaseModuleDispatcher from pytest_ansible.errors import AnsibleConnectionFailure from pytest_ansible.results import AdHocResult from pytest_an...
import logging import pandas from aiogram.types import ContentType from config import API_TOKEN from aiogram import Bot, Dispatcher, executor, types from config import DST_CHAT_ID, SRC_CHAT_ID, TRIGGER_WORDS logging.basicConfig(level=logging.INFO) bot = Bot(token=API_TOKEN) dp = Dispatcher(bot) @dp.message_handl...
import InsiderTrading as IT from datetime import date, timedelta import yfinance as yf stock_name = "MSFT" stock = yf.Ticker(stock_name) print(float(stock.info["previousClose"])) print(str(date.today()-timedelta(1))) print(IT.insider_trading())
#Programa: act11.py #Propósito: Suponiendo que hemos introducido una cadena por teclado que representa una frase (palabras separadas por espacios), realiza un programa que cuente cuantas palabras tiene. #Autor: Jose Manuel Serrano Palomo. #Fecha: 29/10/2019 # # Análisis: # Introduce el usuario una frase # comprobamos c...
""" Sorts importance files output by RandomForest_v2.0 and related SciKit-learn ML scripts and allows for other selection. Required input: -f : path to file or path to directory with multiple imp.txt files Other options: -n : Gives top n most important features -p : Gives top percent p most important features ...
# Write a function that implements a substitution cipher. In a substitution cipher one letter is substituted for another to garble the message. # For example A -> Q, B -> T, C -> G etc. your function should take two parameters, the message you want to encrypt, # and a string that represents the mapping of the 26 lett...
from time import time import json import Common.Emulation as emu import Common.base64encoder as b64 import Common.secrets as sec if sec.Raspberry: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) class Device: def __init__( self, client, clockInterval=1, *, emulation=Fal...
import sqlite3 from flask import g, Flask, jsonify from datetime import datetime import logging from gpiozero import OutputDevice, DigitalInputDevice DATABASE = 'database.db' POOL = 0 SPA = 1 MIN = 0 LOW = 1 HIGH = 2 MAX = 3 PIN_STOP = 5 PIN_STEP1 = 6 PIN_STEP2 = 12 PIN_HEATER = 13 PIN_IN_VALVE = 19 PIN_OUT_VALVE = 1...
import views import unittest from mock import patch class TestMidterm(unittest.TestCase): def setUp(self): self.app = views.app.test_client() self.response = self.app.get('/') def test_get_index_page(self): self.assertEquals('200 OK', self.response.status) def test_title_Midterm_Project(self): ...
############################################################################################################### # Configure Logging: WORKSPACE = "workspace/" ############################################################################################################### # Dynamic pybot variables: # Specifies an 3D-arra...
from django.contrib.auth.hashers import check_password, make_password from django.contrib.auth import logout from django.shortcuts import redirect from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework import viewsets from rest_framewo...
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ # Uses the pre-generated table of primes. See ../prime_gen.py from os.path import abspath, dirname, join PRIME_FILE = abspath(join(dirname(__file__), '..', 'data', 'primes.txt...
# Generated by Django 2.2.5 on 2020-04-25 17:03 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('listings', '0008_auto_20200425_2143'), ] operations = [ migrations.AlterField( model_name='mobi...
import socket import sys import threading import time import csv import os import secrets import pandas as pd import numpy as np import pickle import math import random from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.model_selection import train_tes...
from collections import OrderedDict class BaseModel(object): _properties = None _serializable = None def __init__(self, obj=None): if obj is None: obj = {} if isinstance(obj, BaseModel): properties = obj.serialize() else: properties = obj self._properties = {} self._seria...
""" Creación del tipo especifico del sensor de temperatura """ from agentes_sensores.proxy_sensor_temperatura import * class FactoryProxySensorTemperatura: @staticmethod def crear(tipo: str) -> AbsProxySensorTemperatura: if tipo == "archivo": return ProxySensorTemperaturaArchivo() elif tipo...
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
class Truck: def __init__(self, brand, photo_file_name, carrying, body_whl): self.brand = brand self.photo_file_name = photo_file_name self.carrying = carrying self.body_whl = body_whl try: raw_body_whl = body_whl.split('x') body_length = float(raw_...
import os import numpy if __name__ == '__main__': loadPath = 'D:/PythonProjects_Data/CMU_MOSEI/Step1_StartEndCut/' labelCounter = {1: 0, 0: 0} for fileName in os.listdir(loadPath): data = numpy.reshape(numpy.genfromtxt(fname=os.path.join(loadPath, fileName), dtype=float, delimiter=','), ...
from matrix_utils import getReflection def getPlotData(resultMatrix, superResultMatrix): r = getReflection(resultMatrix) T = 1 / (superResultMatrix[0][0]) print(T) R = superResultMatrix[1][0]/superResultMatrix[0][0] return [r, T, R]
#!/usr/bin/env python from aiokafka import ConsumerRecord import logging from sqlalchemy.engine import RowProxy from typing import ( Dict, List, Optional, ) import ujson from hummingbot.logger import HummingbotLogger from hummingbot.connector.exchange.loopring.loopring_order_book_message import LoopringOr...
import sys import math sys.path.insert(0, '/home/machen/face_expr') from dataset_toolkit.compress_utils import get_zip_ROI_AU import os from collections import defaultdict from config import DATA_PATH,ROOT_PATH from functools import lru_cache import copy import numpy as np import math from PIL import Image...
#!/usr/bin/env python """ _ApMonLite_ Lighter more API friendly way to send data to ApMon """ __all__ = []
def minSubarray(self, nums: List[int], p: int) -> int: n = len(nums) mod = sum(nums)%p if mod==0: return 0 res = n s = 0 hashmap = {0: -1} for i, num in enumerate(nums): s += num key = (s%p - mod) ...
import load sample = '8 0 0 2 0 0 0 4 6 0 0 7 9 0 0 0 0 0 1 0 0 0 0 0 5 0 0 0 0 0 5 0 0 0 3 2 4 0 8 0 0 0 7 0 1 3 2 0 0 0 7 0 0 0 0 0 6 0 0 0 0 0 9 0 0 0 0 0 3 2 0 0 2 8 0 0 0 6 0 0 3' puz = load.Constructor(sample) puzzle = puz.convert_to_puzzle() print(puzzle.total_possibilities_left) puzzle.pretty_print() puzz...
""" Contains upgrade tasks that are executed when the application is being upgraded on the server. See :class:`onegov.core.upgrade.upgrade_task`. """ from sqlalchemy import Column from onegov.core.orm.types import UTCDateTime from onegov.core.upgrade import upgrade_task from sqlalchemy.sql.expression import text fr...
from django import forms from advertising.models import AdvertisingCampaign, AdvertisingType from cities.models import Region from django.core.files.images import get_image_dimensions from djmoney.forms.fields import MoneyField from moneyed import Money, CAD from decimal import Decimal from accounts.widgets import Ch...
height = 165 weight = 168 body_ratio = weight/height print(body_ratio)
import json if __name__ == "__main__": with open('testforms/old_infra.json', encoding='utf-8') as f: forms = json.load(f) for idx, form in enumerate(forms): with open('old_infras/' + str(idx) + '.json', 'w+', encoding='utf-8') as f: f.write(json.dumps(form, ensure_ascii=False,...
class Triangulo: def __init__(self, a, b, c): self.lado_a = a self.lado_b = b self.lado_c = c def calcular_perimetro(self): return self.lado_a + self.lado_b + self.lado_c def maior_lado(self): if self.lado_a > self.lado_b and self.lado_a > self.lado_c: r...
from abc import ABCMeta class Sized(metaclass=ABCMeta): @classmethod def __subclasshook__(cls, C): if cls is Sized: if any("__len__" in B.__dict__ for B in C.__mro__): return True # else: # return False return NotImplemented class A(Sized...
from rest_framework import routers from kratos.apps.log.views import LogViewSet router = routers.DefaultRouter(trailing_slash=False) router.register('log', LogViewSet, basename='log') urlpatterns = router.urls
import numpy as np import cv2 def find_keypoints(img_list): sift = cv2.xfeatures2d.SIFT_create() keypoints = [] descriptors = [] img_keypoints = [] for img in img_list: cur_keypoints, cur_descriptors = sift.detectAndCompute(img, None) keypoints.append(cur_keypoints) ...
# question https://www.hackerrank.com/challenges/py-hello-world/problem # solution if __name__ == '__main__': print("Hello, World!")
import random from abc import ABC, abstractmethod from Event import Event, EventPayload class AbstractObject(ABC): def __init__(self, fixture=None, position=None): self._fixture = fixture self._position = position @property def fixture(self): return self._fixture ...
#-*- coding:utf8 -*- import time import datetime import json import urllib2 import cgi from lxml import etree from StringIO import StringIO from celery.task import task from celery.task.sets import subtask from celery import Task from django.db.models import Q from .models import WeixinUserAward from .service impo...
import os import sys from functools import partial import click from flask import current_app from flask.cli import ( AppGroup, routes_command, ScriptInfo, with_appcontext, pass_script_info) from flask_migrate.cli import db as db_command import opsy from opsy.flask_extensions import db from opsy.app import create_...
print('n>> TRIANGULO') primeiroLado = float(input('Comprimento do lado 01: ')) segundoLado = float(input('Comprimento do lado 02: ')) terceiroLado = float(input('Comprimento do lado 03: ')) if primeiroLado + segundoLado > terceiroLado and segundoLado + terceiroLado > primeiroLado and terceiroLado + primeiroLado > seg...
from graph_utils import * class Graph: def __init__(self): self.nodes: dict[int:Node] = {} self.edges: List[Edge] = [] def add_node(self, node: Node) -> None: self.nodes.update({node.id: node}) def connect(self, node1: int, node2: int) -> None: if node1 not in self.nodes...
# -*- coding: utf-8 -*- """ Created on Thu Jul 12 15:15:10 2018 @author: ragoh """ import unittest from Computer import * class test_isWin(unittest.TestCase): #test empty board def test_emptyBoard(self): self.assertFalse(Player.isWin(Player([0, 0, 0, 0, 0, 0, 0, 0, 0]))[0]) #test board of one ele...
#!/usr/bin/env python # coding=utf-8 ''' Author: John Email: johnjim0816@gmail.com Date: 2020-10-07 20:57:11 LastEditor: John LastEditTime: 2021-04-28 10:13:21 Discription: Environment: ''' import matplotlib.pyplot as plt import seaborn as sns def plot_rewards(rewards,ma_rewards,tag="train",env='CartPole-v0',algo = "...
from practicas.tiempo import Tiempo t1 = Tiempo(10, 20, 30) # Establecemos los valores de Tiempo # Sumamos y restamos Horas print(f"T1: {t1}") h = int(input(f"Horas a sumar a {t1}")) t1.suma_horas(h) print(f"Ahora T1 es {t1}") h = int(input(f"Horas a restar a {t1}")) t1.resta_horas(h) print(f"Ahora T1 es {t1}") # S...
#!/usr/bin/env python from os.path import join, realpath import sys import pandas as pd from typing import List import unittest from hummingsim.backtest.backtest_market import BacktestMarket from hummingsim.backtest.market import ( AssetType, Market, MarketConfig, QuantizationParams ) from hummingsim.b...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2016/3/1 10:22 import bisect # the complexity of the this algorithm is O(n^2) def length_of_lis(nums): length_list = [1] * len(nums) for i in range(1, len(nums)): for j in ra...
#!/usr/bin/env python3 #learning pygame from programarcadegames.com #pong game ''' sounds from: http://opengameart.org/content/3-ping-pong-sounds-8-bit-style The first code a Pygame program needs to do is load and initialize the Pygame library. Every program that uses Pygame should start with these lines: ''' # Imp...
from stream import Stream from generator import Generator from car import Car
import os import sys REDMINE_HOME = '/opt/redmine-3.1.1-0' REDMINE_HOME = '/opt/redmine-3.4.3-1' REDMINE_HOME = '/opt/redmine-4.0.2-1' def redmine_redcase(): os.system('wget https://bitbucket.org/bugzinga/redcase/downloads/redcase-1.0.zip') os.system('unzip redcase-1.0.zip') os.system('mv redcase '+REDMIN...
#!/usr/bin/env python import matplotlib as mpl def rundark(): mpl.rc('lines', linewidth=1, color='w') mpl.rc('patch', edgecolor='w') mpl.rc('text', color='w') mpl.rc('font', size=9, family='sans-serif') mpl.rc('axes', facecolor='k', edgecolor='w', labelcolor='w',\ color_cycle=[ 'w','r'...
from datetime import datetime import getpass import requests import json from lxml import etree import os import re import sys import uuid if sys.version_info[:2] <= (2, 7): # Python 2 get_input = raw_input import ConfigParser as configparser else: # Python 3 get_input = input import configpars...
from flask import Flask, request from flask_restful import Resource, Api, reqparse from flask_jwt import JWT, jwt_required from security import authenticate, identity #När vi använder flask_restful behöver vi inte använda jsonify. Det fixat flask_restful åt oss. app = Flask(__name__) app.secret_key = 'rasmus' api = A...
import conexao_banco as sql def todos(): stmt = 'select "id_clientes","CPF_CNPJ", "email", "telefone","nome_razaosocial" from "Usuarios" inner join "Clientes" on "Usuarios"."id_usuario" = "Clientes"."id_usuario" order by "id_clientes"' result = sql.query(stmt) return(result) def busca(idcliente): stm...
a=int(input("Enter the number")) l=["one","two","three","four","five","six","seven","eight","nine","ten"] if 0<a<=10: print(l[a-1]) else: print("enter between 1 to 10")
#! /usr/bin/env python # title : EKF_filter.py # description : This module reads /vo, /odom, /imu and uses the extended kalman # filtering for the fusion. # author : Salah Eddine Ghamri # date : 17-03-2018 # version : 0.5 # usage : in Roslaunch file...
def largestDivisibleSubset(nums): """ :type nums: List[int] :rtype: List[int] """ nums = sorted(nums) dp = [0]*len(nums) for i in range(len(nums)): for j in range(i, -1, -1): if (nums[i]%nums[j]==0): dp[i] = max(dp[i], dp[j]+1) maxIndex = 0 f...