content stringlengths 5 1.05M |
|---|
# Copyright 2014 Mellanox Technologies, 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 agreed t... |
import requests
import datetime as dt
USERNAME = "nurmatthias"
TOKEN = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
GRAPH_ID = "graph-coding"
HEADERS = {
"X-USER-TOKEN": TOKEN
}
PIXELA_ENDPOINT = "https://pixe.la/v1/users"
GRAPH_ENDPOINT = f"{PIXELA_ENDPOINT}/{USERNAME}/graphs"
create_user = {
"token": TOKEN,
"u... |
class DoppelTestError:
def __init__(self, msg: str):
"""
Custom error class used for testing issues.
:param msg: Error text to print
"""
self.msg = msg
def __str__(self):
return("{}\n".format(self.msg))
|
from datetime import datetime
from pathlib import Path
# noinspection SpellCheckingInspection
class ResultLogger:
def __init__(self, log_file_path: Path):
self.log_file_path = log_file_path
self.file = None
self.start_time = None
@staticmethod
def __format_hyperparams(batch_size, e... |
# Author: Shengjia Yan
# Date: 2018-04-08 Sunday
# Email: i@yanshengjia.com
# Time Complexity: O(1)
# Space Complexity: O(1)
class Solution:
"""
@param A: An integer array
@param index1: the first index
@param index2: the second index
@return: nothing
"""
def swapIntegers(self, A, index1, ... |
"""Views for the ``conversation`` app."""
import collections
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, HttpResponseRedirect
from dj... |
"""
Profile data model.
"""
import pathlib
from e4s_cl import logger
from e4s_cl.error import ProfileSelectionError
from e4s_cl.mvc.model import Model
from e4s_cl.mvc.controller import Controller
from e4s_cl.cf.storage.levels import USER_STORAGE
LOGGER = logger.get_logger(__name__)
def attributes():
return {
... |
import pytest
from slimer.list_serializer import serialize
from slimer.list_serializer import ListSerializer
@pytest.fixture
def data():
return []
def testNullListSerialize(data):
assert "[000000:]" == serialize(data)
def testOneItemListSerialize(data):
data.append("hello")
assert "[000001:000005... |
import logging
from django.utils.functional import LazyObject
class LazyMetrics(LazyObject):
def _setup(self):
from kaneda import Metrics
from kaneda.utils import import_class, get_object_from_settings
from kaneda.exceptions import UnexistingKanedaClass, SettingsError
from . impo... |
from rest_framework import viewsets
from .models import TerminationRequest
from .serializers import TerminationRequestSerializer
class TerminationRequestViewSet(viewsets.ModelViewSet):
queryset = TerminationRequest.objects.all()
serializer_class = TerminationRequestSerializer
|
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** 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, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = [
'Ku... |
import os
import subprocess
import time
from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
MAJOR = 0
MINOR = 1
PATCH = 'rc0'
SUFFIX = ''
SHORT_VERSION = '{}.{}.{}{}'.format(MAJOR, MINOR, PATCH, SUFFIX)
version_f... |
# -*- coding: utf-8 -*-
"""
ImageDataExtractor
~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
__title__ = 'ImageDataExtractor'
__version__ = '0.0.1'
__author__ = 'Karim ... |
import goslate
import emoji
from emoji import get_emoji_regexp
from userbot.events import register
@register(outgoing=True, pattern="^.gs(?: |$)(.*)")
async def _(event):
if event.fwd_from:
return
if "trim" in event.raw_text:
# https://t.me/c/1220993104/192075
return
input_str = ev... |
from tir import Webapp
import unittest
class TMSA200(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGATMS','07/10/2019','T1','M SP 01 ','43')
inst.oHelper.Program('TMSA200')
def test_TMSA200_CT007(self):
self.oHelper.SearchBrowse("M SP 000086")
se... |
# Generated by Django 2.1.7 on 2019-02-15 14:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("forum", "0001_initial")]
operations = [
migrations.AddField(
model_name="forummodel",
name="menu_title",
field=models... |
import copy
from typing import List
import cv2
import numpy as np
from simple_object_detection.object import Object
from simple_object_detection.typing import Point2D, Image, BoundingBox
from simple_object_tracking.datastructures import TrackedObjects
def apply_homography_point2d(point: Point2D, h: np.ndarray) -> P... |
import uvicorn
from galaxy_main import (
GalaxyConfigBuilder,
main,
)
from galaxy.util.properties import load_app_properties
from galaxy.webapps.galaxy.buildapp import app_factory
from galaxy.webapps.galaxy.fast_app import initialize_fast_app
def wsgiloop(args, log):
config_builder = GalaxyConfigBuilder(... |
import os
import subprocess
import shutil
from enum import Enum
from importlib import import_module
from PlatformIndependent.pyValidation import PythonConfiguration as PythonRequirements
PythonRequirements.Validate()
colorama = import_module("colorama")
colorama.init()
class OutputLevel(Enum):
def INFO(x): retu... |
# https://programmers.co.kr/learn/courses/30/lessons/43162
# 네트워크
from collections import deque
def solution(n, computers):
answer = 0
global isVisited
isVisited = [0] * n
for i in range(n):
if isVisited[i] == 0:
answer+=1
isVisited[i] = 1
def dfs(node):
... |
#!/usr/bin/env python3
# from __future__ import print_function
import math
import os
import subprocess
import sys
def main():
trueAssembly = open(sys.argv[1]).readlines()
assembly = sys.argv[2]
verbose = True if len(sys.argv) == 4 and sys.argv[-1] == "verbose" else False
read = []
for line in tru... |
"""
Django settings for PenL_backend project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os... |
#!/usr/bin/env python3.10
import os
import os.path
import shutil
import socket
import stat
import subprocess
import tempfile
import unittest
import lscolors
class TempDirTestCase(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self... |
from django.test import TestCase
from data_facility_admin.models import *
from data_facility_admin.helpers import LDAPHelper
import mock
from mockldap import MockLdap
from django.conf import settings
import ldap
from django.utils import timezone
import datetime
class BaseLdapTestCase(TestCase):
USER_LDAP_ID = Lda... |
""" Module provides functions for querying Quantity Objects """
from models.core.quantity import Quantity
from operations import query_session
def by_id(quantity_id):
""" Get Quantity by its id """
session = query_session.get_session()
return session.query(Quantity).filter(Quantity.id == quantity_id).fi... |
import argparse
from .benchbot_supervisor import Supervisor, DEFAULT_PORT
if __name__ == '__main__':
# Parse all supported arguments
p = argparse.ArgumentParser(description="Runs the BenchBot Supervisor.")
p.add_argument('--port',
help="Supervisor port number (default: 10000)",
... |
import sys
import functools
from ..el.accounts import auth, records, relations
from ..el.accounts.profile import profile
from ..el import posts, images
from ..el.misc import utils
from .. import consts
from . import api, accounts
from bottle import request, redirect, response, abort
__all__ = ['index', 'sign_in', 'si... |
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from .models import Water
def water_list(request):
waters = Water.objects.all()
return render(request, 'watertracking/home.html', {'waters': waters})
@require_http_methods(['PUT'])
def water_drunk(request, ... |
#
# A simple endpoint that can receive documents from an external source, mark them up and return them. This can be useful
# for hooking in callback functions during indexing to do smarter things like classification
#
from flask import (
Blueprint, request, abort, current_app, jsonify
)
import fasttext
import json... |
# -*- coding: utf-8 -*-
"""
celery.backends.rediscluster
~~~~~~~~~~~~~~~~~~~~~
Redis cluster result store backend.
CELERY_REDIS_CLUSTER_BACKEND_SETTINGS = {
startup_nodes: [{"host": "127.0.0.1", "port": "6379"}]
}
"""
from __future__ import absolute_import
from functools import partial
f... |
import numpy as np
import os
DataPath = os.path.dirname(__file__)+"/__data/"
MatrixPath = DataPath + "matrices/"
|
# Script Name: DinfReverseAccumulation
#
# Created By: David Tarboton
# Date: 9/29/11
# Import ArcPy site-package and os modules
import arcpy
import os
import subprocess
# Inputs
inlyr = arcpy.GetParameterAsText(0)
desc = arcpy.Describe(inlyr)
ang=str(desc.catalogPath)
arcpy.AddMessage("\nInput D-Infinity Flo... |
import boto3
class S3Handler:
"""
Interface for interacting with an S3 Bucket.
"""
def __init__(self, bucket):
self.s3 = boto3.resource('s3')
self.s3_client = boto3.client('s3')
self.s3_bucket = self.s3.Bucket(bucket)
def store_content_in_s3(self, obj_key: str, content: s... |
from pyenv.main import env |
from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
import random
import itertools
doc = """This application provides a survey and introductions based on the answers of the survey."""
class Constants(BaseConstants):
name_in_url = '... |
from datetime import datetime
from django.contrib.admin.sites import AdminSite
from django.db import models
from django.test.client import RequestFactory
from nose.tools import eq_
from shared.tests import ModelsTestCase
from stats.monkeypatches import patch as patch_admin
from stats.options import ModelStats
from s... |
"""
Django settings for chipseqbot project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
from __future__ import absolute_import
from .base import *
import os
... |
# -*- coding: utf-8 -*-
# stdlib imports
import subprocess
import re
import sys
# third-party imports
import pytest
import toml
HISTKEY = "black/mtimes"
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption(
"--black", action="store_true", help="enable format checking wi... |
# -*- coding: utf-8 -*-
import zipfile
def unzip(filename, folder=None):
"""unzip zip file"""
zip_file = zipfile.ZipFile(filename)
for names in zip_file.namelist():
zip_file.extract(names, folder)
zip_file.close()
|
from numpy.typing import ArrayLike
import puzzle_1
def find_synchronisation_step(starting_state: ArrayLike) -> int:
"""Find the first step after which all octopuses flash together."""
n_steps = 0
state = starting_state
while state.sum() > 0:
n_steps += 1
state, _ = puzzle_1.progre... |
import pytest
from demisto_sdk.commands.common.hook_validations.script import ScriptValidator
from demisto_sdk.commands.common.hook_validations.structure import \
StructureValidator
from mock import patch
def get_validator(current_file=None, old_file=None, file_path=""):
with patch.object(StructureValidator, ... |
# Scan an Apple header file, generating a Python file of generator calls.
import sys
import os
from bgenlocations import TOOLBOXDIR, BGENDIR
sys.path.append(BGENDIR)
from scantools import Scanner
LONG = "QuickTime"
SHORT = "qt"
OBJECTS = ("Movie", "Track", "Media", "UserData", "TimeBase", "MovieController")
def main... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from past.builtins import basestring
import logging
import http.cookiejar
from flexget import plugin
from flexget.event import event
from flexget.utils.tools import TimedD... |
import markdown
import subprocess
import os
from modules import mylogger as ml
import jinja2
from pathlib import Path
class ReportMaker():
def __init__(self,base_path="results/",file="report.html"):
self.base_path = base_path
self.file = file
self.filename = os.path.join(self.base_path,self... |
import ccxt
import ast
import requests
#import webhook_bot
import datetime
from database import db
import json
import time
import pymongo
import pandas as pd
from historicdownloader import historic,datamanagement,drop_data
from technical import qtpylib
import chart_studio.plotly as py
import plotly.graph_objs as go
fro... |
# Version: 2020.02.21
#
# MIT License
#
# Copyright (c) 2018 Jiankang Deng and Jia Guo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitatio... |
#Copyright (C) 2008 Codethink Ltd
#Copyright (C) 2010 Novell, Inc.
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License version 2 as published by the Free Software Foundation.
#This program is distributed in the hope that it will be useful... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 28 18:52:37 2020
@author: nww73
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
if __name__ == '__main__':
df_train = pd.read_csv("data/train.csv", engine='c')
df_t... |
import os
import socket
import struct
import sys
# Python 2 / 3 checks
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
# Blacknet Message Types between server and client.
class BlacknetMsgType:
HELLO = 0
CLIENT_NAME = 1
SSH_CREDENTIAL = 2
SSH_PUBLICKEY = 3
PING ... |
import sys
import os
import pyttsx3
from PyQt5.QtWidgets import (
QApplication,
QWidget,
QPlainTextEdit,
QPushButton,
QVBoxLayout,
QHBoxLayout,
QFileDialog,
QLabel,
QSlider,
)
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtMultimedia import QMediaPlayer... |
from os import path
import json
NODE_CORE_MODULES = {
'assert',
'assert/strict',
'async_hooks',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'dns/promises',
'domain',
'events',
'fs',
'fs/promises',
'http',
... |
import json
# Descarga esta librería con el comando 'pip install json2html'
from json2html import *
class Usuario(object):
'''
Esta función inicializa la clase cuando se instancia
'''
def __init__(self, **args):
self.nombre = args.get('nombre')
self.edad = args.get('edad')
self.... |
from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import thread_add_ipxact
expected_verilog = """
module test;
reg CLK;
reg RST;
reg [32-1:0] saxi_awaddr;
reg [4-1:0] saxi_awcache;
reg [3-1:0] saxi_awprot;
reg saxi_awvalid;
wire saxi_awready;
reg [32-1:0] s... |
from keras.models import load_model
from keras.utils.vis_utils import plot_model
model = load_model("decoder.h5")
plot_model(model, to_file="model.png", show_shapes=True)
|
#!/usr/bin/env python
# coding=utf-8
from Queue import Empty, Queue
from multiprocessing.pool import Pool
from threading import RLock
import json, sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../backend_server')))
from JSONManager import createOverviewRequest, createFullListRequ... |
import jsonschema
from schemas.user_schema import *
from flask import jsonify, Response, request, json
from models.user_model import User
from messages.error_messages import *
def get_users():
return_value = jsonify({'users': User.get_all_users()})
return return_value
def get_by_username(username):
res... |
import re
import os
import logging
import aiohttp
import asyncio
from cozytouchpy import CozytouchClient
from cozytouchpy.constant import USER_AGENT
from cozytouchpy.exception import (
AuthentificationFailed,
CozytouchException,
HttpRequestFailed,
HttpTimeoutExpired,
)
from datadog_checks.base import ... |
from django.urls import path
from counselorchange import views
# Url paths of the website with naming
urlpatterns = [
path('', views.contact_us, name='ch-contactus'),
]
|
import os
import sys
from workflow import Workflow3
from toolchain import run_script
from commands import CMD_DUMP_STACK
mod = os.getenv('function')[11:]
class Activity():
def __init__(self, name, package, affinity=None):
self.name = name
self.package = package
self.affinity = affinity
... |
# Copyright(c) 2007-2009 by Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of PyCha.
#
# PyCha is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License,... |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.piratesgui.SheetFrame
from pirates.piratesgui import ListFrame
from pirates.piratesgui import PiratesGuiGlobals
class SheetFram... |
print('Hello, World.')
print(input())
|
# -*-coding:utf8-*-
"""
author:zhiyuan
date:20190310
use lr model to check the performance in test file 使用训练好的LR模型,在测试数据里检验效果
准确率:
假设样本实际label为 1 0 1 0 1
通过LR模型估计label为 0 1 0 0 1
此时准确率为:2/5
AUC 表明了模型对样本预测的一种序关系(在点击率预测中,我们不是判断具体样本是正样本还是负样本,而是只要得出样本的概率大小的排序,
取排序靠前的topN推荐即可,所以点击率预估中... |
"""
Parameters for spike initiation simulations.
"""
from brian2.units import *
# Passive parameters
EL = -75*mV
S = 7.85e-9*meter**2 # area (sphere of 50 um diameter)
Cm = 0.75*uF/cm**2
gL = 1. / (30000*ohm*cm**2)
Ri = 150*ohm*cm
# Na channels
ENa = 60*mV
ka = 6*mV
va = -40*mV
gNa = gL * 2*S
taum = 0.1*ms
|
# --------------
# Importing header files
import numpy as np
import pandas as pd
from scipy.stats import mode
import warnings
warnings.filterwarnings('ignore')
#Reading file
bank_data = pd.read_csv(path)
#Code starts here
categorical_var=bank_data.select_dtypes(include="object")
print(categorical_... |
"""
Power Switch Over Supercap Module
"""
import logging
import queue
from . import INPUT_LIST_KEY_PIN_NUMBER, RUNNING_ON_PI
if RUNNING_ON_PI: # pragma: no cover
import RPi.GPIO as GPIO
PSO_COMMAND_PSO = "PSO"
class PSO:
def __init__(self, input_list=None, thread_lock=None, que=None):
self._input_l... |
"""Make sure the service launches correctly"""
import platform
from io import BytesIO
from pathlib import Path
from flask import url_for
from flask.testing import FlaskClient
def test_launch(client):
res = client.get(url_for('home'))
assert res.status_code == 200
assert platform.node() in res.data.decod... |
from classes import Graph, Queue, PriorityQueue
from graph_init import graph, weights, heuristic
def a_star_search(graph, start, goal):
searchFrontier = PriorityQueue()
searchFrontier.put(start, heuristic[start])
currentCost = {}
currentCost[start] = 0
path = ""
while not searchFrontier.empty... |
import pybind11module
import time
pybind11module._inst.seed(3141592654)
nqs = pybind11module.Nqs(n_visible=20)
ising1dsymmetric = pybind11module.Ising1dSymmetric(nqs=nqs)
metropolis_hastings = pybind11module.MetropolisHastings(nqs=nqs, operator=ising1dsymmetric)
tic = time.time()
metropolis_hastings.run()
print("time... |
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E07000125"
addresses_name = (
"local.2018-05-03/Version 1/Democracy_Club__03May2018 Rossendale.tsv"
)
stations_name = (
"local.2018-05-03/... |
from __future__ import absolute_import, print_function, unicode_literals
# Use this this to preconfigure "register_compatibility_fixer" for a set of fixers
from functools import partial
from ..deprecation import *
from ..registry import register_compatibility_fixer
@register_compatibility_fixer(
fixer_refer... |
import torch
import numpy as np
import sys, copy, math, time, pdb
import pickle
import scipy.io as sio
import scipy.sparse as ssp
from sklearn.model_selection import KFold
import os.path
import random
import argparse
from SEAL import util_functions
from pytorch_DGCNN import main
from main import *
import matplotlib
imp... |
from sqlalchemy import select, delete,update
from sqlalchemy.orm import Session, query
from src.schema import schemas
from src.infra.sqlalchemy.models import models
class RepositorioEmpresa():
def __init__(self, session: Session):
self.session = session
def cadastrar(self, empresa: schemas.Empresa):
... |
import pandas as pd
def load_predictions(filepath):
predictions = pd.read_csv(
filepath, index_col=0, parse_dates=True, infer_datetime_format=True
).assign(alarm=lambda df: df["alarm"].astype(bool))
freq = pd.infer_freq(predictions.index)
return predictions.asfreq(freq)
def load_simulations(... |
import envia #envia.py
import os.path as path
import requests
link = "https://ptin2018.herokuapp.com/api/devices/"
# Funcion para registrar y guardar en el archivo .dades, los datos de registro,
# tambien se envia a la funcion en envia.py llamada registra()
def registra():
nom = raw_input("nom: ")
tipus = raw_inpu... |
import pytest
import inspect
import random
import magma as m
from common.genesis_wrapper import GenesisWrapper
from common.generator_interface import GeneratorInterface
TOP = "test_run_genesis"
INFILES = ["test_common/test_run_genesis.vp"]
PARAMS = {
"width": 16,
}
INTERFACE = GeneratorInterface()\
.register(... |
import argparse
import os, sys
import shutil
import time
import numpy as np
import os
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.trans... |
import torch
import numpy as np
from numpy.random import shuffle
IGNORE_INDEX = -100
class DataIteratorPack(object):
def __init__(self, features, example_dict,bsz, device, sent_limit, entity_limit,
entity_type_dict=None, sequential=False, max_seq_len=512):
self.bsz = bsz # batch_size
... |
from flask import request, make_response, render_template
from xml.etree import ElementTree
from model import db, Members, app
# open like.xml
tree = ElementTree.parse("like.xml")
like = tree.getroot()
@app.route("/", methods=["GET", "POST"])
def index():
csong = like.findall("work")[0].text
sss = like.findall("wor... |
#%%
import networkx as nx
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%%
import seaborn as sns
from networkx.generators import (
connected_watts_strogatz_graph,
barabasi_albert_graph,
stochastic_block_model,
)
from src.features import (
avg_clustering_coefficient,
avg_s... |
import pandas as pd
import sklearn
from sklearn.isotonic import IsotonicRegression
from toolz import curry
from fklearn.common_docstrings import learner_pred_fn_docstring, learner_return_docstring
from fklearn.types import LearnerReturnType
from fklearn.training.utils import log_learner_time
@curry
@log_learner_tim... |
""" Sample system controller """
from kervi.controllers.controller import Controller
from kervi.values import BooleanValue
from kervi.actions import action, Actions
class SystemController(Controller):
def __init__(self):
Controller.__init__(self, "systemController", "System")
self.type = "s... |
class Solution(object):
def XXX(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == '':
return 0
haystack = list(haystack)
needle = list(needle)
length = len(needle)
for i in ra... |
import io
import json
from google.cloud import vision
from google.cloud.vision import types
from pymongo import MongoClient
import collections
clientMongo = MongoClient('mongodb://localhost:27017/')
db = clientMongo['GoogleVision']
collection = db['ResultsExpressions']
client = vision.ImageAnnotatorClient()
file_n... |
from django.contrib import admin
# Register your models here.
from monitor.models import Client
admin.site.register(Client)
|
import sys
import cmds
import chatfetcher
def main():
if len(sys.argv) != 2:
print("usage: python3 main.py youtubeVideoID")
return
fetcher = chatfetcher.FetchTube(sys.argv[1])
for comment in chatfetcher.get_comments(fetcher):
print(comment)
cmd = cmds.get_command(comment)
if cmd:
cmd()
if __name__ == ... |
# -*- coding: utf-8 -*-
from pyramid.path import (
DottedNameResolver
)
from zope.interface import Interface
from pyramid_urireferencer import protected_resources
from .referencer import Referencer
from .renderers import json_renderer
class IReferencer(Interface):
pass
def includeme(config):
"""this f... |
"""
Active distribution network management with multiple micro-grids
This is for test of the single-period operation of distribution systems
@author:Zhao Tianyang
@e-mail:zhaoty@ntu.edu.sg
"""
|
# calculate scale and plot individual graphs.
from geopy.distance import geodesic
import pandas
import pickle
import matplotlib.pyplot as plt
locations = ['nz', 'uk']
# make empty dictionaries to populate with imported lat/long data
lats = {}
longs = {}
# import lats and longs from saved csv files
for i in locati... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 25 11:08:48 2018
filter functions for the isobaric gcm
@author: hanbre
"""
import numpy as np
from numba import jit
#filter functions
def polar_fourier_filter(psi):
return psi
def filter_4dx_components(psi):
#filter meridional components
... |
#Copyright 2015 MathWorks, Inc.
"""
MatlabFuture: The class name of a future handle returned by starting MATLAB
asynchronously.
An instance of MatlabFuture is returned from the invocation of starting MATLAB
asyncronously. The future handle serves as a placeholder of the actual MATLAB
instance, the the future handle... |
from fastapi import APIRouter
from app.api.routes import admin, authentication, flashcard, register, user
api_router = APIRouter()
api_router.include_router(
admin.router
)
api_router.include_router(
authentication.router,
)
api_router.include_router(
flashcard.router,
)
api_router.include_router(
registe... |
#
# Copyright (c) 2008-2015 Citrix Systems, Inc.
#
# 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 l... |
import redistrib
from flask import render_template, abort, request, g
from app.bpbase import Blueprint
from app.utils import json_response
from app.render_utils import f_strftime
from models.base import db
import models.node
import models.task
bp = Blueprint('task', __name__, url_prefix='/task')
@bp.before_request
... |
#!/usr/bin/env python3
# The MIT License (MIT)
#
# Copyright (c) 2017 Kaede Hoshikawa
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
# Найти координаты точки пересечения прямых заданных уравнениями a1x+b1y+c1=0 и
# a2x+b2y+c2=0, либо сообщить совпадают, параллельны или не существуют.
# Вводятся координаты прямых
A1 = float(input("Введите A1 ... |
#########################################################################
# This file is a copy from
# https://github.com/cornellius-gp/gpytorch/blob/master/examples/LBFGS.py
# DO NOT CHANGE THE CONTENT
#########################################################################
import torch
import numpy as np
import ma... |
from django.db import models
from django.db import models
from django.db.models import signals
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group, Permission
from django.core.exceptions import ObjectDoesNotExist
from model_utils.fi... |
# trinket.settings.testing
# Testing settings to enable testing on Travis
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Fri Sep 12 16:18:38 2014 -0400
#
# Copyright (C) 2015 District Data Labs
# For license information, see LICENSE.txt
#
# ID: testing.py [] bbengfort@districtdatalabs.com ... |
#!/usr/bin/python
from Solution import Solution
obj = Solution()
#A = [1,1,1,2,2,3]
#A = [0,0,1,1,1,1,2,3,3]
#A = [1, 1, 1, 1]
A = [1]
print(obj.removeDuplicates(A)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.