content stringlengths 5 1.05M |
|---|
import simplejson
import urllib2
import feedparser
import logging
from datetime import timedelta
from django.http import Http404, HttpResponse
from django.template import loader, TemplateDoesNotExist, RequestContext
from django.shortcuts import render_to_response
from django.core.cache import cache
from molly.utils.v... |
from rpy import r
import os.path
# find out where the temp directory is
tempdir = r.tempdir()
# write its name into a file
f = open('tempdir','w')
f.write(tempdir)
f.close()
# put something there..
r.postscript(os.path.join(tempdir,"foo.ps"))
r.plot(1,1)
r.dev_off()
|
import os
from math import ceil
from fastapi import FastAPI, Form
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
from app.aws_s3 import S3
from app.mongo import MongoDB
API = FastAPI(
title='DocDB DS API',
version="1.0.0",
docs_url='/',
)
API.db = MongoDB()
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
""" Analyse des efforts statiques dans un treillis
(assemblage de barres et de pivots)
Le problème est traité en 2D (dans un plan)
Pierre Haessig — Mars 2013
"""
from __future__ import division, print_function, unicode_literals
import numpy as np
import matplotlib.pyplot as p... |
import logging
from datetime import datetime
from enum import Enum
import ntplib
from scapy.layers.ntp import NTPHeader
from ntp_raw import RawNTP
_PCK_1_YEAR = 1995
_PCK_2_YEAR = 2000
class CP3Mode(Enum):
"""
In CP3 an NTP package can be marked as a type 1, or 2 package or as nothing. This class represent... |
from helusers.oidc import ApiTokenAuthentication as HelApiTokenAuth
from django.conf import settings
class ApiTokenAuthentication(HelApiTokenAuth):
def __init__(self, *args, **kwargs):
super(ApiTokenAuthentication, self).__init__(*args, **kwargs)
def authenticate(self, request):
jwt_value = se... |
from inquire_sql_backend.semantics.embeddings.vector_models import VECTOR_EMBEDDERS
def vector_embed_sentence(sent, tokenized=False, model="default"):
embed_func = VECTOR_EMBEDDERS[model]
return embed_func(sent, batch=False, tokenized=tokenized)
def vector_embed_sentence_batch(sent, tokenized=False, model="... |
import torch.nn as nn
import torch
from .conv2d_repeat import Conv2dRepeat
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __ini... |
from flask import Blueprint
socket_client = Blueprint('socket_client', __name__)
from . import events |
from rest_framework import serializers
from puzzle.models import Offer
class OfferSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(
source="author.user.username", read_only=True)
class Meta:
model = Offer
fields = ["id", "author_name", "created",
... |
"""Collection of PBM-based click simulators."""
from typing import Optional
from typing import Tuple
import torch as _torch
from pytorchltr.utils import mask_padded_values as _mask_padded_values
_SIM_RETURN_TYPE = Tuple[_torch.LongTensor, _torch.FloatTensor]
def simulate_pbm(rankings: _torch.LongTensor, ys: _torch... |
import ila
import riscv_um
def genVlg():
rm = riscv_um.riscvModel()
rm.loadUnprivNxtFromDir('unpriv_asts')
rm.model.generateVerilog('RISC-V-VLG.v')
if __name__ == '__main__':
genVlg()
|
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, 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 requi... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#import libraries
import string
import ast
from itertools import islice
import csv
from nltk.tokenize import RegexpTokenizer
def createTsvFile_Search1(listUrl_Movies3):
#create tsv file in 'tsv_correct' directory wehere we have preprocessed the tsv file (just creat... |
from django import template
from classytags.core import Options
from classytags.helpers import AsTag
from classytags.arguments import Argument
from ..models import CallToActionRepository
class GetCallToAction(AsTag):
name = 'get_call_to_action'
options = Options(
Argument('code', required=True),
... |
import json
def get_list():
with open("config.json", "r") as f_obj:
f_json = json.load(f_obj)
return f_json
def get_lang(item):
return get_list()[item]
def set_lang(item, lang):
with open("list_lang.json", "r") as f_obj:
list_lang = json.load(f_obj)
if not (lang in list_lan... |
import os
import os.path as osp
import copy
import yaml
import numpy as np
from ast import literal_eval
from utils.collections import AttrDict
__C = AttrDict()
cfg = __C
# ---------------------------------------------------------------------------- #
# MISC options
# -------------------------------------------------... |
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
def rules_clojure_dependencies():
jvm_maven_import_external(
name = "org_clojure",
artifact = "org.clojure:clojure:1.10.1",
artifact_sha256 = "d4f6f991fd9ed2a59e7ea4779010b3b069a2b905f3463136c42201106b4ad21a",
... |
from django.apps import AppConfig
class ApacheKafkaConfig(AppConfig):
name = 'apache_kafka'
|
import click
from neobox.cmd.list import list_
from neobox.cmd.clear_cache import clear_cache
from neobox.cmd.login import login
from neobox.cmd.logout import logout
from neobox.cmd.search import search
from neobox.cmd.play import play
from neobox.cmd.pause import pause
from neobox.cmd.stop import stop
@click.group(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author : yasin
# @time : 18-12-28 下午9:28
# @File : config.py
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("novel-update-monitor-account")
bindIp = '0.0.0.0'
bindPort = 12126
token = 'VqmB965wOEBrPLNoMkHCfIOpxF0WWFM6'
g... |
"""User profile model"""
# Django
from django.db import models
# Utilities
from mydea.utils.models import MyDeaModel
class Profile(MyDeaModel):
"""Profile model.
A profile holds a user's data"""
# user
user = models.OneToOneField('users.User', on_delete=models.CASCADE)
def __str__(self):
... |
#----------------------------------------------------------------------
# Deep learning for classification for contrast CT;
# Transfer learning using Google Inception V3;
#-------------------------------------------------------------------------------------------
import os
import numpy as np
import pandas as pd
import... |
import os
from time import time
import krgram.tl.protocol
import krgram.tl.protocol.auth
from krgram.client.crypto import TLEncryptor
from krgram.client.errors import SecurityError
from krgram.mtproto.connection import MTProtoAbridgedConnection
from krgram.mtproto.dcs import DataCenters
from krgram.mtproto.errors impo... |
import sqlalchemy
from pydantic import BaseModel
from .model import Base
class Category(BaseModel):
""""""
name: str
color: str
class CategoryTable(Base):
__tablename__ = "category"
name = sqlalchemy.Column(sqlalchemy.String, primary_key=True)
color = sqlalchemy.Column(sqlalchemy.String)
... |
#!/usr/bin/env python3
import sys
import gzip
import ast
import json
class Dumper:
def __init__(self, path):
self.path = path
self.open_file = {}
def close_all(self):
#close previous file(s)
for name in self.open_file:
self.open_file[name].close()
self.open... |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 th... |
import os
class Config:
title = 'VocView'
# URL root of this web application. This gets set in the before_first_request function.
url_root = None
# Subdirectory of base URL. Example, the '/corveg' part of 'vocabs.tern.org.au/corveg'
SUB_URL = ''
# Path of the application's directory.
AP... |
list1=['car','ara','cabc']
c=0
for i in list1:
a=list1
if(
c=c+1
print(c)
|
import pyeccodes.accessors as _
def load(h):
h.add(_.Unsigned('n2', 2))
h.add(_.Unsigned('n3', 2))
h.add(_.Unsigned('nd', 3))
h.alias('numberOfDiamonds', 'nd')
h.alias('Nj', 'nd')
h.add(_.Unsigned('Ni', 3))
h.add(_.Codeflag('numberingOrderOfDiamonds', 1, "grib1/grid.192.78.3.9.table"))
... |
import struct
from io import BytesIO
p8 = lambda x:struct.pack("<B", x)
u8 = lambda x:struct.unpack("<B", x)[0]
p16 = lambda x:struct.pack("<H", x)
u16 = lambda x:struct.unpack("<H", x)[0]
p32 = lambda x:struct.pack("<I", x)
u32 = lambda x:struct.unpack("<I", x)[0]
p64 = lambda x:struct.pack("<Q", x)
u64 = lambda x... |
from sacnn.core.we import get_word_to_vector
word_to_vector, WORD_DIMENSION = get_word_to_vector()
|
from __future__ import annotations
import collections
import copy
import json
import logging
import operator
import os
from typing import Any, Dict, List, Optional, Tuple
import joblib
from poker_ai import utils
from poker_ai.poker.card import Card
from poker_ai.poker.engine import PokerEngine
from poker_ai.games.sh... |
import json
class SwearWords(object):
def __init__(self):
self.data = json.load(open('data.json'))
def filter_words(self,text,symbol="*"):
text = text.split()
print(text)
for i in range(len(text)):
if text[i] in self.data['word']:
text[i] = symbol * ... |
import RPi.GPIO as GPIO
led_pin = 29
button_pin = 40
buzzer_pin = 31
GPIO.setmode(GPIO.BOARD)
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(buzzer_pin, GPIO.OUT)
while True:
if GPIO.input(button_pin) == GPIO.HIGH:
GPIO.output(led_pin, True)
GPIO.output(buz... |
"""
MIT License
Copyright (c) 2021 isaa-ctaylor
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, ... |
"""
The Importer feature sets up the ability to work with cuneiform text(s)
one-on-one, whether it is the Code of Hammurabi, a collection of texts such as
ARM01, or whatever your research desires.
This cdli_corpus module is for working with text files having already been read
by file_importer. The file_lines required ... |
# Copyright (c) 2016-2018, Neil Booth
#
# All rights reserved.
#
# See the file "LICENCE" for information about the copyright
# and warranty status of this software.
import asyncio
import pylru
from aiorpcx import run_in_thread
from electrumx.lib.hash import hash_to_hex_str
class ChainState(object):
'''Used a... |
import sys
from secret import FLAG, REGISTER, TAPS
assert FLAG.startswith('flag')
assert len(REGISTER) == 16
assert len(TAPS) == 5
class LFSR:
def __init__(self, register, taps):
self.register = register
self.taps = taps
def next(self):
new = 0
ret = self.register[0]
... |
# -*- coding: utf-8 -*-
# External import
import pytest
from numpy import array, pi
from os.path import join
from multiprocessing import cpu_count
# Pyleecan import
from pyleecan.Classes.ImportGenVectLin import ImportGenVectLin
from pyleecan.Classes.ImportMatrixVal import ImportMatrixVal
from pyleecan.Classes.Simu1 i... |
#!/usr/bin/env python3
"""SERVICE YET TO BE IMPLEMENTED. THIS FILE IS JUST A PLACEHOLDER."""
print("Sorry! This service has not yet been implemented\n(will you be the one to take care of it?\n --- RIGHT NOW THIS FILE IS JUST AN HANDY PLACEHOLDER ---")
|
# Copyright 2020, The TensorFlow Federated 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 o... |
# Generated by Django 2.1.3 on 2018-11-09 05:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('restapi', '0010_annotatedrecording_recitation_mode'),
]
operations = [
migrations.CreateModel(
name='TajweedInformation',
... |
# MIT License
#
# Copyright (c) 2021 TrigonDev
#
# 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, pu... |
import torch
from numpy import histogram, random
from scipy.stats import skewnorm
from torch import Tensor, from_numpy
from torch.nn.functional import softmax
class WGAN:
def __init__(self) -> None:
super().__init__()
def discriminator_loss(self, real_scores: Tensor, fake_scores: Tensor) -> Tensor:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-01 13:53
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0003_auto_20170801_1819'),
]
operations = [... |
import pytest
from pathlib import Path
from coolcmp.cmp.source_code import *
from unit_tests.utils import run_test_codegen
tests = []
with open('unit_tests/compiled_files.txt') as f:
for line in f:
tests.append(Path(line.rstrip()).resolve())
@pytest.mark.complete
@pytest.mark.parametrize('file', tests, i... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
from common.log import logger
from common.globalvar import db_related_to_project_dic
from unittesttestcase import MyUnittestTestCase
__all__ = ['DBUnittestTestCase']
class DBUnittestTestCase(MyUnittestTestCase):
def test_select_one_record(self)... |
"""
Simple HTTP Server with GET that waits for given seconds.
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import time
ENCODING = 'utf-8'
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
"""Simple multi-threaded HTTP Server."""
pass
class MyR... |
from .regressor import CrossLgbRegression |
from django.urls import path, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
admin.autodiscover()
import autobot.views
# To add a new path, first import the app:
# import blog
#
# Then add the new path:
# path('blog/', blog.urls, name="blog")
#
# Learn more here: https:/... |
# This imports all that is listed in __init__.py of current directory:
from __init__ import *
#-------------------------------------------------------------------------------------- MAIN WINDOW CLASS ----------------------------------------------------------------------------------#
class Window(QtGui.QMainWindow): ... |
import os
# Database connection setup
class Config(object):
SERVER = ''
DATABASE = ''
DRIVER = ''
USERNAME = ''
PASSWORD = ''
SQLALCHEMY_DATABASE_URI = f'mssql+pyodbc://{USERNAME}:{PASSWORD}@{SERVER}/{DATABASE}?driver={DRIVER}'
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG = True
S... |
import os
import sys
filename = __file__[:-5] + '-input'
with open(filename) as f:
lines = f.read().splitlines()
lines = list(map(lambda s: s.split('-'), lines))
connections = {}
for line in lines:
if line[0] not in connections and line[1] != 'start' and line[0] != 'end':
connections[line[0]] =... |
import numpy as np
from . InverterException import InverterException
from . InputData import InputData
class Image(InputData):
"""
This class represents a camera image and can be used as input to the
various inversion algorithms. Images can be created directly, or by
importing and filtering a video.
... |
"""Support for Avanaza Stock sensor."""
|
import os
import re
import codecs
def isValidLine(line):
if re.search('include \"', line) == None or line.find('.PSVita') != -1 or line.find('.PS4') != -1 or line.find('.Switch') != -1 or line.find('.XBoxOne') != -1:
return True
return False
class CreateHeader:
def __init__(self):
self.lines = []
def addLine... |
from __future__ import annotations
from typing import List, Tuple
import ujson
import os.path as path
import stargazing.pomodoro.pomodoro_controller as pomo_pc
CONFIG_FILE_PATH = f"{path.dirname(path.abspath(__file__))}/../config/settings.json"
def get_saved_youtube_player_urls() -> List[str]:
with open(CONFIG_... |
OUTPUT_ON = b'1'
OUTPUT_OFF = b'0'
OUTPUT_PULSE = b'P'
OUTPUT_CURRENT = b'O'
INPUT_DELTA = b'D'
INPUT_CURRENT = b'C'
TURNOUT_NORMAL = b'N'
TURNOUT_REVERSE = b'R'
IDENTIFY = b'Y'
SERVO_ANGLE = b'A'
SET_TURNOUT = b'T'
GET_TURNOUT = b'G'
CONFIG = b'F'
ACKNOWLEDGE = b'!'
STORE = b'W'
ERRORRESPONSE = b'E'
WARNINGRESPONSE = ... |
import tensorflow as tf
# Stolen from magenta/models/shared/events_rnn_graph
def make_rnn_cell(rnn_layer_sizes,
dropout_keep_prob=1.0,
attn_length=0,
base_cell=tf.contrib.rnn.BasicLSTMCell,
state_is_tuple=False):
cells = []
for num_units in rnn_layer_sizes:
cell = base_cell(num_units, stat... |
from block import Block
from transaction import Transaction
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
import bitcoin
class BlockChain:
def __init__(self):
self.chain = []
self.tx_pool = []
self.bits = 2
self.reward = 50
genesis_block = Block(None, sel... |
'''
Nombre de archivo:
+procesamientodatos.py
Descripción:
+Librería con funciones para el procesamiento de los datos
Métodos:
|--+cargar_datos
|--+generar_tablas
|--+almacenar_tablas
'''
#librerías necesarias
import sys, os, glob, datetime as dt
from pyspark.sql import SparkSession, functions as F, window ... |
"""VIC Emergency Incidents feed entry."""
from typing import Optional, Tuple
import logging
import re
from time import strptime
import calendar
from datetime import datetime
import pytz
from aio_geojson_client.feed_entry import FeedEntry
from geojson import Feature
from markdownify import markdownify
from .consts impo... |
import networkx as nx
from . import utils
# ===== asexual lineage metrics =====
def get_asexual_lineage_length(lineage):
"""Get asexual lineage length.
Will check that given lineage is an asexual lineage.
Args:
lineage (networkx.DiGraph): an asexual lineage
Returns:
length (int) of ... |
import tqdm
from multiprocessing import Pool
import logging
from dsrt.config.defaults import DataConfig
class Filter:
def __init__(self, properties, parallel=True, config=DataConfig()):
self.properties = properties
self.config = config
self.parallel = parallel
self.init_logger()
... |
import os
import numba
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ReduceLROnPlateau
from optimizer import *
from trainer_callbacks import *
from utils import *
#%% #################################### Model Trainer Class ####################################
class ModelTrainer(... |
from backend.stage import ready_stage
from backend import message
from backend import helpers
class JobStage(ready_stage.ReadyStage):
stage_type = 'Job'
def __init__(self, game) -> None:
super().__init__(game)
self._job_selected = {} # facility selected indexed by player
@classmethod
... |
""" Robot http server and interface handler
Approach to operations:
This http server module is conceptualized as a gateway between a robot,
with private, internal operations, and the web. Incoming requests for
actions to be executed by the robot and requests for information such as
telemetry data arriv... |
"""
How plugins work
----------------
From a user's perspective, plugins are enabled and disabled through the command
line interface or through a UI. Users can also configure a plugin's behavior
through the main Kolibri interface.
.. note::
We have not yet written a configuration API, for now just make sure
... |
# -*- coding: utf-8 -*-
"""
Base classes for Models.
"""
import typing as tp
from uuid import UUID
ModelType = tp.TypeVar("ModelType", bound='ModelBase')
class Model(tp.Protocol):
"""
Interface for base model class.
"""
uid: tp.Optional[UUID]
class ModelBase(object):
"""
Model storage ultim... |
# pylint doesn't know about pytest fixtures
# pylint: disable=unused-argument
import datetime
import os
import time
import uuid
import boto3
import pytest
from dagster_k8s.test import wait_for_job_and_get_raw_logs
from dagster_k8s_test_infra.integration_utils import (
can_terminate_run_over_graphql,
image_pull... |
from __future__ import annotations
import src.globe.hexasphere as hexasphere
if __name__ == "__main__":
hs = hexasphere.Hexsphere(50, 1, 0.8)
print(hs)
|
import itertools
from matplotlib import cm
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from rllab.envs.base import Env
from rllab.misc import logger
from rllab.spaces import Box
from rllab.spaces import Discrete
from utils import flat_to_one_hot, np_seed
class Discre... |
from distutils.core import setup
import setuptools
setup(
name="turkishnlp",
version="0.0.61",
packages=['turkishnlp'],
description="A python script that processes Turkish language",
long_description=open('README.md', encoding="utf8").read(),
long_description_content_type='text/markdown',
u... |
"""Frontend for spectra group project"""
__author__ = """Group01"""
__version__ = '0.1.0'
|
#!/usr/bin/env python
# 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, software... |
import os
import csv
import json
import torch
import pickle
import random
import warnings
import numpy as np
from functools import reduce
from typing import Dict, List, Tuple, Set, Any
__all__ = [
'to_one_hot',
'seq_len_to_mask',
'ignore_waring',
'make_seed',
'load_pkl',
'save_pkl',
'ensure... |
import os
import boto3
AMI = os.environ["AMI"]
INSTANCE_TYPE = os.environ["INSTANCE_TYPE"]
KEY_NAME = os.environ["KEY_NAME"]
SUBNET_ID = os.environ["SUBNET_ID"]
REGION = os.environ["REGION"]
INSTANCE_PROFILE = os.environ["INSTANCE_PROFILE"]
ec2 = boto3.client("ec2", region_name=REGION)
def create_instance(event, ... |
# coding: utf-8
"""Pytest fixtures and utilities for testing algorithms."""
import gym
import torch
import torch.nn as nn
import torch.distributions as distrib
import pytest
from irl.algo.value_methods import TensorQValues
class ProbPolicy(nn.Module):
"""A simple test probabilistic policy."""
def __init__... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline ... |
from __future__ import print_function, division, absolute_import
from distributed.compatibility import (
gzip_compress, gzip_decompress, finalize)
def test_gzip():
b = b'Hello, world!'
c = gzip_compress(b)
d = gzip_decompress(c)
assert b == d
def test_finalize():
class C(object):
pas... |
# ActivitySim
# See full license in LICENSE.txt.
import logging
import pandas as pd
from activitysim.core import tracing
from activitysim.core import config
from activitysim.core import pipeline
from activitysim.core import inject
from activitysim.core.util import assign_in_place
from activitysim.abm.models.trip_pu... |
# pytest file that runs the things in shell-sessions/
import codecs
import os
import pathlib
import re
import shutil
import sys
import time
import pytest
import asdac.__main__
sessions_dir = pathlib.Path(__file__).absolute().parent / 'shell-sessions'
@pytest.fixture
def shell_session_environment(tmp_path):
os.... |
#!/usr/bin/env python
import asyncio
import websockets
isExit = False
async def client(uri):
global isExit
async with websockets.connect(uri) as websocket:
while True:
content = await websocket.recv()
print(content)
await asyncio.sleep(0.1)
if isExit:
... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... |
from actors.actions.action import Action
class DelayedAction(Action):
def __init__(self, action, delay_remaining=1):
self.action = action
self.delay_remaining = delay_remaining
def on(self, actor, tile, root):
delay_remaining = self.delay_remaining - 1
return root, (DelayedAc... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG),
# acting on behalf of its Max Planck Institute for Intelligent Systems and the
# Max Planck Institute for Biological Cybernetics. All rights reserved.
#
# Max-Planck-Gesellschaft zur Förderung der Wissens... |
#!/usr/bin/env python
"""
Script to calculate the mean and std
Usage:
./scripts/cal_deepfashion_ds_meanstd.py
"""
import os.path
import sys
cur_path = os.path.realpath(__file__)
cur_dir = os.path.dirname(cur_path)
parent_dir = cur_dir[:cur_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
# -------------------... |
'''
This function returns the first longest word from the input string
'''
def LongestWord(sen):
max=0
st=""
for c in sen:
if c.isalnum():
st=st+c
else:
st=st+" "
words=st.split(" ")
for word in words:
if len(word) > max:
max=len(word)
... |
from django.urls import NoReverseMatch, reverse
from django.utils.html import format_html
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop
from django.views import View
from memoized import memoized
from dimagi.utils.parsing import string_to_utc_datetime
from dimag... |
"""Base class for module overlays."""
from pytype import datatypes
from pytype.abstract import abstract
class Overlay(abstract.Module):
"""A layer between pytype and a module's pytd definition.
An overlay pretends to be a module, but provides members that generate extra
typing information that cannot be expres... |
import cplex
import numpy as np
names = ["x11", "x12", "x13", "x14",
"x21", "x22", "x23", "x24",
"x31", "x32", "x33", "x34",
"y11", "y12", "y13", "y14",
"y21", "y22", "y23", "y24",
"y31", "y32", "y33", "y34"]
T = np.array([[3.0, 2.0, 2.0, 1.0],
[4.0, 3.0, 3.0... |
"""Main entry point for the pixelation tool."""
import sys
from .constants import SUCCESS
from .core import PixelArt
from .parser import build_parser, parse_args
def main() -> None:
"""Parses the command line arguments and runs the tool."""
arg_parser = build_parser()
args = parse_args(arg_parser)
... |
"""Classes for defining instructions."""
from __future__ import absolute_import
from . import camel_case
from .types import ValueType
from .operands import Operand
from .formats import InstructionFormat
try:
from typing import Union, Sequence, List, Tuple, Any, TYPE_CHECKING # noqa
from typing import Dict # n... |
#!/usr/bin/env python3
"""
Abstract base class for data Readers.
"""
import sys
sys.path.append('.')
from logger.utils import formats
################################################################################
class Reader:
"""
Base class Reader about which we know nothing else. By default the
output form... |
import os
import shutil
from codecs import open
from os import path
from setuptools import setup, Command
here = path.abspath(path.dirname(__file__))
name = 'sqe'
version = '0.1.0'
class CleanCommand(Command):
description = "custom clean command that forcefully removes dist and build directories"
user_optio... |
from datetime import date, datetime, timedelta
from django.test import TestCase
from projects.models import Project, Invoice
from inspectors.models import Inspector
class ProjectModelTest(TestCase):
def setUp(self):
date_1 = date.today()
date_2 = date_1 + timedelta(days=10)
p1 = Project.... |
# coding: utf-8
"""
vloadbalancer
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from ncloud_vloadbalancer.api_client import ApiClient
class V2Api(object):
... |
from selenium import webdriver
import logging
import os
logging.getLogger().setLevel(logging.INFO)
def lambda_handler(event, context):
logging.info("python-selenium-chromium-on-lambda started")
chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory": "/tmp", "safebrowsing.enable... |
#
# PySNMP MIB module WHISP-BOX-MIBV2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WHISP-BOX-MIBV2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:29:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.