text
stringlengths
38
1.54M
# Written by Dr Daniel Buscombe, Marda Science LLC # for the USGS Coastal Change Hazards Program # # MIT License # # Copyright (c) 2020, Marda Science LLC # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in...
from numba.core.extending import overload from numba.core import types from numba.misc.special import literally, literal_unroll from numba.core.errors import TypingError @overload(literally) def _ov_literally(obj): if isinstance(obj, (types.Literal, types.InitialValue)): return lambda obj: obj else: ...
import os from time import time class ProjectPath: base = os.path.dirname(os.path.dirname(__file__)) def __init__(self, logdir): self.logdir = logdir from time import localtime, strftime self.timestamp = strftime("%B_%d__%H_%M", localtime()) self.model_path = os.path.join(Pr...
#!/usr/bin/env python3 import os import os.path import subprocess import sys import pyparsing as pp MARK = "|@|" MARK_ARGS = ";;;@;;;" root = os.path.dirname(sys.argv[0]) ASM = os.path.join(root, "asm") SIM = os.path.join(root, "sim") errors = [0] def error(msg): print("error: %s" % msg) errors[0] += 1 ...
def csv(a): print "FILE NAME IS:::" print a b = [] f = open(a, 'r') for i in f.readlines(): b.append(i) print [i.split('!') for i in b] csv("eg.txt")
import asyncio import sys from apscheduler.schedulers.asyncio import AsyncIOScheduler from ntpan.config import params from ntpan.log import log from ntpan.main import collect if __name__ == "__main__": scheduler = AsyncIOScheduler() scheduler.add_job(collect, "interval", minutes=params.run_interval, id="ntpa...
class Cell: num = 0 def __init__(self, num): self.num = num def __add__(self, other): if (type(self) != type(other)): raise TypeError('Both arguments must be ceils') return Cell(self.num + other.num) def __sub__(self, other): if (type(self) != type(other))...
import glob import os import cv2 import argparse import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.model_selection import train_test_split from tqdm import tqdm from albumentations import (Compose, Flip, HorizontalFlip, Normalize, RandomBrightnessContrast, Rando...
from numpy import* p = array(eval(input("MASSA: "))) a = array(eval(input("alt: "))) n = size(p) b = zeros(n) i = 0 for x in p: b[i] = round((x/a[i]**2),2) i += 1 print(b) print("O MAIOR IMC DA TURMA EH",max(b)) if(max(b)<17): print("MUITO BAIXO DO PESO") elif(17<max(b)<=18.49): print("ABAIXO DO PESO") elif(18.5<=m...
#!/usr/bin/env python3 from networkx import DiGraph from os import getpid, getppid, execvpe, environ, fork, waitpid from os import open as os_open, pipe, dup2, close, set_inheritable from os import O_RDONLY, O_WRONLY from sys import argv noread = os_open('/dev/null', O_RDONLY) nowrite = os_open('/dev/null', O_WRONLY...
# ---------------------- homework_9 ------------------------ def snake_style_converter(phrase): """ Func. takes given string, removes all '_' between words and saves in 'phrase'. First 'for' cycle takes words from 'phrase', makes first letters capitals and saves in 'phrase_cap'. After it uses 'join' ...
"""Handle merging and spliting of DSI files.""" import numpy as np from nipype.interfaces import afni import os.path as op from nipype.interfaces.base import (BaseInterfaceInputSpec, TraitedSpec, File, SimpleInterface, InputMultiObject, traits) from nipype.utils.filemanip import fnam...
# coding: utf-8 import math from osv import fields,osv import tools import pooler from tools.translate import _ class res_partner_syndicate_ext(osv.osv): _inherit = 'res.partner' _columns = { 'syndicate': fields.boolean('Sindicato', help="Check this box if the partner is a syndicate."), } res_partner_syndicate_...
import boto3 import StringIO import json import re from nose.tools import assert_equals class TestNumberOfColumns: def __init__(self): self.lam = None def setup(self): self.lam = boto3.client('lambda') def json_file(self, line_delimiter='\n', field_delimiter='\t', target_file="out_file_...
""" :summary This is python 3.7 supported selenium 3.141.0 :since January 2020 :author Sathya Sai M :keyword Python, selenium basics conditionalcommands """ import time from selenium import webdriver class Conditional: def conditional(self): driver = webdriver.Chrome(executable_path="....
import numpy as np from collections import defaultdict from itertools import groupby def find_nth_vaporized(asteroids, position, n): """Return position of the nth asteroid to be vaporized.""" groups = group_by_angle(asteroids, position) deleted = 0 i = 0 while deleted < n - 1: if groups[i...
from flask import Flask, render_template, request, redirect, url_for import mysql.connector from mysql.connector import cursor connection = mysql.connector.connect( host="localhost", database="Company", user="root", password="Pass@123" ) app = Flask(__name__) @app.route("/home") def home(): con = connection.c...
import re from typing import Tuple from runrex.main import process from runrex.schema import validate_config from anaphylaxis_nlp.algo.epinephrine import get_epinephrine from anaphylaxis_nlp.algo.observation import get_observation from anaphylaxis_nlp.algo.primary_dx import get_anaphylaxis_dx from anaphylaxis_nlp.alg...
# Generated by Django 2.1.5 on 2020-07-08 18:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Brand', fields=[ ...
from bs4 import BeautifulSoup import glob import os from fpdf import FPDF fpath = "/projects/niblab/bids_projects/Experiments/BBx/fmriprep/ses-1/sub-*/fmriprep/sub*.html" htmls = glob.glob(fpath) svgpath = "/projects/niblab/bids_projects/Experiments/BBx/fmriprep/ses-1/sub-*/fmriprep/sub-*/figures/*rois.svg" pngpath ...
from django.contrib.auth.models import User from django.test import TestCase from ..models import Task, Preferences class TaskModelTests(TestCase): @classmethod def setUpTestData(cls): User.objects.create_user(username='tom', email='tom@dummy.com', password='asdf1234') def setUp(self)...
from collections import Counter class Pattern(object): def __init__(self, index, x, y, dx, dy): self.index = index self.pos_tuples = [] for xi in range(x,x+dx): for yi in range(y,y+dy): self.pos_tuples.append((xi,yi)) def all_pos_unique(self, pos_counter): ...
import logging import requests from bs4 import BeautifulSoup css_url = "https://chicagosocial.com/sports/indoor-volleyball/" def parse_css(content): schedules = [] league = "Chicago Sports and Social" soup = BeautifulSoup(content, "html.parser") rows = soup.select(".hide-on-mobile.league-row") fo...
from django.urls import path from .views import ( SearchProductView, fluid_search, ) urlpatterns = [ path('', SearchProductView.as_view(), name='query'), path('ajax-search/', fluid_search, name='fluid-search') # path('<slug>/', ProductDetailViewSlug.as_view(), name='details'), ]
""" Test to make sure specifying that modules have a shared mycontext """ import repyhelper import test_utils TESTFILE1 = "rhtest_mycontext_shared1.r2py" TESTFILE2 = "rhtest_mycontext_shared2.r2py" test_utils.cleanup_translations([TESTFILE1, TESTFILE2]) modname1 = repyhelper.translate(TESTFILE1, shared_mycontext=...
# have a help command # have a show command # Make a list to hold on Items shopping_list = [] def show_help(): # Print out instreuction print("What shoud we pick up from store? ") print(""" Enter 'DONE' to stop adding items. Enter 'HELP' for this help. Enter 'SHOW' to see your list """) ...
#coding: utf-8 """ @Author: Well @Date: 2013-01-26 """ #习题13:参数,解包,变量 from sys import argv # noinspection PyPep8,PyPep8,PyPep8 my_argv_script, my_argv_test1, my_argv_test2, my_argv_test3 = argv # noinspection PyPep8 print "script", my_argv_script # noinspection PyPep8 print "test1", my_argv_test1 # noinspection PyPep...
-X FMLP -Q 0 -L 1 71 300 -X FMLP -Q 0 -L 1 61 400 -X FMLP -Q 0 -L 1 49 150 -X FMLP -Q 1 -L 1 35 125 -X FMLP -Q 1 -L 1 34 175 -X FMLP -Q 1 -L 1 28 150 -X FMLP -Q 2 -L 1 23 100 -X FMLP -Q 2 -L 1 21 250 -X FMLP -Q 2 -L 1 13 125 -X FMLP -Q 3 -L 1 11 125 -X FMLP -Q 3 -L 1 10 100 -X FMLP -Q ...
# coding=utf-8 from __future__ import absolute_import, division, print_function import argparse import logging from . import vfp2py def parse_args(argv=None): parser = argparse.ArgumentParser(description='Tool for rewriting Foxpro code in Python') parser.add_argument("--logging", help="output logging informa...
from django.db import models import datetime from django.contrib.auth.models import User from django.db.models.fields import NullBooleanField from django.db.models.fields.related import OneToOneField from django.utils.tree import Node from jsonfield import JSONField from typing_extensions import runtime # Create your ...
import meinheld_zeromq as zmq import meinheld.server import greenlet ctx = zmq.Context() main_greenlet = greenlet.getcurrent() def sleep(secs): meinheld.schedule_call(secs, greenlet.getcurrent().switch) main_greenlet.switch() def pingpong(): sock = ctx.socket(zmq.REQ) sock.connect('tcp://127.0.0.1:10...
import argparse import csv import torch import transformers def parse_arguments(): parser = argparse.ArgumentParser(description="MiniConf Portal Command Line") parser.add_argument("papers", default=False, help="papers file to parse") return parser.parse_args() if __name__ == "__main__": args = par...
# Refaça o desafio 035 dos triangulos acrescentando o recurso de mostrar que tipo de triangulo será formado: # EQUILÁTERO: Todos os lados são iguais # ISÓSCELES: 2 lados iguais # ESCALENO: todos os lados são diferentes retaA = float(input("Digite o comprimento da primeira reta: ")) retaB = float(input("Digite o ...
import numpy as np class P_controller: def __init__(self, environment, AGENT_PARAMS, i): self.z_nom = AGENT_PARAMS["INIT_POSITION"] self.tank = environment.tanks[i] self.h_set = AGENT_PARAMS["SS_POSITION"] * environment.tanks[i].h self.k = self.tank.init_l / self.z_nom self...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-04-12 09:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cms_test2', '0006_auto_20180412_0942'), ] operatio...
from os import getenv, path, mkdir, sys, unlink, listdir, stat # workaround to allow flask to find modules CUR_DIR = path.dirname(path.abspath(__file__)) sys.path.append(path.dirname(CUR_DIR+"/")) from flask import Flask, Response, request, cli, g, send_file, send_from_directory from flask_cors import CORS import...
from django.db import models class Author(models.Model): name = models.CharField(max_length=200) class Book(models.Model): title = models.CharField(max_length=200) published = models.DateField() author = models.ForeignKey(Author, on_delete=models.CASCADE)
import multiprocessing import Tkinter as tk import cv2 e = multiprocessing.Event() p = None # -------begin capturing and saving video def startrecording(e): cap = cv2.VideoCapture(0) while(cap.isOpened()): if e.is_set(): cap.release() out.release() c...
#!/usr/bin/env python2.6 import logging import unittest if __name__ == '__main__': logging.basicConfig(level=logging.CRITICAL) # logging.basicConfig(level=logging.DEBUG) unittest.main()
#!/usr/bin/python3 import sys from importlib import import_module mod = import_module(sys.argv[1] + '.' + sys.argv[1]) run = getattr(mod,'run') run(True)
"""Rejestracja URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-b...
# pylint: disable=missing-docstring import doctest import re from unittest import TestCase import awking from awking import (LazyRecord, RangeGrouper, _ensure_predicate, _make_columns, records) class TestEnsurePredicate(TestCase): def test_string(self): predicate = _ensure_predicate('...
############################### # This file is part of PyLaDa. # # Copyright (C) 2013 National Renewable Energy Lab # # PyLaDa is a high throughput computational platform for Physics. It aims to make it easier to submit # large numbers of jobs on supercomputers. It provides a python interface to physical input, suc...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'getWays' function below. # # The function is expected to return a LONG_INTEGER. # The function accepts following parameters: # 1. INTEGER n # 2. LONG_INTEGER_ARRAY c: contain values of coins # def dyn_get_ways(n, coins): ...
import urllib.request rawdata = urllib.request.urlopen('http://www.google.cn/').read() import chardet print(chardet.detect(rawdata))
""" # 使用viewset代替 from rest_framework import generics from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Post from .serializers import PostSerializer @api_view(["GET"]) def post_list(request): queryset = Post.objects.filter(status=Post.STAT...
""" Aqui se implemento tomar 16 mediciones para tener un promedio del infrarrojo """ import serial import matplotlib.pyplot as plt import numpy as np import time def open_port(): ser = serial.Serial('COM8', 38400) return ser def close_port(port): port.close() def detect_data(port): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2014 Lukas Kemmer # # 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 require...
# -*- coding: utf-8 -*- """ Created on Fri Aug 31 10:18:52 2018 @author: Urchaug """ #python program to find the HCF of two input number #define a function def hcf(x,y): """this function takes two integers and returns the HCF""" # choose the smaller number if x>y: smal...
from django.shortcuts import render from django.views.generic import TemplateView, ListView from django.views.generic import CreateView, DetailView, DeleteView from django.urls import reverse_lazy from .forms import PhotoPostForm from django.utils.decorators import method_decorator from django.contrib.auth.decorators i...
import FWCore.ParameterSet.Config as cms import copy from DisappTrks.StandardAnalysis.Cuts import * # Put all the individual cuts in this file from DisappTrks.StandardAnalysis.EventSelections import * # Get the composite cut definitions from DisappTrks.StandardAnalysis.MuonTagProbeSelections import * # Get the compos...
import csv import math import matplotlib.pyplot as plt from bisect import bisect_left import networkx as nx # specification of the time discrtization step (time interval) dt = 30 def gen_bus_stop_nodes(G): with open('Bus_stops_coord.csv', 'r') as bsc: BusStopsReader = csv.DictReader(bsc) for row i...
import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam import opensim as osim import sys from rl.policy import BoltzmannQPolicy from rl.agents import SARSAAgent #from rl.random ...
import pandas as pd import scipy.stats as sci import seaborn as sns import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np import glob from decimal import Decimal import networkx as nx def makePPIandTransfacFile(): out_file = open('../rawData/PPIandTRANSFAC.txt','w+') print ...
import pandas as pd import numpy as np import unittest from dstools.preprocessing.OneHotEncoder import OneHotEncoder class TestOneHotEncoder(unittest.TestCase): def compare_DataFrame(self, df_transformed, df_transformed_correct): """ helper function to compare the values of the transformed DataFr...
from vumi.services.truteq.base import Publisher, Consumer, SessionType from vumi.services.worker import PubSubWorker from twisted.python import log from alexandria.client import Client from alexandria.sessions.backend import DBBackend from alexandria.sessions.manager import SessionManager from alexandria.sessions.db i...
def potencia(op1,op2): print("EL resultado de la potencia es: ",op1**op2) def redondear(numero): print("EL redonde el numero es: ",round(numero))
from sklearn.decomposition import PCA as sklearnPCA from sklearn.preprocessing import StandardScaler import pandas as pd import numpy as np import json def create_file_json(): url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" #assign colum names to the dataset names = ['sepal-leng...
import pygame from chess.constants import WIDTH, HEIGHT, CELL_SIZE, BLACK, button_font, RED from chess.board import Board from sys import exit import socket from threading import Thread from tkinter import * from pickle import loads, dumps pygame.init() client = None def click(): global client,...
from openpyxl import Workbook import os, sys import numpy as np import skbio.alignment, skbio.sequence from xhtml2pdf import pisa from .formatting import format_html, format_seq_line pisa.showLogging() def prep_excel(sequencing_dir, files, template_seq_name, excel_name='report.xlsx'): ''' Extract the sequence...
__author__ = 'pablo' data = [] with open('chalearn_full_db.csv', 'r') as f: lines = f.readlines() for l in lines: name, real, age, _ = l.split(',') data.append([name, age, '-1']) with open('fgnet.csv', 'r') as f: lines = f.readlines() for l in lines: age, ind, name, _ = l.split...
# Copyright 2022 The Cobalt 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 applicable ...
class Cell: """Contains all information and methods regarding the cells""" def __init__(self): """Sets up the initial variables""" self.cell_history = [[False, 0]] # The total history of the cell def is_alive(self): """Return whether the cell is alive or not""" return self....
#!/usr/bin/env python # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software...
# Generated by Django 3.0.5 on 2020-04-22 00:28 from django.db import migrations class Migration(migrations.Migration): dependencies = [("data", "0001_initial")] operations = [ migrations.RemoveField( model_name="organizationidentifier", name="organization" ), migrations...
def giveParts(number): string = str(number) a = (int(string[0:2]), number, int(string[2:4])) return a if __name__ == '__main__': triangle = [] square = [] pentagons = [] hexagons = [] heptagons = [] octagons = [] upper = 9999 lower = 999 n = 1 card = 6 halt ...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- radio = ({"radio": "Express FM", "stream": "http://stream4.nadaje.com:13324/express", "service": "NULL"}, {"radio": "Bielsko FM", "stream": "http://stream4.nadaje.com:13322/radiobielsko", "service": "NULL"}, {"radio": "Mega", "stream": "http://stream6.na...
# -*- coding: utf-8 -*- """Tests using pytest_resilient_circuits""" from __future__ import print_function import os import pytest from resilient_circuits.util import get_config_data, get_function_definition from resilient_circuits import SubmitTestFunction, FunctionResult from difflib import SequenceMatcher PACKAGE_N...
# Use of break statement inside the loop for val in "string": if val == "g": break print(val)
import re from typing import Set, Tuple TESTINPUT = """initial state: #..#.#..##......###...### ...## => # ..#.. => # .#... => # .#.#. => # .#.## => # .##.. => # .#### => # #.#.# => # #.### => # ##.#. => # ##.## => # ###.. => # ###.# => # ####. => #""" State = Set[int] Rule = Tuple[bool, bool, bool, bool, bool] Rule...
from tika import parser from os.path import isfile, join import glob import re files_no_ext = [".".join(f.split(".")[:-1]) for f in glob.glob("*.pdf") if isfile(f)] files_no_ext.sort() print(files_no_ext[0]) def scrap_file(t): file_name = t + '.pdf' path = './' + file_name raw = parser.from_file(path...
# region headers # * author: salaheddine.gassim@nutanix.com # * version: v1.0/10032020 - initial version # task_name: F5DeleteNode # description: Delete a single node # input vars: node_name # output vars: n/a # endregion # region capture Calm variables api_server = "@@{fortigate_endpoint}@@" f5_login = ...
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import math from torch.utils.data import TensorDataset, DataLoader import torch.utils.data as data from torchvision import transforms from torch.autograd import Variable from torch.nn import functional as F from torch import nn import torch from r...
import os import sys import json from copy import deepcopy import __main__ import textwrap from types import ModuleType from typing import TextIO, Dict, Any, Generator, List from herzog.parser import parse_cells, CellType, JUPYTER_SHELL_PFX, JUPYTER_MAGIC_PFX class Cell: def __init__(self, cell_type): self...
def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b for fib in fibonacci(): print(fib) if fib > 100: break
import threading import time def test1(): for i in range(5): print("--------test1-------%d--------" % i) time.sleep(1) def main(): print(threading.enumerate()) # 线程指定目标为一个函数比较方便 # 当目标比较复杂时,线程也可以直接指定为一个类,继承于threading.thread类 # 然后直接创建该类对象,然后可以调用父类的start方法,然后自动先调用该类的run方法 # 注意一定是run方法,其...
import sys for _ in [0]*int(sys.stdin.readline().strip()): v=4*float(sys.stdin.readline().strip()) a=pow(v,0.3333333333333333) x=a*a*1.7320508075688772 print("%.10f"%((x/2)+(3*a*(v/x))))
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import xlwt import base64 from io import StringIO from odoo import api, fields, models, _ import platform class PurchaseReportOut(models.Model): _name = 'expense.report.out' _description = 'expense order report...
#!/usr/bin/python # -*-coding:Utf-8 -* ########################################################## """ Exceptions for the SOLIDServer modules """ __all__ = ["SDSError", "SDSInitError", "SDSServiceError", "SDSRequestError"] class SDSError(Exception): """ generic class for any excep...
from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings from django.views.decorators.csrf import csrf_exempt from blog.views import AboutView, handler404, handler500 from write_blog.views import image_upload urlpatterns = [ ...
#!/usr/bin/python import httplib import sys import threading import time import urlparse import urllib from collections import OrderedDict from os import _exit,system def connect(host,port,verb,path,query,data=None,headers={}): path = path +'?'+ urllib.urlencode(query) h = httplib.HTTPConnection(host,int(port)) h...
#!/usr/bin/env python import jinja2 import mimetypes import numpy as np import os import smtplib import sys import getpass import email import email.utils from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase if len(sys.argv) < 3: print('Usage: ./...
def countUnvisited(n, m): i = 0 x = (m * n) - m - n queue = [] queue.append(x) set = {x} count = 0 while (len(queue) > 0): curr = queue[0] queue.remove(queue[0]) count += 1 key = curr - m if (key > 0 and key not in set): queue.append(key) ...
from player import Player from playerprovider import PlayerProvider class BettingGame: """A base class for other games to inherit from. This handles collecting/paying out bets and running rounds. Base functionality: collectBet -- handles the interaction with a player to collect their bets. payB...
from selenium.webdriver.common.by import By class Purchase_page: country = (By.ID, "country") checkbox = (By.CSS_SELECTOR, "label[for='checkbox2']") confirm_button = (By.CSS_SELECTOR, "input[class*='btn-success']") success_message = (By.CSS_SELECTOR, "div[class *='alert-success']") def __init__(s...
import logging from datetime import date, timedelta from urllib import parse import scrapy logging.basicConfig(filename='eska.log', level=logging.DEBUG) def initialize_start_urls(): BASE_URL = 'http://www.eskarock.pl/archiwum_playlist/' ONE_DAY = timedelta(days=1) start_date = date(2010, 9, 1) END_...
import unittest def remove_duplicates(s: str) -> str: if len(s) < 2: return s result = [] for i in s: if i not in result: result.append(i) return "".join(result) class TestCase(unittest.TestCase): def test_case1(self): self.assertEqual(remove_duplicates("abcd...
from itertools import islice from io import open from conllu import parse_incr import pandas as pd import numpy as np from collections import Counter import string import math #for deep copy import copy #for commandline input import sys #for precision and recall from sklearn.metrics import precision_score from sk...
import sys def visit(matrix, marked, i, j, marked_by, count): #print('visiting '+str((i, j))+' count:'+str(count)) if marked[i][j][0] is True: return count else: marked[i][j] = (True, marked_by) count += 1 for x in [i-1, i, i+1]: for y in [j-1, j, j+1]: ...
#!/home/despoB/mb3152/anaconda2/bin/python import brain_graphs import pandas as pd import matlab import matlab.engine import os import sys import time import numpy as np import subprocess import pickle import h5py import random import time import scipy from scipy.io import loadmat import scipy.io as sio from scipy.stat...
### Test for secrets.py # Should return length of secret token from functions import getSecret def test_secrets(): access_token = getSecret('twitter-rob') assert (len(access_token))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ###################################################### ## Sending control commands to AP via MAVLink ## ## Based on set_attitude_target.py: https://github.com/dronekit/dronekit-python/blob/master/examples/set_attitude_target/set_attitude_target.py #################...
import os from datetime import datetime from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.authentication import TokenAuthentication from rest_framework.parsers import FileUploadParser, JSONParser from rest_framework.permissions import IsAuthenticated from rest_fram...
#!/usr/bin/env python import socket with socket.socket(socket.AF_INET , socket.SOCK_STREAM) as s: host = "time.nist.gov" port = 13 s.connect ((host , port)) s.sendall(b'') time=str(s.recv (4096) , 'utf -8') print(time)
sum = 0 for i in xrange(1, 101): sum += i print sum lst = xrange(1, 101) def add(x, y): return x + y print reduce(add, lst) print reduce((lambda x, y: x + y), xrange(1, 101))
import numpy as np import math import matplotlib.pyplot as plt class Bayesian_Model_Face: def __init__(self): self.training_classes = [ [{'#':0, ' ':0} for i in range(60)] for i in range(70)] self.training_labels = [] self.testing_classes = [ ...
-X FMLP -Q 0 -L 3 89 300 -X FMLP -Q 0 -L 3 79 300 -X FMLP -Q 0 -L 3 69 300 -X FMLP -Q 0 -L 3 61 200 -X FMLP -Q 1 -L 2 46 175 -X FMLP -Q 1 -L 2 42 150 -X FMLP -Q 1 -L 2 41 125 -X FMLP -Q 1 -L 2 38 125 -X FMLP -Q 2 -L 1 36 400 -X FMLP -Q 2 -L 1 24 150 -X FMLP -Q 2 -L 1 24 125 -X FMLP -Q ...
#Purpose: manipulate data for plotting of Pressure vs Dilitation from Tkinter import Tk from tkFileDialog import askopenfilename Tk().withdraw() ############################################################################### filename = askopenfilename() print "Working with file:", filename scale = input('What modul...
from flask import Flask from flask import request from flask import make_response from werkzeug import secure_filename from flask import url_for from flask import render_template from flask import send_from_directory import os app = Flask(__name__) app.config['UPLOAD_FOLDER'] = '/Users/qylk/' app.secret_key = '123456'...
# -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 3. # See the file http://www.gnu.org/licenses/gpl.txt from pisi.actionsapi import pythonmodules from pisi.actionsapi import pisitools from pisi.actionsapi import get from pisi.actionsapi import shelltools WorkDir="setuptools-%s" % get....