text string | size int64 | token_count int64 |
|---|---|---|
import doctest, json, logging, os, unittest, sys
sys.path.insert(0, "..")
import configr
class Tests(unittest.TestCase):
''' Test suite. '''
def tests_metadata(_):
_.assertTrue(hasattr(configr, "version"))
_.assertTrue(hasattr(configr.version, "__version__"))
_.assertTrue(hasattr(configr.version, "_... | 3,350 | 1,206 |
import numpy as np
import matplotlib.pyplot as plt
# define constants
g_l = 2.0
g_ca = 4.0
g_k = 8.0
e_l = -50.0
e_ca = 100.0
e_k = -70.0
tau = 0.1
v1 = -1.2
v2 = 18.0
v3 = 2.0
v4 = 30.0
cap = 20.0
# steady state functions
def m_ss(v):
return (1.0/2.0) * (1.0 + np.tanh((v - v1)/v2))
def n_ss(v):
return (1.0/... | 1,640 | 908 |
import h5py
import kaldi_io
import numpy as np
from collections import defaultdict
from config import get_config
from fuel.datasets.hdf5 import H5PYDataset
from lexicon import create_dictionary_from_lexicon, create_dictionary_from_punctuation_marks
def get_uttids_from_text_file(path):
uttids = set()
with open... | 12,059 | 3,957 |
# Generated by Django 2.0.5 on 2018-06-07 19:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0012_auto_20180607_1916'),
]
operations = [
migrations.AlterField(
model_name='student',
name='student_pa... | 511 | 222 |
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import Image,Profile,Comments
from .forms import UpdateProfile,UpdateUser,PostImageForm,CommentForm
from django.conf.urls import url
# Create your views here.
... | 3,409 | 1,015 |
import logging
from threading import Thread
from time import sleep
import os
import json
import schedule
#from django.utils.timezone import localtime, now
from apiai import ApiAI
from backend.models import Push, FacebookUser, Wiki
from .fb import send_text, send_buttons, button_postback, PAGE_TOKEN
from .handlers.pay... | 10,596 | 3,180 |
from .sqlschema import SQLSchema, SQLResultSet
import psycopg2
import psycopg2.extensions as pe
class POSTGRESQLResultSet(SQLResultSet):
def perform_insert(self, script, param, pk_fields, table, new_key):
script += u' returning %s' % u','. join ([
self.schema.render_name(field) for field in pk_fields
])
... | 4,994 | 2,119 |
from datetime import datetime
from typing import Any, Mapping, NamedTuple, Sequence, Union
from dateutil.relativedelta import relativedelta
from dateutil.utils import today
from django.db.models import Q
from django.utils.timezone import utc
class DatetimeLessThanCleanupFilter(NamedTuple):
"""Represents a filter... | 2,232 | 634 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Project:
## Author: Oliver Watts - owatts@staffmail.ed.ac.uk
import sys
import os
import glob
import re
import timeit
import math
from argparse import ArgumentParser
import numpy as np
from synth_halfphone import Synthesiser
import copy
# import pylab
if __name__... | 7,696 | 2,589 |
# Copyright (c) 2015 HGST 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 required by ... | 39,693 | 12,733 |
def select_debian_node(item, params):
params['ZUUL_NODE'] = 'debian'
| 73 | 30 |
#!/usr/bin/env python3
import argparse
import glob
import hashlib
import os
from shared_sql_generator import (
COMPONENT_DIR,
generate_uid,
HERE,
ingest_json,
make_indexes_sql,
make_matview_refresh,
make_modification_sql,
make_stats_sql,
split_indexes_chunks,
TEMPLATE,
)
# Usa... | 9,044 | 3,124 |
from typing import List
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
lo, hi = 1, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
lt, eq = 0, 0
for n in nums:
if n == mid:
eq += 1
elif lo <... | 1,526 | 617 |
class cloudprovider:
def instance_id(self):
pass
def instance_stop(self):
pass
def instance_start(self):
pass
def instance_status(self):
pass
| 194 | 58 |
# -*- coding: utf-8 -*-
"""
Variational Sparse Log Cox Gaussian Process
===========================================
Here we fit the hyperparameters of a Gaussian Process by maximizing the (log)
marginal likelihood. This is commonly referred to as empirical Bayes, or
type-II maximum likelihood estimation.
"""
# sphinx_... | 13,733 | 4,859 |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import random
def f(x):
return -x**4 + 2 * x**3 + 2 * x**2 - x
def exhaustive(function, start, stop, step):
x = start
best = (x, function(x))
while x < stop:
y = function(x)
if y > best[1]:
best = (x,... | 822 | 315 |
import random
sayi = random.randint(1,100)
print ("Tahmin Oyununa Hos Geldiniz")
sayac=0
while True:
tahmin = int(input("Sayi Girin:"))
sayac += 1
if tahmin == sayi:
print ("\nTebrikler {} denemede bildiniz!" .format(sayac))
break
elif tahmin < sayi:
print ("Daha Buyuk Bir... | 389 | 155 |
# This line required to prevent an empty file.
| 47 | 12 |
# --------------------------------------------------------------------
# The osmRoad is
#
# Copyright (c) 2018 by Zhongpu Chen (chenloveit@gmail.com)
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the followin... | 3,333 | 1,073 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import sys
import codecs
from argparse import ArgumentParser
from util import load_dais, load_texts, write_das, write_texts, write_toks, DAI
import kenlm
import numpy as np
from delexicalize import Delexicalizer
from tgen.l... | 8,319 | 2,860 |
from app.blueprints.base_blueprint import Blueprint, BaseBlueprint, request, Security, Auth
from app.controllers.bot_controller import BotController
url_prefix = '{}/bot'.format(BaseBlueprint.base_url_prefix)
bot_blueprint = Blueprint('bot', __name__, url_prefix=url_prefix)
bot_controller = BotController(request)
@b... | 532 | 163 |
# encoding: utf-8
"""
Copyright (c) 2019 Keitaro AB
Use of this source code is governed by an MIT license
that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
"""
# this is a namespace package
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
... | 394 | 137 |
from gda.device.scannable import PseudoDevice
from arduinoScannable import arduinoScannable
import time
from org.slf4j import LoggerFactory
logger = LoggerFactory.getLogger(__name__ + '.py')
class arduinoMotor(PseudoDevice):
def __init__(self, name, stepsPerRotation, motorPin1, motorPin2, motorPin3, motorPin4):
... | 3,908 | 1,187 |
import unittest
from TM1py import ChoreStartTime
class TestChoreStartTime(unittest.TestCase):
def test_start_time_string_happy_case(self):
chore_start_time = ChoreStartTime(year=2020, month=11, day=26, hour=10, minute=11, second=2)
self.assertEqual(chore_start_time.start_time_string, "2020-11-26... | 809 | 347 |
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E06000027"
addresses_name = "local.2019-05-02/Version 1/Democracy_Club__02May2019tor.tsv"
stations_name = "local.2019-05-02/Version 1/Democracy_Club__02May201... | 2,986 | 1,363 |
soma = 0
for c in range(0,6):
c = int(input('Digite um numero : '))
if c%2==1 :
soma = soma+c
print(' A soma dos impares dara {}'.format(soma))
print('FIM ') | 179 | 80 |
r"""ViViT Factorised Encoder model for Epic Kitchens.
"""
from absl import logging
import ml_collections
EPIC_TRAIN_SIZE = 67217
EPIC_VALID_SIZE = 9668
def get_config():
"""Returns the base experiment configuration."""
config = ml_collections.ConfigDict()
config.experiment_name = 'vivit_large_factorised_enc... | 6,325 | 2,277 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 12.py
# 2016/10/11(火)
# walkingmask
# check
# cut -f1 hightemp.txt
# cut -f2 hightemp.txt
col1f = open('col1.txt', 'w')
col2f = open('col2.txt', 'w')
for line in open('hightemp.txt', 'r'):
raw = line.rstrip().replace("\t"," ").split(" ")
col1f.write(raw[0]+"\n")
... | 376 | 187 |
################################################################################
# Copyright (c) 2015-2018 Skymind, Inc.
#
# This program and the accompanying materials are made available under the
# terms of the Apache License, Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0.
#
# Unless... | 1,115 | 374 |
import unittest
import datetime
from app import ScheduleHandler
class TestScheduleHandler(unittest.TestCase):
def test_timer(self):
class PartialIrcBot(ScheduleHandler):
pass
t = PartialIrcBot()
df = "%d/%m/%Y %H:%M:%S"
for d in [9, 10, 11, 12, 13]:
d_s... | 1,026 | 378 |
/home/runner/.cache/pip/pool/97/d1/9c/0ee9b4b39bafa05abf8cf04999afafcd584adf4911ee4f06c64e772d34 | 96 | 70 |
# -*- coding: utf-8 -*-
"""Utility functions for validation of command line interface parameter inputs."""
from aiida.cmdline.utils import decorators
from aiida.common import exceptions
import click
@decorators.with_dbenv()
def validate_kpoints_mesh(ctx, param, value):
"""Command line option validator for a kpoin... | 6,150 | 1,871 |
import pyxb.binding.generate
import pyxb.binding.datatypes as xs
import pyxb.binding.basis
import pyxb.utils.domutils
import os.path
xsd='''
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="iopt" nillable="true" type="xs:integer"/>
</xs:schema>
'''
#file('schema.xsd', 'w').write(xsd)
code =... | 972 | 358 |
from .param_file import param_file
| 35 | 11 |
from enum import Enum
import os
import sys
import inspect
import logging
import datetime
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
from Utils.Utils import Actions
class Trade():
def __init__(s... | 2,197 | 663 |
from collections import namedtuple
from config.config import CONF
PlayerInfo = namedtuple('PlayerInfo', ['team', 'slack_name'])
class PlayerNotFound(Exception):
def __init__(self, player):
msg = "Player '{}' cannot be found in player-to-team " \
"mapping.".format(player)
super(Playe... | 497 | 141 |
#!/bin/env python
import os
import sys
from XenServer import XenServer
from GELF import GELF
import traceback
try:
xs_session = XenServer().make_session()
pool = xs_session.xenapi.pool.get_all()[0]
pool_uuid = xs_session.xenapi.pool.get_uuid(pool)
hosts = xs_session.xenapi.host.get_all()
for ho... | 1,862 | 559 |
# -*- coding: utf-8 -*-
"""
This file contains ELMKernel classes and all developed methods.
"""
# Python2 support
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from .mltools import *
import numpy as np
import ... | 18,590 | 4,943 |
import numpy as np
import astropy.units as u
from ..instrument import CameraGeometry
from ..containers import ConcentrationContainer
from .hillas import camera_to_shower_coordinates
from ..utils.quantities import all_to_value
__all__ = ["concentration_parameters"]
def concentration_parameters(geom: CameraGeometry, ... | 1,561 | 545 |
import os
from pathlib import Path
import dj_database_url
from django.utils.translation import gettext_lazy as _
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = (os.getenv('DEBUG', 'False').upper() == 'TRUE')
DEBUG_TOOLBAR = (os.getenv('DEBUG_TOOLBAR', 'False').upper... | 5,647 | 1,908 |
"""
Essential parts borrowed from https://github.com/ipython/ipython/pull/1654
"""
import signal
from devp2p.service import BaseService
import gevent
from gevent.event import Event
import IPython
import IPython.core.shellapp
from IPython.lib.inputhook import inputhook_manager, stdin_ready
from ethereum import slogging
... | 2,682 | 784 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-21 05:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('adventure', '0007_auto_20160306_0055'),
]
operations = [
migrations.RenameFi... | 670 | 229 |
from .common import *
from .classification import *
from .segmentation import *
from .verification import *
from .retrieval import *
from .metric_manager import MetricManager
| 175 | 46 |
"""MagicStrip light implementation."""
from __future__ import annotations
import logging
from typing import Any, MutableMapping
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_EFFECT,
ATTR_RGB_COLOR,
COLOR_MODE_RGB,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_EFFECT,
... | 4,935 | 1,462 |
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
def vertical_bar(data: pd.DataFrame, label: str, value: str, ax=None, ratio=True, fontsize=14):
if ax is None:
n = data.shape[0]
fig = plt.figure(figsize=(16, 1 * n))
ax = fig.add_subplot(1, 1, 1)
labels = getatt... | 1,069 | 397 |
"""
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.length
n == matrix[i].len... | 1,407 | 498 |
import mysql.connector as connector
from ..utils.utils import get_sql_commands_from_a_file
from ..utils.consts import db_credentials
from ..utils.log import logger
class DBWrapper():
def __init__(self, db_credentials):
self.database_name = "telegram_ecommerce"
self.connection = connector.connect... | 2,161 | 635 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: addnn/node/proto/neural_network.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflec... | 5,346 | 2,004 |
"""Module for computing features."""
import logging
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from itertools import groupby
from os import cpu_count
from typing import Iterator
import numpy as np
from .features import Feature
from .generators import FullGenerator
from .image imp... | 5,334 | 1,489 |
import os
import sys
import time
from pathlib import Path
from random import choice
from codecs import decode
from base64 import b64decode
import tweepy
max_errors_count = 5
CONSUMER_KEY = os.environ["CONSUMER_KEY"]
CONSUMER_SECRET = os.environ["CONSUMER_SECRET"]
ACCESS_TOKEN = os.environ["ACCESS_TOKEN"]
ACCESS_TOKE... | 2,319 | 838 |
#
# Copyright (c) 2009-2021 fem2ufo
#
# Python stdlib imports
#from typing import NamedTuple, Dict, List, Iterable, Union
# package imports
from steelpy.f2uModel.load.sqlite.basic_load import BasicLoadSQL
from steelpy.f2uModel.load.sqlite.combination import LoadCombSQL
from steelpy.f2uModel.results.sqlite.operation.... | 1,787 | 534 |
# -*- coding: utf-8 -*-
from ._version import version_info, __version__ # noqa: F401 imported but unused
def get_include(user=False):
import os
d = os.path.dirname(__file__)
if os.path.exists(os.path.join(d, "include")):
# Package is installed
return os.path.join(d, "include")
else:
... | 423 | 143 |
#!/usr/bin/env python
from troposphere import Template, Output, GetAtt, Parameter, Ref, events, awslambda
t = Template()
lambda_arn = t.add_parameter(Parameter(
'LambdaArn',
Type='String',
Description='Lambda Arn'
))
rule = t.add_resource(
events.Rule(
"ReC2Rule",
Targets=[events.Tar... | 990 | 320 |
#!/usr/bin/env python
"""
Report retriever module.
Grab HTML from the url provided.
"""
import random
import requests
from urllib.parse import quote as url_quote
from pyquery import PyQuery as pq
USER_AGENTS = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
'Mo... | 3,716 | 1,389 |
import logging
import math
from collections import deque
from node import Node
from operator import itemgetter
from h3math import compute_radius, compute_hyperbolic_area, compute_delta_phi, compute_delta_theta
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.patches import Circle
import matplotlib.pyplot as ... | 20,347 | 5,649 |
def hwc2chw(image):
"""
Changes the order of image pixels from Height-Width-Color to Color-Height-Width
Parameters
-------
image : numpy.ndarray
Image with pixels in Height-Width-Color order
Returns
-------
image : numpy.ndarray
Image with pixels in Color-Height-Width o... | 744 | 224 |
import matplotlib.pyplot as plt
def plot_results(model_name: str, history, history_keys: list, training_dictionary:dict):
"""
Plot the results of a simulation.
Parameters
----------
model_name: (str) model name
history: (tf history) result of a Keras model fit
history_keys: (list) lis... | 1,530 | 549 |
"""
Question:
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the len... | 3,564 | 1,032 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import numpy as np
from numpy.testing import assert_allclose
import abel
DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data')
def test_basex_basis_sets_cache():
# n_vert, n_horz =... | 1,971 | 840 |
#main class handles user input and current gameState class
import pygame as p
import shogiEngine1
import os
import copy
import Piece
import Menu
height = 1057 #defines the board resolution
width = 1920
sq_size = 66
x_offset = 459
y_offset = 243
scale = 1
p.font.init()
myfont = p.font.SysFont('Comi... | 23,554 | 8,161 |
from sense_hat import SenseHat
#from collections import OrderedDict
import paho.mqtt.client as mqttClient
import time
import config
import json
sense=SenseHat()
sense.clear()
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker")
global Connected ... | 2,848 | 979 |
import numpy as np
import re
import random
from toolz.curried import *
def preview(df):
'''Previews a dataframe
Args:
x (df) a dataframe
'''
print(df.head())
return df
def convert_var(var,lookup):
return(var.map(lookup))
def convert_covid(var):
out = convert_var(var,{True:'C... | 1,315 | 487 |
import os
from os.path import join as pjoin
import cPickle as cp
import numpy as np
import tensorflow as tf
from sklearn.metrics import accuracy_score
from models.bnn import BNN
# command line arguments
flags = tf.flags
flags.DEFINE_integer("batchSize", 128, "batch size.")
flags.DEFINE_integer("nEpochs", 1500, "numb... | 6,777 | 2,216 |
"""
Build ML Lab React Webapp
"""
import os
import subprocess
import argparse
# Wrapper to print out command
def call(command):
print("Executing: "+command)
return subprocess.call(command, shell=True)
call("npm run setup")
| 234 | 72 |
import numpy as np
def levenshtein(first, second):
"""
O(nm) time & space for word of n and m characters
"""
n = len(first)
m = len(second)
matrix = np.array([np.arange(m)+i+1 for i in range(n)])
for i in range(1, n):
for j in range(1, m):
matrix[i,j] = min(
matrix[i-1, j] +1,
matrix[i, j-1] +1... | 505 | 251 |
def fizzbuzz(number):
if number <= 0:
return None
is_multiple_of_3 = (number % 3 == 0)
is_multiple_of_5 = (number % 5 == 0)
if is_multiple_of_3 and is_multiple_of_5:
return "FizzBuzz"
if is_multiple_of_3:
return "Fizz"
if is_multiple_of_5:
return "Buzz"
return str(number)
| 308 | 136 |
n = int(input('Digite um número: '))
#prox = n + 1
#ant = n -1
print ('Analizando o valor {}, seu antecessor é {} e o sucessor é {}.'.format(n, (n-1), (n+1)))
| 159 | 69 |
"""
Defines a series of useful Elasticsearch queries for the ONS
"""
from typing import List
from elasticsearch_dsl import query as Q
from elasticsearch_dsl.aggs import A as Aggregation
from dp_conceptual_search.ons.search.fields import AvailableFields
from dp_conceptual_search.ons.search.content_type import ContentT... | 2,781 | 856 |
#!/usr/bin/env python3
"""
Author : Leszek Grechowicz <leszek_grechowicz@o2.pl>
Date : 2021-06-13
Purpose: Choose the correct article
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
descript... | 1,486 | 439 |
from .edit import *
from .regedit import *
from .view_dict import *
| 68 | 22 |
#!/usr/bin/env python
# encoding: utf-8
from dynet import parameter, transpose, dropout, rectify
from dynet import layer_norm, affine_transform
from dynet import concatenate, zeroes, dot_product
from dynet import GlorotInitializer, ConstInitializer, SaxeInitializer
import math
class Dense(object):
def __init__(... | 4,233 | 1,420 |
n=int(input("enter the number: "))
temp=n
rev=0
while n>0:
dig=n%10
rev=rev*10+dig
n=n//10
if temp==rev:
print ("number is a palindrome", sep='a')
else:
print("number is not a palindrome")
| 222 | 103 |
#!/usr/bin/python3
import socket # used for TCP/IP communication
import smtplib # used to send email report
import time # used to insert current date in email report
import threading
class Buzzbox():
# Constructor, saving constants
def main(self, _ip: str, _port: int, _light: int, _led: int):
self.BUZZ... | 6,449 | 2,801 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import numpy as np
import open3d as o3d
from time import time, sleep
import rospy
from sensor_msgs.point_cloud2 import read_points
from vpp_msgs.srv import GetMap
from tensorboard_logger_ros.msg import Scalar
from tensorboard_logger_ros.srv import ScalarToBool
... | 17,997 | 5,346 |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 The Pybricks Authors
"""
Hardware Module: 1
Description: Verifies color sensing and calibration capability.
"""
from pybricks.pupdevices import Motor, ColorSensor, UltrasonicSensor
from pybricks.parameters import Port, Color
# Initialize devices.
motor = Motor(Por... | 1,314 | 494 |
#!/usr/bin/env python3
import argparse
import binascii
import os
import struct
import sys
import serial
import numpy as np
import scipy.io as sio
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--serial', default='/dev/tty.usbserial-AL00EZAS')
parser.add_argument('-b', '--baudrate', default=3000000,... | 3,406 | 1,425 |
__doc__="routines for selected Kolmogorov-Smirnov related statistics on text analysis"
import numbers
def ksComparisons(sectors_analysis):
multigroup_measures=[]
isnot_numeric_measures=[]
detached_measures=[]
ks_measures=P.utils.nestedDict()
for measure_domain in sectors_analysis["peripherals"]:
... | 15,427 | 4,408 |
import requests
import re
from .exceptions import BadURLException, ExpandingErrorException
URL_RE = re.compile(
r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.]"
r"[a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)"
r"))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()"
r'\[\]{};:\'".,<>?«»“... | 4,642 | 1,382 |
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
import requests
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdi... | 3,937 | 1,592 |
from unittest import TestCase
import os.path
import cv2
from lxml import html
from functions import ParameterTemplate
from functions.template import FunctionTemplate
FIXTURES_FILTER_HTML = "/usr/share/doc/opencv-doc/opencv4/html/d4/d86/group__imgproc__filter.html"
FIXTURES_FRAGMENT_HTML = os.path.join(os.path.dirname... | 1,362 | 407 |
#Day3: Toboggan Trajectory
#Part1: Starting in Top-Left Corner, follow a slope of Right 3 and Down 1.
f=open("input_day3.txt")
lines=f.readlines() #read in each line
f.close()
#print("lines\n",lines)
length=0
mnt=[]
for row in lines:
mnt.append(str(row)) #move into new list for easier manipulation
length=leng... | 3,662 | 1,578 |
from enum import auto, Enum
class EquipmentSlots(Enum):
MAIN_HAND = auto()
OFF_HAND = auto()
HEAD = auto()
BODY = auto()
LEGS = auto()
BOOTS = auto()
L_RING = auto()
R_RING = auto()
CLOAK = auto()
| 235 | 97 |
"""Added auth-related fields to User
Revision ID: 452902fab185
Revises: 501404b36cef
Create Date: 2013-09-24 12:42:04.461000
"""
# revision identifiers, used by Alembic.
revision = '452902fab185'
down_revision = '501404b36cef'
from alembic import op
import sqlalchemy as sa
def upgrade():
### ... | 1,130 | 423 |
class A:
vc = 234
def __init__(self):
vc = 456
a = A()
b = A()
a.vc = 432
print(a.vc)
print(b.vc)
print(A.vc) | 129 | 71 |
# -*- coding: utf-8 -*-
__author__ = 'olunx'
from django.forms import ModelForm
from core.models import ProductItem
class ProductItemForm(ModelForm):
class Meta:
model = ProductItem
fields = ['income_url', 'title', 'content', 'images', 'images_checked', 'purchasing_location', 'purchasing_price',... | 343 | 109 |
#!/usr/licensed/anaconda3/2020.11/bin/python
base = "/home/jdh4/bin/gpus"
import sys
sys.path = list(filter(lambda p: p.startswith("/usr"), sys.path))
sys.path.append(base)
import json
import subprocess
import pandas as pd
from dossier import ldap_plus
if 1:
rows = []
with open(base + "/utilization.json") as f... | 1,200 | 476 |
#!/usr/bin/python3
__version__ = '0.0.3' # Time-stamp: <2021-10-16T01:25:51Z>
## Language: Japanese/UTF-8
"""相続のテスト"""
##
## License:
##
## Public Domain
## (Since this small code is close to be mathematically trivial.)
##
## Author:
##
## JRF
## http://jrf.cocolog-nifty.com/software/
## (Th... | 4,777 | 1,693 |
import numpy as np
from sklearn.cluster import KMeans
from detectron.core.config import cfg
import detectron.utils.boxes as box_utils
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
cfg_TRAIN_NUM_KMEANS_CLUSTER = 3
cfg_RNG_SEED = 3
cfg_TRAIN_GRAPH_IOU_THRESHOLD = 0.4
cfg_TRAIN_MA... | 8,345 | 3,266 |
import numpy as np
import pandas as pd
from flask_restful import Resource
from flask_restful_swagger_2 import swagger
from marshmallow import fields, validates, Schema, ValidationError
from src.master.helpers.database import get_db_session
from src.master.helpers.io import marshal, load_data, InvalidInputData
from src... | 19,109 | 5,303 |
from django.db import models
from datetime import datetime
# Create your models here
class Realtor(models.Model):
name = models.CharField(max_length=200)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True)
description = models.TextField(max_length=400,blank=True)
phone = models.Positive... | 567 | 182 |
import helpers
import urllib
def main(request, response):
"""Respond to `/cookie/set?{cookie}` by echoing `{cookie}` as a `Set-Cookie` header."""
headers = helpers.setNoCacheAndCORSHeaders(request, response)
# Cookies may require whitespace (e.g. in the `Expires` attribute), so the
# query string shou... | 472 | 144 |
#
# Pick.py -- Pick plugin for Ginga fits viewer
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHel... | 18,233 | 6,234 |
from django.urls import path
from elastic.api.views import GoogleView, AppleView
urlpatterns = [
path('auth/google/verify/', GoogleView.as_view()),
path('auth/apple/verify/', AppleView.as_view())
]
| 208 | 68 |
"""
Provides representation for Commands that can be executed against
Executor instances.
"""
class Command(object):
"""
Represents a command that can be executed against different
executors, behaving similarly across them.
"""
def __init__(self, args: list, stdout: bool=False, stderr: bool=False,... | 4,992 | 1,232 |
from django.shortcuts import render, redirect
from .models import Comment
from .forms import CommentForm
def index(request):
comments = Comment.objects.order_by('-create_at')
context = {'comments': comments}
return render(request, 'blog/index.html', context)
def sign(request):
if request.method == '... | 715 | 192 |
from django.db import models
class Choice(models.Model):
"""
Модель варианта ответа
"""
choice_text = models.CharField(max_length=100, verbose_name="Текст варианта ответа")
question = models.ForeignKey("Question", on_delete=models.CASCADE, verbose_name="Вопрос")
class Meta:
verbose_na... | 2,668 | 913 |
from __future__ import print_function
import cm_client
from cm_client.rest import ApiException
from collections import namedtuple
from pprint import pprint
import json
import time
import sys
def wait(cmd, timeout=None):
SYNCHRONOUS_COMMAND_ID = -1
if cmd.id == SYNCHRONOUS_COMMAND_ID:
return cmd
SL... | 2,572 | 887 |
n=int(input())
def findMax(n):
l=0
r=n
while r-l>=2:
m1=l+(r-l)//2
m2=m1+1
s1=(m1+1)*(m1/2)
s2=(m2+1)*(m2/2)
if s2 >= n > s1:
return m2
elif s1 < n:
l=m1
else:
r=m1
return 1
def printLines(n,m):
for i in rang... | 447 | 195 |
from ANNarchy import *
from ANNarchy.extensions.bold.PredefinedModels import balloon_two_inputs
from ANNarchy.extensions.bold import BoldModel
from parameters import params, rng
setup(dt=params['dt'])
setup(num_threads=params['num_threads'])
setup(seed=params['seed'])
Constant('RS_v_r',params['RS_v_r'])
Constant('FS_v... | 4,914 | 1,773 |
import unittest
from atlascli.commands import Commands
from atlascli.atlasmap import AtlasMap
class TestPreFlight(unittest.TestCase):
def test_preflight(self):
map = AtlasMap()
map.authenticate()
c = Commands(map)
with self.assertRaises(SystemExit) as e:
c.preflight_clu... | 483 | 163 |