content stringlengths 5 1.05M |
|---|
# coding:utf8
from celery import Celery
from celery.schedules import crontab
app = Celery('tasks', borker='redis://localhost:6379/0')
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
# Calls test('hello') every 10s
sender.add_periodic_task(10.0, test.s('hello'), name='add every 10')
... |
""" [fabric](fabfile.org) script for deploying the app to a server
This script can be used to deploy the app.
One needs to call `deploy` with the fabric cli.
It compresses the app into a .tar.gz file, uploads and unpacks it
and sets a symlink to the latest revision.
It is also possible to use the ... |
class Gui:
def __init__(self):
pass |
# Twitcaspy
# Copyright 2021 Alma-field
# See LICENSE for details.
from ..utils import fromtimestamp
from .model import Model
class Movie(Model):
"""Movie Object
Attributes
----------
id: :class:`str`
| |movie_id|
user_id: :class:`str`
| |id|
title: :class:`str`
| Liv... |
import secrets
def generate(length):
char_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', ... |
from .providers import Gmail, Hotmail, Live, Provider, create_provider
VERSION = "0.0.1"
__all__ = [Gmail, Hotmail, Live, Provider, VERSION, create_provider]
|
import numpy as np
# enumerate results filenames
result_files = ('modern_net_drop_bin_scaled_results.np',
'modern_net_predicted_bin_scaled_results.np',
'modern_net_mode_bin_scaled_results.np',
'net_drop_bin_scaled_results.np',
'net_replace_bin_scaled_resul... |
import time
t1 = time.time()
t2 = time.time()
print("Iteration=%s, Time=%s" % (i, t2 - t1))
|
def handler(event, context):
print('Dummy ETL')
|
import numpy as np
class Mesh():
def __init__(self, filename):
# parse the .obj file
V, T = [], []
with open(filename) as f:
for line in f.readlines():
if line.startswith('#'): continue
values = line.split()
if not values: continue
... |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more informations
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
"""
RIP (Routing Information Protocol).
"""
from scapy.packet import *
from scapy.fields import *
from scapy.layers.inet imp... |
import pytest
from spacy.language import Language
from spacy.lang.en import English
from spacy.training import Example
from thinc.api import ConfigValidationError
from pydantic import StrictBool
def test_initialize_arguments():
name = "test_initialize_arguments"
class CustomTokenizer:
def __init__(se... |
# -*- coding=utf-8 -*-
"""
RestService signals module
"""
import django.dispatch
from django.conf import settings
from onadata.apps.restservice.tasks import call_service_async
ASYNC_POST_SUBMISSION_PROCESSING_ENABLED = \
getattr(settings, 'ASYNC_POST_SUBMISSION_PROCESSING_ENABLED', False)
# pylint: disable=C0103... |
import multiprocessing
def worker(num):
print('Worker %s, argument: %s' % (multiprocessing.current_process().name, num))
return
if __name__ == '__main__':
processes = []
for i in range(5):
# the same as for threading, we have to pass an iterable as argument
# so if we pass a single a... |
# we start by importing the unittest module
import unittest
# Next lets import our function that we intend to do testing on
#
# **We could also import all functions by using * or just import the module
# itself but for now lets just import the function
from challenge_7 import missing_int
# lets define our suite of te... |
from alpha_vantage.timeseries import TimeSeries
import yfinance as yf
from datetime import datetime
#
# Thanks, Barry!
#
# A simple robo-broker that'll tell you when interesting stuff happens
#
# He's too dumb to tell you what to buy, but he watches the market like a hawk
# and will tell you when something you own ha... |
import sys
import math
from collections import defaultdict, deque
sys.setrecursionlimit(10 ** 6)
stdin = sys.stdin
INF = float('inf')
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().strip()
S = input().split()
d = defaultdict(str)
d["Left"] = "<"
d["Right"]... |
#The tee() function returns several independent iterators (defaults to 2) based on a single original input.
from itertools import *
r = islice(count(),5)
print(r)
i1,i2 = tee(r)
print('r:',end=" ")
for i in r:
print(i, end=' ')
if i >1:
break
print()
print('i1:', list(i1))
print('i2:', list(i2))
|
from functools import reduce, lru_cache
import numpy as np
from typing import List, Any, Callable
import scipy.integrate as integrate
from mule_local.rexi.pcirexi.gauss_cache import GaussCache
from mule_local.rexi.pcirexi.section import section
def _complex_quad(func, a, b):
real = integrate.quad((lambda a: func... |
"""
configurations
"""
import os
import tensorflow as tf
from prepare import prepare
from main import test, train
if not os.path.exists("data/vocab"):
os.system("mkdir data/vocab")
if not os.path.exists("data/experimental"):
os.system("mkdir data/experimental")
if not os.path.exists("train"):
os.system("m... |
# Generated by Django 2.2.6 on 2020-08-03 12:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0003_post_author'),
]
operations = [
migrations.AlterField(
model_name='post',
name='image',
fi... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
#
# Copyright (c) 2021 Facebook, Inc. and its affiliates.
#
# This file is part of NeuralDB.
# See https://github.com/facebookresearch/NeuralDB for further info.
#
# 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... |
# How to print multiple non-consecutive values from a list with Python
from operator import itemgetter
animals = ['bear', 'python', 'peacock',
'kangaroo', 'whale', 'dog', 'cat', 'cardinal']
print(itemgetter(0, 3, 4, 1, 5)(animals))
print(animals)
print(type(animals))
# Slicing indexes
course_name = "Pytho... |
"""All unit tests for the gaslines display module."""
import pytest
from gaslines.display import Cursor, reveal
from gaslines.grid import Grid
from tests.utility import draw_path
# Note: these automated tests merely verify that the functions under test behave
# consistently. Given the functions' visual nature, ver... |
from datetime import datetime
from flask import (
render_template,
flash,
redirect,
url_for,
request,
g,
jsonify,
current_app,
)
from flask_login import current_user, login_required
from app import db
from app.main.forms import EditProfileForm, CreateResourceForm
from app.models import U... |
# coding=utf-8
import time
from selenium import webdriver
# driver = webdriver.Chrome() #打开浏览器
from common.pub import readconfig
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver import ActionChains
from common.pub.selenium_rewrite import isElementExist
from common... |
# -*- test-case-name: mimic.test.test_nova -*-
"""
Canned responses for nova's GET limits API
"""
from __future__ import absolute_import, division, unicode_literals
def get_limit():
"""
Canned response for limits for servers. Returns only the absolute limits
"""
return {"limits":
{"absolu... |
SQL_LITE_DB = 'sqlite:///db.sqlite3' |
from config import CITIES_COLLECTION_NAME
from .base import CommandBase
class CommandCity(CommandBase):
async def __call__(self, payload):
self.sdk.log("/city handler fired with payload {}".format(payload))
if not payload['params']:
message = "Enter city ID\n\nExample: /city 498817"
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2012, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
from collections import defaultdict
from milk.utils import get_nprandom
import nump... |
# This file is part of DagAmendment, the reference implementation of:
#
# Michel, Élie and Boubekeur, Tamy (2021).
# DAG Amendment for Inverse Control of Parametric Shapes
# ACM Transactions on Graphics (Proc. SIGGRAPH 2021), 173:1-173:14.
#
# Copyright (c) 2020-2021 -- Télécom Paris (Élie Michel <elie.michel@tel... |
"""
Parser which works with tokens
"""
import sys
from lexer import Lexer, TokenType
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.pos = 0
def match(self, expectedTypes):
if self.pos < len(self.tokens):
token = self.tokens[self.pos]
if t... |
"""
Copyright (c) 2020 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WI... |
import dnest4.classic as dn4
from pylab import *
plt.rcParams["font.family"] = "serif"
plt.rcParams["font.size"] = 16
plt.rc("text", usetex=True)
data = loadtxt('galaxies.txt')
posterior_sample = atleast_2d(dn4.my_loadtxt('posterior_sample.txt'))
x = linspace(0., 50.0, 10001)
def mixture(x, params):
N = int(para... |
from itertools import chain
import argspec
S_INVOKE = '(Error invoking event %s on %r with args %r: %r)'
# events: dict of (event_name:handler_levels)
# handler_levels: 3-tuple of sets of functions
class Events(object):
EVENT_LEVELS = BLOCK, CONSUME, NOTIFY = range(3)
def __init__(self, defau... |
'''
'''
from observer import Event
class StateChangeEvent(Event):
'''
'''
def __init__(self, emitter, old_state, new_state):
super().__init__(emitter)
self.old_state = old_state
self.new_state = new_state
|
import torch
from sklearn.metrics import r2_score
def my_metric(output, target):
with torch.no_grad():
#pred = torch.argmax(output, dim=1)
#assert pred.shape[0] == len(target)
#correct = 0
#correct += torch.sum(output == target).item()
output = output.cpu()
target =... |
#! /usr/bin/env python3
from setuptools import setup
import sys
if sys.version_info[0] < 3:
raise Exception("Sorry, you must use Python 3")
import pathlib
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text(encoding='utf... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
tree.py
---------------------
Date : November 2013
Copyright : (C) 2013-2016 Boundless, http://boundlessgeo.com
************************************************************... |
import halfedge_mesh
from halfedge_mesh.halfedge_mesh import distance
mesh = halfedge_mesh.HalfedgeMesh("cube.off")
#def dijkstra(mesh, s):
# création d'une liste distance
#d = [ None for v in mesh.vertices ]
# le premier point est à zéro
#d[s.index] = 0
# les précédesseurs ne sont pas... |
import arrow
import cassiopeia
from cassiopeia import Region, Platform
import pytest
from merakicommons.container import SearchableList
from datapipelines.common import NotFoundError
from .constants import CHAMP_NAME, SUMMONER_NAME, UNKNOWN_SUMMONER_NAME
def test_masteries_correct_type():
summoner = cassiopeia... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-28 09:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parkstay', '0034_auto_20161222_1642'),
]
operations = [
migrations.AlterFie... |
import csv
import requests
import lxml
from bs4 import BeautifulSoup
def get_page(url):
response = requests.get(url)
if not response.ok:
print('Server responded:', response.status_code)
else:
soup = BeautifulSoup(response.text, 'lxml')
return soup
def get_detail_data(soup):
# tit... |
#One player game of Tic-Tac-Toe where each player plays
#against an AI. Uses a console text interface.
import random #Used to generate random variables
gameBoard = None #Variable to hold the grid representing the game board
playerVariable = None #Variable that represents the player
computerVariable = None #Variable t... |
from pathlib import Path
from PIL import Image
import numpy as np
import xml.etree.ElementTree as ET
import random
import pickle
import torch
import sys
from utils.config import cfg
anno_path = cfg.CUB.KPT_ANNO_DIR
img_path = cfg.CUB.ROOT_DIR + 'images'
ori_anno_path = cfg.CUB.ROOT_DIR + 'Annotations_original'
set_pa... |
# import section
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import pyttsx3
import pywhatkit
import pyjokes
import rotatescreen
import os
import PyPDF2
from textblob import TextBlob
import platform
import calendar
import cowsay
from translate import Translator
import sounddevice
f... |
from spacemapping_curve.quadtree import *
from spacemapping_curve.distance import FuckYouBernhardFunction
from spacemapping_curve.distance import DistanceToCurve
from spacemapping_curve.hilbertcurve import draw_hc
import Rhino.Geometry as rg
pts_1 = [
rg.Point3d(-100, 0, 0),
rg.Point3d(-50, 50, 0),
rg.Po... |
# Copyright 2019-2022 ETH Zurich and the DaCe authors. All rights reserved.
""" SDFG API sample that showcases state machine creation and the `simplify` call, which will fuse them. """
import dace
import numpy as np
# Define a symbol to be used in the SDFG
T = dace.symbol('T')
# Create an empty SDFG
sdfg = dace.SDFG(... |
import logging
from collections import namedtuple
from pathlib import Path
import requests
from tqdm import tqdm
logger = logging.getLogger(__name__)
SingleLineFixExample = namedtuple(
"SingleLineFixExample", ("id", "buggy_code", "fixed_line", "lineno")
)
def download(url, out_path, *, size_estimate=None):
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import unittest
import sys
from mock import MagicMock
from ansible_collections.spot.cloud_modules.plugins.modules.event_subscription import expand_subscription_request
sys.modules['spotinst_sdk'] = MagicMock()
class MockModul... |
#!/usr/bin/env python
"""Import required modules."""
from traininglabs import defaultlab
def main():
"""Main function."""
defaultlab.create_lab()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# Copyright (c) 2017 Cable Television Laboratories, Inc. and others.
#
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
"... |
# Copyright 2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
# (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# 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
#
# ... |
def solve(n: int) -> int:
if n == 0:
return 1
else:
return n * solve(n - 1)
|
import urllib.request
from bs4 import BeautifulSoup
from pprint import pprint
import json
url = 'http://www.thesaurus.com/browse/'
words = ['sentence']
def lookForSynonyms(word):
try:
synonyms = []
content = urllib.request.urlopen(url + word)
#print(fp.geturl())
#print(fp.info())
... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine import recipe_test_api
class IsolatedTestApi(recipe_test_api.RecipeTestApi):
def properties(self,
server='https://exa... |
import argparse
import gc
import time
import torch.backends.cudnn as cudnn
from models import create_model
from entry import experiment_main
from load_config import load_config
from typing import List, Union
import numpy as np
import decord
def count_experiments(series: Union[dict, List[dict]]) -> int:
if type(se... |
import contextlib
import dataclasses
import logging
import os
import pkg_resources
import tempfile
import typing as t
import requests
from databind.core import annotations as A
from shut.data import load_string
from shut.model.requirements import Requirement
from shut.renderers.core import Renderer
from shut.test.base... |
from pyramid import pyramid
import numpy
from sp0Filters import sp0Filters
from sp1Filters import sp1Filters
from sp3Filters import sp3Filters
from sp5Filters import sp5Filters
import os
from maxPyrHt import maxPyrHt
from corrDn import corrDn
import math
from LB2idx import LB2idx
import matplotlib
from showIm import sh... |
import os
import time
from urllib.parse import urlparse
import requests
from auth import get_auth
def get_resource_list(url):
"""
Returns a list of HC resources specified by the url basename (such as .../articles.json)
:param url: A full endpoint url, such as 'https://support.zendesk.com/api/v2/help_cent... |
'''
This is the input node that receives spikes and converts to Baxter joint angles.
'''
import argparse
from brian_multiprocess_udp import BrianConnectUDP
def from_spikes_to_baxter(spikes_pipe_in, spikes_pipe_out):
"""
This function substitutes the run_brian_simulation and converts the received spikes in... |
# -*- coding: utf-8 -*-
from openerp import tools, models, fields, api, exceptions
############################################################################################################################ Cikk-polc kapcsolat ###
class LegrandCikkPolc(models.Model):
_name = 'legrand.cikk_polc'
_... |
import logging
import os
logging.basicConfig(format='%(levelname)s %(message)s')
logging.getLogger('__main__').setLevel(logging.INFO)
logger = logging.getLogger(__name__)
from bravado.client import SwaggerClient
logger.info('trying to get swagger definition')
client = SwaggerClient.from_url(os.getenv('SWAGGERURL', 'h... |
import os
import shutil
import zipfile
# 首先引入需要的工具包
# shutil为后期移动文件所需,可以忽略此项
# 源路径
parent_path = r'G:/KittiRaw_zip/2011_10_03'
# 目标路径
target_path = r'H:/KittiRaw/2011_10_03'
# 文件类型选择
# 可以自行更改压缩文件类型,需要引入其它工具包,如tarfile等
# 这里是因为在自己的windows上,zip比较常见,其他类型请自行更改
file_flag = '.zip'
# 删除已解压的zip文件
# 不建议初次使用,在确定程序无误后可以添加使用
def de... |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.extension_base impo... |
# do nothing, just exist to make "classes" package
|
from urllib.error import HTTPError
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import time
import logging
import sys
class API:
def __init__(self, token, api_url='https://api.tinybird.co', version='v0'):
self.api_url = api_url.rstrip('/')
self.ver... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 law o... |
"""empty message
Revision ID: ad467baf7ec8
Revises: 4b483a762fed
Create Date: 2021-12-02 16:32:50.884324
"""
import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ad467baf7ec8'
down_revision = '4b483a762fed'
branch_labels = None
depends_on = None... |
from typing import NoReturn
import click
from watchgod import RegExpWatcher, watch
from bock.helpers import absolute_paths_to_articles_in, click_option_article_root
from bock.logger import log
from bock.search import (
create_search_index,
get_search_index,
update_index_incrementally,
)
def run(article_... |
# -*- coding: utf-8 -*-
# Copyright 2017 ProjectV 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 requi... |
#from django.conf import settings
#settings.DEBUG = True
from django.core.management import call_command
from testcases import (
TestServerTestCase,
get_client
)
class ExistsTestCase(TestServerTestCase):
def setUp(self):
self.start_test_server()
self.client = get_client()
call_com... |
import torch
import torch.nn as nn
import numpy as np
from Layers.bottlenecks import LinearBottleneckLayer
class ReactionDotProduction(nn.Module):
''' Scaled Dot Productionss '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.d... |
from abc import ABCMeta, abstractmethod
from enum import Enum
class ActionType(Enum):
SHELL = 'shell'
RELEASE = 'release'
class Action(metaclass=ABCMeta):
@abstractmethod
def run(self, path: str, config=None, system_config=None, erlang_vsn: str = None) -> bool:
pass
@abstractmethod
... |
c.JupyterHub.authenticator_class = 'ldapauthenticator.LDAPAuthenticator'
c.LDAPAuthenticator.server_address = '172.17.0.2'
c.LDAPAuthenticator.bind_dn_template = [
"uid={username},dc=example,dc=org"
]
c.JupyterHub.spawner_class = 'simplespawner.SimpleLocalProcessSpawner'
c.SimpleLocalProcessSpawner.args = ['--allo... |
from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
state = "Stopped"
def __init__(self, request, client_address, server):
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
def do_GET... |
# Copyright 2016 Quora, 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 law or agreed to in writing, so... |
import preprocessing as prep
def kldplot(ax, kld_data_loc, kld_max, countmin, countmax, rearr_start, rearr_period, rearr_idc = True):
kld_data = prep.data(kld_data_loc, 2)
x3 = list(map(lambda d: d[0], kld_data))
y3 = list(map(lambda d: abs(d[1]) , kld_data))
ax.plot(x3, y3)
ax.set_ylabel("KL dive... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# 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 L... |
from collections import defaultdict
from statistics import mean
from record_helper import *
import vcfpy
def generate_sv_record(records, comparison_result, sample_names):
"""
This method generates a single SV record after a call has been made over a set of input records
:param records: the input records i... |
#!/usr/bin/env python
"""
Example for commanding robot without moveit
"""
import sys
import numpy as np
import rospy
from geometry_msgs.msg import Pose, Point, Quaternion
from sensor_msgs.msg import JointState
from trac_ik_python.trac_ik import IK
GRIPPER_LINK = "gripper_link"
ARM_BASE_LINK = "arm_base_link"
MOVE_GR... |
# Generated by Django 2.2.24 on 2021-11-30 19:06
from django.db import migrations
# the sql commands in this migration file create a function to update
# the re-use flags on cwts if the cwt has been reused for different
# species, year classes, stains, in different lakes, and by different
# agencies. The first stat... |
"""
Tests for pecoregex.pcre.
"""
import re
from ctypes import CDLL
import pytest
from pecoregex import pcre
# pylint: disable=C0111
def test_nametable_entry():
entry = bytes((1, 0)) + b'hello' + bytes(28)
index, name = pcre.nametable_entry(entry)
assert index == 256
assert name == 'hello'
def test_pcre_lib_cons... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : kill.py
@Contact : 379327479@qq.com
@License : MIT
@Modify Time @Author @Version @Description
------------ ------- -------- -----------
2021/10/26 9:49 zxd 1.0 None
"""
import uiautomator2 as u2
from uiautomato... |
from itertools import combinations
from solvatore import Solvatore
from cipher_description import CipherDescription
from ciphers import present
cipher = present.present
rounds = 9
solver = Solvatore()
solver.load_cipher(cipher)
solver.set_rounds(rounds)
# Look over all combination for one non active bit
for bits in ... |
import numpy as np
import talib
import math
class Algorithm:
# @staticmethod
# def lm_kdj(df, n,ksgn='close'):
# lowList= pd.rolling_min(df['low'], n)
# lowList.fillna(value=pd.expanding_min(df['low']), inplace=True)
# highList = pd.rolling_max(df['high'], n)
# highList.fillna(v... |
# -*- coding: utf-8 -*-
'''
Created on 2019年03月02日
@author: Zhukun Luo
Jiangxi university of finance and economics
'''
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.sql import SparkSession
conf = SparkConf().setAppName("Spark App").setMaster("local[4]")#默认分配线程
sc = SparkContext(conf=con... |
from tkinter import *
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import requests
import bs4
import threading
import os
#threading
def threading1():
t1= threading.Thread (target = run_tom)
t1.start()
listener = sr.Recognizer()
engine = pytts... |
#!/usr/bin/env python3
import datetime
import os
import shutil
import subprocess
import stat
def get_real_path(path):
return os.path.expandvars(os.path.expanduser(path))
def get_install_dir():
install_dir = os.environ.get('INSTALL_DIR')
if not install_dir:
install_dir = os.path.dirname(os.path.a... |
class InvalidSubscription(Exception):
pass
|
"""
flowRecorder system tests
"""
# Handle tests being in different directory branch to app code:
import sys
import struct
# For file handling:
import os
import csv
# For system calls to run commands:
import subprocess
# flowRecorder imports:
import config
# test packet imports:
import http1 as groundtruth_http1
i... |
# 构建路径
# 除了将现有路径分开之外,
# 经常需要从其他字符串构建路径。要将多个路径组件组合为单个值,请使用join():
import os.path
PATHS = [
('one', 'two', 'three'),
('/', 'one', 'two', 'three'),
('/one', '/two', '/three'),
]
for parts in PATHS:
print('{} : {!r}'.format(parts, os.path.join(*parts)))
"""
output:
('one', 'two', 'three') : 'one\\two\\t... |
import os
import sys
import tempfile
import time
from pathlib import Path
from typing import IO, List, Set
import csv
import pandas
from util.jtl_convertor import jtl_validator
from util.project_paths import ENV_TAURUS_ARTIFACT_DIR
LABEL = 'Label'
SAMPLES = '# Samples'
AVERAGE = 'Average'
MEDIAN = 'Median'
PERC_90 = ... |
#!/usr/bin/env python
import os
from distutils.core import setup
def get_package_data_files():
files = []
pkgdir = os.path.join(os.path.dirname(__file__), "src", "cloc")
for root, _, filenames in os.walk(os.path.join(pkgdir, "config")):
for f in filenames:
files.append(os.path.join(ro... |
import pyspark.sql.functions as F
from pyspark.sql import SparkSession
# Start SparkSession
spark = SparkSession.builder.appName("missingdata").getOrCreate()
df = spark.read.csv("ContainsNull.csv", header=True, inferSchema=True)
df.show()
# Drop any row that contains missing data
df.na.drop().show()
# Has to have at ... |
#!/usr/bin/env python3
import argparse
'''
* Stream of numbers.
* First N numbers (N=25 for this code) are part of the preamble.
* Every number following the preamble must be a sum of two of the N numbers prior to it
'''
g_args = None
#------------------------------------------------------------------------------
... |
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENS... |
'''
Slide lexer defines tokens used on all but the first level of the input document
(inside slides and inside all subsequent nested hierarchical nodes).
Some document tokens are reused.
Created on 1 Feb 2018
@author: Teodor G Nistor
@copyright: 2018 Teodor G Nistor
@license: MIT License
'''
from __future__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.