content stringlengths 5 1.05M |
|---|
"""
update date: 2021/09/24
Author: Xu Chenchen
content: 1. download_pdf()中,在GET请求前确保url没有转义字符
update date: 2021/08/05
Author: Xu Chenchen
content: 1. 修改了主函数的示例,导入version2的xpath筛选模块
2. 下载的pdf文件可以自主确定文件路径(新增功能)
"""
import requests
from urllib.robotparser import RobotFileParser
import time
from urllib.parse imp... |
#!/usr/bin/env python3
import csv
import logging
import argparse
from pathlib import Path
from fast_forward.ranking import Ranking
from fast_forward.index import InMemoryIndex, Mode
from fast_forward.encoder import TransformerQueryEncoder, TCTColBERTQueryEncoder
LOGGER = logging.getLogger(__name__)
def main():
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 16 11:40:46 2019
@author: msr
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import glob
files_snoring = list(glob.glob("snoring_test_data/*.csv"))
files_snoring.sort()
test_file_snoring = fil... |
import json
import time
from rest_framework import status
import api
from api.models import House, Note
__author__ = 'schien'
from rest_framework.test import APITestCase, APIRequestFactory, force_authenticate
from django.core.urlresolvers import reverse
from api.tests.constants import house_serializer_id_field
fr... |
# BSD LICENSE
#
# Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
# 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 copy... |
from typing import List
import pandas
from pathlib import Path
from xfeat import SelectCategorical, ConcatCombination, LabelEncoder, Pipeline, SelectNumerical
def read_df(root_dir:str, path:str, categorical_cols:List[str], exclude_cols:List[str]=["imp_time"]):
df = pandas.read_csv(Path(root_dir, path))
df = d... |
# coding: utf-8
from __future__ import absolute_import, division, print_function
import logging
class Message(object):
token = ""
team_id = ""
channel_id = ""
channel_name = ""
timestamp = 0
user_id = ""
user_name = ""
# raw text
text = ""
# parsed text
args = []
comm... |
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def countLess(nums, x):
ret = 0
for num in nums:
if num <= x:
ret += 1
return ret
length = len(nu... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 07:46:43 2018
@author: jhodges
"""
import h5py
import numpy as np
import glob
import skimage.measure as skme
import matplotlib.pyplot as plt
def writeConstH5(name,elevImg,canopyImg,canopyHeightImg,canopyBaseHeightImg,fuelImg):
hf = h5py.File(name,'w')
hf.crea... |
import os
print("path = ",os.getcwd())
files = []
for x in os.listdir():
if ('.zip' in x):
files.append(x)
count = len(files)-1
if count < 10 :
os.rename(os.getcwd()+"\\"+files[-1],os.getcwd()+"\\"+str(count).zfill(2)+'-'+files[-1])
else:
files[-1] = str(count)+'-'+files[-1]
os.r... |
import click
from OpenSSL import crypto
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
from consul_kube.lib.color import debug, info, color_assert
from consu... |
"""Tools for managing evaluation contexts. """
from sympy.utilities.iterables import dict_merge
from sympy.polys.polyutils import PicklableWithSlots
__known_options__ = set(['frac', 'gens', 'wrt', 'sort', 'order', 'domain',
'modulus', 'gaussian', 'extension', 'field', 'greedy', 'symmetric'])
__global_options__ =... |
from django.apps import AppConfig
from django.conf import settings
import tensorflow as tf
import os
class LstmConfig(AppConfig):
name = 'lstm'
model = tf.keras.models.Sequential([
tf.keras.layers.Lambda(lambda x: x * 0.1,
input_shape=[None,6]),
tf.keras.layers.Conv1... |
BIG_ENDIAN = ">"
LITTLE_ENDIAN = "<"
|
"""
msort is the library backing the mediasort.py command line tool
"""
__version__ = "2.0"
class MSortError(Exception):
"""
Generic msort based error
"""
pass
|
#!/usr/bin/python
import sys
from os.path import join,exists,dirname
import random
import numpy as np
from numpy.random import randint, choice
from sklearn.datasets import load_svmlight_file
from torch.autograd import Function, Variable
import torch.nn as nn
import torch.optim as optim
import torch
from torch import F... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Tags set to None of False will be ignored
# Tags set to True will be used as-is
# Tags set to a string will be replaced by that string
# Tags set to a list will be replaced with multiple tags
from __future__ import unicode_literals
TAGS_MAP = {u'1:2000': None,
u'1:5000': No... |
import heapq
if __name__ == '__main__':
candidates =[2,3,6,7]
target = 7
res = []
resList = []
heapq.heappop()
def backtracking(start, rest):
if rest == 0:
temp = resList[:]
res.append(temp)
for i in range(start, len(candidates)):
if (candi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-18 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK
"""
Capture photo with picamera and display it on a screen.
Requires picamera to be installed.
"""
import io
import sys
import time
from PIL import Image
from l... |
from __future__ import annotations
from dials_algorithms_background_ext import * # noqa: F403; lgtm
__all__ = ("RadialAverage", "set_shoebox_background_value") # noqa: F405
|
from yann.modules.conv.utils import get_same_padding
def test_get_same_padding():
assert get_same_padding(3) == 1
assert get_same_padding(5) == 2
assert get_same_padding(7) == 3
|
"""Colors"""
white_ambiance_luminaires = {
'concentrate': 233,
'default': 367,
'energize': 156,
'reading': 346,
'relax': 447,
}
"""light recipes"""
|
MAPS = {
'30x30':['SFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
'FFFFFFFFFFFFFFFFFFFFHFFFFFFFFF',
'FFFFFFFHFFFHFFFFFHFHFFFFFFFFFF',
'FFFFFFFFFFFFFHFFFFFFFFFFFFFFFF',
'FFFFFFFFFFHFFFFFHFFFFFFFHFFFGF',
'FFFFFFHFFFFFFFFFFFFFHFFFFFFFFF',
'FFFFFFFFFFFFHFF... |
#!/usr/bin/python3
from frc971.control_loops.python import control_loop
from y2020.control_loops.python import flywheel
import numpy
import sys
import gflags
import glog
FLAGS = gflags.FLAGS
gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
# Inertia for a single 4" diameter, 1" wide neopreme ... |
#!/usr/bin/env python
import os
import sys
import h5py
import glob
import numpy as np
import pandas as pd
def main():
"""run synergy calculations <- separate bc need R and such
"""
# inputs
#out_dir = sys.argv[1]
grammar_summary_file = "/mnt/lab_data3/dskim89/ggr/nn/2019-03-12.freeze/dmim.shuffle... |
import cv2 as cv
from package.color_histogram import color_histogram as ch
# while running please ensure this example is in same directory as package
image = cv.imread('images/lines.jpg')
c = ch.ColorHistogram((8, 8, 8))
features = c.Regional(image)
print(features)
|
# Copyright 2021 Hakan Kjellerstrand hakank@gmail.com
#
# 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 ... |
lista = []
for c in range(0, 5):
lista.append(int(input(f'Digite um número para a posição {c+1}: ')))
print(f'O maior número da lista foi o {max(lista)} e apareceu nas posições ', end='')
for pos, valores in enumerate(lista):
if valores == max(lista):
print(f'{pos+1}...', end=' ')
print(f'\nO menor núme... |
#
# Copyright (c) 2013 Markus Eliasson, http://www.quarterapp.com/
#
# 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 rights to use... |
"""DNS Authenticator for Domeneshop DNS."""
import logging
import re
import zope.interface
from domeneshop.client import Client as DomeneshopClient, DomeneshopError
from certbot import errors
from certbot import interfaces
from certbot.plugins import dns_common
logger = logging.getLogger(__name__)
HELP_URL = "http... |
# -*- coding: utf-8 -*-
# Copyright (C) Canux CHENG <canuxcheng@gmail.com>
#
# 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 rights to ... |
#!/usr/bin/env python
"""
Convolutional Neural Network based on the 6-layer deep model proposed by
Barkan et al. [1]_
"""
import tensorflow as tf
from tensorflow.keras import layers
from spiegelib.estimator.tf_estimator_base import TFEstimatorBase
class Conv6(TFEstimatorBase):
"""
:param input_shape: Shape o... |
x = int(input('Qual tabuada quer saber? '))
for n in range(1,11):
print (f'{x} x {n} = {x*n}')
|
from __future__ import annotations
from ..typecheck import *
from ..import core
from ..import ui
from ..import dap
from ..terminal import Terminal, Line
from ..autocomplete import Autocomplete
from .variable import VariableComponent
from .tabbed_panel import Panel
from .import css
import re
import webbrowser
import... |
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro número: '))
soma = n1 + n2
subi = n1 - n2
multi = n1 * n2
divi = n1 / n2
diviinte = n1 // n2
divirest = n1 % n2
expo = n1 ** n2
print('A soma entre {} e {} equivale a {}, \n Equanto a subtração tem o valor de {}, \n A multiplicação de {}, \n A divisão d... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
# Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
# For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
import pytest
from harness.interface.defs import status
@pytest.mark.rt1051
@pytest.mark.service_desktop_test
@pytest.mark.usefixtures("phone_unlocked")
def test_battery_file(harness):
... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
import torch
import to... |
import asyncio
import logging
import os
import signal
import socket
import time
from typing import Optional, TYPE_CHECKING
from urllib.parse import urlsplit
from addict import Dict
from pyrogram.types import Message
from hikcamerabot.common.video.tasks.ffprobe_context import GetFfprobeContextTask
from hikcamerabot.co... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022, CloudBlue
# All rights reserved.
import copy
from typing import Dict, List, Tuple, Sequence
from connect.client import R, ConnectClient
from connect.client.models import ResourceSet
from google.cloud import channel
from google.cloud.channel_v1 import Offer, PriceByResour... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
#
# pylint: disable=unused-argument, too-many-public-methods, too-many-instance-attributes
"""Create an interactive view of a configuration.
This ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
from seata.exception.NotSupportYetException import NotSupportYetException
from seata.exception.ShouldNeverHappenException import ShouldNeverHappenException
from seata.sqlparser.SQLType import SQLType
from seata.sqlparser.mysql.MySQLDeleteSQLRe... |
from django.core.management.base import BaseCommand
from ...actions import plans
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
plans.sync_plans()
|
from oscar.apps.partner import config
class PartnerConfig(config.PartnerConfig):
name = 'tests._site.apps.partner'
|
import argparse, logging, subprocess, time, multiprocessing, sys
from pathlib import Path
from unet_test import run_segmentation
if __name__=="__main__":
# Initialize the logger
logging.basicConfig(format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s',
datefmt='%d-%b-%y %H:%... |
"""
Fall 2017 CSc 690
File: controller.py
Author: Steve Pedersen & Andrew Lesondak
System: OS X
Date: 12/13/2017
Usage: python3 spotify_infosuite.py
Dependencies: model, musikki, playback, reviews, view, requests, urllib, unidecode, pyqt5
Description: Controller class. Used to generate window frames and handle events,... |
from .const import (
ATTR_ACCELERATION,
ATTR_ALARM,
ATTR_BATTERY,
ATTR_CARBON_MONOXIDE,
ATTR_CODE_CHANGED,
ATTR_CODE_LENGTH,
ATTR_COLOR_MODE,
ATTR_COLOR_NAME,
ATTR_COLOR_TEMP,
ATTR_CONTACT,
ATTR_CURRENT,
ATTR_DEVICE_ID,
ATTR_DOOR,
ATTR_DOUBLE_TAPPED,
ATTR_ENER... |
"""Themes for plotnine."""
import plotnine as p9
import endktheme.colors
import endktheme.style
def theme_energinet() -> p9.themes.theme:
"""Create a simple Energinet theme."""
return p9.theme(
text=p9.element_text(family=endktheme.style.font_family()),
axis_line=p9.element_line(color="black")... |
"""
test_Plant_FinanceSE_gradients.py
Created by Katherine Dykes on 2014-01-07.
Copyright (c) NREL. All rights reserved.
"""
import unittest
import numpy as np
from commonse.utilities import check_gradient_unit_test
from plant_financese.basic_finance.basic_finance import fin_cst_component, fin_cst_assembly
from plant... |
#-*- encoding:utf-8 -*-
__author__ = 'Nobody'
str = raw_input()
len = len(str)
str = list(str)
for i in range(0, len):
j = i+1
for k in range(j, len):
if(str[i] == str[k]):
str[k] = "\0"
print "".join(str)
|
# DEFAULT
import tkinter
from tkinter import messagebox
class Frame:
def __init__(self):
# create the main window
self.root = tkinter.Tk()
self.root.title="Greet the User!!!"
self.root.geometry("425x100")
self.root.resizable(0,0)
# add a new label
self.label... |
import flask
from flask import Blueprint, session, redirect, url_for, escape, request, abort, g
import flask_login;
from flask.ext.cors import cross_origin
from flask.ext.login import login_required, current_user
import urllib2
import lxml.html
from . import database
import urlparse
import json
from marrow_config impor... |
# -*- coding: utf-8 -*-
from qcloudsdkcore.request import Request
class CreateLVBChannelRequest(Request):
def __init__(self):
super(CreateLVBChannelRequest, self).__init__(
'live', 'qcloudcliV1', 'CreateLVBChannel', 'live.api.qcloud.com')
def get_channelDescribe(self):
return sel... |
from __future__ import division, print_function, absolute_import
__author__ = 'Alex Rogozhnikov'
# Dirty hack so things are importable in tests without installing
import sys
sys.path.insert(0, '..')
|
from datetime import datetime
from typing import Any
from typing import Callable
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Type
import warnings
from optuna import TrialPruned
from optuna._imports import try_import
from optuna.distributio... |
from .appwindow import AppWindow
|
##########################################################################
#
# Copyright (c) 2020 Tom Cowland. 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 sou... |
#Import the OS module "Step#1"
import os
#Module for reading the Csv "Step#2"
import csv
# Declaring Variables "Step#6"
total_votes = 0
khan_votes = 0
correy_votes = 0
li_votes = 0
otooley_votes = 0
pypoll= os.path.join("PyPoll/election_data.csv")
print(pypoll)
# Open the CSV
with ope... |
""" Cisco_IOS_XR_sysadmin_asic_errors_ael
"""
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler im... |
import psi4
import numpy
psi4.core.set_output_file('ccsdrun.out', False)
psi4.set_memory('24 GB')
mol = psi4.geometry("""
units ang
symmetry c1
#FLAGXYZ
""")
mol.fix_com(True)
mol.fix_orientation(True)
psi4.core.set_num_threads(NUMTHREADS)
psi4.set_options({'basis': 'cc-pvdz'})
psi4.set_options({'maxiter': 500})
p... |
import re
import datetime
import jwt
from flask import request
from main import app
from main import (
maximum_age,
minimum_age,
)
from models import User, db
def validate_phonenumber_and_email_in_db(email, phonenumber):
email_exists = db.session.query(User).filter_by(email=email).count()
... |
import pytest
from brownie import ETH_ADDRESS, chain
from brownie_tokens import MintableForkToken
pytestmark = pytest.mark.usefixtures("add_synths")
@pytest.mark.parametrize("btc_idx", range(2))
def test_btc_to_eth(
Settler, alice, bob, swap, sBTC, sETH, curve_sbtc, curve_seth, btc_idx
):
initial = MintableF... |
"""Constants for the Salus iT600 smart devices."""
# Temperature units
TEMP_CELSIUS = "°C"
# Supported features
SUPPORT_TARGET_TEMPERATURE = 1
SUPPORT_PRESET_MODE = 16
# HVAC modes
HVAC_MODE_OFF = "off"
HVAC_MODE_HEAT = "heat"
# HVAC states
CURRENT_HVAC_OFF = "off"
CURRENT_HVAC_HEAT = "heating"
CURRENT_HVAC_IDLE = ... |
import dash
import dash_core_components as dcc
import dash_html_components as html
#import plotly.graph_objects as go
#from numpy import random
from graphFromText.graphByEquals import graphByEquals2, graphByEqualsFxn1, graphByEquals3, graphByEquals4
from graphFromText.graphEquations import graphEquations, graphEquation... |
import re
from object_detection.utils import config_util
import tensorflow as tf
from functools import reduce
def isfloat(value):
"""Returns if a given value can be converted to a float or not.
Args:
value: Input value of each type
Returns:
bool: Boolean if the input value can be parsed to a ... |
config = {
"twitter_consumer_key" : "",
"twitter_consumer_secret" : "",
"twitter_oauth_token" : "",
"twitter_oauth_token_secret" : "",
"db_username" : "",
"db_password" : "",
"pg_connection_string" : "",
"server_socket_port" : 9001,
"pidfile" : "/data/log/twitter-daemon.pid",
"de... |
from __future__ import print_function, with_statement
from _utils import githuboptparse, githublogin, get_filtered_repos
def has_webhook (hooks, url):
"""Goes through all the web hooks checking if any URL references the given URL"""
found = False
for temp_hook in hooks:
if temp_hook.config... |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..loss import acc
from ..post_processing import BeamSearch
class PAN_PP_RecHead(nn.Module):
def __init__(self,
input_dim,
hidden_dim,
voc,
ch... |
#
# PySNMP MIB module BTI7800-CONDITIONS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BTI7800-CONDITIONS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:24:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
# from .iter_counter import IterationCounter
# from .visualizer import Visualizer
# from .metric_tracker import MetricTracker
from .util import *
# from .html import HTML
# from .pca import PCA
|
from os import walk
import h5py
import numpy as np
import spotipy
import json
from config.Database import Base
from config.Database import engine
from config.Database import Session
from models.Music import Music
from kohonen.kohonen import run
def main():
# 2 - generate database schema
Base.metadata.create_all(e... |
from django.urls import path
from .views import (
order_success,
order_progress,
OrderListView,
order_detail,
)
app_name = 'order'
urlpatterns = [
path('order/success/', order_success, name="success"),
path('order/progress/', order_progress, name="progress"),
path('order/detail/<str:order... |
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import numpy
import unittest
from pyscf import gto
from pyscf import scf
mol = gto.M(
verbose = 5,
output = '/dev/null',
atom = '''
O 0 0 0
H 0 -0.757 0.587
H 0 0.757 0.587''',
basis = 'cc-pvdz',
)... |
#encoding=utf-8
from math import sin, pi
import time
import serial
import struct
import numpy as np
import h5py
import string
import binascii
global hand_id
hand_id = 1
#把数据分成高字节和低字节
def data2bytes(data):
rdata = [0xff]*2
if data == -1:
rdata[0] = 0xff
rdata[1] = 0xff
else:
rdata[0... |
from collections import defaultdict
from heapq import heappop, heappush
from sqlalchemy import Boolean, ForeignKey, Integer
from sqlalchemy.orm import aliased, backref, relationship
from sqlalchemy.schema import UniqueConstraint
from eNMS.database import db
from eNMS.models.base import AbstractBase
from eNMS.forms imp... |
#!/usr/bin/env python3
"""This is the main WordRoom script.
It contains all of the UI views and actions.
"""
# coding: utf-8
import os.path
import builtins
import json
import webbrowser
from urllib.parse import urlparse, unquote
import ui
import dialogs
import console
# import appex
from jinja2 import Environment, Fil... |
#!/usr/bin/env python3
import dash_core_components as dcc
import dash_html_components as html
from .data.config import Config
from .layout_providing import LayoutProviding
from .data.data_provider import DataProvider, RepresentableData
from .data.data_constants import DataConstants
from .data.config import Config
impo... |
from perceptron import perceptron
class cluster():
def __init__(self):
self.inputNode = perceptron.perceptron()
self.output1 = perceptron.perceptron()
self.output2 = perceptron.perceptron()
self.output3 = perceptron.perceptron()
self.finalOutput = perceptron.perceptron()
... |
from io import BytesIO
import matplotlib.pyplot as plt
from model import *
def get_main_image():
loss_time = [get_loss_times(r) for r in data]
losses = [get_loss(r) for r in data]
damages = [get_damage(r) for r in data]
plt.clf()
plt.scatter(loss_time, losses, alpha=0.5)
plt.xlabel('time')... |
from __future__ import absolute_import, division
import numpy as np
import pandas as pd
import pickle
import tables
import csv
import os
import re
import csv
def total_exp(cell_lines, path_to_networks):
for cl in cell_lines:
nets = 0
for exp in os.listdir(path_to_networks + cl):
path_ex... |
import pymem
import re
pm = pymem.Pymem('csgo.exe')
# bypass NtOpenFile hook in csgo.exe
csgo = pymem.process.module_from_name(pm.process_handle,
'csgo.exe')
csgoModule = pm.read_bytes(csgo.lpBaseOfDll, csgo.SizeOfImage)
address = csgo.lpBaseOfDll + re.search(rb'.\x1A\xF6\x45\x... |
import sys
file1 = sys.argv[1]
file2 = sys.argv[2]
FIRST = open(file1, 'r').read()
SECOND = open(file2, 'r').read()
import re
s1 = FIRST.split(' ')
s2 = SECOND
longest = ""
i = 0
for x in s1:
if re.search(x, s2):
s = x
while re.search(s, s2):
if len(s)>len(longest):
longest = s
... |
# Jay Williams 2017
# This module is included as part of https://github.com/codingJWilliams/jw_utils
# Liscenced according to ../../LISCENCE
# Contact codingJWilliams on github with any queries
import jw_utils
def is_prime(n):
if n == 0 or n == 1: return False
for i in range(1, n):
x = (n - i)
if x == 0 o... |
"""
A python wrapper for NAMD 2.9
"""
#=============================================================================================
# IMPORTS
#=============================================================================================
import os, sys, gzip
try:
from AlGDock import findPath
from AlGDock impor... |
# #!/usr/bin/env python
import json
import requests
import pprint
import time
LG_API = 'http://127.0.0.1:5001/load-generator'
RM_API = 'http://127.0.0.1:5002/resource-mapper'
OC_API = 'http://127.0.0.1:5003/openstack-client'
rrhs = []
bbus = []
def requestGet(url):
r = requests.get(url)
if (r.status_code != ... |
import config
import requests
from app.helpers import imagesource, response, dbhelper
from app.resources import limiter, images_blueprint
from flask import make_response, jsonify, request, stream_with_context, Response
@images_blueprint.route("/view/<int:sid>")
@limiter.limit(lambda : config.view_images_limit)
def vie... |
# 098 - Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: inicio, fim e passo.
#Seu programa tem que realizar três contagens através da função criada:
from time import sleep
def contagem(ini, fim, pas):
if ini<=fim:
for c in range(ini, fim+1, pas):
print(f'{c}', end =... |
# -*- coding: utf-8 -*-
# Author : 怕你呀
# Time : 2021/5/14
# File : main_page
# IDE : PyCharm
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from page.base_page import BasePage
class MainPage(BasePage):
__by_of_search = (By.XPATH, '//*[@id="... |
# Copyright 2014 The Oppia Authors. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
import numpy as np
def magnitude(x):
"""Returns magnitude of a vector"""
return np.linalg.norm(np.array(x))
def distance(p1, p2):
"""Returns distance between two positions p1 and p2"""
return magnitude(np.array(p2) - np.array(p1))
def unit_vector(x):
"""Returns unit_vector of a vector"""
retu... |
import random
import time
from pathmap.tree import Tree
class Timer():
def __init__(self):
self.start = time.time()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
end = time.time()
runtime = end - self.start
msg = 'The function... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... |
from abc import abstractmethod
from .statement_interface import StatementInterface
class QueryInterface(StatementInterface):
@abstractmethod
def as_expression(self) -> 'ExpressionInterface':
raise NotImplementedError('as_expression must be implemented')
@abstractmethod
def compile(self) -> '... |
# Copyright (c) 2017 Hanson Robotics, Ltd.
import os
import time
import datetime as dt
import logging
import rospy
import emopy
from cv_bridge import CvBridge, CvBridgeError
from std_msgs.msg import String
from sensor_msgs.msg import Image
logger = logging.getLogger('hr.emotion_recognizer')
class EmotionRecognizer(o... |
import RPi.GPIO as GPIO
import time
pin_1 = 18
pin_2 = 17
def initGPIO ():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(pin_1,GPIO.OUT)
GPIO.setup(pin_2,GPIO.OUT)
def ledOn_1 ():
GPIO.output(pin_1, GPIO.HIGH)
print "LED 1 on"
def ledOff_1 ():
GPIO.output(pin_1, GPIO.LOW)
print "... |
#!/usr/bin/python3
"""
Doorstop PyQt GUI
"""
import sys
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, QWidget, QFileDialog
from PyQt5.QtWidgets import QSplitter, QVBoxLayout, QTreeWidget, QTreeWidgetItem, QTableWidget
from PyQt5.QtWidgets import QTabWidget, QStack... |
[
[
float("NaN"),
0.55170308,
0.47929564,
float("NaN"),
0.55170308,
float("NaN"),
0.57323057,
1.0,
float("NaN"),
],
[
float("NaN"),
0.66380801,
1.0,
float("NaN"),
0.63761809,
float("NaN"),... |
from rest_framework import serializers
from ..models import Prediction, Equipment
class PredictionSerializer(serializers.HyperlinkedModelSerializer):
base_equipment = serializers.CharField()
target_equipment = serializers.CharField()
def _get_equipment_or_raise(self, symbol):
eq = Equipment.objec... |
#!/usr/bin/env python3
# coding: utf-8
from .checkpoint_update_base_test import CheckpointUpdateBaseTest
class CheckpointUpdateCompressTest(CheckpointUpdateBaseTest):
def test_compress_concurrent_update_eviction_single_checkpoint(self):
self.concurrent_update_eviction_base(True, False, False, 0)
def test_compres... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.