content stringlengths 5 1.05M |
|---|
import cv2
import numpy as np
face_csc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('richfacepoorface.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_csc.detectMultiScale(gray,1.1,4)
for (x,y,w,h) in fa... |
import operator
from prettytoml.elements import traversal as t, traversal
from itertools import *
from functools import *
from prettytoml.elements.metadata import WhitespaceElement
from prettytoml.elements.table import TableElement
from prettytoml.prettifier import common
def deindent_anonymous_table(toml_file_elemen... |
def count_pair(arr, sum):
hm = dict()
for elt in arr:
hm[elt] = hm.get(elt, 0) + 1
count = 0
for elt in arr:
remaining = sum - elt
count += hm.get(remaining, 0)
return count/2
if __name__ == "__main__":
arr = [7, 5, 1, -1, 5]
sum = 6
pair_count = count_pair(arr,... |
#!/usr/bin/env python3
"""
Test for rundaterange limit
"""
import unittest
from base_test import PschedTestBase
from pscheduler.limitprocessor.limit.rundaterange import *
LIMIT = {
"start": "2019-01-01T00:00:00-04",
"end": "2019-12-31T23:59:59-04",
"overlap": True
}
LIMIT_NO_OVERLAP = {
"start":... |
"""
Helper class to interact with the Matomo API
"""
import re
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
class MatomoApiManager:
"""
This class helps to interact with Matomo API
There are several functions to retrieve unique visitors for last 30 days,
... |
from cryptography.fernet import Fernet
if __name__ == '__main__':
print(Fernet.generate_key())
|
from itscsapp.utils.models import ITSModel
from django.db import models
class Contact(ITSModel):
name = models.CharField(max_length=255, verbose_name='Nombre')
phone_number = models.CharField(max_length=255, verbose_name='Numero De Telefono')
subject = models.CharField(max_length=255, verbose_name='Asunto... |
"""Facebook ResNet-200 Torch Model
Model with weights ported from https://github.com/facebook/fb.resnet.torch (BSD-3-Clause)
using https://github.com/clcarwin/convert_torch_to_pytorch (MIT)
"""
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import torch.utils.model_zoo a... |
# Copyright (c) 2013 Vindeka, LLC.
#
# 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 writ... |
senha = int(input('Jogador 1 digite um valor entre 0 a 100 como senha:\n'))
tentativas = 5
if senha >= 0 and senha <= 100:
for i in range(tentativas):
senha2 = int(input(f'Qual é a senha jogador 2 ? Você tem {tentativas} chances!\n'))
if senha2 == senha:
print('Acesso permitido!')
... |
import os
import cv2 as cv
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from pose_estimator import PoseEstimator
# test run
SAMPLES_DIR = os.environ['ROOT_DIR']+"/src/flask_app/static/images/samples"
sample_file = SAMPLES_DIR+"/profile_images/sample-profile-image1.jpg"
img = cv... |
""""Interface for exercise statistics."""
import datetime
import practicer_flask.user_exercise_stats.history_postgres as exercise_history
import practicer_flask.user_exercise_stats.streak
import practicer_flask.user_exercise_stats.experience
import practicer_flask.user_exercise_stats.progress as exercise_progress
his... |
import gzip
import json
import os
import requests
from helpers import get_movie_file, get_response
def main():
try:
movie_file = get_movie_file()
except FileNotFoundError:
print('File not selected, exiting')
return -1
response = get_response(movie_file)
if 'useragent is not va... |
__author__ = 'Sujit Mandal'
#Date : 30-08-2020
import pandas as pd
import urllib.request
'''
# Author : Sujit Mandal
Github : https://github.com/sujitmandal
My Package : https://pypi.org/project/images-into-array/
My Package : https://pypi.org/project/scrape-search-engine/
LinkedIn : https://www.linkedin.com/in/sujit... |
"""
Book: The Essentials of Computer Architecture.
Chapter: 4
Problem: Write a Computer Program that measures the difference in execution
times between the integer division and floating point division. Execute the operation
100,000 times and compare the difference in the running time.
Interesting Observation:
* I... |
#While loops
i = 1
while i < 8: #While x is less than 8 loop through this code
if i == 6:
break #Tells python to stop the loop
print(i)
i += 1
x = 0
while x < 12:
x += 2
if x == 8:
print("Skips 8")
continue #Skips when x is 8
print("X: " + str(x))
else: #When the loop is done do this code
print("x is no... |
import argparse
from abc import ABC, abstractclassmethod
from argparse import RawTextHelpFormatter
from asreview import __version__
class BaseEntryPoint(ABC):
"""Base class for defining entry points."""
description = "Base Entry point."
extension_name = "asreview"
version = __version__
@abstrac... |
from PyQt5.QtCore import QObject, pyqtSignal, QThread, QRunnable
import time
from controllers.WSignals import WSignals
import traceback, sys
class fakeElevator(QRunnable):
'''
Worker thread
Inherits from QRunnable to handler worker thread setup, signals and wrap-up.
:param callback: The function call... |
from hw.maria_saganovich.lesson6_hw.lvl11_relations_bt_2_sets import (
func11_relation_bt_2_sets,
)
def test_func11_relation_bt_2_sets() -> None:
assert func11_relation_bt_2_sets({1, 2}, {1, 3}) == { # noqa: JS101
"data": {
"a&b": {1},
"a|b": {1, 2, 3},
"a-b": {2},... |
# -*- coding: utf-8 -*-
import sys
from pathlib import Path
import numpy as np
import pendulum
from alg_complexity import datagen
from alg_complexity.trees import AVLTree
from alg_complexity.utils import class_execution_time, ClassExecTime
if __name__ == '__main__':
now = pendulum.now()
now_str = now.to_date... |
# Generated by Django 2.2.12 on 2020-05-20 19:41
from django.db import migrations, models
import django.db.models.deletion
from contentPages.models import AllResourcesPage, AssetTypePage, ResourceItemPage
def create_new_draft_revisions(apps, schema_editor):
resource_pages = AllResourcesPage.objects.filter(live=F... |
from typing import Any, Dict
from utils.globalvars import METADATA_FILE
import json
class Metadata:
"""This class manages metadata, which store hardware (such as lna or receiver type), software
(such as recipe used) and run-time parameters (such as frequency or name of the satellite).
This metadata i... |
import csv
import sys
nargs=len(sys.argv)
ofileName='mergedDataset.csv'
with open(ofileName, "wb") as f:
o=csv.writer(f,quoting=csv.QUOTE_ALL)
o.writerow(["IssueTitle","IssueDescription","Label","PrTitle","PrDescription"])
for i in range(1,nargs):
with open(sys.argv[i], "rb") as g:
... |
# -*- coding: utf-8 -*-
'''
Created on 2016-10-20
@author: hustcc
'''
# for sqlite
# DATABASE_URI = 'sqlite:///git_webhook.db'
# for mysql
DATABASE_URI = 'mysql://root:root@mysql/git_webhook'
CELERY_BROKER_URL = 'redis://:@redis:6379/0'
CELERY_RESULT_BACKEND = 'redis://:@redis:6379/0'
GITHUB_CLIENT_ID = 'b6e751cc4... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# aire.py
#
# Copyright 2010 Javier Rovegno Campos <tatadeluxe<at>gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... |
from rest_framework import viewsets, filters
from django_filters.rest_framework import DjangoFilterBackend
from src.Models import Squad
class SquadsViewSet(viewsets.ModelViewSet):
queryset = Squad.SquadModel.objects.all()
serializer_class = Squad.SquadSerializer
filter_backends = (filters.SearchFilter, ... |
#! /usr/bin/env python
#
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions ... |
def render_graph_DefaultRenderGraph():
g = RenderGraph("DefaultRenderGraph")
loadRenderPassLibrary("AccumulatePass.dll")
loadRenderPassLibrary("GBuffer.dll")
loadRenderPassLibrary("OptixDenoiser.dll")
loadRenderPassLibrary("MegakernelPathTracer.dll")
loadRenderPassLibrary("ToneMapper.dll")
G... |
frase = str(input('Digite uma frase: ').strip().upper())
palavras = frase.split()
juncao = ''.join(palavras)
'''inverso = ''
for letra in range(len(juncao) - 1, -1, -1):
inverso += juncao[letra]'''
inverso = juncao[::-1]
if inverso == juncao:
print('É palíndromo, {} e {}'.format(juncao, inverso))
else:
prin... |
import re
import sys
from io import BytesIO
from pathlib import Path
from random import randbytes
from subprocess import PIPE, Popen
from urllib.request import urlopen
from http import HTTPStatus
import pytest
from limit_reader import LimitReader
def new_reader(size, limit):
data = randbytes(size)
io = Byte... |
def longest_increasing_subsequence(arr):
count = 1
memo = arr[0]
for i in range(1, len(arr)):
if arr[i] > memo:
count = count + 1
memo = arr[i]
return count
input_sequence = [10, 22, 9, 33, 21, 50, 41, 60]
print(longest_increasing_subsequence(input_sequence))
|
"""
parser.http.bsouplxml.html module (imdb.parser.http package).
This module adapts the beautifulsoup interface to lxml.html module.
Copyright 2008 H. Turgut Uyar <uyar@tekir.org>
2008 Davide Alberani <da@erlug.linux.it>
This program is free software; you can redistribute it and/or modify
it under the ter... |
# -*- coding: utf-8 -*-
"""
@Time : 2021/5/26 10:49
@Author : BarneyQ
@File : code_test.py
@Software : PyCharm
@Description :
@Modification :
@Author :
@Time :
@Detail :
"""
import numpy as np
screen = np.zeros((10,10))
# print(screen)
#
# print(screen[0:5:3,0:... |
def inicstr(str_data):
d = {}
if len(str_data) > 0:
lst = str_data.split('/')
if len(lst) > 3:
|
import numpy as np
import copy
from classtestify import Testify
from classcapability import Capability
from classtable import Table
from class2ndmethod import SecondMethod
from class2Randr import SecondRate
from class1stRandr import FirstRate
r"""
INPUT:
- ''demands'' -- [K*I] matrix: which user is asking for w... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from importlib import import_module
from django import VERSION as DJANGO_VERSION
from django.conf import settings
# Do we support set_required and set_disabled?
# See GitHub issues 337 and 345
# TODO: Get rid of this after support for Django 1.8 LTS end... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_To... |
import sklearn.metrics as skm
import matplotlib as mp
mp.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
from patsy import ModelDesc, EvalFactor, Term, dmatrix
from os import linesep, path
from sklearn.preprocessing import Imputer
from sklearn.model_selection import trai... |
import gc
import xgboost as xgb
from tqdm import tqdm
class BaggedXgboost(object):
def __init__(self, n_models, verbose=True):
self.n_models = n_models
self.verbose = verbose
self.models = []
def train(self, params, dtrain, *args, **kwargs):
if self.verbose:
itera... |
"""Temperature Module protocol commands."""
from .set_target_temperature import (
SetTargetTemperature,
SetTargetTemperatureCreate,
SetTargetTemperatureParams,
SetTargetTemperatureResult,
SetTargetTemperatureCommandType,
)
from .await_temperature import (
AwaitTemperature,
AwaitTemperature... |
from __future__ import annotations
from typing import overload
myint = int
def sum(x: myint, y: myint) -> myint:
"""docstring"""
return x + y
@overload
def mult(x: myint, y: myint) -> myint:
...
@overload
def mult(x: float, y: float) -> float:
...
def mult(x, y):
"""docstring"""
return... |
import argparse
import os
from highlights import create_highlights, get_multiple_highlights
from utils import make_dirs, find_features_layer
from rl_baselines_zoo.utils import ALGOS
from get_traces import load_agent
from environments import Evnironments
from agent_comparisons import compare_agents
import logging
if ... |
# Generated by Django 3.0.7 on 2020-10-03 17:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('thesis', '0008_auto_2020... |
import numpy as np
from pymc import *
model = Model()
with model:
k = 5
a = constant(np.array([2, 3., 4, 2, 2]))
p, p_m1 = model.TransformedVar(
'p', Dirichlet.dist(a, shape=k),
simplextransform)
c = Categorical('c', p, observed=np.random.randint(0, k, 5))
def run(n=3000):
if n ... |
import os, sys
import bpy
from mathutils import Matrix, Vector
from PIL import Image
from math import radians, sin, cos
import numpy as np
import random
import json
import ipdb
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cur_dir)
from image_utils import obtain_obj_region, obtain_obj_center
fro... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# -*- coding: utf-8 -*-
import os
import pandas
__author__ = 'Petr Belohlavek <me@petrbel.cz>'
print()
class PscKonvertor:
"""Konvertuje postovni smerovaci cisla na prislusne okresy a kraje.
Vyhledavani je pro maximalni rychlost indexovane."""
_MODULE_PATH = os.path.dirname(os.path.abspath(__file__... |
import pytest
from eth2.beacon.state_machines.forks.serenity import (
SerenityStateMachine,
)
from eth2.beacon.state_machines.forks.xiao_long_bao import (
XiaoLongBaoStateMachine,
)
@pytest.mark.parametrize(
"sm_klass",
(
SerenityStateMachine,
XiaoLongBaoStateMachine,
)
)
def test... |
"""This program was created on 12/04/2015
It takes an user inputted string
encrypts it with the Transposition Cipher
and emails it to the users choice of person
https://www.facebook.com/AiiYourBaseRBel0ngToUs
"""
# SECURITY NOTICE
# THE EMAIL SENDS THE KEY NUMBER
# GET RID OF "myKey" in msg under main()
# to... |
from .table import TableCreate, TableOut, TableUpdate, TableBase # noqa
|
test = { 'name': 'q3_1_4',
'points': 1,
'suites': [ { 'cases': [ {'code': '>>> type(relative_risk(NHS)) in set([float, np.float64])\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> np.isclose(round(float(relative_risk(NHS)), 3) - 0.474, 0)\nTrue', 'hidden': Fal... |
#merges observational notation from Gsheet link = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQ5JRPuanz8kRkVKU6BsZReBNENKglrLQDj1CTWnM1AqpxdWdWb3BEEzSeIcuPq9rSLNwzux_1l7mJb/pub?gid=1668794547&single=true&output=csv'
import sys
import numpy as np
import pandas as pd
import os.path
from datetime import datetime
im... |
from rlcard.utils.utils import print_card
from rlcard.games.base import Card
class HumanAgent(object):
''' A human agent for Hearts.
'''
def __init__(self, num_actions):
''' Initilize the human agent
Args:
num_actions (int): the size of the output action space
'''
... |
import numpy as np
from numba import jit
from multiprocessing import Pool
from functools import partial
@jit(forceobj=True)
def construct_bin_column(x: np.array, max_bins: int) -> np.array:
x, cnt = np.unique(x, return_counts=True)
sum_cnt = np.sum(cnt)
if len(x) == 1:
return np.array([], 'float64... |
from input_device import InputDevice
import core.app.app_server as app_server
class AppDevice(InputDevice):
"""
Simple wrapper around the app server
"""
def __init__(self, host, port):
super(AppDevice, self).__init__()
self.host=host
self.port=port
def main(self, outp... |
# -*- coding:utf-8 -*-
"""
在插件热插拔的基础上实现中间件
PS:
需要注意的是,插件目录如果有同名文件,则只会导入第一个目录中找到的文件
"""
import copy
import logging
import loader
from inspect import isfunction, getargspec
# 中间件
class Middleware(object):
def __init__(self, logger=logging):
self.logger = logger
self.funcList = [] # 要执行的... |
from django.apps import AppConfig
class HeadsupappConfig(AppConfig):
name = 'HeadsUpApp'
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
tintri_flr.py
~~~~~~~~~~~~~~~~~~~~~~~~
CLI programm to Map and Unmap a Tintri Snapshot to a virtual LINUX machine
Requirements:
The programm needs "root" rights or "sudo" to run.
This is needed because it uses the commands "mount" and "unm... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import subprocess
setup(name="stitchclient",
version="0.9.3.post1",
description="A Stitch API client for Python",
author="Stitch",
author_email="support@stitchdata.com",
url="https://github.com/stitchdata/python-stitch-cli... |
from __future__ import annotations
from typing import Callable, List, Optional, Sequence, Tuple
import numpy as np
import thinc
from cytoolz import itertoolz
from thinc.api import Model, chain, concatenate
def get_model_preds(model: Model, texts: List[str], classes: np.ndarray) -> List[str]:
"""
Get model p... |
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from scipy.linalg import pascal, toeplitz
__doc__ = """
See :ref:`Polynomials` for details and examples.
.. toctree::
:hidden:
tools/polynomial
"""
class Polynomial(object):
r"""
Polynomial function and its Abel transform.
... |
def ___gmres_stop_criterion___(tol, atol, ITER, maxiter, BETA):
"""
:param tol: relative tolerance.
:param atol: absolute tolerance
:param ITER:
:param maxiter:
:param BETA: A list of beta (residual) of some recent iterations.
:return:
"""
assert tol < 0.01, f"tol={tol} too large,... |
from __future__ import print_function
import re
import pytest
from click.testing import CliRunner
from dagster.cli.pipeline import execute_scaffold_command, pipeline_scaffold_command
from .test_cli_commands import (
valid_external_pipeline_target_args,
valid_external_pipeline_target_cli_args,
)
def no_pri... |
#!/usr/bin/env python
# roulette.py - a russian roulette for phenny
import random
deaths = ("valt dood.", "ziet er verbaasd uit.", "schiet zichzelf overhoop.",
"maakt het meubilair vuil.", "- in Soviet Russia, gun levels you.", "nu als spook!",
"gaat naar de eeuwige jachtvelden.", "heeft nu hoof... |
from Qt import QtWidgets, QtCore
DEFAULT_COLOR = "#fb9c15"
class View(QtWidgets.QTreeView):
data_changed = QtCore.Signal()
def __init__(self, parent=None):
super(View, self).__init__(parent=parent)
# view settings
self.setAlternatingRowColors(False)
self.setSortingEnabled(T... |
#!/usr/bin/env python
import base64
import random
from flask import Flask, render_template, request
from flags import flags
from create_hearts import get_hearts_svg
app = Flask(__name__)
@app.template_filter("base64")
def encode_as_base64(xml_string):
return base64.b64encode(xml_string.encode("ascii")).decod... |
from find_successor_in_bst import find_successor_of_node_in_bst, Node
import unittest
class Test_Case_Find_Successor_In_Bst(unittest.TestCase):
def test_find_successor_in_bst(self):
root = build_binary_search_tree([1,2,3,4,5,6,7])
three_node = root.left_child.right_child
ans = find_successo... |
"""
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
* What constitutes a word?
A sequence of non-space characters constitutes a word.
* Could the inp... |
from copy import copy
from typing import Union
from hdlConvertorAst.hdlAst._defs import HdlIdDef
from hdlConvertorAst.hdlAst._expr import HdlValueInt, HdlOp, HdlOpType, \
HdlValueId
from hdlConvertorAst.translate.verilog_to_basic_hdl_sim_model.utils import hdl_getattr, \
hdl_call
from hdlConvertorAst.translate... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GUI.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("D... |
# %matplotlib inline # magic
import pandas as pd
import matplotlib.pyplot as plt
import sys
import click
# dir stuff
# import os
# os.getcwd()
# os.chdir(r'C:\Users\lknogler\Desktop\python\nick\Day1')
# filename = 'oktoberfestgesamt19852016.csv'
@click.group()
def cli():
"""Can display and plot csv files"""... |
PICS_OF_CATS_DATASET = {
"id": "1",
"title": "This Study is about Pictures of Cats",
"author": "Peter Bull",
"description": "In this study we prove there can be pictures of cats.",
}
ATOM_DATASET = "../resources/atom-entry-study.xml"
|
########################################################################################################################
__doc__ = \
"""
This add the oddity fixing functionality. Generally odd corner cases.
Formerly part of collapse_ring.py
"""
#######################################################... |
# Copyright (c) 2017, CNRS-LAAS
# 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 copyright notice, this
# list of conditions and the f... |
"""
Write a Python program to find those numbers
which are divisible by 7 and multiple of 5,
between 1500 and 2700 (both included).
"""
for num in range(1500, 2701):
if num % 5 == 0 and num % 7 == 0:
print(num)
|
# The MIT License (MIT)
#
# Copyright (c) 2016 Litrin Jiang
#
# 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, copy, modi... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from model_utils.fields import AutoCreatedField, AutoLastModifiedField
from . import JobStatus
class IndexedTimeStampedModel(models.Model):
created_at = AutoCreatedField(_("created"), db_index=True)
updated_at = AutoLastMod... |
import unittest
from minmax_heap import MinHeap, MaxHeap
class Node(object):
def __init__(self, name: str, distance: int):
self.name = name
self.distance = distance
def __repr__(self):
return f"({self.name},{self.distance})"
def __lt__(self, other):
return self.distance <... |
import numpy as np
from imageio import formats
from imageio.core import Format
from . import read, write
EXTENSIONS = '.mha', '.mhd'
class MetaImageIOFormat(Format):
def _can_read(self, request):
return request.mode[1] in self.modes and request.extension in EXTENSIONS
def _can_write(self, request)... |
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2021/6/22 16:13
Desc: 东方财富网-经济数据-银行间拆借利率
http://data.eastmoney.com/shibor/shibor.aspx?m=sg&t=88&d=99333&cu=sgd&type=009065&p=79
Attention: 大量获取容易封 IP, 建议 20 分钟后再尝试或者切换 WIFI 为手机热点, 也可以修改本函数只更新增量
"""
import pandas as pd
import requests
from bs4 import BeautifulSoup
f... |
"""
This problem will show how to use some of pytacs more advanced load setting proceedures.
The nominal case is a 1m x 1m flat plate. The perimeter of the plate is fixed in
all 6 degrees of freedom. The plate comprises 900 CQUAD4 elements.
We consider two structural problems:
1. A static case where a 10 kN point f... |
from xml.etree import ElementTree
from sickle import Sickle
from sickle.iterator import OAIResponseIterator, OAIItemIterator
from sickle.oaiexceptions import BadArgument, BadResumptionToken, NoSetHierarchy
import urllib.parse
import logging
import random
import os
class InvalidPrefixError(Exception):
pass
... |
"""test create ddf dataset from csv"""
from ddf_utils.cli import from_csv
from click.testing import CliRunner
import os
from tempfile import mkdtemp
from ddf_utils.model.package import DDFcsv
from ddf_utils.package import create_datapackage
def test_from_csv():
input_dir = os.path.join(os.path.dirname(__file__),... |
import logging
from config import Config
try:
filename = Config()['default']['logging_dir']
except:
filename = '/tmp/dtt.log'
logging.basicConfig(filename=filename, level=logging.DEBUG)
def logger(name):
return logging.getLogger(name)
|
#!/usr/bin/env python3
# Josh Goodman sp20-516-220 E.Cloudmesh.Common.5
import time
from cloudmesh.common.StopWatch import StopWatch
if __name__ == "__main__":
StopWatch.start('timer1')
time.sleep(1)
StopWatch.start('timer2')
time.sleep(1)
StopWatch.stop('timer2')
StopWatch.start('timer3')
... |
from os import environ
from loader import Loader
import actions
LOADER = Loader()
def lambda_handler(event, context):
# return event
status = LOADER.personalize_cli.describe_dataset_group(
datasetGroupArn=event['datasetGroupArn']
)['datasetGroup']
actions.take_action_delete(status['status'])... |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... |
#!/usr/bin/env python
import argparse
import yaml
def read_param() -> dict:
"""
read parameters from terminal
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--ScreenType", help="type of screen ['enrichment'/'depletion']", type=str, choices=["enrichment", "depletion"]
)
... |
import unittest
from gerel.genome.edge import Edge
from gerel.genome.node import Node
import itertools
from tests.factories import genome_pair_factory
from gerel.algorithms.NEAT.metric import generate_neat_metric
class TestMetrics(unittest.TestCase):
def setUp(self):
# reset innovation number
Node... |
import argparse
import bs4
import os
import re
import requests
import signal
import sys
import unidecode
# determine if text is processed or not
PROCESSED_TEXT = False
# we can't split sentences on abbreviations that end in a '.'
ABB = [
'etc', 'mr', 'mrs', 'ms', 'dr', 'sr',
'jr', 'gen', 'rep', 'sen', 'st', '... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# Advent of Code 2018 Day 13
#
from operator import add
import numpy as np
# Read file and extract dependencies
file = open("../inputs/Advent13", 'r')
input = [row[:-1] for row in file]
def visualise_grid():
outgrid = np.copy(grid)
for a, b, c, d in carts:
outgrid[b[0], b[1]] = c
for i in ran... |
from __future__ import annotations
from pentagram.parse.group import parse_group
from pentagram.parse.line import parse_lines
from pentagram.parse.statement import parse_statements_block
from pentagram.parse.word import parse_word_lines
from pentagram.syntax import SyntaxBlock
def parse(source: str) -> SyntaxBlock:
... |
from flask import Blueprint
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_login import current_user
from flask_login import login_required
from flask_login import login_user
from flask_login import logout_user
from werkzeug.urls import url_pa... |
from pathlib import Path
import typer
from cookiecutter.main import cookiecutter
from grapl_common.utils.find_grapl_root import find_grapl_root
from grapl_template_generator.rust_grpc_service.create_rust_grpc_service_args import (
CreateRustGrpcServiceArgs,
)
from grapl_template_generator.rw_toml import ReadWriteT... |
class SplitRule:
def __init__(self, attribute, split_value):
self.attribute = attribute
self.split_value = split_value
def __str__(self):
return "A" + str(self.attribute) + " > " + str(self.split_value)
|
#Script để tải truyện từ Truyencv
#Script tải html từng chương truyện về, sau đó extract lấy text, ghi vào file Ketqua.txt
from bs4 import BeautifulSoup
import requests
import fileinput
import random
import time
import os
headers = {
'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.0; App Runtime for Chrome Dev B... |
import numpy as np
import matplotlib.pyplot as plt
import sys
from pdb import set_trace
np.random.seed(0)
if len(sys.argv) < 2:
print("Usage: python xx.py fpath fig_title out_file_name")
exit(0)
fpath = sys.argv[1]
data = np.loadtxt(fpath, delimiter=',')
nrows = 6
ncols = 8
idxes = np.random... |
from web.app import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from web.app import login_manager
import telegram.chat.states as states
from sqlalchemy import or_
from time import time
import jwt
from flask import current_a... |
"""
matread1.py
A demo program for reading in a matrix then printing it out
"""
from __future__ import print_function
import sys
import numpy
from np_helper import loadmatrix1, printmatrix1
def read1(argv):
if len(argv) < 2:
print("Needs an input file name on arg1", file=sys.stderr)
sys.exit(1)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.