content stringlengths 5 1.05M |
|---|
# %%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import logging
import math
import matplotlib as mpl
from pylab import cm
avenirfont = {'fontname': 'Avenir', 'size': 18}
units = {'perf': 'paket/sn', 'cost': 'USD/saat'}
names = {'perf': 'performans', 'cost': 'maliyet'}
plt.rcParams['text.use... |
#!/usr/bin/env python
import argparse
import os
import subprocess
import sys
import threading
from collections import OrderedDict
import yaml
import yodl
debug = False
class DockerCompose:
def __init__(self, compose, project, compose_base_dir, requested_services):
self.project = project
self.co... |
import math
import vmath
from vmathlib import vcolor, vutil
import drawutil
from unit_manager import Unit
class Testease(Unit):
def tick(self, delta_time):
self._draw_ease_panel(vmath.Vector3())
def _draw_ease_panel(self, panel_position):
exp = 3
ease_funcs = [
vutil.alpha_ease_none,
vutil.alpha_eas... |
import unittest
import wd.parallel
from selenium import webdriver
import copy
class Selenium2OnSauce(unittest.TestCase):
def setUp(self):
desired_capabilities = [
webdriver.DesiredCapabilities.FIREFOX,
webdriver.DesiredCapabilities.FIREFOX,
webdriver.DesiredCapabilities... |
# Задача 10. Вариант 49.
#Напишите программу "Генератор персонажей" для игры. Пользователю должно быть предоставлено 30 пунктов, которые можно распределить между четырьмя характеристиками: Сила, Здоровье, Мудрость и Ловкость. Надо сделать так, чтобы пользователь мог не только брать эти пункты из общего "пула", но и воз... |
# Copyright 2012 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the... |
from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules
from django.utils.translation import gettext_lazy as _
from .settings import MODULE_INIT_DEFAULT
class UwsgifyConfig(AppConfig):
name = 'uwsgiconf.contrib.django.uwsgify'
verbose_name = _('uWSGI Integration')
... |
"""Appication sub-layer for list synchronization."""
import collections
import itertools
import logging
from typing import Deque, Generic, List, Optional, Type, TypeVar
import attr
from typing_extensions import Protocol
from ventserver.protocols import events
from ventserver.protocols import exceptions
from ventser... |
from scfmsp.controlflowanalysis.AbstractInstruction import AbstractInstruction
from scfmsp.controlflowanalysis.StatusRegister import StatusRegister
class InstructionRra(AbstractInstruction):
name = 'rra'
def get_execution_time(self):
oplist = self.oplist.split()
if(self.register_mode):
... |
"""Helpful constants, functions, and classes for use of the Publican."""
from calendar import isleap, mdays
from datetime import date, timedelta
from decimal import Decimal
# Conveniences when working with decimals.
zero = Decimal('0.00')
zero_places = Decimal('1')
two_places = Decimal('1.00')
def dollars(n):
r... |
import os
from flask_restful import Resource, request
from jsonschema import ValidationError
from server.database import db
from server.database.queries.executions import get_execution
from server.resources.decorators import login_required, marshal_response
from server.database.models.execution import Execution, Execut... |
def is_match(text, pattern):
"""Basic Regex Parser that only includes '.' and '*'. Case sensitive."""
def match(t_char, p_char):
"""Defines the comparision between characters in the text and pattern."""
if t_char == p_char or p_char == ".":
return True
return False
# Sc... |
# Ordering
def cascade(n):
"""Print a cascade of prefixes of n.
>>> cascade(1234)
1234
123
12
1
12
123
1234
"""
if n < 10:
print(n)
else:
print(n)
cascade(n//10)
print(n)
def cascade2(n):
"""Print a cascade of prefixes of n."""
p... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
https://github.com/cgloeckner/pyvtt/
Copyright (c) 2020-2021 Christian Glöckner
License: MIT (see LICENSE for details)
"""
import unittest, tempfile, pathlib
import utils
class FancyUrlApiTest(unittest.TestCase):
def setUp(self):
# create... |
import re
import sys
import os
import unicodecsv as csv
import pandas as pd
import itertools
import numpy as np
from collections import Counter
import science.roles as r
roles = r.Roles()
empl_path = sys.argv[1] #directory of csv files to process
#target = sys.argv[2] #csv file name to write
## Iterate.
empl_file_ls... |
import sys
from hmac import new as sign
from hashlib import sha256
from .validators import *
PY2 = True if sys.version_info.major == 2 else False
if PY2:
from urlparse import urlparse, urlunparse, parse_qs
from base64 import encodestring as encode
else:
from urllib.parse import urlparse, urlunparse, parse... |
# Moeda
# 111
# Crie um pacote chamado utilidadesCeV que tenha dois módulos internos chamados moeda e dado. Transfira todas as funções utilizadas nos desafios 107, 108 e 109 para o primeiro pacote e mantenha tudo funcionando.
def aumentar(preco = 0, taxa = 0, formato = False):
'''
-> Funcao para calcular o aum... |
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib
import numpy as np
from pathlib import Path
plt.style.use('seaborn-white')
# sns.set()
font = {'family' : 'sans-serif',
'size' : 16}
matplotlib.rc('font', **font)
sns.set_palette('mako')
def coverage(y, yL, yH):
return (100 / y.sha... |
# -*- coding: utf-8 -*-
# encoding: utf-8
import json
import os
from time import time
import re
import requests
from base64 import b64encode
from kitty.data.report import Report
from kitty.targets.server import ServerTarget
from requests.exceptions import RequestException
from utils import set_class_logger
@set_c... |
from foundations_events.consumers.jobs.mixins.job_event_notifier import JobEventNotifier
class JobNotifier(JobEventNotifier):
"""Sends a notification message when a job is queued
Arguments:
job_notifier {JobNofitier} -- A JobNotifier for sending out the messages
"""
@staticmethod
... |
from . import plot_target_dist
from . import plot_tfidf
from . import plot_words_cdf
from . import plot_roc_curve
from . import plot_comment_length_hist
|
# Objective: visualize X and E, the input graph to the model
import matplotlib.pyplot as plt
import numpy as np
# take in X and E
# draw a large point for X(i,1:4)
# for every E(i,j) = 1, draw a line between X(i,1:4) and X(j,1:4)
def plotGraph(X, E):
fig = plt.figure()
ax = plt.axes(projection="3d")
ax.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2019. Mike Herbert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your... |
def string_hash(s: str) -> int:
a = sum( ord(c) for c in s )
n = s.count(' ')
b = ord(s[-1])-ord(s[0]) if s else 0
c = (a | b) & (~a << 2)
d = c ^ ( (n+1) << 5 )
return d |
# Напишите функцию (F): на вход список имен и целое число N; на выходе список длины N случайных
# имен из первого списка (могут повторяться, можно взять значения: количество имен 20, N = 100,
# рекомендуется использовать функцию random)
from random import choices
def choices_name(list_names,N=15):
'''Задается спи... |
# -*- coding: utf-8 -*-
"""
1637. Widest Vertical Area Between Two Points Containing No Points
Given n points on a 2D plane where points[i] = [xi, yi],
Return the widest vertical area between two points such that no points are inside the area.
A vertical area is an area of fixed-width extending infinitely along the y... |
import os
import unittest
from smartexcel.smart_excel import SmartExcel
from smartexcel.tests.data.definitions.dummy import DUMMY_DEFINITION
from smartexcel.tests.data.data_models.dummy import DummyData
class TestParse(unittest.TestCase):
def setUp(self):
self.definition = DUMMY_DEFINITION
self.da... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import datetime
from tests import factories
from tests.common import ApiBaseTest
from webservices.rest import api
from webservices.resources.filings import FilingsView, FilingsList
class TestFilings(ApiBaseTest):
def test_committee_filings(self):
""" Check filing returns with a specified committee id""... |
###Titulo: Contagem de cédulas e modedas
###Função: Este programa modifica a listagem 5.14 para trabalhar também com moedas de R$ 0,50 R$ 0,10 R$ 0,05 R$ 0,02 e R$ 0,01
###Autor: Valmor Mantelli Jr.
###Data: 26/12/2018
###Versão: 0.0.1
# Declaração de variáve e atribuição de valor
valor = float(input("Digite o valor ... |
vowels=['a','e','i','o','u']
word=input("enter the words to search for vowels:")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("the no. of different vowels present in",word,"is",len(found)) |
"""
Plot training/validation loss and F1-score per category.
TODO: generalize the plotter for different situations than 4 models...
"""
import matplotlib.pyplot as plt
from glob import glob
import re
def plot_training_loss(dirname, model):
"""
Plot training and validation loss during training
:param dirna... |
from tornado.gen import coroutine
from torip.ipapis import api_factory
__author__ = 'mendrugory'
class Locator:
"""
Main Class which will be the responsible of locating the IP.
"""
def __init__(self, api_name=None, **config):
self.api_name = api_name
self.config = config
@corou... |
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import uuid
import requests_mock
from canvasapi.canvas import Canvas
from canvasapi.upload import Uploader
from tests import settings
from tests.util import cleanup_file, register_uris
@requests_mock.Mocker()
class Te... |
''' backup db from db_production '''
from connect import connect
def backup():
''' backup all document from production to backup '''
clients = {'production': connect('production'), 'backup': connect('backup')}
dbs = {'production': clients['production']['test'], 'backup': clients['backup']['test']}
for... |
# Generated by Django 3.2.7 on 2021-09-07 18:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='video',
old_name='author',
new_name... |
#!/usr/bin/env python
r"""Contais Ion class.
Class inherets from :py:class:`~solarwindpy.core.base.Base` and contains :py:class:`~solarwindpy.core.vector.Vector` along with
:py:class:`~solarwindpy.core.tensor.Tensor` objects.
"""
import pdb # noqa: F401
# import numpy as np
import pandas as pd
# We rely on views v... |
#!/usr/bin/env python
#################################################################################
## Program: BRAINS (Brain Research: Analysis of Images, Networks, and Systems)
## Language: Python
##
## Author: David Welch
##
## This software is distributed WITHOUT ANY WARRANTY; without even
## the ... |
"""1725. Number Of Rectangles That Can Form The Largest Square
https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/
"""
from typing import List
def count_good_rectangles(rectangles: List[List[int]]) -> int:
k = min(rectangles[0])
for l, w in rectangles:
k = max(k, min(l... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'messenger.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Messenger(object):
def setupUi(self, Messenger):
Messenger... |
"""Implementation of Fowler's Money pattern"""
from __future__ import annotations
from math import floor
from decimal import Decimal, ROUND_HALF_EVEN
from re import sub
import operator
from babel.numbers import format_currency
class Money:
"""
Money class that implements Fowler's Money pattern:
https://m... |
# -*- coding: utf-8 -*-
"""
migrated from TheCannon package
"""
import numpy as np
# from functools import partial
# from multiprocessing import Pool
# import matplotlib.pyplot as plt
import scipy.optimize as opt
LARGE = 200.
SMALL = 1. / LARGE
def _partial_func(func, *args, **kwargs):
""" something """
def... |
#from core.classifier import CustomizedClassifier,isbad #classifier class
from core import xyz #coorddb class (holds the data)
import math
#sklearn module - does the classification
import core.classifier as classifier
from core.classifier import *
import traceback
from sklearn import semi_supervised
class Spe... |
#!/usr/bin/env python
import os
import yaml
import logging
import pymysql
from connections import Connections
__dir__ = os.path.dirname(__file__)
config = yaml.safe_load(open(os.path.join(__dir__, "../default_config.yaml")))
try:
config.update(yaml.safe_load(open(os.path.join(__dir__, "../config.yaml"))))
except I... |
import cv2
import sys
# from PIL import Image
import numpy as np
import os
import base64
# import sys
import io
from PIL import Image
cascade_file = "haarcascade_frontalface_default.xml"
#만약 dataset이라는 폴더 못찾으면 만들도록 설정
path_data = 'dataset'
if path_data not in os.listdir():
os.mkdir(path_data)... |
"""
Module cart3d -- Cartesian coordinates, 3 axes, double-precision.
Includes class Cart3d.
"""
import array as ar
class Cart3d():
"A 3-element tuple of double-precision values."
prefix = "Cart3d."
enumx = (0, 1, 2) # enumeration of indices
zeros = [ 0.0, 0.0, 0.0 ]
def __init__(self, *arg... |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('skinematics', parent_package, top_path)
'''
# An example Fortran extension
config.add_extension(
'fortran_stuff',
sources=['fortran_stuff.f90']
... |
import radical.utils as _ru
import os
from prof_utils import *
_pwd = os.path.dirname (__file__)
_root = "%s/.." % _pwd
version_short, version_detail, version_base, version_branch, \
sdist_name, sdist_path = _ru.get_version([_root, _pwd])
version = version_short |
'''
---------------------------------------------
MyDict - My version of the class Dictionary
Author: Kethan Vegunta
---------------------------------------------
Description:
My version of the python dictionary. It's syntax is very similar to a regular
python dict.
'''
import pickle
class MyDict:
'''
Create ... |
from dino_utils import (
get_model_slug_for_dino,
get_model_for_dino,
get_model_resolution_for_dino,
label_image_for_dino,
count_num_features_for_dino,
get_preprocessing_for_dino,
)
from keras_utils import (
get_model_slug_for_keras,
get_model_for_keras,
get_model_resolution_for_kera... |
import os
from solaris.eval.base import Evaluator
import solaris
import geopandas as gpd
import pandas as pd
class TestEvaluator(object):
def test_init_from_file(self):
"""Test instantiation of an Evaluator instance from a file."""
base_instance = Evaluator(os.path.join(solaris.data.data_dir,
... |
"""
Exceptions raised by geopy.
"""
class GeopyError(Exception):
"""
Geopy-specific exceptions are all inherited from GeopyError.
"""
class ConfigurationError(GeopyError):
"""
When instantiating a geocoder, the arguments given were invalid. See
the documentation of each geocoder's `__init__` f... |
from django import template
register = template.Library()
@register.filter(name='get_notetype_notes_count')
def get_notetype_notes_count(notes):
notes_without_type = notes.filter(note_type=None).count()
notes_count = notes.count()
notes_with_type = notes_count - notes_without_type
return notes_with_t... |
from django.urls import path
from . import views
urlpatterns = [
path('translate', views.TranslateApiView.as_view()),
] |
"""Tests for hedging_value function."""
import unittest
from numpy import kron, cos, sin, pi, sqrt, isclose
from toqito.states import basis
from toqito.nonlocal_games.quantum_hedging import QuantumHedging
class TestQuantumHedging(unittest.TestCase):
"""Unit test for hedging_value."""
e_0, e_1 = basis(2, 0),... |
import unittest
from . import test_shapes
loader = unittest.TestLoader()
suite = unittest.TestSuite()
suite.addTests( loader.loadTestsFromModule(test_shapes) )
runner = unittest.TextTestRunner(verbosity = 3)
result = runner.run(suite) |
import numpy as np
import torch
import torch.optim as optim
from datasets.kitti import FrustumKitti
from datasets.kitti.attributes import kitti_attributes as kitti
from meters.kitti import MeterFrustumKitti
from modules.frustum import FrustumPointNetLoss
from evaluate.kitti.frustum.eval import evaluate
from utils.conf... |
import numpy as np
import os
import ntpath
import time
from . import util
from . import html
from pdb import set_trace as st
import math
# save image to the disk
def save_images(webpage, images_list, names_list, image_path, title=None, width=256):
image_dir = webpage.get_image_dir()
short_path = ntpath.basena... |
import datetime
from enum import Enum
from django.utils import timezone
from apps.db_data.models import Event
class AnnouncementType(Enum):
WEEK = "week"
TOMORROW = "tomorrow"
TODAY = "today"
HOUR = "hour"
B_TIME = "now" # Berkeley Time
def get_events_in_time_delta(requested_atype: Announceme... |
import re
def is_alpha(string):
charRe = re.compile(r"[^a-zA-Z.]")
string = charRe.search(string)
return not bool(string)
def location_handler(loc):
if len(loc) and loc != " " and loc.isalpha():
return True
return False
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: fds/protobuf/stach/table/RowDefinition.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf impo... |
#!/usr/bin/env python
"""
This script will handle running SMILESMerge in a docker container.
It handles generating the docker image and container, handling the user variables,
executing SMILESMerge, and copying the files from the container to the desired directory.
This script requires a JSON file that contains all th... |
import logging
import threading
from ftplib import FTP
class FtpUploader(threading.Thread):
TMP_DIR = '/tmp/'
def __init__(self, files, host, user, passwd, ftp_dir=None, logger=None):
super().__init__()
self.daemon = True
self.files = files
self.host = host
self.user =... |
# 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.
# -----------------------------------------------------------------------... |
from O365.contact import Contact
from O365.group import Group
from O365.connection import Connection
import logging
import json
import requests
import time
log = logging.getLogger(__name__)
class Event( object ):
'''
Class for managing the creation and manipluation of events in a calendar.
Methods:
create -- Cr... |
import arcpy
import os
import logging
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
arcpy.env.wo... |
import os
import numpy as np
from utils.load_data import load_data
from utils.CSV_data_generator import DataGen
from models.NormBase import NormBase
def evaluate_model(config, save_name, legacy = False):
"""
This function runs and evaluates the model with given config.
The model is saved to models/saved/c... |
import cv2
import numpy as np
from utils import transform
def main():
img = cv2.imread('/home/sandeep/tmp/img01.png', cv2.IMREAD_COLOR).astype(np.float32)
img = transform.blur_image(img)
cv2.imwrite('/home/sandeep/tmp/img01-blur.png', img)
if __name__ == '__main__':
main()
|
from typing import Optional
from contracts.story import (GetStoryRequest, GetStoryResponse,
DetailStoryRequest, DetailStoryResponse,
PostStoryRequest, PostStoryResponse,
PutStoryRequest, PutStoryResponse,
... |
import hashlib
import pathlib
from io import TextIOBase
from typing import Optional, List, Tuple, Set
from cincan.command_log import CommandLogIndex, CommandLog, quote_args
class FileDependency:
"""File dependency information for command log"""
def __init__(self, file: pathlib.Path, digest: str, out:bool):
... |
import os
os.environ['AWS_REGION'] = 'eu-west-1'
from ..index import Item
def test_bool_convert():
item = Item()
item.item_key = {'key': {'S': 'value'}}
item.item_value = {
'string': {'S': 'str'},
'bool': {'BOOL': 'true'},
'map': {'M': {
'string': {'S': 'str'},
... |
import math
import random
import sqlite3
# CONSTANTS
NODE_POS_OFFSET_AT_CREATION = 10
MIN_NODE_FRICTION = 0
MAX_NODE_FRICTION = 1
class Node:
def __init__(self, x_pos, y_pos, friction, speed, angle):
# position in space
self.x_pos = x_pos
self.y_pos = y_pos
# friction with the g... |
# SPDX-License-Identifier: Apache-2.0
"""
Test scikit-learn's PowerTransform
"""
import unittest
import numpy as np
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
from test_utils import dump_data_and_model, TARGET_OPSET
try:
from sklearn.preprocessing import PowerTra... |
import fpdf
from fpdf import FPDF, HTMLMixin
# Create pdf report to show the results in a readable way
# The content of the pdf has to be written following the
# HTML standard. It will be converted in pdf at the end,
# using output_pdf()
class MyFPDF(FPDF, HTMLMixin):
pass
# parameters for the pdf
pdf = MyFPDF... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# @license : Copyright(C), Your Company
# @Author: Zhang Dong
# @Contact : 1010396971@qq.com
# @Date: 2020-07-19 9:20
# @Description: 模型下载地址:https://github.com/pytorch/vision/issues/616
# 调用本地模型:https://github.com/pytorch/vision/pull/1057
# @Software : PyCharm
f... |
#!/usr/bin/env python
def gcd(m, n):
while n:
m, n = n, m % n
return m
def lcm(m, n):
return m * n / gcd(m, n)
def is_power(n):
return ((n & (n - 1)) == 0) and n != 0
if __name__ == '__main__':
print lcm(512, 3)
print '16:', is_power(16)
print '4:', is_power(4)
print '2:', is... |
from typing import Tuple
import numpy as np
from numpy.core.fromnumeric import size
def get_dataset() -> Tuple[np.ndarray, np.ndarray]:
"""OR-Function dataset"""
x = np.array([[0, 0], [1, 0], [0, 1], [1, 1]]) # Input in das OR-Gatter
y = np.array([[0], [1], [1], [1]]) # Ergebnis eines OR-Gatters
ret... |
from random import randint
from sqlalchemy.exc import IntegrityError
from faker import Faker
from app import db
from app.models import User, Post, Comment
def post_comments():
fake = Faker()
user_count = User.query.count()
post_count = Post.query.count()
for i in range(1,post_count+1):
p = Post... |
"""
Given a number of stairs, you can climb at most m stairs at a time.
For instance, for m=3, you can climb 1, 2, or 3 stairs at a time.
Count the number of different ways that you can reach the top.
:param stair_count: No of stairs to climb.
:param max_steps: Max no of stairs you can climb at a time.
:return: Number... |
from store_vertices import store_vertices
from dijkstra_algo import dijkstra
def main():
nodes = set()
graph = dict()
result = []
visited = {}
e = int(input('Enter the number of roads: '))
store_vertices(e, nodes, graph)
starting = input('Starting point: ')
ending = input('ending point... |
# -*- coding: utf-8 -*-
#
# 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
#... |
#! /usr/bin/env python2
__author__ = "Jordan Prince Tremblay, Ismael Balafrej, Felix Labelle, Felix Martel-Denis, Eric Matte, Adam Letourneau, Julien Chouinard-Beaupre, Antoine Mercier-Nicol"
__copyright__ = "Copyright 2018, DEVINE Project"
__credits__ = ["Simon Brodeur", "Francois Ferland", "Jean Rouat"]
__license__ =... |
#!/usr/bin/env python3
import os
import sys
from subprocess import check_call, check_output, Popen
from glob import glob
EMAIL_ADDRESS = 'dummy@liamg.com'
# if this is true, then the sbatch files won't actually be submitted
dryrun = False
# if this is true, then existing output files will be overwritten
# this has... |
from copy import deepcopy
from unittest import TestCase
from unittest.mock import patch, MagicMock
from libcloud.compute.types import Provider
from libcloud.compute.drivers.ec2 import EC2NodeDriver
from host_provider.providers.aws import AWSProvider, OfferingNotFoundError
from host_provider.credentials.aws import Crede... |
"""file_renamer: module for renaming files"""
from pathlib import Path
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING: # pragma: no cover
from file_renamer.src.main import MainPage
class FileRenamer:
"""A class for renaming files"""
def __init__(self, kivy_gui: "MainPage") -> None:
... |
"""Automate the Boring Stuff didn't finish the tic-tac-toe program in its
dictionaries section. Someone had to answer the call...
...It shouldn't have been me."""
import sys, time
# we'll just leave this here
ttt_board = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
... |
# -*- coding: utf-8 -*-
from .wiserapi import WiserBaseAPI, _convert_case
class HotWater(WiserBaseAPI):
def __init__(self, *args, **kwargs):
"""Represnts the /HotWater object in the Restful API"""
# Defining default values
self.id = None # 2
self.override_type = None # "None",
... |
from koapy.backend.kiwoom_open_api_w.core.KiwoomOpenApiWEventHandler import (
KiwoomOpenApiWEventHandler,
)
from koapy.utils.logging.Logging import Logging
class KiwoomOpenApiWLoggingEventHandler(KiwoomOpenApiWEventHandler, Logging):
def OnReceiveTrData(self, scrnno, rqname, trcode, recordname, prevnext):
... |
from awsio.python.lib.io.s3.s3dataset import S3Dataset
from torch.utils.data import DataLoader
url_list = ['s3://image-data-bucket/train/n01440764/n01440764_10026.JPEG',
's3://image-data-bucket/train/n01440764/n01440764_10027.JPEG',
's3://image-data-bucket/train/n01440764/n01440764_10029.JPEG']
dataset = S3Dataset... |
# Generated by Django 2.0.4 on 2018-04-25 18:34
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("feeds", "0004_auto_20180425_1530")]
operations = [
migrations.RemoveField(model_name="notificationfeed", name="read_a... |
#!/usr/bin/env python
"""
Numba sampling routines
"""
import numpy as np
import numba
import math
from numba import jit, int8, int16, int32, float32, float64, prange
import lom._numba.lom_outputs as lom_outputs
import lom._numba.lom_outputs_fuzzy as lom_outputs_fuzzy
from numba.types import int64
def get_scalar_outp... |
from unittest.mock import patch, call
from django.core.management import call_command
from django.db.migrations import RunSQL, RunPython
from django.test import TestCase
from .commands.collect_sql import SqlType, SqlObjectOperation
class MockMigration(object):
def __init__(self, operations):
self.operat... |
import operator
import itertools
import logging
import yapsy
import yapsy.PluginFileLocator
import yapsy.PluginManager
from . import types
from . import decorators
from . import locator
class PluginManager(object):
PLUGIN_CATS = {types.ConversationPlugin.CATEGORY:
types.ConversationPlugin,
... |
import json
import os
import threading
import urllib.request
from collections import defaultdict
from flask import Flask, abort, jsonify, redirect, request
CACHE_PATH = os.getenv("CACHE_PATH", "cache.json")
DEFAULT_SOURCE = os.getenv("DEFAULT_SOURCE", "repo.horoscope.dev")
USER_AGENT = os.getenv("USER_AGENT", "Dalamu... |
from .default_tagger import tag
from .base import map_paren, reverse_map_paren
__all__ = ['tag', 'map_paren', 'reverse_map_paren']
|
from typing import Callable, Optional
from flask import Blueprint
def _factory(
partial_module_string: str,
url_prefix: str,
protected: bool = False,
auth_function: Optional[Callable] = None,
) -> Blueprint:
# Create the blueprint
blueprint = Blueprint(
partial_module_string,
... |
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
ANSI = "\u001b["
CODE = f"{ANSI}38;5;"
THEME = {
"th_added": f"{CODE}48;1m",
"th_conflicted": f"{CODE}209;1m",
"th_deleted": f"{CODE}203;1m",
"th_dim": f"{ANSI}2m",
"th_error": f"{CODE}9;1m",
"th_keyword": f"{CODE}171;1m",
"th_modified": f"{CODE}221;1m",
"th_normal": f"{CODE}15;1m",
... |
#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a c... |
import scrapy
import lxml.html
import re
import urllib2
from ceCrawler.items import assignment
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
import json
def first():
list... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.