text stringlengths 2 999k |
|---|
from sys import argv
script, filename = argv
print "We are going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print ... |
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... |
'''
Fama-Macbeth Regerssion Fama-Macbeth 回归
Following Two step 分为两步
1. specify the model and take cross-sectional regression 确定模型,进行截面回归
2. take the time-series average of regress coefficient 对系数在时间序列上取平均
For more academic reference:
Empirical Asset Pricing: The Cross Section of Stock Returns. Bali, Engle, Murray. 2... |
from api import db
import datetime
class BlogpostModel(db.Model):
"""
Blog Model
"""
__tablename__ = 'blogpost'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text)
content = db.Column(db.Text, nullable=False)
... |
# -*- test-case-name: twisted.scripts.test.test_scripts -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Post-install GUI to compile to pyc and unpack twisted doco.
"""
import sys
import zipfile
import py_compile
# we're going to ignore failures to import tkinter and fall b... |
# This logic is to help convert address: str to address: bytes
# copied from https://github.com/cosmos/cosmos-sdk/blob/main/types/address.go
from typing import List
import bech32
def address_to_bytes(address: str) -> bytes:
_prefix, b = bech32.bech32_decode(address)
b = from_words(b)
return bytes(b)
... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..brains import landmarksConstellationAligner
def test_landmarksConstellationAligner_inputs():
input_map = dict(
args=dict(argstr="%s",),
environ=dict(nohash=True, usedefault=True,),
inputLandmarksPaired=dict(argstr="--inputLandmar... |
import cv2
import numpy as np
# Create our body classifier
body_classifier = cv2.CascadeClassifier('haarcascade_fullbody.xml')
# Initiate video capture for video file, here we are using the video file in which pedestrians would be detected
cap = cv2.VideoCapture(0)
# Loop once video is successfully loaded
... |
#!/usr/bin/python
#coding:utf8
#这几行代码是从 Coursera 课程 Algorithms for DNA Sequencing 里学到的,很漂亮的方法。一个是利用字典来转换碱基,一行代码搞定了之前要进行四次判断才能搞定的事;二是 t = Complement[base] + t,直接得到反转后的序列,省去 reverse 一道工序。
def reverseComplement(s):
complement = {'A':'T', 'T':'A', 'G':'C', 'C':'G'}
t = ''
for base in s:
t = c... |
from django.conf.urls import url
from django.views.generic.base import TemplateView
app_name = 'another_app'
urlpatterns = [
url(r'^page1/$', TemplateView.as_view(template_name='another_app/page1.html'), name='page1'),
url(r'^page2/$', TemplateView.as_view(template_name='another_app/page2.html'), name='page2... |
import os
'''
Let's see how we could test code using
filesystem and stdout stream.
'''
def tree(path, sizes=False):
def enum_last(list_):
length = len(list_)
islast = [False] * (length - 1) + [True] * bool(length)
return [e for e in zip(list_, islast)]
def print_dir(dir_path, lasts):
... |
from datetime import datetime
import uuid
def get_current_date_len8():
"""
:return: yyyymmdd
"""
date_current = datetime.now().strftime("%Y%m%d")
return date_current
def get_current_date_len10():
"""
:return: yyyy-mm-dd
"""
date_current = datetime.now().strftime("%Y-%m-%d")
r... |
from django import forms
from django.contrib.auth.models import User
from fishbook.models import WebUser
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password',)
class WebUserForm(forms.Mode... |
tabby_rat="\t I'm tabbed in"
persian_rat="I'm slip \n on a line"
backslash_rat="I'm \\ a \\ cat"
fat_rat="""
I'll do a list
\t* Cat food
\t* Fishes
\t* Catnip\n\t* Grass
"""
print(tabby_rat)
print(persian_rat)
print(backslash_rat)
print(fat_rat)
|
"""使用心知天气数据查询天气"""
"https://www.seniverse.com/"
import requests
import json
KEY = '###############' # API key(私钥)
UID = "###############" # 用户ID, TODO: 当前并没有使用这个值,签名验证方式将使用到这个值
LOCATION = 'beijing' # 所查询的位置,可以使用城市拼音、v3 ID、经纬度等
API = 'https://api.seniverse.com/v3/weather/daily.json' # API URL,可替换为其他 URL
UNIT = 'c... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('C6A', ['C8pro'])
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C3ub')
Monomer('C3A', ['Xiap', 'ParpU', 'C6pro'])
Mo... |
#!/usr/bin/env python3
import socket
import logging
from colorlog import ColoredFormatter
def get_ip_from_hostname(hostname: str) -> str or None:
try:
ip = socket.gethostbyname(hostname)
except socket.gaierror as e:
logging.error(e)
return None
else:
return ip
def init_l... |
import numpy as np
import sys
class Point(object):
""""A point in the plane.
Attributes
----------
x, y : float
Point coodinates
"""
def __init__(self, x, y):
self.x = x
self.y = y
class Distance(object):
"""Distance between two points.
... |
import time
import gevent
from copy import copy
import events
from exception import StopLocust
from log import console_logger
STATS_NAME_WIDTH = 60
class RequestStatsAdditionError(Exception):
pass
class RequestStats(object):
requests = {}
total_num_requests = 0
global_max_requests = None
global_... |
from time import sleep
from approxeng.input.controllers import find_matching_controllers, ControllerRequirement
from approxeng.input.selectbinder import bind_controllers
discovery = None
# Look for an attached controller, requiring that it has 'lx' and 'ly' controls, looping until we find one.
while discovery is Non... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Main OpenQA training and testing script."""
import argparse
import torch
import numpy as np
import json
import os
import sys
import subprocess
import logging
import random
import regex as re
sys_dir = '/data/disk2/private/linyankai/OpenQA'
sys.path.append(sys_dir)
... |
#!/usr/bin/env python
"""Cross-entropy loss layer for MXNet.
"""
import os
import numpy as np
import mxnet as mx
# ref: http://mxnet.io/how_to/new_op.html
class CrossEntropyLoss(mx.operator.CustomOp):
"""An output layer that calculates gradient for cross-entropy loss
y * log(p) + (1-y) * log(p)
for label... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
class Constants:
RTM_READ_DELAY = 1 # 1 second delay between reading from RTM
|
import sys
import os
import pip
import time
if not os.geteuid() == 0:
sys.exit('You must Run this Script as ROOT!')
try:
os.system('apt-get install python-pip')
os.system('easy_install pip')
os.system('apt-get install nmap')
os.system('apt-get install curl')
install = os.system("apt-get update && apt-get instal... |
from abc import abstractmethod
from .abstract_problem import AbstractProblem
class TimeDependentProblem(AbstractProblem):
@property
@abstractmethod
def temporal_variable(self):
pass
|
import logging
from datetime import date, datetime
from os import makedirs
from os.path import join, isdir
from .settings import log_dir
def ensure_dir_exists(dir_path):
if not isdir(dir_path):
makedirs(dir_path)
def with_logging(do):
ensure_dir_exists(log_dir)
# Log everything to a rotating fi... |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name = 'pySGDabao',
packages = ['pySGDabao'],
version = '1.0.1',
license='Apache License 2.0',
description = 'A library for your Singapore food delivery needs',
long_description = long_descri... |
"""
#################################
Pre-requisites needed
#################################
If you are missing any of the following you can install with:
pip install $name
Example: pip install csv
OR if you are using pip3
pip3 install $name
Example: pip3 install csv
"""
import csv
import datetime
import o... |
import graphene
import graphql_jwt
import links.schema
import users.schema
class Query(users.schema.Query, links.schema.Query, graphene.ObjectType):
pass
class Mutation(users.schema.Mutation, links.schema.Mutation, graphene.ObjectType):
token_auth = graphql_jwt.ObtainJSONWebToken.Field()
verify_token =... |
from extensions.base.burpextensionapi import BurpExtensionApi
class HttpListener(BurpExtensionApi):
NAME = 'some http listener (changeme)'
# tools, as defined by burp
# can be used to restrict handling of request/response to a specific tool
TOOL_COMPARER = 512
TOOL_DECODER = 256
TOOL_EXTENDE... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
"""TODO(xtreme): Add a description here."""
from __future__ import absolute_import, division, print_function
import csv
import glob
import json
import os
import textwrap
import six
import nlp
# TODO(xtreme): BibTeX citation
_CITATION = """\
@article{hu2020xtreme,
author = {Junjie Hu and Sebastian Ruder a... |
import numpy as np
from deerlab import mixmodels
from deerlab.dd_models import dd_gauss, dd_rice
def test_gaussgauss():
# ======================================================================
"Check the construction of a mixed model of Gaussian-Gaussian"
r = np.linspace(2,6,100)
parIn1 = [3, 0.5... |
# -*- coding: utf-8 -*-
from .base_case import ChatBotTestCase
from chatterbot.conversation import Statement, Response
class ChatterBotResponseTests(ChatBotTestCase):
def setUp(self):
super(ChatterBotResponseTests, self).setUp()
response_list = [
Response('Hi')
]
sel... |
# -*- coding: utf-8 -*-
"""
transitions.extensions.nesting
------------------------------
Adds the capability to work with nested states also known as hierarchical state machines.
"""
from copy import copy, deepcopy
from functools import partial
import logging
from six import string_types
fr... |
# Generated by Django 2.2.7 on 2019-12-11 22:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('board', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='cfuser',
name='grade',
field=... |
from socket import *
import time
# Local
serverName = '127.0.0.1'
serverPort = 12000
# Public DNS server
pubName = '114.114.114.114'
pubPort = 53
# Cache
caches = []
cacheTTL = 3600 # one hour
"""
Header
ID 2bytes
Flags 2bytes
Questions, Answer RRs, Authority RRs, Addition RRs 8bytes
Body
QName length is not fixe... |
# Generated by Django 2.0.6 on 2018-11-01 14:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='verify_code',
fie... |
#!/usr/bin/env python
#
# Copyright 2015 Google Inc. 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 requir... |
"""This module contains the meta information of ConfigResolveClass ExternalMethod."""
from ..imccoremeta import MethodMeta, MethodPropertyMeta
method_meta = MethodMeta("ConfigResolveClass", "configResolveClass", "Version142b")
prop_meta = {
"class_id": MethodPropertyMeta("ClassId", "classId", "NamingClassId", "V... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import re, ast
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in salary_calculation/__init__.py
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('salary_calcu... |
#
# GDAX/PublicClient.py
# Daniel Paquin
#
# For public requests to the GDAX exchange
import requests
class PublicClient(object):
"""GDAX public client API.
All requests default to the `product_id` specified at object
creation if not otherwise specified.
Attributes:
url (Optional[str]): API... |
# This module serves as a Singleton that will store
# a registry of the ouptut files needed
import json
from firexapp.submit.uid import Uid
import os
class KeyAlreadyRegistered(Exception):
pass
class KeyNotRegistered(Exception):
pass
class Singleton(type):
_instances = {}
def __call__(cls, *args... |
# mininode.py - RavenDark P2P network half-a-node
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# This python code was modified from ArtForz' public domain half-a-node, as
# found in the mini-node branch of http://github... |
from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
class CommandTests(TestCase):
def test_wait_for_db_ready(self):
"""
Tests the wait for db command when the db is available
"""
... |
# Generated by Django 3.0.7 on 2021-05-10 22:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoFi... |
from django.core.exceptions import SuspiciousOperation
class DisallowedModelAdminLookup(SuspiciousOperation):
"""Invalid filter was passed to admin view via URL querystring"""
pass
class DisallowedModelAdminToField(SuspiciousOperation):
"""Invalid to_field was passed to admin view via URL query string""... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="ppt2pdf", # Replace with your own username
version="0.0.3",
author="Swarag Narayanasetty",
description="Converts PPT to PDF",
long_description=long_description,
long_description_conten... |
import time
import math
from typing import Optional
from pyglet import gl
import glm
from lib.opengl import *
from lib.math import FollowFilter
from .._path import ASSET_PATH
from ..game import Game
from .rs import GameRenderSettings
from .tilemap_node import TileMapNode
from .wangtex_node import WangTextureNode
from... |
from django import forms
from django.forms.models import modelform_factory
from django.utils.translation import ugettext_lazy as _
from wagtail.admin import widgets
from wagtail.admin.forms.collections import (
BaseCollectionMemberForm, collection_member_permission_formset_factory)
from wagtail.documents.models im... |
# sqlalchemy/pool.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Connection pooling for DB-API connections.
Provides a number of connection p... |
from dask_gateway.scheduler_preload import make_gateway_client, GatewaySchedulerService
from distributed import Security, Scheduler, Worker
from distributed.core import Status
from tornado import gen
from .local import UnsafeLocalBackend
__all__ = ("InProcessBackend",)
class InProcessBackend(UnsafeLocalBackend):
... |
"""
Serve web page and handle web sockets using Tornado.
"""
import json
import time
import asyncio
import socket
import mimetypes
import traceback
import threading
from urllib.parse import urlparse
# from concurrent.futures import ThreadPoolExecutor
import tornado
from tornado import gen, netutil
from tornado.web im... |
# Copyright (C) 2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import logging
import os.path
import subprocess
import _winreg
from lib.common.abstracts import Auxiliary
from lib.common.registry import set_regkey
from l... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-18 01:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exploration', '0037_shardhaven_weight_no_treasure_backtrack'),
]
operations = [
... |
import Gradient_Descent_Solver as GDS
# #############################################################################
# Setup
X = [[1, 2, 4],
[1, 4, 16],
[1, 6, 36]]
LR = 0.001
# Cheat to get Y easier
Y = [[0], [0], [0]]
wa = [1.0, 0.5, 0.25] # with numpy [[1.0], [0.5], [0.25]]
gds = GDS.Gradient_Descent_S... |
"""
A module to demonstrate global variables.
Author: Kyle Gortych
Date: 5/21/2021
"""
# The global variable
VAR = 1
def next():
"""
Returns and increments the value of VAR.
"""
global VAR
VAR += 1
return VAR
|
# Copyright (c) 2009-2012 testtools developers. See LICENSE for details.
"""Content - a MIME-like Content object."""
__all__ = [
'attach_file',
'Content',
'content_from_file',
'content_from_stream',
'text_content',
'TracebackContent',
]
import codecs
import json
import os
import sys
impor... |
from django import forms
from django_countries.fields import CountryField
from django_countries.widgets import CountrySelectWidget
from .models import Item, CATEGORY_CHOICES, LABEL_CHOICES
class CheckoutForm(forms.Form):
shipping_address = forms.CharField(required=False)
shipping_address2 = forms.CharField(r... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import unittest
from iptest import run_test
class BigIntTest(unittest.TestCase):
def axiom_helper(self, a... |
#!/usr/bin/python
'''
(C) Copyright 2018-2020 Intel Corporation.
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 applic... |
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-swiss-styleguide'... |
# -*- coding: utf-8 -*-
"""
Regression
==========
Defines various objects to perform regression:
- :func:`colour.algebra.least_square_mapping_MoorePenrose`: *Least-squares*
mapping using *Moore-Penrose* inverse.
References
----------
- :cite:`Finlayson2015` : Finlayson, G. D., MacKiewicz, M., & Hurlbert, A.
... |
import sys
import os
import argparse
import xml.etree.ElementTree as ET
import csv
from contextlib import contextmanager
from multiprocessing import Manager, Pool, cpu_count
import traceback
# |**********************************************************************
# |* Project : Norman Lab Python 3 BLAST Qua... |
"""
DIRBS REST-ful data_catalog API schema module.
Copyright (c) 2018-2019 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are me... |
# import sys
# script, filename = sys.argv
# print("How old are you?", end=' ')
# age = int(input())
# print("How tall are you?", end=' ')
# height = int(input())
# print("How much do you weigh?", end=' ')
# weight = int(input())
# print(f"So, you're {age} old, {height} tall and {weight} heavy.")
# txt = open(filen... |
import threading
import time
import traceback
import weakref
from collections import deque
import pandas as pd
import ibis.common.exceptions as com
import ibis.expr.schema as sch
import ibis.expr.types as ir
import ibis.util as util
from ibis.backends.base import Database
from ibis.backends.base.sql.compiler import D... |
import pickle
import gfootball.env as football_env
# files = ["state_2949524111894", "state_2967625968164", "state_8740717452850", "state_8749651218096", "state_8753940391337", "state_8755588872887", "state_8756517669836", "state_8763774177870", "state_8794464646222", "state_9223363242555257663", "state_92233632554067... |
import queue
from loguru import logger
from backtest.backtest import Backtest
class EventHandler:
def __init__(self,
bt: Backtest,
verbose=False):
self.event_queue = queue.Queue()
self.bt = bt
self.verbose = verbose
def put_event(self,
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import polyaxon as plx
def create_experiment(output_dir, X, y, train_steps=1000, num_units=7, output_units=1, num_layers=1):
"""Creates an experiment using LSTM architecture for timeseries regression problem."""
config ... |
"""
A row of five black square tiles is to have a number of its tiles replaced with
coloured oblong tiles chosen from red (length two), green (length three), or
blue (length four).
If red tiles are chosen there are exactly seven ways this can be done. If
green tiles are chosen there are three ways. And if blue tiles a... |
# -*- coding: utf-8 -*-
# @Time : 2021/5/31 14:54
# @Author : WuBingTai
import subprocess
import os
from math import ceil
pkg_name = "com.myzaker.ZAKER_Phone"
cpu = []
men = []
flow = [[], []]
def top_cpu(pkg_name):
cmd = "adb shell dumpsys cpuinfo | grep " + pkg_name
temp = []
# cmd = "adb shell top... |
# encoding: utf8
u"""Defines a construct `pokemon_struct`, containing the structure of a single
Pokémon saved within a game -- often seen as a .pkm file. This is the same
format sent back and forth over the GTS.
"""
import datetime
from construct import *
# TODO:
# - strings should be validated, going both in and o... |
"""
Django settings for vp project.
Generated by 'django-admin startproject' using Django 3.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Buil... |
"""
Python Lotame API wrapper.
==========================
Filename: lotame.py
Author: Paulo Kuong
Email: pkuong80@gmail.com
Python Version: 3.6.1
Please refer to https://api.lotame.com/docs/#/ to get all Endpoints.
Please refer to README (https://github.com/paulokuong/lotame) for examples.
"""
from lotame.lotame impor... |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Test Access Control roles Workflow Admin propagation"""
import ddt
from ggrc.models import all_models
from integration.ggrc.access_control import rbac_factories
from integration.ggrc.access_control.acl_... |
# -*- coding: utf-8 -*-
"""rackio_opcua/worker.py
This module implements the worker for RackioOPCUA.
"""
import time
from threading import Thread
class OCPUAWorker(Thread):
def __init__(self, core, *args, **kwargs):
super(OCPUAWorker, self).__init__(*args, **kwargs)
self.core = core
s... |
from itertools import product
k, m = map(int, input().split())
l = [list(map(int, input().split()))[1:] for i in range(k)]
ma = 0
for p in list(product(*l)):
ma= max(ma, sum([x**2 for x in p])%m)
print(ma)
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Copyright 2018 The TensorFlow Probability 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... |
def check_right(grid, i, j):
product = 1
for k in grid[i][j:j+4]:
product *= k
return product
def check_down_right(grid, i, j):
product = 1
i2 = 4
if i+i2 > len(grid):
i2 = len(grid) - i
if j+i2 > len(grid[i]):
i2 = len(grid[i]) - j
for k in range(i2):
product *= grid[i+k][j+k]
return pr... |
"""
Helper classes for the management of subscription and unsubscription of the
Items handled by the Remote Data Adapter.
"""
from contextlib import contextmanager
import threading
from _collections import deque
from lightstreamer_adapter.protocol import RemotingException
from . import DATA_PROVIDER_LOGGER
class _I... |
# Copyright (C) 2017 Tiancheng Zhao, Carnegie Mellon University
from __future__ import print_function
import numpy as np
from laed.utils import Pack
from laed.dataset.dataloader_bases import DataLoader
# Stanford Multi Domain
class SMDDataLoader(DataLoader):
def __init__(self, name, data, config):
supe... |
# Copyright (c) 2012 Midokura Japan K.K.
#
# 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 l... |
import os
import subprocess
import sys
import textwrap
from setuptools import Command, Extension, setup
from setuptools.command.test import test as TestCommand
# Import version even when extensions are not yet built
__builtins__.__LIGHTFM_SETUP__ = True
from lightfm import __version__ as version # NOQA
def define_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-01-19 07:49
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('typeclasses', '0005_auto_20160625_1812'),
]
operations = [
migrations.DeleteModel(
... |
# 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
# distributed under t... |
"""The NEW_NAME integration."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
aiohttp_cli... |
#!/usr/bin/env python
# $Id$
import glob
import os
import platform
from setuptools import setup
from subprocess import *
PACKAGE_NAME = "impacket"
VER_MAJOR = 0
VER_MINOR = 9
VER_MAINT = 23
VER_PREREL = "dev1"
try:
if call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w')) == 0:
p = Popen("... |
from django.test import TestCase
from ditto.core.utils import datetime_from_str
from ditto.lastfm.factories import (
AccountFactory,
AlbumFactory,
ArtistFactory,
ScrobbleFactory,
TrackFactory,
)
from ditto.lastfm.models import Account, Album, Artist, Scrobble, Track
class AccountTestCase(TestCase... |
#!/usr/bin/env python3
import os
import sys
from PIL import Image
import math
import matplotlib.image as mpimg
import numpy as np
label_file = 'submission.csv'
h = 16
w = h
imgwidth = 608
imgheight = imgwidth
nc = 3
prediction_tags = [105, 106, 107, 108, 10, 115, 116, 11, 121, 122, 123, 124, 128, 129, 12, 130, 131,... |
from setuptools import setup
setup(
name='example_python_package_shim',
author='Jon',
version="0.0.1",
author_email='mail@jshimwell.com',
license='MIT',
url='https://github.com/Shimwell/example_python_package_shim',
description='Skeleton python project example.',
packages=["example_pyt... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 7, transform = "Difference", sigma = 0.0, exog_count = 100, ar_order = 0); |
import math
from flask import Flask, render_template,request
app = Flask (__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/pitagoras', methods=['GET','POST'])
def pitagoras():
if request.method == 'POST':
a = request.form['front']
b = reque... |
# coding: utf-8
import xml.etree.ElementTree as ET
def main():
countrydata = """<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austri... |
#
# Licensed to Dagda under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Dagda licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance... |
fruits = ["apple", "watermellon", "grapes"]
fruits = iter(fruits)
# fruits.__next__()
"""
print(next(fruits))
print(next(fruits))
print(next(fruits))
"""
# This is eq as
y = iter(range(1, 11))
for i in y:
print(i)
while True:
try:
value = next(y)
print(value)
except StopIteration:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-18 12:59
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
import wagtail.search.index
class Migration(migrations.Migration):
initial = True
dependencies = [
("taggit", "0002_auto_20150616_... |
"""f90nml.parser
=============
Fortran namelist parser and tokenizer to convert contents into a hierarchy
of dicts containing intrinsic Python data types.
:copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
:license: Apache License, Version 2.0, see LICENSE for details.
"""
import copy
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.