text
stringlengths
8
6.05M
# -*- coding: utf-8 -*- """ Created on Wed May 15 16:35:41 2019 @author: Administrator """ import numpy as np from scipy import signal import matplotlib.pyplot as plt import rcos import gold import wave import struct SIG_FREQ = 500 SAMPLE_FREQ = 4000 # PN_CODE = np.array([1,1,1,1,1,-1,-1,1,1,-1,1,-1,1]) # PN_CODE ...
#encoding: utf-8 import circulo import random import sys import subprocess def circuloRandom(): #Devuelve una lista [x1,y1,r,data] x1 = random.randint(1,399) y1 = random.randint(1,399) rmax = min(400-x1,400-y1) if (400-x1) > (400-y1) : r = random.randint(1,rmax) else: r = random.randint(1,rmax) data = str(x...
from requests import get, post import os from dotenv import load_dotenv load_dotenv() import pandas as pd # Module variables to connect to moodle api KEY = os.getenv("MOODLE_API_KEY") URL = os.getenv("URL") ENDPOINT="/webservice/rest/server.php" def rest_api_parameters(in_args, prefix='', out_dict=None): """Trans...
# coding=utf-8 import unittest import warnings from mock import patch, Mock from . import interface_factory from . import api_details from paypal.exceptions import PayPalAPIResponseError, PayPalConfigError from paypal.interface import PayPalInterface from paypal.response import PayPalResponse interface = interface_...
# Copyright 2017 The Forseti Security Authors. 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 # # Unless required by ap...
def convert(s, numRows): n = len(s) dic = dict() incr = 0 flag = 1 for i in range(n): if incr not in dic.keys(): dic[incr] = '' dic[incr] += s[i] incr += flag if incr == 0 or incr == numRows-1: flag *= -1 ans = '' for value in dic.value...
# # carkov markov chain library # © Copyright 2021 by Aldercone Studio <aldercone@gmail.com> # This is free software, see the included LICENSE for terms and conditions. # """ Various filter functions that may be useful for processing certain kinds of corpora. """ from typing import Optional # from unidecode import u...
import codecademylib3_seaborn import numpy as np from matplotlib import pyplot as plt from sklearn import datasets from sklearn.cluster import KMeans digits = datasets.load_digits() #print(digits.target[100]) plt.gray() plt.matshow(digits.images[100]) plt.show() model = KMeans(n_clusters = 10, random_state = 43) model...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua a = 'hello word' b = a.replace('word','python') print(b)
listRange=list(range(4)) # 0 to 3 print(listRange) listRange1=list(range(-6,7,2)) # -6 to +6 by 2 print(listRange1) list1=[[x**2,x**3] for x in range(4)] print(list1) list2=[[x, x / 2, x * 2] for x in range (-6,7,2)if x > 0] print(list2)
# Problem name: Coin Piles # Description: You have two coin piles containing a and b coins. # On each move, you can either remove one coin from the left pile and two coins from the right pile, or two coins from the left pile and one coin from the right pile. # Your task is to efficiently find out if you can empty bo...
import cv2 import numpy as np import sys import os ASCII_CHARS = ['.',',',':',';','+','*','?','%','S','#','@'] ASCII_CHARS = ASCII_CHARS[::-1] def asciify(frame): frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame = frame // 25 frame = frame.tolist() text = [[ASCII_CHARS[px] for px in line[::10]] f...
from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.utils import timezone def dateStartValidator(value): dateStartValidator.lastValue = value def dateEndValidator(value): if dateStartValidator.lastValue > value: raise ValidationE...
# Generated by Django 2.2.2 on 2019-09-06 15:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations = [ migrations.AddField( model_name='comment', name='is_anonymity', ...
import modules as m #from modules import Add print(m.Add.__doc__) print(m.Add(2,5))
# http://www.practicepython.org/exercise/2014/03/26/08-rock-paper-scissors.html from random import randint puntj = puntia = 0 print ("Al primero que gane tres!") while True: while puntj<3 and puntia<3: jugador = "inicial" while (jugador != "piedra" and jugador != "papel" and jugador != "tijeras" a...
from time import sleep from serial import Serial import sys sys.path.append('/home/pi/tracer/python') from tracer import Tracer, TracerSerial, QueryCommand port = Serial('/dev/ttyAMA0', 9600, timeout = 1) port.flushInput() port.flushOutput() tracer = Tracer(0x16) t_ser = TracerSerial(tracer, port) query = QueryComman...
class Solution: def threeSum(self, nums): res = [] nums.sort() for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue # two sum j = i + 1 k = len(nums) - 1 while j < k: if nums[i] +...
import numpy as np def calculate(list): if len(list) == 9: calculations = dict() np_list = np.array(list) matrix = np.reshape(np_list, (3, 3)) calculations['mean'] = (np.mean(matrix, axis=0), np.mean(matrix, axis=1), np.mean(matrix)) calculations['variance'] = (np.var(matrix...
"""Test tailrecursion.py.""" from tailrecursion import Recursion from tailrecursion import tail_recursive @tail_recursive def fib(seq_num: int, _i: int = 0, _j: int = 1) -> int: """Return the nth Fibonacci number.""" if seq_num == 0: return _i else: raise Recursion(seq_num - 1, _i=_j, _j=(...
import streamlit as st import pandas as pd import matplotlib.pyplot as plt import seaborn as sb def load_clean_data(): data = pd.read_csv('kc_house_data.csv') data.date = pd.to_datetime(data.date, infer_datetime_format=True) return data data = load_clean_data() def show_EDA_page(): st.title('EDA of...
import numpy as np import matplotlib.pyplot as plt def getrsr(x1, x2, x3): return (0.4 * x1 + 0.4 * x2 + 0.2 * x3) / 30.0 plt.rcParams['font.family'] = 'SimHei' plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False lables = np.array(['查找算法', '排序算法', '树结构', '数字操作', '数组', '图结构', ...
# Generated by Django 3.0.3 on 2020-03-18 21:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dimensoes', '0005_dimensaomodel_data'), ] operations = [ migrations.AlterField( model_name='dimensaomodel', name='pr...
""" Example conversion of ical to csv """ from csv_ical import Convert convert = Convert() convert.CSV_FILE_LOCATION = 'examples/BostonCruiseTerminalSchedule.csv' convert.SAVE_LOCATION = 'examples/arrive.ics' convert.read_ical(convert.SAVE_LOCATION) convert.make_csv() convert.save_csv(convert.CSV_FILE_LOCATION)
#Google BooksでAPIを叩く import requests as req ISBN = input() response = req.get( 'https://www.googleapis.com/books/v1/volumes', params={ "q": "isbn=" + str(ISBN) }) BookInfo = dict(response.json()).get("items")[0]["volumeInfo"] BookTitle = BookInfo["title"] BookAuthor = BookInfo["authors"...
n1 = int(input('Digite o primeiro número inteiro: ')) n2 = int(input('Digite o segundo número inteiro: ')) if n1 > n2: print('O primeiro valor é maior do que o segundo') elif n2 > n1: print('O segundo valor é maior do que o primeiro') else: print('Não há valor maior, os dois são iguais')
import csv reader = csv.reader(file) writer = csv.writer(file) writer.writerow(data) # write one line writer.writerows(data) # write multi line # Dictionary reader = csv.DictReader(file) writer = csv.DictWriter(file) writer.writeheader() # file header writer.writerow(data) # write one line writer.writerows(d...
import pygame from GameParameter import display def drawing_text(text, x, y, font_color=pygame.Color('black'), font_size=30): font_type = pygame.font.Font('lost.ttf', font_size) text = font_type.render(text, True, font_color) display.blit(text, (x, y))
import asyncio import os import logging from colorlog import ColoredFormatter from tonga.stores.persistency.shelve import ShelvePersistency, StoreKeyNotFound from tonga.stores.persistency.memory import MemoryPersistency from tonga.stores.persistency.rocksdb import RocksDBPersistency def setup_logger(): """Retur...
n=input() list1=[int(x) for x in raw_input().split(" ")] list2=[] for i in list1: list2.append([i]) Count=0
""" script to create hepevt files (as input for JUNO detsim) containing IBD signals. IBD signal: - positron with initial momentum between 10 MeV and 100 MeV - neutron with initial momentum corresponding to the positron energy format of hepevt file (momentum and mass in GeV): number particles in e...
import turtle #turtle.shape('turtle') #square=turtle.clone() #square.shape('square') #square.goto(100,100) #square.goto(300,300) #square.stamp() #square.goto(100,100) #turtle.mainloop() UP_ARROW='Up' LEFT_ARROW='Left' DOWN_ARROW='Down' RIGHT_ARROW='Right' SPACEBAR='space' UP=0 DOWN=1 LEFT=2 RIGHT=3 direction=UP d...
import argparse import re import glob import os import numpy as np import matplotlib.pyplot as plt import sys args = dict() data = dict() origDir = os.getcwd() #plt.style.use('ggplot') ## plt.style.use('grayscale') ## plt.style.use('fivethirtyeight') #print plt.style.available numAccesses = re.compile('Total Access...
# created by Ryan Spies # 2/19/2015 # Python 2.7 # Description: parse through a summary file of usgs site info obtained from website # and split out individual cardfiles for each site. Also creates a summary csv file # with calculated valid data points and percent of total. Used to display in arcmap import os import ...
#!/usr/bin/python import subprocess import sys import time #import StringIO import os import io from PIL import Image # Original code written by brainflakes and modified to exit # image scanning for loop as soon as the sensitivity value is exceeded. # this can speed taking of larger photo if motion detected early in...
from unittest.case import TestCase from exercicios_basicos.ex_01_calculadora_soma import efetua_soma class TestSoma(TestCase): def test_soma_esta_correta(self): self.assertEqual(0, efetua_soma()) def test_soma_esta_correta_quando_tem_negativos(self): self.assertEqual(10, efetua_soma(-1, 1, ...
test_cases = int(input()) case_list = [] for case in range(test_cases): booking_list = {1:{}} booking_num = int(input()) for booking in range(booking_num): start , end , cost = input().split() start ,end ,cost = int(start) ,int(end),int(cost) try : booking_list[start][en...
from rest_framework import serializers from .models import ExerciseAndReporting,\ SwimStats,\ BikeStats,\ Steps,\ Sleep,\ Food,\ Alcohol,\ Grades,\ UserQuickLook class ExerciseAndReportingSerializer(serializers.ModelSerializer): user_ql= serializers.PrimaryKeyRelatedField(read...
##encoding=utf-8 """ Import Command -------------- from archives.htmlparser import htmlparser """ from bs4 import BeautifulSoup as BS4 import re class HTMLParser(): def get_total_number_of_records(self, html): """get how many results returns """ s = re.findall(r"(?<=>Showing 1-10 of )...
"""Modules used in the README example""" from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LinearRegression import numpy as np from flexp import flexp class LoadData: """Load queries and targets from a tsv file""" ...
import struct class Packer(object): def __init__(self, buf): self._buffer = buf self._offset = 0 self._typemethods = {'b': self.pack_int8, 'B': self.pack_uint8, 'h': self.pack_int16, 'H': self.pack_uint16, 'i': self.pack_int32, 'I':...
from molecularfunctionsOOP import particleClass from molecularPhysicalQuantities import PlotPQs import numpy as np from JosPlotPy import AnimatedScatter import molecularPhysicalQuantities as PQ #matplotlib.pyplot.close("all") #closing all the figures #set global constants Np=108 deltat=.004 mass = 1 dens = .85 temp =...
from bs4 import BeautifulSoup import requests import os import spotipy import spotipy.util as util import datetime '''Scrapes hotnewhiphop top 100 songs then creates and returns list of songs by artists I enjoy parameters: fav_artists - artists I want songs from ''' def getTopSongs(fav_artists): artists = [] ...
#! /usr/bin/env python """ dumps crops from a databag to disk.dumps USING: Author: Martin Humphreys """ import cv2 from argparse import ArgumentParser from math import floor, ceil import os import uuid from DataBag import DataBag from Query import Query import numpy as np def build_parser(): par...
import cv2 as cv import numpy as np def detect(image): classifier = cv.CascadeClassifier() classifier.load(cv.samples.findFile('./data/haarcascade_frontalface.xml')) faces = classifier.detectMultiScale(image) heights = [face[-1] for face in faces] f = [0,0,0,0] if(heights): m = max(heig...
def recurPower(base, exp): if exp == 1: return base elif exp > 0 and exp % 2 == 0: return recurPower(base ** 2, exp / 2) elif exp > 0 and exp % 2 != 0: return recurPower(base, exp - 1) * base print recurPower(2, 3)
import logging import sys import warnings import os import six from tqdm import tqdm log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') def loglevel_from_string(level): """ >>> _loglevel_from_string('debug') 10 >>> _loglevel_from_string(logging.INFO) 20 ...
from app import app from flask import render_template, request, redirect, jsonify, make_response from datetime import datetime import os from werkzeug.utils import secure_filename from flask import send_file, send_from_directory, safe_join, abort, session, url_for from flask import flash @app.templa...
# -*- coding: utf-8 -*- import os import numpy as np import glob import shutil import matplotlib.pyplot as plt # %matplotlib inline import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D from tensorflow.keras.preprocessi...
""" MAP@K word level and character level are explained in detail in this paper: dpUGC: Learn Differentially Private Representationfor User Generated Contents Xuan-Son Vu, Son N. Tran, Lili Jiang In: Proceedings of the 20th International Conference on Computational Linguistics and Intelligent Text Processing, April, 2...
class Visit: # ENROLLHD visit #def __init__(self, seq, age, days, vtype, tfc, motor, function, cognitive, pbas): # self.seq = seq # visit sequence nr # self.age = age # Age at time of visit # self.days = days # Days since Baseline visit # sel...
num1=int(input("Enter a number")) num2=int(input("Enter the divisor")) def is_div(num1,num2): if num1%num2 ==0: return True return False print(is_div(num1,num2))
#************************************ (C) COPYRIGHT 2019 ANO ***********************************# import sensor, image, time, math, struct import json from pyb import LED,Timer from struct import pack, unpack import Message,LineFollowing,DotFollowing,ColorRecognition,QRcode,Photography #初始化镜头 sensor.reset() sen...
from itertools import combinations input = list(map(int, open('data/09.txt').read().split('\n'))) for i, num in enumerate(input): if i >= 25 and num not in list(map(lambda x: x[0]+x[1], list(combinations(input[i-25:i], 2)))): print(num)
song="JINGLE Bells jingle Bells Jingle All The Way" song.upper() song_words=song.split() count=0 print(song_words) for word in song_words: if(word.startswith("jingle")): count=count+1 print(count) name = "pavan"
#Iterative Approach class Solution: def reverseList(self, head: ListNode) -> ListNode: if not head: return current = head nxt = head.next prev = None while nxt: current.next = prev prev = current current = nxt nxt = ...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class Cython(Package): url = "http://cern.ch/service-spi/external/MCGenerators/distribution/cython/cython-0.22-src.tgz" version('0.22', 'f7653aaae762593e13a...
"""Construct aggregate text blob from multiple manuals.""" import os def build_aggregate(lower_bound, upper_bound, start_time, time_elapsed): """Construct aggregate text blob from multiple manuals.""" year_list = ['/Users/alextruesdale/Documents/moodys_code/WIP/text_dictionaries/text_output/industrials19{}.t...
#!/usr/bin/env python class Header(object): """DNS message header class that has header properties.""" __message_id = 1 __flags = 1 __question_count = 0 __answer_count = 0 __authority_count = 0 __additional_count= 0 @property def message_id(self): """Message id property ...
# Generated by Django 3.1.3 on 2021-05-23 15:39 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
from rest_service.config import Config from rest_service.service import RestService import unittest import time import os import requests BASIC_CONFIG = ''' [rest-service] host = '0.0.0.0' port = 9448 use_ssl = false cert_pem = '/path/rest/server.pem' key_pem = '/path/rest/server.key' use_jwt =...
from flask import jsonify , request def product_delete(collection_name,name): productlist = collection_name try : query = productlist.delete_one({'name':name}) output = {'Status code': 200 ,'Message': 'Product successfully deleted'} return jsonify({'result':output}) except :...
# https://github.com/Rapptz/discord.py/blob/async/examples/reply.py import discord import requests #allows for the api import xml.etree.cElementTree as ET from discord.ext.commands import Bot from discord.ext.commands import MemberConverter from TOKEN import TOKEN #gets the token from token.py from TOKEN import BUNGIE...
# -*- coding: utf-8 -*- """ Created on Tue Jun 9 16:43:49 2020 @author: logun """ import matplotlib.pyplot as plt import cv2 img = cv2.imread('binary_small.png', cv2.IMREAD_GRAYSCALE) plt.figure(dpi=700) dims = img.shape M_0_0 = 0 M_1_0 = 0 M_0_1 = 0 for row in range (dims[0]): for col in range (dims[1]): ...
import dash_bootstrap_components as dbc from dash import Dash, html def test_mdcap001_components_as_props(dash_duo): app = Dash(__name__) app.layout = html.Div( [ dbc.Checklist( [ {"label": html.H2("H2 label"), "value": "h2"}, { ...
# change gui font size in linux: xrandr --output HDMI-0 --dpi 55 # https://further-reading.net/2018/08/quick-tutorial-pyqt-5-browser/ from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWebEngineWidgets import * from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout, QLab...
# class 2 # 7/19/16 # Playing with conditionals input_value = input("Enter a number: ") x = int(input_value) if x == 2: print('Your number is equal to 2') elif x > 100: print('Your number is greater than 100') elif x % 5 == 0: print('Your number is a multiple of five and less than 100') else: print('Your number i...
# from re import compile, search # # VALID = compile('\([0-9]{3}\) [0-9]{3}-[0-9]{4}') # # # def validPhoneNumber(number): # """ valid_phone_number == PEP8, forced camelCase by CodeWars """ # check = search(VALID, number) # return number == check.group(0) if check else False from re import compile, match ...
#!/usr/bin/env python3 import yaml from aws_cdk import core from three_tier_web.three_tier_web_stack import ThreeTierWebStack # Demonstrates how to externalize configurations on your stack config = yaml.load(open('./config.yaml'), Loader=yaml.FullLoader) app = core.App() # Create a different stack depending on the ...
{ 'targets': [ { 'target_name': 'NodeCoreAudio', 'sources': [ 'NodeCoreAudio/AudioEngine.cpp', 'NodeCoreAudio/NodeCoreAudio.cpp', ], 'include_dirs': [ '<(module_root_dir)/NodeCoreAudio/', '<(module_root_dir)/portaudio/' ], "conditions" : [ [ 'OS!="win"', { "libraries"...
from outbreaksim import Simulation import numpy as np import matplotlib.pyplot as plt # Monte Carlo Simulation with varying percentage of the population being stationary def main(): svals = [0.00, 0.25, 0.5, 0.75, 1] numRuns = 10000 # Simulation Options options = { 'N': 100, # Grid Siz...
""" MongoDB/AWS DocumentDB登録のための観測所マスター情報 """ from __future__ import annotations import copy import dataclasses import inspect import urllib.parse from datetime import datetime, timezone from logging import Logger, getLogger, NullHandler from pathlib import Path from typing import Optional, Any, Sequence, Mapping, Mut...
from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import json import numpy as np import pandas as pd import scipy.sparse as sparse import data_utils as data import datasets import upper_bounds import defenses...
import tweepy import json import pymongo print("hello_tweepy.py Loaded") from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client.twit_ids if db == None: print ('kaaskoek') # sirColgrevance auth = tweepy.OAuthHandler("npb4vI5OhwkXyxY8ixvZ2qAHx","SR10qi0e2nLcl4a2cXDZ8ZNeM3M...
# from selenium import webdriver # import time # from selenium.webdriver.remote.webelement import WebElement # from selenium.common.exceptions import StaleElementReferenceException # # def wait(driver): # elem = driver.find_element_by_tag_name("html") # count = 0 # while True: # count += 1 # ...
import re a = input() pattern = re.compile(r'[^\w+]') s = re.sub(pattern, '', a).lower() if s == s[::-1]: print("Палиндром") else: print("Не палиндром")
# https://wikidocs.net/1015 s1 = set([1, 2, 3]) print(s1) s2 = set('Hello') print(s2) s3 = set() print(s3) l1 = list(s1) print(l1) s1 = set([1, 2, 3, 4, 5, 6]) s2 = set([4, 5, 6, 7, 8, 9]) print(s1 & s2) print(s1.intersection(s2)) print(s1 | s2) print(s1.union(s2)) print(s1 - s2) print(s1.difference(s2)) print(s1) ...
from .src.graph_pb2 import GraphDef from .src.node_def_pb2 import NodeDef from .src.versions_pb2 import VersionDef from .src.attr_value_pb2 import AttrValue from .src.tensor_shape_pb2 import TensorShapeProto from .src import types_pb2 as dt from collections import defaultdict import numpy as np import chainer.variable ...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.core.util_rules.external_tool import TemplatedExternalTool class GrpcPythonPlugin(TemplatedExternalTool): options_scope = "grpc-python-plugin" help = "The gRPC Protobu...
# Generated by Django 2.1.3 on 2019-02-08 18:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogapp', '0002_com'), ] operations = [ migrations.CreateModel( name='tegory', fields=[ ('id', model...
from selenium import webdriver import pytest from selenium.webdriver.common.by import By @pytest.yield_fixture() def driver(): _driver = webdriver.Chrome() yield _driver _driver.quit() def login(driver, username, password): driver.get("http://localhost/litecart/admin/") driver.find_element_by_na...
import re import string import pandas as pd data = pd.read_excel('sampledata.xlsx') data.columns = ['Text'] print(data.head()) print(data.shape) ''' Clean data ''' from eunjeon import Mecab from konlpy.tag import Okt def preprocword(text): def clean_text(text): text = text.replace(".",...
#!/usr/bin/env python3 import rospy import numpy as np from sensor_msgs.msg import Image,CameraInfo from cv_bridge import CvBridge, CvBridgeError import tf from std_msgs.msg import String,Int64MultiArray from geometry_msgs.msg import * from vision_msgs.msg import Detection2DArray def same_object(labels,Object): c...
''' @Description: @Date: 2020-05-06 23:47:09 @Author: Wong Symbol @LastEditors: Wong Symbol @LastEditTime: 2020-05-29 20:24:23 ''' ''' 区间交集问题 问题描述:快速找出两组区间的交集 ''' def intervalIntersection(A, B): i,j = 0,0 # 指针 res = [] # 保存结果 while i < len(A) and j < len(B): a1,a2 = A[i][0],A[i][1] b1,b2 = B[j][0],B[j][1] ...
# auth : wdt0818@naver.com, bluehdh0926@gmail.com # import os class PathSearcher(): def __init__(self): self.setPath(os.environ['HOMEDRIVE'] + os.environ['HOMEPATH'] + "\AppData\Local\Packages") self.is_find = False self.findPath = "" self.debug = False def setPath(self, path...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ################################################################################################# # # # extract_gyro_data.py: find gyro drift ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # According to: # http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: ret...
from django.test import TestCase from . import models class AdsTestCase(TestCase): def test_ads(self): for i in range(20): o = models.Ad( title="Puppy #{}".format(i + 1), description="lovely puppy, brown and happy", posted_by="Udi", ...
import collections def chain_map(): a = {'a': 'a', 'c': 'c', 'num': 0} b = {'b': 'b', 'c': 'cc'} c = {'b': 'bbb', 'c': 'ccc'} print(a) a.update(b) print(a) a.update(c) print(a) print('---- chain map ----') m = collections.ChainMap(a, b, c) print(m) print('--- m.maps -...
#Variables matriz = [] #Funciones def mat(n): for i in range (n): matriz.append([]) for j in range (n): matriz[i].append(0) return matriz def llenar(n): matriz = mat(n) for x in range (n): for y in range (n): matriz[x][y] = float(input('Valor de [' + str...
from db_patient import Patient import sendgrid import os import datetime from sendgrid.helpers.mail import * def existing_beats(patient_id): """ checks whether there are existing heart beats for a patient :param patient_id: integer ID of patient to check if there is beat data :return: True if patient...
from django.conf.urls import url from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token from api import views urlpatterns = [ url(r'^auth/token/?$', obtain_jwt_token, name="obtain-token"), url(r'^auth/token-verify/?$', verify_jwt_token, name="verify-token"), url(r'^cate...
import uuid import adal from settings import settings from office365.directory.group_profile import GroupProfile from office365.graph_client import GraphClient def acquire_token(): authority_url = 'https://login.microsoftonline.com/{0}'.format(settings['tenant']) auth_ctx = adal.AuthenticationContext(author...
import graphene from ingredients.serializers import IngredientSerializers, CategorySerializers class CategoryInput(graphene.InputObjectType): name = graphene.String() class IngredientInput(graphene.InputObjectType): id = graphene.ID() name = graphene.String() category = graphene.ObjectType
# coding=utf8 from lib.models_others import CorpModel from lib.corp import Corp import re, urllib.parse, json, time class ZJRCCorp(Corp): def __init__(self): config = { 'info_from': '浙江人才网', 'corplist_url': 'http://www.zjrc.com/Services/Jobs/GetSearch.ashx', ...
#!/usr/bin/env python #------------------------------------------------------------------------------ # Copyright 2008-2011 Istituto Nazionale di Fisica Nucleare (INFN) # # Licensed under the EUPL, Version 1.1 only (the "Licence"). # You may not use this work except in compliance with the Licence. # You may obtain a co...
__author__ = "Christian Kongsgaard" __license__ = "MIT" __version__ = "0.0.1" # -------------------------------------------------------------------------------------------------------------------- # # Imports # Module imports import cmf from datetime import datetime from datetime import timedelta import numpy as np i...
from kivy.app import App from kivy.factory import Factory from kivy.uix.filechooser import FileChooser from kivy.utils import * from kivy.uix.boxlayout import BoxLayout from kivy.uix.actionbar import * from kivy.uix.popup import Popup from kivy.uix.button import ButtonBehavior from kivy.uix.image import Image from kiv...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.terraform.goals.tailor import PutativeTerraformTargetsRequest from pants.backend.terraform.goals.tailor import rules as terraform_tailor_rules from pants.backend.terrafo...
# Generated by Django 3.1.5 on 2021-01-30 20:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reporter', '0002_auto_20210130_2017'), ] operations = [ migrations.AlterField( model_name='gpxfile', name='gpx_file'...