text stringlengths 2 999k |
|---|
# Copyright (c) 2020 PaddlePaddle Authors. 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 app... |
import torchvision.transforms as transforms
from torchvision.utils import save_image
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch
cuda = True if torch.cuda.is_available() else False
Tenso... |
# -*- coding:utf-8 -*-
from .bean import Bean
class Metric(Bean):
_tbl = 'metric'
_id = 'id'
_cols = 'id, name, update_at'
def __init__(self, _id, name, update_at):
self.id = _id
self.name = name
self.update_at = update_at
@classmethod
def query(cls, page, limit, que... |
#!/usr/bin/env python
import asyncio
import os
import signal
import statistics
import tracemalloc
import websockets
from websockets.extensions import permessage_deflate
CLIENTS = 20
INTERVAL = 1 / 10 # seconds
WB, ML = 12, 5
MEM_SIZE = []
async def handler(ws, path):
msg = await ws.recv()
await ws.send... |
from ._JointState import *
from ._MotorState import *
from ._MotorStateList import *
|
# coding: utf-8
"""
BillForward REST API
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
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... |
from fontTools.misc.py23 import *
from array import array
from fontTools.misc.fixedTools import MAX_F2DOT14, otRound
from fontTools.pens.basePen import LoggingPen
from fontTools.pens.transformPen import TransformPen
from fontTools.ttLib.tables import ttProgram
from fontTools.ttLib.tables._g_l_y_f import Glyph
from font... |
from connect4.field import Field
import unittest
import numpy as np
class TestField(unittest.TestCase):
def setUp(self):
self.field = Field()
def test_legal_placement(self):
self.field.place(1,Field.Player.P1)
self.field.place(1,Field.Player.P2)
self.field.place(2,Field.Player... |
# Copyright 2017 The TensorFlow Authors 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 applicab... |
import faiss
import itertools
import numpy as np
from code.utils.evaluation_metrics import *
class KNN_Classifier():
def __init__(self,K,t):
self.K = K #number of neighbors to take into account
self.t = t #temperature of the softmax
def fit(self, train_descrs, train_labels):
s... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import math
from ccxt.base.errors import ArgumentsRequired
class coss (Exchange):
def descri... |
from .base import BaseGrader
class OptimizationGrader(BaseGrader):
def __init__(self, problem):
super().__init__(problem)
self.num_tasks = problem.num_tasks
def grade(self, submission, score):
task = submission.task
self.task_number = task.task_number
self.task_data = t... |
# MIT License
#
# Copyright (c) 2018-2019 Tskit Developers
#
# 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, modif... |
import sys
from .checker import PackagesDistroChecker
def main(*args: str) -> int:
return PackagesDistroChecker(*args).run()
def cmd():
sys.exit(main(*sys.argv[1:]))
if __name__ == "__main__":
cmd()
|
{
'variables': {
'project_name%': 'electron',
'product_name%': 'Electron',
'company_name%': 'GitHub, Inc',
'company_abbr%': 'github',
'version%': '1.3.4',
},
'includes': [
'filenames.gypi',
'vendor/native_mate/native_mate_files.gypi',
],
'target_defaults': {
'defines': [
... |
import _plotly_utils.basevalidators
class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name='visible', parent_name='splom', **kwargs):
super(VisibleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
# -*- coding: utf-8 -*-
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Libs
import salt.states.rdp as rdp
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from t... |
import gc
from micropython import const
from PXSensor import PxHub, key
import os
import peripheral
import binascii
import ujson as js
from machine import RTC
DEBUG = False
OPEN_SCENE_SHOW_TIME = const(2000)
CLOSING_TIME = const(10000)
CLOSE_SCENE_SHOW_TIME = const(1000)
class TextColour:
HEADER... |
# 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 ... |
"""Translation helper functions."""
from __future__ import unicode_literals
import locale
import os
import re
import sys
import gettext as gettext_module
from threading import local
import warnings
from django.utils.importlib import import_module
from django.utils.encoding import force_str, force_text
from django.uti... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... |
import _plotly_utils.basevalidators
class CmaxValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="cmax", parent_name="scattergl.marker.line", **kwargs
):
super(CmaxValidator, self).__init__(
plotly_name=plotly_name,
parent_name=pare... |
# -*- coding: utf-8 -*-
"""
integration tests for mac_pkgutil
"""
from __future__ import absolute_import, print_function, unicode_literals
import os
from tests.support.case import ModuleCase
from tests.support.helpers import (
destructiveTest,
requires_system_grains,
runs_on,
skip_if_binaries_missing,... |
import unittest
from unittest.mock import patch, Mock, MagicMock, call
from app import app, db
from flask import Flask, request, make_response, Response, jsonify, abort, g
import datetime
import os
class BaseTest(unittest.TestCase):
def setUp(self):
# self.mock_connection = Mock()
self.validUserna... |
import codecs
import fnmatch
import glob
import os
from os import path
import re
import shutil
import sys
import uuid
import json
from copy import copy
from build import ConfigurationError
import firefox_tasks
import lib
from lib import task, walk_with_depth, read_file_as_str, cd
import safari_tasks
import ie_tasks
im... |
# -*- coding: utf-8 -*-
"""
Execution utilities.
"""
import multiprocessing
import concurrent.futures as cf
from subprocess import call, Popen, PIPE
import logging
import gc
from math import floor
import os
import psutil
import getpass
import shlex
from warnings import warn
from rex.utilities.loggers import LOGGERS, l... |
from fractions import Fraction
from transnet.instance import shared_transnet_instance
from .exceptions import InvalidAssetException
from .account import Account
from .amount import Amount
from .asset import Asset
from .utils import formatTimeString
from .utils import parse_time, assets_from_string
class Price(dict):
... |
#!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Run inference for pre-processed data with a trained model.
"""
import logging
import math
import os
import sys
... |
import torch
from . import network as net
import torch.nn as nn
import torch.nn.functional as F
from .utils.config import cfg
import math
from torch.autograd import Variable
import torchvision as tv
from .rpn.anchor_target_layer import _AnchorTargetLayer
from .rpn.proposal_layer import _Proposallayer
import numpy as np... |
import argparse
from pathlib import Path, PurePath
import numpy as np
import src.data
import src.file_util
import src.image_util
import src.model
def eval(
image_chunks: np.ndarray,
mask_chunks: np.ndarray,
downscale_factor: int,
g_c: src.data.ModelFile,
g_f: src.data.ModelFile,
) -> np.ndarray:... |
import unittest
import os
from modules.DatabaseModule.DBManager import DBManager
from opentera.config.ConfigManager import ConfigManager
from tests.opentera.db.models.BaseModelsTest import BaseModelsTest
class TeraTestTest(BaseModelsTest):
filename = os.path.join(os.path.dirname(__file__), 'TeraTestTest.db')
... |
from models import Chatter
from datetime import timedelta
def expired_users(c):
expiry = timedelta(seconds=30)
tbr = c.check_in - expiry
u = Chatter.objects.all()
for user in u:
if tbr > user.check_in:
user.delete()
return u;
|
from random import *
tests = ((-1, 0), #on défini les coodonnées de vecteurs, lesquels permettront d'effectuer des tests dans le plateau de jeu
( 1, 0),
( 0, -1),
( 0, 1),
(-1, -1),
(-1, +1),
( 1, -1),
( 1, 1)
)
def Jouer(grille, c... |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
# Copyright 2017 IBM RESEARCH. 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/licen... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
"""This module contains some common functions for both folium and ipyleaflet.
"""
import csv
import os
import requests
import shutil
import tarfile
import urllib.request
import zipfile
import folium
import ipyleaflet
import ipywidgets as widgets
import whitebox
from IPython.display import display, IFrame
class Titil... |
#!/usr/bin/env python3
from flask import Flask
from ask_sdk_core.skill_builder import SkillBuilder
from flask_ask_sdk.skill_adapter import SkillAdapter
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
from ask_sdk_model... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.shortcuts import render
from django.utils import timezone
from django.views import generic
from AfeNews.models import New
from Copywriter.forms import ArticleForm
from... |
"""
WSGI config for Learning project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... |
"""This is reservoir sampling, each sample has storage-probability 'buffer samples M / seen samples'
"""
import torch
import torch.nn as nn
import torch.optim as optim
import random
class Net(nn.Module):
def __init__(self,
n_inputs,
n_outputs,
n_tasks,
... |
"""
CInterval-extensions module: contains methods to extend functionality
of the CInterval class
"""
from direct.directnotify.DirectNotifyGlobal import directNotify
notify = directNotify.newCategory("Interval")
def setT(self, t):
# Overridden from the C++ function to call privPost... |
from __future__ import with_statement
from logging.config import fileConfig
from sqlalchemy import engine_from_config, create_engine
from sqlalchemy import pool
from alembic import context
from rdl.entities import Base
from rdl.shared import Constants
# this is the Alembic Config object, which provides
# access to ... |
from analyzer import Pattern
from analyzer import PatternRecognizer
# List from https://ntsi.com/drivers-license-format/
# ---------------
# WA Driver License number is relatively unique as it also
# includes '*' chars.
# However it can also be 12 letters which makes every 12 letter'
# word a match. Therefore we spli... |
#!/usr/bin/python3
import gym
from gym import wrappers
import time
from PPO_clonedAll_ants import PPO, Memory
from PIL import Image
import torch
import numpy as np
import ants
deviceName = "cuda:0" if torch.cuda.is_available() else "cpu"
deviceName = "cpu"
device = torch.device(deviceName)
def test():
##########... |
import sys
from rpython.rlib import rlocale
from rpython.rlib.objectmodel import we_are_translated
def getdefaultencoding(space):
"""Return the current default string encoding used by the Unicode
implementation."""
return space.wrap(space.sys.defaultencoding)
def setdefaultencoding(space, w_encoding):
""... |
"""
Argo Workflows API
Argo Workflows is an open source container-native workflow engine for orchestrating parallel jobs on Kubernetes. For more information, please see https://argoproj.github.io/argo-workflows/ # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-g... |
from mlflow.entities.model_registry._model_registry_entity import _ModelRegistryEntity
from mlflow.entities.model_registry.model_version_tag import ModelVersionTag
from mlflow.entities.model_registry.model_version_status import ModelVersionStatus
from mlflow.protos.model_registry_pb2 import (
ModelVersion as ProtoM... |
from django import template
from django.db.models import get_model
from oscar.apps.basket.forms import AddToBasketForm
register = template.Library()
product_model = get_model('product','item')
@register.tag(name="basket_form")
def do_basket_form(parse, token):
tokens = token.split_contents()
if len(token... |
import json
from datetime import datetime
import pytest
import responses
from twitch import TwitchHelix
from twitch.constants import BASE_HELIX_URL
from twitch.exceptions import TwitchAttributeException
from twitch.helix.base import APICursor
from twitch.resources import Clip, Follow, Game, Stream, StreamMetadata, V... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from wtforms import Form, validators
from wtforms import TextField
class UserForm(Form):
name = TextField('name', [validators.Length(max=64, message="姓名最多允许 64 个字符"),
validators.DataRequired()])
phone = TextField('phone', [validators... |
"""
Представлен список чисел.
Определить элементы списка, не имеющие повторений.
Сформировать итоговый массив чисел, соответствующих требованию.
Элементы вывести в порядке их следования в исходном списке.
Для выполнения задания обязательно использовать генератор.
Пример исходного списка: [2, 2, 2, 7, 23, 1, 44, 44, 3, ... |
#!/usr/bin/env python
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import os
import shutil
import glob
def clean():
to_delete = [
'session_stats',
'libtorrent_logs*',
'round_trip_ms.log',
'dht.log',
'upnp.log',
'natpmp.log',
'bin',
'build-a... |
# coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. 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
#
# Un... |
# -*- coding: utf-8 -*-
import select
class SocksPoll(object):
"""兼容 macOS 和 Linux 的 poll 对象"""
@staticmethod
def create():
if hasattr(select, "epoll"):
return SocksEpoll()
else:
return SocksKqueue()
def __init__(self):
self.socks = {} # fileno: so... |
import functools
class SnareDrum: pass
class Cymbal: pass
class Stick: pass
class Brushes: pass
@functools.singledispatch
def play(instrument, accessory):
raise NotImplementedError('Cannot play these')
@play.register(SnareDrum)
def _(instrument, accessory):
if isinstance(accessory, Stick):
return '... |
# -*- coding: utf-8 -*-
"""
Basic JavaLexer Test
~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import time
import pytest
from pygments.token import Keyword, Name, Number, Punctuation, String, Text
from pygments.lex... |
from integration.helpers.base_test import BaseTest
class TestBasicApplication(BaseTest):
"""
Basic AWS::Serverless::Application tests
"""
def test_basic_application_s3_location(self):
"""
Creates an application with its properties defined as a template
file in a S3 bucket
... |
import six
from unittest import TestCase
from Bio.Alphabet.IUPAC import IUPACAmbiguousDNA
from dark.dna import (
AMBIGUOUS, BASES_TO_AMBIGUOUS, compareDNAReads, matchToString,
findKozakConsensus, FloatBaseCounts, sequenceToRegex)
from dark.reads import Read, DNARead, DNAKozakRead
class TestAmbiguousLetters(... |
import os
import unittest
import json
from mock import patch
from spotinst_sdk import SpotinstClient
class SimpleNamespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
keys = sorted(self.__dict__)
items = ("{}={!r}".format(k, self.__dict__[k]) for k... |
'''
Deep Neural Net.
'''
# -------------------- Imports -------------------- #
from keras.models import Sequential
from keras.layers import Dense
from pokerman_common import *
# -------------------- Preparign the Data -------------------- #
train_y_onehot = list()
for y in range(len(train_y)):
temp = [0] * conf... |
#!/usr/bin/python -Wall
# ================================================================
# Copyright (c) John Kerl 2007
# kerl.john.r@gmail.com
# ================================================================
from __future__ import division # 1/2 = 0.5, not 0.
from kerlutil import *
from cmath import *
def c(x):... |
# -*- 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... |
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# -*- coding: utf-8 -*-
"""
"""
def from_sgraph(sgraph):
"""
:param sgraph:
:return:
"""
new_graph = {}
elements = {}
nodes = []
edges = []
nodes_original = sgraph.vertices
el = sgraph.edges
node_attr = nodes_original[0].keys()
for node in nodes_original:
new... |
from click.testing import CliRunner
from cdtm_appliednlp.scripts.predict import main
def test_predict():
runner = CliRunner()
result = runner.invoke(main, [])
assert result.exit_code == 0
|
# coding: utf-8
# In[1]:
from detecting.config import cfg
from detecting.build.fasterrcnn import FasterRCNNModel
from detecting.datasets.datasets import load_data_generator
from detecting.utils.eval_coco import eval_coco
# In[ ]:
# 与配置文件中的配置合并
cfg.merge_from_file('eval.yml')
# 载入模型
model = FasterRCNNModel(cfg)
... |
# Copyright 2018 OpenStack Foundation
# 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 requ... |
# -*- coding: utf-8 -*-
"""Console script for nessie_client."""
import datetime
import sys
from collections import defaultdict
from typing import Any
from typing import Dict
from typing import Generator
from typing import List
from typing import Mapping
from typing import Optional
from typing import Tuple
import attr
... |
from __future__ import with_statement
__author__ = "Sunil Kumar (kumar.sunil.p@gmail.com)"
__copyright__ = "Copyright 2014, Washington University in St. Louis"
__credits__ = ["Sunil Kumar", "Steve Pieper", "Dan Marcus"]
__license__ = "XNAT Software License Agreement " + \
"(see: http://xnat.org/about/lic... |
import nltk
import pickle
from nltk.classify import ClassifierI
from nltk.classify.scikitlearn import SklearnClassifier
from nltk.metrics.scores import precision, recall
from nltk.tokenize import word_tokenize
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB, GaussianN... |
from __future__ import absolute_import
import re
import datetime
import logging
import os
import socket
from socket import error as SocketError, timeout as SocketTimeout
import warnings
from .packages import six
from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection
from .packages.six.moves.http_... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'acount-settings.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCo... |
import json
import logging
import os
import uuid
from collections import namedtuple
from typing import (
Dict,
List,
Optional,
)
from gxformat2 import (
from_galaxy_native,
ImporterGalaxyInterface,
ImportOptions,
python_to_workflow,
)
from pydantic import BaseModel
from sqlalchemy import an... |
import pytest
from pandas_visual_analysis import DataSource
from pandas_visual_analysis.widgets import BaseWidget
from tests import sample_dataframes
@pytest.fixture(scope="module")
def small_df():
return sample_dataframes.small_df()
# for coverage
def test_base_widget_abstract_methods(small_df):
BaseWidg... |
from collections import OrderedDict
import numpy as np
import pytest
from pytest_mock import MockerFixture
from pyquil.api._qam import QAMExecutionResult
from pyquil.gates import RZ, RX, I, CZ
from pyquil.noise import (
pauli_kraus_map,
damping_kraus_map,
dephasing_kraus_map,
tensor_kraus_maps,
_g... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
loop = 1
choice = 0
def menu():
print "We have several operations : "
print "Option 1 - plus"
print "Option 2 - minus"
print "Option 3 - multiply"
print "Option 4 - divide"
print "Option 5 - exit"
return input("Please, select operation: ")
... |
"""airline URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
import requests
import User as Internal
import Utils as Utils
def BuyItem(MarketID: int) -> str:
Data = requests.get(f"https://api.roblox.com/marketplace/productinfo?assetId={MarketID}").json()
sellerId = Data['Creator']['Id']
Price = Data['PriceInRobux']
if(Price == None):
Price = 0
produc... |
card_value = {
'A': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T': 10,
}
class Hand:
def __init__(self, player, cards=''):
self.player = player
self.cards = cards
self.is_doubled = False
def add_card(self, card):
... |
from gensim.corpora import Dictionary
from gensim.models.tfidfmodel import TfidfModel
from gensim.matutils import sparse2full
import spacy
nlp = spacy.load('en_core_web_sm')
import numpy as np
import itertools
class TfIdfEncoder:
def __init__(self, config):
self.docs = config['docs']
self.normalize = Tr... |
"""
Tools for waiting for a cluster.
"""
import click
from dcos_e2e.node import Transport
from dcos_e2e_cli.common.options import (
enable_spinner_option,
existing_cluster_id_option,
superuser_password_option,
superuser_username_option,
verbosity_option,
)
from dcos_e2e_cli.common.utils import che... |
# Simple elasticsearch logger
from typing import Any, Dict
from elasticsearch import Elasticsearch, NotFoundError
import cowrie.core.output
from cowrie.core.config import CowrieConfig
class Output(cowrie.core.output.Output):
"""
elasticsearch output
"""
index: str
pipeline: str
def start... |
import re
import requests
BASE_URL = 'https://www.facebook.com/{handler}/'
PATTERN_PAGE = '\{\"pageID\"\:\"(\d+?)\"\,\"pageName\"\:\"'
PATTERN_PROFILE = '\"entity_id\"\:\"(\d+?)\"\}'
def get_id(handler):
"""Returns Facebook user/page ID for the given handler
"""
req = requests.get(BASE_URL.format(handler=... |
# VXT
# Developed by Christian Visintin
#
# MIT License
# Copyright (c) 2021 Christian Visintin
# 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 limitati... |
import numpy as np
def H(x):
"""
step function
"""
return 0.5*(np.sign(x-1e-9)+1)
def G(t1, t2):
"""
pulse
"""
return lambda t: H(t2-t) - H(t1-t)
def round_dt(dt):
return float('{0:.7f}'.format(dt))
# return dt
def round_dv(dv):
return float('{0:.7f}'.format(dv))
# ret... |
#!/usr/bin/env python3
import logging
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
from torch import Tensor
class ResultDiffs:
def __init__(self, diffs: Tensor):
self._diffs = diffs
self._rmse = None
... |
from turkey.models import User
from turkey import app
from flask.ext.login import (LoginManager, login_user, logout_user,
login_required, current_user)
from flask import request, render_template, redirect, url_for, flash, abort
from wtforms import Form, TextField, PasswordField, validators
... |
from keras.layers import Input
from keras import backend as K
from keras.engine.topology import Layer
import numpy as np
class DynamicMaxPooling(Layer):
def __init__(self, psize1, psize2, **kwargs):
# for psize1, psize2 [3, 10]
self.psize1 = psize1
self.psize2 = psize2
super(Dynami... |
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls.base import reverse
from django.views.generic import ListView
from django.core.mail import send_mail
from . models import Post, Comment
from . form import EmailForm, CommentForm
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class KarmaTracking(models.Model):
_name = 'gamification.karma.tracking'
_description = 'Track Karma Chang... |
import textwrap
from pathlib import Path
from typing import Optional
import cli_ui as ui
import tsrc
import tsrc.executor
import tsrc.git
class Cloner(tsrc.executor.Task[tsrc.Repo]):
""" Implement cloning missing repos. """
def __init__(
self,
workspace_path: Path,
*,
shallo... |
#use dataclass if >=python3.7
class ParamConfig:
def __init__(self, batch_size, epochs, workers, cuda, use_half, learning_rate):
self.batch_size = batch_size
self.epochs = epochs
self.workers = workers
self.cuda = cuda
self.use_half = use_half
self.learning_rate = le... |
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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... |
from .encode import support_check
import PIL.Image as Imager
import numpy as np
import sys
class Decoder:
def __init__(self, img, passwd=None):
self.img, self.passwd = img, passwd
self.start_indicator, self.stop_indicator, self.msg, self.img_arr, self.img_mode = (None,) * 5
def get_img_arr_d... |
# -*- test-case-name: twisted.web.test.test_util -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An assortment of web server-related utilities.
"""
import linecache
from twisted.python import urlpath
from twisted.python.compat import _PY3, unicode, nativeString, escape
from twisted.p... |
# -*- coding: utf-8 -*-
"""
mod: api
version: v1
"""
from flask import (
Flask, Blueprint, request, session, g,
redirect, url_for, abort, render_template,
flash, current_app, make_response
)
from flask_restful import reqparse, abort, Resource, Api
bp = Blueprint(__name__, __name__, url_prefix='/api... |
import os
from glob import glob
import imageio
from batchlib.preprocessing import Preprocess
# TODO make it more general
def get_barrel_corrector(folder):
barrel_corrector_path1 = '../misc/barrel_corrector.h5'
barrel_corrector_path2 = '../misc/barrel_corrector_1024x1024.h5'
in_path = glob(os.path.join(f... |
"""
This is an implementation of `sha256_treehash`, used to calculate
puzzle hashes in clvm.
This implementation goes to great pains to be non-recursive so we don't
have to worry about blowing out the python stack.
"""
from typing import Optional, Set
from clvm import CLVMObject
from venidium.types.blockchain_forma... |
"""scraperproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
from __future__ import print_function, division
from sympy.core import S, sympify, cacheit, pi, I
from sympy.core.add import Add
from sympy.core.function import Function, ArgumentIndexError, _coeff_isneg
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.elementary.exp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.