content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3
import sys
import kdb
base_key = "/sw/org/kdbdummy/#0/current"
spec_base_key = "spec" + base_key
spec = kdb.KeySet(10, kdb.Key(spec_base_key, kdb.KEY_META, "command", ""),
kdb.Key(spec_base_key + "/printversion",
kdb.KEY_META, "description", "print version information and exit (ignoring a... |
import io
import sys
import unittest
from unittest.mock import call, patch
from fzfaws.s3.bucket_s3 import bucket_s3, process_path_param
from fzfaws.s3 import S3
class TestS3BucketCopy(unittest.TestCase):
def setUp(self):
self.capturedOutput = io.StringIO()
sys.stdout = self.capturedOutput
de... |
class Node:
__slots__ = 'next', 'data'
def __init__(self, data):
self.data = data
self.next = None
class Stack:
"""
LiFo Stack
Methods:
- to_list() - O(n)
Returns list representation of stack, used for debugging
- peek() - O(1)
Returns the data on the top o... |
# Copyright 2017 Hewlett Packard Enterprise Development LP
#
# 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 applicabl... |
import json
import numpy as np
from experiences.core.generate_topo import PATHS, NETEM, BANDWIDTH, DELAY, QUEUING_DELAY
from experiences.core.generate_xp import XP_TYPE, SCHEDULER_CLIENT, SCHEDULER_SERVER, CC, \
CLIENT_PCAP, SERVER_PCAP, HTTPS_FILE, HTTPS_RANDOM_SIZE, QUIC_MULTIPATH, RMEM, \
QUIC, HTTPS, WEB... |
s = 'prova de python'
print(len(s))
print(19//2)
print(19%2) |
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stencilview import StencilView
from kivy.properties import StringProperty
from kivy.uix.label import Lable
from kivymd.label import MDLabel
class GalleryTitle(BoxLayout, StencilView, Label, MDLabel):
titletext = StringProperty("")
|
import urllib.request
pic_link = "http://images2015.cnblogs.com/news/24442/201703/24442-20170331214657258-1483842641.png" #图片链接
urllib.request.urlretrieve(pic_link, "d://MyPhotos//test.png") |
"""
Simple Render Engine
++++++++++++++++++++
"""
import bpy
import bgl
class CustomRenderEngine(bpy.types.RenderEngine):
# These three members are used by blender to set up the
# RenderEngine; define its internal name, visible name and capabilities.
bl_idname = "CUSTOM"
bl_label = "Custom"
bl_us... |
# Copyright 2020 Adrien Guinet <adrien@guinet.me>
#
# 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... |
from django.urls import path
from rsa.views import input_values_view
app_name = 'rsa'
urlpatterns = [
path('',input_values_view ,name = 'rsa'),
]
|
# pylint=disable(maybe-no-member)
import pickle
import keras
from gregarious.data import io
from gregarious.network import Gregarious
from keras.optimizers import Adam
# dd = io.DataDescription()
# df = io.DataFile('corpora/datasets/BotBonanza-2019-balanced.csv', dd, name="botbonanza-1000")
# df.compile()
# df.sav... |
from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields.encrypted import EncryptedCharField
class QuickbooksToken(models.Model):
user = models.ForeignKey(User)
access_token = EncryptedCharField(max_length=255)
access_token_secret = EncryptedCharField(max_l... |
'''
https://leetcode.com/problems/subsets/
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
'''
'''
Accepted
'''
class Solution:
# at each step we need to consider ... |
import unittest
from make_dataset import MakeDataset
class TestLoadData(unittest.TestCase):
def test_load_data(self):
X, y = MakeDataset.load_data();
self.assertTrue(X.size == 17017, f'expected 17017 columns, found {X.size}')
if __name__ == '__main__':
unittest.main()
|
from extensions import db
from models.user_type import UserType
class User(db.Model):
id = db.Column(db.String(80), primary_key=True, nullable=False)
# 1(Organisation)-to-many(User)
org_id = db.Column(db.String(80), db.ForeignKey('organisation.id'), nullable=False)
username = db.Column(db.String(120)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2017 In-Q-Tel, 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... |
import os
import sys
from .input import Input
# http://ascii-table.com/ansi-escape-sequences.php
_CLEAR_TEXT_ON_LINE = '\x1b[2K'
_MOVE_CURSOR_TO_START_OF_LINE = '\x1b[1000D' # Actually moves the cursor 1000 characters to the left
ERASE_LINE = _CLEAR_TEXT_ON_LINE + _MOVE_CURSOR_TO_START_OF_LINE
class TerminalInput... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" QiBuild """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print... |
__author__ = 'dwhite'
__date__ = '9/23/16'
import os
import subprocess
def getSourceRoot():
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
def getNetworkFolder():
return os.path.join(getSourceRoot(), "ExampleNets", "regression")
def script_folder():
r... |
#
# @lc app=leetcode id=102 lang=python3
#
# [102] Binary Tree Level Order Traversal
#
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @lc code=start
class Solution:
def levelOrder(sel... |
# *****************************************************************************
# *****************************************************************************
#
# Name: font5x7.py
# Purpose: Generate font file.
# Created: 14th March 2020
# Reviewed: 16th March 2020
# Author: Paul Robson (paul@robsons.org... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
from tables import s_box, rcon
from utils import *
from copy import deepcopy
def key_expansion_core(row, i):
rotate_row(row, -1)
for j in range(4):
row[j] = s_box[row[j]]
row[0] ^= rcon[i]
def key_expansion(key, expanded_key):
for i in range(16)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Challenges a player to a random battle when PM'd, or
accepts any random battle challenge and runs Gen 1
random battles with other files in this repo.
"""
import showdown
import asyncio
from pprint import pprint
from battle_manager import Gen1Knight
from os import path
... |
import operator, random, msgpack, json, sys, re, os
from datetime import datetime
import dateutil.parser
from utils import URL_PATTERN, open_for_write, get_domain, read_people_file, read_filtered, settings
def main():
print('Do not run this file. Run "message_formatter.py" to convert messages.')
def test_ig_l... |
from ramda.private.asserts import *
from ramda.ends_with import ends_with
def ends_with_test():
assert_equal(ends_with("c", "abc"), True)
assert_equal(ends_with("b", "abc"), False)
assert_equal(ends_with(["c"], ["a", "b", "c"]), True)
assert_equal(ends_with(["b"], ["a", "b", "c"]), False)
|
# -*- coding: utf-8 -*-
"""
Custom exceptions
"""
class PotcarParserError(Exception):
"""Exception raised by the PotcarParser class."""
pass
class PotcarPathError(Exception):
"""Exception raised by the PotcarPathParser class."""
pass
class IncarWrapperError(Exception):
"""Exception raised by... |
from flask_login import current_user
from flask import render_template, redirect, url_for, flash, request
from .models.product import Product
from .models.product_review import ProductReview
from .models.user import User
from flask import Blueprint
bp = Blueprint('products', __name__)
product_sellers = {1: 'Beyu Blu... |
__version_tuple__ = (0, 5, 1)
__version__ = '0.5.1'
|
# Copyright 2019 University of Basel, Center for medical Image Analysis and Navigation
#
# 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
#
# U... |
# This script monitors topics in io.adafruit.com and publishes some of them to my local MQTT broker
import logging
import time
import sys
from .mqtt import MqttMonitor
from .adafruit import Adafruit
from .private import username, password
# private.py is not part of the checked in code. You will need to create it.
# I... |
class MomentumType:
nesterov = 0
heavy_ball = 1
ema = 2
class ParallelAxes:
model = "model_parallel"
data = "data_parallel"
|
import json, logging
from fastapi import Depends, FastAPI
from app.e_get_friends import route
app = FastAPI()
app.include_router(route.router)
@app.get("/")
async def root():
return {"message": "This is the login service"}
|
import algsel
import argparse
import aslib_scenario
import json
import logging
import pandas as pd
import os
import subprocess
import tempfile
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--aslib_scenario_dir', type=str, default=os.path.expanduser('~/projects/aslib_data'))
par... |
# -*- coding: utf-8 -*-
"""
tkutil/config
@copyright: 2011 by Tatsuya Koyama
(www.tatsuya-koyama.com)
"""
import ConfigParser
from misc import MyDict
from console import cprint
class Config(object):
"""
Config accessor.
You can access with object-like format.
Normal dictionary access is a... |
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
_kern = None
def _get_kern():
global _kern
if _kern is None:
_kern = cuda.elementwise(
'T cond, T x, T slope', 'T y',
'y = cond >= 0 ? x : (T)(slope * x)', 'lrelu')
re... |
from functools import wraps
def vowel_filter(func):
VOWELS = ["a", "A", "e", "E", "i", "I", "o", "O", "u", "U", "y", "Y"]
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return [char for char in result if char in VOWELS]
return wrapper
@vowel_filter
def get... |
# -*- coding: utf-8 -*-
import logging
import os
from vindauga.constants.buttons import bfDefault, bfNormal
from vindauga.constants.command_codes import cmOK, cmCancel
from vindauga.constants.message_flags import mfError, mfOKButton
from vindauga.constants.event_codes import evCommand, evBroadcast
from vindauga.consta... |
#!/usr/bin/env python
import sys, os, commands, string, subprocess, shutil, optparse, tempfile
""" version 1.1 """
def stop_err( msg ):
sys.stderr.write( "%s\n" % msg )
sys.exit()
def __main__():
galaxyhome=os.environ.get('GALAXY_HOME')
'''
n = len(sys.argv)
for i in range(0,n):
print sy... |
from .preresnet import *
from .vgg import *
from .wide_resnet import *
from .simple import *
from .resnet import *
|
# Controller will be built Wednesday |
import numpy as np
import scipy.ndimage as nd
import torch
import torch.nn as nn
import torch.nn.functional as F
from engine.logger import get_logger
from seg_opr.seg_oprs import one_hot
logger = get_logger()
class SigmoidFocalLoss(nn.Module):
def __init__(self, ignore_label, gamma=2.0, alpha=0.25,
... |
# -*- coding: utf-8 -*-
from pymongo import IndexModel, ASCENDING, DESCENDING
class Message(object):
def __init__(self,
rid=None,
ts=None,
mid=None,
edited_at=None,
edited_by=None,
msg=None,
fid=... |
"""
Copyright 2017 MLiy Contributors
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, soft... |
from collections import Counter
from dataclasses import dataclass, field
from typing import List, NamedTuple, Tuple
class DuplicateError(Exception):
pass
class ComplexFormation(NamedTuple):
rxn_no: int
components: set
complex: str
is_binding: bool
@dataclass
class ThermodynamicRestrictions(obj... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 数组循环右移
"""
Topic: sample
Desc : 数组循环右移
"""
__author__ = 'Xiong Neng'
def right_shift(seq, k):
n = len(seq)
k %= n
seq[0:n - k] = seq[n - k - 1::-1]
seq[n - k: n] = seq[:n - k - 1:-1]
seq[:] = seq[::-1]
if __name__ == '__main__':
s = l... |
# A library for understanding the different Probability distribution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.integrate import quad
from tabulate import tabulate
import os
import imageio
import warnings
warnings.filterwarnings("ignore")
plt.rcParams["figure.figsize"] = (20,10)... |
from __future__ import annotations
import pandas as pd
import abc
from typing import TYPE_CHECKING, Any
from src.core.Setupable import Setupable
if TYPE_CHECKING:
from src.metric.SampleMetricManager import SampleMetricManager
class Filter(Setupable, metaclass=abc.ABCMeta):
"""
Abstract static class outli... |
# to allow code to work with Python 2 and 3
from __future__ import print_function # print is a function in python3
from __future__ import unicode_literals # avoid adding "u" to each string
from __future__ import division # avoid writing float(x) when dividing by x
import os.path
import logging as log
class Blast2hi... |
import pytest
from genomics_data_index.storage.model.NucleotideMutationTranslater import NucleotideMutationTranslater
from genomics_data_index.storage.model.QueryFeatureMutationSPDI import QueryFeatureMutationSPDI
def test_to_spdi_position():
assert 'seq:1:1:T' == NucleotideMutationTranslater.to_spdi('seq', 1, 1... |
'''
Created on 16 mar 2020
@author: giuliacarla
'''
import unittest
import numpy as np
from arte.control.transfer_function import ZetaTransferFunction, \
IdealTransferFunction, LaplaceTransferFunction
class TestIdealTransferFunction(unittest.TestCase):
def testIdealControlValues(self):
ic = IdealTr... |
import numpy as np
from enum import IntEnum
class Heading(IntEnum):
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
class Grid:
def __init__(self, height, width):
# the grid itself will be stored as a 3 dimensional array of (x, y, h)
# where h is the heading referring to the numbers shown... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 05_imageTools.ipynb (unless otherwise specified).
__all__ = ['viewMask', 'findCenter', 'findDiskCoord', 'preComposite', 'compositeBuild', 'findContours',
'contours2Segmentations', 'seg2BBoxArea', 'findCoord', 'compositeImage', 'imgCompSegBbox']
# Cell
import pand... |
from setuptools import setup, find_packages
setup(
name="rd_filters",
version="0.1",
packages=find_packages(),
entry_points={
'console_scripts': [
'rd_filters=rd_filters.rd_filters:main',
],
},
install_requires=['pandas', 'docopt'],
include_package_data=True,
)
|
import sys
sys.stdin = open('input.txt')
numTest = int(input())
for itertest in range(numTest):
N = int(input())
P = raw_input().strip()
L = len(P)
remains = 0
for x in range(L):
remains = (remains * 10 + 1) % N
print remains
|
import abc
class TextRenderer(metaclass=abc.ABCMeta):
@abc.abstractmethod
def render(self):
pass
class TextoNormal(TextRenderer):
def __init__(self, text):
self._text = text
def render(self):
return '¡' + self._text + '!'
class DecoradorT(TextRenderer, metaclass=abc.ABCMeta... |
from io import BytesIO
from picamera import PiCamera
stream = BytesIO()
camera = PiCamera()
camera.resolution = (640, 480)
camera.start_recording(stream, format='h264', quality=23)
camera.wait_recording(15)
camera.stop_recording() |
"""Main finite automata module."""
from types import MethodType
class InvalidTransition(RuntimeError):
"""
Invalid Transition Exception.
Exception is raised by FiniteAutomata instance is disallowed
transition has been called.
"""
class AbortTransition(RuntimeError):
pass
class FiniteAuto... |
#program to check if all items of a list is equal to a given string.
color1 = ["green", "orange", "black", "white"]
color2 = ["green", "green", "green", "green"]
print(all(c == 'blue' for c in color1))
print(all(c == 'green' for c in color2)) |
from django.db import models
# Create your models here.
# name, material, and manufacturerDate
class Cup(models.Model):
name = models.CharField(max_length=200, default="")
material = models.CharField(max_length=200, default="")
manufactuerDate = models.DateField(default="")
# phoneApp
# from django.db... |
import streamlit as st
from piidetect.piiregex import *
from utils import commonutils
entity_to_extract_list = ["emails", "ips", "ipv6s", "phones", "dates", "times", "links", "paths", "ssn", "guids"]
def read_in_chunks(file_object, chunk_size=8*1024):
"""
Lazy function (generator) to read a file piece by pi... |
from typing import Optional
from django.db import transaction
from django.utils.timezone import now as timezone_now
from zerver.lib.realm_logo import get_realm_logo_data
from zerver.models import Realm, RealmAuditLog, UserProfile, active_user_ids
from zerver.tornado.django_api import send_event
@transaction.atomic(... |
"""
Unit tests for the model predictions.
"""
import unittest
class TestPredict(unittest.TestCase):
"""
Tests for model predictions: (1) greedy search, (2) beam search for
reactant 1 only, (3) beam search for the full tree.
"""
def test_predict(self):
"""
Tests synthetic tree gene... |
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
sender_email = input("What is your email?\n")
password = input("Type your password and press enter: \n")
subject = "Internship Opportunity Se... |
from .pretrain import BERTTrainer, BERTTrainer_AL
|
import os
import json
import torch
import lib.utils.data as torchdata
import cv2
from torchvision import transforms
from scipy.misc import imread, imresize
import numpy as np
# Round x to the nearest multiple of p and x' >= x
def round2nearest_multiple(x, p):
return ((x - 1) // p + 1) * p
class TrainDataset(torch... |
import tensorflow as tf
import contextlib
def forward(inputs, model, loss_fn, training=False):
xs, ys = inputs
if training:
context = tf.GradientTape()
else:
context = contextlib.nullcontext()
with context as tape:
preds = model(xs, training=training)
loss = tf.reduce_... |
# Copyright 2018, Intel Corporation
#
# 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 list of conditions and the following di... |
"""
Graphe du fichier hauteur.csv
"""
import matplotlib.pyplot as plt
f = open('hauteur.csv')
lignes = f.readlines()
listeDonnees = [[], [], []]
listeLabel = ["n", "Hauteur moyenne", "Facteur de déséquilibre moyen"]
for l in lignes:
donnees = l.split(";")
for i in range(len(donnees)):
listeDonnees[i]... |
targetfile = 'list.txt'
outputprefix = 'BM'
# bowtie2 index files, generate by modified cDNA fasta
index = '/mnt/data8/zhaoyuancun/GRCm38/GRCm38_idx'
# OverlapModeVal
OverlapModeVal = True
# verbose
verbocity = True
# The minimum allowed probe length
l = 12
# The maximum allowed probe length
L = 17
# The minimum allow... |
import newrelic.agent
def retry_handler(job, exc_type, exc_value, traceback):
"""
Requeue a failed job max_retry times before giving up.
The number of times the job is requeued and the number of times is has been requeued
are configured and tracked in the job metadata:
job.meta["max_retry"] ... |
__all__ = ['OrderLog', 'OrderLogTruncated']
class OrderLog:
def __init__(self):
self._key = None
self._data = None
def get_key(self):
return self._key
def set_key(self, key):
if not isinstance(key, int):
raise ValueError('Date must be in int format')
s... |
import os, json, pdb, tqdm
from shutil import copyfile
split = "minival"
json_path = "datasets/coco/annotations/densepose_{}2014.json".format(split)
if "val" in split:
img_dir = "datasets/coco/val2014"
out_dir = img_dir + "_dp"
os.makedirs(out_dir)
with open(json_path, "r") as f:
# pdb.set_trace()
data = json.loa... |
import os
from .trace import trace_pyramid
import pyramid.config
import wrapt
def patch():
"""
Patch pyramid.config.Configurator
"""
if getattr(pyramid.config, '_datadog_patch', False):
return
setattr(pyramid.config, '_datadog_patch', True)
_w = wrapt.wrap_function_wrapper
_w('... |
"""
Copyright 2019 Samsung SDS
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... |
# Because division is different in Python 2 and 3
from __future__ import division
import numpy as np
from typing import Tuple
from ...phi import struct
from . import extrapolation as extrapolation
from . import _functions as math
from ._config import GLOBAL_AXIS_ORDER
from .extrapolation import Extrapolation
from ._fu... |
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from osmaxx.excerptexport.models import Export
def tracker(request, export_id):
export = get_object_or_404(Export, pk=export_id)
export.set_and_handle_new_status(request.GET['status'], incoming_request=request)
response ... |
"""
The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
Contributed by Sokolov Yura, modified by Tupteq.
"""
# import pyperf
DEFAULT_ARG = 9
def fannkuch(n):
count = list(range(1, n + 1))
max_flips = 0
m = n - 1
r = n
perm1 = list(range(n))
perm = list(range(n))
... |
"""__init__.py - Various utilities to use throughout the system."""
def serialize_sqla(data):
"""Serialiation function to serialize any dicts or lists containing
sqlalchemy objects. This is needed for conversion to JSON format."""
# If has to_dict this is asumed working and it is used.
if hasattr(data... |
from flask import (Flask,
render_template,
request,
redirect,
url_for,
flash,
jsonify)
from sqlalchemy import create_engine, desc
from datetime import datetime
from sqlalchemy.orm import sessionmaker
from d... |
# Generated by Django 2.1.1 on 2018-10-27 16:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('music', '0005_favorite'),
]
operations = [
migrations.RemoveField(
model_name='song',
name='is_liked',
),
]
|
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="sallybrowse",
version="1.2.8.9.15",
author="Simon Allen/Nick Leung",
author_email="author@example.com",
description="Easy to use web-based file/directory viewer.",
long_description=long_description,
long_... |
# (c) Copyright [2018-2021] Micro Focus or one of its affiliates.
# 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 applicabl... |
# Generated by Django 3.0.3 on 2020-08-22 01:40
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('core', '0004_merge_20200329_1743'),
]
operations = [
migrations.RemoveField(
model_... |
# Copyright (C) 2016 by Per Unneberg
# Helper functions for filetypes
import os
import re
import yaml
from os.path import join as pjoin
from os.path import normpath, dirname
try:
from pytest_ngsfixtures import ROOT_DIR
except ImportError as e:
print(("\n\n pytest-ngsfixtures not installed; ",
"ins... |
from neat.nn.feed_forward import FeedForwardNetwork
from neat.nn.feed_forward_fpga import FeedForwardNetworkFPGA
from neat.nn.recurrent import RecurrentNetwork
|
import sys
input = sys.stdin.readline
def main():
N = int(input())
A = list(map(int, input().split()))
ans = 0
for i, a in enumerate(A, start=1):
if i % 2 == 1 and a % 2 == 1:
ans += 1
print(ans)
if __name__ == "__main__":
main()
|
import unittest
from mock import Mock, MagicMock
from telegrambot import api
class TestMessage(unittest.TestCase):
def test_init_with_objects(self):
bot = MagicMock()
chat = api.Chat.from_api(api=bot, **{'id': 1, 'type': 'private'})
msg = api.Message(api=bot, chat=chat, text='Testing...'... |
from saleor.graphql.core.utils import to_global_id_or_none
from saleor.graphql.tests.utils import get_graphql_content
CHECKOUT_QUERY = """
query getCheckout($token: UUID) {
checkout(token: $token) {
id
}
}
"""
def test_checkout_by_token(checkout, user_api_client, customer_user):
# given
check... |
__all__ = ['Query']
from .deferred import Deferred
from .expr import Expr
class Query(object):
def __init__(self, store, d):
self.store = store
self.d = d
self.select_clauses = []
self.where_clause = None
def select(self, *args):
for select_clause in args:
... |
import re
documents = []
with open("inputs/day04.input", "r") as our_input:
document = {}
for line in our_input:
if len(line) == 1:
documents.append(document)
document = {}
continue
params = line.strip().split(" ")
for param in params:
k... |
#coding=utf8
import requests
import sys
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
base_url=sys.argv[1]
base_url=base_url.rstrip("/")
#upload file name and content
#modify by k8gege
#Connect "shell.jsp" using K8fly CmdShell
... |
#!/usr/bin/env python
# $Id$
# pyftpdlib is released under the MIT license, reproduced below:
# ======================================================================
# Copyright (C) 2007-2012 Giampaolo Rodola' <g.rodola@gmail.com>
#
# All Rights Reserved
#
# Permission is hereby granted, fr... |
# Incomplete overview of Numpy basics
import numpy as np
if __name__ == "__main__":
# Linspace generates an array (len = arg #3) of evenly spaced points between arg #1 and #2
print("Linspace array: ", np.linspace(0, 100, 25))
# Generate an array and reshape as a matrix
ranarr = np.random.randint(... |
from sys import stdout as s
from time import sleep as j
def w(print):
for i in print:
j(.03)
s.write(i)
s.flush()
next = input()
def noinput(print):
for i in print:
j(.03)
s.write(i)
s.flush()
w("Hello there! Over the course of 12 lessons, you will be learning how to code with Python! (Cli... |
# PyPI packages
import unicodecsv
# Local modules
from base import Exportable, Importable
class PostgreSQL(Exportable, Importable):
COPY_CMD = ("COPY {table} FROM STDIN WITH "
"CSV "
"DELIMITER '{delimiter}' "
"NULL '{null_string}' "
"ESCAPE '{esca... |
#!/usr/bin/python
"""Calls system_profiler and prints hardware info about
the current machine"""
import plistlib
import subprocess
cmd = ['/usr/sbin/system_profiler', 'SPHardwareDataType', '-xml']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, error) = proc.communicate()
info ... |
import re
def ip_classification( ip ):
# TODO deprecated
intraPatterns = [ '172\..*',
'10\.[^.]*[13579]\..*',
]
for ptn in intraPatterns:
if re.match( ptn, ip ):
return 'intra'
else:
return 'extra'
def filter_ip_extra( ips ):
... |
"""PyTorch-compatible datasets.
Guaranteed to implement `__len__`, and `__getitem__`.
See: https://pytorch.org/docs/stable/data.html
"""
import os
import sys
import torch
from PIL import Image
import torch.utils.data
import cv2
import numpy as np
from robosat_pink.tiles import tiles_from_slippy_map, buffer_tile_ima... |
from django.contrib import admin
from .models import Cliente
admin.site.register(Cliente)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.