content stringlengths 5 1.05M |
|---|
#! /usr/bin/env python
# coding=utf-8
#
# Copyright © 2017 Gael Lederrey <gael.lederrey@epfl.ch>
#
# Distributed under terms of the MIT license.
#
# Based on the code of Ulf Astrom (http://www.happyponyland.net)
from camogen.helpers import *
class Polygon:
"""
Set of vertices defining a surface
(Last ver... |
VERSION = (0, 2, 0)
|
class Solution:
def scoreOfParentheses(self, S: str) -> int:
stack, score = [], 0
for s in S:
if s == '(':
stack.append("(")
else:
last = stack[-1]
if last == '(':
stack.pop()
sta... |
#!/usr/bin/env python2
# coding: utf-8
# Original code: Aditya K Sood - SecNiche Security Labs (c) 2013
# Updated/Bugfixes by: Glenn 'devalias' Grant - http://devalias.net/
# Refactorisation by: Borja R - https://www.libcrack.so/
import os
import re
import sys
import logging
import urllib2
import httplib
import reques... |
n = int(input())
al = list(map(int, input().split()))
ave = sum(al)/n
ans = 0
ans_diff = abs(ave - al[0])
for i, a in enumerate(al):
if abs(ave-a) < ans_diff:
ans = i
ans_diff = abs(ave-a)
print(ans)
|
import argparse
import socket
parser = argparse.ArgumentParser(description='Task 1 Client')
parser.add_argument('--host', help='Hostname/IP to connect', default='127.0.0.1')
parser.add_argument('--port', help='Port to connect', default=1337)
parser.add_argument('-b', '--buffer', help='Connection buffer size', type=int... |
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.layouts import row
from bokeh.models import HoverTool
from bokeh.models import LinearColorMapper
from bokeh.models import Slider
from bokeh.plotting import figure
from bokeh.tile_providers import STAMEN_TERRAIN_RETINA
from bokeh.models.widgets impo... |
import string
from typing import Union
from sc2 import UnitTypeId
class UnitCount:
def __init__(self, enemy_type: UnitTypeId, count: Union[int, float]):
assert isinstance(enemy_type, UnitTypeId)
assert isinstance(count, int) or isinstance(count, float)
self.count = count
self.ene... |
import json
import itertools
from typing import (
Any,
)
from substratum.types import (
RPCEndpoint,
RPCResponse,
)
from substratum.utils import (
to_bytes,
to_text,
)
class BaseProvider:
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
raise NotImplementedErro... |
from os import path
import sys
import subprocess
from typing import List
from ._make_experiment_csv import make_experiment_csv
def write_experiment(
db_credentials:str, output_folder:str, image_ids,
spot_channels:List[str], stain_channels:List[str] = None,
... |
from setuptools import setup, find_packages
version = open("VERSION").read().strip()
with open("requirements.txt", encoding="utf8") as handle:
reqs = handle.readlines()
with open("requirements-dev.txt", encoding="utf8") as handle:
dev_reqs = handle.readlines()
setup(
name="wgh-ner",
version=version,... |
# -*- coding: utf-8 -*-
#
# © 2015-2016 Krux Digital, Inc.
#
#
# Standard libraries
#
from functools import wraps
# Declare the baseboto class a metaclass to avoid
# it being used directly
from abc import ABCMeta, abstractmethod
import os
#
# Third party libraries
#
# For differences between version2 & version3, ... |
from keras.models import load_model
import numpy as np
from keras.optimizers import Adam
from keras.models import Model
from keras.layers import Dense, Conv2D, Conv3D, BatchNormalization, Activation, \
Concatenate, AvgPool2D, Input, MaxPool2D, UpSampling2D, Add, \
ZeroPadding2D, ZeroPadding3D, Lambda, Resha... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
# coding=utf-8
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
class DateFormats(object):
Full = '%m/%d/%Y %H:%M:%S.%f'
def epoch_seconds(dt):
return (dt - epoch).total_seconds()
def formated(dt, format_str=DateFormats.Full):
return dt.strftime(format_str)
if __name__ == '__main__':
... |
TRUE = 1 # ACK, YES
FALSE = 0 # NAK, NO
class cursor (object):
def __init__ (me, height, width, show=FALSE):
me.height = height
me.width = width
me.show = show
me.reset()
def reset (me):
me.row = 0
me.col = 0
def line_feed (me):
'''
return... |
# -*- coding: utf-8 -*-
"""
Count the number of valid sketches in Sketchy database.
Created on Wed Dec 2 10:25:18 2020
@author: lbechberger
"""
import argparse, csv
parser = argparse.ArgumentParser(description='Scan Sketchy labels')
parser.add_argument('input_file', help = 'csv file containing the Sketchy info')
... |
import argparse
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
import ray
from ray import tune
from ray.experimental.sgd.tf.tf_trainer import TFTrainer, TFTrainable
NUM_TRAIN_SAMPLES = 1000
NUM_TEST_SAMPLES = 400
def create_config(... |
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2019 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import debug
from tech import drc
import design
... |
#
# GETBULK Command Generator
#
# Send a series of SNMP GETBULK requests
# with SNMPv2c, community 'public'
# over IPv4/UDP
# to an Agent at 195.218.195.228:161
# with values non-repeaters = 0, max-repetitions = 25
# for two OIDs in tuple form
# stop on end-of-mib condition for both OIDs
#
# Thi... |
from lm_eval import tasks
from pytablewriter import MarkdownTableWriter
writer = MarkdownTableWriter()
writer.headers = ["Task Name", "Train", "Val", "Test", "Metrics"]
values = []
def chk(tf):
if tf:
return '✓'
else:
return ' '
for tname, Task in tasks.TASK_REGISTRY.items():
task = Task... |
from wataru.commands.models.base import CommandBase
from wataru.logging import getLogger
import code
logger = getLogger(__name__)
class Console(CommandBase):
def apply_arguments(self, parser):
parser.add_argument('--config-path', action='store', dest='configpath', default='')
def execute(self, names... |
from botocore.model import ServiceModel
from nifcloud import serialize
class TestRdbSerializer(object):
rdb_model_metadata = {
"apiVersion": "2013-05-15N2013-12-16",
"endpointPrefix": "rdb",
"protocol": "rdb",
"serviceAbbreviation": "rdb",
"serviceFullName": "NIFCLOUD RDB"... |
import numpy as np
import random
import networkx as nx
import more_itertools
import matplotlib.pyplot as plt
import geopy.distance as geodesic_dist
from models.distance import get_dist_func
import argparse
def get_fitness(solution_edgelist):
"""
Compute fitness value for solution given by edge list.
Args... |
"""
@file
@brief Helpers for pip
Some links to look:
* `installing_python_packages_programatically.py <https://gist.github.com/rwilcox/755524>`_
* `Calling pip programmatically <http://blog.ducky.io/python/2013/08/22/calling-pip-programmatically/>`_
"""
class PQPipError(Exception):
"""
Any exception raised ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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
#... |
from django.contrib.auth.hashers import make_password, check_password
from django.core.paginator import Paginator
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from api.models import ATUser, Product, Apis, Apitest, Apistep, Bug, Set, App... |
from more_itertools import ilen
from my.location.ip import ips
def test_ips() -> None:
assert ilen(ips()) > 10
|
import json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
# mensagem
msg = MIMEMultipart()
message = "Email recebido!"
# Cred. e assuntos #
password = "*** Senha do seu e-mail ***"
msg['From'] = "*** login do e-mail que vai enviar ***"
msg['To'] = "*** login do e... |
from pytest import fixture
from starlette.config import environ
from starlette.testclient import TestClient
from app.db.mongodb import get_database
from app.core.config import database_name, users_collection_name
import pyyaml
@fixture(scope="session")
def test_user():
return {
"user": {
"email... |
class Probe:
def __init__(self, vx, vy, x, y):
self.vx = vx
self.vy = vy
self.x = x
self.y = y
def update(self):
self.x += self.vx
self.y += self.vy
if self.vx != 0:
self.vx -= self.vx // abs(self.vx)
self.vy -= 1
def containe... |
#!/usr/bin/env python
from flask import Flask, render_template, url_for, request, redirect, session
from flask_session import Session
import datetime
from dateutil.parser import parse as parse_date
from utils import create_connection
import pandas as pd
import logging
import sys
import os
import re
import sqlite3
impo... |
from rest_framework import status
from django.urls import reverse
from rest_framework.test import APITestCase, APIRequestFactory
from api.models import *
from django.contrib.auth import get_user_model
from api.serializers import *
User = get_user_model()
# Helper Function
def create_nomaluser():
return User.obje... |
import re
from bs4 import BeautifulSoup
from datetime import datetime
import httplib
import praw
import os
if os.path.exists('settings.py'):
import settings
def GetPraw():
return praw.Reddit(client_id = settings.client_id,
client_secret = settings.client_secret,
us... |
# Generated by Django 3.2 on 2022-03-13 20:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('media', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='media',
name='image_url',
field... |
from onnx_runner_generator import generate_onnx_runner
operators = {}
operators['Sigmoid'] = {
'inputs':'[np.array([1, 2, 3]).astype(np.float32)]'
}
operators['BitShift'] = {
'inputs':'[np.random.randn((2,3,4)),np.random.randn((2,3,4))]'
}
for operator, operator_info in operators.items():
generate_onn... |
#!/usr/bin/env python
import unittest
import cStringIO
from amara.lib import testsupport, inputsource
from amara.xupdate import reader, XUpdateError, apply_xupdate
class test_xupdate(unittest.TestCase):
class __metaclass__(type):
def __init__(cls, name, bases, members):
if '__metaclass__' not i... |
from typing import Union
import torch
from torch import nn, Tensor
from byol.utils import mlp
class EncoderWrapper(nn.Module):
def __init__(
self,
model: nn.Module,
projection_size: int = 256,
hidden_size: int = 4096,
layer: Union[str, int] = -2,
):
super().__... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-05-15 06:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('proso_models', '0001_initial'),
]
operations = [
migrations.AlterIndexTogether(
... |
# -*- coding: utf-8 -*-
import asyncio
import functools
import os
import sys
#------------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)
#----------------------------------------------------... |
# Generated by Django 3.1.3 on 2020-12-19 18:26
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('inventario', '0001_initial'),
]
operations = [
migrations.... |
import numpy as np
# Setting the random seed, feel free to change it and see different solutions.
np.random.seed(42)
def stepFunction(t):
if t >= 0:
return 1
return 0
def prediction(X, W, b):
return stepFunction((np.matmul(X, W) + b)[0])
# TODO: Fill in the code below to implement the percept... |
# Generated by Django 2.2.1 on 2019-10-25 11:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('digi', '0023_themeindexpage_guides_and_support_header'),
]
operations = [
migrations.AlterField(
model_name='projectpage',
... |
from setuptools import setup, find_packages
# Go!
setup(
# Module name
name='pkpd',
version='0.0.1dev0',
# License name
license='BSD 3-clause license',
# Maintainer information
maintainer='David Augustin',
maintainer_email='david.augustin@dtc.ox.ac.uk',
# Packages and data to inc... |
import unittest
from bot_top_ranking import handlers
from bot_top_ranking.utils import state, bot
from bot_top_ranking.help_functions import create_top
from unittests.conf import (
call,
message,
chat,
mock_upload_song,
user,
mock_send_message,
mock_pin_chat_message,
get_captur... |
from django import forms
class AddToCartForm(forms.Form):
# The form for entering the amount of a book
# to add.
# choices is an option that defines what values
# the user can populate the field with; in this
# case I've set it to be 1-99, i.e. a user can't
# add less than one copy of a
# ... |
"""
Question 1
"""
import assignment2 as a
import graph_operations as go
import matplotlib.pyplot as plt
# Find probability p such that the ER graph will have approximately the
# same number of edges as the computer network.
NODES = 1239
EDGES = 3047
NETWORK_GRAPH = a.load_graph(a.NETWORK_URL)
# EDGE_PROB is probab... |
# -*- coding: utf-8 -*-
#: The title of this site
SITE_TITLE='HasGeek Funnel'
#: Support contact email
SITE_SUPPORT_EMAIL = 'test@example.com'
#: TypeKit code for fonts
TYPEKIT_CODE=''
#: Google Analytics code UA-XXXXXX-X
GA_CODE=''
#: Database backend
SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'
#: Secret key
SECRET... |
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.urls import re_path
from django.views.static import serve
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import gettext_lazy as ... |
#!/usr/bin/env python
#
# (C) 2001 by Argonne National Laboratory.
# See COPYRIGHT in top-level directory.
#
## NOTE: we do NOT allow this pgm to run via mpdroot
"""
usage: mpdcleanup [-h] [-v] [-f <hostsfile>] [-r <rshcmd>] [-u <user>] [-c <cleancmd>] [-k 'killcmd'] [-n <num_from_hostsfile>]
or: mpdcleanu... |
import os
import sys
import re
import subprocess
import codecs
from PIL import Image
def GetFileContent (fileName):
file = codecs.open (fileName, 'r', 'utf-8')
content = file.read ()
file.close ()
return content
def SetFileContent (fileName, content):
file = codecs.open (fileName, 'w', 'utf-8')
file.write (cont... |
import tensorflow as tf
import threading
import datetime
import signal
import os
from target_driven_method.networks.A3C_networks import A3CFFNetwork
from target_driven_method.networks.target_driven_navigation_networks import TargetDrivenFFNetwork
from target_driven_method.networks.A3C_networks import A3CLSTMNetwork
f... |
from __future__ import print_function
import os.path
import sys
import re
import warnings
from django.db import connection, models
from django.db.backends.util import truncate_name
from django.core.management.color import no_style
from django.db.models.fields import NOT_PROVIDED
from django.db.utils impo... |
from __future__ import absolute_import
# import apis into api package
from tiledb.cloud.rest_api.api.array_api import ArrayApi
from tiledb.cloud.rest_api.api.array_tasks_api import ArrayTasksApi
from tiledb.cloud.rest_api.api.favorites_api import FavoritesApi
from tiledb.cloud.rest_api.api.invitation_api import Invita... |
#!/usr/bin/env python
from setuptools import setup
setup(
name="ectou-metadata",
version="1.0.2",
description="Yet another EC2 instance metadata mocking service.",
url="https://github.com/monetate/ectou-metadata",
author='Monetate',
author_email='jjpersch@monetate.com',
license="MIT",
... |
"""Register with PNP server and wait for remote peers to connect."""
# import argparse
import os
import asyncio
import sys
import json
import yaml
import aiohttp
from typing import Any
from pathlib import Path
from loguru import logger
# from aiortc import RTCIceCandidate, RTCSessionDescription
from peerjs.peer import... |
"""empty message
Revision ID: 3bfc81510c43
Revises: 2505ad08a7d0
Create Date: 2020-08-12 12:12:22.439674
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3bfc81510c43'
down_revision = '2505ad08a7d0'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the mscgen_ Sphinx_ extension.
.. _mscgen: http://www.mcternan.me.uk/mscgen/
.. _Sphinx: http://sphinx.pocoo.org/
Allow mscgen-formatted Message Sequence Chart (MSC) graphs to be included in
Sphinx-generated do... |
import numpy as np
from tg_config import *
def random_mistake(origin_func):
def wrapper(self, *args):
prob = np.random.randint(100)
if( prob < game_configs['mistake_prob']):
origin_result = origin_func(self, *args)
return -1 * origin_result
else:
origin_r... |
from django.contrib import admin
from django.db.models import Count
from django.contrib.auth.admin import UserAdmin
import editor.models
admin.site.register(editor.models.SiteBroadcast)
admin.site.register(editor.models.Tip)
admin.site.register(editor.models.NewExam)
admin.site.register(editor.models.NewQuestion)
ad... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Justin Cunningham
import pandas as pd
import re
import sys
import argparse
from .demutate_corpus import DemutateText
from .utils import pad_sentence, add_window
reg = re.compile("[^a-záéíóú]")
def create_parser(subparsers=None):
if subparsers:
p... |
import base64
import hashlib
from os.path import join
from random import Random
import pandas as pd
from config import DATA_DIR, RANDOM_SEED
from modapt.utils import save_json
from tqdm import tqdm
RNG = Random()
RNG.seed(RANDOM_SEED)
_SUBSAMPLE_SIZE = 10000
_POLARITY_TO_LABEL = {"positive": "pos", "negative": "neg"... |
import json
import logging
from django.db import connection
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from .database import Database
logger = logging.getLogger("django")
class TestView(APIView):
def get(self, request):
try... |
# Generated by Django 2.0.1 on 2018-03-22 15:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('django_workflow', '0009_auto_20180226_1444'),
]
operations = [
migrations.RemoveField(
model_name='transitionlog',
name='obj... |
##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... |
from enum import Enum
string = """proc main() -> unit {
print("Hello World!")
}"""
class TokenKind(Enum):
NOUN = 1
LBRACE = 2
RBRACE = 3
ARROW = 4
LCURLY = 5
RCURLY = 6
STRING = 7
MINUS = 8
STRING = 9
class Token:
def __init__(self, line, pos, kind, contents):
self... |
"""
Tests for the data_download module
Includes three tests for the each of the two data functions
"""
import unittest
from detention_data_dashboard.data_download import *
class TestDashboard(unittest.TestCase):
"""
create class for unittests
"""
def test_smoke_data1(self):
"""
Simp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import xmlrpc.client
import ssl
# try to use xmlrpxlibex from https://github.com/benhengx/xmlrpclibex (install with pip3 install xmlrpclibex)
try:
from xmlrpclibex import xmlrpclibex
can_use_socks = True
except ImportError:
can_use_socks = False
import lo... |
from typing import NamedTuple, Callable, Any, Tuple, List, Dict, Type, cast, Optional
"""
Contains utility functions for working with nested python data structures.
A *pytree* is Python nested data structure. It is a tree in the sense that
nodes are Python collections (e.g., list, tuple, dict) and the leaves are
Pyth... |
__author__ = 'Suyash Soni'
__email__ = 'suyash.soni248@gmail.com'
import os
from setuptools import setup, find_packages
from src.conf.settings import VERSION
def curr_version():
py_repo = os.environ['PY_REPO']
version = VERSION[py_repo]
print('[SETUP] Preparing sqlalchemy_json_querybuilder-{version} to up... |
#import tensorflow as tf
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("..")
from gaussian_dataset import generate_dataset
from simple_mine_refact import SimpleMINE
from grad_corrected_mine import GradMINE
from simple_mine_f import MINEf
import tim... |
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from .core import views
router = routers.DefaultRouter()
router.register(r'orders', views.OrderViewSet)
router.register(r'products', views.ProductViewSet)
# router.register(r'productorders', views.ProductOrderVi... |
from setuptools import setup
project_name = 'requests-ntlm2'
# PyPi supports only reStructuredText, so pandoc should be installed
# before uploading package
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except ImportError:
long_description = ''
requires = [
"requests ==... |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了90.60% 的用户
内存消耗:13.7 MB, 在所有 Python3 提交中击败了68.93% 的用户
解题思路:
动态规划
例: 1,17,5,10,13,15,10,5,16,8
1 17 5 10 13 15 10 5 16 8
↗ 0 ↗ 1 ↘ → 1 ↗ 3 ↗ 3 ↗ 3 ↘ → 3 ↘ → 3 ↗ 5 ↘ → 5
... |
#!/usr/bin/env python
import os, logging
# shut some mouths
logging.getLogger("botocore").setLevel(logging.ERROR)
logging.getLogger("boto").setLevel(logging.ERROR)
logging.getLogger("s3transfer").setLevel(logging.ERROR)
logging.getLogger("urllib3").setLevel(logging.ERROR)
import config, biothings
from biothings.util... |
# coding=utf-8
import csv as csv
from pipelines.auxmod.auxiliary import read_chromsizes, open_comp, check_bounds
def process_ucsc_cgi(inputfile, outputfile, boundcheck, nprefix):
"""
:param inputfile:
:param outputfile:
:param boundcheck:
:param nprefix:
:return:
"""
bounds = read_ch... |
# coding=utf-8
import pytest
from cla.learn.classifier import TraditionalClassifier
@pytest.fixture(scope="module")
def setup_classifier():
classifier = TraditionalClassifier(vector_model_path="cla/res/test/model.bin",
training_data_path="cla/res/test/labeled_train.txt")
... |
import csv
from pymongo import MongoClient
try:
from credentials import MONGOLAB_URL
except ImportError:
MONGOLAB_URL = 'mongodb://localhost:27017/naturalisations'
def export_csv(series_id):
dbclient = MongoClient(MONGOLAB_URL)
db = dbclient.get_default_database()
with open('data/{}.csv'.format(s... |
#
# Count of sum of digits using recursion
#
def sum_of_digits(count):
if(count<=0):
return 0
final = (count%10) + sum_of_digits(count/10);
return final
count = 1234
print(sum_of_digits(count))
|
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (CONF_NAME)
import homeassistant.helpers.config_validation as cv
from .api import P2000Api
"""Start the logger"""
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "... |
from .soc_psql import PSQLConfig
from .soc_psql_forward import PSQLForwardConfig
from .soc_preprocessed_seq import PreprocessedSeqConfig
from .soc_preprocessed_forward import PreprocessedForwardConfig
from .soc_preprocessed_text_forward import PreprocessedTextForwardConfig
from .soc_psql_text_seq import PSQLTextConfig... |
import django
__version__ = '3.10.0'
if django.VERSION < (3, 2):
default_app_config = 'cms.apps.CMSConfig'
|
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# from src.self import SelfEnum as self_enum
import gen_browser_header.self.SelfEnum as self_enum
import gen_browser_header.helper.Helper as helper
import datetime
CHROME_MAX_RELEASE_YEAR = datetime.date.today().year - 2008 + 1
class GbhSetting(object):
# 如果是模拟window... |
from django.core.management.base import BaseCommand, CommandError
from django_comments.models import Comment
from molo.profiles.models import UserProfile, SecurityAnswer
from molo.forms.models import MoloFormSubmission
from wagtail.core.models import Site
class Command(BaseCommand):
help = ('Accepts site ids and ... |
import asyncio
import pytest
@pytest.fixture
def queue() -> asyncio.Queue:
return asyncio.Queue()
|
import random
from abc import ABC, abstractmethod
from typing import Sequence, List
from .action import Action
from .states.game_state import GameState
class Agent(ABC):
@abstractmethod
def choose_action(self, state: GameState, possible_actions: Sequence[Action]) -> Action:
raise NotImplementedError
... |
import os
import shutil
import re
from pathlib import Path
from datetime import datetime
from dataclasses import dataclass
from typing import List
from loguru import logger
class FileStructure:
def __init__(self, infile: str, klass: str, indent=" ") -> None:
self.infile = infile
with open(infil... |
__author__ = 'wanderknight'
__time__ = '2019/8/9 20:31'
from django.conf.urls import url
from ..views.oj import ClassgroupAPI
urlpatterns = [
url(r"^classgroups/?$", ClassgroupAPI.as_view(), name="classgroup_api"),
]
|
import sys
import time
import fastprocesspool_debug as fastprocesspool
from multiprocessing.pool import Pool
if sys.version_info[0] > 2:
from concurrent.futures import ProcessPoolExecutor
import zstd
import msgpack
class TestValues(object):
def __init__(self):
self.result = 0
self.worker = N... |
#input variables to Developer Newsletter Creation Step 13: Get Smart Campaigns
input={
'token': 'Token', #from Step 2: Get Token
'parent id': 'fid', #from Step 3: Get Parent ID or Create Parent Folder
}
import requests
import re
authorization = "Bearer " + input['token']
url = "https://028-jjw-728.mktorest.com... |
# -*- coding: utf-8 -*-
"""
"""
import pytest
import json
from assassin.lib.helper_functions import validate_ip
from assassin.lib.helper_functions import getDomainInfo
def test_getDomaininfo_com(capsys):
response = getDomainInfo('cnn.com')
temp = json.dumps(response)
json_data = json.loads(temp)
assert 'obj... |
# Generated by Django 3.1.6 on 2021-03-20 10:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0017_auto_20210320_1014'),
]
operations = [
migrations.AddField(
model_name='order',
name='email',
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from exam import fixture
from sentry.interfaces.exception import (
SingleException, Exception, trim_exceptions
)
from sentry.testutils import TestCase
class ExceptionTest(TestCase):
@fixture
def interface(self):
return Exception.to_... |
# frontiers.py
# ----------------
# COMP3620/6320 Artificial Intelligence
# The Australian National University
# For full attributions, see attributions.txt on Wattle at the end of the course.
""" This file contains data structures useful for representing search frontiers
for your depth-first, breadth-first, and a... |
import os
import gym
import numpy as np
import pygame
from gym.utils import EzPickle, seeding
from pettingzoo import AECEnv
from pettingzoo.utils import wrappers
from pettingzoo.utils.agent_selector import agent_selector
from pettingzoo.utils.conversions import parallel_wrapper_fn
from .ball import Ball
from .cake_p... |
# -*- coding: utf-8 -*-
from openprocurement.api.roles import RolesFromCsv
from schematics.exceptions import ValidationError
from schematics.types.compound import ModelType
from schematics.types import StringType
from openprocurement.tender.core.models import ContractValue
from openprocurement.api.utils import get_now
... |
import os
import re
import glob
import logging
import itertools
import pytz
import requests
from lxml import etree
import html5lib
import markdown
import yaml
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from django.core.management.base impo... |
'''
testimports.py
Copyright (C) 2013 Liam Deacon
MIT License (see LICENSE file for details)
Test Imports - checks whether key modules and extensions can be imported
'''
import sys,os
import unittest
def isimportable(package, module):
"""
Determine whether module is importable from given package
Ret... |
# coding: utf-8
from keras.callbacks import EarlyStopping, TensorBoard
from keras.layers import Input, Concatenate, Conv1D
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.models import Model
from keras.utils.training_utils import multi_gpu_model
from sklearn.model_selection import StratifiedKFo... |
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from . import models
# Create your views here.
def render404(request):
return HttpResponse("404")
def render500(request):
return HttpResponse("500")
def index(request):
moives = models.douban_top250.objects.all()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.