text string | size int64 | token_count int64 |
|---|---|---|
import string
import spacy
from text_studio.utils.timer import timer
from text_studio.transformer import Transformer
class SpacyTokenizer(Transformer):
def setup(self, stopwords=None, punct=None, lower=True, strip=True):
spacy.cli.download("en_core_web_sm")
self.nlp = spacy.load(
"en_... | 925 | 285 |
import ptypes
from ptypes import *
from . import umtypes, ketypes, mmtypes
from .datatypes import *
class SYSTEM_INFORMATION_CLASS(pint.enum):
_values_ = [(n, v) for v, n in [
(0, 'SystemBasicInformation'),
(1, 'SystemProcessorInformation'),
(2, 'SystemPerformanceInformation'),
(3,... | 25,336 | 8,526 |
from OpenGL import GL
from PIL import Image
from pathlib import Path
import numpy as np
import gc
import os
import ctypes
GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1
VBO = None
VAO = None
TEXTURE = None
SHADER = None
vertexData = [
-1.0, -1.0, 0.0, 0.0, 1.0,
-1.0, 1.0, 0.0, 0.0, 0.0,
1.0, 1.0, 0.0, 1.0,... | 3,829 | 1,699 |
# Time: 0.72 s
movies = []
for _ in range(int(input())):
movies.append(tuple(map(int, input().split())))
movies.sort(key=lambda x: x[1])
last_end_time = 0
movie_count = 0
for start_time, end_time in movies:
if start_time >= last_end_time:
last_end_time = end_time
movie_count += 1
print(movi... | 329 | 130 |
import os
'''
path and dataset parameter
配置文件
'''
DATA_PATH = 'data'
PASCAL_PATH = os.path.join(DATA_PATH, 'pascal_voc')
CACHE_PATH = os.path.join(PASCAL_PATH, 'cache')
OUTPUT_DIR = os.path.join(PASCAL_PATH, 'output') # 存放输出文件的地方,data/pascal_voc/output
WEIGHTS_DIR = os.path.join(PASCAL_PATH, 'weights') # ... | 1,487 | 744 |
from typing import List
from wtforms import ValidationError
from sarna.core.roles import valid_auditors, valid_managers
from sarna.model import User
def users_are_managers(_, field):
users: List[User] = field.data
if type(users) != list:
users = [users]
for user in users:
if user.user_... | 707 | 220 |
from os.path import join, splitext
from uuid import uuid4
import datetime
from django.db import models
#from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
from django.urls import reverse
from django.contrib.auth.models import User
# Create your models here.
#@... | 16,133 | 5,075 |
'''
Description:
Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops en... | 2,370 | 701 |
"""
-------------------------------------------------
# @Project :外卖系统
# @File :shopping
# @Date :2021/8/8 10:21
# @Author :小成
# @Email :1224069978
# @Software :PyCharm
-------------------------------------------------
"""
import requests,os
from conf.host import *
from libs.login import *
from libs.shop ... | 1,195 | 438 |
import binascii
from winsniffer.gui.parsing.default_parser import DefaultParser
def prettify_mac_address(mac_address):
return ':'.join(map(binascii.hexlify, mac_address))
def get_protocol_stack(frame):
protocols = []
while hasattr(frame, 'data'):
protocols.append(frame.__class__.__name__)
... | 1,039 | 325 |
from typing import List
from reader import read_nums
nums = read_nums()
longest_reg_fragment: List[int] = []
reg_fragment: List[int] = []
current_gap = nums[1] - nums[0]
for i in range(1, len(nums)):
num1 = nums[i - 1]
num2 = nums[i]
gap = abs(num1 - num2)
if not reg_fragment:
reg_fragment.... | 772 | 278 |
"""A central mechanism for shop-wide settings which have defaults.
Repurposed from Sphene Community Tools: http://sct.sphene.net
"""
from django.conf import settings
satchmo_settings_defaults = {
# Only settings for core `satchmo` applications are defined here,
# (or global settings) -- all other defaults sh... | 1,586 | 558 |
from utils.postprocessing.PostProcessing import PostProcessing
from utils.postprocessing.SelectLabelsPostprocessor import SelectLabelsPostprocessor
| 148 | 35 |
from django.db import models
from django.utils import timezone
from django.core.validators import MinLengthValidator
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
email = models.EmailField(unique=True)
# Nickname is display name
nickname = models.CharField(
validato... | 1,227 | 361 |
# Copyright 2014 Tomas Machalek <tomas.machalek@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 require... | 12,465 | 3,975 |
import io
import torchvision.transforms as transforms
from PIL import Image
import onnxruntime as ort
import numpy as np
class_map = {
0: "10 Reais Frente",
1: "10 Reais Verso",
2: "20 Reais Frente",
3: "20 Reais Verso",
4: "2 Reais Frente",
5: "2 Reais Verso",
6: "50 Reais Frente",
... | 1,960 | 774 |
import arcpy
arcpy.env.workspace = "c:/temp/Donnees.gdb"
arcpy.env.overwriteOutput = True
listes = arcpy.ListDatasets()
for d in listes:
print(d) | 150 | 62 |
import random
import socket
import time
class client:
def __init__(self, name, address, socket, color):
self.name = name
self.address = address
self.socket = socket
self.color = color
sep = '\n'
def dice_roll():
return (str(random.randint(1, 6)) + ',' + str(random.randint(1... | 5,421 | 1,783 |
from django import template
from django.conf import settings
register = template.Library()
@register.filter
def sort_apps(apps):
count = len(apps)
print(f'count del index admin page: {count}')
apps.sort(
key=lambda x:
settings.APP_ORDER.index(x['app_label'])
if x['app_label... | 849 | 259 |
import os
import numpy as np
from matplotlib import pyplot as plt
class DrawGraphs:
def __init__(self,path_ONLY):
self.path_ONLY=path_ONLY
if not os.path.exists("./MakeGraph/graphs/"):
os.makedirs("./MakeGraph/graphs/")
def DrawEmotion(self,emotiondataarray):
colors = ["#... | 1,147 | 413 |
from enum import IntEnum
from typing import Optional, Any
from zkay.compiler.privacy.library_contracts import bn128_scalar_field
from zkay.transaction.types import AddressValue
def __convert(val: Any, nbits: Optional[int], signed: bool) -> int:
if isinstance(val, IntEnum):
val = val.value
elif isinst... | 926 | 327 |
from __future__ import absolute_import
from .classification import accuracy
from .ranking_1 import cmc, mean_ap
__all__ = [
'accuracy',
'cmc',
'mean_ap',
]
| 170 | 62 |
#This file contain examples for os module
#What is os module?
#is a module using for list files in folder, we can get name of current working directory
#rename files , write on files
import os
def rename_files():
# (1) get file names from a folder
file_list = os.listdir(r"C:\Users\user\Desktop\python\pythonCodes\... | 661 | 231 |
import logging
def result_db(database):
""" This function return the result of database.
They return a dict
:returns: a dict with all rows in database
:rtype: dict
"""
logging.info("The result of filter")
return list(database.find({}, {"_id": 0}))
| 279 | 82 |
class angle_adjustclass(): #ステアリングの切れ角を調整する
def __init__(self):
self.angle_adjust = 1.0
return
def angleincrease(self):
self.angle_adjust = round(min(2.0, self.angle_adjust + 0.05), 2)
print("In angle_adjust increase",self.angle_adjust)
def angledecrease(self):
self... | 493 | 193 |
import argparse
import math
import h5py
import numpy as np
import tensorflow as tf
import socket
import time
import resource
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(ROOT_DIR)
sys.path.append(os.path.join(R... | 18,351 | 6,514 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2018 all rights reserved
#
"""
Check that declarations of trivial protocols produce the expected layout
"""
def test():
import pyre
# declare
class protocol(pyre.protocol):
"""a trivial protocol"""
... | 1,015 | 330 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# create some logger details
import logging.handlers
# create a weather logger
weather_path = '/home/pi/WeatherPi/logs/Weather_Log_Data.log'
WEATHER_LOG_FILENAME = weather_path
# Set up a specific logger with our desired output level
weather_logger = logging.getLogger('Weath... | 1,210 | 402 |
import pytest
import requests
import logging
from pytest_bdd import scenarios, given, then, parsers
from requests.exceptions import ConnectionError
def is_responsive(url):
try:
response = requests.get(url)
if response.status_code == 404:
return True
except ConnectionError:
... | 2,358 | 732 |
from django.shortcuts import render
from django.views import View
from goods.models import GoodsChannel
from contents.models import ContentCategory
from .utils import get_categories
class IndexView(View):
def get(self, request):
# 定义一个字典categories包装所有数据
# categories = {}
# # 查询出所有商品频道数据并按照... | 1,922 | 824 |
from txtrader_monitor import Monitor
import json
from pprint import pprint
m = Monitor(log_level='WARNING')
def status(channel, data):
print(f"{channel}: {data}")
if data.startswith('.Authorized'):
pass
return True
def ticker(channel, data):
print(f"{channel}: {data}")
return True
def... | 615 | 216 |
import tensorflow as tf
import numpy as np
import itertools
import time
import random
import sys
def chunks(l, n):
# for efficient iteration over whole data set
for i in range(0, len(l), n):
yield l[i:i + n]
def read_file(file):
feats = []
wrds = []
vcb = {'UNK': 0}
with open(fi... | 5,055 | 1,669 |
#!/usr/bin/env python3
import os
import sys
import subprocess
default_contracts_dir = '/opt/cyberway/bin/data-dir/contracts/'
nodeos_url = os.environ.get('CYBERWAY_URL', 'http://nodeosd:8888')
os.environ['CYBERWAY_URL'] = nodeos_url
os.environ['CLEOS'] = '/opt/cyberway/bin/cleos'
args = {
'basedir': os.path.dirn... | 1,840 | 762 |
#!/usr/bin/python
import sys
import csv
reader = csv.reader(sys.stdin, delimiter='\t')
writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
userInfo = None
for line in reader:
thisType = line[1]
if thisType == 'A':
userInfo = line
elif thisType == 'B':
... | 500 | 169 |
import sys
import os
NODE_SCRIPT_EXEC_FAILED = -5
errCode = 0
try:
readFifo = sys.argv[2]
scriptLen = int(sys.argv[3])
taskId = int(sys.argv[4])
numTasks = int(sys.argv[5])
jobId = sys.argv[6]
fifo = os.open(readFifo, os.O_RDONLY)
bytes = bytearray()
while len(bytes) < scriptLen:
... | 724 | 308 |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_im... | 21,328 | 8,335 |
"""Begin PrOwl
"""
from .prowl import watch
if __name__ == '__main__':
watch()
| 86 | 37 |
# -*- coding:utf-8 -*-
from flask import Blueprint
main = Blueprint('main',__name__)
from . import views,errors
from ..models import Permission
@main.app_context_processor
def inject_permissions():
return dict(Permission=Permission) | 248 | 84 |
#!/usr/bin/env python
from setuptools import setup
from os.path import abspath, dirname, join
from codecs import open
here = abspath(dirname(__file__))
long_description = ''
with open(join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask_logging_decorator',
versi... | 954 | 333 |
from web3 import Web3
import contracts.doe_token_abi as doe_token_abi
def get_main_balance(w3, wallet):
contract_address = "0xf8E9F10c22840b613cdA05A0c5Fdb59A4d6cd7eF"
contract = w3.eth.contract(address=contract_address, abi=doe_token_abi.get_abi())
balanceOf = contract.functions.balanceOf(wallet).call()
... | 656 | 287 |
import os, sys
thisdir = os.path.dirname(os.path.abspath(__file__))
libdir = os.path.abspath(os.path.join(thisdir, '../../../'))
if libdir not in sys.path:
sys.path.insert(0, libdir)
| 188 | 76 |
# 072220
# CodeSignal
# https://app.codesignal.com/arcade/intro/level-6/mCkmbxdMsMTjBc3Bm/solutions
def array_replace(inputArray, elemToReplace, substitutionElem):
# loop through input array
# if element = elemToReplace
# replace that element
for index,i in enumerate(inputArray):
if i == elemT... | 402 | 133 |
import urllib.request, urllib.error, urllib.parse
import http.cookiejar
from getpass import getpass
import sys
def send(number,scheme):
username="9791011603"
passwd="D5222M"
message="You have successfully been enrolled for "+scheme
'''
username = input("Enter Username: ")
passwd = getpass()
message = input("En... | 1,574 | 658 |
# This is automatically-generated code.
# Uses the jinja2 library for templating.
import cvxpy as cp
import numpy as np
import scipy as sp
# setup
problemID = "tv_1d_0"
prob = None
opt_val = None
# Variable declarations
np.random.seed(0)
n = 100000
k = max(int(np.sqrt(n)/2), 1)
x0 = np.ones((n,1))
idxs = np... | 1,169 | 465 |
"""Construction of the master pipeline.
"""
from typing import Dict
from kedro.pipeline import Pipeline
from .data import pipeline as de
from .models import pipeline as ds
###########################################################################
# Here you can find an example pipeline, made of two modular pipeli... | 1,071 | 291 |
import datetime as dt
import re
from abc import ABC, abstractmethod
from decimal import Decimal
from typing import Any, Callable, Generator, Optional
from uuid import UUID
from aiochclient.exceptions import ChClientError
try:
import ciso8601
datetime_parse = date_parse = ciso8601.parse_datetime
... | 9,946 | 3,566 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [("meupet", "0015_pet_published")]
operations = [
migrations.AddField(
mod... | 866 | 288 |
from space_api.utils import generate_find, AND
from space_api.transport import Transport
from space_api.response import Response
class Update:
"""
The DB Update Class
::
from space_api import API, AND, OR, COND
api = API("My-Project", "localhost:4124")
db = api.mongo() # For a Mon... | 5,389 | 1,455 |
import dlib
import cv2
image = cv2.imread("../testeOpenCV.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
hogFaceDetector = dlib.get_frontal_face_detector()
faces = hogFaceDetector(gray, 1)
for (i, rect) in enumerate(faces):
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - ... | 432 | 192 |
from yaml import Node
from yamlen import Tag, TagContext
from preacher.compilation.argument import Argument
class ArgumentTag(Tag):
def construct(self, node: Node, context: TagContext) -> object:
key = context.constructor.construct_scalar(node) # type: ignore
return Argument(key)
| 305 | 84 |
#!/usr/bin/python
import socket
import struct
import math
import time
import Keithley_PS228xS_Sockets_Driver as ps
echoCmd = 1
#===== MAIN PROGRAM STARTS HERE =====
ipAddress1 = "134.63.78.214"
ipAddress2 = "134.63.74.152"
ipAddress3 = "134.63.78.214"
port = 5025
timeout = 20.0
t1 = time.time()
#ps.instrConnect(s... | 1,341 | 613 |
import OpenEXR
from navirice_get_image import KinectClient
from navirice_helpers import navirice_image_to_np
DEFAULT_HOST= 'navirice'
DEFAULT_PORT=29000
kin = KinectClient(DEFAULT_HOST, DEFAULT_PORT)
kin.navirice_capture_settings(rgb=False, ir=True, depth=True)
last_count=0
img_set, last_count = kin.navirice_get_... | 736 | 320 |
from typing import Optional
from datetime import datetime
from sqlite3.dbapi2 import Cursor
from ..config import config
from .. import schema
class CRUDUser():
model = schema.User
def create(
self,
db: Cursor,
qq: int,
code: str
) -> None:
user_dict = {
... | 2,386 | 751 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from strip_language_from_uri import LanguageStripper
import urlparse
correct, wrong = [], []
def strip_uri(uri, language_stripper):
parsed_uri = urlparse.urlparse(uri)
matched_language = language_stripper.match(parsed_uri.path)
if not matched_lang... | 2,424 | 752 |
import copy
from typing import Callable
import numpy as np
from .explicit import ExplicitIntegrator
from .integrator import Integrator
class ImplicitIntegrator(Integrator):
def generate_correct_function(
self, *args, **kwargs
) -> Callable[[np.ndarray, np.ndarray, float], np.ndarray]:
raise ... | 4,276 | 1,357 |
"""Module for results adapter."""
import logging
import os
from typing import List
from aiohttp import ClientSession
from aiohttp import hdrs
from aiohttp import web
from multidict import MultiDict
RACE_HOST_SERVER = os.getenv("RACE_HOST_SERVER", "localhost")
RACE_HOST_PORT = os.getenv("RACE_HOST_PORT", "8088")
RACE_... | 3,714 | 1,099 |
from django.db.models import Q
from hier.search import SearchResult
from hier.grp_lst import search as hier_search
from hier.params import get_search_mode
from .models import app_name, Task
def search(user, query):
result = SearchResult(query)
search_mode = get_search_mode(query)
lookups = None
if (se... | 786 | 257 |
"""
Adds one or many StitchBlocks to an embroidery pattern supplied as
pyembroidery.EmbPattern instance
Inputs:
Pattern: The pattern to be modified as pyembroidery.EmbPattern
instance.
{item, EmbPattern}
StitchBlock: The stitchblock(s) to add to the pattern.
... | 4,217 | 1,186 |
# Script used to read all help text from Neato.
# Simply connect Neato, update your port
# name ('/dev/neato') and run this script.
# All help markdown is written to a file in the
# same directory called neato_help.md
# Author: Brannon Vann brannon.vann@gmail.com
# License: MIT
# Run this script: python api.py
# Not... | 3,920 | 1,186 |
import sublime, sublime_plugin
import json
import useutil
class UseImportJumpCommand(sublime_plugin.TextCommand):
def description(self):
return 'Jump to File (Use-Import)'
def is_enabled(self):
return self.is_javascript_view()
def is_visible(self):
return self.is_javascrip... | 2,162 | 637 |
while True:
print('\n--- MULTIPLICATION TABLE ---')
num = int(input('Type a number integer: '))
if num < 0:
break
for c in range(1, 11):
print(f'{c} X {num} = {c*num}')
print('END PROGRAM') | 221 | 85 |
# 154. 寻找旋转排序数组中的最小值 II
# 剑指 Offer 11. 旋转数组的最小数字
#
# 20200722
# huao
# 这个其实还真是不好做呀
# O(n)的算法自然是非常简单的,直接扫一遍就完了
# 但是这个list本身是由两段排好序的list组合而成的,这个条件实在是不太好用上啊
from typing import List
class Solution:
def findMin(self, nums: List[int]) -> int:
minNum = nums[0]
for i in range(len(nums)):
minN... | 423 | 262 |
import pytest
import sys
# test value and failed initialization with characters
@pytest.mark.parametrize(
"offset,scale,lower,upper",
[
(1, 2, 0, 1),
(5, 4, -1, 1),
pytest.param("t", "e", "s", "t", marks=pytest.mark.xfail),
],
)
def test_scale_layer(offset, scale, lower, upper):
... | 1,202 | 437 |
# -*- coding: utf-8 -*-
from urllib.parse import urljoin
from datetime import datetime, timedelta
from .api import SwrveApi
class SwrveExportApi(SwrveApi):
""" Class for requesting stats with Swrve Export API
https://docs.swrve.com/swrves-apis/non-client-apis/swrve-export-api-guide
"""
kpi_factors... | 17,548 | 5,398 |
#创建数据库并把txt文件的数据存进数据库
import sqlite3 #导入sqlite3
cx = sqlite3.connect('FaceRes.db') #创建数据库,如果数据库已经存在,则链接数据库;如果数据库不存在,则先创建数据库,再链接该数据库。
cu = cx.cursor() #定义一个游标,以便获得查询对象。
#cu.execute('create table if not exists train4 (id integer primary key,name text)') #创建表
fr = open('log.txt') #打开要读取的txt文件
for line... | 605 | 323 |
import numpy as np
import matplotlib.pyplot as plt
import glob
from strawberryfields.decompositions import takagi
def jsa_from_m(m):
"""Given a phase sensitive moment m returns the joint spectral amplitude associated with it.
Args:
m (array): phase sentive moment
Returns:
(array): joint... | 2,801 | 1,222 |
"""
2997. 네 번째 수
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 68 ms
해결 날짜: 2020년 9월 26일
"""
def main():
num = sorted(map(int, input().split()))
d1 = num[1] - num[0]
d2 = num[2] - num[1]
if d1 == d2: res = num[2] + d1
elif d1 > d2: res = num[0] + d2
else: res = num[1] + d1
print(re... | 361 | 224 |
'''
Created on 10.08.2014
@author: Philip Peter <philip.peter@justgeek.de>
As long as you retain this notice you can do whatever you want with this stuff.
If we meet some day, and you think this stuff is worth it, you can buy me a
beer in return
Philip Peter
'''
import os
if __name__ == '__main__':
pass
inpu... | 679 | 257 |
from decimal import Decimal
from pathlib import Path
import requests
from django.core.management import BaseCommand
from django.db.models import F
from django.db.models.aggregates import Max, Min
from moviepy.video.VideoClip import ColorClip, TextClip
from moviepy.video.compositing.CompositeVideoClip import CompositeV... | 4,127 | 1,352 |
from wsgiref.simple_server import make_server
from nlabel.io.carenero.schema import create_session_factory, \
Text, ResultStatus, Result, Tagger, Vector, Vectors
from nlabel.io.carenero.common import ExternalKey
from nlabel.io.common import ArchiveInfo, text_hash_code
from nlabel.io.carenero.common import json_to_... | 9,097 | 2,618 |
# vim:ts=4:sw=4:et:
# Copyright 2012-present Facebook, Inc.
# Licensed under the Apache License, Version 2.0
# no unicode literals
from __future__ import absolute_import, division, print_function
import os
import pywatchman
import WatchmanEdenTestCase
class TestEdenUnmount(WatchmanEdenTestCase.WatchmanEdenTestCase... | 993 | 315 |
class A(object):
def foo(self):
print "foo"
class B(A):
def foo(self):
super().foo()
# <ref>
B().foo()
| 144 | 52 |
from PySide import QtGui, QtOpenGL, QtCore
from OpenGL import GL
from OpenGL import GL
from OpenGL.GL import shaders
from OpenGL.arrays import vbo
from OpenGL.GL.ARB import texture_rg
from OpenGL.GL.ARB import half_float_vertex
from ctypes import c_void_p
import numpy
import math
vert_src = """#version 120
attribute v... | 13,742 | 4,706 |
"""
COCO-style detection evaluation using
`pycocotools <https://github.com/cocodataset/cocoapi/tree/master/PythonAPI/pycocotools>`_.
| Copyright 2017-2020, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
# pragma pylint: disable=redefined-builtin
# pragma pylint: disable=unused-wildcard-import
# pragma pyl... | 12,867 | 3,983 |
def plot(width, height):
for j in range(height):
y = height - j - 1
print("y = {0:3} |".format(y), end="")
for x in range(width):
print("{0:3}".format(f(x,y)), end="")
print()
print(" +", end="")
for x in range(width):
print("---", end="")
prin... | 1,038 | 398 |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2018. Authors: see NOTICE file.
# *
# * 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... | 5,692 | 1,686 |
# Copyright 2015 Cray
# Copyright 2016 FUJITSU LIMITED
# Copyright 2017 Hewlett Packard Enterprise Development LP
#
# 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/lic... | 53,155 | 15,182 |
"""ГОСТ Р 51777-2001 Кабели для установок погружных электронасосов.
Общие технические условия (с Поправкой) """
import math
from scipy.optimize import fsolve
# TODO реализовать нормально ГОСТ, отрефакторить, учитывать разные формы кабеля
# TODO толщины слоев сделать
# TODO рисунок кабеля при инициализации
class ... | 7,032 | 2,851 |
from .order import Order
from .user import User
| 48 | 13 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 800 | 191 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import vplot
import scipy.signal as sig
#plt.rcParams["text.usetex"]=True
#plt.rcParams["text.latex.unicode"]=True
plt.rcParams.update({'font.size':16,'legend.fontsize':15})
import sys
# Check correct number of arguments
if (len(sys.argv) != ... | 8,035 | 4,018 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import array
import numpy as np
from numcodecs.compat import buffer_tobytes
def test_buffer_tobytes():
bufs = [
b'adsdasdas',
bytes(20),
np.arange(100),
array.array('l', b'qwertyuiqwertyui'... | 417 | 149 |
# Get a collection object for 'my_collection'
myColl = db.get_collection('my_collection')
| 92 | 29 |
from app.cache import get_from_cache, set_into_cache, delete_from_cache
import logging as _logging
import hashlib, json
logging = _logging.getLogger("matrufsc2_decorators_cacheable")
logging.setLevel(_logging.DEBUG)
__author__ = 'fernando'
CACHE_CACHEABLE_KEY = "cache/functions/%s/%s"
def cacheable(consider_only=No... | 2,051 | 554 |
import warnings
from dataclasses import dataclass
from typing import List, Optional
import torch
from falkon.utils.stream_utils import sync_current_stream
from falkon.mmv_ops.utils import _get_gpu_info, create_output_mat, _start_wait_processes
from falkon.options import FalkonOptions, BaseOptions
from falkon.utils i... | 8,929 | 2,907 |
'''
node.py
ancilla
Created by Kevin Musselman (kevin@frenzylabs.com) on 01/14/20
Copyright 2019 FrenzyLabs, LLC.
'''
import time
from .api import Api
from ..events import Event
from ...data.models import Service, Printer, Camera, ServiceAttachment, CameraRecording, Node
from ..response import AncillaError, Ancil... | 13,791 | 4,431 |
import codecs
import sys
RAW_DATA = "../data/ptb/ptb.train.txt"
VOCAB = "data/ptb.vocab"
OUTPUT_DATA = "data/ptb.train"
# 读取词汇表并建立映射
with codecs.open(VOCAB, "r", "utf-8") as f_vocab:
vocab = [w.strip() for w in f_vocab.readlines()]
word_to_id = {k: v for (k, v) in zip(vocab, range(len(vocab)))}
# 如果出现了被删除的低频词,替换... | 727 | 397 |
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template
bp_error = Blueprint("bp_error", __name__, url_prefix="/error")
# Specific Error Handlers
@bp_error.route("/default")
def default():
return render_template(
"error/error_base.html",
error_code=500,
header_n... | 661 | 221 |
import time
import datetime
from waveshare_epd import epd7in5_V2
from PIL import Image, ImageDraw, ImageFont
import calendar
import random
import os
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
fontdir = os.path.join(os.path.dirname(os.path.dirname(os.path.rea... | 7,611 | 3,015 |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class DistributedKartPadAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedKartPadAI')
def __init__(self, air):
DistributedObjectAI.__init__(... | 961 | 289 |
from PyQt5 import Qt
from PyQt5 import QtCore,QtWidgets,QtGui
import sys
import PyQt5
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QFileDialog, QGraphicsRectItem, QGraphicsScene
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import QSize
import cv2
import numpy as np
from matplotlib import pypl... | 22,644 | 8,804 |
import logging
import sys
import classes.iDb as db
# Set Logging Level
logging.basicConfig(level=logging.INFO)
class Friend:
def __init__(self, User, Friend):
self.user_id = User.user_id
self.friend_id = Friend.user_id
pass
def addFriend(self):
pass
def removeFriend(self)... | 1,551 | 453 |
# save frames asynchronously
import cv2 as cv
def frame_saver(queue, lock):
while True:
lock.take_lock()
cv.imwrite("frame.jpg", queue.peek()) # peek non existent
lock.release_lock()
| 214 | 71 |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from .views import PostListView, PostDetailView
urlpatterns = patterns('',
# URL pattern for the PostListView # noqa
url(
regex=r'^$',
view=PostListVi... | 1,529 | 374 |
import os
import click
from fasta_reader import read_fasta
from hmmer_reader import open_hmmer
from iseq.alphabet import alphabet_name
from iseq.hmmer3 import create_profile
from iseq.hmmer_model import HMMERModel
from iseq.model import EntryDistr
from .debug_writer import DebugWriter
from .output_writer import Outp... | 3,270 | 993 |
'''
Psuedo-joystick object for playback of recorded macros
'''
class PlaybackJoystick():
def __init__(self, playback_data):
self.playback_data = playback_data
self.t = 0
def setTime(self, t=0):
self.t = t
def getRawAxis(self, axis):
#TODO fix me, get correct index for ... | 847 | 266 |
#!/usr/bin/env python
# WRF-CMake (https://github.com/WRF-CMake/wps).
# Copyright 2018 M. Riechert and D. Meyer. Licensed under the MIT License.
import os
import sys
import shutil
import glob
import string
import itertools
import argparse
def link(src_path, link_path):
assert os.path.isfile(src_path)
if os.p... | 2,323 | 772 |
default_app_config = "freight.apps.FreightConfig"
__version__ = "1.5.1"
__title__ = "Freight"
| 95 | 40 |
import efr32bg1p.halconfig.halconfig_types as halconfig_types
import efr32bg1p.halconfig.halconfig_dependency as halconfig_dependency
import efr32bg1p.PythonSnippet.ExporterModel as ExporterModel
import efr32bg1p.PythonSnippet.RuntimeModel as RuntimeModel
import efr32bg1p.PythonSnippet.Metadata as Metadata | 307 | 105 |
import turtle
# initialization
t=turtle.Turtle()
t.speed(0)
t.up()
t.bk(200)
t.down()
# ask for data file name
fname=input('enter data file name: ')
print('reading from file: '+fname)
# create an empty list datalines
datalines=[]
# read lines from the data file into the list datalines
with open(fname) as df:
da... | 738 | 284 |