text stringlengths 2 999k |
|---|
from __future__ import absolute_import
from .req_install import InstallRequirement
from .req_set import RequirementSet, Requirements
from .req_file import parse_requirements
__all__ = [
"RequirementSet", "Requirements", "InstallRequirement",
"parse_requirements",
]
|
import os
import fnmatch
import sys
from Tkinter import *
import SearchEngine
from SearchDialogBase import SearchDialogBase
def grep(text, io=None, flist=None):
root = text._root()
engine = SearchEngine.get(root)
if not hasattr(engine, "_grepdialog"):
engine._grepdialog = GrepDialog(root, engine, f... |
# -*- coding: utf-8 -*-
import sys
import os
import unittest
import trytond.tests.test_tryton
from trytond.tests.test_tryton import POOL, DB_NAME, USER, CONTEXT
from trytond.transaction import Transaction
from decimal import Decimal
DIR = os.path.abspath(os.path.normpath(os.path.join(
__file__, '..', '..', '..', ... |
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2020/5/27 19:57
Desc: 新浪财经-股票-机构持股
http://vip.stock.finance.sina.com.cn/q/go.php/vComStockHold/kind/jgcg/index.phtml
"""
import demjson
import pandas as pd
import requests
def stock_institute_hold(quarter: str = "20051") -> pd.DataFrame:
"""
新浪财经-股票-机构持股一... |
from config import FLAGS
from os.path import join
from utils import get_save_path, load, save, get_corpus_path
from build_graph import build_text_graph_dataset
from dataset import TextDataset
import gc
def load_data():
dir = join(get_save_path(), 'split')
dataset_name = FLAGS.dataset
train_ratio = int(FLA... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import django_rq
def perform_all_jobs_sync():
worker = django_rq.get_worker()
worker.work(burst=True)
|
# -*- coding: utf-8 -*-
#
# phpMyAdmin documentation build configuration file, created by
# sphinx-quickstart on Wed Sep 26 14:04:48 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# ... |
from builtins import super
from .base import AbstractTask
import sh
class ProdigalTask(AbstractTask):
task_name = 'prodigal'
def __init__(self, preprocess_task):
super().__init__()
self.preprocess_task = preprocess_task
self.prodigal = sh.Command(self.config['prodigal']['bin']).bake... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-15 20:43
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("wagtailsearchpromotions", "0002_capitalizeverbose"),
("wagtailforms", "0003_capitalizeverbo... |
# TODO: add more tests for `from_dict` method.
from pathlib import Path
import typing as ty
import pytest
from neurodocker.reproenv.renderers import DockerRenderer
from neurodocker.reproenv.renderers import SingularityRenderer
from neurodocker.reproenv.state import _TemplateRegistry
from neurodocker.reproenv.tests.u... |
# coding=utf-8
# Copyright 2022 DataLab Authors and the current dataset script contributor.
#
# 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
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 10:24:54 2020
@author: nigo0024
"""
'''
Set up a test to run through all of the functions (and various options) and
provide a report on how many were returned with errors (coverage).
Then this file can be run anytime a change is made and changes are pushed to
see if ... |
class Solution:
def XXX(self, s: str) -> int:
return len(s.strip(' ').split(' ')[-1])
|
# Copyright (c) 2017, 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
import p... |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import pyauto_functional
import pyauto
import chromeos.file_browser
import test_utils
class ChromeosFileBrowserTest(pyauto.PyUIT... |
"""
O motor terá responsabilidade de controlar a velocidade.
Ele oferece os seguintes atributos:
1) Atributo de dado velocidade
2) Método acelerar, que deverá incrementar a velocidade de uma unidade
3) Método frear que deverá decrementar a velocidade em duas unidades
"""
class Motor:
def __init_... |
import json
DEFAULT_GUNICORN_TIMEOUT = "60"
def generate_model_info(model_name, image_tag, api_name, timeout, num_of_workers):
model_info = {
"ContainerHostname": model_name,
"Image": image_tag,
"Environment": {
"API_NAME": api_name,
"BENTOML_GUNICORN_TIMEOUT": str... |
import time
init_time = time.time()
from datetime import timedelta
import logging
from config import conf
# Se cargan las configuraciones del problema plano
conf.load(problema_plano='Raul Saavedra')
logging.basicConfig()
# Se define el nivel de logging del modulo main
logger = logging.getLogger(__name__)
logger.setLev... |
from __future__ import annotations
import operator
from collections import Counter
from typing import Iterable
import click
import fiona
from shapely.geometry import Point, LineString, shape, mapping
from surficial.tools import messages
def scan(
test_point: Point,
points: list[Point],
decimal: float
)... |
# app
from ..constants import FORMATS, LOG_FORMATTERS, LOG_LEVELS, REPOSITORIES, STRATEGIES
_TARGET = dict(
type='dict',
schema={
'format': dict(
type='string',
required=True,
allowed=FORMATS,
),
'path': dict(
type='string',
r... |
def my_logging(func):
def wrapper():
print('logging - {} is running'.format(func.__name__))
func() # run func() Equivalent run f1()
return wrapper
def bold(func):
def wrapper():
print("<b>")
func()
print("</b>")
return wrapper
def italic(func):
def wra... |
import pylewm.commands
import pylewm.focus
from pylewm.rects import Rect
import win32gui
import win32api
import win32con
import ctypes
import time
import threading
def is_window_handle_cloaked(hwnd):
output = (ctypes.c_uint * 1)()
result = ctypes.windll.dwmapi.DwmGetWindowAttribute(
hwnd,
cty... |
#!/usr/bin/env python3
import os
import sys
import subprocess
######## GLOBALS #########
MAINPREFIX = "z"
PREFIX = "hatchet_vanilla_"
##########################
def mod_time(path):
if not os.path.isdir(path):
return os.path.getmtime(path)
maxi = os.path.getmtime(path)
for p in os.listdir(path):
... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
from .generate import generate_config_cg
__all__ = ["generate_config_cg"]
|
#!/usr/bin/python
import pandas as pd
import numpy as np
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error
import warnings
warnings.simplefilter("ignore")
def get_data(start):
#iterate through protocols
protocols = ['dns', 'http', 'https', 'icmp', 'ntp', '... |
from django.contrib import admin
from .models import TestModel, TestChildModel
class ChildInline(admin.StackedInline):
model = TestChildModel
extra = 1
@admin.register(TestModel)
class TestModelAdmin(admin.ModelAdmin):
inlines = [ChildInline]
|
"""Base Test Case"""
import os
import unittest
from selenium_unittest_common.common import driver_factory
from selenium_unittest_common.common import page as html_page
# CONSTANTS
DRIVER_FACTORY = driver_factory.DriverFactory()
class BaseTestCase(unittest.TestCase):
"""Base test case class"""
@classmethod
... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU'])
Monomer('BaxM', ['BidM', 'BaxA'])
Monomer('Apop', ['C3pro', 'X... |
import _plotly_utils.basevalidators
class ThicknessValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name='thickness',
parent_name='histogram2dcontour.colorbar',
**kwargs
):
super(ThicknessValidator, self).__init__(
plotly_... |
from tortoise import fields
from tortoise.models import Model
class Answer(Model):
id = fields.IntField(pk=True)
name = fields.CharField(64)
grade_name = fields.CharField(64)
cafe_name = fields.JSONField()
feedback = fields.TextField()
created_at = fields.DatetimeField(auto_now_add=True)
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import os
import shutil
import unittest
from unittest import mock
from datetime import datetime
import requests
from opentelemetry.sdk.trace.export import SpanExportResult
from azure.core.exceptions import HttpR... |
# coding: utf8
class AbstractView(object):
"""Defines interface for View classes"""
def __init__(self, config, **kwargs):
raise NotImplementedError(
"Can't instantiate View interface, use its implementation"
)
def display(self, context):
"""Displays data given to cont... |
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin)
from django.db import models
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""
Creates and saves a new user
... |
class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
|
"""Configuration file parsing and utilities."""
import copy
import itertools
import os
from collections import namedtuple
from collections.abc import Set
from re import compile as re
from configparser import RawConfigParser
from .utils import __version__, log
from .violations import ErrorRegistry, conventions
def c... |
import os
import json
#
# Maybe use https://stackoverflow.com/questions/18406165/creating-a-timer-in-python/18406263
# in order to delay writes for 2 seconds?
#
class PersistentProperties(object):
def __init__(self, filePath:str, bAutoStore:bool = True):
self.__filePath = filePath
self.__data = self.__try... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import model_pb2 as model__pb2
class CanControllerStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, chan... |
import time
from tests import TestBase
EXPECTED_OPERATION_NAMES = ["Transfer", "Distribute", "Consolidate", "Mix", "Dispense", "Provision", "Spread", "Autopick", "Thermocycle", "Incubate", "Seal", "Unseal", "Cover", "Uncover", "Spin", "Image Plate", "Absorbance", "Fluorescence", "Luminescence", "Gel Separate", "Autop... |
from django.apps import AppConfig
class CreateTableConfig(AppConfig):
name = 'tutorials.create_table'
|
def convert_to_page_rank_factor_graph_file(path_to_input_file,path_to_output_file):
with open(path_to_input_file, "r") as f:
all_lines = f.readlines()
num_node = int(all_lines[0])
all_edges = list()
for line in all_lines[1:]:
[x,y] = line.split()
all_edges.app... |
'''
Created on 3 janv. 2022
@author: slinux
'''
#
#
#
# wxRaven for building .exe
#
#
#
import json
import wx
import wx.xrc
import wx.dataview
import wx.dataview
import wx.aui
import wx.richtext
import wx.lib
import wx.lib.scrolledpanel
import wx.lib.buttons
import wx.adv
import wx.grid
import wx.html2
import wx... |
import tabulate
def descomponer():
separador = str(input("Introduce el separador que desea utilizar: "))
cadena = str(input("Introduce un texto para analizar: "))
ca = cadena.split(separador)
lista = []
for i in range(0, len(ca)):
lista.append(list(ca[i:i+1]))
table = lista
headers = ["nº", "Ca... |
class VehicleState:
def __init__(self, x, y, theta1, theta2):
self.x = x
self.y = y
self.theta1 = theta1
self.theta2 = theta2
def getPoint(self):
return (self.x, self.y)
def getAttributes(self):
return (self.x, self.y ,self.theta1, self.theta2)
def copy(s... |
from scripts import General, Parameters, Constants
from scripts.frontend.custom_widgets import CustomLabels
class Label(CustomLabels.InformationLabel):
_text_status = "Status: "
_text_running = "Running"
_text_stopped = "Stopped"
def __init__(self, root, column, row, default_status=False,
... |
import sys
import bisect
read = sys.stdin.readline
n, c = map(int, read().split())
lst = []
for _ in range(n):
lst.append(int(read()))
lst.sort()
upper = (lst[-1] - lst[0]) // (c - 1)
lower = 1
while upper > lower:
# test if ans can be tangible
possible = True
ans = (upper + lower) // 2 + 1
last =... |
__author__ = 'Administrator'
import os
import sys
import msvcrt
import win32api
import win32con
# Get file descriptor from argument
ppid = int(sys.argv[1])
pipearg = int(sys.argv[2])
pipe2arg = int(sys.argv[3])
curproc = win32api.GetCurrentProcess()
parent_process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,... |
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from p... |
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from livesettings import *
from satchmo_store.shop import get_satchmo_setting
from satchmo_utils import is_string_like, load_module
SHIPPING_GROUP = ConfigurationGroup('SHIPPING', _('Shipping Settings'))
SHIPPING_ACTIVE = config_... |
"""
ASGI config for rajastan_studios_project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefa... |
import sys;p=sys.argv[1]
def w(c):s=sys.stdout;s.write(str(c)+' ');s.flush()
i=j=0;d=[0];a=abs;b=bool
while i<len(p):
s=0;x,y=p[i],d[j]
if x=='>':d+=[0];j+=1
elif x=='<':d=[0]+d
elif x in '+-':d[j]+=(-1,1)[x=='+']
elif x=='.':w(d[j])
elif x==',':d[j]=(input('>'))
elif x in '[]':s=(1,-1)[x==']']
if s!=0 and b(s+... |
import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="size", parent_name="area.hoverlabel.font", **kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=paren... |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
import datetime
import logging
from contextlib import contextmanager
from os import getpid
from sqlalchemy import Column, Date, Boolean, String, ForeignKey, Enum, \
DateTime, create_engine, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sq... |
# 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, software
# distributed unde... |
# Copyright 2019 The TensorFlow Probability Authors.
#
# 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... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/kinetic/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.... |
import requests
from Code.Task1Spider import Task1Spider
from Code.Task2Spider import Task2Spider
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
class LoginCracker:
def __init__(self, username, p... |
"""
The script reads and analyzes the dataset. After cleaning, it is oberved that
dataset cleaning is not required.
Also, the **locations** and **restaurant type** dictionaries are saved. This is
required for the application to accept user inputs.
"""
import pandas as pd
from logzero import logger, logfile
import... |
import sims4.reload
import sims4.telemetry
import telemetry_helper
TELEMETRY_GROUP_CLOCK = 'CLCK'
TELEMETRY_HOOK_CHANGE_SPEED_REPORT = 'CHSR'
TELEMETRY_HOOK_MAX_TICK_SPIKE = 'MCTS'
TELEMETRY_HOOK_GAME_CLOCK_BEHIND = 'CGCB'
TELEMETRY_FIELD_CLOCK_SPEED = 'clsp'
TELEMETRY_FIELD_TIME_SPENT_IN_SPEED = 'tmsp'
TELEMETRY_FIELD... |
# Generated by Django 3.2.12 on 2022-04-02 00:41
from django.db import migrations
from django.utils.timezone import make_aware
def migrate_script_data(apps, schema_editor):
AutomatedTask = apps.get_model("autotasks", "AutomatedTask")
# convert autotask to the new format
for task in AutomatedTask.objects.... |
# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.forms import SetPasswordForm, PasswordChangeForm, \
AdminPasswordChangeForm as DjagnoAdminPasswordChangeForm, UserCreationForm, \
AuthenticationForm as DjangoAut... |
import pytest
from tree import Node, BinaryTree, BinarySearchTree
def test_tree_structure():
assert BinaryTree()
def test_left_and_right():
tree_node = BinarySearchTree()
tree_node.add(5)
tree_node.add(8)
tree_node.add(5)
left = tree_node.root.left.value
expect_left = 8
right = tree_n... |
import os
import pytest
import tempfile
import xarray as xr
import pandas as pd
import fsspec
from fsspec.registry import known_implementations
import aiohttp
import argopy
from argopy.stores import (
filestore,
httpstore,
indexfilter_wmo,
indexfilter_box,
indexstore,
)
from argopy.stores.filesyst... |
"""Test suite for hash tables."""
from hash_table import HashTable, naive_hash
from os import path
import pytest
from faker import Faker
dictionary = path.realpath(__file__).replace('test_hash.py',
'american-english')
with open(dictionary, 'r') as dictionary:
dictiona... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from app.forms import SteuerlotseBaseForm
from app.forms.multistep_flow import MultiStepFlow, FormStep, DisplayStep, RenderInfo
from app.forms.fields import EuroField, EntriesField
from collections import namedtuple
from decimal import Decimal
from flask import render_template
from flask_babel import _
from flask_babe... |
from django.test import TestCase
from example.views.views import ListDataModelView
from example.views.models import ListData
class TestViewListTable(TestCase):
def setUp(self):
pass
def test_view_list_empty(self):
pass
def test_view_list_results(self):
pass
def test_view_l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#HW2 for EECS 598 Motion Planning
#code based on the simplemanipulation.py example
import time
import openravepy
#### YOUR IMPORTS GO HERE ####
import astarTool as a
from copy import deepcopy
#### END OF YOUR IMPORTS ####
if not __openravepy_build_doc__:
from openrave... |
#
# The Python Imaging Library.
# $Id$
#
# base class for image file handlers
#
# history:
# 1995-09-09 fl Created
# 1996-03-11 fl Fixed load mechanism.
# 1996-04-15 fl Added pcx/xbm decoders.
# 1996-04-30 fl Added encoders.
# 1996-12-14 fl Added load helpers
# 1997-01-11 fl Use encode_to_file where possibl... |
import click
from .backup import *
from .prompts import *
from .reinstall import *
from .git_wrapper import *
from .utils import mkdir_warn_overwrite, destroy_backup_dir, expand_to_abs_path
# custom help options
@click.command(context_settings=dict(help_option_names=['-h', '-help', '--help']))
@click.option('-all', i... |
# Generated by Django 3.0.7 on 2020-06-08 10:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0005_auto_202006... |
#!/usr/bin/python
################################################################################
# 21119b98-5cc5-11e4-af55-00155d01fe08
#
# Justin Dierking
# justindierking@hardbitsolutions.com
# phnomcobra@gmail.com
#
# 10/24/2014 Original Construction
################################################################... |
"""
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRa... |
##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
## Dimensionality reduction via FDA for TE data
## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% import required packages
import numpy as np
import matplotlib.pyplot as plt
... |
# encoding: utf-8
from __future__ import absolute_import
import os
import csv
import pickle
import zipfile
from io import BytesIO, TextIOWrapper
from six.moves import urllib
NAMES_URL = 'http://www.ssa.gov/oact/babynames/names.zip'
def load(path=None):
datafile = 'names.pickle'
if path:
datafile = ... |
# module 're' -- A collection of regular expression operations
r"""Support for regular expressions (RE).
This module provides regular expression matching operations similar to
those found in Perl. It's 8-bit clean: the strings being processed may
contain both null bytes and characters whose high bit is set. Regular
e... |
import json
from django import forms
from django.utils.encoding import smart_text
from django.utils.translation import pgettext_lazy
from django_prices.templatetags.prices_i18n import amount
from ..cart.forms import AddToCartForm
from ..core.utils.taxes import display_gross_prices
class VariantChoiceField(forms.Mod... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
from .util import query_yes_no
logger = logging.getLogger('mutagenerate')
class Source(object):
def generate(self, id3, update=False):
logger.info('Generating sources for %s' % id3.pprint().replace('... |
# https://leetcode.com/problems/valid-palindrome
import re
class Solution:
def isPalindrome(self, s):
s = s.lower()
s = re.sub("[^0-9a-z]", "", s)
lp, rp = 0, len(s) - 1
while lp <= rp:
if s[lp] != s[rp]:
return False
lp += 1
rp ... |
from __future__ import annotations
import os
import re
import shutil
from argparse import ArgumentTypeError
from functools import lru_cache
from typing import Callable
from typing import Generator
from typing import TypeVar
T = TypeVar('T')
class cptkException(Exception):
""" Base cptk exception. All exceptions ... |
import requests
import pandas as pd
import json
class CryptoAPI:
def get_pair(self, symbol, granularity=86400):
#code example from: https://www.cryptodatadownload.com/blog/how-to-download-coinbase-price-data.html
url = f'https://api.pro.coinbase.com/products/{symbol}/candles?granularity={granularit... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
int_or_none,
orderedSet,
parse_duration,
qualities,
unified_strdate,
xpath_text,
)
class EuropaIE(InfoExtractor):
_VALID_URL = r"https?://ec... |
from urllib.parse import urlparse
from flask import request, render_template, redirect, url_for, flash
from flask_mail import Message
from justin import app, mail
from justin.forms import MessageForm
@app.before_request
def redirect_to_io():
urlparts = urlparse(request.url)
if urlparts.netloc == "justin-le.h... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from datetime import timedelta
from django.utils.translation import gettext_lazy as _
from django.conf import settings
from django.test.signals import setting_changed
from rest_framework.settings import APISettings as _APISettings
from .algorithms import (
RSA_SIZE_2048,
KEY_ALGORITHM_RS512,
EdDSA_CURVE_Ed2... |
import sys
import re
import datetime
import docassemble.base.config
if __name__ == "__main__":
docassemble.base.config.load(arguments=sys.argv)
from docassemble.base.config import daconfig
from docassemble.base.functions import word
from docassemble.webapp.app_object import app
from docassemble.webapp.db_object imp... |
""" Astropy coordinate class for the Palomar 5 stream coordinate system """
# Third-party
import numpy as np
import astropy.units as u
import astropy.coordinates as coord
from astropy.coordinates import frame_transform_graph
from astropy.coordinates.matrix_utilities import matrix_transpose
__all__ = ["Pal5PriceWhela... |
#!/usr/bin/python
#This scrpt checks status (running:true or false) of currnet node in rabbitmq cluster
import pycurl
import cStringIO
import errno, sys
import socket
import syslog
user = sys.argv[1]
password = sys.argv[2]
vip = sys.argv[3]
currentip=((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
... |
import unittest
import datafilereader
class TestAllFiles(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.chief = datafilereader.construct_chief_controller(datafilereader.ALL_FILES_PATH)
@classmethod
def tearDownClass(cls):
cls.chief.close()
def test_all_files_can_be_see... |
from platypush.message.event import Event, EventMatchResult
class FlicButtonEvent(Event):
""" Flic button event """
def __init__(self, btn_addr, sequence, *args, **kwargs):
super().__init__(btn_addr=btn_addr, sequence=sequence, *args, **kwargs)
def matches_condition(self, condition):
re... |
import os
import csv
import sys
import json
import geopy
import logging
from geopy.distance import great_circle
# https://github.com/gyuho/learn/blob/master/doc/go_graph_shortest_path/code/graph.json
# command line args
file = sys.argv[1]
name = sys.argv[2]
# check file
if not os.path.exists(file):
print("File n... |
#!/usr/bin/env python3
# coding=utf-8
import numpy as np
base_data = np.arange(100, 200)
print("base_data\n={}\n".format(base_data))
print("base_data[10] = {}\n".format(base_data[10]))
every_five = np.arange(0, 100, 5)
print("every_five={}\n".format(every_five))
print("base_data[every_five] = \n{}\n".format(base_da... |
import asyncio
import discord
import requests, json
from discord.ext import commands
from discord.ext.commands import MissingRequiredArgument
from datetime import timedelta, datetime
from cogs.libs import brainfuck # BrainFu*k Interpreter
from cogs.libs import getch
from cogs.libs.JB import jbin #JB Interpreter ... |
_base_ = ['../_base_/mini/mini_mani_skill_pointnet_transformer.py']
env_cfg = dict(
type='gym',
env_name='OpenCabinetDrawer_1045_link_0-v0',
)
replay_cfg = dict(
type='ReplayMemory',
capacity=1000000,
)
train_mfrl_cfg = dict(
total_steps=150000,
warm_steps=0,
n_steps=0,
n_updates=50... |
from subprocess import PIPE, run
import json
import yaml
def parse_events(stdout):
line_split = stdout.split('☁️ cloudevents.Event\n')
# Parse the input and output data from the cloud events
log_data = []
for event_iter in range(1, len(line_split)):
event = line_split[event_iter]
co... |
import json
from typing import TypedDict
class IAppConfig(TypedDict):
nodesExcelPath: str
tokenUrl: str
clientId: str
clientSecret: str
clientScope: str
pingStatusCreationEndPnt: str
def getConfig(fName: str = "config.json") -> IAppConfig:
with open(fName) as f:
data = json.load(... |
from . import (
addtocsv,
areas,
areatypes,
places,
points,
postcodes,
reconcile,
search,
tools,
)
def init_app(app):
app.register_blueprint(areas.bp)
app.register_blueprint(areatypes.bp)
app.register_blueprint(postcodes.bp)
app.register_blueprint(points.bp)
ap... |
from dataclasses import dataclass
from typing import Any, Dict
from decouple import Event
@dataclass
class StateSaveEvent(Event):
state: Dict[str, Any] = None
state_type: str = None
@dataclass
class StateLoadEvent(Event):
state_type: str = None
@dataclass
class CheckpointLoadingEvent(Event):
chec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.