content stringlengths 5 1.05M |
|---|
#!/usr/bin/python
#
# Copyright 2019 Polyaxon, 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... |
import pytest
from centpy.equations import Equation1d
from centpy.parameters import Pars1d
class Scalar(Equation1d):
def initial_data(self):
return [20, 12]
def boundary_conditions(self, u):
u[0] = 10
def flux_x(self, u):
return 0.5 * u
def spectral_radius_x(self, u):
... |
##################################################################
# test T-splines mesh creation. The example is taken from Fig. 23,
# Isogeometric Analysis using T-splines
##################################################################
#importing Kratos modules
from KratosMultiphysics import *
from KratosMultiphys... |
from onegov.org import _
from onegov.form import Form
from wtforms import StringField, TextAreaField, SelectField
from wtforms.fields.html5 import URLField
from wtforms.validators import InputRequired
from onegov.org.models.external_link import ExternalLinkCollection
class ExternalLinkForm(Form):
title = String... |
#!/usr/bin/env python
from setuptools import setup
setup(name='broti',
version='1.0',
description='A bot for IRC',
author='Stefan Koch',
author_email='programming@stefan-koch.name',
packages=['broti', 'broti.modules', 'broti.providers'],
install_requires=['irc'],
entry_points... |
# Copyright The IETF Trust 2021, 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 law o... |
import sys
import os
import ssl
import time
import json
import MySQLdb
from datetime import datetime
import socket
import random
import threading
class GetSvaData():
isError = False
nowTime = datetime.now()
appname = ""
brokeip = ""
brokerport = ""
queueid = ""
companyid = ""
def __... |
import itertools
import numpy as np
from config import *
from time import time
def full(num, count):
return [num] * count
def zeros(count):
return full(0, count)
def ones(count):
return full(1, count)
def minus(count):
return full(-1, count)
class Pattern:
@classmethod
def divisions(cl... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from functools import wraps
import json
from django.db import models
from django import forms
from . import conf
__all__ = [
'override_djconfig',
'serialize']
def override_djconfig(**new_cache_values):
"""
Temporarily override config ... |
'''
Given a binary tree and a number, return true if the tree has a
root-to-leaf path such that adding up all the values along the
path equals the given number. Return false if no such path can be found.
'''
def targetsum(root, target):
if not root:
return False
if not root.left and not root.righ... |
# coding: utf-8
from abc import ABC, abstractmethod
from .ingredient_factory import (
NYPizzaIngredientFactory,
ChicagoPizzaIngredientFactory
)
from .pizza import (
CheesePizza,
ClamPizza
)
class PizzaStore(ABC):
def order_pizza(self, pizza_type):
pizza = self.create_pizza(pizza_type)
... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
"""Demonstrate the representations of values using different encodings.
"""
#end_pymotw_header
from codecs_to_hex import to_hex
text = u'pi: π'
encoded = text.encode('utf-8')
decoded = encoded.decode('utf-8')
print ... |
"""
Crie um programa que lê 6 valores inteiros pares e, em seguida, mostre na tela os valores lidos na ordem
inversa
"""
num = list(range(0, 11, 2))
print(num)
num.reverse()
print(num)
|
"""Tests for refactoring requests."""
from hamcrest import assert_that, is_
from tests import TEST_DATA
from tests.lsp_test_client import session
from tests.lsp_test_client.utils import StringPattern, as_uri
REFACTOR_TEST_ROOT = TEST_DATA / "refactoring"
def test_lsp_rename_function():
"""Tests single file fun... |
# draw a house
from turtle import *
forward(141)
left(90)
forward(100)
left(45)
forward(100)
left(90)
forward(100)
left(45)
forward(100)
done()
|
"""
WSGI config for djhome project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
from datetime import timedelta
import os
from django.core.wsgi import get_wsgi_application
from red... |
# Copyright 2017 F5 Networks
#
# 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, ... |
import json
import logging
from datetime import datetime
from typing import List, Dict, Any, Type
from pydantic import BaseModel
from csr.tabular_file_reader import TabularFileReader
logger = logging.getLogger(__name__)
class EntityReader:
"""Reader that reads entity data from tab delimited files.
"""
de... |
# -*- coding: utf-8 -*-
"""
A telemetry recording pipeline.
"""
import zmq
from ..cyloop.loop import IOLoop
from ..utils.msg import internal_address
from .handlers import Telemetry, TelemetryWriter
__all__ = ['PipelineIOLoop', 'create_pipeline']
def create_pipeline(address, context=None, chunksize=1024, filename="t... |
from urlparse import urlparse
from threading import Thread
import httplib, sys, multiprocessing
from Queue import Queue
import simplejson
import time
#Run as "time python perfprocess.py > out 2>&1 &" then "tail -f out"
num_processes = int(sys.argv[1])
num_threads = int(sys.argv[2])
num_requests = int(sys.argv[3])
num... |
#!/usr/bin/env python3
# Software Name: pyngsild
# SPDX-FileCopyrightText: Copyright (c) 2021 Orange
# SPDX-License-Identifier: Apache 2.0
#
# This software is distributed under the Apache 2.0;
# see the NOTICE file for more details.
#
# Author: Fabien BATTELLO <fabien.battello@orange.com> et al.
import threading
im... |
# -*- coding: utf-8 -*-
from datetime import datetime
class LedgerEntry(object):
def __init__(self):
self.date = None
self.description = None
self.change = None
def create_entry(date, description, change):
entry = LedgerEntry()
entry.date = datetime.strptime(date, '%Y-%m-%d')
... |
import unittest
from mock import patch, MagicMock
from add_user import AddUser
from user_repository import UserRepository
class AddUserTest(unittest.TestCase):
def setUp(self):
self.user_repo = UserRepository()
def test_add_user_should_add_user_to_repository(self):
self.user_repo.user_exists... |
import numpy as np
from casim.utils import to_binary, to_decimal
def test_to_binary():
assert np.array_equal(to_binary(54), [0, 0, 1, 1, 0, 1, 1, 0])
def test_to_decimal():
assert to_decimal(np.array([0, 0, 1, 1, 0, 1, 1, 0]), 8) == 54
|
# Using Try, Except, Finally and Else clauses
# handle errors and exceptions gracefully
# comment out examples as required so they run
# Test 1 - Generating a single error, change number1 to zero
# Test 2 - Adding a second error type, change number1 to 'apple'
# Test 3 - Use an 'else' clause if no error is generated,... |
from ansiblelint import AnsibleLintRule
class PlaysContainLogicRule(AnsibleLintRule):
id = 'EXTRA0008'
shortdesc = 'plays should not contain logic'
description = 'plays should not contain tasks, handlers or vars'
tags = ['dry']
def matchplay(self, file, play):
results = []
for log... |
from Crypto.Random.random import randrange
import argparse
def sequence(max_num_incl=2048, sequence_len=24):
print(f"Generating sequence of {sequence_len} numbers 1-{max_num_incl}...")
for i in range(sequence_len):
print(randrange(1, max_num_incl + 1))
def run():
cli_name = "germ-otp"
parser... |
#!/usr/local/bin/python
#
# t t y L i n u x . p y
#
# getLookAhead reads lookahead chars from the keyboard without
# echoing them. It still honors ^C etc
#
import termios, sys, time
if sys.version > "2.1" : TERMIOS = termios
else : import TERMIOS
def setSpecial () :
"set keyboard to read single c... |
# Generated by Django 2.1.7 on 2019-02-28 18:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("catalogsources", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="fetchedgame",
name="platforms"... |
import numpy as np
import scipy.signal as scisig
def FindPedestal(p, m):
noOutlier = RejectOutliers(p, m=m)
return np.mean(noOutlier)
def RejectOutliers(data, m=2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d / mdev if mdev else 0.
return data[s < m]
def WaveformDiscrimin... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass
from typing import Union
import torch
@dataclass
class DensePoseChartPredictorOutput:
"""
Predictor output that contains segmentation and inner coordinates predictions for predefined
body parts:
... |
import logging
from flask import redirect, render_template, request, url_for
from structlog import wrap_logger
from frontstage import app
from frontstage.common.authorisation import jwt_authorization
from frontstage.controllers import collection_instrument_controller, party_controller, conversation_controller
from fr... |
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from typing import Any, AsyncIterable, Callable, Iterable, List, Tuple, TypeVar, Union, cast
from urllib.parse import urlparse
from grpc import (
AuthMetadataContext,
Au... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import super
from future import standard_library
standard_library.install_aliases()
from vcfx.field.nodes import Field
#######
# TODO(cassidy): Figure out w... |
#! /usr/bin/env python
# -*- coding:UTF-8 -*-
# 一些比较好的代码片段
def pick_and_reorder_columns(listofRows, column_indexes):
return [ [row[ci] for ci in column_indexes ] for row in listofRows ]
def pairwise(iterable):
iternext = iter(iterable).next()
while True:
yield itnext(),itnext()
def dictFromSeq(s... |
__author__ = 'konradjk'
import gzip
import argparse
def main(args):
f = gzip.open(args.vcf) if args.vcf.endswith('.gz') else open(args.vcf)
g = gzip.open(args.output, 'w') if args.output.endswith('.gz') else open(args.output, 'w')
for line in f:
if line.startswith('##'):
g.write(line)... |
"""
MicroPython Eduponics mini water level sensor - demo
https://github.com/STEMinds/micropython-eduponics
MIT License
Copyright (c) 2021 STEMinds
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 w... |
import unittest
from translate.util.baidu_sign import generate_token
class BaiduSignTest(unittest.TestCase):
def test_token(self):
gtk = '320305.131321201'
self.assertEqual(generate_token('hello', gtk), '54706.276099')
self.assertEqual(generate_token('hello world are you ok ? this is funn... |
"""
A collection of functions that call Instagram Basic Display API endpoints.
Functions:
get_auth_url(app_id, redirect_url, state) -> string
get_short_token(app_id, app_secret, redirect_url, auth_code) -> string
get_long_token(app_id, app_secret, redirect_url, auth_code) -> string
refresh_long_token(to... |
import math
import torch
import torch.nn as nn
import numpy as np
from outside_index import get_outside_index, OutsideIndexCheck
from inside_index import get_inside_index, InsideIndexCheck
from inside_index import get_inside_index_unique
from offset_cache import get_offset_cache
from inside_index import get_inside_co... |
from move_images.tasks import get_posts, update_post
posts = get_posts()
for p in posts:
update_post(p)
|
from dataclasses import dataclass
import numpy as np
import random
from typing import Dict, Mapping
from entity_gym.environment import (
CategoricalAction,
DenseCategoricalActionMask,
Environment,
CategoricalActionSpace,
ActionSpace,
EpisodeStats,
ObsSpace,
Observation,
Action,
)
fr... |
import pandas as pd
import matplotlib.pyplot as plt
import os
'''
© 2018 Aaron Penne
Taken from https://github.com/aaronpenne/data_visualization
Assumes the data is already normalized.
'''
def make_output_dir(output_name):
output_dir = os.path.realpath(output_name)
if not os.path.isdir(output_dir):
o... |
from twisted.web.server import Site, Request
from twisted.web.resource import Resource
from twisted.internet import reactor, endpoints
root = Resource()
class Foo(Resource):
def render(self, request: Request): # $ requestHandler
print(f"{request.content=}")
print(f"{request.cookies=}")
p... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Population analyses based on cclib data."""
import logging
import numpy
from .calculationmethod import ... |
from django.test import TestCase
from authorization.views import LoginView, LoginRefreshView, RegisterView
class TestRegisterView(TestCase):
def setUp(self):
self.view = RegisterView()
def test_queryset_belongs_to_user_model(self):
self.assertEqual("User", self.view.queryset.model.__name__)
... |
# https://github.com/rafa-acioly/animal_case
import re
def _unpack(data):
if isinstance(data, dict):
return data.items()
return data
def to_snake_case(value):
"""
Convert camel case string to snake case
:param value: string
:return: string
"""
first_underscore = re.sub('(.)([... |
import _plotly_utils.basevalidators
class SlidersValidator(_plotly_utils.basevalidators.CompoundArrayValidator):
def __init__(self, plotly_name='sliders', parent_name='layout', **kwargs):
super(SlidersValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
#!/usr/bin/env python
# Class autogenerated from /home/sam/Downloads/aldebaran_sw/nao/naoqi-sdk-2.1.4.13-linux64/include/alproxies/alautonomouslifeproxy.h
# by Sammy Pfeiffer's <Sammy.Pfeiffer at student.uts.edu.au> generator
# You need an ALBroker running
from naoqi import ALProxy
class ALAutonomousLife(object):
... |
import numpy as np
import torch
import matplotlib.pyplot as plt
import numba as nb
def parity_mapping(state, parity):
'''
Function that does the following parity mapping:
Args:
state: a numpy array representing the number of photons in each mode.
parity: type of parity mapping done (0 or ... |
import transmitm
import pytest
def test_api():
"""Test imported names"""
assert all([
hasattr(transmitm, '__version__'),
hasattr(transmitm, 'Dispatcher'),
hasattr(transmitm, 'Tap'),
hasattr(transmitm, 'TCPProxy'),
hasattr(transmitm, 'UDPProxy'),
hasattr(transmit... |
import pytest
PREDICTION_TEXT = "This is a test prediction. If a finetune model predicts on this we may get an empty list as result."
@pytest.fixture(scope="module")
def model_group(indico):
results = indico.model_groups()
try:
return next(
result
for result in results
... |
from math import tan, pi
def polysum(n: int, s: int) -> float:
"""
n: number of sides,
s: length of sides
Return the sum of the area and square of the perimeter
of the regular polygon, rounded to 4 decimal places.
"""
area = (0.25 * n * s**2)/(tan(pi/n))
perimeter = n * s
return r... |
"""
The :mod:`fatf.utils.data.segmentation` module implements image segmenters.
.. versionadded:: 0.1.1
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
# pylint: disable=too-many-lines
from numbers import Number
from typing import List, Optional, Tuple, Union
import abc
import logging
import w... |
from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView
class Homepage(TemplateView):
template_name = 'index.html'
class BaseTemplateView(TemplateView):
template_name = 'base.html'
class Demo(CreateView):
template_name = 'stu... |
#!/usr/bin/env python
'''
readSequenceFromListTest.py: Example reading a list of PDB IDs from a local MMTF Hadoop sequence \
file into a tubleRDD.
'''
__author__ = "Mars (Shih-Cheng) Huang"
__maintainer__ = "Mars (Shih-Cheng) Huang"
__email__ = "marshuang80@gmail.com"
__status__ = "Warning"
import unittest
from pyspar... |
"""
database manager functions
edits text file databases
Functions: fillDB(), searchDB()
"""
def fillDB(data):
"""
This function will open memberDB and appends the data.
input = type str
example input = 'name money level daily\n'
void
"""
file = open("memberDB.txt","a")
fi... |
number = 0
def add_number():
global number
number += 1
def print_number():
print(f'number is {number}')
print('module executed') |
x = int(raw_input())
y = int(raw_input())
z = int(raw_input())
n = int(raw_input())
print sum(sum([[ [ [X,Y,Z] for Z in range(z+1) if X+Y+Z != 2 ] for Y in range(y+1)] for X in range(x+1) ], []), [])
|
import unittest
from RomanNumeralsConverter import RomanNumeralsConverter
class RomanNumeralsConverterTests(unittest.TestCase):
test_cases = [
[1,'I'],
[2,'II'],
[3,'III'],
[4,'IV'],
[5,'V'],
[6,'VI'],
[7,'VII'],
[8,'VIII'],
[9,... |
# 阶乘
# n! = 1x2x3x...n
def fact(n):
"""
1 定义的时候调用自己
2 要有停止条件
3 防止栈溢出,控制递归的次数
应用:查看当前目录先的所有子目录及文件...
"""
if n == 1:
return 1
return n * fact(n-1)
|
#!/usr/bin/env python
import csv, re
from datetime import datetime, timezone
inputFile = "log.csv"
outputFile = "log.adif"
contest = "ARRL-SCR"
# "CLASS-I" for individual.
# "CLASS-C" for club (non-school).
# "CLASS-S-EL" for elementary school.
# "CLASS-S-JH" for middle/intermediate/junior high school.
# "CLASS-S-HS"... |
import time
import unittest
from datetime import datetime
from nokia import NokiaObject
class TestNokiaObject(unittest.TestCase):
def test_attributes(self):
data = {
"date": "2013-04-10",
"string": "FAKE_STRING",
"integer": 55555,
"float": 5.67
}
... |
# -*- coding: utf-8 -*-
from os import getenv
from enum import Enum
# Verify that using ANSI color is supported
_color_is_supported: bool = getenv('ANSI_COLORS_DISABLED') is None
class _ANSIColor(Enum):
COLOR_BLACK = 30
COLOR_RED = 31
COLOR_GREEN = 32
COLOR_YELLOW = 33
COLOR_BLUE = 34
COLOR_... |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXX XXXXXX XXXXXXXXXXXXXX XXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXX XXXXXXXX XXXXXXXX XXX XXXXX XX XXXXXXXX XXXXXXXXXXXXXX XXXXXX XX XXX
XXXXXXX XXXXXXXXXXXXXX XXXX XXXXXXXXXXXXX XXX XXXXXXX XX XXXXX XXX XXXX XXXXXX
XXXXXXX X... |
"""
This is a script to convert the predictions to regions
-------------------------------------
Author: Sushanth Kathirvelu
"""
import json
import matplotlib.pyplot as plt
from numpy import array, zeros
import numpy as np
from scipy.misc import imread, imsave
from PIL import Image
mask = Image.open('../../training_ma... |
# python decorator function
import functools
print '************** partial function Test Programs **************'
print int('11111111',base=2)
print int('11111111',base=8)
print int('11111111',base=16)
int2 = functools.partial(int, base=2)
print int2('11111111')
max2 = functools.partial(max,10)
print max2(2,3,4,5... |
import ssl
import tarfile
import logging
import time
import os
import io
import tempfile
import http
import hashlib
from threading import Timer
from datetime import datetime, timedelta
from urllib import request
from pyVmomi import vim, vmodl
from subcontractor_plugins.common.files import file_reader, file_writer
""... |
"""Client to connect to a database server."""
import hmac
import socket
from contextlib import contextmanager
from typing import Dict, List
from luxdb.commands import (AddItemsCommand, ConnectCommand, CountCommand, CreateIndexCommand, DeleteIndexCommand,
DeleteItemCommand, GetEFCommand, Ge... |
# Generated by Django 2.2.5 on 2020-07-24 10:23
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... |
# -*- coding:utf-8 -*-
#########################################################
# Rutap Bot 2019 Timeform Module (By. Preta) #
# 모든 저작권은 Preta가 소유합니다. 모든 권리를 보유합니다. #
#########################################################
import time, datetime
def timeform(dt1):
now = datetime.datetime.now()
... |
_, k = list(map(int, input().strip().split(' ')))
a = list(input().strip().split(' '))
result = a[k:] + a[:k]
print(' '.join(result))
|
from __future__ import annotations
import datetime
from typing import Iterable, Optional
from django.db.models import QuerySet
from django.template import Library
from django.utils import timezone
from django.utils.safestring import SafeText, mark_safe
from markdown import markdown as md
from ..models import Show, T... |
from selenium import webdriver
from NewItems.pages.main_page import MainPage
from NewItems.pages.item_page import ItemPage
from NewItems.pages.trash_page import TrashPage
class Application:
def __init__(self):
self.driver = webdriver.Chrome()
self.main_page = MainPage(self.driver)
self.ite... |
import numpy as np
import copy
from unsafe_runaway import *
import time
from nose.tools import assert_raises
class mockup:
pass
def makeLaserData():
laser_data = mockup()
laser_data.range_max = 5.6
laser_data.angle_min = -2.1
laser_data.angle_increment = 0.06136
laser_data.ranges = list(1+np.random.rand(69... |
"""
Author: Jacob Dachenhaus, jdachenh@purdue.edu
Assignment: 05.4 - Hello Turtle
Date: 10/11/2021
Description:
Program that draws text with a limited selection of characters.
Currently hard-coded to draw "hello turtle"
Contributors:
None
My contributor(s) helped me:
[x] understand the assignment exp... |
class Solution:
"""
@param str: The string before proofreading.
@return: Return the string after proofreading.
有一些单词中有拼写错误,请编写一个程序,能够自动校对单词的拼写,并且返回正确值。
校对的规则如下:
如果有三个相同的字符连在一起,一定是拼写错误,去掉其中一个,如:ooops -> oopsooops−>oops。
如果有两对一样的字符(AABB的形式)连在一起,,一定是拼写错误,去掉第二对中的一个字符,如:helloo -> hellohelloo−>hello。
以上两条规则要... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2007 Søren Roug, European Environment Agency
#
# This is free software. You may redistribute it under the terms
# of the Apache license and the GNU General Public License Version
# 2 or at your option any later version.
#
# This program is distributed in th... |
# Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__all__ = ['Deny', 'Identifier', 'ScopedIdentifier', 'Style', 'Use']
from dataclasses import dataclass, field
from typing import List, Callable, IO, Optional... |
import unittest
from dpipe import make_dataset
import tensorflow as tf
DATAPATH_IMAGES = 'images_dataset'
DATAPATH_VIDEOS = 'videos_dataset'
def make_model():
inputs = tf.keras.Input(shape=(128, 128, 3))
x = tf.keras.layers.Flatten()(inputs)
x = tf.keras.layers.Dense(64, activation='relu')(x)
x = tf.ke... |
from absl import flags
from celery import Task
import tensorflow as tf
from pysc2.env import sc2_env
import importlib
from evolution.model_input import ModelInput
from evolution.model_output import ModelOutput
from evolution.model_config import ModelConfig
from common.env_wrapper import EnvWrapper
from common.... |
import math
import pyglet
from pyglet import gl
import graphicutils as gu
from app import colors
from .camera import Camera
def draw_lines(vertices):
pyglet.graphics.draw(
len(vertices) // 2,
gl.GL_LINES,
('v2f', vertices),
)
def draw_circle(x, y, r, color, mode=gl.GL_LINE_LOOP, re... |
import hashlib
def dict_to_hash(key):
"""
Given a dictionary `key`, returns a hash string
"""
hashed = hashlib.md5()
for k, v in sorted(key.items()):
hashed.update(str(k).encode())
hashed.update(str(v).encode())
return hashed.hexdigest()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: gexiao
# Created on 2017-09-08 15:28
import sys
sys.path.append('..')
import math
import pymongo
import json
import re
from datetime import datetime
from elasticsearch import Elasticsearch
from pymongo import MongoClient
from config.config import *
SHARDS_NUMB... |
from output.models.nist_data.atomic.name.schema_instance.nistschema_sv_iv_atomic_name_min_length_5_xsd.nistschema_sv_iv_atomic_name_min_length_5 import NistschemaSvIvAtomicNameMinLength5
__all__ = [
"NistschemaSvIvAtomicNameMinLength5",
]
|
# This script reads in a GTF transcript annotation and extracts the splice
# junctions. Exons must be in order.
# The output format is designed to match the STAR SJ file output format
from optparse import OptionParser
from pyfasta import Fasta
def getOptions():
parser = OptionParser()
parser.add_option("--f"... |
from PyPDF2 import PdfFileReader, PdfFileWriter
def merge_pdf(infnList, outfn):
pdf_output = PdfFileWriter()
for infn in infnList:
pdf_input = PdfFileReader(open(infn, 'rb'))
page_count = pdf_input.getNumPages()
for i in range(page_count):
pdf_out... |
#!/usr/bin/python
# vim:fileencoding=utf-8
# (c) 2011 Michał Górny <mgorny@gentoo.org>
# Released under the terms of the 2-clause BSD license.
import shutil, subprocess, tempfile
from ..exceptions import InvalidBashCodeError
from . import BashParser
_bash_script = '''
while
(
while read -r __GENTOOPM_CMD; do
... |
#!/usr/bin/env python
"""
Oracle procedures in schema
"""
import sys
import logging
from lib_properties import pc
import lib_oracle
import lib_common
from sources_types.oracle import schema as oracle_schema
from sources_types.oracle import procedure as oracle_procedure
def Main():
cgiEnv = lib_oracle.OracleEnv... |
# Generated by Django 3.2.3 on 2021-05-30 22:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='College',
fields=[
... |
import os
import time
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from scipy import signal
from matplotlib.ticker import StrMethodFormatter
# School ID = 03118942
# F=9+4+2=15=>1+5=6
myFreq=6000
A=4
# Βοηθιτικες Συναρτησεις
def PlotYLim(Max, Min):
plt.ylim... |
from chapter_04.binary_search_tree import BinarySearchTree
from chapter_04.binary_tree import BinaryTree
def is_binary_search_tree(tree):
return _is_bst(tree.root)
def _is_bst(node, min_val=None, max_val=None):
if not node:
return True
if (min_val and node.key < min_val) or (max_val and node.key... |
"""The following module demonstrates how to read files"""
import json
import csv
def write_json_file(file_name, json_file_content):
"""Write JSON file.
:type file_name:
:param file_name:
:raises:
:rtype:
"""
with open(file_name, 'w') as json_file:
json.dump(json_file_content, js... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Sione Taumoepeau and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import math
import frappe
from frappe import _
from frappe.utils import cstr, formatdate, cint, getdate, date_diff, add_days, time_diff_in_hours, rou... |
GITHUB_URL = 'https://github.com/esdandreu/gcal2clickup/tree/main'
RAWGITHUB_URL = 'https://raw.githubusercontent.com/esdandreu/gcal2clickup/main'
def readme(title: str = 'gcal2clickup') -> str:
# Returns a link to the readme
return f'{GITHUB_URL}#{title}'
def readme_image_url(filename: str) -> str:
# R... |
# coding: utf8
import cv2 as cv
if __name__ == '__main__':
# 替换字符列表
ascii_char = list(r"#8XOHLTI)i=+;:,. ")
# ascii_char = list(r"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
char_len = len(ascii_char)
# 读取图片
frame = cv.imread("img.jpg")
# 转灰度图
img_gray =... |
"""2019-05-28 10:50:34"""
|
# -*- coding:utf-8 -*-
from . import douyin
__all__ = ['douyin']
|
from typing import Any, Sequence, Tuple, cast, TypeVar, Dict
from scipy.stats import mode
from numpy.typing import NDArray
def windowed_mean(
array: NDArray[Any], window_size: Tuple[int, ...], **kwargs: Dict[Any, Any]
) -> NDArray[Any]:
"""
Compute the windowed mean of an array.
"""
reshaped = res... |
cmdId = RPR_NamedCommandLookup("_FNG_SELECT_NOTES_NEAR_EDIT_CURSOR")
RPR_Main_OnCommand(cmdId, 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.