text stringlengths 2 999k |
|---|
#!/usr/local/bin/python
# Find all po files, and copy them to specified directory.
# Useful for uploading to Google Translator tool
#
# e.g.
# python copy_po_files_to_dir.py /tmp
import fnmatch
import os
from shutil import copyfile
import sys
from time import strftime
add_date = True
po_files = []
for root, dirnam... |
"""
Test the endpoints in the ``/oauth2`` blueprint.
"""
import pytest
from fence.jwt.token import SCOPE_DESCRIPTION, CLIENT_ALLOWED_SCOPES
def test_all_scopes_have_description():
for scope in CLIENT_ALLOWED_SCOPES:
assert scope in SCOPE_DESCRIPTION
@pytest.mark.parametrize("method", ["GET", "POST"])
... |
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = get_user_model()
fields = ('username', 'email')
|
# Copyright (c) 2009-2022 The Regents of the University of Michigan.
# Part of HOOMD-blue, released under the BSD 3-Clause License.
# features
"""Energy minimizer for molecular dynamics."""
from hoomd.md.minimize.fire import FIRE
|
# -*- 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
#... |
# pylint: disable=duplicate-code
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# ... |
"""
Quantilization functions and related stuff
"""
from functools import partial
from pandas.core.dtypes.missing import isna
from pandas.core.dtypes.common import (
is_integer,
is_scalar,
is_categorical_dtype,
is_datetime64_dtype,
is_timedelta64_dtype,
is_datetime64tz_dtype,
is_datetime_or_... |
#!/usr/bin/env python
# coding: utf-8
# 2D CNN Results: DescribeResult(nobs=20, minmax=(0.61764705, 0.9117647), mean=0.80882347, variance=0.007421234, skewness=-0.6640346646308899, kurtosis=-0.6421787948529669)
# 175.59881496429443
#
# 1D CNN Results: DescribeResult(nobs=20, minmax=(0.5, 0.7647059), mean=0.6014706, v... |
from pwn import *
from Crypto.Random import get_random_bytes
import base64
# fairly standard padding oracle attack
#
# the goal is to xor the ticket so that, decrypted, it reads
#
# ...junk.. "numbers:jackpot1,jackpot2,...jackpot5" "\x01"
# <--- at least 49 chars ---------------------->
# ... |
# Copyright 2015 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 applica... |
# -*- coding: utf-8 -*-
"""
meepo_examples.tutorial.mysql
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A demo script on how to use meepo with mysql row-based binlog.
"""
import logging
import click
import pymysql
from meepo.utils import setup_logger
setup_logger()
logger = logging.getLogger("meepo_examples.tutorial.mysql")
from... |
import matplotlib.pyplot as plt
import torch
from torch.cuda.amp import autocast
from tqdm import tqdm
from ..audio_zen.acoustics.feature import mag_phase, drop_band
from ..audio_zen.acoustics.mask import build_complex_ideal_ratio_mask, decompress_cIRM
from ..audio_zen.trainer.base_trainer import BaseTrainer
plt.swit... |
#!/usr/bin/env python
# --*-- coding:UTF-8 --*--
"""
this is a gauss unmixing methos for IRM(isothermal remanent magnetisition) acquisition curves
which is edit from
1D Gaussian Mixture Example
---------------------------
see below and https://github.com/astroML/astroML/blob/master/book_figures/chapter4/fig_GMM_1D.py
"... |
import uuid
from flask import request
from flask_restful import Resource, marshal
from FlaskProject.extendsions import cache
from blog.models import UserBlog
from common import blog_fields
from common.status import HTTP_406_UNKNOW_ACCESS, HTTP_400_ERROR, HTTP_201_CREATE_OK, TIMEOUT, HTTP_200_OK
from .models ... |
from src import TrainPageGetter, StationsGetter, StationTimetableGetter, config
from flask import Flask, jsonify, send_from_directory
from flask_cors import CORS
from datetime import datetime, timedelta
from dateutil import tz, parser
app = Flask(__name__)
CORS(app)
# Generate the station lookup table
config.global_s... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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,... |
"""
Module to dynamically generate a Starlette routing map based on a directory tree.
"""
import importlib
import inspect
import typing as t
from pathlib import Path
from starlette.routing import Route as StarletteRoute, BaseRoute, Mount
from nested_dict import nested_dict
from backend.route import Route
def cons... |
# Copyright (c) 2014 Rackspace, Inc.
#
# 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 wr... |
"""Test cases for base parser."""
import pytest
from lila.serialization.parser import Parser
def test_parse_field():
"""Check that NotImplementedError is raised if parse_field is called.
1. Create an instance of Parser class.
2. Try to parse a field.
3. Check that NotImplementedError is raised.
... |
"""
opcode module - potentially shared between dis and other modules which
operate on bytecodes (e.g. peephole optimizers).
"""
__all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs",
"haslocal", "hascompare", "hasfree", "opname", "opmap",
"HAVE_ARGUMENT", "EXTENDED_ARG", "hasnargs"]
... |
# -*- coding: utf-8 -*-
"""
"""
__title__ = "SweetRPG API Core"
__description__ = "Common code for API microservice applications"
__url__ = "https://github.com/sweetrpg/api-core"
__version__ = "0.0.81"
__build__ = 0x000000
__author__ = "Paul Schifferer"
__author_email__ = "dm@sweetrpg.com"
__license__ = "MIT"
__copyri... |
# Copyright (c) 2016 Intel Corporation.
#
# 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 la... |
grocery_item = ["Potato", "Tomato", "Water", "Ginger", "Onion"]
print(grocery_item)
# for item in grocery_item:
# if item == 'Water':
# break
# print(item)
for i in range(0, len(grocery_item)):
print(grocery_item[i])
print("***Finished***")
|
"""
.. _tut_info_objects:
The :class:`Info <mne.Info>` data structure
==============================================
"""
from __future__ import print_function
import mne
import os.path as op
###############################################################################
# The :class:`Info <mne.Info>` data object is... |
# -*- coding:utf-8 -*-
# Created by Machine (Fan Jin build the code-generator)
import tornado, os, MySQLdb
import tornado.gen
import tornado.web
import json
class form3Handler(tornado.web.RequestHandler):
def get(self):
print('----------------------------Get form3--------------------------')
try... |
# Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
thing = str(input('Digite algo: '))
print(f'É alfanumerico? : {thing.isalnum()}')
print(f'É alfabetico? : {thing.isalpha()}')
print(f'É minuscula? : {thing.islower()}')
print(f'É maiuscula? ... |
#! /usr/bin/env python3
import sys
import re
def vet_nucleotide_sequence(sequence):
"""
Return None if `sequence` is a valid RNA or DNA sequence, else raise exception.
Parameters
----------
sequence : str
A string representing a DNA or RNA sequence (upper or lower-case)
Returns
... |
import torch
from bindsnet.network import Network
from bindsnet.network.monitors import Monitor, NetworkMonitor
from bindsnet.network.nodes import Input, IFNodes
from bindsnet.network.topology import Connection
class TestMonitor:
"""
Testing Monitor object.
"""
network = Network()
inpt = Input(... |
from cogs.fun.fun import Fun
def setup(bot):
bot.add_cog(Fun(bot)) |
import copy
import json
from datetime import datetime
import pytest
from flask import url_for
from freezegun import freeze_time
from app.main.views.dashboard import (
aggregate_notifications_stats,
aggregate_status_types,
aggregate_template_usage,
format_monthly_stats_to_list,
get_dashboard_totals... |
# -*- coding: utf-8 -*-
import os
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
INSTALL_REQUIRES = [
'six>=1.9.0',
'enum34>=1.0.4',
'invoke>=0.10.1',
'requests>=2.6.2',
'decorator>=3.4.2',
'inflection>=0.3.0',
'sch... |
import os
import pkg_resources
DEFAULT_ENDPOINTS_PATH = "endpoints.yml"
DEFAULT_CREDENTIALS_PATH = "credentials.yml"
DEFAULT_CONFIG_PATH = "config.yml"
DEFAULT_DOMAIN_PATH = "domain.yml"
DEFAULT_ACTIONS_PATH = "actions"
DEFAULT_MODELS_PATH = "models"
DEFAULT_DATA_PATH = "data"
DEFAULT_RESULTS_PATH = "results"
DEFAULT_... |
import inspect
import pprint
class ParametrizedObject(object):
"""
Get the object configuration from the __init__ method.
The same as is done in the sklearn package.
"""
@classmethod
def _get_param_names(cls):
"""Get parameter names for the recommender"""
init = getattr(cls.__... |
#!/usr/bin/env python
# $Id: rst2newlatex.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing LaTeX using
the new LaTeX writer.
"""
try:
import locale
lo... |
from random import random
import logging
from telegram.ext import JobQueue, Job, run_async
from typing import *
import re
import maya
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Message, Bot
import captions
import settings
import util
from custom_botlistbot import BotListBot
from dial... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace re... |
import smbus2 as smbus
class BH1750:
def __init__(self,bus=0,address=0x23):
self.bus = smbus.SMBus(bus)
self.address = address
def get_data(self,type="lux"):
source = self.__read()
temp = source[0]
source[0] = source[1]
source[1] = temp
lux = (int.fro... |
#!/usr/bin/env python
import itertools, multiprocessing, os, random, sys, time
from optparse import OptionParser
import numpy as np
# Save people from having to set PYTHONPATH
import os
sys.path.insert(0, os.path.dirname(__file__))
from pygr import util, dnaseq, divsufsort, powrs
# The following functions allow us t... |
# 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... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, List, Optional, Any, Final
... |
import pysmurf
#S = pysmurf.SmurfControl(make_logfile=False,setup=False,epics_root='test_epics',cfg_file='/usr/local/controls/Applications/smurf/pysmurf/pysmurf/cfg_files/experiment_fp28_smurfsrv04.cfg')
import numpy as np
import time
Vrange=np.linspace(0,0.195/6.,100)+S.get_tes_bias_bipolar(3)
Vrange=[Vrange,Vrang... |
from setuptools import setup, find_packages
setup_requirements = ['pytest-runner', ]
test_requirements = ['pytest>=3', ]
setup(
name='botlander',
author="Lucas Eliaquim",
author_email='lucas_m-santos@hotmail.com',
version='1.0',
description= 'Your package short description.',
include_package_... |
import bball
def main():
team1 = bball.Team('lakers')
team2 = bball.Team('celtics')
team1.detailed_players_info()
team2.detailed_players_info()
game = bball.Game(team1, team2)
game.start()
game.save_stats()
if __name__ == '__main__':
main()
#> Think Code |
# Copyright 2018 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 applica... |
# *_*coding:utf-8 *_*
import os
import json
import warnings
import numpy as np
from torch.utils.data import Dataset
warnings.filterwarnings('ignore')
def pc_normalize(pc):
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))
pc = pc / m
return ... |
__author__ = 'palmer'
|
import json
import mmap
from tqdm import tqdm
import string
from .text_dataset import TextDataset, TextDatasetCache
from typing import Tuple, List
import os
import tarfile
class CFQ(TextDataset):
URL = "https://storage.cloud.google.com/cfq_dataset/cfq1.1.tar.gz"
def tokenize_punctuation(self, text):
... |
# -*- coding: utf-8 -*-
#
# Copyright IBM Corp. - Confidential Information
#
# Util classes for Splunk
#
import splunklib.client as splunk_client
import splunklib.results as splunk_results
import time
import requests
import urllib
from xml.dom import minidom
import json
import logging
LOG = logging.getLogger(__name... |
import tensorflow as tf
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.... |
import datetime
import unittest
from hft.backtesting import backtest
import numpy as np
from hft.backtesting.output import StorageOutput
from hft.backtesting.readers import ListReader
from hft.units.metrics.instant import VWAP_volume
from hft.units.metrics.time import TradeMetric
from hft.utils.consts import TradeSid... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# 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/l... |
# -*- coding: utf-8 -*-
"""
Exceptions raised by MTH5
Created on Wed May 13 19:07:21 2020
@author: jpeacock
"""
# Schema Error
class MTSchemaError(Exception):
pass
class MTTimeError(Exception):
pass
class MTH5Error(Exception):
pass
class MTH5TableError(Exception):
pass
class MTTSError(Except... |
#@+leo-ver=5-thin
#@+node:ekr.20140726091031.18152: * @file ../plugins/writers/__init__.py
# A dummy file to make leo.plugins.writers a package.
#@-leo
|
# -*- coding: utf-8 -*-
from .base64analyzer import Base64Analyzer
from base64 import b64decode
import binascii
class Base64AsciiAnalyzer(Base64Analyzer):
"""Analyzer to match base64 strings which decode to valid ASCII"""
name = 'Base64AsciiAnalyzer'
def __init__(self, actions, min_len=1, decode=False):
... |
import numpy as np
from chainer import cuda
from chainercv.links.model.faster_rcnn.utils.bbox2loc import bbox2loc
from chainercv.transforms.image.resize import resize
from chainercv.utils.bbox.bbox_iou import bbox_iou
class ProposalTargetCreator(object):
"""Assign ground truth classes, bounding boxes and masks ... |
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from direct.fsm import StateData
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.PythonUtil import *
from direct.task import Task
from . import CCharPaths
from toontown.toon... |
import os
from distutils.util import strtobool
from urllib.parse import urlparse
from aiohttp.web import Response
from vortex.config import DOMAIN
from vortex.middlewares import middleware
ALLOWED_ORIGINS = os.getenv("VORTEX_ALLOWED_ORIGINS", "localhost")
DISABLE_ORIGIN_CHECK = strtobool(os.getenv("VORTEX_DISABLE_OR... |
import os
from subprocess import check_output
import logging
LOGGER = logging.getLogger('PYWPS')
def ncdump(dataset):
'''
Returns the metadata of the dataset
Code taken from https://github.com/ioos/compliance-checker-web
'''
try:
output = check_output(['ncdump', '-h', dataset])
... |
# Lint as: python2, python3
# Copyright 2018 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
#
... |
import souvlaki as sv
def mutate_word(word, style):
if style.startswith('$'):
if len(word) < 2:
return word.upper()
return word[0].title() + word[1:]
elif style.islower():
return word.lower()
elif style.istitle():
return word.title()
elif style.isupper():
... |
from app import db
class Temperature(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.Text)
degrees = db.Column(db.Float) |
from data_specification.enums.data_type import DataType
from spynnaker.pyNN.models.neuron.plasticity.stdp.timing_dependence\
.abstract_timing_dependence import AbstractTimingDependence
from spynnaker.pyNN.models.neuron.plasticity.stdp.synapse_structure\
.synapse_structure_weight_only import SynapseStructureWei... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import unittest
from typing import Dict, List, Optional
import frappe
from frappe.core.doctype.doctype.doctype import (
CannotIndexedError,
DoctypeLinkError,
HiddenAndMandatoryWithoutDefaultError... |
from random import choice
languages = [
'python',
'C++',
'JavaScript',
'Java',
'go',
'ruby',
'Kotlin',
'Dart',
'Swift',
]
print('----------------------')
print(choice(languages))
print('----------------------')
|
# hash_filter.py
import hashlib
def j2_hash_filter(value, hash_type="sha1"):
"""
Example filter providing custom Jinja2 filter - hash
Hash type defaults to 'sha1' if one is not specified
:param value: value to be hashed
:param hash_type: valid hash type
:return: computed hash as a hexadecima... |
"""
random
"""
import random
start = 0
end = 100
seed = 123
rnd = random.Random(seed) # random object with seed
print(rnd.random())
print(random.random())
print(random.randint(start, end))
print(random.randrange(end))
print(random.randrange(start+2, end))
print(random.randrange(start+2, end, step=2... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, CTERA Networks Ltd.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',... |
#!/usr/bin/python -i
import sys
import xml.etree.ElementTree as etree
try:
import urllib.request as urllib2
except ImportError:
import urllib2
import json
#############################
# vuid_mapping.py script
#
# VUID Mapping Details
# The Vulkan spec creation process automatically generates string-based un... |
#!venv/bin/python
from app import app
from flaskext.actions import Manager
manager = Manager(app)
if __name__ == '__main__':
manager.run()
|
# 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... |
import pytest
from starlette.testclient import TestClient
# from sqlalchemy import create_engine
# from sqlalchemy_utils import database_exists, create_database, drop_database
# from alembic import command
# from alembic.config import Config
from app.main import v1
from app.config import DATABASE_URL
# @pytest.fixtu... |
#!/usr/bin/env python
from distutils.core import setup
from commands import getoutput
version = getoutput('git describe --always') or '1.0'
setup(name='unifi',
version=version,
description='API towards Ubiquity Networks UniFi controller',
author='Jakob Borg',
author_email='jakob@nym.se',
... |
def greetings(msg):
print("hello")
|
import functools
import numpy as np
from scipy.stats import norm as ndist
import regreg.api as rr
from selectinf.tests.instance import gaussian_instance
from selectinf.learning.utils import full_model_inference, pivot_plot
from selectinf.learning.core import normal_sampler, keras_fit
def generate(n=200, p=100, s=1... |
#
# PySNMP MIB module DES3028P-L2MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DES3028P-L2MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:40:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
import logging
import os
import yaml
import sys
from ClusterShell import NodeSet
class Config:
POSSIBLE_ATTRS = ["ipmi_user", "ipmi_pass", "model", "snmp_oids", "ro_community" ]
def __init__(self, yamlConfigFilePath):
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
if os.path.i... |
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accom... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from collections import deque
from qt.QtCore import (
Qt,
QMetaObject,
QThread,
QObject,
Slot,
Q_ARG,
QMutex,
QMutexLocker
)
import heapq
import itertools
class Action(QObject):
def __init__(self, impl, finished=None, failed=None, ma... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import ast
import lo... |
# Copyright 2016 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 applica... |
import unittest
from gaussian_system import System, time_matrix, wang_landau
from gaussian_system.thermodynamic_integration import generate_samples_mcmc
import numpy as np
from scipy.stats import multivariate_normal
class TestLikelihood(unittest.TestCase):
def test_trivial(self):
self.assertEqual("a", "a"... |
from .graph_module import GraphModule
from .graph import Graph
from .node import Argument, Node, Target, map_arg, map_aggregate
from .proxy import Proxy
from .symbolic_trace import Tracer
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
class Interpreter:
"""
An Interpreter executes an FX g... |
import re
from absl import app
import jax
from jax._src.numpy.lax_numpy import argsort, interp, zeros_like
import jax.numpy as jnp
from jaxopt import implicit_diff
from jaxopt import linear_solve
from jaxopt import OptaxSolver, GradientDescent
from matplotlib.pyplot import vlines
import optax
from sklearn import datase... |
########
# Copyright (c) 2013 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... |
from math import prod
import networkx as nx
def parse_data():
with open('2021/09/input.txt') as f:
data = f.read()
G = nx.grid_graph((100, 100))
for y, line in enumerate(data.splitlines()):
for x, height in enumerate(line):
G.add_node((x, y), height=int(height))
return ... |
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(max_iter=5000,\
solver='lbfgs',\
multi... |
# 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 use ... |
# -*- coding: utf-8 -*-
from odoo import api, fields, models, tools
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
active = fields.Boolean('Active', default=True)
workcenter_id = fields.Many2one('mrp.workcenter', string='Work Center', required=False, check_compa... |
import csv
import logging
from django import forms
from django.conf import settings
import requests
from pyisemail import is_email
try:
import phonenumbers
except ImportError:
phonenumbers = None
logger = logging.getLogger(__name__)
class PublicBodyValidator:
def __init__(self, pbs):
self.pbs... |
from pyramid.scaffolds import PyramidTemplate
class RestJsonTemplate(PyramidTemplate):
_template_dir = 'restjson_scaffold'
summary = 'Template to do REST/JSON services'
def pre(self, command, output_dir, vars):
vars["project_cc"] = self._to_camel_case(vars["project"])
return PyramidTempla... |
from typing import List
from pydantic import BaseModel
class Migration(BaseModel):
"""
Migration
"""
issueNumber: str
status: str
class MigrationOutList(BaseModel):
migrations: List[Migration]
|
from plotly.basedatatypes import BaseTraceType as _BaseTraceType
import copy as _copy
class Treemap(_BaseTraceType):
# class properties
# --------------------
_parent_path_str = ""
_path_str = "treemap"
_valid_props = {
"branchvalues",
"count",
"customdata",
"custo... |
from bingads.service_client import _CAMPAIGN_OBJECT_FACTORY_V12
from bingads.v12.internal.bulk.string_table import _StringTable
from bingads.v12.internal.bulk.entities.single_record_bulk_entity import _SingleRecordBulkEntity
from bingads.v12.internal.bulk.mappings import _SimpleBulkMapping, _DynamicColumnNameMapping
fr... |
from pyvisa import VisaIOError, ResourceManager
import numpy as np
from pylabnet.utils.logging.logger import LogHandler
class Driver:
def __init__(self, gpib_address=None, logger=None):
"""Instantiate driver class.
:gpib_address: GPIB-address of the scope, e.g. 'GPIB0::12::INSTR'
Ca... |
#! /usr/bin/python3
import sys, os, time
from typing import Tuple
Input = str
def part1(puzzle_input: Input) -> int:
return 1
def part2(puzzle_input: Input) -> int:
return 2
def solve(puzzle_input: Input) -> Tuple[int,int]:
return (part1(puzzle_input), part2(puzzle_input))
def get_input(file_path: ... |
import fresh_tomatoes
import media
# first Movies
Wings_of_Liberty = media.Movie("StarCraft II: Wings of Liberty",
"The storyline of StarCraft II takes place"
"four years after StarCraft: Brood War.",
"http://wallpapers... |
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# 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... |
import docassemble.base.config
docassemble.base.config.load()
import docassemble.webapp.db_object
db = docassemble.webapp.db_object.init_sqlalchemy()
from docassemble.webapp.files import SavedFile
from docassemble.webapp.file_number import get_new_file_number
from docassemble.webapp.core.models import Shortener, Email,... |
# Copyright 2021 DeepMind Technologies Limited
#
# 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 agr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.