text stringlengths 2 999k |
|---|
"""Incantations only a selected group of High Wizards can utilize.
"""
from re import * # pylint: disable=W0614, W0401, W0622
|
#!/usr/bin/env python
from .fmap import FieldEnhance, FieldToRadS, FieldToHz, Phasediff2Fieldmap, Phases2Fieldmap
|
import os
import json
from flask import Flask, jsonify, request, send_file
from flask_cors import CORS, cross_origin
DEFAULT_LOGO = 'logos/default.jpg'
app = Flask(__name__)
CORS(app)
@app.route('/')
def hello():
return "Hello World!"
@app.route('/logos/<org>', methods=['GET'])
def get_image(org):
if os.pat... |
import numpy as np
import pandas as pd
import hydrostats.data as hd
import hydrostats.visual as hv
import HydroErr as he
import matplotlib.pyplot as plt
import os
from netCDF4 import Dataset
# Put all the directories (different states and resolutions) and corresponding NetCDF files into lists.
list_of_files = []
list_... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import logging
from PIL import Image
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
import torchvision.transforms.functional as TF
from torchvision import transforms
import random
import os
cl... |
# Select deconvolution method
from networks.G.FP import FP
from networks.G.Wiener import Wiener
def select_G(params, args):
if args.G_network == 'FP':
return FP(params, args)
elif args.G_network == 'Wiener':
return Wiener(params, args)
else:
assert False, ("Unsupported generator ne... |
#!/usr/bin/env python
"""
For more information on this API, please visit:
https://duo.com/docs/adminapi
-
Script Dependencies:
requests
Depencency Installation:
$ pip install -r requirements.txt
System Requirements:
- Duo MFA, Duo Access or Duo Beyond account with aministrator priviliedges.
- Duo ... |
# Databricks CLI
# Copyright 2017 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"), except
# that the use of services to which certain application programming
# interfaces (each, an "API") connect requires that the user first obtain
# a license for the use of the APIs from Databricks,... |
"""
sphinx.ext.autodoc.importer
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Importer utilities for autodoc
:copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import importlib
import traceback
import warnings
from typing import Any, Callable, Dict, List, M... |
from dataclasses import dataclass, field
from enum import Enum, auto, unique
from eth_typing import BLSPubkey
from eth2._utils.humanize import humanize_bytes
from eth2.beacon.signature_domain import SignatureDomain
from eth2.beacon.typing import CommitteeIndex
from eth2.validator_client.tick import Tick
@unique
cla... |
from click.testing import CliRunner
from pyskel_bc.cli import cli
def test_cli_count():
runner = CliRunner()
result = runner.invoke(cli, ['3'])
assert result.exit_code == 0
assert result.output == "False\nFalse\nFalse\n"
|
from typing import Generic, Iterator, TypeVar
T = TypeVar('T')
class Peekable(Generic[T]):
__slots__ = "just", "next", "iterator"
def __init__(self, iterator: Iterator[T]):
self.iterator = iterator
self.next: T | None = next(self.iterator, None)
self.just: T | None = None
... |
import unittest
from programy.config.file.yaml_file import YamlConfigurationFile
from programy.clients.restful.config import RestConfiguration
from programy.clients.events.console.config import ConsoleConfiguration
class RestConfigurationTests(unittest.TestCase):
def test_init(self):
yaml = YamlConfigura... |
"""RCS interface module for CVSGit."""
from __future__ import absolute_import
import rcsparse
# Some observations about RCS + CVS, although I don't really know
# that much about the RCS format or the CVS usage of it...
#
# 1. The 'branch' keyword is normally absent (or empty?), but has
# the value "1.1.1" for file... |
'''
========================
efficient_vdf module
========================
Created on Feb.6, 2022
@author: Xu Ronghua
@Email: rxu22@binghamton.edu
@TaskDescription: This module provide efficient verifiable delay function implementation.
@Reference: Efficient Verifiable Delay Functions (By Wesolowski)
C++ prototype:... |
from __future__ import annotations
import pytest
from bot.emote import EmotePosition
from bot.emote import parse_emote_info
@pytest.mark.parametrize(
('s', 'expected'),
(
('', []),
('303330140:23-31', [EmotePosition(23, 31, '303330140')]),
('302498976_BW:0-15', [EmotePosition(0, 15, ... |
from django.contrib.auth import get_user_model, authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ("email", "password", "name")
extra_k... |
import psycopg2
import pandas.io.sql as sqlio
import pandas as pd
import dash
from dash import dcc
from dash import html
import plotly.express as px
app = dash.Dash(__name__)
# Connect to Materialize as a regular database
conn = psycopg2.connect("dbname=materialize user=materialize port=6875 host=localhost")
# Read ... |
import re
from typing import List
import requests
from anime_cli.anime import Anime
from anime_cli.search import SearchApi
class GogoAnime(SearchApi):
def __init__(self, mirror: str):
super().__init__(mirror)
self.url = f"https://gogoanime.{mirror}"
@staticmethod
def get_headers() -> di... |
# Copyright (c) 2021, IAC Electricals and contributors
# For license information, please see license.txt
import frappe
from frappe import _
import gzip
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
def before_insert(self,method=None):
self.flags.name_set = 1
current = fr... |
from typing import Iterable, Type
from vkbottle.api import ABCAPI
from vkbottle.http import AiohttpClient, SingleSessionManager
from vkbottle.modules import logger
from vkbottle.polling import ABCPolling, BotPolling
from .bot import Bot
def bot_run_multibot(bot: Bot, apis: Iterable[ABCAPI], polling_type: Type[ABCPo... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 AVSystem <avsystem@avsystem.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
from pytorch_lightning.callbacks import Callback
import math
from typing import List
__all__ = ['LrSchedullerStep']
def _annealing_cos(start_value: float, end_value: float, pct: float) -> float:
''' Calculate value for Cosine anneal.
Return value at pct, as pct goes from 0.0 to 1.0, from `start_value` to `en... |
def read_next(*args):
for el in args:
for ch in el:
yield ch
for item in read_next('string', (2,), {'d': 1, 'i': 2, 'c': 3, 't': 4}):
print(item, end='') |
import numpy as np
import tensorflow as tf
import gym
import time
from spinup.algos.td3 import core
from spinup.algos.td3.td3_randtarg import ReplayBuffer
from spinup.algos.td3.core import get_vars
from spinup.utils.logx import EpochLogger
from spinup.utils.run_utils import ExperimentGrid
"""
Exercise 2.3: Details M... |
import pytest
from numpy.testing import assert_array_almost_equal
from landlab import RasterModelGrid
from landlab.components import ErosionDeposition, FlowAccumulator, Space
@pytest.fixture
def grid():
grid = RasterModelGrid((10, 10), xy_spacing=10.0)
grid.set_closed_boundaries_at_grid_edges(True, True, Tru... |
# (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 OpenStack Foundation
#
# 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
#
# ... |
# -*- coding: utf-8 -*-
"""
Learning Shapelets
==================
This example illustrates how the "Learning Shapelets" method can quickly
find a set of shapelets that results in excellent predictive performance
when used for a shapelet transform.
More information on the method can be found at:
http://fs.ismll.de/pub... |
# -*- coding: utf-8 -*-
# Copyright 2019 IBM.
#
# 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 agre... |
"""
All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
its licensors.
For complete copyright and license terms please see the LICENSE at the root of this
distribution (the "License"). All use of this software is governed by the License,
or, if provided, by the license below or the license... |
import urllib.request
import json
from calc import calc
URL = ("https://data.nasa.gov/resource/y77d-th95.json")
class MeteoriteStats:
def get_data(self):
with urllib.request.urlopen(URL) as url:
return json.loads(url.read().decode())
def average_mass(self, data):
c = calc.Calc()... |
# Generated by Django 2.1.7 on 2019-03-17 08:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('paste', '0004_auto_20190315_1134'),
]
operations = [
migrations.AlterField(
model_name='paste',
name='lang',
... |
# 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
from ... import _utilities, _tables
from... |
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import re
from reframe.core.exceptions import ReframeError
def re_compile(patt):
try:
return re.compile(patt)
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class Repository(pulumi.CustomResourc... |
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
import difflib
import asyncio, ssl, sys, random
import mrworkserver, mrpacker
num = 0
users = {}
async def on_start(ws):
print("on_start")
ws.gather = asyncio.ensure_future( gather(ws) )
async def on_stop(ws):
print("on_stop, num =",num)
async def callback(ws, msgs):
for m in msgs:
num += 1
print ("P... |
import numpy as np
import os
from mpEntropy import mpSystem
import matplotlib as mpl
from matplotlib.pyplot import cm
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
# This is a workaround until scipy fixes the issue
import warnings
warnings.filterwarnings(action="ignore", module="scipy", messag... |
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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 ... |
'''
BSD Licence Copyright (c) 2016, Science & Technology Facilities Council (STFC)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright no... |
from __future__ import division, absolute_import, print_function
import sys
import time
from datetime import date
import numpy as np
from numpy.testing import (
run_module_suite, assert_, assert_equal, assert_allclose, assert_raises,
)
from numpy.lib._iotools import (
LineSplitter, NameValidator, StringCo... |
from parser import OneOf, character, greedy, greedy1, pack, satisfy, token
def use(templateResult):
return templateResult[0][0]
def template():
return greedy(literal().orElse(substitution()))\
.map(lambda result: Concatenation(result))
def literal():
return greedy1(escapedCharacter().orElse(notAn... |
"""
Unit tests
"""
from django.test import TestCase
from django.test.utils import override_settings
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import LANGUAGE_SESSION_KEY
from mapentity.factories import SuperUserFactory
from geotrek.authent.models i... |
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect
from django.urls import reverse_lazy
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.generic import ListView, Detai... |
# coding=utf-8
import Adafruit_DHT
import time
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Potrebbe essermi utile per generare un topic in caso di errore di lettura dal sensore
import paho.mqtt.clie... |
import numpy as np
from numpy.fft import fft, ifft, fftfreq, rfftfreq
from astropy.io import ascii,fits
from scipy.interpolate import InterpolatedUnivariateSpline, interp1d
from scipy.integrate import trapz
from scipy.special import j1
import multiprocessing as mp
import sys
import gc
import os
import bz2
import h5py
... |
# ----------------------------------------------------------------------------
# Copyright (c) 2017-2019, Ben Kaehler.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -------------------------------------------------------------... |
from datetime import datetime
import sqlalchemy as sql
from web import sql_database as db
from sqlalchemy.orm import relationship
class Queue(db.Model):
id = sql.Column(sql.Integer, primary_key=True)
song_id = sql.Column(sql.Integer, sql.ForeignKey(
'song.id'), nullable=False, unique=True)
song = ... |
#!/usr/bin/env python
# Copyright 2018 The Kubernetes 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 appli... |
# 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 ... |
# Generated by Django 2.0.10 on 2019-04-30 22:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('meal_app', '0005_auto_20190430_2250'),
]
operations = [
migrations.RenameField(
model_name='meal',
old_name='date_fieled',
... |
#!/usr/bin/python3
import argparse
from core import main
parser = argparse.ArgumentParser(description='Classify some data.')
parser.add_argument('-k', type=int, default=1, help='k Nearest Neighbor classifier')
parser.add_argument('-d', '--distance', choices=['euclidean', 'hamming+', 'linear_mahalanobis', 'quadratic_... |
from flask import render_template,url_for,redirect,request
from . import main
from app import db, photos
from sqlalchemy import and_
from flask_login import login_required,current_user
from .forms import updateForm, findMatches, photoForm
from ..models import Quality, User
from werkzeug.utils import secure_filen... |
#!/usr/local/bin/python
# coding: utf-8
#
# EPXERIMENTAL TOC STRUCTURE!!!
#
from IIIFpres import iiifpapi3
import csv
from collections import defaultdict
import requests
iiifpapi3.BASE_URL = "https://dlib.biblhertz.it/iiif/bncrges1323/" # this is the path where the manifest must be accessible
# some of the resources... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from elasticsearch import Elasticsearch
class ESClient(object):
def __init__(self, hosts):
self.hosts = hosts
self.es = None
self.is_init = False
self.init()
def init(self):
if not isinstance(self.hosts, list):
... |
import os
import requests
def save_audio(audio_url, filename, dirname='audio'):
try:
audio_content = requests.get(audio_url).content
filename = os.path.join(dirname, filename)
f = open((filename), 'wb')
f.write(audio_content)
f.close()
return filename
except:
return ""
|
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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... |
# Copyright 2008-2020 Yannick Versley
#
# 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, publish, dist... |
# -*- coding: utf-8 -*-
"""
gc3-query.__init__.py [9/8/2018 1:34 PM]
~~~~~~~~~~~~~~~~
<DESCR SHORT>
<DESCR>
"""
################################################################################
## Standard Library Imports
import sys, os
############################################################################... |
# suorganizer/urls.py
# Django modules
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls', namespace='blog')),
path('', include('organizer.urls', namespace='organizer')),
]
|
#!/usr/bin/env python3
"""
pass.py
Find hardcoded passwords on source code of your project.
python pass.py path/to/project
"""
import os
import sys
import re
import fnmatch
import json
from argparse import ArgumentParser
DEFAULT_BAD_WORDS = ['token', 'oauth', 'secret', 'pass', 'password', 'senha']
DEFAULT_ANALYZERS... |
import json
import pexpect
from programmingalpha.Utility import getLogger
logger = getLogger(__name__)
class SimpleTokenizer(object):
def tokenize(self,txt):
return txt.split()
class CoreNLPTokenizer(object):
def __init__(self):
"""
Args:
classpath: Path to the cor... |
from typing import Tuple
import torch
from torch import nn
from torch.nn import functional as F
from utils import Tensor, assert_shape, build_grid, conv_transpose_out_shape
class SlotAttention(nn.Module):
"""Slot attention module that iteratively performs cross-attention.
Args:
slot_agnostic (bool)... |
# Version: 0.11
"""
The Versioneer
==============
* like a rocketeer, but for versions!
* https://github.com/warner/python-versioneer
* Brian Warner
* License: Public Domain
* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy
[]... |
import uuid
from django.db import models
from electionnight.fields import MarkdownField
class PageContentBlock(models.Model):
"""
A block of content for an individual page.
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
page = models.ForeignKey(
"PageCont... |
#import h5py
import numpy as np
import scipy.io as sio
import torch
from sklearn import preprocessing
import sys
import h5py
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('Ba... |
class ChangeMetricsClass(object):
instanceName = '';
LOC = 0;
LOC_touched = 0;
Number_of_Revisions = 0;
Fix_Count = 0;
Authors = 0;
LOC_added = 0;
Max_LOC_added = 0;
Average_LOC_added = 0;
Churn = 0;
Max_Churn = 0;
Average_Churn = 0;
Change_Set_Size = 0;
Max... |
from ..abstract_base_classes.table_cruder_default import TableCRUDerDefault
from ....models.daily_traded_volume_money import DailyTradedVolumeMoney
__all__ = ['DailyTradedVolumeMoneyTableCRUDer']
class DailyTradedVolumeMoneyTableCRUDer(TableCRUDerDefault):
def __init__(self, daily_traded_volume_money_table, db_... |
"""Implements the Raster extension.
https://github.com/stac-extensions/raster
"""
import enum
from typing import Any, Dict, Generic, Iterable, List, Optional, TypeVar, cast
import pystac
from pystac.extensions.base import (
ExtensionManagementMixin,
PropertiesExtension,
SummariesExtension,
)
from pystac.... |
import authority
from kitsune.forums.models import Forum
class ForumPermission(authority.permissions.BasePermission):
label = 'forums_forum'
checks = ('thread_edit', 'thread_sticky', 'thread_locked', 'thread_delete',
'post_edit', 'post_delete', 'thread_move', 'view_in', 'post_in')
# view_in... |
# Generated by Django 2.1.2 on 2018-11-26 16:13
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),
('tran', '0001_initial'),
... |
# Python Version: 3.x
import functools
import pathlib
import subprocess
from logging import getLogger
from typing import *
from onlinejudge_verify.config import get_config
from onlinejudge_verify.languages.models import Language, LanguageEnvironment
logger = getLogger(__name__)
class NimLanguageEnvironment(Language... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-11-14 06:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mridata', '0026_data_tags_manager'),
]
operations = [
migrations.RemoveField(
... |
# 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 ... |
#
# 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"); you may not... |
#!/usr/bin/python
# Copyright (C) 2018-2021 aitos.io
#
# 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 ... |
# Copyright 2016 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 agree... |
from django.urls import path
from .views import ArticleListView,ArticleDetailView
urlpatterns = [
path('',ArticleListView.as_view()),
path('<pk>',ArticleDetailView.as_view()),
] |
# -*- coding: utf-8 -*-
# Copyright 2018-2021 The Matrix.org Foundation C.I.C.
#
# 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 re... |
# 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"); you may not u... |
"""
usage:
pbxproj folder [options] <project> <path> [--target <target>...]
[--exclude <regex>...]
[(--recursive | -r)]
[(--no-create-groups | -G)]
... |
#
# BSD 3-Clause License
#
# Copyright (c) 2020, Jonathan Bac
# 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
# ... |
import argparse
class Namespace(argparse.Namespace):
def __init__(self, prototype=None, **kwargs):
super().__init__(**kwargs)
self.prototype = prototype
def has_own_property(self, prop):
return prop in self.__dict__
def __getattribute__(self, attr):
try:
retur... |
from django.apps import AppConfig
class BofanConfig(AppConfig):
name = 'bofan'
|
# -*- coding: utf-8 -*-
# Copyright 2020 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... |
from django import forms
from django.shortcuts import get_object_or_404
from django.utils.text import slugify
from text_unidecode import unidecode
from ...product.models import Category
class CategoryForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.parent_pk = kwargs.pop('parent_pk')
... |
# std
import re
from typing import List
# ours
from jekyll_relative_url_check.abstract import RelativeURLHook
class MarkdownRelativeURLHook(RelativeURLHook):
def __init__(self):
super().__init__()
self.absolute_url_regexs: List[re.Pattern] = [
re.compile(r"\[[^]]*]\(/[^)]*\)")
... |
from __future__ import print_function
import matplotlib
from matplotlib import pyplot as plt
plt.switch_backend('agg')
import os
import json
import numpy as np
def extract(file_path):
if not os.path.isfile(file_path):
return -1, -1, -1
with open(file_path, 'r') as f:
lines = f.readlines()
... |
n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
n3 = int(input('Digite o terceiro numero: '))
menor = n1
if n2 < n3 and n2 < n1:
menor = n2
if n3 < n2 and n3 < n1:
menor = n3
maior = n1
if n2 > n3 and n2 > n1:
maior = n2
if n3 > n2 and n3 > n1:
ma... |
# stdlib
from typing import Dict
from typing import Type
# third party
import statsmodels
# syft relative
from ...generate_wrapper import GenerateWrapper
from ...lib.python.primitive_factory import PrimitiveFactory
from ...lib.python.string import String
from ...proto.lib.statsmodels.family_pb2 import FamilyProto
FA... |
# Copyright (c) 2015 Clinton Knight. 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 requir... |
# Copyright 2014 Diamond Light Source 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 applicable law or agreed t... |
from random import choice, choices, randint, random, sample, shuffle
PHONEMES = {}
PHO_CON = []
PHO_VOW = []
class Phoneme:
def __init__(self, key, **kwargs):
self.start = [key]
self.mid = [key]
self.end = [key]
self.vowel = False
self.no_start = False
self.no_mid =... |
# -*- coding: utf-8 -*-
import unittest
import pykintone
from pykintone.model import kintoneModel
import tests.envs as envs
class TestAppModelSimple(kintoneModel):
def __init__(self):
super(TestAppModelSimple, self).__init__()
self.my_key = ""
self.stringField = ""
class TestComment(uni... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
"""
Python module: 'img.py'
author: Julien Straubhaar
date: jan-2018
Definition of classes for images and point sets (gslib), and relative
functions.
"""
import os
import numpy as np
# ======================================================================... |
# Tests need to be a package otherwise ipyparallel will not find them in the package,
# when trying to import the tests in the subprocesses.
# Therefore, LEAVE THIS FILE HERE |
# Copyright (c) 2016 Orange.
# 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 a... |
import warnings
import pytest
from evalml.tuners import GridSearchTuner, NoParamsException
from evalml.tuners.tuner import Tuner
def test_grid_search_tuner_inheritance():
assert issubclass(GridSearchTuner, Tuner)
def test_grid_search_tuner_unique_values(dummy_pipeline_hyperparameters):
tuner = GridSearchT... |
# pyportal_weather.py updated for CircuitPython v7.1.0 2022-01-04
import sys
import time
import board
from adafruit_pyportal import PyPortal
cwd = ("/"+__file__).rsplit('/', 1)[0] # the current working directory (where this file is)
sys.path.append(cwd)
import openweather_graphics # pylint: disable=wrong-import-positi... |
import requests
import config
class Wallpaper:
def __init__(self, path, keyword="8k", page_num=1):
self.URL = f"https://api.pexels.com/v1/search?query={keyword}&orientation=landscape&page={page_num}&size=large&per_page=1"
self.HEADERS = {"Authorization": f"{config.api_key}"}
self.JSON = se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.