text stringlengths 8 6.05M |
|---|
# class DjangoStudent():
# def __init__(self, name, laptop):
# self.name = name
# self.computer = laptop
# mystudent = DjangoStudent("Ejiro", "Macbook")
# print(mystudent.name)
# print(mystudent.computer)
# class car():
# def __init__(self, brand, price):
# s... |
class plugin:
handle = "plugin"
method = "string"
do_init = True
def init( self ):
print( "Plugin initialised" )
def run( server, nick, channel, message ):
if channel[0] == "#":
reply_to = channel
else:
reply_to = nick
server.send_message( reply_to, "You posted \"%s\" to %s." % ( message[:-1... |
import os
import sys
import argparse
def parse_arguments(argv):
parser = argparse.ArgumentParser(
description='Start Aurora server on http://<host>:<port>'
)
parser.add_argument(dest='path', nargs='?',
help='Path where to find the Aurora content',
... |
from django.apps import AppConfig
class VidhubConfig(AppConfig):
name = 'vidhub'
|
from os import error, path
import sys
sys.path.append(path.dirname(path.abspath(path.dirname(__file__))))
sys.path.append(path.dirname(path.dirname(path.abspath(path.dirname(__file__)))))
from hust_sc_gantry import beamline_phase_ellipse_multi_delta
from work.optim.A04geatpy_problem import *
from work.optim.A04run impo... |
def pillow(arr):
s1, s2 = arr
return bool({i for i, a in enumerate(s1) if a == 'n'} &
{i for i, b in enumerate(s2) if b == 'B'})
|
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
from typing import Dict, Sequence
import math
import os
import logging
from itertools import chain
import imageio
import numpy as np
from osmo_camera import tiff, raw, rgb
from osmo_camera.file_structure import (
create_output_directory,
get_files_with_extension,
datetime_from_filename,
)
def generate_... |
import client
import datetime
def sync_saved(sc, all_playlists):
"""Sync with changes made to saved tracks."""
print('=== Syncing Saved Tracks ===')
saved_tracks = set(sc.get_all_saved_tracks())
playlist_all_uri = all_playlists['all']
playlist_all_tracks, _ = sc.get_all_songs_in_playlist(playlist_... |
import numpy as np
import builtins
def digitsum(n):
return sum([int(i) for i in str(n)])
multiplier = list(range(1,100))
nums = [1 for i in multiplier]
maxsum = 0
for i in multiplier:
for j, val in enumerate(nums):
temp = val * multiplier[j]
nums[j] = temp
digits = digitsum(temp)
... |
# How many circular primes below 1,000,000? Circular if all rotations of digits are prime.
# ====================================================================================
# Want to grasp this one:
import eulerlib
def compute():
isprime = eulerlib.list_primality(999999) # List of True, False,.... for whether ... |
#!/usr/bin/env python
"""
OTFMaker.py: Module for creating basic on-the-fly primitives. Provides a basic class hierarchy
for constructing geometry from streams of vertex coordinates and triangle faces.
"""
__author__ = "John McDermott"
__email__ = "JFMcDermott428@gmail.com"
__version__ = "1.0.0"
__stat... |
import requests
import sys
from argparse import Action
from argparse import ArgumentParser
class SanitizeInput(Action):
def __call__(self, parser, namespace, values, option_string=None):
if 'http' in values or values.startswith('/'):
setattr(namespace, self.dest, values)
elif 'file' i... |
#%%
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon, QFont, QColor
from PyQt5 import QtWidgets
from utils import utils
from config import ConfigConstants
from config.Language import language as LG
from globalObjects import GlobalData
import numpy as np
import pickle
class ParameterDialog:
def __in... |
# coding:utf-8
import time
import socket
import struct
def disp_binary(data: bytes, split: str = r'\x', order: str = '>', sign: str = 'B'):
"""
显示bytes字符串
:param data: 源bytes
:param split: 字符串分隔符,默认为\\x
:param order: data struct.unpack解码顺序
:param sign: data struct.unpack解码符号如B,H等
:return: ... |
import newt,tweepy,time
class StreamListener(tweepy.StreamListener):
def on_status(self, status):
try:
print status.text,str(self.count)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
self.count=self.count-1
if sel... |
import numpy as np
from _neworder_core import MonteCarlo # type: ignore[import]
def as_np(mc: MonteCarlo) -> np.random.Generator:
"""
Returns an adapter enabling the MonteCarlo object to be used with numpy random functionality
"""
class _NpAdapter(np.random.BitGenerator):
def __init__(self, rng: MonteCar... |
"""Test the PackageTask class"""
import os
import tempfile
import shutil
import time
from nose.tools import assert_equals, assert_raises, assert_not_equals
from nose.tools import assert_not_in, assert_in
from ckanpackager.tasks.package_task import PackageTask
from ckanpackager.lib.utils import BadRequestError
from cka... |
from flask import Flask, jsonify
application = Flask(__name__)
@application.route("/")
def hello():
return "Hello World!"
@application.route("/api/v2/test")
def test():
return jsonify("{\"hello\": \"World!\"}")
if __name__ == "__main__":
application.run()
|
import xml.dom.minidom
import os
file_path = os.path.join(os.path.dirname(__file__), 'movies.xml')
print(file_path)
class GetXml(object):
def __init__(self, filepath):
self.filepath = filepath
self.file = xml.dom.minidom.parse(self.filepath) # 打开xml文件
self.DOMTree = self.file.documentEl... |
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
from django.contrib.auth.models import User
from .models import Profil
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Pro... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 28 13:46:18 2021
@author: ad
"""
page_list = [] #페이지 request 리스트 ['page_num','state_time']
page_queue = [] #대기큐
MM=[] #프레임
t = 0 #가상의 현재 시간
Fault = 0
#파일 read
file = input("읽을 파일을 입력: ")
f = open(f"./example_page/{file}.txt",'r')
lines = f.readlines()... |
class Solution(object):
def heapsort(self, list):
def heapify(list, len, a):
#重複步驟後,heapify只會做最前面三項(0,1,2)的排序
largest = a
left = 2*a+1
right = 2*a+2
if left < len and list[largest] < list[left] :
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-12 16:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20160611_1745'),
]
operations = [
... |
import click
from src.input.DefaultInput import DefaultInput
class CliInput(DefaultInput):
def start(self):
while True:
click.echo("Waiting for pressing h or l or q to abort...")
c = click.getchar()
click.echo()
if c == 'h':
self.down()
... |
l1 = ['abcd', 786, 2.23, 'john', 70.2]
l2 = [123, 'apples']
print l1
print l1[0]
print l1[1:3]
print l1[2:]
print l2 * 2
print l1 + l2
print l1[5:]
|
from flask import jsonify
from flask import request
from flask import Blueprint
from ..controllers.projects import get_users_by_project
from ..controllers.projects import get_project_by_id
from ..controllers.projects import register_project
from ..controllers.submissions import get_project_submissions
from flask_jwt im... |
import math
class Pagination:
def __init__(self, pagination_query, items_per_page = 50, range_size = 7):
self.items_per_page = items_per_page
self.range_size = range_size
# self.alchemy_service = alchemy_service
self.pagination_query = pagination_query
self.item_count = ... |
import sys
try:
import phi
except ImportError:
print("phiflow is not installed. Visit https://tum-pbs.github.io/PhiFlow/Installation_Instructions.html for more information."
"\nrun 'pip install phiflow' to install the latest stable version or add the phiflow source directory to your Python PATH.", fil... |
from girder.models.setting import Setting
from girder.plugins.imagespace.settings import ImageSpaceSetting
class FlannSetting(ImageSpaceSetting):
requiredSettings = ('IMAGE_SPACE_FLANN_INDEX',)
def validateImageSpaceFlannIndex(self, doc):
return doc.rstrip('/')
|
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
soma = n1 + n2
print("A soma dos valores é {}".format(soma))
|
# Generated by Django 2.1.7 on 2019-03-11 20:37
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
oper... |
import requests
import json
import csv
from time import sleep
url = "https://www.mcdonalds.com.cn/ajaxs/search_by_point"
headers = {
'Connection': 'Keep-Alive',
'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 10:20:31 2020
@author: anusk
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
def EBMA(targetFrame, anchorFrame, blocksize):
accuracy = 1
p =16
frameH, frameW = anchorFrame.shape
print(anchorFrame.shape)
predictFrame = np.zero... |
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = staticfile... |
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from copy import deepcopy, copy
import timeit
import time
import multiprocessing
from sklearn import model_selection
from tqdm import tqdm
from sklearn.model_selection import ParameterGrid
from .BaseCrossVal import BaseCrossVal
from ..utils imp... |
import datetime
from typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
import pandas as pd
from wfdb.io import _signal
from wfdb.io import util
from wfdb.io.header import HeaderSyntaxError, rx_record, rx_segment, rx_signal
"""
Notes
-----
In the original WFDB package, certain fields have de... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Found(models.Model):
found_name = models.CharField(u'项目名称', max_length=256)
manager = models.CharField(u'负责人', max_length=20)
money = models.FloatField(u'金额', blank=True, null=T... |
import random
import string
import subprocess
import itertools
import types
import prettytable
import re
def randstr(n=4, fixed=True, charset=None):
if not n:
return ''
if not fixed:
n = random.randint(1, n)
if not charset:
charset = string.letters + string.digits
return ''.... |
from PIL import ImageGrab as IG
import pyautogui as pa
import sys
import os
import time
import re
pa.FAILSAFE = True
sec_between_keys = 0.25
sec_between_term = 3
sec_sleep = 0.5
#스크린샷
def screenGrab():
box = ()
im = IG.grab(box)
im.save(os.getcwd() + '\\img\\full_snap__' + str(int(time.time())) + '.png',... |
from django.shortcuts import render, get_object_or_404
from .models import Blog
def all_blogs(response):
instance = Blog.objects.all()
return render(response, "one.html", {'returned' : instance})
def details(response, id):
id = get_object_or_404(Blog, pk = id)
return render(response, "details.html", {... |
"""@package docstring
Provides the base request handler.
"""
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
import openradar.db
import datetime
import o... |
#!/usr/bin/env python
import numpy as np
from scipy.signal import hilbert
from scipy import integrate
def namodel_py(effadse, wdos, delta, ergy):
fermi = np.argmax(ergy >= 0)
htwdos = np.imag(hilbert(wdos, axis=0))
lorentzian = (1/np.pi) * (delta)/((ergy - effadse)**2 + delta**2)
dos_ads = wdos/((erg... |
# 反转一个单链表。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->NULL
#
# 进阶:
# 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
# Related Topics 链表
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
... |
"""
Este archivo ejemplifica la creacion de una topologia de mininet
En este caso estamos creando una topologia muy simple con la siguiente forma
host --- switch --- switch --- host
"""
import os
from mininet.topo import Topo
class Example(Topo):
def __init__(self, half_ports = 2, **opts):
Topo.__in... |
from psycopg2.extras import RealDictCursor
import database_common
import bcrypt
import os
def random_api_key():
"""
:return: salt in secret key
"""
return os.urandom(100)
# query func verific daca username este deja in BD
@database_common.connection_handler
def username_exists(cursor: RealDictCursor... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model
User = get_user_model()
class SignUpForm(UserCreationForm):
"""Prepares help tex... |
import cython_mpi4py
cython_mpi4py()
|
import torch
import torchvision
from PIL import Image
import torchvision.transforms as transforms
def get_detection_model():
model = torchvision.models.detection.__dict__['maskrcnn_resnet50_fpn'](num_classes=91,
pretrained=True)
model.to('cpu')
... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import output
from esphome.const import CONF_ID
empty_binary_output_ns = cg.esphome_ns.namespace('empty_binary_output')
EmptyBinaryOutput = empty_binary_output_ns.class_('EmptyBinaryOutput', output.BinaryOutput,
... |
import lasagne
from utct.common.functor import Functor
class MnistModel(Functor):
def __init__(self):
super(MnistModel, self).__init__()
#self.param_bounds = {
# #'mdl_conv1a_nf': (6, 128),
# #'mdl_conv1b_nf': (6, 128),
# #'mdl_conv2a_nf': (6, 128),
# ... |
"""
Examen Parcial 3
Carrillo Medina Alexis Adrian (CMAA)
Nombre del programa: Parcial3.py
"""
#----- Seccion de bibliotecas
import numpy as np
import matplotlib.pyplot as plt
#----- Codigo
# La validacion se encuentra en el metodo main
#---------- Metodos auxiliares -----------
def sustDelante(A,b):
# Vect... |
"""Common functionality for testing the v1 API."""
from ..base import TestCase as BaseTestCase
from ..base import APITestCase as BaseAPITestCase
class NamespaceMixin(object):
"""Designate the namespace for tests."""
namespace = 'v1'
__test__ = True # Run these tests if disabled in base class
class Te... |
"""
script to scrape a website for doctor addresses
"""
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
with webdriver.Chrome() as driver:
# ini... |
def num_divisible_room(x, y, n, m):
# x, y are the dividing factors
# n is total number of floors in the building
# m_k is number of rooms on floor k
room_nums = []
for floor in range(0, n):
for room in range(0, int(m[floor])):
room_nums.append((floor + 1) * 100 + (room + 1))
counter = 0
for room_num in... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_window.ui',
# licensing of 'main_window.ui' applies.
#
# Created: Thu Jan 2 17:55:43 2020
# by: pyside2-uic running on PySide2 5.9.0~a1
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, QtGui, ... |
from api.utils import *
def fill_match_info(page_url, match_info, start_time=0, end_time=90):
all_matches = get_all_matches(page_url, match_info['league'])
home_team_matches, guest_team_matches = all_matches['home_team_matches'], all_matches['guest_team_matches']
home_team_actions_list = []
guest_tea... |
#!/usr/bin/env python3
import boto3
import botocore
import json
import re
import argparse
def boto3_client(resource):
"""Create Boto3 client."""
return boto3.client(resource)
def s3_list_buckets():
"""Gets all S3 buckets and adds to a set"""
bucket_list = set()
s3_bucket = boto3_client('s3').list... |
#!/usr/bin/python
import math
primes = []
def factors(num):
total = 0
r = num
for p in primes:
if p ** 2 > num:
return total + 1
f = False
while r % p == 0:
f = True
r //= p
if f:
total += 1
if r == 1:
retur... |
protocol_template = ['Protocol: ',
'Prefix: ',
'AD/Metric: ',
'Nex-Hop: ',
'Last update: ',
'Outbound Interface: ']
with open('ospf.txt', 'r') as f:
for line in f:
temp = line.replace('O', 'OSPF')
temp = temp.rstrip().split()
temp[2] = temp[2].strip('[]')
temp[4] = temp[4].rstr... |
# Catherine Maloney - CS 110 HW6
# I pledge my honor that I have abided by the Stevens honor system.
# Problem Two: Write a program that accepts a date in the form of month/day/year
# and outputs whether or not the date is valid. For example, 7/6/1956 is valid
# but 9/31/2000 is not. (Do you know why??). To simplify t... |
#!/usr/bin/env python
"""
This module provides a python wrapper for volume rendering in GLSL using texture lookup tables
and viewport-aligned slice plane geometry. The module also provides a convenient interface object
for initializing sampling geometry and easily configuring the shader uniform values on the fl... |
import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# CreateSamples
#
class CreateSamples(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/S... |
from neuron import *
from functions import *
from connection import *
class Layer(object):
"""docstring for Layer"""
def __init__(self):
self.neurons = []
def activate(self, INPUTS, HIDDL = False):
i = 0
out = []
if not HIDDL:
for N in self.neurons:
N.activate(INPUTS[i])
i += 1
else:
for N ... |
"""Output samples of various Colorgorical settings."""
import itertools as it
import json
import numpy as np
import os
from os import listdir
from os.path import isfile, join
import datetime
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import gridspec
import matplotlib.tri as tr... |
from tkinter import * # import tkinter
root = Tk() # creates tkinter windows and sets it to the root variable
def printhi(): # Creates a defintion (A definiton is a code which can be called on)
print("Hi") # The code in the definition in this case it prints Hi
title_label = Label(root,text="This is a test") # create... |
from django.shortcuts import render, redirect,reverse
import MySQLdb
import pymysql
import mysql.connector
from django.http import HttpResponse
from Django_shop.settings import *
# Create your views here.
from .myclass import signin, salesInfo, shop_cashier
# Create your views here.
# =========实例化身份验证的对象=======
logi... |
inputFile = open("/Users/samuelcordano/Documents/adventOfCode/Day5_BinaryBoarding/inputFile.txt","r")
Lines = inputFile.readlines()
def problem2():
"""
What is the ID of your seat?
"""
listofIDs = []
counter =0
#Get list of IDs
for line in Lines:
counter +=1
currentInput ... |
import os
__version__ = '2016.0'
here = os.path.dirname(__file__)
def get_theme_dir():
return here
|
# Generated by Django 3.2.3 on 2021-05-31 12:32
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
("images", "0003_alter_image_created_at"),
]
operations = [
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
"""
try:
from NaoCreator.nao_scenario_creator import search_face, i_meet_you
from NaoCreator.setting import Setting
from time import sleep
from PlayerManager.player_manager import Player
... |
# Generated by Django 2.0.2 on 2018-07-14 03:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bot', '0002_ordertext_userorder'),
]
operations = [
migrations.AlterField(
model_name='userorder',
name='mail',
... |
# Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import logging
import traceback
from django.conf import settings
from django.core.management.base import BaseCommand
from data_aggregator.management.commands._mixins import RunJobMixin
from data_aggregator.models import AnalyticType... |
import sys
sys.path.append('../src')
from grafo import Grafo
from dijkstra import Dijkstra
g = Grafo()
g.agregar_vertice(0)
g.agregar_vertice(1)
g.agregar_vertice(2)
g.agregar_vertice(3)
g.agregar_vertice(4)
g.agregar_vertice(5)
g.agregar_arista_no_dirigida(0, 1, 7)
g.agregar_arista_no_dirigida(0, 2, 9)
g.agregar_aris... |
# -*- coding: utf-8 -*-
import os
version_info = (0, 0, 7)
__version__ = ".".join(map(str, version_info))
__path = os.path.dirname(__file__)
class Mixer(object):
'''Takes data chunks(requests) from sources, mix data in given proportion
and yields chunks.
Attributes:
num_req: int, total requests ... |
#!/usr/bin/env python3
import gzip
import sys
# Write a program that computes typical stats for sequence files
# See below for command line and output
"""
python3 fasta_stats.py transcripts.fasta.gz
Count: 232
Total: 278793
Min: 603
Max: 1991
Mean: 1201.7
NTs: 0.291 0.218 0.210 0.281
"""
|
import unittest
import attachment
import email_parser
import pop3
import threading
import socket
import ssl
def create_server():
def create_sock():
# server = ssl.SSLSocket(socket.socket()) # socket.AF_INET, socket.SOCK_STREAM
# server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... |
#!/usr/bin/env python3
import sys
import subprocess
filename=sys.argv[1]
with open(filename) as file:
lines=file.readlines()
for line in lines:
oldfile=line.strip()
newfile=line.strip().replace("jane", "jdoe")
result = subprocess.run(["mv", oldfile, newfile], capture_output=True)
print("Oldfile: {} Newfile... |
##
## Copyright (c) 2014 Rodolphe Breard
##
## Permission to use, copy, modify, and/or distribute this software for any
## purpose with or without fee is hereby granted, provided that the above
## copyright notice and this permission notice appear in all copies.
##
## THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR D... |
from smbus import SMBus
import time
addr = 0x8 # bus address
bus = SMBus(1) # indicates /dev/ic2-1
while True:
bus.write_byte(addr, 0x41) # switch it on
time.sleep(0.01)
|
import logging
import sys, os
from abc import abstractmethod
import eons
from .IOFormatFunctor import IOFormatFunctor
class InputFormatFunctor(IOFormatFunctor):
def __init__(self, name=eons.INVALID_NAME()):
super().__init__(name)
#self.data will be returned, so we shouldn't be asking for i... |
#plot_ts_hydrographs.py
#python script to PET data files and create PET comparison plots
#Author: Ryan Spies
#rspies@lynker.com
print("Start Script")
import os
import matplotlib.pyplot as plt
from pylab import *
from matplotlib.ticker import AutoMinorLocator
import pandas as pd
maindir = os.getcwd()
################... |
#!/usr/bin/env python
from Tkinter import *
import tkMessageBox
import tkSimpleDialog
import logic
import math
def error(message):
tkMessageBox.showerror(message=message)
class Heading(Label):
def __init__(self, parent, **kwargs):
Label.__init__(self, parent, font=('Sans-serif', 16, 'bold'), **kwargs... |
from itertools import combinations
lst = [2, 5, 9, 4]
for subset in combinations(lst, 2):
print(subset)
|
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #alistirma13
>>>
>>> for a in range(1,10):
for b in range(0,10):
for c in range(1,10):
for d in range(0,10):
if 1000*a+100*b+1... |
import warnings
from typing import Callable, List, Optional, Sequence, Tuple, Union
import torch
from torch import Tensor
from ..utils import _log_api_usage_once, _make_ntuple
interpolate = torch.nn.functional.interpolate
class FrozenBatchNorm2d(torch.nn.Module):
"""
BatchNorm2d where the batch statistics... |
#!/usr/bin/env python
'''
script.py: part of singularity command line tool
Runtime executable, "shub"
'''
from singularity.package import package, docker2singularity
from singularity.runscript import get_runscript_template
from singularity.utils import check_install
from singularity.app import make_tree
from glob im... |
import re
# 1. Amazon.com
str = "1-16 of 402 results for"
match = re.findall(r'([0-9\.\,]+) results', str)
print(int(match[0].replace(".", "").replace(",", "")))
# 2. Amazon.fr
str = "1-16 sur 28 résultats pour"
match = re.findall(r'([0-9\.\,]+) résultats', str)
print(int(match[0].replace(".", "").replace(",", "")))
... |
def MAPE(pred, test):
pred, test = np.array(pred), np.array(test)
sum = 0
for i in range(7):
if test[i] != 0:
sum += abs((test[i] - pred[i]) / test[i])
return (sum / 7) * 100
def X_generator(X):
X_1, X_2, X_3, X_4, X_5, X_6, X_7, X_8, X_9, X_10, X_sqrt = X, np.power(X, 2), np.po... |
import psutil
def count(iter): # used for counting instances in iterable
return sum(1 for _ in iter)
def list_processes(procs):
for proc in procs:
try:
print("Name: {} PID: {}".format(proc.name(), proc.pid))
# print(len(proc.open_files()))
# print(proc.open_files... |
import graphene
import CookBook.schema
class Query(CookBook.schema.Query, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query) |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-08-24 08:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CctvW... |
# Pass along HARM's own diagnostics for comparison
# TODO implement
#diag = io.load_log(path)
#out_full['t_d'] = diag['t']
#out_full['Mdot_d'] = diag['mdot']
#out_full['Phi_d'] = diag['Phi']
#out_full['Ldot_d'] = diag['ldot']
#out_full['Edot_d'] = diag['edot']
#out_full['Lum_d'] = diag['lum_eht']
#out_full['divbmax_... |
from . import operaciones
from . import tipoOperacion
from . import tipoTipoOperacion |
import define
from binance_f import RequestClient
from binance_f.constant.test import *
from binance_f.base.printobject import *
from binance_f.model.constant import *
import time
import cancelorders
import balance
def closetrade(symbol , data , position , intrade , balancemoney , file ,signal , symbolintrade):
if si... |
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
config.add_section('main')
config.set('main', 'number_of_ISPs', '4')
config.set('main', 'number_of_SIs', '10')
config.set('main', 'number_of_consumers', '400')
config.set('main', 'number_of_steps', '20')
config.set('main', 'market_... |
from datetime import date
from unittest import TestCase
import pytest
from mock import patch
from .helpers import example_file
from popolo_data.importer import Popolo
from approx_dates.models import ApproxDate
EXAMPLE_SINGLE_MEMBERSHIP = b'''
{
"persons": [
{
"id": "SP-937-215",
... |
from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
import re
email_regex = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = "secret"
mysql = MySQLConnector(app,'emails_assignment')
def success():
... |
from django.urls import path, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'jogo', views.JogoViewSet, 'jogo')
router.register(r'simular', views.ExecutarJogoViewSet, 'simular')
urlpatterns = [
path('', include(router.urls))
]
|
from .base_processing_node import BaseProcessingNode, ProcessingArtifact
class DerivedPreviewProcessingNode(BaseProcessingNode):
def __init__(self, available_artifacts, outputs):
super(DerivedPreviewProcessingNode, self).__init__(available_artifacts, outputs)
self.fmt = 'json'
def get_artifac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.