content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import logging
import numpy as np
import torch
import torch.optim as optim
INFTY = 1e20
class DKNN_PGD(object):
"""
Implement gradient-based attack on DkNN with L-inf norm constraint.
The loss function is the same as the L-2 attack, but it uses PGD as an
optimizer.
"""
def __init__(self, dk... | python |
from projecteuler import util
from functools import reduce
from operator import mul
def solution():
"""
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.
... | python |
algo = input('Digite algo: ')
print('O tipo primitivo de algo é', type(algo))
| python |
from __future__ import print_function
import base64
import random
from builtins import object, str
from textwrap import dedent
from typing import List
from empire.server.common import helpers, packets
from empire.server.utils import data_util, listener_util
class Listener(object):
def __init__(self, mainMenu, p... | python |
from blackpearl.modules import Module
from blackpearl.modules import Timer
from blackpearl.projects import Project
class MyTimer(Timer):
tick = 0.1
def setup(self):
self.start()
class Listener(Module):
listening_for = ['timer']
def receive(self, message):
print(message['timer'... | python |
from otree.api import *
c = Currency
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'payment_info'
players_per_group = None
num_rounds = 1
class Subsession(BaseSubsession):
pass
class Group(BaseGroup):
pass
class Player(BasePlayer):
pass
# PAGES
clas... | python |
from src.grid.electrical_vehicle import EV
from collections import defaultdict
from typing import List
import numpy as np
class Scenario:
def __init__(self,
load_inds: list,
timesteps_hr: np.ndarray,
evs: List[EV],
power_price: np.ndarray,
... | python |
from django.shortcuts import render, redirect
from django.http import HttpResponse
import django.contrib.auth as auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from apps import EftConfig
from . import models as etf_models
import json
from parser import parse... | python |
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from gzip import GzipFile
import tarfile
from io import BytesIO
from datetime import datetime
import json
import traceback
from psycopg2 import OperationalError
from interface.settings import PREVIEW_LIMIT... | python |
import os.path
from PIL import Image
import json
appdata_folder = os.path.join(os.environ["LOCALAPPDATA"], "Nightshift")
def generate_wallpapers(day_img_path, night_img_path, step_count):
print "Generating {0} images from {1} and {2} to {3}"\
.format(step_count, day_img_path, night_img_path, appdata_fold... | python |
"""
adapted from keras example cifar10_cnn.py
Train ResNet-18 on the CIFAR10 small images dataset.
GPU run command with Theano backend (with TensorFlow, the GPU is automatically used):
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10.py
"""
from __future__ import print_function
import tensorflo... | python |
class MiscUtils:
def __init__(self):
import requests
import json
r = requests.get("https://backpack.tf/filters")
obj = json.loads(r.text)
particles = obj['particle']
qualities = obj['quality']
rarities = obj['rarity']
paints = obj['paint']
o... | python |
import asyncio
import typing
import logging
from lbrynet.utils import drain_tasks
from lbrynet.blob_exchange.client import request_blob
if typing.TYPE_CHECKING:
from lbrynet.conf import Config
from lbrynet.dht.node import Node
from lbrynet.dht.peer import KademliaPeer
from lbrynet.blob.blob_manager impo... | python |
import grpc
from pkg.api.python import api_pb2
from pkg.api.python import api_pb2_grpc
from pkg.suggestion.test_func import func
from pkg.suggestion.types import DEFAULT_PORT
def run():
channel = grpc.insecure_channel(DEFAULT_PORT)
stub = api_pb2_grpc.SuggestionStub(channel)
set_param_response = stub.Set... | python |
# -*- coding: utf-8 -*-
# @Time: 2020/10/10 11:58
# @Author: GraceKoo
# @File: interview_63.py
# @Desc: https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/
from heapq import *
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
... | python |
import pytest
from pytest_cases.case_parametrizer_legacy import get_pytest_marks_on_function, make_marked_parameter_value
def test_get_pytest_marks():
"""
Tests that we are able to correctly retrieve the marks on case_func
:return:
"""
skip_mark = pytest.mark.skipif(True, reason="why")
@skip... | python |
from Game import game
class MyClass(object):
gamenew = game()
def executegame(self):
self.gamenew.gamce()
print 'test'
if __name__ == '__main__':
a = MyClass()
a.executegame()
| python |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
from combined_thresh import combined_thresh
from perspective_transform import perspective_transform
from Line import Line
from line_fit import line_fit, tune_fit, final_viz, calc_curve, calc_vehicle_offset, viz2... | python |
from typing import List, Dict, Optional, Union
from sharpy.combat import *
from sharpy.general.extended_power import ExtendedPower
from sharpy.interfaces import ICombatManager
from sharpy.managers.core import UnitCacheManager, PathingManager, ManagerBase
from sharpy.combat import Action
from sc2.units import Units
fr... | python |
names = []
while True:
name = input()
if name == '.':
break
names.append(name)
print(names)
print(len(names))
| python |
import ctypes
import cairo
from pygame.rect import Rect
def get_rect_by_size(upper_corner, size):
return Rect(*upper_corner, size, size)
PyBUF_READ = 0x100
PyBUF_WRITE = 0x200
def get_cairo_surface(pygame_surface):
""" Black magic. """
class Surface(ctypes.Structure):
_fields_ = [
(
... | python |
# 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... | python |
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db.models import CharField
from django.db.models.signals import post_save
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.core.mail import EmailMultiAlternatives
from djan... | python |
import numpy as np
class Neurons:
def __init__(self, n_inputs, n_neurons):
self.weights = 1 * np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons)) | python |
import abc
import glob
import logging
import os
import subprocess as sp
from collections import OrderedDict
from enum import Enum
from paprika.utils import get_dict_without_keys
from .simulation import Simulation
logger = logging.getLogger(__name__)
class GROMACS(Simulation, abc.ABC):
"""
A wrapper that ca... | python |
a1 = int(input())
a2 = int(input())
n = int(input())
for p in range(a1, ord(chr(a2 - 1)) + 1):
for i in range(1, (n - 1) + 1):
for j in range(1, (int((n / 2) - 1)) + 1):
if (p % 2 != 0) and (((i + j + p) % 2) != 0):
print(f"{chr(p)}-{i}{j}{p}")
| python |
# Copyright 2020 The Private Cardinality Estimation Framework 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 b... | python |
from gbdxtools.images.worldview import WorldViewImage
from gbdxtools.images.drivers import WorldViewDriver
from gbdxtools.images.util import vector_services_query
from gbdxtools.rda.interface import RDA
rda = RDA()
band_types = {
'MS': 'BGRN',
'Panchromatic': 'PAN',
'Pan': 'PAN',
'pan': 'PAN'
}
class ... | python |
"""
README:
docs/everything-about-prop-delegators.zh.md
"""
# noinspection PyUnresolvedReferences,PyProtectedMember
from typing import _UnionGenericAlias as RealUnionType
from PySide6.QtQml import QQmlProperty
from .typehint import *
from ....qmlside import qmlside
from ....qmlside.qmlside import convert_name_cas... | python |
import time,calendar,os,json,sys,datetime
from requests import get
from subprocess import Popen,PIPE
from math import sqrt,log,exp
from scipy.optimize import minimize
import numpy as np
np.set_printoptions(precision=3,linewidth=120)
def datetoday(x):
t=time.strptime(x+'UTC','%Y-%m-%d%Z')
return calendar.timegm(t)/... | python |
#
# Copyright 2018 Asylo 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 applicable law or agreed to in writi... | python |
"""
Author : Varundev Suresh Babu
Version: 0.1
"""
import rospy
from std_msgs.msg import Float64
steering_publisher = ospy.Publisher("/servo/position", Float64, queue_size = 10)
throttle_publisher = rospy.Publisher("/motor/duty_cycle", Float64, queue_size = 10)
def steering_callback(data):
global steering
st... | python |
# -*- coding: utf-8 -*-
# created by inhzus
from .smms import ImageHost
from .md_parser import parse_md
| python |
def rawify_url(url):
if url.startswith("https://github.com"):
urlparts = url.replace("https://github.com", "", 1).strip('/').split('/') + [None] * 5
ownername, reponame, _, refvalue, *filename_parts = urlparts
filename = '/'.join([p for p in filename_parts if p is not None])
assert o... | python |
"""Raw message parser implementations."""
from twisted.words.protocols.irc import ctcpExtract, parsemsg, X_DELIM
from . import Message
from ..hostmask import Hostmask
class RawMessageParser(object):
"""An implementation of the parsing rules for a specific version of
the IRC protocol.
In most cases, yo... | python |
#-*- coding: utf-8 -*-
from bgesdk.error import APIError
import pytest
import six
def check_result(result):
assert 'result' in result
assert 'count' in result
assert 'next_page' in result
next_page = result['next_page']
assert isinstance(result['result'], list)
assert isinstance(result['coun... | python |
# coding=utf-8
from .email import EmailFromTemplate
def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
"""
Shortcut function for EmailFromTemplate class
@return: None
"""
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_... | python |
import weakref
import uuid
from types import MethodType
from collections import OrderedDict
from Qt import QtGui
from Qt.QtWidgets import QPushButton
from Qt.QtWidgets import QGraphicsProxyWidget
from Qt.QtWidgets import QMenu
from PyFlow.Core.Common import *
from PyFlow.UI.Utils.Settings import *
from PyFlow.Core.No... | python |
import logging
from rest_framework import exceptions
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_user_model
from galaxy.api import serializers
from galaxy.api.views import base_views
from galaxy.main import models
__... | python |
import re
import pandas as pd
from dojo.models import Finding
__author__ = 'Matt Sicker'
class DsopParser:
def __init__(self, file, test):
self._test = test
self._items = []
f = pd.ExcelFile(file)
self.__parse_disa(pd.read_excel(f, sheet_name='OpenSCAP - DISA Compliance', parse_... | python |
from exterminate.Utilities import builtins
from exterminate.Gizoogle import translate
_print = builtins.print
builtins.print = lambda *args, **kwargs: _print(
translate(' '.join([str(x) for x in args])), **kwargs
)
| python |
from builtins import object
import abc
from future.utils import with_metaclass
class Solver(with_metaclass(abc.ABCMeta, object)):
def __init__(self, **kwargs):
self.options = kwargs
if 'verbose' not in self.options:
self.options['verbose'] = False
@abc.abstractmethod
def sol... | python |
# Copyright (c) 2015 Microsoft Corporation
from z3 import *
set_option(auto_config=True)
x = Int('x')
y = Int('y')
f = Function('f', IntSort(), IntSort())
solve(f(f(x)) == x, f(x) == y, x != y)
| python |
"""Capture synthesizer audio for each of a batch of random chords.
By default, prints the number of JACK xruns (buffer overruns or underruns)
produced during the MIDI playback and capture process.
"""
import cProfile
import datetime
import json
import os
import pstats
import time
import numpy as np
import scipy.io.wa... | python |
#swap 4 variables
# swap variable
w=input("enter any nymber")
x=input("enter any nymber")
y=input("enter any number")
z=input("enter any number")
print("w before swap :{}".format(w))
print("x before swap:{}".format(x))
print("y before swap :{}".format(y))
print("z before swap :{}".format(z))
w=w+x+y+z
x=w... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from django.http import HttpResponse
from django.template import Template, RequestContext
from django.shortcuts import render
f... | python |
import UpdateItem as ui
import UpdateChecker as uc
import UpdateFileReader as ufr
import tkinter
from tkinter import messagebox
is_verbose = True
root = tkinter.Tk()
root.withdraw()
userfile = "updateList.txt"
currentReader = ufr.UpdateFileReader(userfile, is_verbose)
while currentReader.getNextItem():
currentItem... | python |
# Modified: 2022-06-02
# Description: Defines the FastAPI app
#
from pathlib import Path
from motor.motor_asyncio import AsyncIOMotorClient
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from controllers import game_controller, player_contro... | python |
'''
Modified run-length encoding.
Modify the result of problem P10 in such a way that if an element
has no duplicates it is simply copied into the result list. Only
elements with duplicates are transferred as (N E) lists.
Example:
* (encode-modified '(a a a a b c c a a d e e e e))
((4 A) B (2 C) (2 A) D (4 E))... | python |
import dash_html_components as html
class Component:
def render(self) -> html.Div:
raise NotImplementedError
| python |
# The MIT License (MIT)
#
# Copyright (c) 2014 Steve Milner
#
# 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, modi... | python |
import smartpy as sp
FA12 = sp.io.import_script_from_url("file:Fa12.py", name="FA12")
"""
Possible states of the swap
"""
class State():
Waiting = 1
Initiated = 2
"""
Swap record -
hashedSecret(bytes): current swap hash
initiator(address): initiators tezos address
initiator_eth_addr(string): ... | python |
with open('Day10 input.txt') as f:
lines = f.readlines()
chunk_dict = {
'(':')',
'[':']',
'{':'}',
'<':'>'
}
score_dict = {
')':3,
']':57,
'}':1197,
'>':25137
}
corrupted = []
score = 0
for line in lines:
chunk = ''
for l in line:
if l in ['(','[','{','<']:
... | python |
#!/usr/bin/python
# encoding: utf-8
import random
import torch
from torch.utils.data import Dataset
from torch.utils.data import sampler
import torchvision.transforms as transforms
import lmdb
import six
import sys
from PIL import Image
import numpy as np
# 关于lmdb数据库使用, 当时对接Python 2.x,所以使用Bytestrings,而不是unicode,
# 所以... | python |
class Occurrence(object):
"""
An Occurrence is an incarnation of a recurring event for a given date.
"""
def __init__(self,event,start,end):
self.event = event
self.start = start
self.end = end
def __unicode__(self):
return "%s to %s" %(self.start, self.end)
de... | python |
# some modules use the old-style import: explicitly include
# the new module when the old one is referenced
hiddenimports = ["email.mime.text", "email.mime.multipart"]
| python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
from xnas.search_space.DARTS.ops import *
from torch.autograd import Variable
def channel_shuffle(x, groups):
batchsize, num_channels, height, width = x.data.size()
channels_per_group = num_channels // groups
# reshape
x ... | python |
# This is just a demo file
print("Hello world")
print("this is update to my previous code") | python |
import os
import asyncio
import sys
from typing import Any, Dict, Union, List # noqa
from tomodachi.watcher import Watcher
def test_watcher_auto_root() -> None:
watcher = Watcher()
assert watcher.root == [os.path.realpath(sys.argv[0].rsplit('/', 1)[0])]
def test_watcher_empty_directory() -> None:
root_... | python |
import tensorflow as tf
import numpy as np
from optimizer import distributed_optimizer
from task_module import pretrain, classifier, pretrain_albert
import tensorflow as tf
try:
from distributed_single_sentence_classification.model_interface import model_zoo
except:
from distributed_single_sentence_classification.m... | python |
# -*- coding: utf-8 -*-
'''test cases for config_loader module'''
import unittest
import os
import shutil
import cray.craylib.config_loader as config_loader
from cray.craylib.generate_manager import GenerateManager
ROOT_DIR = os.path.join(os.path.dirname(__file__), "test_site")
SITE_DIR = os.path.join(os.path.dirnam... | python |
#!/usr/bin/env python3
import sys
import time
import math
def go(l, n, partials):
return (partials[-1] - partials[n]) % 10
def fft(l):
"""Fucked Fourier Transform"""
partials = [0]
sum = 0
for v in l:
sum += v
partials.append(sum)
x = []
for i, y in enumerate(l):
... | python |
import enolib
def test_querying_an_existing_single_line_required_string_comment_from_a_section_produces_the_expected_result():
input = ("> comment\n"
"# section")
output = enolib.parse(input).section('section').required_string_comment()
expected = ("comment")
assert output == expect... | python |
"""
test_finger_pks.py
Copyright 2012 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope ... | python |
import numpy as np
import cv2
# 'uint8' assigns an 8bit unsigned integer to the colour values in the array
pic = np.zeros((512, 512, 3), dtype = 'uint8')
# Draw a rectangle from 0px to 512px
# Magenta colour, not color
colour = (255, 0, 255)
# Circles overview: https://www.khanacademy.org/math/basic-geo/basic-geo-are... | python |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def generateParenthesis(self, n):
if n <= 0:
return []
if n == 1:
return ['()']
res = self.generateParenthesis(n - 1)
ret = set()
for v in res:
for i in range(len(v)):... | python |
from django_codemod.constants import DJANGO_1_9, DJANGO_3_1
from django_codemod.visitors.base import BaseRenameTransformer
class PrettyNameTransformer(BaseRenameTransformer):
"""Replace `django.forms.forms.pretty_name` compatibility import."""
deprecated_in = DJANGO_1_9
removed_in = DJANGO_3_1
rename... | python |
from yahoo import Quote, YahooQuote
stocks = ['AA', 'AXP', 'BA', 'BAC', 'CAT', 'CSCO', 'CVX', 'DD', 'DIS', 'GE', 'HD', 'HPQ', 'IBM', 'INTC', 'JNJ']
stocks += ['JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'PFE', 'PG', 'T', 'TRV', 'UNH', 'UTX', 'VZ', 'WMT', 'XOM']
price = {}
quotes = {}
returns = {}
for s in stocks:
p... | python |
"""Support for control of ElkM1 outputs (relays)."""
from homeassistant.components.switch import SwitchEntity
from . import ElkAttachedEntity, create_elk_entities
from .const import DOMAIN
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Create the Elk-M1 switch platform."""
elk_data =... | python |
import pymongo
import config
from . import connection, db
def create_indexes():
"""
Create mongodb indexes.
"""
# VCF collection indexes
db.vcfs.drop_indexes()
db.vcfs.create_index("name")
db.vcfs.create_index("samples")
db.vcfs.create_index( [ ("filename", pymongo.ASCENDING), ("fi... | python |
#
# Copyright (C) 2018 SecurityCentral Contributors see LICENSE for license
#
"""
This base platform module exports platform related tasks.
"""
from securitycentralplatform.os_detection import platform_detection
class SecurityCentralPlatformTasks(platform_detection("tasks")):
pass
tasks = SecurityCentralPlatfor... | python |
from django import forms
from apps.link.models import Link, Advertise
from apps.post.models import Category, Post
class CategoryAddForm(forms.ModelForm):
class Meta:
model = Category
fields = "__all__"
class CategoryEditForm(forms.ModelForm):
pk = forms.CharField(max_length=100)
class ... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-18 23:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('climate_data', '0006_auto_20160816_1429'),
]
operations = [
migrations.Alter... | python |
import doctest
import unittest
import zeit.cms.testing
def test_suite():
suite = unittest.TestSuite()
suite.addTest(doctest.DocFileSuite(
'content.txt',
package='zeit.cms'
))
suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(
'cleanup.txt',
'cmscontent.txt',
... | python |
# https://stackoverflow.com/questions/31663288/how-do-i-properly-use-connection-pools-in-redis
# settings.py:
import redis
def get_redis_connection():
return redis.StrictRedis(host='localhost', port=6379, db=0)
# task1.py
import settings
connection = settings.get_redis_connection()
def do_something1():
ret... | python |
import base64
import gzip
import io
import json
import re
import struct
from pathlib import Path
from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union
from backend import constants
_here = Path(__file__).parent
with open(_here/'exceptions/enchants.json') as f:
ENCHANT_EXCEPTIONS = json.load(f)
wi... | python |
from timeit import timeit
nTests=10000
print("Each operation performed {} times".format(nTests))
print("")
print("Custom Quaternion")
print("")
importQuatVec = '''
from MAPLEAF.Motion import Quaternion
from MAPLEAF.Motion import Vector
v1 = Vector(1, 1, 2)
'''
# Test Quaternion speed (init)
print("Initializing Quat... | python |
# TI & TA
from pyti.smoothed_moving_average import smoothed_moving_average as pyti_smmoothed_ma
from pyti.simple_moving_average import simple_moving_average as pyti_sma
from pyti.bollinger_bands import lower_bollinger_band as pyti_lbb
from pyti.bollinger_bands import upper_bollinger_band as pyti_ubb
from pyti.accumula... | python |
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Tests for LinearRegionVisual
All images are of size (100,100) to keep a small file size
"""
import numpy as np
from vispy.scene import visuals
from vispy.... | python |
import numpy as np
from heapq import heappush, heappop
from dataclasses import dataclass, field
import os
@dataclass(order=True)
class PosItem:
priority: int
pos: tuple[int, int] = field(compare=False)
path = os.path.join(os.path.dirname(__file__), "input.txt")
def find_path(arr):
pq = []
visited ... | python |
from selenium import webdriver
browser = webdriver.Firefox(executable_path=r"C:\Windows\geckodriver.exe")
browser.get("https://github.com")
browser.maximize_window()
browser.implicitly_wait(20)
sign_in = browser.find_element_by_link_text("Sign in")
sign_in.click()
user_name = browser.find_element_by_id(... | python |
import unittest
import Models
class BasicTestMethods(unittest.TestCase):
def test_asdf(self):
self.assertEqual(Models.asdf(), "asdf", 'nah')
self.assertNotEqual(Models.asdf(), "asdf1", 'nah')
#self.assertEqual(asdf(), "asdf1", 'nah')
if __name__ == '__main__':
unittest.main()
| python |
#!/usr/bin/env python
"""AVIM build configuration"""
from os import path
from datetime import date
from build import BuildConfig
# Type of build to produce.
CONFIG = BuildConfig.RELEASE
# Incremented version number.
# See <https://developer.mozilla.org/en-US/docs/Toolkit_version_format>.
VERSION = (5, 8, 2)
# Build... | python |
import sys
sys.path.append('../src/')
print(sys.path)
import Histograms
import unittest
import numpy
import time
class MyTestCase(unittest.TestCase):
def setUp(self):
pass
def test_learnSingleton(self):
m = Histograms.Histograms({
"histograms": ["test"]
, "AllowLimi... | python |
"""User details and sex of patient added
Revision ID: 7d4bab0acebb
Revises: b4bb7697ace6
Create Date: 2017-09-14 14:53:07.958616
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7d4bab0acebb'
down_revision = 'b4bb7697ace6'
branch_labels = None
depends_on = None... | python |
"""
Author: Justin Cappos
Start date: October 9th, 2009
Purpose: A simple library that serializes and deserializes built-in repy types.
This includes strings, integers, floats, booleans, None, complex, tuples,
lists, sets, frozensets, and dictionaries.
There are no plans for including objects.
Note: that all item... | python |
"""
Author: William Gabriel Carreras Oropesa
Date: April 19, 2020, Neuqué, Argentina
module body: This module has implemented a series of functions and objects
that will be useful when solving the problem of the N bodies.
"""
# necessary modules
import numpy as np
from copy import copy
class body(object):
... | python |
import logging
import multiprocessing
import unicodedata
from argparse import Namespace
from contextlib import closing
from itertools import chain, repeat
from multiprocessing.pool import Pool
from tqdm import tqdm
from transformers.tokenization_roberta import RobertaTokenizer
logger = logging.getLogger(__name__)
c... | python |
name = input("Hello! What's your name? ")
print('Nice to meet you \033[31m{}\033[m!'.format(name))
| python |
"""
This file handles Reservation related HTTP request.
"""
from flask import request
from flask_restplus import Resource
from flask_jwt_extended import jwt_required
from flask_jwt_extended.exceptions import NoAuthorizationError,InvalidHeaderError,RevokedTokenError
from jwt import ExpiredSignatureError, InvalidTokenErr... | python |
from wtforms import Form, StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email
from flask_wtf import FlaskForm
class RegistrationForm(FlaskForm):
email = StringField(
'Email', [DataRequired(), Email(), Length(min=6, max=36)])
username = Strin... | python |
# !/usr/bin/env python
# coding=utf-8
"""
Calcs for HW3
"""
from __future__ import print_function
import sys
import numpy as np
from common import GOOD_RET, R_J, temp_c_to_k, k_at_new_temp, R_ATM, make_fig
__author__ = 'hbmayes'
def pfr_design_eq(x_out, x_in, vol, nuo, k):
"""
PFR design eq for HW3 problem ... | python |
'''Wrapper for nviz.h
Generated with:
./ctypesgen.py --cpp gcc -E -I/Applications/GRASS-7.8.app/Contents/Resources/include -D_Nullable= -I/Users/cmbarton/grass_source/grass-7.8.3/dist.x86_64-apple-darwin18.7.0/include -I/Users/cmbarton/grass_source/grass-7.8.3/dist.x86_64-apple-darwin18.7.0/include -D__GLIBC_HAVE... | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 12:02:28 2021
@author: Clau
"""
'''
Paper: Energy sufficiency (SDEWES LA 2022)
User: School B - LOWLANDS
'''
from core import User, np
User_list = []
#Definig users
SB = User("School type B", 1)
User_list.append(SB)
#Appliances
SB_indoor_bulb = SB.Appliance(SB,12... | python |
# encoding: UTF-8
#
# Copyright (c) 2015 Facility for Rare Isotope Beams
#
"""
Lattice Model application package.
"""
| python |
import fnmatch
import os
def locate(pattern, root=os.getcwd()):
for path, dirs, files in os.walk(root):
for filename in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, pattern)]:
yield filename
| python |
# -*- coding: utf-8 -*-
# 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/licenses/LICENSE-2.0
#
# Unless requ... | python |
import pytest
from beagle.nodes import File, Process
from beagle.transformers.evtx_transformer import WinEVTXTransformer
@pytest.fixture
def transformer() -> WinEVTXTransformer:
return WinEVTXTransformer(None)
def test_process_creation(transformer):
input_event = {
"provider_name": "Microsoft-Windo... | python |
# Exercício 2: Para exercitar nossa capacidade de abstração, vamos modelar algumas partes de um software de geometria. Como poderíamos modelar um objeto retângulo?
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
def area(self):
pass
de... | python |
import os
import matplotlib
from tqdm import tqdm
import numpy as np
from model import FasterRCNNVGG16
from trainer import FasterRCNNTrainer
from utils.config import opt
import data.dataset
import data.util
import torch
from torch.autograd import Variable
from torch.utils import data as data_
import torchvision.transfo... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.