content
stringlengths
0
894k
type
stringclasses
2 values
""" A script that processes the Qualitivity XML files and creates CSV files of extracted data. """ import argparse import os import sys from xml.etree import ElementTree import numpy as np import pandas as pd # data frame columns columns = ['Record ID', 'Segment ID', 'Total pause duration_300', 'Pause count_300', ...
python
# -*- coding: utf-8 -*- import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe' from tkinter import filedialog from tkinter import * root = Tk() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg file...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 14 18:00:19 2021 @author: dipu """ from rico import * from utils import * from moka import * from datasets import * from scipy.optimize import linear_sum_assignment import os import time import sys import shutil import random ...
python
import numpy as np import os import cv2 def make_image_noisy(image, noise_typ): if noise_typ == "gauss": row, col, ch = image.shape mean = 0 var = 40 sigma = var**0.5 gauss = np.random.normal(mean, sigma, (row, col, ch)) gauss = gauss.reshape((row, col, ch)) ...
python
# -*- coding: utf-8 -*- from django.apps import AppConfig import urllib, requests, json from timetable.models import Course from ngram import NGram class SearchConfig(AppConfig): name = 'curso' class SearchOb(object): """docstring for SearchOb""" def __init__(self, uri=None): from pymongo impo...
python
#!/usr/bin/env python """The setup script.""" try: from setuptools import find_packages, setup except ImportError: from distutils.core import find_packages, setup setup(name='hyperscan-python', version='0.1', description='Simple Python bindings for the Hyperscan project.', author='Andreas Moser'...
python
def test_geoadd(judge_command): judge_command( 'GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"', { "command": "GEOADD", "key": "Sicily", "longitude": "15.087269", "latitude": "37.502669", "member": '"Catania"', ...
python
import jpype jpype.startJVM() from asposecells.api import Workbook, PdfSaveOptions, ImageOrPrintOptions, SheetRender import cv2 import numpy as np DEBUG_MODE = False def excel2imgs(excel_path): workbook = Workbook(excel_path) ''' Excel to PDF ''' # pdfOptions = PdfSaveOptions() # pdfOptions.setOneP...
python
# -*- coding: UTF-8 -*- import cv2 as cv import os import argparse import numpy as np import pandas as pd import time from utils import choose_run_mode, load_pretrain_model, set_video_writer from Pose.pose_visualizer import TfPoseVisualizer from Action.recognizer import load_action_premodel, framewise_recogniz...
python
from typing import Optional, List from reconbot.notificationprinters.embedformat import EmbedFormat class NotificationFormat(object): def __init__(self, content: Optional[str], embeds: Optional[List[EmbedFormat]] = None): self.content = content if embeds is None: self.embeds = [] ...
python
from typing import List, Dict, Union from sse_starlette.sse import EventSourceResponse from fastapi import Depends, FastAPI, Request from fastapi_users import FastAPIUsers, BaseUserManager from fastapi_users.authentication import JWTAuthentication from sqlalchemy.orm import Session from . import crud, schemas from .a...
python
# -*- coding: UTF-8 -*- # Copyright 2015-2020 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """Same as :mod:`lino_book.projects.noi1e`, but using :ref:`react` as front end. This uses :ref:`hosting.multiple_frontends`. .. autosummary:: :toctree: settings tests """
python
from mongoengine import signals __author__ = 'Enis Simsar' import json import re import threading from datetime import datetime from decouple import config from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener from models.Tweet import Tweet from models.Topic import Top...
python
#!/usr/bin/env python3 import argparse, os """ Trenco Module for arguments """ def txn_args(parser): parser.add_argument('--annotation-file', dest = 'annotfname', default = '', help="Genode annotations file in gtf format (overwrites --annota...
python
#!/usr/bin/env python3 import argparse import json import sys from datetime import datetime from time import sleep from splinter import Browser from tvlist_loader import xlparser from tvlist_loader import scraper from tvlist_loader import projects_parser as pp def main(): # Parse cli arguments parser = argp...
python
import matplotlib.pyplot as plt import numpy as np import os import seaborn as sns import shutil # =========== HYPERPARAMETERS ========== UNIVARIATE_DISTRIBUTIONS = ['chi_square_9', 'exp_9'] NUM_SAMPLES = 20000 NUM_TRIALS = 5 # ========== OUTPUT DIRECTORIES ========== OUTPUT_DIR = 'examples/power_analyses/univariate...
python
import scrapy import re from locations.items import GeojsonPointItem DAY_MAPPING = { "Mon": "Mo", "Tues": "Tu", "Wed": "We", "Thur": "Th", "Fri": "Fr", "Sat": "Sa", "Sun": "Su" } class KoppsSpider(scrapy.Spider): name = "kopps" item_attributes = { 'brand': "Kopps" } allowed_doma...
python
import smtplib from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email import encoders from user import User from mail import Mail class ImportantUser(User): ''' ImportantUser class inherits from User class. It is more complex version of it. It let's user add attachm...
python
/Users/NikhilArora/anaconda3/lib/python3.6/imp.py
python
# coding: utf-8 """Everythong related to parsing tracker responses""" import urlparse from lxml import etree class BaseParser(object): """Abstract base class for tracker response parser""" def parse_index(self, html): """Parse index html and return list of dicts""" raise NotImplementedError() ...
python
from compas.datastructures import Network def test_add_vertex(): network = Network() assert network.add_vertex() == 0 assert network.add_vertex(x=0, y=0, z=0) == 1 assert network.add_vertex(key=2) == 2 assert network.add_vertex(key=0, x=1) == 0
python
#!/usr/bin/python """ %prog [options] pair_1.fastq pair_2.fastq filter reads from paired fastq so that no unmatching reads remain. output files are pair_1.fastq.trim and pair_2.fastq.trim see: http://hackmap.blogspot.com/2010/09/filtering-paired-end-reads-high.html """ __version__ = "0.1.0" from subprocess import Pop...
python
#!/usr/bin/env python3 # # debris.db -- database-related operations for debris import sqlite3 import time from . import common from .common import run_process from .common import getconfig from .common import log class DebrisDB(object): """Object that can represent the database connection. We are using sql...
python
#AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"extract_tag": "om2.ipynb", "contains_tag": "om2.ipynb", "is_nbx": "om2.ipynb", "is_nbx_cell": "om2.ipynb", "is_magic_or_shell": "om2.ipynb", "": "om2.ipynb", ...
python
#Создай собственный Шутер! from pygame import * from random import randint from time import time as timer mixer.init() mixer.music.load('Fonk.ogg') mixer.music.play(-1) mixer.music.set_volume(0.2) fire_sound = mixer.Sound('blaster.ogg') fire_sound.set_volume(0.1) font.init() font1 = font.SysFont('Arial',80) win = fon...
python
#!/usr/bin/env python3 # # kcri.bap.shims.cgMLSTFinder - service shim to the cgMLSTFinder backend # import os, json, tempfile, logging from pico.workflow.executor import Task from pico.jobcontrol.job import JobSpec, Job from .base import ServiceExecution, UserException from .versions import BACKEND_VERSIONS # Our ser...
python
import time import pytest import examples import progressbar import original_examples def test_examples(monkeypatch): for example in examples.examples: try: example() except ValueError: pass @pytest.mark.filterwarnings('ignore:.*maxval.*:DeprecationWarning') @pytest.mark...
python
from .default import Config class DevelopmentConfig(Config): """ Configurations for Development. """ DEBUG = True TESTING = True SECRET = "DevelopSecret123!!" # pragma: allowlist secret
python
import numpy as np NUM_EXP = 1 def evaluate(job_id, params): np.random.seed(NUM_EXP) x = params['X'] y = params['Y'] z = params['Z'] a = params['A'] #print 'Evaluating at (%f, %f, %f, %f)' % (x, y, z, a) obj1 = float(1.10471 * np.power(x,2.0) * z + 0.04811 * a * y * (14.0+z)) + np.rand...
python
class Config: HOST_URL = "https://www.mirrativ.com" USER_AGENT = "MR_APP/8.67.0/Android/GA00747-UK/5.1.1" USER_ME = "/api/user/me" PROFILE_EDIT = "/api/user/profile_edit" FOLLOW = "/api/graph/follow" COMMENT = "/api/live/live_comment" LIVE = "/api/live/live" EDIT_LIVE = "/api/li...
python
import os import torch import numpy as np import pickle from utils import * def hook_fn(m, i, o): try: visualisation[m] = o.cpu().numpy() except AttributeError: visualisation[m] = o[0].cpu().numpy() if __name__=='__main__': with open('./results/cka/act_std.pkl', 'rb') as file: ...
python
# https://leetcode.com/problems/subsets-ii/description/ # # algorithms # Medium (40.24%) # Total Accepted: 173.2K # Total Submissions: 430.4K # beats 100.0% of python submissions class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] ...
python
""" retrieve environment variables and resolve references to AWS Parameter Store Parameters. """ from typing import Dict import os import boto3 def get(name: str, session: boto3.session.Session) -> str: """ gets the environment variable value specified by `name`. if the `value` starts with ssm://, it will...
python
""" A repository of typed entities, retrievable by their external reference Entity object API: entity.entity_type --> string used for groupung entity.external_ref --> lookup name entity.origin --> one-time settable parameter, set by the entity store entity.validate() --> must return True [for valid enti...
python
import bpy from bpy.props import * from ..node_socket import RenderNodeSocket, SocketBase, RenderNodeSocketmixin, RenderNodeSocketInterface from ..node_socket import update_node class RenderNodeSocketInterfaceRenderList(RenderNodeSocketmixin, RenderNodeSocketInterface, bpy.ty...
python
import ocaml assert(ocaml.Result.get_ok(ocaml.Result.Ok(True)) == True)
python
from opera.parser.yaml.node import Node from ..entity import Entity from ..path import Path from ..string import String class ImportDefinition(Entity): ATTRS = dict( file=Path, repository=String, namespace_prefix=String, namespace_uri=String, ) DEPRECATED = { "name...
python
#online = mongodb_online() #print('mongodb-online: ', online) #TODO: cron docker para mongo
python
# -*- coding: utf-8 -*- import json from django.db.models import Q from rest_framework.exceptions import PermissionDenied from rest_framework.generics import ( CreateAPIView, ListCreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import ( AllowAny, I...
python
from django.contrib import admin # Register your models here. from reg.models import UserProfile from .models import * class BookAuthorAdmin(admin.ModelAdmin): list_display = ('author_last_name', 'author_first_name', 'author_middle_name') search_fields = ('author_last_name', 'author_first_name', 'author_middle_name...
python
import numpy as np class ArgMaxPolicy(object): def __init__(self, critic): self.critic = critic def get_action(self, obs): if len(obs.shape) > 3: observation = obs else: observation = obs[None] ## TODO return the action that maxinmizes the Q-v...
python
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. OpenAPI spec version: v2 Contact: devcenter@docusign.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from ppr...
python
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import json import argparse from modules.FIC_Core import FICCore from modules.config import DEFAULT_DAYS, REP...
python
from django import forms from django.contrib.admin import widgets import os CHOICE = { ('0','キュート'), ('1','クール'), ('2','パッション'), } form SampleForm(forms.Form): select = forms.ChoiceField(label='属性', widget=forms.RadioSelect, choices= CHOICE, initial=0)
python
L=[[[*map(int,v.split(','))]for v in l.split('->')]for l in open("inputday5")] r,m=lambda n,x,y:x<=n<=y or y<=n<=x,max(max(max(p)for p in l)for l in L)+1 c=lambda a,b,f,s,w:(r(a,f[0],s[0])and r(b,f[1],s[1])and(f[0]==s[0]or f[1]==s[1]or(w and abs(f[0]-a)==abs(f[1]-b)))) print(*(sum(a)for a in((sum(c(i,j,f,s,b)for f,s in...
python
# Filename: HCm_UV_v5.0.py ##################### ###### IMPORTS ###### ##################### import string import numpy as np import sys #sys.stderr = open('errorlog.txt', 'w') import warnings warnings.filterwarnings("ignore") ####################### ###### FUNCTIONS ###### ####################### #Function for int...
python
__all__ = [ 'apply', 'applyCSS', 'change', 'changeCSS', 'delete', 'forwarddelete', 'insert', 'queryEnabled', 'queryIndeterm', 'queryState', 'querySupported', 'queryValue', 'selection', 'unapply', 'unapplyCSS' ]
python
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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...
python
from Application import Application if __name__ == '__main__': app = Application()
python
# determines whether a matrix is orthogonal. A square matrix is orthogonal, # if its columns and rows are orthogonal unit vectors, # which is equivalent to: MT M = I import numpy as np def check_orthogonal(M): # make sure the input is a matrix if len(np.shape(M)) !=2: print("error: input is not a mat...
python
""" 抽象工厂 代码实例 Abstract Factory Code Demo 家具工厂 """ from __future__ import annotations from abc import ABC, abstractmethod class Chair(ABC): """ product interface 1: Chair """ @abstractmethod def sit_on(self) -> str: pass class Sofa(ABC): """ product interface 2: Sofa """ ...
python
import requests import time import datetime import json import csv # def get(t): # res_text=requests.get('http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=0000011,3990012&sty=CTBFTA&st=z&sr=&p=&ps=&cb=&token=70f12f2f4f091e459a279469fe49eca5').text # data=eval(res_text) # dh=data[0...
python
import socket from socket import * from win32clipboard import * from win32con import * print "ClipCross Alpha" host = "" #Accept connection from any machine. port = 6000 #We will communicate over port 6000 of this machine. Ports 0-1024 are restricted, ports 1025-65535 are n...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import ...
python
import logging from pkg_resources import DistributionNotFound, get_distribution from feast.infra.offline_stores.bigquery_source import BigQuerySource from feast.infra.offline_stores.contrib.spark_offline_store.spark_source import ( SparkSource, ) from feast.infra.offline_stores.file_source import FileSource from ...
python
# -*- coding: utf-8 -*- """ Created on Sun Apr 8 10:41:43 2018 @author: Haosong """ import sys sys.path.append("C:\\CSCI1001_Project\\PrepareData.py") # Replace the thing in the braces above with the current path PrepareData.py is in import PrepareData PrepareData.prepareData()
python
from django.shortcuts import render, get_object_or_404, redirect from rest_framework.views import APIView from rest_framework.response import Response import json from .functions import classify_passenger, load_model class get_classification(APIView): def post(self, request): model = load_model('./api/titanic_...
python
# -*-coding:utf-8-*- from mobpush.model.BasePush import BasePush class IosNotify(BasePush): serialVersionUID = 6316980682876425791 BADGE_TYPE_SET = 1 BADGE_TYPE_ADD = 2 SLIENT = 1 def __init__(self, title=None, subtitle=None, attachment=None, attachmentType=None, mutableContent=N...
python
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from itsdangerous import URLSafeSerializer as URLSafeSerializer def generate_auth_token(secret_key, username, password): serializer = Serializer(secret_key, expires_in=15000) token = serializer.dumps({'username': username, "password": pass...
python
import mlflow from threading import Thread import os import time from sapsan.core.models import ExperimentBackend class MLflowBackend(ExperimentBackend): def __init__(self, name: str = 'experiment', host: str = 'localhost', port: int = 9000): super().__init_...
python
#!/usr/bin/env python3 # Copyright 2019 HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison, WI. # # 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....
python
from core.buckets import BucketExtend from core.sampler import Sampler class LowDiscrepancySampler(Sampler): def __init__(self, bucket_extend: BucketExtend, samples_count: int, shutterOpen: float, shutterClose: float): super().__init__(bucket_extend, samples_count, shutterOpen, shutterClose) ...
python
#!/usr/bin/env python # coding: utf-8 # In[2]: from pathlib import Path import numpy as np import pandas as pd train = pd.read_csv("corpus/imdb/labeledTrainData.tsv", header=0, delimiter="\t", quoting=3) test = pd.read_csv("corpus/imdb/testData.tsv", header=0, delimiter="\t",...
python
# Available debug categories. DEBUG_CATEGORIES = { 'architects': False, 'callbacks': False, 'controllers': False, 'drivers': False, 'emitters': False, 'imap': False, 'managers': False, 'workers': False, 'all': False, } # Default categories for the 'all' keyword. DEBUG_ALL_CATE...
python
class Solution: def sortColors(self, nums): return nums.sort() if __name__ == '__main__': nums = [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] print("Before Sort: ") print(nums) # [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] Solution().sortColors(nums) print("After Sort: ") print(n...
python
#!/usr/bin/env python3 """ Check Lisp examples in a Markdown file. To run (assuming this repo is a submodule in a dir called .cl-make): $ pip3 install -r .cl-make/requirements.txt $ .cl-make/readme.py README.md The return code is zero iff all Lisp examples in the file run without errors in an SBCL REPL and ...
python
#!/usr/bin/python import serial import time import sys if len(sys.argv) != 2: print "Usage: %s <serial port>" % sys.argv[0] sys.exit() def getResponse(): time.sleep(0.25) s = ser.readline() print "RECV: " print s if "NMI:" in s: print "NMI signal received" #sys.exit() ...
python
import cfscrape from flask import request from flask_restplus import Resource, Namespace, fields, abort from Servers.AnimeFLV.scraper import getList, scrapeEpisodeList, scrapeEpisode, scrapeGenre, scrapeGenreList, scrapeFeed, scrapeLastAnimeAdded cfscraper = cfscrape.create_scraper(delay=10) animeflv_api = Namespace(...
python
from threading import Lock from twisted.internet import protocol, reactor class ClientProtocol(protocol.Protocol): def dataReceived(self, data): self.server_protocol.transport.write(data) def connectionLost(self, reason): self.server_protocol.transport.loseConnection() class ClientFactory(...
python
from pathlib import Path from collections import defaultdict import sys TEST_MODE = bool(len(sys.argv) > 1 and sys.argv[1] == "test") CARD = ['E', 'S', 'W', 'N'] DIRECTIONS = [(1,0),(0,1),(-1,0),(0,-1)] ROTATIONS = [(1,0,0,1),(0,-1,1,0),(-1,0,0,-1),(0,1,-1,0)] def phase1(data): pos = [0,0] facing = 0 for...
python
import pytest from rotkehlchen.tests.utils.ethereum import ETHEREUM_TEST_PARAMETERS @pytest.mark.parametrize(*ETHEREUM_TEST_PARAMETERS) def test_get_block_by_number(ethereum_manager): block = ethereum_manager.get_block_by_number(10304885) assert block['timestamp'] == 1592686213 assert block['number'] == ...
python
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved. import os import random import numpy as np import torch def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) os.environ['PYT...
python
# Copyright 2006-2012 Mark Diekhans import re from pycbio.hgdata.autoSql import intArraySplit, intArrayJoin, strArraySplit, strArrayJoin from pycbio.tsv.tabFile import TabFileReader from pycbio.hgdata import dnaOps from pycbio.hgdata.cigar import ExonerateCigar from collections import defaultdict from deprecation impor...
python
from pydantic import BaseSettings class Settings(BaseSettings): MONGO_URI: str = "mongodb://localhost:27017/" APP_DB: str = "ultraapp" JWT_SECRET: str = "S3CR3T" # jwt secret JWT_LIFETIME: int = 3600 * 24 settings = Settings()
python
import time from typing import List class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if not stack: stack.append(token) if token in {'+', '-', '*', '/'}: y = stack.pop() x = stack.pop...
python
""" Create an OpenVINO model package to upload to Azure Blob Storage and use IoT Hub module update twin to update the Azure Percept AzureEyeModule. """ import argparse import os import json import zipfile import datetime from azure.storage.blob import ( BlockBlobService, BlobPermissions, ) from azure.iot.hub im...
python
EPSILON = 0 UNICODE_LATIN_START = 32 UNICODE_LATIN_END = 127 SEEK_RULE = 1 SEEK_RULE_NAME = 2 SEEK_ST_COLON = 3 SEEK_ND_COLON = 4 SEEK_EQUALS = 5 SEEK_ST_PROD = 6 SEEK_ST_TERM = 7 SEEK_ST_NTERM = 8 SEEK_ST_ESC = 9 SEEK_PROD = 10 SEEK_TERM = 11 SEEK_NTERM = 12 SEEK_ESC = 13 SEEK_SPECIAL_TERM = 14 SEEK_SPECIAL_NTERM = ...
python
''' Script to do analysis ''' import argparse import logging import time import torch import transformers import itertools from collections import defaultdict from models import MTModel # Use with care: logging error only while printing analysis for reading sanity transformers.utils.logging.set_verbosity_error() de...
python
from __future__ import annotations import numpy as np from PySide2.QtCore import QPoint, QRect from PySide2.QtWidgets import QMdiSubWindow class DataViewerSubWindow(QMdiSubWindow): def __init__(self, viewer: DataViewer): super().__init__() self.viewer = viewer self.layout_anchors = None...
python
class AMQPError(Exception): message = 'An unspecified AMQP error has occurred: %s' def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.message % self.args) # Backward compatibility AMQPException = AMQPError class AMQPConnectionError(AMQPError): message = 'Connection can not ...
python
import sys import time from collections import deque from datetime import timedelta from rich import get_console from rich.progress import BarColumn, Progress, ProgressColumn, SpinnerColumn, TextColumn class TimeRemainingColumn(ProgressColumn): """Renders estimated time remaining.""" # Only refresh twice a ...
python
import arcpy arcpy.env.overwriteOutput = True # Note: Script assumes data from Pro SDK community samples are installed under C:\Data, as follows: inFC = r"E:\GISTech\2021\ProProjects\PythonUsage\PythonUsage.gdb\FCL_Lijn" outFC = r"E:\GISTech\2021\ProProjects\PythonUsage\PythonUsage.gdb\ViaScript" # Buffer the input f...
python
# -*- coding: utf-8 -*- from bitshares import BitShares from bitshares.instance import set_shared_bitshares_instance from bitshares.amount import Amount from bitshares.price import Price from bitshares.asset import Asset import unittest class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): ...
python
from ._version import VERSION from ._chat_client import ChatClient from ._chat_thread_client import ChatThreadClient from ._generated.models import ( SendChatMessageResult, ChatThreadInfo, ChatMessageType ) from ._shared.user_credential import CommunicationTokenCredential from ._shared.user_token_refresh_op...
python
from django.test import TestCase from wagtailmenus.conf import constants from wagtailmenus.models import MainMenu from wagtailmenus.tests import base, utils Page = utils.get_page_model() class MainMenuTestCase(TestCase): """A base TestCase class for testing MainMenu model class methods""" fixtures = ['test...
python
""" Receba a altura do degrau de uma escada e a altura que o usuário deseja alcançar subindo a escada. Calcule e mostre quantos degraus o usuário deverá subir para atingir o seu objetivo. """ a = float(input('Qual é a altura do degrau da escada (cm)? ')) ab = float(input('Qual é a altura que você deseja alcançar subin...
python
import numpy as np from netCDF4 import Dataset from .utils import popEntries,setDimensions from .OBSstruct import OBSstruct import pandas as pd def remove_duplicates(S, coordinate = 'fractional'): ''' This function identifies duplicated observations and makes sure all observation on output are unique. ...
python
import matplotlib.pyplot as plt import csv import random import numpy as np import math import matplotlib.patches as patches data = {} with open('datasets/data_boston.csv', 'r') as csvfile: csvfile.readline() file = csv.reader(csvfile, delimiter=',') for row in file: if data.has_key(row[5]): data[row[5]].appe...
python
#!/usr/bin/python #coding:utf-8 import os import re import string import linecache import shutil #Get file name from given directory directoryPath = os.getcwd() #directoryPath2 = os.getcwd() + '\\New' file_extension = ".md" if __name__ == '__main__': for fileName in os.listdir(directoryPath): if(fileName...
python
from .point_cloud import PointCloud, PointCloudMeta, PointCloudSpatial # noqa
python
def empty_graph(n): res = [] for i in range(n): res.append([0]*n) return res def convert(graph): matrix = [] for i in range(len(graph)): matrix.append([0]*len(graph)) for j in graph[i]: matrix[i][j] = 1 return matrix def prims_algo(graph): graph1 = conver...
python
# # customization fragment to run L1 GT emulator starting from a RAW file # # V.M. Ghete 2010-06-09 import FWCore.ParameterSet.Config as cms def customise(process): # # (re-)run the L1 GT emulator starting from a RAW file # from L1Trigger.Configuration.L1Trigger_custom import customiseL1GtEmulat...
python
""" Overview: Useful functions for build representation format of object. """ from typing import List, Tuple __all__ = [ 'get_repr_info', ] def get_repr_info(cls: type, args: List[Tuple]) -> str: """ Overview: Get representation information for object. Can be used in ``__repr__`` meth...
python
# -*- Mode: Python; tab-width: 4 -*- # Copyright (c) 2005-2010 Slide, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyrig...
python
from bnop_source.b_code.bnop_facades import BnopFacades from bnop_source.b_code.core.object_model.bnop_repositories import BnopRepositories from bnop_source.b_code.core.object_model.objects.bnop_objects import BnopObjects from boro_common_source.ckids.boro_object_ckids import BoroObjectCkIds from nf_common_source.code....
python
""" Unit tests for flat_file.py See: https://code.visualstudio.com/docs/python/testing """ import unittest from cred_manage.flat_file import FlatFileCredContainer import os FLAT_FILE_THAT_EXISTS='/tmp/file_that_exist.txt' FLAT_FILE_THAT_DOES_NOT_EXIST='/tmp/file_that_not_exists.txt' def setUpModule(): """ ...
python
from marshmallow import fields, validate from app import ma from nfmanagementapi.models import FilterRule class FilterRuleSchema(ma.SQLAlchemyAutoSchema): class Meta: model = FilterRule ordered = True uuid = fields.UUID(required=True, description="Unique Identifier", dump_only=True) n...
python
import sys import Adafruit_DHT import Adafruit_BMP.BMP085 as BMP085 import requests def getReadings(): humidity, dht_temp = Adafruit_DHT.read_retry(22, 4) if humidity is not None and dht_temp is not None: bmp_sensor = BMP085.BMP085() pressure = bmp_sensor.read_pressure() bmp_temp = bmp_...
python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 ...
python
import bug_killer_client.network.project as project_client from bug_killer_api_interface.schemas.request.project import CreateProjectPayload, UpdateProjectPayload from bug_killer_api_interface.schemas.response import UserProjectsResponse, ProjectResponse async def get_user_projects(auth: str) -> UserProjectsResponse:...
python