content
stringlengths
5
1.05M
#!/usr/bin/env python """remove_all_layers_workspace_geoserver.py: removes all layers in a workspace and (TODO) removes the linked metadata in the catalogue""" import argparse import requests from sys import exit from util.geoserver_client import * from util.csw_client import * from lxml import etree, objectify import ...
import argparse import os import numpy as np import cv2 from skimage.feature import local_binary_pattern from tqdm import tqdm # This script will be used to generate a set of lbps at different scale for each trainning and validation stereo pairs def update_filenames (train_file, dataset_foldername): with open(tra...
from collections import defaultdict import torch import numpy as np class MessageAggregator(torch.nn.Module): """ Abstract class for the message aggregator module, which given a batch of node ids and corresponding messages, aggregates messages with the same node id. """ def __init__(self, device): super...
from googletrans import Translator def translate(text, dest): translator = Translator() return (translator.translate(text, dest=dest))
""" Copyright Ouwen Huang 2019 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 d...
"""This submodule contains the path_parse() function used to convert SVG path element d-strings into svgpathtools Path objects. Note: This file was taken (nearly) as is from the svg.path module (v 2.0).""" # External dependencies from __future__ import division, absolute_import, print_function import re import numpy a...
from datetime import datetime from unittest import IsolatedAsyncioTestCase from unittest.mock import MagicMock, patch from bot.bot import on_message from test.mocks import MockAuthor, MockChannel, MockMessage, AsyncMock class TestBot(IsolatedAsyncioTestCase): @classmethod def setUpClass(self) -> None: ...
import ckan.logic.schema from routes.mapper import SubMapper from ckan.lib.plugins import DefaultTranslation, DefaultOrganizationForm from ckan.plugins import ( implements, IConfigurer, IGroupForm, IRoutes, SingletonPlugin, IActions, IConfigurable, IDatasetForm, IValidators, ITranslation, IPackageController) fr...
#!/usr/bin/python import csv import numpy as np import pandas as pd import random DEVTESTSIZE = 2000 trainData = [] devData = [] testData = [] inFile = "finalTrainData.csv" iTrainFile = open(inFile, "r") readerTrain = csv.reader(iTrainFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) outTrainFile = "model...
class Connections(object): pass CONNECTIONS = Connections()
#Program to find out that whether a given input integer No. is Prime or Not a=int(input()) #Here we are taking the input No. from the user t=0 #Initializing "t" as 0 for further use. for i in range(1,a+1): #Constructed a loop for checking a No. from 1 to the position of the No. itself to find out that whether the No...
from pyzbar.pyzbar import decode from PIL import Image a=decode(Image.open('soosai.png')) print(a)
import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import model_from_json from tensorflow.keras.optimizers import Adam import numpy as np import time import ...
# IMPORTS import time import numpy as np import torch from torch import nn from flair.embeddings import ( Sentence, RoBERTaEmbeddings, BertEmbeddings, XLNetEmbeddings, OpenAIGPT2Embeddings, ) from sklearn.model_selection import train_test_split from sklearn.metrics import precision_recall_fscore_sup...
"""Show augmented samples from training runs by slicing the saved training samples. """ import os from os.path import join import yaml from glob import glob from pathlib import Path import torch import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pylab as plt from PIL import Image mpl.rcPa...
from PyQt5.QtCore import QDir, Qt, QUrl, QSettings from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer from PyQt5.QtMultimediaWidgets import QVideoWidget from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel, QMessageBox, QCheckBox, QPushButton, QSizePolicy, QSl...
#Maximum sub array # Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. # https://leetcode.com/problems/maximum-subarray/ def maxSubArray( nums): global_max = nums[0] current_max = nums[0] local_start = 0 start = 0 ...
from streamer import Stream from streamer.operator import RepeatApply from streamer.collector import Collector from .util import identity def test_basic(): s1 = Stream(range(10)) \ .concat(range(20)) \ .exclude(lambda x: x % 4) \ .map(lambda x: x - 1) \ .collect(lis...
#!/usr/bin/env python3 import matplotlib import matplotlib.pyplot as plt from collections import defaultdict import numpy as np lengths = defaultdict(list) lib_count = defaultdict(int) lib="good" lengths[lib].append(20) lengths[lib].append(30) lengths[lib].append(100) lengths[lib].append(330) lengths[lib].append(10...
import json from sklearn.feature_extraction import DictVectorizer from sklearn import preprocessing import numpy as np from lasagne import layers from lasagne import init import lasagne from lasagne.updates import sgd,nesterov_momentum from nolearn.lasagne import NeuralNet import theano import sys import process_bl...
import os from plottr import QtGui, QtCore, plottrPath gfxPath = os.path.join(plottrPath, 'resource', 'gfx') # The pyqt versions shipped by anaconda (both main channel and conda forge) # are not able to render svg icons if the QIcon is created before the # main qapp is up and running. To work around this we wrapp all...
import gray_code import os def write_gray_code_1d(n=7, m=7, filename='gray_lookup_1d.txt'): """write a 1-D Gray code to disk in a Max/MSP-friendly way""" string = 'table ' code = gray_code.single_1d_gray_code(n=n, m=m, do_print=True) for value in code.values(): string += '%i ' % value if ...
import serial # import pySerial module def getweight(self): try: ComPort = serial.Serial('COM3') # open the COM Port ComPort.baudrate = 2400 # set Baud rate ComPort.bytesize = 8 # Number of data bits = 8 ComPort.parity = 'N' # No parity ComPort.sto...
import numpy as np import linearRegCostFunction as lrcf import scipy.optimize as opt def train_linear_reg(X, y, lmd): initial_theta = np.ones(X.shape[1]) res = opt.minimize(lrcf.linear_reg_cost_function, initial_theta, args=(X, y, lmd), method='TNC', jac=lrcf.linear_reg_grad_function) ...
#!/usr/bin/env python3 import numpy as np werte = np.loadtxt("reaktionzeit.dat",dtype=np.float64) mw = np.mean(werte) sa = np.sqrt((np.sum((werte - mw)**2))/(werte.size - 1)) print("Mittelwert:\t\t", mw) print("Standardabweichung\t", sa)
import requests import threading import unittest import rocket3 def demo_app(environ, start_response): start_response(200, "Hello World") class SimpleTest(unittest.TestCase): def start_server(self): rocket = rocket3.Rocket3(("127.0.0.1", 8007), "wsgi", ...
from setuptools import setup, find_packages setup(name = 'spiro', version = '1.0b2', packages = find_packages(), scripts = ['bin/spiro'], install_requires = ['picamera==1.13', 'RPi.GPIO==0.6.5', 'Flask==1.1.1', 'waitress==1.4.3', 'numpy==1.18.1'], author = 'Jonas Ohlsson', author_ema...
n = int(raw_input()) a=[] for i in range(n): temp = [int(x) for x in raw_input().split()] a.append(temp) visited=[] s,d = map(int,raw_input().split()) def dfs(row,val): print row,d temp=row[d] if temp==1: return val for i in row: if i==1 and i not in visited: dfs(i,...
from typing import Optional import gym import numpy as np import rdkit from nfp.preprocessing.mol_preprocessor import MolPreprocessor from rdkit.Chem.QED import qed from rlmolecule.graph_gym.graph_problem import GraphProblem from rlmolecule.molecule.builder.builder import MoleculeBuilder from rlmolecule.molecule.mole...
# Copyright 2015 kornicameister@gmail.com # Copyright 2016-2017 FUJITSU LIMITED # # 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 ...
#!/usr/bin/env python3 # -*- config: utf-8 -*- from tkinter import * def enter_leave(event): if str(event.type) == 'Enter': event.widget['text'] = 'In' elif str(event.type) == 'Leave': event.widget['text'] = 'Out' root = Tk() lab1 = Label(width=20, height=3, bg='white') lab1.pack() lab1.bi...
class Node: def __init__(self,data=None,next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insert_at_begining(self,data): #inserting_at_begining of the linked list node = Node(data,self.head) self.head = node ...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: command.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobu...
## Filters.py # ------------------------- # # Description: # A collection of functions which implement functions # required by different filtering strategies. # ------------------------- # # Created by: Ashiv Dhondea, RRSG, UCT. # Date created: 23 June 2016 # Edits: # 7 July 2016: added functions for Gauss-New...
def _time(hour, minute): total = 60 * hour + minute return (total // 60) % 24, total % 60 class Clock(object): def __init__(self, hour, minute): self.h, self.m = _time(hour, minute) def __repr__(self): return "{:02d}:{:02d}".format(self.h, self.m) def __eq__(self, other): ...
from django import template from ..utils import can_use_oauth_check register = template.Library() @register.filter def backend_name(name): """Human readable mapping for the social auth backend""" return { 'google-oauth': 'Google OAuth', 'google-oauth2': 'Google OAuth', 'google-openid...
""" Module containing all lark internal_transformer classes """ from collections import defaultdict import re from typing import Any, DefaultDict, Dict, List, Set, Tuple, Union import ibis from ibis.expr.operations import CrossJoin from ibis.expr.types import AnyColumn, TableExpr from lark import Token, Tree, v_args ...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt import pickle from matplotlib.colors import Normalize from matplotlib import rc from matplotlib.colors import LogNorm import glob import ipdb from matplotlib.colors import LogNorm import h5py as h5 methods = ["ienks-transform", "ienks-n-transform...
''' Created on 19 Oct 2013 @author: UserX ''' NAME = '%s' DISPLAY_NAME = '%s' MODULE_NAME = 'devdetect' CLASS_NAME = 'lockwatcherSvc' DESCRIPTION = 'Monitors for possible tampering and reacts accordingly' AUTO_START = True SESSION_CHANGES = True
try: import flask except ImportError: import sys print("tokenapp extras reqired to run this") sys.exit(1) import msal from . import settings, auth app = flask.Flask(__name__) msal_client = msal.PublicClientApplication( authority=settings.AUTH_ENDPOINT, client_id=settings.CLIENT_ID, ) @app...
import glob import os import shlex import tarfile import tempfile import zipfile from typing import Iterable, List, Optional, Set, Union from redun.executors.scratch import get_code_scratch_file from redun.file import File from redun.hashing import hash_stream def find_code_files( basedir: str = ".", includes: O...
"""lcc - Leipzig Corpora Collection. Usage: dasem.lcc get-all-tokenized-sentences [options] dasem.lcc data-directory dasem.lcc download dasem.lcc download-file <file> dasem.lcc get-sentence-words [options] dasem.lcc get-sentence-words-from-file [options] <file> dasem.lcc get-sentences [options] dasem.l...
input = """ true. i(a). h(a,a). % safe constraints :- i(Y), i(X), not h(X,Y). :- i(X), not h(X,X). :- not i(a). % unsafe constraints :- not h(X,Y). :- i(X1), not h(X1,X2). :- i(X2), not h(X1,X2). """ output = """ true. i(a). h(a,a). % safe constraints :- i(Y), i(X), not h(X,Y). :- i(X), not h(X,X). ...
EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'youremail@gmail.com' EMAIL_HOST_PASSWORD = 'yourpassword' EMAIL_PORT = 587
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Leonardo La Rocca """ import melopero_RV_3028 as mp import datetime import time def main(): # First initialize and create the rtc device rtc = mp.RV_3028() # Set the device to use the 24hour format (default) instead of the 12 hour format rtc...
import os import re import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand def _get_version(): v_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'huskar_sdk_v2', '__init__.py') ver_info_str = re.compile...
import logging from colorama import init, Fore, Back, Style init(autoreset=True) logging.basicConfig(level=logging.WARNING) class LogMachine(): def __init__(self): pass def log_info(self, message): logging.info(Fore.YELLOW + "\t" + message) def log_error(self, message): ...
#!/usr/bin/env python3 __author__ = 'dev' from fake_services.service.webservice.fake_web_server_manager import FakeWebServerManager from fake_services.service.networkservice.fake_dns_server_manager import FakeDnsServerManager config = { "/test": [ { "response_content_path": "req...
##################################################################### # # I should probably add a description for balrog! # # # Spencer Everett # UCSC # 12/10/2017 ##################################################################### import numpy as np import random as rand import os, sys, errno import cPickle as pick...
''' This program is useful when you want to add two numbers. It reads from the user 2 input and returns its sum def add(): x = input("Please Give me a number: ") y = input("Input another one: ") return ("The sum of %s and %s is %s") % (x,y,x+y) print add()
def check_predictors_present(data_set, predictor_subset): """Check if all predictors in predictor_subset are present as columns in the data_set dataframe.""" key_word_predictors = ['temporal', 'all'] for predictor in predictor_subset: if ( predictor not in data_set.columns and...
#!/usr/bin/env python # -*- coding: utf-8 -*- from bot import Bot if __name__ == "__main__": bot = Bot() bot.start()
import torch import torch.nn as nn import torch.nn.functional as F import torch.distributed as dist from mmcv.cnn import normal_init import numpy as np from mmdet.core import (sigmoid_focal_loss, iou_loss, multi_apply, multiclass_nms, distance2bbox) from mmdet.core import (AnchorGenerator, ancho...
from date import Date class Assignment: def __init__(self): self.name = 'Untitled' self.start_date = Date() self.due_date = Date() self.end_date = Date() def prompt(self): self.name = input('Name: ') print('\nStart Date:') self.start_dat...
# -*- coding: utf-8 -*- """Top-level package for Python Slide Tools - pic2slide.""" __author__ = """Weibo Ren""" __email__ = 'renweibo@gmail.com' __version__ = '0.1.0'
import ROOT import argparse import pickle import bz2 import os import time """ Stand alone script to convert root files of alpsIO class to python files on alpsdaq2 """ if __name__ == "__main__": usage = "usage: %(prog)s -i infile -o outdir" description = "Convert root alpsIO files to python pickle files" ...
""" j2lsnek, a python-based list server for Jazz Jackrabbit 2 By Stijn (https://stijn.chat) Thanks to DJazz for a reference implementation and zepect for some misc tips. """ import urllib.request import urllib.error import subprocess import importlib import logging import sqlite3 import socket import json import time...
from random import choice COLORS = ('white', 'yellow', 'purple', 'red') class Ghost(object): def __init__(self): self.color = choice(COLORS)
import sys import shutil import re import time from addict import Dict from tqdm import tqdm symbols = Dict({ 'prev_line': '\033[F', 'red': '\033[91m', 'green': '\033[92m', 'blue': '\033[94m', 'cyan': '\033[96m', 'white': '\033[97m', 'yellow': '\033[93m', ...
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # http://www.turnkeylinux.org/blog/django-profile User.profile = property(lambda u: UserProfile.objects.get_...
EVTCAN = "EVTCAN" OPENCAN = "OPENCAN" class HandlerAssociator(type): def __new__(cls, clsname, bases, dct): class_frame = type.__new__(cls, clsname, bases, dct) handlers = [] for attribute in dct.values(): if(hasattr(attribute,'match')): handlers.append(attribu...
# -*- coding: utf-8 -*- __version__ = '1.9.7' import gevent from gevent.local import local from zask.config import Config from zask.logging import create_logger from zask.utils import get_root_path class Zask(object): def __init__(self, import_name): self.default_config = { 'DEBUG': True, ...
import pandas as pd import xml.etree.ElementTree as ET from lxml import etree import sys from random import shuffle category = "" def __init__(self, category): self.category = category def define_file_names_pos_neg(category): file_name = '../data/test_data_raw/'+category+'.xml' return file_name def pa...
import requests import json import csv domain = 'http://localhost:3000/' domain = "http://www.elixirdoc.com:3000/" headers = {'content-type': 'application/json'} """Utils""" def read_json(file_name): with open(file_name, 'r') as input_file: return json.load(input_file) def read_csv(file_name): data = ...
from itertools import chain, cycle def spiral_coords(): """Generate sequence of coordinates.""" spiral, pos = 1, [0, 0] #yield tuple(pos) while True: pos[0] += 1 # Step in the next spiral yield tuple(pos) for axis, offs in [(1, 1), (0, -1), (1, -1), (0, 1)]: while o...
import pathlib from tempfile import NamedTemporaryFile import numpy as np import pandas as pd import pytest from numpy import testing as npt from pandas import testing as pdt from vascpy import specs from vascpy.exceptions import VasculatureAPIError from vascpy.point_vasculature import PointVasculature DATAPATH = pa...
#!/usr/bin/env python # A module for facilitating reading and writing of binary wiggle file data. import commands, math, os, pdb, random, string, struct, sys # Simple utility function for reversing elements of an input array: def reverse(inArray): outArr = [] idx = 1 while (idx <= len(inArray)): ...
from sq_python_helpers.FundUsingFriendbot import fund_using_friendbot from sq_python_helpers.GenerateKeypair import generate_keypair from sq_python_helpers.LoadKeyInformation import load_key_information from sq_python_helpers.SetupServerConnection import setup_server_connection from sq_python_helpers.SubmitHashTransact...
# Generated by Django 3.2.2 on 2021-06-29 12:48 from collections import defaultdict from django.db import migrations, models def set_finished_at(apps, schema_editor): Pod = apps.get_model('kra', 'Pod') Container = apps.get_model('kra', 'Container') pods = Pod.objects.in_bulk(field_name='id') contai...
# GIS4WRF (https://doi.org/10.5281/zenodo.1288569) # Copyright (c) 2018 D. Meyer and M. Riechert. Licensed under MIT. import os from collections import namedtuple import numpy as np import pytest from gis4wrf.bootstrap import bootstrap for t, v in bootstrap(): print('{}: {}'.format(t, v)) from gis4wrf.core.cons...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/xtark/ros_ws/src/vslam/rtabmap_ros/msg/Info.msg;/home/xtark/ros_ws/src/vslam/rtabmap_ros/msg/KeyPoint.msg;/home/xtark/ros_ws/src/vslam/rtabmap_ros/msg/MapData.msg;/home/xtark/ros_ws/src/vslam/rtabmap_ros/msg/MapGraph.msg;/home/xtark/ros_ws/src/v...
#!/usr/bin/python2.7 #capture the request packet from client and save to a queue using iptables and alter send or recieve modified packet #iptables commands iptables -I FORWARD -j NFQUEUE --queue-num 0 import netfilterqueue def process_packet(packet): print packet packet.accept() queue = netfilterqueue.NetfilterQ...
# @copyright@ # Copyright (c) 2006 - 2019 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ # # @rocks@ # Copyright (c) 2000 - 2010 The Regents of the University of California # All rights reserved. Rocks(r) v5.4 www.rocksclusters.org # ...
from typing import Any from pydantic import BaseModel class Error(BaseModel): """ Error holder """ message: str values: dict[str, Any] stacktrace: str
import torch from sklearn.metrics import accuracy_score, precision_score, recall_score, \ f1_score, confusion_matrix import numpy as np # Load the datasets #################################### from nldrp.dnn.modules.dataloading import EmotionDataset from nldrp.dnn.modules.models import EmotionModel from nldrp.dnn.u...
#!/usr/bin/env python def hinge(x): if 1 - x > 0: return 1 - x else: 0 def main(): print("Start training") # [4, 5] dataset = [[2.0, 3.0, 0.0, 5.0, 2.8], [3.0, 4.0, 5.0, 0.0, 0.0], [0.5, 0.3, 0.7, 0.9, 0.0], [-2.0, 0.1, 0.2, 0.9, 0.0]] # [4] labels = [1, 1, -1, -1] feature_size ...
# Copyright 2018-2021 Alvaro Bartolome, alvarobartt @ GitHub # See LICENSE for details. import json from datetime import date, datetime, timedelta from random import randint import pandas as pd import pytz import requests from lxml.html import fromstring from .constant import FUNDS_INTERVAL_FILTERS, INTERVAL_FILTERS...
import logging import os import requests import yaml from fastapi.testclient import TestClient from document.config import settings from document.entrypoints.app import app logger = settings.logger(__name__) def test_send_email_with_ar_nav_jud_pdf() -> None: """ Produce verse level interleaved document for...
# Copyright (c) 2009-2017, Matthew Brett and Christoph Gohlke # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright...
#Import from time import sleep #Setting a custom mac address custom_mac = "11:22:33:44:55:66" def on_eth_msg_received(msg): #Checking if source mac address in the message equals to custom_mac #we can also check if deestination mac address equals to Loopback adapter Mac address if msg.mac_address_source ==...
from vpython import * #GlowScript 2.7 VPython # Create a simple scrolling text object scene.width = scene.height = 250 scene.title = 'This is a test' B = box(pos=vec(0.1,0.2,0)) # Create a textarea element on the web page, below the box object. # $ stands for jQuery, an important web page addition to JavaScript. # The...
# coding: utf-8 """ service.proto No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: version not set Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_impor...
from data_processing.categorizer import Categorizer from config import search_categories # Categorizer def test_compile_category_words(): """Creates dict of words from jobs in each category""" categorizer = Categorizer() categorizer.compile_category_words(test = True) for category in search_categori...
import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim from torchvision import models import sys from utils.utilities import matrix_mul, element_wise_mul from utils.pytorchtools import EarlyStopping import numpy as np import time import copy import math import os import glob ...
#!/usr/bin/python # Example 4 from TensorFlow tutorial # set logging folder from globals import TESTSUITE_DIR logDir = TESTSUITE_DIR + "/faultLogs/" confFile = TESTSUITE_DIR + "/confFiles/injections_config.yaml" #specify the config file # ***the call to TensorFI to instrument the model must include these directori...
# Python3 implementation of the approach # Function to print the requried pattern def drawPattern(N) : n = N; row = 1; # 'nst' is the number of values nst = 1; # 'nsp' is the number of spaces nsp1 = n - 1; nsp2 = -1; val1 = row; val2 =...
# coding=utf-8 # http://poj.org/problem?id=3250 # 牛头向右,每头牛能看到多少牛 class Solution(object): def cow_see(self, cows): # 暴力 # O(n^2) result = [0] * len(cows) for i in range(len(cows)-1): for j in range(i+1, len(cows)): if cows[j] <= cows[i]: ...
from logging.config import fileConfig fileConfig('./appIng/logging.cfg') #fileConfig('./logging.cfg')
"Opencv Drawing" import numpy as np import cv2 from numpy.core.fromnumeric import size from numpy.random import randint # Initialize our canvas of certain size with 3 channels canvas = np.zeros((300, 300, 3), dtype='uint8') # Drawing a green line from top left corner green = (0, 255, 0) cv2.line(canvas, pt1=(0, 0...
import numpy as np import pandas as pd import os import matplotlib matplotlib.use('pdf') import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import adjusted_rand_score from sklearn.preproce...
import os import pandas as pd import numpy as np from collections import Counter import re from dataloader import * import joblib import optparse # function to transform hours and minutes to seconds def trans_seconds(time_list): seconds_list = [] seconds = 0 for i in range(len(time_list)): ...
# ---------------------------------------------------------------- # Copyright 2017 Cisco Systems # # 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/LICENS...
from django.shortcuts import render,get_list_or_404 from .models import Job # Create your views here. def homepage(request): jobs= Job.objects return render(request,'jobs/home.html',{'jobs':jobs}) def detail(request,job_id): job_detail = get_list_or_404(Job,pk=job_id) print("yay",job_detail) retur...
# Copyright (c) 2018, Vanessa Sochat All rights reserved. # See the LICENSE in the main repository at: # https://www.github.com/openschemas/openschemas-python from openschemas.logger import bot from openschemas.utils import ( read_yaml, read_file, write_yaml ) import frontmatter import os import sys i...
import sys sys.stdin = open('2568.txt') A = [0 for _ in range(500001)] N= int(input()) max_n = 0 for _ in range(N): a,b = map(int, input().split()) max_n = max(a, max_n) A[a] = b len = [[0,0] for _ in range(500001)] node = [0 for _ in range(500001)] idx = 0 def low_binary(last, find): low = 0 h...
########################################################################## # Copyright (c) 2013, ETH Zurich. # All rights reserved. # # This file is distributed under the terms in the attached LICENSE file. # If you do not find this file, copies can be found by writing to: # ETH Zurich D-INFK, CAB F.78, Universitaetstr...
from __future__ import print_function, division import csv import functools import json import os import random import warnings import numpy as np import torch from pymatgen.core.structure import Structure from torch.utils.data import Dataset, DataLoader from torch.utils.data.dataloader import default_collate from to...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 4 21:33:10 2019 @author: george """ import numpy as np import matplotlib.pyplot as plt def plot_prob_state( state_probs, state = 1, index_real = None, real_state = None, name = None): """ plo...
import logging from cinp.client import CInP, NotFound class Contractor(): def __init__( self, site, host, root_path, proxy ): super().__init__() self.module_list = [] self.site = '{0}Site/Site:{1}:'.format( root_path, site ) self.cinp = CInP( host=host, root_path=root_path, proxy=proxy ) def set...
import argparse import json import os import os.path import tensorflow as tf from tensorflow import keras import common SPLIT_PERCENTAGE = 0.8 BATCH_SIZE = 32 NUM_EPOCHS = 15 def main(): output_dir = os.path.abspath('output') records_dir = os.path.abspath('records') metadata_file = os.path.abspath('sbubby_metada...