content
stringlengths
5
1.05M
import torch import torch.nn as nn import torch.nn.functional as F from layers import ImplicitGraph from torch.nn import Parameter from utils import get_spectral_rad, SparseDropout import torch.sparse as sparse class IGNN(nn.Module): def __init__(self, nfeat, nhid, nclass, num_node, dropout, kappa=0.9, adj_orig=N...
from PIL import Image import argparse import os import sys current_directory = os.getcwd() def args_check(args = None): if(args == None): print("Arguments are reqiured for execution") parser = argparse.ArgumentParser(description="Resizer - A lightweight Image size and resolution resizer") parse...
a,b = 1,2 print a+b
import shlex import json from .BaseClient import BaseClient from .Response import JSONResponse from . import typchk DefaultTimeout = 10 # seconds class ContainerClient(BaseClient): class ContainerZerotierManager: def __init__(self, client, container): self._container = container ...
import tensorflow as tf import keras # print(tf.__version__, keras.__version__) amv_model_path = "model/frmodel.h5" export_path = "model/ArtMaterialVerification/2" model = tf.keras.models.load_model(amv_model_path) with tf.keras.backend.get_session() as sess: tf.saved_model.simple_save( sess, ex...
import pandas as pd import numpy as np import scipy as sp import random from scipy.spatial.distance import mahalanobis class TrainOutlier: data = None percentilek = None valuecountsdict = None colsum = None median = None invcovmx = None cols = None threshold = None ...
import os from twisted.logger import FilteringLogObserver, LogLevelFilterPredicate, LogLevel, jsonFileLogObserver from twisted.python import logfile from twisted.python.log import FileLogObserver log_dir = os.environ.get("LOG_DIR", '/var/log/') log_level = os.environ.get("TWISTED_LOG_LEVEL", 'INFO').lower() log_rotat...
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under Simplified BSD License (see LICENSE) import os import pytest from datadog_checks.redisdb import Redis from . import common pytestmark = pytest.mark.e2e def assert_common_metrics(aggregator): tags = ['redis_host:{}'.format(common.HOST), 'r...
import os from oelint_adv.cls_rule import Rule from oelint_parser.helper_files import expand_term from oelint_parser.helper_files import get_layer_root class RubygemsTestCase(Rule): TESTCASE_DIR = "lib/oeqa/runtime/cases" def __init__(self): super().__init__(id="rubygems.testcase", ...
# -*- coding: utf-8 -*- """Sonos Alarms.""" from __future__ import unicode_literals import logging from datetime import datetime import re import weakref from .core import discover, PLAY_MODES from .xml import XML log = logging.getLogger(__name__) # pylint: disable=C0103 TIME_FORMAT = "%H:%M:%S" def is_valid_rec...
"""The core event-based simulation engine""" import heapq from abc import abstractmethod from dataclasses import dataclass, field from enum import Enum, auto from typing import Iterator, List, NamedTuple, Optional, Protocol, runtime_checkable # from .event import EventError, EventLike, StopEngineError __all__ = [ ...
import pdb import copy import json import numpy as np from utils import game_util import constants class ActionUtil(object): def __init__(self): self.actions = [ {'action' : 'MoveAhead', 'moveMagnitude' : constants.AGENT_STEP_SIZE}, {'action' : 'RotateLeft'}, ...
import requests apikey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwODE4ODU1YTcxOGRmNGVkMTkwZjE1ZSIsImlhdCI6MTYxOTEwMTc4MSwiZXhwIjoxNjIxNjkzNzgxfQ.SlyayNaXu8PTPYAtyR9h7tIlR9ooXn72DRn6EAwcgV6rNY1rZQCoSs_d2EESIJs3kb0LwCSfU9o5lWMW9_Twigj3FxX99iAg7_gB1m6TReJ2moZ-rYIst6RTtJtWQWBezZ-37RyACH9s44WQ9qnlrXBYKgnW6LyVi18Kdf...
# coding: utf-8 from distutils.core import setup __version__ = '0.2.3' short_description = 'Statistics for Django projects' try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): long_description = short_description install_requires = [ 'Djang...
import os sd = None def set_sd(new_sd): global sd sd = new_sd tmp_dir = "tmp/" export_tmp = tmp_dir + "dashboard_export.csv" if not os.path.exists(tmp_dir): os.mkdir(tmp_dir)
# Seasons SEASONS = [ "PRESEASON 3", "SEASON 3", "PRESEASON 2014", "SEASON 2014", "PRESEASON 2015", "SEASON 2015", "PRESEASON 2016", "SEASON 2016", "PRESEASON 2017", "SEASON 2017", "PRESEASON 2018", "SEASON 2018", "PRESEASON 2019", "SEASON 2019", ]
import fire from .utils import * tfd=test_font_dir if __name__ == '__main__': fire.Fire()
print('='* 40) print('{:^40}'.format('Listagem de Preços!!')) print('='* 40) listagem = ('Espeto de Carne', 8.00, 'Espeto de Frango', 5.00, 'Espeto de Linguiça', 5.50, 'Espeto de Kafta', 6.00, 'Espeto de Queijo', 6.50, 'Espeto de Medalhão Frango', 6.00, ...
from django.shortcuts import render from django.http import HttpResponse from random import randint def big(): return randint(0, 1_000_000) def index(request): return HttpResponse("Hello, there! Welcome to the base of the project! Your big ugly number is " + str(big()))
import os from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from settings import CLIENT_NAME, Client, LAUNCH_MODE, LaunchMode, URL, LocatorType class LauncherNotSu...
import logging import subprocess import os import platform import sys from cmd2 import utils logger = logging.getLogger(__name__.split(".")[-1]) class Command: """ Provides a way to run bash commands on local or remote side Remote execution of commands is done over SSH protocol for given username and ho...
# print ' name ' , multiple times # for loop for i in range(1,11): i = 'Omkar' print(i) # while loop i = 1 while (i<11) : print('Omkar) i = i + 1
# see https://www.codewars.com/kata/614adaedbfd3cf00076d47de/train/python def expansion(matrix, n): for _ in range(n): rows = [x + [sum(x)] for x in matrix] extraRow = [sum([x[i] for x in rows]) for i in range(len(matrix))] + [sum([matrix[i][i] for i in range(len(matrix))])] rows.append(extraRow) mat...
""" Multi-core and Distributed Sampling =================================== The choice of the sampler determines in which way parallelization is performed. See also the `explanation of the samplers <sampler.html>`_. """ from .singlecore import SingleCoreSampler from .mapping import MappingSampler from .multicore impo...
from game_state import GameState import arcade as ac import math class DrawingManager: @classmethod def tick(cls): if "entities" in GameState.current_state: for ent in GameState.current_state["entities"]: if "pos" in ent and "rot" in ent and "drawing" in ent: ...
#!/usr/bin/python3 # # Copyright 2012 Sonya Huang # # 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 a...
import os, sys # add NADE to path nade_path = os.path.join(os.path.abspath('.'), 'bench_models', 'nade') sys.path.append('./bench_models/nade/')
""" Part of BME595 project Program: Show statistics of dataset """ from collections import Counter from data import data_loader, _preprocess_dataset_small, _preprocess_dataset_large def show_distribution(max_len=60, deduplicate=False): small_sentences, small_polarities, purposes, _ = _preprocess_dataset_small(m...
import re from behave import given, when, then from django.core import mail from {{ cookiecutter.project_slug }}.apps.myauth.tests.factories import VerifiedUserFactory from {{ cookiecutter.project_slug }}.apps.profile.models import Profile from features.hints import BehaveContext @given("a registered user") def ste...
from mle_monitor import MLEProtocol meta_data = { "purpose": "Test MLEProtocol", "project_name": "MNIST", "exec_resource": "local", "experiment_dir": "log_dir", "experiment_type": "hyperparameter-search", "base_fname": "main.py", "config_fname": "tests/fixtures/base_config.json", "num_s...
""" Module: 'sys' on esp32 1.9.4 """ # MCU: (sysname='esp32', nodename='esp32', release='1.9.4', version='v1.9.4 on 2018-05-11', machine='ESP32 module with ESP32') # Stubber: 1.2.0 argv = None byteorder = 'little' def exit(): pass implementation = None maxsize = 2147483647 modules = None path = None platform = 'es...
import pickle filename = './data/29_header_payload_all.traffic' with open(filename, 'r') as f: traffic = f.readlines() with open('./data/29_payload_all.traffic','w') as f: for i in range(len(traffic)): s_traffic = traffic[i].split() if s_traffic[10] == '11': payload = s_traffic[0...
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of Ansible # # Ansible 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 version. ...
import falcon from chromarestserver.resource import ( ChromaSdkResource, SessionRootResource, HeartBeatResource, KeyboardResource ) from chromarestserver.model import ( KeyboardModel, SessionModel ) app = falcon.API() usb_keyboard = KeyboardModel() session = SessionModel() chromasdk = Chroma...
import os import json from typing import Optional from requests import post,get from fastapi import FastAPI app = FastAPI() ha_ip = os.environ['HA_IP'] ha_port = os.environ['HA_PORT'] ha_entity = os.environ['HA_ENTITY'] #must be a sensor ha_token = os.environ['HA_TOKEN'] ha_friendly_name = os.environ['HA_FRIENDLY_N...
# ISC # # Copyright (c) 2022 Adir Vered <adir.vrd@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS...
from huobi.client.trade import TradeClient from huobi.constant import * from huobi.utils import * trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key) symbol_test = "eosusdt" i = 0 n = 3 order_id_list = [] while i < n: order_id = trade_client.create_order( symbol=symbol_test, ac...
from Utils import * ''' On Adamson data ''' Data_dir = "/home/luodongyang/SCData/Perturb/Adamson/" #------------------------------------------------------------------------# # Read Data ## Matrix mat=mmread(os.path.join(Data_dir, "GSM2406677_10X005_matrix.mtx.txt")) cell_ident = pd.read_csv(os.path.join(Data_dir, "GSM2...
# debug_importer.py import sys class DebugFinder: @classmethod def find_spec(cls, name, path, target=None): print(f"Importing {name!r}") return None sys.meta_path.insert(0, DebugFinder)
import json import os import unittest from netdice.common import Flow, StaticRoute from netdice.explorer import Explorer from netdice.input_parser import InputParser from netdice.problem import Problem from netdice.properties import WaypointProperty, IsolationProperty from netdice.reference_explorer import ReferenceEx...
import os from datetime import datetime from flask import Flask, render_template, redirect, flash, abort, url_for, request from flask.ext.restless import APIManager from flask_admin import Admin from flask_admin.contrib.sqla import ModelView from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import UserM...
from setuptools import setup, find_packages from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='ciscoaplookup', version="0.10.0", author="Steffen Schumacher", aut...
# -*- coding: utf-8 -*- """ Created on Fri Jun 28 11:07:41 2019 @author: Kevin """ import numpy as np import pickle from shapely.geometry import Point class TileCreator(object): def __init__(self, configuration, polygon): self.output_path = configuration['tile_coords_path'] # A...
from setuptools import setup setup( name='YAFN', version='0.0.1', author='txlyre', author_email='me@txlyre.website', packages=['yafn', 'yafn-tracker'], url='https://github.com/txlyre/yafn', license='LICENSE', description='Yet another p2p file network protocol.', install_requires=[ 'cbor2', 'p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 14 14:47:38 2021 @author: cxue2 """ import torch from xfdlfw import Result from xfdlfw.metric import ConfusionMatrix, Accuracy, MeanSquaredError, MeanAbsoluteError, CrossEntropy acc = Accuracy('acc') ce_ = CrossEntropy('ce_') mse = MeanSquaredErro...
"""BleBox sensor entities.""" # pylint: disable=fixme from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.entity import Entity from . import CommonEntity, async_add_blebox async def async_setup_platform(hass, config...
from CHECLabPy.spectrum_fitters.gentile import sipm_gentile_spe, \ calculate_spectrum, SiPMGentileFitter, SpectrumParameter import numpy as np from numpy.testing import assert_allclose from numba import typed def test_sipm_gentile_spe(): x = np.linspace(-1, 20, 1000, dtype=np.float32) y = sipm_gentile_spe...
# the url address of the REST API server CDS_LB='https://rest-endpoint.example.com' # location of client certificate and key CDS_CERT='../certs/cds_cert.pem' CDS_KEY='../certs/cds_key.pem' # the endpoint url of REST server, multiple version can and will be available CDS_API='/v2.0/DetectionRequests' CDS_URL=CDS_LB+CDS...
import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import dash_table_experiments as dt import json import pandas as pd import numpy as np import plotly app = dash.Dash() app.scripts.config.serve_locally=True DF_WALMART = pd.read_csv('https:/...
from pathlib import Path import pytest RESOURCES_DIR = Path(__file__).parent / "resources" @pytest.fixture def users_path(): return RESOURCES_DIR / "test-users.json" @pytest.fixture def tweets_path(): return RESOURCES_DIR / "test-tweets.json"
import pandas as pd __all__ = ["calc_embedding_size"] def calc_embedding_size(df: pd.DataFrame) -> int: """ Calculates the appropriate FastText vector size for categoricals in `df`. https://developers.googleblog.com/2017/11/introducing-tensorflow-feature-columns.html Parameters ------...
import mailparser import re from nltk.tokenize import word_tokenize from nltk import pos_tag # #### typo_parser def typo_parser(x): """ 1. replace irrelevant symbol "|" or "*" 2. remove extra space " " 3. replace extra \n "\n\n" into "\n" 4. replace "> *>" into ">>" for further analysis @pa...
"""API package. Contains controller and model definitions. Modules: models routes views """
from transformers import AutoModelForSequenceClassification, Trainer, AutoTokenizer from sklearn.metrics import accuracy_score, precision_recall_fscore_support from datasets import load_from_disk import tarfile import os if len(os.listdir('model')) == 0: with tarfile.open('model.tar.gz') as tar: tar.extrac...
""" Visualize ========= pypesto comes with various visualization routines. To use these, import pypesto.visualize. """ from .reference_points import (ReferencePoint, create_references) from .clust_color import (assign_clusters, assign_clustered_colors, ...
import boto3 import pytest import uuid acm = boto3.client('acm') @pytest.fixture(scope="module") def certificate(): name = 'test-%s.binx.io' % uuid.uuid4() alt_name = 'test-%s.binx.io' % uuid.uuid4() certificate = acm.request_certificate(DomainName=name, ValidationMethod='DNS', SubjectAlternativeNames=[a...
import numpy as np from nlpaug.util import Method from nlpaug import Augmenter class SpectrogramAugmenter(Augmenter): def __init__(self, action, name='Spectrogram_Aug', aug_min=1, aug_p=0.3, verbose=0): super(SpectrogramAugmenter, self).__init__( name=name, method=Method.SPECTROGRAM, action=a...
# -*- coding: utf-8 -*- from flask import jsonify, request from pronto import utils from . import bp @bp.route("/<path:accessions>/proteins/") def get_proteins_alt(accessions): accessions = set(utils.split_path(accessions)) try: comment_id = int(request.args["comment"]) except KeyError: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 8 18:04:51 2021 @author: jm """ # required libraries import pytest import pandas as pd import numpy as np from task1.helpers import Helper # sample rate values for different currencies rates = {'USD': 1.067218} # sample data frame df = pd.DataFr...
from ctypes import cdll, c_int, c_size_t my_lib = cdll.LoadLibrary('target/debug/librust_ffi.so') int_array_size = c_size_t(256) int_array = (c_int * int_array_size.value)() my_lib.produce_us_some_numbers(int_array, int_array_size) for i,n in enumerate(int_array): print(str(n) + ' ', end='') if (i + 1) % 16...
shapes = [ # Grosses L [ (0, 0, 0), (1, 0, 0), (2, 0, 0), (0, -1, 0) ], # T [ (0, 0, 0), (1, 0, 0), (2, 0, 0), (1, -1, 0) ], # Eck aka kleines L [ (0, 0, 0), (1, 0, 0), (0, -1, 0) ], # Treppe [ (0, 0, 0), (1, 0, 0), (1, 1, 0), (2, 1, 0) ], # Asymmetrische Ecken [ (0, 0, 0), ...
import sys import time import datetime lines = open(sys.argv[1], 'r') for line in lines: line = line.replace('\n', '').replace('\r', '') if len(line) > 0: a, b = sorted([datetime.datetime.strptime(x, "%H:%M:%S") for x in line.split(' ')]) hours, remainder = divmod((b - a).seconds, 3600...
# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at: # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
# -*- coding: utf-8 -*- """The multi-process processing engine.""" import abc import ctypes import os import signal import sys import threading import time from plaso.engine import engine from plaso.engine import process_info from plaso.lib import definitions from plaso.multi_process import logger from plaso.multi_pr...
#!/usr/local/bin/python2.7 ## # OOIPLACEHOLDER # # Copyright 2014 Raytheon Co. ## from mi.core.versioning import version from mi.dataset.dataset_parser import DataSetDriverConfigKeys from mi.dataset.driver.cg_stc_eng.stc.mopak_o_dcl_common_driver import MopakDriver from mi.dataset.parser.mopak_o_dcl import \ Mopak...
# Aula 08 (Usando Módulos do Python) from math import sin, cos, tan, radians # para seno, cosseno e tangente # é preciso converter o ângulo para radians angulo = float(input('Digite um Ângulo qualquer: ')) print('Ângulo: {:.2f}' '\nSeno: {:.2f}' '\nCosseno: {:.2f...
from consola import leer_caracter from consola import leer_entrada_completa from consola import obtener_caracter from consola import avanzar_caracter from consola import hay_mas_caracteres from consola import imprimir from consola import cambiar_color_texto min_C3_BAscula = None may_C3_BAscula = None def Buscar_vocal...
import os ls=["python main.py --configs configs/train_ricord1a_unetplusplus_timm-regnetx_002_fold0_noda.yml", "python main.py --configs configs/train_ricord1a_unetplusplus_timm-regnetx_002_fold1_noda.yml", "python main.py --configs configs/train_ricord1a_unetplusplus_timm-regnetx_002_fold2_noda.yml", "python main.py -...
nCr = [[0 for j in range(101)] for i in range(101)] for i in range(101): for j in range(i+1): if i==j or j==0: nCr[i][j] = 1 else: nCr[i][j] = nCr[i-1][j-1] + nCr[i-1][j] while True: n,r = list(map(int,input().split())) if n==0 and r==0: break print(str(n...
print("hola") kjnkjk
from setuptools import setup, find_packages setup( name="django-allmedia", url="http://github.com/suselrd/django-allmedia/", author="Susel Ruiz Duran", author_email="suselrd@gmail.com", version="1.0.20", packages=find_packages(), include_package_data=True, zip_safe=False, descriptio...
""" cloudalbum/app.py ~~~~~~~~~~~~~~~~~~~~~~~ AWS Chalice main application module :description: CloudAlbum is a fully featured sample application for 'Moving to AWS serverless' training course :copyright: © 2019 written by Dayoungle Jun, Sungshik Jou. :license: MIT, see LICENSE for more details...
# noqa: E501 ported from https://discuss.pytorch.org/t/utility-function-for-calculating-the-shape-of-a-conv-output/11173/7 import math def num2tuple(num): return num if isinstance(num, tuple) else (num, num) def conv2d_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): h_w, kernel_size, stride, ...
resposta = 42 print('A resposta para tudo é: ', resposta)
# -*- coding: utf8 -*- # # Copyright (c) 2016 Linux Documentation Project from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import unittest import argparse from argparse import Namespace from tldptesttools import TestToolsFilesystem from tldptesttools import CCT...
import time from adafruit_servokit import ServoKit kit = ServoKit(channels=16) def mouth(action): if(action == 0): print("openMouth") kit.servo[0].angle = 40 if(action == 1): print("close") kit.servo[0].angle = 180 if(action == 2): print("talk") #kit.servo[0...
""" Perceptual decision-making task, loosely based on the random dot motion task. """ import numpy as np from pycog import Model, RNN, tasktools #------------------------------------------------------------------------------- # Network structure #----------------------------------------------------------------------...
from OpenGL.GL import * import threading import random import time class Block: """ Block * Base block class """ def __init__(self, name, renderer): """ Block.__init__ :name: name of the block :texture: texture of the block :parent: the parent window ...
from django.conf import settings from .filebased import FileBackend from .s3 import S3Backend DEFAULT_CLASS = FileBackend def get_backend_class(): if settings.FILE_STORAGE_BACKEND == "s3": return S3Backend elif settings.FILE_STORAGE_BACKEND == "file": return FileBackend else: ...
from setuptools import setup setup(name='data_loader', version='0.1', description='Hackathon data loader', url='https://github.com/snowch-labs/or60-ocado-ibm-hackathon', author='Chris Snow', author_email='chris.snow@uk.ibm.com', license='Apache 2.0', packages=['data_loader'], ...
from json import loads from gtts import gTTS import urllib.request import time import random link = "http://suggestqueries.google.com/complete/search?client=firefox&q=" rap = "" def editLinkWithUserInput(link): magicWord = str(input("What do you want your starting words to be? ")) if " " in magicWord: ...
import sys import os cur = os.path.dirname(os.path.abspath(__file__)) sys.path.append(cur) sys.path.append(cur+"/..") sys.path.append(cur+"/../common") from SearchRepository import ISearchRepository import unittest from IQRServer import QRContext from IQRRepository import IQRRepository from search_service import * fro...
# =============================================================================== # Copyright 2015 Jake Ross # # 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...
#!/usr/bin/python from __future__ import division, print_function import multiprocessing from subprocess import call import numpy as np import pandas as pd import numpy.linalg as linalg from math import sqrt import ld.ldscore as ld import ld.parse as ps from ldsc_thin import __filter_bim__ from scipy.stats import norm ...
file1=open("./protein1.pdb","r") file2=open("./protein2.pdb","r") from math import * model1=[] model2=[] for line in file1: line=line.rstrip() if "CA" in line: list1=line.split() model1.append([float(list1[6]),float(list1[7]),float(list1[8])]) for line in file2: line=line.rstrip() if "CA" in line: list2=line....
""" 关键点解析 链表的基本操作(删除指定节点) 虚拟节点dummy 简化操作 其实设置dummy节点就是为了处理特殊位置(头节点),这这道题就是如果头节点是给定的需要删除的节点呢? 为了保证代码逻辑的一致性,即不需要为头节点特殊定制逻辑,才采用的虚拟节点。 如果连续两个节点都是要删除的节点,这个情况容易被忽略。 eg: // 只有下个节点不是要删除的节点才更新current if (!next || next.val !== val) { current = next; } """ """ Before writing any code, it's good to make a list of edge cases ...
""" Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2:...
import redis rds=redis.StrictRedis('db', 6379)
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django.contrib.auth.forms import PasswordChangeForm class CreateProject(forms.Form): projectname = forms.SlugField(label="Enter project name", max_length=50, required=True) helper = FormHelper() ...
from JumpScale import j def cb(): from .HttpClient import HttpClient return HttpClient() j.base.loader.makeAvailable(j, 'clients') j.clients._register('http', cb)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Assumes: Python 3 (>= 3.6) # selenium ($ pip install selenium) # ChromeDriver (http://chromedriver.chromium.org) # Chrome binary (> v61) # __author__ = "Adam Mikeal <adam@tamu.edu>" __version__ = "0.8" import os import sys import logging i...
""" Azdevman Consts This module contains constant variables that will not change """ # Environment Variables AZDEVMAN_ENV_PREFIX = "AZDEVMAN_" # Azure Devops AZ_BASE_URL = "https://dev.azure.com/" AZ_DEFAULT_ORG = "ORGANIZATION" AZ_DEFAULT_PAT = "UEFUCg==" AZ_DEFAULT_PROJECT = "PROJECT" # Config file CONFIG_DIR = "...
class JintaroException(Exception): """Base class for Jintaro exceptions""" class ConfigError(JintaroException): """Base class for config exceptions""" class UnknownOptionError(ConfigError): """""" class ConfigValueError(ConfigError): """""" class InputListError(JintaroException): """""" cl...
#! /usr/bin/env python def read_file(): """Opens Project Euer Name file. Reads names, sorts and converts str into a list object""" a = open('names.txt', 'r') data = a.read() names = data.split(",") a.close() names.sort() return names def name_score(): """Calculates the total nam...
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # 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...
#!/usr/bin/env python # J-Y Peterschmitt - LSCE - 09/2011 - pmip2web@lsce.ipsl.fr # Test the use of hatches and patterns in the isofill # and fill area graphics methods # Import some standard modules from os import path # Import what we need from CDAT import cdms2 import vcs # Some data we can plot from the 'sampl...
from thresher.scraper import Scraper from thresher.query_share import QueryShare import furl import csv import os from slugify import slugify import wget import json ### Possibly convert this to docopt script in the future ### class Thresher: #assumes that links is a list of dictionaries with the keys as a conten...
from hknweb.academics.views.base_viewset import AcademicEntityViewSet from hknweb.academics.models import Instructor from hknweb.academics.serializers import InstructorSerializer class InstructorViewSet(AcademicEntityViewSet): queryset = Instructor.objects.all() serializer_class = InstructorSerializer
import sys if len(sys.argv) == 2: print("hello, {}".format(sys.argv[1])) #print("hello,"+(sys.argv[1])) else: print("hello world")
import pydot # I like to use the full path for the image as it seems less error prone. # Therefore, first we find the current path of this file and use that to locate the image - assuming the image, # is in the same folder as this file. import pathlib current_path = pathlib.Path(__file__).parent.resolve() # Create t...