content stringlengths 5 1.05M |
|---|
# ----------------------------------------------------------------------------
# Copyright (C) 2017 Verizon. 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
#
# ... |
dofd = {
"d1": {
"a": 1,
"b": 2
},
"d2": {
"c": 3,
"d": 4
}
}
print(dofd)
print(dofd["d1"])
print(dofd["d1"]["a"])
|
from setuptools import setup, find_packages
requirements = open("requirements.txt").readlines()
setup(name="blackjack",
setup_requires=['pbr>=1.9',
'setuptools>=17.1'],
pbr=True,
)
|
#-*-coding:utf-8-*-
import requests
import os
from bs4 import BeautifulSoup
from urllib import parse
import re
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView
class Complex(QWebEngineView):
def __init__(self, url):
from PyQt5.QtWidgets import QApplication
import sys
fro... |
from __future__ import print_function
from future.utils import iteritems
import dask.array as dsa
import xarray as xr
import numpy as np
def weighted_mean(da_data, da_weight, **kwargs):
"""calculate average of da_data weighted by da_weight
Parameters
----------
da_data : xarray.DataArray
Dat... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
This directory contains modules for implementing a productionized RoBERTa model.
These modules implement the same Transformer components that are implemented in
the fairseq library, however they're distilled down to just... |
# Copyright (c) 2019 SUSE LINUX GmbH
#
# 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 w... |
import cv2, os
import numpy as np
import matplotlib.image as mpimg
height, width, chennels = 70, 200, 3
input_shape = (height, width, chennels)
def load_image(data_dir, image_file):
"""
Load RGB images from a file
"""
return mpimg.imread(os.path.join(data_dir, image_file.strip()))
def crop(image):... |
from sys import copyright
def main():
print(copyright)
if __name__ == '__main__': main() |
from puzzle import Puzzle
class MNPuzzle(Puzzle):
"""
An nxm puzzle, like the 15-puzzle, which may be solved, unsolved,
or even unsolvable.
"""
def __init__(self, from_grid, to_grid):
"""
MNPuzzle in state from_grid, working towards
state to_grid
@param MNPuzzle s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2017-12-13 13:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" perfectly centered window """
import tkinter
def center(tk):
w = 500
h = 150
sw = tk.winfo_screenwidth()
sh = tk.winfo_screenheight()
x = (sw - w) / 2
y = (sh - h) / 2
tk.geometry('%dx%d+%d+%d' % (w, h, x, y))
if __name__ == '__main__... |
#!/usr/bin/python
"""Reports the fraction of successful geocodes by borough."""
import json
import sys
import boroughs
import re
from collections import defaultdict
records = json.load(file(sys.argv[1]))
boros_re = '(New York|Manhattan|Brooklyn|Bronx|Queens|Staten Island), (?:NY|N\.Y\.)$'
total_by_borough = default... |
# Generated by Django 2.2.22 on 2021-05-25 17:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0059_remove_embedconfig_show_other_contributor_information'),
]
operations = [
migrations.AddField(
model_name='contribu... |
import json as json_lib
import requests
import logging
import pathlib
from typing import Dict
class GraphSession():
"""Serves as the Session for the Current Microsoft
Graph API."""
def __init__(self, client: object) -> None:
"""Initializes the `GraphSession` client.
###... |
import gc
import uos
import os
import machine
import platform
import app
import board
from fpioa_manager import *
import pwmc
board_info=board.board_info()
file_list = os.ls()
for i in range(len(file_list)):
if file_list[i] == '/init.py':
import init
|
import glob
from pwn import *
shellcode = asm("""
mov rdi, 0x1337
""", arch="amd64", os="linux")
p = process(glob.glob('/challenge/embry*'))
print(p.recv(timeout=2).decode())
p.send(shellcode)
print(p.recvall().decode()) |
# Rasterize a shapefile with PIL
# https://github.com/GeospatialPython/Learning/raw/master/hancock.zip
try:
import Image
import ImageDraw
except:
from PIL import Image
from PIL import ImageDraw
import shapefile
r = shapefile.Reader("hancock.shp")
xdist = r.bbox[2] - r.bbox[0]
ydist = r.... |
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
"""
Anagram: string 2 is formed by some other permutation of characters from first string.
Idea1. is to loop over target string and
matching chars from first string. O(n**2)
Idea2: Loop over src string. ... |
import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import argparse
from app.db import Document, Image
import os
from PIL import Image, ImageDraw
def parseargs():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--database', type=str, required=Tr... |
import pandas as pd
import sqlite3
from sklearn.utils import parallel_backend
from sqlalchemy import create_engine
import sys
import joblib
import re
import nltk
from sklearn.base import BaseEstimator, TransformerMixin
nltk.download(['punkt', 'wordnet','stopwords'])
nltk.download('averaged_perceptron_tagger')
from ... |
import os, sys, time
import re
import json
import glob
import utils
def load_json_files(json_files) :
startime = time.time()
corpus_raw_french = u""
# corpus_raw_english = u""
if __name__ == "__main__":
if len(sys.argv) < 2 :
print(u"Please use # python beatstats.py settings.xml")
sys.exit(1)
else :
s... |
'''Conway's Game of Life
Canned patterns.
'''
from pkg_resources import ResourceManager
Patterns = {}
_EXT = '.life'
_rm = ResourceManager()
_pkg = 'GameOfLife.patterns.data'
for fname in [f for f in _rm.resource_listdir(_pkg, '.') if f.endswith(_EXT)]:
with _rm.resource_stream(_pkg, fname) as f:
Patter... |
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible, force_text
from django.utils.translation import ugettext_lazy as _
from operator import attrgetter
from .enums import (ZONE... |
from typing import Tuple
from kurt3.block import Block
from kurt3.blocks.input_slot import InputSlotFloat
from kurt3.project import Project
STYLES = {
"LEFT_RIGHT": "left-right",
"DONT_ROTATE": "don't rotate",
"ALL_AROUND": "all around"
}
def MoveSteps(project: Project, steps = 10) -> Block:
return Bl... |
# _*_coding:utf-8_*_
"""
Author: Lingren Kong
Created Time: 2020/4/3 14:17
"""
import graphviz
dot = graphviz.Digraph(node_attr={'fontname':'SimHei'},format='png') #建立对象, engine='fdp'
dot.node('CH','储户(用户)', fontname='SimHei', shape='box')
CHLIST = ['身份证号','姓名','性别','出生年月','电话','邮箱','邮编','地址']
for i in range(len(CHL... |
from abc import ABC, abstractmethod
from torch.nn import Module
class ModuleFactory(ABC):
@abstractmethod
def create(self) -> Module:
pass |
# encoding: utf-8
import subprocess
import os
import json
def get_ansible_config_path():
return os.path.join(os.getcwd(), 'onecloud/ansible.cfg')
def _run_cmd(cmds):
shell_cmd = ' '.join(cmds)
print(shell_cmd)
os.environ['ANSIBLE_FORCE_COLOR'] = '1'
config_file = get_ansible_config_path()
if... |
#!/usr/bin/env python3
import unittest
from unittest.mock import patch
import pandas
import numpy as np
from tmc import points
from tmc.utils import load, get_stdout, patch_helper
module_name="src.read_series"
read_series = load(module_name, "read_series")
ph = patch_helper(module_name)
@points('p03-13.1')
class R... |
ANSIBLE_METADATA = {
"metadata_version": "1.0",
"status": ["stableinterface"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: project_archive
short_description: unpack a project archive
description:
- Unpacks an archive that contains a project, in order to support handling versioned
... |
# -*- coding: utf-8 -*-
import requests
import subprocess
import argparse
import sys
import os
GITLAB_API = '/api/v4'
def clone_repo(url, path):
os.makedirs(path, exist_ok=True)
subprocess.run(['git', 'clone', url, path])
def get_subgroups_for_group(domain, cookies, group_id, recursive, insecure):
try:... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... |
# -*- coding: utf-8 -*-
#
# Copyright 2018-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
import asyncio
from aiokafka import AIOKafkaConsumer, TopicPartition
async def pull(loop, server, topic, group_id, batch_size=1, shuffle=False):
client = AIOKafkaConsumer(
topic,
loop=loop,
bootstrap_servers=server,
group_id=group_id,
auto_offset_reset='earliest',
e... |
from vk import VKAPI
class Likes(VKAPI):
method_class = 'likes'
def __init__(self, access_token=''):
super(Likes, self).__init__(access_token=access_token)
def add(self, **params):
self.set_method('add')
return self.send(params)
def delete(self, **params):
self.s... |
__author__ = 'DYEDEN'
|
#!/usr/bin/env python3
'''
This is the example application taken from the FoundationDB documentation here:
https://apple.github.io/foundationdb/class-scheduling.html
and re-made using gateaux structures.
This is functionally exactly the same, the only difference being the strucutres are
obvious and... |
from algobox.price import Ohlc
from enum import Enum
import talib
class OhlcPattern(Enum):
DOJI = 'DOJI'
DRAGONFLY_DOJI = 'DRAGONFLY_DOJI'
GRAVESTONE_DOJI = 'GRAVESTONE_DOJI'
HAMMER = 'HAMMER'
HANGING_MAN = 'HANGING_MAN'
INVERTED_HAMMER = 'INVERTED_HAMMER'
LONG_LEGGED_DOJI = 'LONG_LEGGED_... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appli... |
# This file is generated by profile_coder.py. DO NOT EDIT!
from __future__ import annotations
from gaphor.core.modeling.properties import (
association,
attribute,
relation_many,
relation_one,
)
from gaphor.UML import Class, Dependency, Element, Property, State
class AND(Class):
pass
class Gat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 5/22/19 3:40 PM
@author: matt
"""
import logging
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QListWidgetItem
from quiz_gui.quiz_uic import Ui_MainWindow
from quiz_cli.Question import Question
from quiz_cli.Quiz import Quiz
from quiz_... |
version = "03-00-00"
#DO NOT EDIT BY HAND!!
patch =2
packageName = 'pyBurstAnalysisGUI'
def getVersion():
return "%sp%s" % (version,patch)
pass
def getPackageName():
return packageName
pass
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Sandeep Raju. See LICENSE.txt for details.
from setuptools import setup
setup(
name='Subraminion',
version='0.0.3a',
url='https://github.com/sandeepraju/subraminion',
author='Sandeep Raju',
author_email='me@sandeepraju.in',
license=open('LICENSE.txt'... |
from enum import Enum
class PidTypes(Enum):
SPEED = 1
FUEL_LEVEL = 2
RPM = 3
MAF = 4
RUN_TIME = 5
class Units(Enum):
kmh = 1
percent = 2
rpm = 3
grams_per_second = 4
seconds = 5 |
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('ori_med.png')
median = cv2.medianBlur(img,5)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(median),plt.title('MedianBlur')
plt.xticks([]), plt.yticks([])
plt.show() |
# Functions to do colorful log printing in the terminal
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class plogger(object):
@staticmethod
def w... |
# MIT License
#
# Copyright (c) 2021 Clivern
#
# 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, modify, merge, publ... |
import os
from setuptools import setup, find_packages
import sklego
base_packages = [
"numpy>=1.16.0",
"scipy>=1.2.0",
"scikit-learn>=0.20.2",
"pandas>=0.23.4",
"patsy>=0.5.1",
"autograd>=1.2",
"Deprecated>=1.2.6",
"umap-learn>=0.4.3"
]
cvxpy_packages = ["cvxpy>=1.0.24"]
all_packages =... |
# */
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements. See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership. The ASF licenses this file
# * to you under the Apache License, Version 2.0 (the
# * "License... |
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import ClientMessage
from hazelcast.protocol.custom_codec import *
from hazelcast.util import ImmutableLazyDataList
from hazelcast.protocol.codec.client_message_type import *
from hazelcast.six.moves import range
REQUEST_TYPE = CLIENT_GE... |
"""Utility function for repositories checkout.
"""
import os
import re
JOB_NAME_REGEX = re.compile("job-name=\"([a-z0-9-]+)\"")
def find_job_name(line):
"""Find job name from labels.
Args:
line: str. A line in labels file from Downward API.
Returns:
job_name: Job name from labels.
"""
job_name = ... |
"""ARCTIC Imager"""
|
### BIFS GUI ###
### ###
### This file contains the GUI interface ###
### for the BIFS package ###
### ###
import cProfile, pstats
try:
# new in 3.7... |
from suds.bindings import binding
from suds.client import Client
binding.envns = ('soap12', 'http://www.w3.org/2003/05/soap-envelope')
DOMAINBOX_COMMANDS = {
'AccountQueryBalance': 'AccountQueryBalanceParameters',
'AddPublishingAlias': 'AddPublishingAliasParameters',
'AddWebHostingDatabase': 'AddWebHostin... |
import unittest
import libraries.morflessLibs as libs
# import test values and expected outputs
# main includes sidebar data
import unit.read_schematic_test_io.read_schematic_1_test_io as tv1
import unit.read_schematic_test_io.read_schematic_2_test_io as tv2
import unit.read_schematic_test_io.read_schematic_3_test_io ... |
import cv2 # noqa: F401
import numpy as np # noqa: F401
from ..openvino_base.base_model import Base
class PersonDetection(Base):
"""Class for the Person Detection Model."""
def __init__(
self,
model_name,
source_width=None,
source_height=None,
device="CPU",
... |
import os
import re
import logging
logger = logging.getLogger(__name__)
from astropy.io import registry
from astropy.table import Table, MaskedColumn
from astropy.time import Time
def _read_obslog(filename):
"""A customized function use to read the observing log
Args:
filename (str): Filename of the ... |
from datetime import datetime
# Third-party imports
import pytest
from mock import patch
from money import Money
# Project imports
from zmsavings.data.model import Goal, ProgressiveTotal, Transaction
def rur(value):
return Money(value, 'RUR')
@pytest.fixture
def fixture():
class Fixture(object):
pas... |
from readpe.readpe import * |
import sys
import os
import numpy as np
from scipy.stats import spearmanr
from collections import OrderedDict
directory = sys.argv[1]
filenames = os.listdir(directory)
"""
param sequence: list: A sequence.
param other_sequence: list: A permutation of sequence.
returns: np.array: an array of indices. If the indices ... |
from glob import glob
import os
from pathlib import Path
from math import log
from mamba.mamba_api import transmute as mamba_transmute
from joblib import Parallel, delayed
from rich.console import Console
console = Console()
unit_list = list(zip(["bytes", "kB", "MB", "GB", "TB", "PB"], [0, 0, 1, 2, 2, 2]))
def siz... |
# -*- coding: utf-8 -*-
import io
import logging
import subprocess
from diff_maker import DiffMaker
from counter import Counter
def build_diff(argv, structures, pgup_config):
logger = logging.getLogger("pgup.build_diff")
diffMaker = DiffMaker(argv, pgup_config)
diffMaker.prepare()
queries, names = di... |
"""This module handle bandpass of observation modes."""
from __future__ import division, print_function
import numpy as np
from .observationmode import ObservationMode
from .spectrum import CompositeSpectralElement, TabularSpectralElement
from . import units
from . import exceptions
def ObsBandpass(obstring, graphta... |
'''
Created on Jun 24, 2012
@author: jonathanfriedman
'''
import numpy as np
from pandas import DataFrame as DF
from numpy import array, asarray, zeros, log, var, matrix, tile
from core_methods import _get_axis
def alr(frame, ref=None, axis=0):
'''
Compute the additive log-ratio (alr) transformation
wi... |
# Copyright 2015 by Raytheon BBN Technologies Corp. All Rights Reserved.
"""
Unroll for loops (and possibly other conditional/iterative statements)
within a "with concur" block.
"""
import ast
import pyqgl2.ast_util
from pyqgl2.ast_util import ast2str
from pyqgl2.debugmsg import DebugMsg
from pyqgl2.qreg import QR... |
from .__dictkey import get, query, page
|
# coding: utf-8
"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import struct
import zlib
def to_png(data, size, level=6, output=None):
# type: (bytes, Tuple[int, int], int, Optional[str]) -> Union[None, bytes]
"""
Dump data to a PNG file. If `output` is `N... |
"""
A deterministic decoder.
"""
import numpy as np
import sys
import os.path as osp
from collections import defaultdict
from warnings import warn
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
# We include the path of the t... |
for i, v in enumerate(['running', 'with', 'scissors']):
print i, v
|
from ._tools import *
from ._config import * |
import nltk
# with open('football.txt', 'r') as f:
# sample = f.read().encode('ascii', 'ignore')
#
# sentences = nltk.sent_tokenize(sample)
sentences=["CNN.com delivers the latest breaking news and information on the latest top stories, weather, business, entertainment, politics, and more",
"Flights to ... |
'Type library'
__all__ = []
from cartocomutils import _esriGraphicsSymbols
from cartocomutils import Enumeration, IndexProperty, _IIDMap, _CLSIDMap, _RecordMap
import uuid
|
import requests
def dataFromPincode(pincode):
url = f'https://api.postalpincode.in/pincode/{pincode}'
response = requests.request('GET', url)
return response.json()
|
from django.db import models
from django.urls import reverse
from sell.fields import ThumbnailImageFieldFile
from sell.fields import ThumbnailImageField # Define custom field
# Create your models here.
class Merchandise(models.Model): # Define Merchandise table
title=models.CharField('TITLE',max_length=30)
bra... |
# load and display an image with Matplotlib
from matplotlib import image
from matplotlib import pyplot
import numpy as np
import os
import array as arr
folder_planetsfiles = 'planets_files/Titan/'
# filename = os.path.join(folder_planetsfiles, 'back_mat.png')
# filename = os.path.join('', 'back_mat.png')
filenam... |
from __init__ import init_args
from __init__ import get_driver
from __init__ import init_search
from __init__ import create_folder
from __init__ import download_all_current_page_images
import logging.config
if __name__ == "__main__":
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S ... |
import getpass, os, time, subprocess, math, pickle, queue, threading, argparse, time, backoff, shutil, gc
import numpy as np
import pandas as pd
import pyvo as vo
import traceback as tb
from timewise.general import main_logger, DATA_DIR_KEY, data_dir, bigdata_dir, backoff_hndlr
from timewise.wise_data_by_visit import ... |
from typing import TextIO, Tuple, Dict
from io import StringIO
Atom = Tuple[str, Tuple[str, str, str]]
CompoundDict = Dict[str, Atom]
def read_molecule(reader: TextIO) -> CompoundDict:
"""Read a single molecule from reader and return it, or return None to
signal end of file. The returned dictionary has one ke... |
# +-----------------------+---------+----------------+---------+----------+
# | hex(SHA224(password)) | CRLF | Trojan Request | CRLF | Payload |
# +-----------------------+---------+----------------+---------+----------+
# | 56 | X'0D0A' | Variable | X'0D0A' | Variable |
# +-------------... |
import sys, os, atexit, functools
try:
import sourceinspect as oinspect
except ImportError:
import taichi as ti
ti.warn('`sourceinspect` not installed!')
ti.warn(
'Without this package Taichi may not function well in Python IDLE interactive shell, '
'Blender scripting module and Python ... |
#!/usr/bin/env python
#
# mcmandelbrot
#
# An example package for AsynQueue:
# Asynchronous task queueing based on the Twisted framework, with task
# prioritization and a powerful worker interface.
#
# Copyright (C) 2015 by Edwin A. Suominen,
# http://edsuom.com/AsynQueue
#
# See edsuom.com for API documentation as wel... |
import tensorflow as tf
import numpy as np
from KENN2.layers.RangeConstraint import RangeConstraint
class ClauseEnhancer(tf.keras.layers.Layer):
"""Clause Enhancer layer
"""
def __init__(self, available_predicates, clause_string, initial_clause_weight, save_training_data=False):
"""Initialize th... |
import json
import flask
import pytest
from werkzeug.datastructures import MultiDict
from api.admin.exceptions import *
from core.marc import MARCExporter
from core.model import (
AdminRole,
ConfigurationSetting,
ExternalIntegration,
create,
get_one,
)
from core.model.configuration import External... |
import subprocess
import shlex
import os
from utils import absolute_path, file_exists
## Management of containers installation on correctly configured hosts
# The port for the host is assumed to be 2375
# It is the same one used to check if a host
# exposes a docker engine
def composeUp(composeFilePaths, host):
... |
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... |
"""Unit Tests for the SnowTrace class"""
from messari.blockexplorers import SnowTrace
import unittest
import os
import sys
import pandas as pd
import time
from typing import Dict
API_KEY = os.getenv('SNOWTRACE_API_KEY')
if API_KEY is None:
print('Please define SNOWTRACE_API_KEY in your runtime enviornment')
s... |
from ramda import *
from ramda.private.asserts import *
def union_test():
assert_equal(union([1, 2, 3], [2, 3, 4]), [1, 2, 3, 4])
|
# Copyright 2019-2020 Stanislav Pidhorskyi
#
# 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 i... |
from flask import Flask
from flask import jsonify
from flask import request
app = Flask(__name__)
import heapq
import nltk
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag
from nltk.corpus import wordnet as wn
import tensorflow as tf
import pickle
from model import Model
from nltk.tokenize import ... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('hs_tools_resource', '0007_auto_20160122_2240'),
]
operations = [
migrations.CreateModel(
nam... |
import time
import asyncio
from unittest import mock
import pytest
from waterbutler.core import remote_logging
from waterbutler.core import utils as core_utils
from waterbutler.core.path import WaterButlerPath
import tests.utils as test_utils
# Task testing doesn't play nice with unittest-style tests, so fallback ... |
from terminio.commandexecutor.commandexecutor import CommandExecutor
class ls(CommandExecutor):
def __init__(self, session):
super(ls, self).__init__(session)
self.grammer = {
'-l' : {
'description' : 'use a long listing format',
'type' : 'boolea... |
import logging
from datetime import timedelta
from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import ugettext as _
from TWLight.... |
# Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,
# … shows the first 11 ugly numbers. By convention, 1 is included.
# Read an integer that indicates the number of input to read
# The input are two integers, calculate how many ugly numbers are there bet... |
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import logging
import optparse
from collections import Counter
from pymongo import MongoClient
from dbFunction import dbFunction, initTrafficLight, initRunCount, saveStats, getRunCount
from globals import init
from helper... |
import os.path
import sys
sys.path = [os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')] + sys.path
from amqpsfw import amqp_spec
from amqpsfw import ioloop
from amqpsfw.server.server import Server
io_loop = ioloop.IOLoop()
Server(io_loop)
io_loop.start() |
#!/usr/bi.env python
import csv
import jinja2
import numpy as np
import os
import sys
def get_id(num):
return "{0:0=2d}".format(num)
def get_item(data, name):
item = data[name].decode('utf-8')
if len(item) == 0:
item = None
return item
def file_name(num, title, presenter):
lastname= prese... |
__author__ = 'Junn'
from django.utils.html import format_html, format_html_join
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.contrib.admin.widgets import AdminFileWidget
from django import forms
from django.utils.safestring import mark_safe
from django.contrib.admin.widgets impo... |
# coding=utf-8
"""
Tests for calc_split_avg.
"""
import shutil
import tempfile
import unittest
import logging
import os
from md_utils.calc_split_avg import bin_by_pattern, calc_avg_stdev, OUT_FNAME_FMT, write_avg_stdev, OUT_KEY_SEQ, \
AVG_KEY_CONV, main
from md_utils.md_common import read_csv, diff_lines, silent... |
import sys
import RPi.GPIO as GPIO
import pigpio
global row_count
global col_count
global row_col_val
pi = pigpio.pi()
#Parameter
GPIO.setmode(GPIO.BCM) ## Use board pin numbering
GPIO.setwarnings(False)
row_count = 4
col_count = 4
input_len = len(sys.argv)
def check_input(input, limit):
input_check = int(input)
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.