content stringlengths 5 1.05M |
|---|
from newrelic.agent import wrap_in_function, WSGIApplicationWrapper
def instrument_gevent_wsgi(module):
def wrapper_WSGIServer___init__(*args, **kwargs):
def _bind_params(self, listener, application, *args, **kwargs):
return self, listener, application, args, kwargs
self, listener, ap... |
from flask import Flask, request, render_template, redirect, url_for
from flask_restful import Api
from flask_jwt import JWT
from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemList
from resources.inventory import Inventory, InventoryList
app = Flas... |
# Made by Kerberos v1.0 on 2008/02/03
# this script is part of the Official L2J Datapack Project.
# Visit http://www.l2jdp.com/forum/ for more details.
import sys
from com.l2jserver.gameserver.ai import CtrlIntention
from com.l2jserver.gameserver.model.quest import State
from com.l2jserver.... |
# Copyright 2020 DeepMind Technologies Limited.
#
# 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 ag... |
#!/usr/bin/env python3
import sys
from random import randint
def generate_array(amount: int, outfile: str) -> None:
with open(outfile, 'w') as file:
print("Writing random numbers to file.")
file.write(str(amount))
file.write(" ")
for _ in range(amount):
file.write(str(ra... |
#!/usr/bin/env python
"""
Pegasus utility functions for pasing a kickstart output file and return wanted information
"""
from __future__ import print_function
##
# Copyright 2007-2010 University Of Southern California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ... |
import framework, secret
from framework import discord
############################################################################################
# GUILD MESSAGES DEFINITION #
###########################################################################... |
from pathlib import Path
from typing import BinaryIO
import pytest
from quetz import hookimpl
from quetz.authorization import MAINTAINER, MEMBER, OWNER
from quetz.condainfo import CondaInfo
from quetz.config import Config
from quetz.db_models import ChannelMember, Package, PackageMember, PackageVersion
from quetz.err... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-05-29 20:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat', '0014_auto_20181116_0657'),
]
operations = [
migrations.AddField(
... |
#!
# pip3 install translate
#https://www.udemy.com/course/complete-ethical-hacking-bootcamp-zero-to-mastery/
from translate import Translator
LANG = input("Input a compatible language to translate to:" )
translator = Translator(to_lang=LANG)
try:
with open('filename.txt', mode='r') as
text = (file.read())
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
N=int(input())
x=input().split()
#N,n = int(raw_input()),raw_input().split()
print (all([int(i)>0 for i in x]) and any([j == j[::-1] for j in x]))
|
#!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright 2015 Esri
# 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.apa... |
# Copyright 2021 Canonical
# See LICENSE file for licensing details.
"""Module defining Legend DB consumer class and helpers."""
import json
import logging
from ops import framework
# The unique Charmhub library identifier, never change it
LIBID = "02ed64badd5941c5acfdae546b0f79a2"
# Increment this major API versi... |
# -*- coding: utf-8 -*-
import copy
import json
import os
import re
import shutil
import subprocess
import time
from requests_toolbelt import MultipartEncoder
from . import config
def download_video(
self,
media_id,
filename=None,
media=False,
folder="videos"
):
video_urls = []
if not me... |
# Lint as: python3
# Copyright 2020 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 ... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import Rule
class SinaSpider(scrapy.Spider):
name = 'sina'
allowed_domains = ['sina.com']
start_urls = ['https://news.sina.cn']
def parse(self, response):
li_list = response.xpath('//ul[@class="swiper-wrapper"]/li')
for li in l... |
# coding: utf-8
import re
import os
import sys
import json
import types
import errno
import random
import string
import functools
import hashlib
import traceback
import requests
import urlparse
from urllib import urlencode
from datetime import datetime, date
from StringIO import StringIO
from jinja2 import Markup
from ... |
import codecs
import configparser
class Parser:
def __init__(self):
self.configfile = './config/config.ini'
config = configparser.ConfigParser()
config.read_file(codecs.open(self.configfile, "r", "utf-8-sig"))
self.api_key = config['Binance']['API_Key']
self.secret = conf... |
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.BlogHome.as_view(), name='blog'),
)
|
from datetime import datetime
from flask import url_for
from sopy import db
from sopy.auth.models import User
from sopy.ext.models import IDModel
class WikiPage(IDModel):
title = db.Column('title', db.String, nullable=False, unique=True)
body = db.Column(db.String, nullable=False)
updated = db.Column(db.D... |
import collections
import charmhelpers.contrib.openstack.context as context
import yaml
import json
import unittest
from copy import copy, deepcopy
from mock import (
patch,
Mock,
MagicMock,
call
)
from tests.helpers import patch_open
import six
if not six.PY3:
open_builtin = '__builtin__.open'
el... |
import os, sys, json
import subprocess
## A script to generate Fig.13
## Fig.13 includes two subplot
## (a) preemption latency with increased kernel execution time
## (b) preemption latency with increased kernel number
quick_eval = False
if os.getenv("REEF_QUICK_EVAL") != None:
quick_eval = True
def run_shell_cm... |
# Copyright 2014 Max Sharples
#
# 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, ... |
# -*- coding: utf-8 -*-
"""This file contains a plist plugin for the iPod/iPhone storage plist."""
from __future__ import unicode_literals
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.parsers import plist
from plaso.parsers.plist_plugins imp... |
'''
CS 115, Inheritance Activity
Author: <your name here>
Pledge: <write pledge>
'''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' RULES: You can use Canvas to download this file and upload your solution.
' You can use Eclipse to edit and run your program. You should NOT look at
' ot... |
import os
import sys
import argparse
from map_functions import read_content
parser = argparse.ArgumentParser(description='Count objects in the custom dataset')
parser.add_argument('-a', '--anno_dir', default=None, help='annotation dir')
args = parser.parse_args()
anno_list = sorted(os.listdir(args.anno_dir))
paths =... |
import PySimpleGUI as sg
class App:
def __init__(self):
layout = [
[sg.Text('Primeiro número:' ), sg.Input(key='num1')],
[sg.Text('Segundo número: '), sg.Input(key='num2')],
[sg.Button('OK'), sg.Button('Cancel')]
]
self.win = sg.Window('EXE-003', layout)
... |
from test_utils import create_and_save_env
from flatland.envs.rail_env import RailEnv
from flatland.envs.rail_generators import sparse_rail_generator, random_rail_generator, complex_rail_generator, \
rail_from_file
from flatland.envs.schedule_generators import sparse_schedule_generator, random_schedule_generator, ... |
"""Base classes for Jenkins test report unit tests."""
from ..source_collector_test_case import SourceCollectorTestCase
class JenkinsTestReportTestCase(SourceCollectorTestCase): # skipcq: PTC-W0046
"""Base class for Jenkins test report unit tests."""
SOURCE_TYPE = "jenkins_test_report"
|
# -*- coding: utf-8 -*-
"""
Original file from Telefónica I+D:
https://github.com/telefonicaid/lettuce-tools/blob/master/lettuce_tools/dataset_utils/dataset_utils.py
dataset_utils module contains:
- A dataset manager to prepare test data:
* generate_fixed_length_params: Transforms the '[LENGTH]' para... |
from os import getcwd
from os.path import join
PATH = getcwd()
LOG_FILE_DIR = join(PATH, "log")
LOGGER_CONFIG = join(PATH, "utils", "logging.json") |
from globals import Globals
import os
import subprocess
import datetime as dt
from urllib import \
request as request
# urlopen
from io import \
StringIO, BytesIO
import string
import requests
import re
import csv
import threading
import utils as utils
import time
import datetime as datetime
import multiproces... |
"""
This file is derived from the original XNAS source code,
and has not been rigorously tested subsequently.
If you find it useful, please open an issue to tell us.
recoded file path: XNAS/tools/sng_nasbench1shot1.py
"""
import argparse
import os
import ConfigSpace
import numpy as np
from nasbench import api
fro... |
import asyncio
import os
import requests
import pytest
import starlette.responses
import ray
from ray import serve
from ray._private.test_utils import SignalActor, wait_for_condition
from ray.serve.application import Application
@serve.deployment()
def sync_d():
return "sync!"
@serve.deployment()
async def as... |
import importlib
import threading
import requests
from discord_interactions import verify_key_decorator
from flask import Blueprint, abort, send_file, request, jsonify
from globals import tokens, running_interactions, client
from statics import config
views = Blueprint("misc", __name__)
@views.route("/pictures/<gui... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
This example uses adafruit_display_text.label to display text using a custom font
loaded by adafruit_bitmap_font.
Adapted for use on MagTag
"""
import time
import board
from adafruit_display_text import label
f... |
import requests
from bs4 import BeautifulSoup
from settings import DATAFILE, OUTFILE
def main():
html_doc = open(DATAFILE).read()
soup = BeautifulSoup(html_doc, 'html.parser')
with open(OUTFILE, 'w') as open_file:
for _ in soup('dt'):
if _.h3:
print(_.h3.string)
... |
import pandas as pd
visits = pd.read_csv('./analysis/data/pagevisitsfunnel/visits.csv', parse_dates=[1])
cart = pd.read_csv('./analysis/data/pagevisitsfunnel/cart.csv', parse_dates=[1])
checkout = pd.read_csv('./analysis/data/pagevisitsfunnel/checkouts.csv', parse_dates=[1])
purchase = pd.read_csv('./analysis/data/pag... |
#!/usr/bin/env python3
import sqlite3
from datetime import datetime
import config
# set pathname
database_file = config.database_file
class SqlConnect:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.connection = sqlite3.connect(self.filename)
self.cu... |
r"""
Mappings from `Ontology`\ s to particular languages.
"""
from attr import attrib, attrs
from attr.validators import instance_of
from immutablecollections import ImmutableSet, ImmutableSetMultiDict
from immutablecollections.converter_utils import _to_immutablesetmultidict
from vistautils.preconditions import check... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Sword York
# GitHub: https://github.com/SwordYork/sequencing
# No rights reserved.
#
import random
from collections import deque, namedtuple
import subprocess
import numpy
import tensorflow as tf
import sequencing as sq
from sequencing import MODE, TIME_... |
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfulla... |
from numpy import array
from UQSetting import UQSetting
from UQSettingFormatter import UQSettingFormatter
class Samplingresult:
def __init__(self, uqsetting):
"""
Create a Samplingresult using data of the given UQSetting. If
a filename or a list of filenames is given, load the UQSetting... |
import discord
class Utils:
def __init__(self, client: object):
self.client: object = client
@staticmethod
def is_DMChannel(message: str) -> bool:
return isinstance(message.channel, discord.channel.DMChannel)
def is_Command(self, message: str) -> list:
prefix: str = self.clien... |
#!/usr/bin/env python3
import gvm
from gvm.protocols.latest import Gmp
from gvm.transforms import EtreeCheckCommandTransform
from gvm.errors import GvmError
connection = gvm.connections.TLSConnection(hostname='localhost')
username = 'admin'
password = 'admin'
transform = EtreeCheckCommandTransform()
try:
with ... |
def average(li):
s = sum(li)
n = len(li)
return s / n
li = [1, 2, 3]
print("Averagr:", average(li))
li = [10, 20, 30, 40, 50, 60, 70, 80];
print("Averagr:", average(li))
li = [-1, 0, 1]
print("Averagr:", average(li)) |
from .base import db
def init_app(app):
db.init_app(app)
|
import pytest
from ...core import ProxyTypeError
from ...primitives import Int, Str
from ...geospatial import ImageCollection, Image, FeatureCollection, GeometryCollection
from .. import Tuple, List, zip as wf_zip
examples = [
List[Int]([1, 2, 3]),
List[Str](["a", "b", "c"]),
List[Tuple[Int, Str]]([(1, ... |
import requests
from json import JSONDecodeError
import pythoncom
pythoncom.CoInitialize()
class LocationRecord:
"""Holds and records the location of the client device
Keyword Arguments:
ip -- Current client device IP address (Default: None)
city -- Approximate city of the dev... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Blueprint, jsonify, request
from app.classes.network import Network
network = Network()
network_bp = Blueprint("network", __name__)
@network_bp.route("/status", methods=["GET"])
def api_network_status():
""" Get the network status of e... |
# -*- coding: utf-8 -*-
# unzip練習
# http://www.pythonchallenge.com/pc/def/channel.html
import os
import os.path
import zipfile
import re
fileName = 'channel'
# フォルダがなかったら作成してunzip
if not os.path.isdir(fileName) :
os.mkdir(fileName)
# unzip
fZip = zipfile.ZipFile(fileName+'.zip', 'r')
fZip.extractall(fileName)... |
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
d = 1j
p = 0
for ins in instructions:
if ins == "L":
d = d * 1j
elif ins == 'R':
d = d * (-1j)
else:
p += d
return False if (d == 1... |
#Desafio10
#Crie um programa que leia quanto dinheiro uma pessoa tem na carteira
#e mostre quantos dólares ela pode comprar
#Considere US$1,00 = R$3,27
rs=float(input('Quanto dinheiro você tem na carteira?: R$ '))
dolar = rs/3.27
print('Com R${:.2f} você pode comprar US${:.2f}'.format(rs,dolar))
|
from pytransform import pyarmor_runtime
pyarmor_runtime()
__pyarmor__(__name__, __file__, b'\x50\x59\x41\x52\x4d\x4f\x52\x00\x00\x03\x09\x00\x61\x0d\x0d\x0a\x08\x2d\xa0\x01\x00\x00\x00\x00\x01\x00\x00\x00\x40\x00\x00\x00\xba\x1b\x00\x00\x00\x00\x00\x18\x5b\x96\xc4\xd6\x8b\x57\xf3\x80\xa1\x68\x9e\x3b\xfc\xc3\x8d\xb6\x... |
from django.shortcuts import render
from django.http import HttpResponse
from api.models import *
import requests
import json
import dateutil.parser
#Method:GET - Method to query by book name.
def external_books(request):
if request.method == "GET":
pass
else:
return HttpResponse("Error: ... |
import sys
a=[0]*1002
a[0]=1
a[1]=1
a[2]=1
for i in range(3,1002):
a[i]=(3*(2*i-3)*a[i-1]-(i-3)*a[i-2])//i
b=[0]*1002
b[0]=1
b[1]=1
b[2]=2
for i in range(3,1002):
b[i]=(2*i*(2*i-1)*(b[i-1]))//((i+1)*i)
for line in sys.stdin:
n=int(line)
if(n<3):
print(0)
else:
print(a[n]-b[n-1]) |
# %%
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import lightgbm as lgb
from mail import mail
# %%
user = pd.read_csv(
'data/train_preliminary/user.csv').sort_values(['user_id'], ascending=(True,))
Y_train_ge... |
from abc import ABCMeta
import math
from django.test import override_settings
from django.urls import reverse
from spacer.config import MIN_TRAINIMAGES
from api_core.tests.utils import BaseAPITest
from images.model_utils import PointGen
from images.models import Source
from lib.tests.utils import create_sample_image
... |
'''Matcher class'''
from easy_tokenizer.tokenizer import Tokenizer
from . import LOGGER
from .token_trie import TokenTrie
from .match_patterns import PatternsGZ
from .match_patterns import PatternsCT
from .match_patterns import PatternsNT
from .matched_phrase import MatchedPhrase
from . import data_utils
class Matc... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Projects, Profile, Rating, User
from .forms import NewProjectsForm, NewP... |
#!/usr/bin/env python
import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
from scipy.special import gammaln
import numpy.lib.recfunctions as recfunctions
def chooseBins(catalog = None, tag=None, binsize = None, upperLimit = None, lowerLimit = None):
i... |
"""
Created on April 4, 2020
Tensorflow 2.1.0 implementation of APR.
@author Anonymized
"""
import numpy as np
from elliot.recommender.base_recommender_model import BaseRecommenderModel
from elliot.recommender.recommender_utils_mixin import RecMixin
from elliot.recommender.test_item_strategy import test_item_only_fil... |
import logging
from django.conf import settings
from django.core.urlresolvers import reverse, NoReverseMatch
from debug_toolbar.toolbar.loader import DebugToolbar
from debug_toolbar.middleware import DebugToolbarMiddleware
from debug_logging.settings import LOGGING_CONFIG
logger = logging.getLogger('debug.logger')
f... |
import json
import os
import datetime
import tornado.web
import tornado.auth
import psycopg2.pool
from tornado import gen
from redshift_console import settings
from redshift_console import redshift
connection_pool = psycopg2.pool.ThreadedConnectionPool(settings.REDSHIFT['connection_pool_min_size'], settings.REDSHIFT['... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-04-30 15:40
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
dependencies = [
... |
#!/usr/bin/env python
#
# Copyright (c) 2010 Jiri Svoboda
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this li... |
"""Advent of Code 2015 Day 5."""
def main(file_input='input.txt'):
strings = [line.strip() for line in get_file_contents(file_input)]
nice_strings = get_nice_strings(strings, is_nice_string)
print(f'Nice strings: {len(nice_strings)}')
nice_strings_part_two = get_nice_strings(strings, is_nice_string_pa... |
#!/usr/bin/env python
"""
Re-write config file and optionally convert to python
"""
__revision__ = "$Id: wCfg.py,v 1.1 2012/03/30 17:46:35 paus Exp $"
__version__ = "$Revision: 1.1 $"
import getopt
import imp
import os
import pickle
import sys
import xml.dom.minidom
from random import SystemRandom
from ProdCommon.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-21 06:31
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0023_alter_page_revision_... |
"""Tests out the code for generating randomised test trades/orders.
"""
from __future__ import print_function
__author__ = 'saeedamen' # Saeed Amen / saeed@cuemacro.com
#
# Copyright 2017 Cuemacro Ltd. - http//www.cuemacro.com / @cuemacro
#
# See the License for the specific language governing permissions and limit... |
"""
hudai.resources.company_profile
"""
from ..helpers.resource import Resource
class CompanyProfileResource(Resource):
def __init__(self, client):
Resource.__init__(
self, client, base_path='/companies/{company_id}/profiles')
self.resource_name = 'CompanyProfile'
def fetch(self, ... |
import face_recognition
import cv2
import numpy as np
import os
import time
import pymysql
from datetime import datetime
import requests
import json
import csv
def save_csv_encodingVector():
train_path = 'C:/Users/dongyoung/Desktop/Git/face_recognition_project/examples/knn_examples/train/'
file_list = os.listd... |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
from project.server import app, db, bcrypt
from sqlalchemy import Column, Date, Integer, Text, create_engine, inspect
DONOR_MATCH = {
'O-': ['O-'],
'O+': ['O-', 'O+'],
'B-': ['O-', 'B-'],
'B+': ['O-', 'O+', 'B-', 'B+'],
'A-': ['O-', 'A-'],
'A+': ['O-', 'O+', 'A-', 'A+'],
'AB-': ['O-', 'B... |
#!/usr/bin/env python3
# Author: Katie Sexton
# Tested on: UniFi Cloud Key Gen2 Plus firmware version 1.1.10
# This script parses UniFi Management Portal's ump.js and outputs a list of API
# endpoints and associated HTTP methods
import argparse
import json
import sys
import os.path
import time
import re
VALID_METHOD... |
from datetime import datetime, timedelta
from os import getenv
from google.cloud import datastore
from telegram_send.telegram_send import send
import requests
YC_REQUEST_URL = getenv("YC_REQUEST_URL")
YC_AUTH_COOKIE = getenv("YC_AUTH_COOKIE")
YC_GOOD_ID = getenv("YC_GOOD_ID")
TG_TOKEN = getenv("TG_TOKEN")
TG_CHAT_ID ... |
# Copyright 2020 trueto
# 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... |
"""
Basic Path Resolver that looks for the executable by runtime first, before proceeding to 'language' in PATH.
"""
from aws_lambda_builders.utils import which
class PathResolver(object):
def __init__(self, binary, runtime, executable_search_paths=None):
self.binary = binary
self.runtime = runt... |
# Lint as: python3
# Copyright 2020 The AdaNet 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless requir... |
# -*- coding: utf-8; -*-
#
# Copyright (c) 2016 Álan Crístoffer
#
# 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, ... |
# Special vocabulary symbols. Artifact from the vocab system. I don't know a good way to replace this in a linear system
PAD_ID = 0.0
GO_ID = -5.0
EOS_ID = 2.0
UNK_ID = 3.0
data_linspace_tuple = (0, 100, 10000)
import numpy as np
import pandas as pd
import logging
logging.basicConfig(level=logging.INFO)
def x_sin(... |
from connect_ssh_class import ConnectSSH
import time
class CiscoSSH(ConnectSSH):
def __init__(self, ip, username, password, enable_password, disable_paging=True):
super().__init__(ip, username, password)
self._ssh.send("enable\n")
self._ssh.send(enable_password + "\n")
if disable_p... |
import torch
import torch.nn as nn
class Conv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding, stride=1, bias=True):
super(Conv2d, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias)
self.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains implementation to create Artella launchers
"""
from __future__ import print_function, division, absolute_import
__author__ = "Tomas Poveda"
__license__ = "MIT"
__maintainer__ = "Tomas Poveda"
__email__ = "tpovedatd@gmail.com"
import os
import sy... |
#!/usr/bin/python
import sys
d = {}
def myfun1(x):
return d[x][0]
def myfun2(x):
return d[x][1]
def myfun3(x):
return x[0]
for o in sys.stdin:
o = o.strip()
line_val = o.split(',')
bowler,batsman,runs,balls = line_val
runs = int(runs)
balls = int(balls)
key = (bowler,batsman)
if key in d:
d[key][0].append(... |
N = int(input())
c = 1
for i in range(1, 10):
for j in range(1, 10):
if c != N:
c += 1
continue
print(str(j) * i)
exit()
|
from django.contrib.auth import logout
from django.shortcuts import render, redirect
from website.views.decorators.auth import require_auth_or_redirect_with_return
@require_auth_or_redirect_with_return
def profile(request):
return render(request, "user/profile/index.html", {
'page_title': 'User Profile'
... |
from arm.logicnode.arm_nodes import *
class TranslateObjectNode(ArmLogicTreeNode):
"""Translates (moves) the given object using the given vector in world coordinates."""
bl_idname = 'LNTranslateObjectNode'
bl_label = 'Translate Object'
arm_section = 'location'
arm_version = 1
def arm_init(self... |
# standard imports
import glob
import pandas as pd
import os
import lightkurve as lk
# useful functions
def locate_files(tic,path=None):
'''
~ Locates TESS lightcurve files with filenames formatted from a mast bulk download.~
REQUIRES: glob
Args:
tic -(int or str)TESS TIC ID
... |
from flask import Flask, request, Response
from flask import render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
resp = Response("FLASK 2 DOCKERIZED")
return(resp)
@app.route('/vulnerabilities/mime-sniffing/')
def mimesniffing_home():
return render_template('mime_sniffing_demo.html')
@app.ro... |
#!/usr/bin/env python3
while True:
n = int(input("Please enter an Integer: "))
if n < 0:
continue #there will retrun while running
elif n == 0:
break
print("Square is ", n ** 2)
print("Goodbye")
|
import falcon
from expects import expect, be, have_key
# NOTE(agileronin): These keys are returned from the XKCD JSON service.
VALID_KEYS = [
'month',
'num',
'link',
'year',
'news',
'safe_title',
'transcript',
'alt',
'img',
'title'
]
class TestAPI:
"""API test class.
... |
####################################
# --- Day 19: Go With The Flow --- #
####################################
import AOCUtils
####################################
program = AOCUtils.loadInput(19)
pc, program = int(program[0].split()[1]), program[1:]
registers = [0 for _ in range(6)]
while registers[pc] < len(progr... |
"""
Tests
"""
def test_phat_persistence_diagram():
import numpy as np
from numpy.testing import assert_allclose
from dmt.complexes import MorseComplex
from dmt.phat_wrap import persistence_diagram
# Filtered circle
morse_complex = MorseComplex([[0, 0, 0, 1, 0, 1],
... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
import sys, os
"专门用于调用处理coco数据相关的脚本"
file_path = os.path.abspath(__file__)
sys.path.append(os.path.abspath(os.path.join(file_path, "..", "..")))
from code_aculat.data_analyse.data_analyse_coco import analyse_obs_size_after_resized, analyse_obs_ratio, check_annos, \
analyse_image_hw, analyse_obs_size, analyse_num_... |
import bcrypt
import pytz
from flask_sqlalchemy import SQLAlchemy
import datetime
from tzlocal import get_localzone
db = SQLAlchemy()
def insert_timestamp():
user_timezone = pytz.timezone(get_localzone().zone)
new_post_date = user_timezone.localize(datetime.datetime.now())
return new_post_date.astimezone... |
#!/usr/bin/env python
import yaml
import docker
import tempfile
import pdb
import sys
with open(sys.argv[1], 'r') as stream:
pkg = yaml.load(stream)
requires = " \\n".join(pkg['build_requires'])
pkg['requires'] = requires
container_tag = '/'.join([pkg['namespace'], pkg['name']])
skip_build = False
client = dock... |
''' File IO and miscellaneous utilities'''
__author__ = "Adam Hughes"
__copyright__ = "Copyright 2012, GWU Physics"
__license__ = "Free BSD"
__maintainer__ = "Adam Hughes"
__email__ = "hugadams@gwmail.gwu.edu"
__status__ = "Development"
import os
from pandas import DataFrame, read_csv, concat
from skspec.core.imk_uti... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Hammer logging code.
#
# See LICENSE for licence details.
__all__ = ['HammerVLSIFileLogger', 'HammerVLSILogging', 'HammerVLSILoggingContext', 'Level']
from .logging import HammerVLSIFileLogger, HammerVLSILogging, HammerVLSILoggingContext, Level
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.