content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import os
os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES']=''
import numpy as np
from tensorflow.keras.layers import Input, Dense, SimpleRNN, GRU, LSTM, Bidirectional
from tensorflow.keras.models import Model
REC = LSTM
sequence_length = 3
feature_dim = 1
features_in = Input(batch_shap... | python |
import b128
import itertools
import os
import plyvel
import secp256k1
from binascii import unhexlify
from utxo.script import OP_DUP, OP_HASH160, OP_EQUAL, \
OP_EQUALVERIFY, OP_CHECKSIG
def ldb_iter(datadir):
db = plyvel.DB(os.path.join(datadir, "chainstate"), compression=None)
obf_key = db.get((unhexlify... | python |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Provider Model Serializers."""
import logging
from collections import defaultdict
from django.conf import settings
from django.db import transaction
from rest_framework import serializers
from rest_framework.fields import empty
from api.common... | python |
"""
collision_detection.py is used on each iteration to detect whether
an agent has collided with walls and to provide an adequate environment
response (i.e. updated position & velocity such that agen slides along the wall).
"""
import numpy as np
import pygame as pg
from decimal import Decimal
import configs as cfg
... | python |
import copy
import numpy as np
import pytest
import xarray as xr
from gcm_filters import Filter, FilterShape, GridType
from gcm_filters.filter import FilterSpec
def _check_equal_filter_spec(spec1, spec2):
assert spec1.n_steps_total == spec2.n_steps_total
np.testing.assert_allclose(spec1.s, spec2.s)
asse... | python |
import configparser
import logging
import os
import shutil
from pathlib import Path
from urllib.error import URLError
import intake
import matplotlib.image as mplimg
import pandas as pd
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
pkg_name = __name__.split("... | python |
class Instance(Element,IDisposable):
""" The base class for all instance objects. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def getBoundingBox(self,*args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def GetTotalTransform(self):
"""
GetTot... | python |
from layers import *
from encoding import *
import matplotlib.pyplot as plt
import csv
import sys
import getopt
import random
# Path to save the parameters
filename = 'parameters.npz'
# Train the RNN with the given parameters
def train(learning_rate, units, epochs):
# Try to load the parameters if they are sa... | python |
def selection_sort(some_list):
"""
https://en.wikipedia.org/wiki/Selection_sort
Split the list into a sorted/unsorted portion. Go through the list from left to right, starting with position 0 in
the unsorted portion. When we find the minimum element of the unsorted portion, swap it to the end of the sor... | python |
"""
Boolean Satisfiability
Interface Classes:
DPLLInterface
Interface Functions:
backtrack
iter_backtrack
dpll
"""
import random
class DPLLInterface(object):
"""DPLL algorithm interface"""
def bcp(self):
"""Boolean Constraint Propagation
Return an untyped point that result... | python |
import numpy as np
class Constant(object):
"""
Concatenates a constant value to the node attributes.
**Arguments**
- `value`: the value to concatenate to the node attributes.
"""
def __init__(self, value):
self.value = value
def __call__(self, graph):
value = np.zeros((g... | python |
import glob
from os import path as osp
import numpy as np
import pytest
import tqdm
import habitat_sim
NUM_TESTS = 100
TURN_DEGREE = 30.0
ACCEPTABLE_SPLS = {
("try_step", False): 0.97,
("try_step_no_sliding", False): 0.925,
("try_step", True): 0.82,
("try_step_no_sliding", True): 0.60,
}
base_dir =... | python |
""" Views related to rsync or FTP account access. """
__author__ = "William Tucker"
__date__ = "2018-03-13"
__copyright__ = "Copyright 2019 United Kingdom Research and Innovation"
__license__ = "BSD - see LICENSE file in top-level package directory"
from django.shortcuts import render, redirect
from uploader.ftp.fo... | python |
from dataclasses import dataclass, field
from typing import Optional
# TODO: remove default Hydra pallets - pallets will become required parameter
PALLETS = ["amm", "exchange", "transaction_multi_payment"]
@dataclass
class Config:
do_db_bench: bool = False
substrate_repo_path: str = "./substrate"
do_pall... | python |
import pyaudio
class AudioRecorder:
def __init__(self, channels_=2, format_=pyaudio.paInt16, rate_=44100, chunk_=256):
self.audio = pyaudio.PyAudio()
self.stream = self.audio.open(format=format_, channels=channels_,
rate=rate_, input=True, frames_per_buffer=chunk_)... | python |
import argparse
import logging
import gdk.commands.methods as methods
import gdk.common.parse_args_actions as actions
import pytest
def test_run_command_with_valid_namespace_without_debug(mocker):
# Integ test that appropriate action is called only once with valid command namespace.
args_namespace = argparse... | python |
# -*- encoding: utf-8 -*-
from django import forms
from .models import Image, UserProfile, Establishment
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.forms.widgets import TextInput, PasswordInput
from mysite.widgets import MyClearable... | python |
#!/usr/bin/python
# Copyright 2012 Google Inc. All Rights Reserved.
# Author: mrdmnd@ (Matt Redmond)
# Based off of code in //depot/google3/experimental/mobile_gwp
"""Code to transport profile data between a user's machine and the CWP servers.
Pages:
"/": the main page for the app, left blank so that users cann... | python |
from typing import Iterable
import torch
from torch import Tensor
def to_np(arr):
return arr.detach().cpu().numpy()
def to_t(t: Iterable, device: torch.device = 'cuda', dtype: torch.dtype = torch.float64) -> Tensor:
if isinstance(t, Tensor):
return t
return torch.tensor(t, device=device, dtype=... | python |
"""PivotCalculator
Pivot points is the top/bottom that the price has ever reached.
"""
from collections import deque, namedtuple
from operator import gt
class PivotCalculator(object):
def __init__(self, window_size=5, cmp=gt):
self.window_size = window_size
self.cmp = cmp
# exit_check: w... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | python |
import logging
import os
import yaml
from DataCuration.main import main as start_web_scrape
from util import create_folder
def load_config():
"""
Loads the configuration file
:return: Content of the configuration file
"""
with open('config.yaml', 'r') as file:
content = yaml.load(file, ... | python |
########################################
# PROJECT 1 - Linked List
# Author: Tony Sulfaro
# PID: A52995491
########################################
class Node:
# DO NOT MODIFY THIS CLASS #
__slots__ = 'value', 'next_node'
def __init__(self, value, next_node=None):
"""
DO NOT EDIT
... | python |
from html_parse.src.parser import Parser
import unittest
class TestParser(unittest.TestCase):
def test_remove_end_tags(self):
parser = Parser()
html_string = '<title>Hello</title>'
self.assertEqual(parser.remove_end_tags(html_string), '<title>Hello|;|')
def test_remove_end_tags_wit... | python |
"""
Book: Building RESTful Python Web Services
Chapter 3: Improving and adding authentication to an API with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from rest_framework.pagination import LimitOffsetPagination
class LimitOffsetPagination... | python |
# AUTHOR: Dalon Lobo
# Python3 Concept: Plotting line plot using matplotlib
# GITHUB: https://github.com/dalonlobo
import numpy as np
import matplotlib.pyplot as plt
# Create dummy x and y values. In this case I create values using numpy.
# This graph will show sine wave
x = np.arange(0, 10, 0.1) # Values for x coor... | python |
#!/usr/bin/env python
'''Tools for modifying halo data output files.
@author: Zach Hafen
@contact: zachary.h.hafen@gmail.com
@status: Development
'''
import copy
import glob
import numpy as np
import os
import pandas as pd
import galaxy_dive.galaxy_linker.linker as galaxy_linker
import galaxy_dive.analyze_data.halo_... | python |
import typing
from django.core.paginator import Paginator
class Pagination:
result_list: typing.Iterable
can_show_all: bool
show_all: bool
multi_page: bool
paginator: Paginator
page_num: int
list_per_page = 20
list_max_show_all = 2000
def __init__(self, object_list: typing.Iterab... | python |
import spotipy
from spotipy import util
from spotipy.oauth2 import SpotifyClientCredentials
import os
from dotenv import load_dotenv
from pprint import pprint
# load_dotenv()
#
# os.environ['SPOTIPY_CLIENT_ID'] = os.getenv('client_id')
# os.environ['SPOTIPY_CLIENT_SECRET'] = os.getenv('client_secret')
client_id = '... | python |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/odd-even-level-difference/1
def getLevelDiff(root):
h = {0: 0, 1: 0}
level = 0
populateDiff(root, level, h)
return h[0]-h[1]
def populateDiff(root, level, h):
if root == None:
return
l = level%2
h[l] += root.... | python |
############################################################################
# #
# Copyright (c) 2019 Carl Drougge #
# #
# Licensed u... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
import re
import os
import sqlite3
from bs4 import BeautifulSoup
from datetime import datetime
from loc_code import LOC_CODE
def jp_sqlite3_init(conn, cursor):
cursor.execute('''CREATE TABLE IF NOT EXISTS realestate (district text, dong text, a... | python |
#
# This is a dummy class to illustrate the use of cvui in a project
# that contains multiple files.
#
# Copyright (c) 2018 Fernando Bevilacqua <dovyski@gmail.com>
# Licensed under the MIT license.
#
import cvui
class Class1:
def __init__(self):
self.checked = [False]
def renderInfo(self, frame):
cvui.window(f... | python |
# from subtlepatterns.com
bg = """\
iVBORw0KGgoAAAANSUhEUgAAABIAAAANCAMAAACTkM4rAAAAM1BMVEXy8vLz8/P5+fn19fXt7e329vb4+Pj09PTv7+/u7u739/fw8PD7+/vx8fHr6+v6+vrs7Oz2LjW2AAAAkUlEQVR42g3KyXHAQAwDQYAQj12ItvOP1qqZZwMMPVnd06XToQvz4L2HDQ2iRgkvA7yPPB+JD+OUPnfzZ0JNZh6kkQus5NUmR7g4Jpxv5XN6nYWNmtlq9o3zuK6w3XRsE1pQIEGPIsdtTP3m2cYwlPv6... | python |
#!/usr/bin/env python
# PNG2PDF - Graphic interface related class and methods.
from gi.repository import Gtk, Gio
from gi.repository.GdkPixbuf import Pixbuf, InterpType
from wand.image import Image
from wand.exceptions import BlobError
class GuiWindow(Gtk.Window):
"""
PNG2PDF main window class, derivates fro... | python |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
METRIC_MAP = {
'consul_client_rpc': 'client.rpc',
'consul_client_rpc_failed': 'client.rpc.failed',
'consul_memberlist_degraded': 'memberlist.degraded',
'consul_memberlist_gossip': 'memberli... | python |
import os as os
import numpy as np
import pandas as pd
import re
import botutils
zx=pd.read_csv('./recipies_full_v2.csv',index_col=0)
def Recuperador(ingredientes,df=zx,Criterio='Ingredientes'):
len_ing=[]
match=[]
qw=0
for i in range(len(df)):
len_ing.append(len(df.Ingredientes.iloc[i].split(... | python |
from flask import render_template, session, flash, request, redirect
import tags
import awstools
import contestmode
import language
from datetime import datetime, timedelta
def home():
if contestmode.contest():
return redirect(f'/contest/{contestmode.contestId()}')
userinfo = awstools.getCurrentUserIn... | python |
import socket
import sys
import traceback
import random
def upper_monitor():
examples = ["Normal#ru-RU#Здраствуйте, меня зовут Жулдз, я робот гид", "Happy#ru-RU#Я так рада что вы тут",
"Sad#ru-RU#Простите, я вас не поняла, можете, пожалуйста, перефразировать",
"Angry#ru-RU#Алё, тупо... | python |
"""
https://tinkerpop.apache.org/docs/current/reference/
"""
from typing import Hashable, Generator, Iterable
import time
import pandas as pd
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __, GraphTraversalSource
from gremlin_python.driver.driver_remote_connection... | python |
import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management import BaseCommand
class Command(BaseCommand):
"""Djanho commandf to pause executuoin until datbase is availane"""
def handle(self, *args, **options):
self.stdout.write('Waiting for... | python |
import csv
import requests
def getArray():
# To use a local file, comment out this part, and uncomment the next part
r = requests.get('https://github.com/HeardLibrary/digital-scholarship/raw/master/code/pylesson/challenge4/cartoons.csv')
fileText = r.text.split('\n')
if fileText[len(fileText)-1] == '':... | python |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import logging
import os
import pytest
# Bail on the test if ly_test_tools doesn't exist.
pytest.importorskip(... | python |
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path... | python |
# library to do some animations
# assumes you want to do a x/y plot and an energy plot
# empty placeholders for different plots
def plot_animations(fig, ax, t, E, r):
nFrames = len(t) #number frames in our animation
n_part = r.shape[0] #number particles
# initialize our plots with empty data
trajs =... | python |
import os
import pathlib
import enum
import warnings
import colorama
import requests
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
import invoke
class MoleculeDriver(enum.Enum):
docker = 1
lxd = 2
vagrant = 3
class TestPlatform(enum.Enum):
linux... | python |
# Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.FileHandler.FileReader import FileReader
from typing import Optional
class WorkspaceReader(FileReader):
def __init__(self) -> None:
super().__init__()
self._workspace_name = None # type: Op... | python |
import jetson.inference
import jetson.utils
import time
import cv2
import numpy as np
timeStamp=time.time()
fpsFilt=0
#Importing custom dataset and using ssd-mobilenet-v2 model
net=jetson.inference.detectNet('ssd-mobibilenet-v2',['--model=models/YOUR MODEL/ssd-mobilenet.onnx','--input-blob=input_0','--output-cvg=scores... | python |
import os
from flask import Flask, jsonify
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
app = Flask(__name__)
if 'APP_CONFIG_FILE' in os.environ:
app.config.from_envvar('APP_CONFIG_FILE')
else:
app.config.from_pyfile('config/production.py')
db = ... | python |
import os
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', hours=2)
def main():
print('[!] Starting crawling.')
os.system('python -m scrapy crawl imdnews')
print('[!] Ending crawling.')
print('[!] Sending messages.')
os.sy... | python |
# coding: utf-8
from setuptools import setup, find_packages
import os
# not so bad: http://joebergantine.com/blog/2015/jul/17/releasing-package-pypi/
version = __import__('filer_addons').__version__
def read(fname):
# read the contents of a text file
return open(os.path.join(os.path.dirname(__file__), fname... | python |
from distutils.core import setup
setup(
name="pinax.checkers",
version="1.1",
author="Pinax",
author_email="development@eldarion.com",
url="https://github.com/pinax/pinax-checkers",
description="Style checker for Pinax and Eldarion OSS",
license="BSD",
packages=[
"pinax",
... | python |
#!/usr/bin/python3
import copy
import random
with open('tiles.txt') as fh:
lines = fh.readlines()
tilestrs = ''.join(lines).split('\n\n')
tilestrs = {int(t.split('\n')[0][5:9]):'\n'.join(t.strip().split('\n')[1:]) for t in tilestrs}
tiles = {}
for tilekey,tilestr in tilestrs.items():
tile = []
for rowstr... | python |
import model as mo
import view as vi
custlist=[]
page=-1
view = vi.viewer()
model = mo.model()
while True:
choice = view.hello()
if choice=="I":
custlist, page = model.inputI(custlist, page)
elif choice=="C":
custlist, page = view.inputC(custlist, page)
elif choice == 'P':
cust... | python |
def add_time(start, duration, start_day=''):
days = 0
real_duration = 0
days_of_week = [
'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'saturday'
]
hours_in_day = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 2... | python |
import json
from flask import request, send_file
from flask_restplus import Namespace, Resource, marshal
from .utils import *
from polylogyx.utils import require_api_key
from polylogyx.dao import carves_dao as dao
from polylogyx.dao import nodes_dao as nodedao
from polylogyx.wrappers import parent_wrappers as parentw... | python |
#!/usr/bin/python3
import re
with open("sar.txt") as fp:
reading = False
for l in fp:
s = l.split()
if len(s) == 0:
continue
m = re.match("[\d]{3,5}", s[0])
if (s[0] != "TOTAL") and (s[1] != "DO") and (m is None):
continue
if m is not No... | python |
#Jackknife reduction templates for NIRC2 and OSIRIS pipelines.
#Author: Sean Terry
def jackknife():
"""
Do the Jackknife data reduction.
"""
##########
#
# NIRC2 Format
#
##########
##########
# Ks-band reduction
##########
# Nite 1
target = 'MB07192'
sci_file... | python |
"""
This module contains helper functions for handling manipulation
of atom geometries
"""
import numpy as np
def _correct_vec(vec):
''' correct vectors in fractional coordinates
(assuming vectors minimal connection between 2 points)
'''
vec[np.where(vec >= 0.5)] -= 1.0
vec[np.where(vec < ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from src.gui.configtool.connectionControl import ConnectionControlGroupBox
from src.gui.configtool.controlLoopConfig import ControlLoopGroupBox
from src.gui.configtool.deviceJoggingControl import DeviceJoggingControl
from src.gui.configtool.droD... | python |
from protocols.video_protocols.UCSDProtocol import UCSDProtocol
from protocols.video_protocols.AvenueProtocol import AvenueProtocol
from protocols.video_protocols.ShanghaiTechProtocol import ShanghaiTechProtocol
from protocols.video_protocols.SubwayProtocol import SubwayProtocol
| python |
import logging
import re
from html import unescape
from urllib.parse import quote
from dvtag.utils import create_request_session
session = create_request_session()
class DoujinVoice():
def __init__(self, rjid: str) -> None:
self.rjid = rjid
self.dl_count = 0
self.url = ""
self.w... | python |
# vim: set tabstop=4 shiftwidth=4 expandtab
##############################################################################
# Written by: Ray Wang <rawang@novell.com>
# Date: 01/13/2008
# Description: Application wrapper for datetimepicker_dropdown.py
# be called by ../datetimepicker_dropdown_ops.py... | python |
from malcolm.yamlutil import check_yaml_names, make_block_creator
ADAndor3_driver_block = make_block_creator(__file__, "ADAndor3_driver_block.yaml")
ADAndor3_runnable_block = make_block_creator(__file__, "ADAndor3_runnable_block.yaml")
__all__ = check_yaml_names(globals())
| python |
import torch
import torch.nn as nn
import embeddings
from torch.autograd import Variable
import pdb
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class RNNEncoder(nn.Module):
def __init__(self, ninp, nhid, nlayers, bsz):
super(RNNEncoder, self).__... | python |
# Generated by Django 3.0.7 on 2020-08-22 19:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('staff', '0007_auto_20200820_2133'),
]
operations = [
migrations.AlterField(
model_name='staff',
name='mname',
... | python |
from flask_sqlalchemy import SQLAlchemy
from models import ProductArea
#This file contians the functions that compose the Product Area API
"""
The getProductAreas function, doesn't take any parameters.
the ProductArea.query.all() returns a list of all the ProductAreas in the ProductArea table
the serialize func... | python |
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | python |
#-*-coding:utf-8-*-
# date:2020-03-28
# Author: xiang li
import numpy as np # 加载 Numpy 库
import torch # 加载 Torch 库
'''
思考这一节的用法与实际项目的使用方式结合
'''
if __name__ == "__main__":
x = torch.tensor(3.1415)
print(x.floor())# tensor 向上取整
print(x.ceil())# tensor 向下取整
print(x.trunc())# tensor 取整数部分
... | python |
from __future__ import absolute_import
import numpy as np
from pydci import DCI
from ann_benchmarks.algorithms.base import BaseANN
class PYDCIKNN(BaseANN):
def __init__(self, dim, num_simple=10, num_composite=10):
self.name = 'PYDCIKNN(d=%d, num_simple=%d, num_composite=%d' % (
dim, num_simple... | python |
from .commands import (
MODULES, SYSTEMS, args
)
__all__ = ["args", "MODULES", 'SYSTEMS'] | python |
# -*- coding: utf8 -*-
from pathlib import Path
HOME = str(Path.home())
# BASE_URL = 'http://localhost'
BASE_URL_BACKEND = 'http://130.211.114.2'
BASE_API_SERVER = 'http://34.122.87.173'
PORT = 80
# PORT1 = 5000
# PORT2 = 5001
API_URL_BASE = "{}:{}".format(BASE_API_SERVER, PORT)
API_BACKEND = "{}:{}".format(BASE_UR... | python |
from mxnet.gluon import HybridBlock
import mxnet as mx
class SigmoidCrisp(HybridBlock):
def __init__(self, smooth=1.e-2,**kwards):
super().__init__(**kwards)
self.smooth = smooth
with self.name_scope():
self.gamma = self.params.get('gamma', shape=(1,), init=mx.init.One())
... | python |
from __future__ import unicode_literals
from django.db import models
from adventures.models import Adventure
class Picture(models.Model):
adventure = models.ForeignKey(Adventure)
img = models.ImageField(upload_to='pictures')
description = models.CharField(max_length=50)
funny_facts = models.TextField(max_length=25... | python |
import subprocess
import os
class Pythuby:
def __init__(self, code = False, file = False):
if code:
self.code = code
self.pythuby()
if file:
self.file = file
def pythuby(self):
with open("Temp.rb", "w") as temp_rb_script:
temp_rb_script.... | python |
import time
from typing import Optional, List
import graphene as g
from graphql.execution.base import ResolveInfo
from graphql_jwt.decorators import login_required, superuser_required
from contak import models
from contak.graphql.object_types import Contact
LOAD_DELAY = 0.5
class Query:
contact = g.Field(Contac... | python |
# -*- coding: utf-8 -*-
"""The preg front-end."""
import logging
from dfvfs.helpers import file_system_searcher
from dfvfs.lib import definitions as dfvfs_definitions
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver import resolver as path_spec_resolver
from plaso.dfwinreg import definitions a... | python |
from .tracker import Tracker
class Rifle:
def __init__(self , display_width , display_height , triggerHandler):
# openCV tracer
self.tracker = Tracker('orange')
# variables to scale the cursor to desired screen width and height
self.display_width = display_width
self.displa... | python |
# -*- coding: utf-8 -*-
"""
* This is a script file to associate images and IMU data.
* Copyright 2018 Nanjing University of Science and Technology
* Author: Zhixing Hou <zxhou@njust.edu.cn>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with ... | python |
# Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array.
# The returned array must be in sorted order.
# Expected time complexity: O(n)
# Example:
# nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5,
# Result: [3, 9, 15, 33]
# nums ... | python |
import numpy as np
import warnings
def into_patches(image, patch_shape, patch_n):
"""
Process a 2D image into evenly spaced-out 2D patches.
Arguments:
image: image to process into patches as a 2D numpy array.
patch_size: target size of patches: (height, width).
patch_n: number... | python |
# -*- coding:utf-8 -*-
# Copyright 2019 Huawei Technologies Co.,Ltd.
#
# 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... | python |
from typing import List
from datetime import datetime
from pydantic import BaseModel
from model.Schema.word import Word
class init_module(BaseModel):
module_name: str
publisher: str
word: List[Word]
class Module(init_module):
created_at: datetime
module_id: int
class Response_module(BaseMod... | python |
from ...Colors import *
from ..BaseControlClass import GradientTypesEnum
from copy import copy
from json import dump, load
class StyleHintsEnum(object):
Flat = 'Flat'
Raised = 'Raised'
Sunken = 'Sunken'
Hover = 'Hover'
Image = 'Image'
# Custom = 'Custom'
class DefaultStyle(object):
def ... | python |
lista1 = []
lista2 = []
exp = str(input('Digite a expressão: '))
for c in exp:
if c == '(':
lista1.append('(')
if c == ')':
lista2.append(')')
if len(lista1) == len(lista2):
print('Sua expressão está correta!')
else:
print('Sua expressão está errada!')
| python |
import argparse
import logging
import sys
from . import config
from . import gerrit
from . import jenkins
from . import output
def run():
parser = argparse.ArgumentParser(
description='A command line tool for working with Ovirt CI')
parser.add_argument(
'--debug',
help="Show noisy de... | python |
# exceptions.py -- custom exception classes for this module
class PayloadException(Exception):
'''
Something went wrong with the payload from the GitHub API.
'''
pass
class WorkerException(Exception):
'''
Something went wrong in the worker process.
'''
pass
class QueueException(Exc... | python |
import os
from http import HTTPStatus
from pathlib import Path
from typing import Union
from restit._response import Response
from restit.internal.suffix_media_type_mapping import SUFFIX_MEDIA_TYPE_MAPPING
class StaticFileResponse(Response):
def __init__(
self, file_path: Union[str, Path],
... | python |
#
# PySNMP MIB module SNMP-REPEATER-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-REPEATER-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:28:55 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:5... | python |
import os
import unittest
import numpy as np
from pyfluka.utils import PhysicsQuantities as PQ
from pyfluka.plugins.PlotMaker import PlotMaker as PM
from pyfluka.utils.Plotter import PlotConfig as PC
class TestPlotMaker(unittest.TestCase):
def setUp(self):
plotConfigDict = {'type': "2D", 'quantity': "Ac... | python |
from __future__ import absolute_import, division, print_function
import sys
from iotbx import reflection_file_editor
if __name__ == "__main__" :
reflection_file_editor.run(sys.argv[1:])
| python |
from unittest.mock import MagicMock, patch
import pytest
from geniust import constants
from geniust.functions import account
@pytest.mark.parametrize("genius_token", [None, "some_token"])
@pytest.mark.parametrize("spotify_token", [None, "some_token"])
def test_login_choices(update_message, context, genius_token, sp... | python |
from insights.parsers import docker_list
from insights.tests import context_wrap
DOCKER_LIST_IMAGES = """
REPOSITORY TAG DIGEST IMAGE ID CREATED VIRTUAL SIZE
rhel6_vsftpd ... | python |
from math import cos
from reclaimer.hek.defs.objs.tag import HekTag
class DeviTag(HekTag):
def calc_internal_data(self):
HekTag.calc_internal_data(self)
devi_attrs = self.data.tagdata.devi_attrs
devi_attrs.inv_power_acceleration_time = 0
devi_attrs.inv_power_transition... | python |
from pepy.domain.model import ProjectName
def test_project_name_strip_spaces():
project = ProjectName(" some-project ")
assert "some-project" == project.name
def test_set_lowercase_to_project_name():
project = ProjectName("Some-Project")
assert "some-project" == project.name
| python |
from sqlalchemy import *
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import *
from sqlalchemy.sql import text
# Hive
engine = create_engine('hive://192.168.10.12:10010/ltv')
sql = text("select * from ltv.rac_grant_credit limit 10")
sql_rst = engine.execute(sql).fetchall()
print sql_rst
| python |
orders_num = int(input())
total = 0
for n in range(orders_num):
price_capsule = float(input())
days = int(input())
capsule_count = int(input())
price = price_capsule * days * capsule_count
total += price
print(f'The price for the coffee is: ${price:.2f}')
print(f'Total: ${total:.2f}') | python |
""" Models for notice app """
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from messaging.tasks import send_email
from condominium.models import Company
class Feedback(models.Model):
New = 'NEW'
Resolved = 'RES'
Ignored = 'IGN'
... | python |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import argparse
import subprocess
import os
import gzip
import feather
def load_pair_data(path):
if path.endswith('.txt.gz'):
return pd.read_csv(path, sep='\t', usecols=['pair_id', 'slope', 'slope_se'], index_col=0, dtype={'pair_id':str, 'slope... | python |
#from nose.plugins.skip import SkipTest
from nose.tools import assert_equal, raises
from mock import Mock, patch
from unittest import TestCase
from JenkinsPluginResolver.JenkinsPluginResolver import JenkinsPluginResolver
from os.path import dirname, realpath
class Test_JekinsPluginResolver(TestCase):
@patch('Jenk... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.