content stringlengths 5 1.05M |
|---|
import time
from multiprocessing import Queue
from queue import Full
import numpy as np
from .sampler import Sampler
class FakeSampler(Sampler):
def __init__(self,
instance: np.ndarray,
sample_queue: Queue,
num_of_samples: int = 1000):
super(FakeSample... |
# Copyright (c) 2013 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
import os.path as P
def relative_path(this_file , rel_path):
return P.join(P.dirname(this_file) , rel_path) |
import pytest
from qualipy.filters import *
PATTERN = 'tests/images/pattern.jpg'
NON_PATTERN = 'tests/images/lama.jpg'
def test_recognizes_pattern():
assert Pattern().predict(PATTERN)
def test_doesnt_recognize_normal_image():
assert not Pattern().predict(NON_PATTERN)
def test_setting_threshold():
a... |
from . import backup
import logging
from .config import DropboxOfflineBackupConfig
def start():
logging.getLogger('').setLevel(logging.DEBUG)
console = logging.StreamHandler()
file_handler = logging.FileHandler(DropboxOfflineBackupConfig().config['DropboxBackup']['LogFile'])
formatter = logging.Formatt... |
#! /usr/bin/python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
import os
import re
import time
import commonl.testing
import tcfl.tc
srcdir = os.path.dirname(__file__)
ttbd = commonl.testing.test_ttbd(
config_files = [
# strip to remove the compiled/optimized versi... |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/FamilyMemberHistory
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""
import io
import json
import os
import unittest
import pytest
from .. import familymemberhistory
from ..fhirdate import FHIR... |
# -*- coding: utf-8 -*-
# Time : 2021/7/25 13:59
# Author : QIN2DIM
# Github : https://github.com/QIN2DIM
# Description:
import json
import os
from datetime import datetime
from bs4 import BeautifulSoup
from selenium.common.exceptions import (
StaleElementReferenceException,
WebDriverException,
... |
import stweet as st
def test_return_tweets_objects():
phrase = '#koronawirus'
search_tweets_task = st.SearchTweetsTask(
all_words=phrase,
tweets_count=200
)
tweets_collector = st.CollectorTweetOutput()
result = st.TweetSearchRunner(
search_tweets_task=search_tweets_task,
... |
import lmfit
import numpy as np
from uncertainties import ufloat
from scipy.stats import sem
from collections import OrderedDict
from pycqed.analysis import fitting_models as fit_mods
from pycqed.analysis import analysis_toolbox as a_tools
import pycqed.analysis_v2.base_analysis as ba
from pycqed.analysis.tools.plottin... |
def zk_demo(cfg,V,F,ZMvtk) : #function max_abs_diff = demo( V,F,ZMvtk )
#
num_vertices = 3 # num_vertices = 3;
num_facets = cfg.size(F,0) #! ... |
from django.urls import path
from . import api_views, views
urlpatterns = [
path('', views.firework_home, name='fireworks-home'),
path('add/', views.add_firework, name='fireworks-add'),
path('categories', views.category, name='fireworks-categories'),
path('category/<slug:category_slug>/', views.catego... |
from pydantic import BaseModel
from starlette.requests import Request
from fastapi.security.base import SecurityBase
from fastapi.security.utils import get_authorization_scheme_param
from typing import Optional
from starlette.status import HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED
from fastapi.exceptions import HTTPE... |
print(1)<caret> |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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, either version 3 of the License, or
(at your option) any later version.
CVXPY is distributed i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import torch
from torchknickknacks import metrics
x1 = torch.rand(100,)
x2 = torch.rand(100,)
r = metrics.pearson_coeff(x1, x2)
x = torch.rand(100, 30)
r_pairs = metrics.pearson_coeff_pairs(x)
|
# Based off of https://github.com/getninjas/celery-executor/
#
# Apache Software License 2.0
#
# Copyright (c) 2018, Alan Justino da Silva
#
# 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
#
# ... |
import os
import sys
import json
from pathlib import Path
import shutil
import argparse
from wikiutils import split_wiki, sample_docs, cleanup_paths, save_stats
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--lang", required=True, help="language of the wiki-dump to download / preprocess", type=str)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import uuidfield.fields
class Migration(migrations.Migration):
dependencies = [
('schedule', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_US... |
from .base import Dashboard |
from django import forms
from django.contrib import messages
class InputForm(forms.Form):
query = forms.CharField(max_length=200) |
#!/usr/bin/python
import base64
import binascii
# CONSTANTS
WORDLISTFILE = r'OSPD4.txt'
SET1CH4INPUTFILE = r'4.txt'
SET1CH6INPUTFILE = r'6.txt'
# Functions
def hextobase64(hexstring):
bin = binascii.unhexlify(hexstring)
return base64.b64encode(bin).decode()
def xor(binary1, binary2):
return ''.join(chr(ord(a) ^... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import unittest
from mock import mock
from conans.client.tools.oss import detected_architecture
class DetectedArchitectureTest(unittest.TestCase):
def test_various(self):
# x86
with mock.patch... |
import pytest
import shutil
from accident_prediction_montreal.weather import get_weather_station_id_df
from accident_prediction_montreal.utils import init_spark
@pytest.fixture(scope='session')
def spark():
return init_spark()
def test_get_weather_station_id_df(spark):
acc_sample = spark.read.parquet('test... |
# -*- coding: utf-8 -*-
import sys
import argparse
from kits.parse_articles import parse_articles
from config.conf import conf
from config.conf import enviroment
from kits.log import get_logger
def initialize():
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--env", action="store", dest="env... |
#!/usr/bin/env python
# encoding: utf-8
# PYTHON_ARGCOMPLETE_OK
# from __future__ imports must occur at the beginning of the file
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from .bypy import main
if __name__ == "__main__":
main()
# vim: tabstop=4 n... |
"""
Define a new function using the @qgsfunction decorator.
The function accept the following parameters
:param [any]: Define any parameters you want to pass to your function before
the following arguments.
:param feature: The current feature
:param parent: The QgsExpression object
:param context: If th... |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from datetime import datetime
class CommonRealDateUtils:
... |
import logging
from .utils import get_logging_level
class Client(object):
""" This object autheticates the account to the api """
def __init__(self, auth, **kwargs):
"""
Initializes Client object.
Args:
auth (tuple): Authentication object
api (str): Api endpat... |
from django.shortcuts import render
from .models import Salas,Rentals
from django.db.models import Q
from django.shortcuts import get_object_or_404
from .forms import RentalForm
def salas_home_view(request,*args,**kargs):
hora_inicial = request.GET.get('inicio',None)
hora_fim = request.GET.g... |
from typing import MutableSequence
class WrappingList(MutableSequence):
def __init__(self, l=[]):
if type(l) is not list:
raise ValueError()
self._inner_list = l
def __len__(self):
return len(self._inner_list)
def __delitem__(self, index):
index = self.__va... |
import numpy as np
from scipy.special import erf
class GELU:
def __call__(self, x: np.ndarray, approximate: bool = True) -> np.ndarray:
if approximate:
return x * 0.5 * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * np.power(x, 3))))
return x * 0.5 * (1.0 + erf(x / np.sqrt(2.0)))
... |
import sys
import os
import pty
import subprocess
import shlex
import selectors
import multiprocessing as mp
def run(cmd, input_lines=[]):
"""Run an interactive given command with input and capture all IO.
Parameters
----------
cmd: str
The command to run
input_lines: list
List ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 3 14:52:19 2017
@author: Falaize
"""
from __future__ import absolute_import
import sys
from PyQt5.QtWidgets import QApplication
from widgets import PyphsGui
import os
path = os.path.join('pyphs_gui', 'tests', 'rlc.net')
os.chdir('..')
def runn... |
# Copyright 2014 Baidu, 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 writing, softwa... |
#*******************************************************************************
#
# Filename : EDMNaming.py
# Description : Getting the reduced name of a dataset and others
# Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
#
#*******************************************************************... |
# Copyright 2019 Extreme Networks, 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 i... |
# -*- coding: utf-8 -*-
from rest_framework import viewsets, mixins
from .models import Pet, Birth, Breed
from .serializers import PetSerializer, BreedSerializer, BirthSerializer
class PetViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
queryset ... |
""" Tests Input.__init__() and classes in input_classes.py
Note that this is more of a regression test than a unit test.
Compares with previously computed results."""
import os
import numpy as np
import pytest
import astropy.units as u
from astropy.time import Time
from nexoclom.solarsystem import SSObject
from nexoclo... |
import argparse
import os
import numpy as np
import torch
from mmcv.runner import Sequential
from tensorflow.python.training import py_checkpoint_reader
from mmcls.models.backbones.efficientnet import EfficientNet
def tf2pth(v):
if v.ndim == 4:
return np.ascontiguousarray(v.transpose(3, 2, 0, 1))
el... |
import requests
import re
from bs4 import BeautifulSoup
import pandas as pd
import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage
import bs4 as bs
import urllib.request
import os
import datetime
path_of_brandwise = 'C:\\LavaWebScraper\\BrandWiseF... |
#!/usr/bin/env python3
import argparse
import sys
import os
import stat
import httplib2
from oauth2client.service_account import ServiceAccountCredentials
import apiclient
SCOPE = 'https://www.googleapis.com/auth/androidpublisher'
SCRIPT_VERSION = '2021-08-22'
def print_info():
print('publisher.py: %s' % SCRIPT_V... |
"""Base register module"""
def pad_zeroes(addr, n_zeroes):
"""Padds the address with zeroes"""
if len(addr) < n_zeroes:
return pad_zeroes("0" + addr, n_zeroes)
return addr
def int_addr(addr):
"""Gets the integer representation of an address"""
return int(addr[1:])
def next_addr(addr, i):
... |
from . import views
from django.urls import path
urlpatterns = [
path('', views.BlogHome.as_view(), name='blog'),
]
|
# Time: O(n)
# Space: O(1)
# Two pointers solution
class Solution(object):
def numSubarraysWithSum(self, A, S):
"""
:type A: List[int]
:type S: int
:rtype: int
"""
result = 0
left, right, sum_left, sum_right = 0, 0, 0, 0
for i, a in enum... |
from pytest import raises
import pandas as pd
from agape.mapping import dictify, gene2symbol
class TestDictify(object):
def setup_method(self):
self.df = pd.DataFrame({"A": [0, 1],
"B": ["x", "y"]})
self.key = "A"
self.value = "B"
def test_returns_dict(... |
from . import api
from . import core
from .core import Stream, NameSpace, DataFeed
|
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# Th... |
"""Test Refiners can be constructed with various configurations"""
import os
from copy import deepcopy
import pytest
from dxtbx.model.experiment_list import ExperimentListFactory
from libtbx import phil
from dials.algorithms.refinement import DialsRefineConfigError, RefinerFactory
from dials.algorithms.refinement.... |
import pytest
from geonotebook.kernel import Remote
@pytest.fixture
def remote(mocker):
protocols = [{'procedure': 'no_args',
'required': [],
'optional': []},
{'procedure': 'required_only',
'required': [{"key": "a"}, {"key": "b"}],
... |
import serial
import time
import datetime
import numpy as np
import csv
from pathlib import Path
import random as random
myFile = Path('BigHouse.csv')
if not myFile.exists():
with open('BigHouse.csv','a', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=';',
quotechar='|', quoting=csv... |
import curses
from itertools import islice, izip
from .pad_display_manager import PadDisplayManager
from .rate import get_rate_string
SESSIONS_HEADER = "| Idx | Type | Details | RX Rate | TX Rate | Activity Time "
SESSIONS_BORDER = "+-----+------+-------------... |
import binascii
import collections
import datetime
import hashlib
from urllib.parse import quote
from google.oauth2 import service_account
def generate_signed_url(
service_account_file,
bucket_name,
object_name,
expiration,
http_method="GET",
query_parameters=None,
headers=None,
):
es... |
import unittest
from number_of_islands.solution import Solution
class TestSolution(unittest.TestCase):
def test_solution(self):
self.assertEqual(0, Solution().num_islands(
None))
self.assertEqual(0, Solution().num_islands(
[[]]))
self.assertEqual(1, Solution().num... |
from subprocess import PIPE, run
my_command = "["ipconfig", "/all"]"
result = run(my_command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.stdout, result.stderr)
input("Press Enter to finish...") |
import connexion
#app = connexion.FlaskApp(__name__)
app = connexion.AioHttpApp(__name__)
app.add_api("swagger/openapi.yaml")
application = app.app |
import time
import board
import displayio
import adafruit_ssd1325
displayio.release_displays()
spi = board.SPI()
oled_cs = board.D5
oled_dc = board.D6
oled_reset = board.D9
display_bus = displayio.FourWire(
spi, command=oled_dc, chip_select=oled_cs, reset=oled_reset, baudrate=1000000
)
time.sleep(... |
from yahoofinancials import YahooFinancials
import pandas as pd
import datetime as dt
def get_downloader(start_date,
end_date,
granularity='daily',):
"""returns a downloader closure for oanda
:param start_date: the first day on which dat are downloaded
:param end_date: the la... |
# Python script for generatign panda_drv.h from *DRV entries in registers
# configuration file.
from __future__ import print_function
import sys
from parse_indent import parse_register_file
registers = parse_register_file(sys.argv[1])
base, fields = registers['*DRV']
base = int(base)
print('''\
/* Register definit... |
import setuptools
setuptools.setup(
name="cinemasci",
version="0.1",
author="David H. Rogers",
author_email="dhr@lanl.gov",
description="Tools for the Cinema scientific toolset.",
url="https://github.com/cinemascience",
packages=["cinemasci",
"cinemasci.cdb",
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 16:34:40 2020
@author: skyjones
"""
import os
import re
import pandas as pd
from glob import glob
import nibabel as nib
import numpy as np
import shutil
out_csv = '/Users/manusdonahue/Documents/Sky/volume_testing/volume_comparisons_fastonly.... |
#!/usr/bin/env python
"""
===========
{PROG}
===========
----------------------------------------------------
Compute exponentially weighted moving average
----------------------------------------------------
:Author: skipm@trdlnk.com
:Date: 2013-03-15
:Copyright: TradeLink LLC 2013
:Version: 0.1
:Manual section: 1
... |
import os
import sys
import time
import WareHouse
import ConfigLoader
import PythonSheep.IOSheep.PrintFormat as PrintSheep
import PythonSheep.IOSheep.InputFormat as InputSheep
from Commands.HelpDocument import HelpDocument
from Commands.ReloadConfig import ReloadConfig
from Commands.OpenConfig import OpenConfig
# 初... |
from movelister.core.context import Context
def reopenCurrentFile():
"""
Reopens current file. All variables made before this will be
invalid. Make sure to initialize them too.
"""
frame = Context.getFrame()
frame.loadComponentFromURL(getUrl(), "_self", 0, ())
def getUrl():
"""
Retur... |
#!/usr/bin/env python3
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import sys
import os
import redis
from Bio import SeqIO
def main(argv):
# Put stuff in JSON config file
r=redis.Redis()
batch = 1000;
itera = 0
checkID = ""
pipeline=r.pipeline()
handle = open( argv[0], "r")
for record in SeqIO.parse(handle, "fasta") :
pipeline.set( str( record.id ), str( ... |
from peewee import CharField, IntegerField
from core.db.db import BaseModel
class Materials(BaseModel):
name = CharField(unique=True)
type_id = IntegerField()
class Meta:
table_name = 'materials'
|
from keras import backend
from keras.constraints import Constraint
from keras.initializers import RandomNormal
from keras.layers import Dense, Conv2D, Conv2DTranspose, BatchNormalization, Activation, Reshape, LeakyReLU, \
Dropout, Flatten
from keras.models import Sequential, load_model
from wasserstein import wass... |
import events
import io
import json
import os
from executors.python import run as python_run
from executors.workflow import run as workflow_run
from . import utils
from girder_worker.utils import JobStatus, StateTransitionException
from girder_worker import config, PACKAGE_DIR
# Maps task modes to their implementati... |
import os
from urllib.parse import urlparse
from boxsdk import OAuth2, Client
from django.conf import settings
from swag_auth.base import BaseSwaggerDownloader, BaseAPIConnector
from swag_auth.oauth2.views import CustomOAuth2Adapter
class BoxAPIConnector(BaseAPIConnector):
def __init__(self, token):
sup... |
from typing import List, Optional, Dict, Iterable
from fhirclient.models.codeableconcept import CodeableConcept
from fhirclient.models.encounter import Encounter
import fhirclient.models.patient as fhir_patient
from fhirclient.models.fhirreference import FHIRReference
from transmart_loader.loader_exception import Load... |
from datetime import datetime
import django
import factory
from django.utils import timezone
from api.cases.enums import CaseTypeEnum
from api.compliance.enums import ComplianceVisitTypes, ComplianceRiskValues
from api.compliance.models import OpenLicenceReturns, ComplianceSiteCase, CompliancePerson, ComplianceVisitC... |
#!/usr/bin/env python3
"""某青空文庫の実験用コード。
参考:
<https://github.com/ozt-ca/tjo.hatenablog.samples/tree/master/r_samples/public_lib/jp/aozora>
<https://tjo.hatenablog.com/entry/2019/05/31/190000>
AP: 0.945
Prec: 0.88742
Rec: 0.86312
実行結果:
```
[INFO ] Accuracy: 0.892 (Error: 0.108)
[INFO ] F1-macro: 0.894
[INFO ] ... |
import FWCore.ParameterSet.Config as cms
from SimG4Core.Configuration.SimG4Core_cff import *
g4SimHits.Watchers = cms.VPSet(cms.PSet(
MaterialBudgetVolume = cms.PSet(
lvNames = cms.vstring('BEAM', 'BEAM1', 'BEAM2', 'BEAM3', 'BEAM4', 'Tracker', 'ECAL', 'HCal', 'VCAL', 'MGNT', 'MUON', 'OQUA', 'CALOEC'),
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2013, David Stygstra <david.stygstra@gmail.com>
# 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_v... |
import datetime
import struct
import time
from sakuraio.hardware.commands import CommandMixins, CMD_ERROR_NONE
from sakuraio.hardware.exceptions import CommandError, ParityError
SAKURAIO_SLAVE_ADDR = 0x4f
def calc_parity(values):
parity = 0x00
for value in values:
parity ^= value
return parity
... |
from django.apps import AppConfig
class RidersportalAppConfig(AppConfig):
name = 'ridersportal_app'
|
#!/usr/bin/env python
import os, imp
def main(args):
if len(args) == 0:
print "Usage: python launch.py [args...]"
return
launch_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"auth_server.py")
auth_server = imp.load_source("auth_server", launch_path)
... |
"""Given two dictionaries for weights, find pairs of matching weights"""
import argparse
import io
import pathlib
import sys
import numpy as np
def find_matching_weights(filepath0, filepath1):
dict0 = np.load(io.BytesIO(filepath0.read_bytes()), allow_pickle=True).item()
dict1 = np.load(io.BytesIO(filepath1.r... |
prestamo_bolivares = float(input(" prestamo de Bolivares: "))
intereses_pagados = float(input("porcentaje de los intereses pagados: "))
tasa_interes_anual = round(((intereses_pagados * 100) / (prestamo_bolivares * 4)), 10)
print(f"El porcentaje de cobro anual por el prestamo de {prestamo_bolivares:,} Bolivares durant... |
import os
from os.path import join
from nip.config import defaults
def get_basename():
return os.path.basename(os.getcwd().rstrip('/'))
def directory_is_empty(target_dir):
if os.path.exists(target_dir):
for _, folders, files in os.walk(target_dir):
return False if (files or folders) els... |
# simple script to delete duplicated files based on scene id (NOTE MUST MANUALLY ADJUST
# file_name SLCING DEPENDING ON PRODUCT!!!)
# Author: Arthur Elmes, 2020-02-25
import os, glob, sys
def main(wkdir, product):
print("Deleting duplicates in: " + str(wkdir) + " for product: " + str(product))
if product == ... |
"""
Utility functions
"""
import logging
import os
import sys
def get_func(func_name, module_pathname):
"""
Get function from module
:param func_name: function name
:param module_pathname: pathname to module
:return:
"""
if sys.version_info[0] >= 3:
if sys.version_info[1] >= 6:
... |
# 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 dynamixel_sdk as sdk
from typing import Union, Tuple, Any
from enum import Enum
from .connection import Connection
from .register import Instruction, AX, MX
from .util import validate_response
class MotorType(Enum):
AX = 1
MX = 2
class Motor:
def __init__(
self, conn: Connection, id: int... |
import sys
import os
import time
import cPickle as pickle
import tensorflow as tf
import numpy as np
import utils.reader as reader
import models.net as net
import utils.evaluation as eva
#for douban
#import utils.douban_evaluation as eva
import bin.train_and_evaluate as train
import bin.test_and_evaluate as test
# ... |
# -*- coding: utf-8 -*-
from importlib import import_module
from wsgiref.util import FileWrapper
from django.conf import settings
from django.http import HttpResponse, StreamingHttpResponse
from django.utils.encoding import smart_text, smart_bytes
class DjangoDownloadHttpResponse(StreamingHttpResponse):
... |
from ..IPacket import IPacket
from ..DataStructures.GamePoint import GamePoint
class UseItem(IPacket):
"Sent by client to use an item"
def __init__(self):
self.time = 0
self.slotID = 0
self.init = GamePoint(0,0)
self.target = GamePoint(0,0)
self.projectileID = 0
... |
import json
import sqlite3
with open('../data_retrieval/acm/acm_paper_doi.json') as data_file:
data = json.load(data_file)
connection = sqlite3.connect('scholarDB.db')
with connection:
cursor = connection.cursor()
count = 0
for row in data:
journal_category = row['journal category']
a... |
import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init
from mmedit.models.common import GCAModule
from mmedit.models.registry import COMPONENTS
from ..encoders.resnet_enc import BasicBlock
class BasicBlockDec(BasicBlock):
"""Basic residual block for decoder.
For decoder, we use ConvTranspose2d... |
from http import HTTPStatus
from flask import Blueprint, request
from injector import inject
from edu_loan.config.dependencies import Application
from edu_loan.domain.event_flow_service import EventFlowService, EventFlowServiceException
from edu_loan.domain.serializers import SerializerException, EventFlowSerializer... |
print('Hello, Word!')
print()
print(1 + 2)
print(7 * 6)
print()
print("The end", "or is it?", "keep watching to learn more about Python 3") |
import typing
import pytest
from terraform import schemas, unknowns
@pytest.mark.parametrize(
"schema,value,expected_value",
[
pytest.param(schemas.Block(), None, None, id="empty",),
pytest.param(
schemas.Block(
attributes={
"foo": schemas.Attr... |
import os
from setuptools import setup, find_packages
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='... |
'''
This file is a part of Test Mile Arjuna
Copyright 2018 Test Mile Software Testing Pvt Ltd
Website: www.TestMile.com
Email: support [at] testmile.com
Creator: Rahul Verma
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 ... |
n = int(input("INSIRA O NUMERO DE TERMOS DA PA: "))
pt = int(input("INSIRA O 1° TERMO DA PA: "))
r = int(input("INSIRA A RAZÃO DA PA: "))
print("*"*40)
print("OS TERMOS DA PA SÃO")
calc = pt + ( n - 1 )*r
for i in range(pt, calc+r, r):
print(f'{i}',end='->')
soma = n * (pt + calc) // 2
print()
print(">A SOMA DOS TE... |
from typing import Any, Dict
import argparse
import logging
import pathlib
import random
import sys
from pprint import pprint
import pandas as pd
import torch as th
import numpy as np
try:
from icecream import install # noqa
install()
except ImportError: # Graceful fallback if IceCream isn't installed.
... |
# pylint: disable=invalid-name,missing-docstring,protected-access
# Generated by Django 2.2.13 on 2020-06-26 20:41
from django.db import migrations
from django.db import models
import leaderboard.models
class Migration(migrations.Migration):
dependencies = [
('leaderboard', '0014_submission_s... |
import config
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.optimizers import Adam
from sklearn.preprocessing import LabelBinarizer
import numpy as np
cfg = config.Config... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Load cookies from FireFox, to be used by Requests etc.
import sqlite3
from sqlite3 import Error
from sys import platform
import os
def _getFireFoxCookieFile(profileName="default"):
"""Locate FireFox cookies.sqlite file. Supply optional profile name"""
ffbasedir = No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.