content stringlengths 5 1.05M |
|---|
import setuptools
setuptools.setup(
name="parallel-execute",
version="0.1.0",
author="Sahil Pardeshi",
author_email="[email protected]",
description="Python wrappers for easy multiprocessing and threading",
long_description=open('README.rst').read(),
url="https://github.com/parallel-execut... |
#-------------------------------------------------------------------------------
# Get a screen catpure from DPO4000 series scope and save it to a file
# python 2.7 (http://www.python.org/)
# pyvisa 1.4 (http://pyvisa.sourceforge.net/)
# numpy 1.6.2 (http://numpy.scipy.org/... |
from .Stock import Stock |
# xxPostxx
def Xploder(s):
if s==-1:
return 0
elif s==0:
return 1
elif s %2 == 0:
return ((s*2))+1
elif s==2:
return 2
else:
#for x in range(0,10):
temp = s+1
#print(s,temp)
s = temp * 2 -1
return s
def exploder(s):
if s % 2 == 0 and s != 2:
return s-1
elif s==... |
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import auth, messages
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from .forms... |
import setuptools
with open("../README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="fuzzy-potato",
version='0.0.1',
author="Cezary Maszczyk",
author_email="[email protected]",
description="Library for string fuzzy matching",
long_description=long_descriptio... |
import logging
import argparse
import os
import xml.etree.ElementTree as ET
import vision_genprog.tasks.image_processing as image_processing
import genprog.core as gpcore
import cv2
import ast
logging.basicConfig(level=logging.DEBUG, format='%(asctime)-15s %(message)s')
def main(
imageFilepath,
indivi... |
from tkinter import Variable
from typing import Callable
from flask import Flask
from flask.testing import FlaskClient
from strawberry.flask.views import GraphQLView
from strawberry import Schema
from src import APOLLO_PERSTISANCE_EXT_KEY
from .conftest import Query
from pytest_benchmark.fixture import BenchmarkFix... |
#!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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... |
class Solution:
def numRescueBoats(self, people, limit):
"""
:type people: List[int]
:type limit: int
:rtype: int
"""
people.sort()
start, end = 0, len(people) - 1
total = 0
while start <= end:
total += 1
if people[start... |
#!/usr/bin/env python3
import requests
import sys
import os
import typing
from bech32 import bech32_encode, bech32_decode
BECH32_PUBKEY_ACC_PREFIX = "bandpub"
BECH32_PUBKEY_VAL_PREFIX = "bandvaloperpub"
BECH32_PUBKEY_CONS_PREFIX = "bandvalconspub"
BECH32_ADDR_ACC_PREFIX = "band"
BECH32_ADDR_VAL_PREFIX = "bandvaloper... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-14 21:08
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('namubufferiapp', '0008_auto_20170211_214... |
# python3
from gooey import *
import sys
from pyfaidx import Fasta
# input parameters
@Gooey(required_cols=4, program_name= 'split fasta into chunks optimized', header_bg_color= '#DCDCDC', terminal_font_color= '#DCDCDC', terminal_panel_color= '#DCDCDC')
def main():
ap = GooeyParser()
ap.add_argument("-in", "--input",... |
import pytest
from sr.tables import _cid, _concepts, _snomed
def test_cid_table():
"""Basic _cid table functionality tests."""
assert _cid.name_for_cid[2] == "AnatomicModifier"
assert "SCT" in _cid.cid_concepts[2]
assert "DCM" in _cid.cid_concepts[2]
def test_concepts_table():
"""Basic _concept... |
#!/home/jepoy/anaconda3/bin/python
import sys
import os
import random
import datetime
def main():
v = sys.version_info
print('Python version {}.{}.{}'.format(*v)) # note *v - returns a collection
v = sys.platform
print(v)
v = os.name
print(v)
v = os.getenv('PATH')
print(v)
v = os.g... |
def divisors(nb: int, extremum = False) -> list:
divisors = []
inf = 1 if extremum else 2
for i in range(inf, int(nb ** 0.5) + 1):
q, r = divmod(nb, i)
if r == 0:
if q >= i:
divisors.append(i)
if q > i:
divisors.append(nb // i)
... |
from collections import OrderedDict
class CaseInsensitiveDict:
def __init__(self):
self.dict = OrderedDict()
def __repr__(self):
return str(list(self.dict.values()))
def __getitem__(self, key):
return self.dict[key.lower()][1]
def __setitem__(self, key, value):
self.dict[key.lower()] = (key, val... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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... |
# coding: utf-8
# Like v2, and in contrast to v1, this version removes the cumprod from the forward pass
# In addition, it uses a different conditional loss function compared to v2.
# Here, the loss is computed as the average loss of the total samples,
# instead of firstly averaging the cross entropy inside each tas... |
# author: Fei Gao
#
# Reverse Integer
#
# Reverse digits of an integer.
# Example1: x = 123, return 321
# Example2: x = -123, return -321
#
# click to show spoilers.
# Have you thought about this?
# Here are some good questions to ask before coding. Bonus points
# for you if you have already thought through this!
# I... |
from flask import jsonify, request
from flask_jwt_extended import create_access_token, jwt_refresh_token_required, get_current_user
from app.blueprints.recipes.errors import bad_request, error_response
from app.blueprints.auth import bp
from app.blueprints.auth.helpers import get_fresh_jwt_token, send_password_reset_e... |
import string
def filter_to_list(filterFunc, l):
return list(filter(filterFunc, l))
def keys_from_template_string(tempStr):
stringTuples = list(string.Formatter.parse("", tempStr))
# Special case: string with no template arguments
firstTuple = stringTuples[0]
if(firstTuple[1] == None and firstTu... |
#!/usr/bin/env python3
import os
import sys
import argparse
pageCount = 0
noErrors = True
def updatePageCount():
global pageCount
pageCount += 1
sys.stdout.write("\rFound {} pages".format(pageCount))
sys.stdout.flush()
def printMessage(message):
sys.stdout.write(message)
sys.stdout.flush()
... |
#######################################################################
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE AUT... |
# encoding='utf-8'
'''
/**
* This is the solution of No. 867 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/transpose-matrix
*
* The description of problem is as follow:
* =====================================================================================... |
import setuptools
requirements = ["click >= 7.0", "Pillow >= 7.0.0"]
dev_requirements = ["black >= 19.10b0", "pre-commit >= 1.20.0"]
test_requirements = [
"coveralls >= 1.11.0",
"pytest >= 5.2.4",
"pytest-cov >= 2.8.1",
"pytest-mock >= 2.0.0",
]
with open("README.md", "r") as fh:
long_description ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 13 09:23:51 2017
@author: philipp
"""
# Analyze count distribution
# =======================================================================
# Imports
from __future__ import division # floating point division by default
import sys
import yaml
import ... |
###
# Copyright (c) 2002-2005, Jeremiah Fincher
# 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 co... |
from __future__ import absolute_import, division, print_function
import os
import sys
import uuid
import argparse
from vivarium.core.experiment import (
generate_state,
Experiment
)
from vivarium.core.composition import (
make_agents,
simulate_experiment,
plot_agents_multigen,
EXPERIMENT_OUT_D... |
# -*- coding: utf-8 -*-
"""Toolcall exception hierarchy.
"""
class ToolcallException(Exception):
"""Toolcall exception base class.
"""
class ToolcallInvalidResponse(ToolcallException):
"""Something other than a 200 OK response.
"""
class ToolcallJSonDecodeError(ToolcallException):
"""Couldn't... |
"""Module containing the actual commands stapler understands."""
import math
import os
try:
from PyPDF2 import PdfFileWriter, PdfFileReader
except:
from pyPdf import PdfFileWriter, PdfFileReader
import more_itertools
from . import CommandError, iohelper
import staplelib
def select(args, inverse=False, even_p... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: modules/tools/fuzz/third_party_perception/proto/third_party_perception_fuzz.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import ... |
import math
from TestKit import *
from UnderGUI.Commons import *
from lxml.html.builder import FONT
__all__ = ['test_commons']
def test_commons():
### Pos ###
pos = Pos(1, 2)
assert pos.x == 1 and pos.y == 2
assert Pos(1, 2) == Pos(1, 2)
assert (Pos(1, 2) == Pos(1, 3)) == False
assert (Po... |
import numpy as np
def rsiDBcross(rsi1, rsi2):
states = np.zeros(len(rsi2))
bought = 1
sold = 1
states[0] = 0
for i in range(len(rsi1)-1):
if(rsi2[i+1]>rsi1[i+1]):
if (rsi2[i+1] - rsi1[i+1] > 5) & sold == 1:
states[i+1] = 0
bought = 1
... |
#!/usr/bin/env python
from flask import Flask
from flask import request
import image_pb2 as impb
from PIL import Image
import io
import imutils
import cv2
app = Flask(__name__)
@app.route('/invocations', methods = ['POST'])
def index():
data = request.data
# Read the existing image.
image_packet = impb.I... |
from macop.utils import progress |
#import the USB and Time librarys into Python
import usb.core, usb.util, time, sys
import logging
log = logging.getLogger('hardware/owi_arm')
# led pesistence variable
led = 0
RoboArm = 0
def setup(robot_config):
#Allocate the name 'RoboArm' to the USB device
global RoboArm
RoboArm = usb.core.find(idVen... |
import asyncio
import inspect
from typing import (
Dict,
Optional,
List,
Type,
Union,
Tuple,
Mapping,
TypeVar,
Any,
overload,
Set,
)
from typing import TYPE_CHECKING
from uuid import UUID, uuid4
from bson import ObjectId, DBRef
from motor.motor_asyncio import AsyncIOMotorDat... |
from enum import Enum
from cyanodbc import connect, Connection, SQLGetInfo, Cursor, DatabaseError, ConnectError
from typing import Optional
from cli_helpers.tabular_output import TabularOutputFormatter
from logging import getLogger
from re import sub
from threading import Lock, Event, Thread
from enum import IntEnum
f... |
"""
Copyright (c) 2021, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
from argparse import Namespace
import logging
import torch
import json
import numpy
import math
from... |
#!/usr/bin/python
from __future__ import absolute_import, print_function, unicode_literals
import sys
import pytz
from datetime import datetime
import logging
from json2sor import tools
import re
import struct
import math
logger = logging.getLogger('pyOTDR')
unit_map = {
"mt (meters)":"mt",
"km... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T
#
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# ... |
"""Helper functions."""
import random
def make_id(stringLength=10):
"""Create an id with given length."""
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
return "".join(random.choice(letters) for i in range(stringLength))
|
"""
Transform a fragment in progress.
Note that intermediate functions from this module modify only `temporal_content` and
`sonic_content` attributes, but `melodic_lines` and `sonorities` attributes are left unchanged.
This is done for the sake of performance. It is cheaper to update all dependent attributes
just once... |
import pytest
import connexion
from app import usersData
@pytest.fixture(scope='module')
def client():
flask_app = connexion.FlaskApp(__name__)
with flask_app.app.test_client() as c:
yield c
def test_get_health(client):
# GIVEN no query parameters or payload
# WHEN I access to the url GET /hea... |
from contextlib import contextmanager
from datetime import datetime
from datetime import timezone
from textwrap import dedent
import mock
import pytest
from Crypto.PublicKey import RSA
from freezegun import freeze_time
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from ocflib.account.cr... |
import unittest
from backend.settings import config, template
class ConfigCorrectTest(unittest.TestCase):
def test_keys_match(self):
self.assertListEqual(list(config.keys()), list(template.keys()),
"Config and its template must have the same keys!")
def test_config_value... |
# Copyright 2021 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://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
#热门推荐(纪录片,评测,娱乐都没有)
import json
import requests
import re
from bs4 import BeautifulSoup
import urllib
url = 'https://weibo.com/video/aj/load?ajwvr=6&page=2&type=channel&hot_recommend_containerid=video_tag_15&__rnd=1584096137063'
cookies = dict(SUB='_2AkMpN-raf8NxqwJRmfoXxGniZIl_ygvEieKfaxsBJRMxHRl-yj92qhFTtRB6ArfENQB... |
import ssl
import pytest
import httpx
@pytest.mark.asyncio
async def test_load_ssl_config():
ssl_config = httpx.SSLConfig()
context = await ssl_config.load_ssl_context()
assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED
assert context.check_hostname is True
@pytest.mark.asyncio
async def ... |
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--n_epochs', type=int, default=200, help='number of epochs of training')
parser.add_argument('--batch_size', type=int, default=64, help='size of the batches')
parser.add_argument('--lr', type=float, default=0.0002, help='adam... |
from setuptools import setup
from setuptools import find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name = 'calcmass',
version = '2.0',
description = 'A script to calculate the molecular mass of a chemical compound in g/mol with its chemical formula',
author = 'Manu Kond... |
from maza.core.exploit import *
from maza.core.exploit.payloads import (
ArchitectureSpecificPayload,
Architectures,
BindTCPPayloadMixin,
)
class Payload(BindTCPPayloadMixin, ArchitectureSpecificPayload):
__info__ = {
"name": "MIPSBE Bind TCP",
"description": "Creates interactive tcp b... |
from flask_sqlalchemy import SQLAlchemy
# The rest of the initilization is in __init__.py
database = SQLAlchemy()
class User(database.Model):
uId = database.Column(database.Integer, primary_key = True, nullable = False)
username = database.Column(database.String(50), unique=True,nullable = False)
passw... |
import os
from moviepy.editor import VideoFileClip
from moviepy.editor import concatenate_videoclips
from .step import Step
from yt_concate.settings import OUTPUT_DIR
import logging
class EditVideo(Step):
def process(self, inputs, utils, data):
logger = logging.getLogger('record')
logger.warning('... |
from deficrawler.dex import Dex
def test_protocol_entities():
uniswap = Dex(protocol="Uniswap", chain="Ethereum", version=2)
balancer = Dex(protocol="Balancer", chain="Ethereum", version=1)
assert(uniswap.supported_entities() == [
'swap', 'pool'])
assert(balancer.supported_entities() == [
... |
from kivy.vector import Vector
from parabox.structures import Collector
class ElasticCollissionProcessor(object):
"""Collission processor for elastic objects"""
@staticmethod
def process_collission(first, second):
"""Process collission for two elastic objects
:param first: first widget ... |
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
from torch.utils.tensorboard import Su... |
#!/usr/bin/env python
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Tests for moe.mercurial."""
__author__ = '[email protected] (Daniel Bentley)'
from google.apputils import basetest
from moe import base
from moe import mercurial
from moe import moe_app
import test_util
REPO = None
def setUp():
glob... |
import pytz
from datetime import datetime
import pendulum
from ..conftest import assert_datetime
def test_equal_to_true():
d1 = pendulum.datetime(2000, 1, 1, 1, 2, 3)
d2 = pendulum.datetime(2000, 1, 1, 1, 2, 3)
d3 = datetime(2000, 1, 1, 1, 2, 3, tzinfo= pendulum.UTC)
assert d2 == d1
assert d3 =... |
"""
File: hangman.py
Name: Jess Hung
-----------------------------
This program plays hangman game.
Users sees a dashed word, trying to
correctly figure the un-dashed word out
by inputting one character each round.
If the user input is correct, show the
updated word on console. Players have N_TURNS
chances to try and w... |
from algoliasearch_django import AlgoliaIndex
from algoliasearch_django.decorators import register
from products.models import Product
from category.models import Category
@register(Product)
class ProductIndex(AlgoliaIndex):
fields = ('title',)
settings = {
'searchableAttributes': ['title',]
}
... |
# encoding: utf-8
import torch.nn as nn
from torch.nn import functional as F
class SingleLinearClassifier(nn.Module):
def __init__(self, hidden_size, num_label):
super(SingleLinearClassifier, self).__init__()
self.num_label = num_label
self.classifier = nn.Linear(hidden_size, num_label)
... |
import gi, logging
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Gio, GObject, GLib
from .account_tile import AccountTile
class AccountPane(Gtk.ScrolledWindow):
def __init__(self, model):
super().__init__()
self.model = model
self.flow_box = Gtk.FlowBox()
s... |
#!/usr/bin/env python3
# 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.
"""
List of all opt presets distributed with ParlAI.
This file is for automatically generating docs.
"""
# PRESET_DESC... |
"""
Various XML utilities
"""
import re
import string # pylint: disable=deprecated-module
from xml.etree import ElementTree
import salt.utils.data
def _conv_name(x):
"""
If this XML tree has an xmlns attribute, then etree will add it
to the beginning of the tag, like: "{http://path}tag".
"""
if... |
from cec15 import *
|
class Puzzle3:
def __init__(self, puzzle_input):
self.puzzle_input = puzzle_input
def calculate_gamma_epsilon(self):
gamma = ''
epsilon = ''
for i in range(len(self.puzzle_input[0])):
values = [x[i] for x in self.puzzle_input]
g = self.group(values)
... |
import datetime
import os
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
from torch.backends import cudnn
from torch.utils.data import DataLoader
from torchvision import transforms
from tensorboardX import SummaryWriter
from tqdm import tqdm
import joint_transforms
from ... |
import json
import aiohttp
from rki_covid_parser.const import DISTRICTS_URL, DISTRICTS_URL_RECOVERED, DISTRICTS_URL_NEW_CASES, DISTRICTS_URL_NEW_RECOVERED, DISTRICTS_URL_NEW_DEATHS
async def test_endpoint_districts():
"""Test the real service endpoint for availibility."""
await _test_endpoint(DISTRICTS_URL)
... |
#-------------------------------------------------------------------------------
# 3-D stirred box test
#
#
#-------------------------------------------------------------------------------
from math import *
from Spheral3d import *
from SpheralTestUtilities import *
from SpheralGnuPlotUtilities import *
from findLastRe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 17:31:56 2020
@author: Paolo Campeti
This script reproduces Figure 8 in the paper.
Uses methods imported from module sgwbprobecomb/SGWB_Signal.py and
sgwbprobecomb/Binned_errors.py.
"""
import os.path as op
import numpy as np
import matplotli... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# A Solution to "Smallest multiple" – Project Euler Problem No. 5
# by Florian Buetow
#
# Sourcecode: https://github.com/fbcom/project-euler
# Problem statement: https://projecteuler.net/problem=5
#
def calc_smallest_multiple(numbers):
factors = []
for n in rang... |
"""
Some old, example code
"""
from mcstatus import MinecraftServer
import click
from json import dumps as json_dumps
# If you know the host and port, you may skip this and use MinecraftServer("example.org", 1234)
server = MinecraftServer.lookup("example.com")
# 'status' is supported by all Minecraft servers that ar... |
from schematics.types import StringType, EmailType
from schematics.models import Model
from .utils import BaseObject, BoolIntType
class Recipient(BaseObject):
validate_on_change = False
def __init__(self, name=None, email=None, **kwargs):
kwargs['name'] = name
kwargs['email'] = email
... |
import os
import requests
import pygtrie as trie
from joblib import dump
from config import PUBLIC_SUFFIX_LIST_URL, SUFFIX_TRIE, DATA_DIR
def fetch_public_suffix_data():
data = []
try:
r = requests.get(PUBLIC_SUFFIX_LIST_URL, stream=True)
data = r.text.split("\n")
except Exception as e:
... |
import numpy as np
def thinning_T(start, intensity, lambda_max, T):
n = 0
indicators = []
sample = []
next_arrival_time = start
while True:
next_arrival_time += np.random.exponential(scale=1.0 / lambda_max)
if next_arrival_time < T:
n += 1
d = np.random.rand... |
from taichi.core import tc_core as core
from taichi.dynamics import *
from taichi.geometry import *
from taichi.misc.util import Vector, Vectori
from taichi.scoping import *
from taichi.tools import *
from taichi.visual import *
from taichi.misc import *
from taichi.misc.task import Task
from taichi.misc import setting... |
from PyQt5.QtWidgets import QWidget
from StockAnalysisSystem.interface.interface import SasInterface as sasIF
# ----------------------------------------------------------------------------------------------------------------------
def plugin_prob() -> dict:
return {
'plugin_id': 'e4b259f1-9d6a-498a-b0de-... |
import pytest
from core.controller import TypeController
from tests.test_utils import hass_mock
from core.type.switch_controller import SwitchController
@pytest.fixture
@pytest.mark.asyncio
async def sut(hass_mock, mocker):
c = SwitchController()
mocker.patch.object(TypeController, "initialize")
c.args =... |
class Circle:
'''
circle object
'''
END = ' 0'
X = ' 10'
Y = ' 20'
Z = ' 30'
RADIUS = ' 40'
LAYER = ' 8'
# circle object takes in the dxf list and the line
# number where the circle entity can be found
def __init__(self, dxf, start_line):
# initialise x, y, z... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def slice_(value, begins, ends, strides,
dtype=None, name=None, par=1,
value_ram_size=None, out_ram_size=None,
value_dtype=None):
slices = to_slices(begins, ends, strides)... |
"""
This creates an index.html file for a version downloads dir on
the openmdao.org site.
"""
import sys
import os.path
import hashlib
def file_md5(fpath):
"""Return the MD5 digest for the given file"""
with open(fpath,'rb') as f:
m = hashlib.md5()
while True:
s = f.read(4096)
... |
from typing import Tuple
from torch.utils.data import Dataset
from .datasets import get_dataset
from .augmentor import ContrastiveAugmentor
from .base_dataset_wrapper import BaseDatasetWrapper
class UnsupervisedDatasetWrapper(BaseDatasetWrapper):
"""Dataset wrapper for unsupervised image classification"""
... |
from gast.astn import AstToGAst, GAstToAst
import gast
import ast
import sys
class Ast3ToGAst(AstToGAst):
def visit_Name(self, node):
new_node = gast.Name(
self._visit(node.id),
self._visit(node.ctx),
None,
)
return ast.copy_location(new_node, node)
... |
from suii_protocol.task_protocol import TaskProtocol
from suii_mux_manager_comm.task_list import TaskList
from suii_protocol.protocol.enum_task_type import TaskType
from suii_mux_manager_comm.task import Task
## ===== RefBoxConverter ===== ##
# Converts from Refbox's ROS to our objects
class RefBoxConverter:
@stat... |
#!/usr/bin/env python
from manimlib.imports import *
from from_3b1b.old.clacks.question import BlocksAndWallExample
class NameBump(BlocksAndWallExample):
CONFIG = {
"name": "Grant Sanderson",
"sliding_blocks_config": {
"block1_config": {
"mass": 1e6,
"ve... |
import logging
import math
LOG_FORMAT = '%(asctime)s:%(levelname)s:%(message)s'
logging.basicConfig(filename='./Basic/div.log',
level=logging.DEBUG,
format=LOG_FORMAT)
def div(a, b):
try:
a/b
except ZeroDivisionError as e:
logging.error(e)... |
# -*- coding: utf-8 -*-
def limit(value, v_min, v_max):
"""
limit a float or int python var
:param value: value to limit
:param v_min: minimum value
:param v_max: maximum value
:return: limited value
"""
try:
return min(max(value, v_min), v_max)
except TypeError:
r... |
# Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import auth
from django.conf import settings
from django.template.context_processors import csrf
from django.shortcuts import render
from django.http import Http404
from django.http i... |
import random
import dgl
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.optimize import linear_sum_assignment
from utils.chem import NODE_FEATS, BOND_TYPES
from models import utils
from models.baseline_models.egnn import EnEquiNetwork
from models.baseline_models.se3_tr... |
import json
import datetime
import re
with open('./data.json') as f:
data = json.load(f)
data = data['data']
new_data = []
for entry in data:
title = entry[0]
serial = "{}-{}".format(re.split(r'(\d+)', entry[1])[0], re.split(r'(\d+)', entry[1])[1])
region = entry[2]
if "compatusa" in region:
region = ... |
import discord
from discord.ext import commands
import sys
sys.path.append("../")
import os
import pickle
import asyncio
import re
import requests
import json
import collections
from random import*
from pathlib import Path
from .utils.draft import Draft
from .utils.player import Player
from .utils.dataIO import dataI... |
from wagtail.core import blocks
from wagtail.core.blocks import RichTextBlock
from wagtail.core.fields import StreamField
from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList
from falmer.content import components
from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock... |
import json
CHAR_LOC = "character_table.json"
ITEM_LOC = "item_table.json"
FORMULA_LOC = "building_data.json"
FTYPE='formulaType'
FCT = 'manufactFormulas'
CHIP = "F_ASC"
FCT_REMOVE = ('weight', 'costPoint', 'formulaType', 'buffType', 'requireRooms', 'requireStages')
WRK = 'workshopFormulas'
ELITE = "F_EVOLVE"
WRK_R... |
# Generated by Django 3.2 on 2021-05-17 19:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_api', '0012_auto_20210517_0801'),
]
operations = [
migrations.AddField(
model_name='user',
name='pays',
... |
import copy
import json
from urllib3 import ProxyManager
from urllib import request
from flask import Response
from sqlalchemy import func
from config.config import HTTP_PROXY
from decorator.log_task import log_task
class UpdateLifelongLearningServices:
def __init__(self, db):
self.db = db
@log_ta... |
from aws_cdk import core
import aws_cdk.aws_apigateway as apigw
import aws_cdk.aws_certificatemanager as cm
import aws_cdk.aws_route53 as route53
import aws_cdk.aws_route53_targets as route53_targets
from .constructs import Api
from . import Environment
class Production(core.Stack):
def __init__(self, scope: cor... |
from flask import session
from flask_login import UserMixin
class User(UserMixin):
"""User model
Saves user data in Flask session
"""
def __init__(self, user_id, token, email=None, name=None):
self.id = user_id
self.token = token
self.email = email
self.name = name
... |
import json
from time import sleep
import requests
def match():
d = {}
count = 1
template1 = "http://cricapi.com/api/cricket"
data = requests.get(template1)
js = data.json()
if js['cache']:
for i in js['data']:
d[count] = [i["unique_id"],i['description']]
count += 1
return d
def details... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.