text string | size int64 | token_count int64 |
|---|---|---|
# 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... | 2,699 | 777 |
from setuptools import setup
from pip.req import parse_requirements
import sys, os
sys.path.append("wutu/")
sys.path.append("wutu/compiler/")
install_reqs = list(parse_requirements("requirements.txt", session={}))
def version():
import version
return version.get_version()
setup(name="wutu",
version... | 718 | 229 |
import itertools
import threading
import pickle
import time
import sys
def animate():
for c in itertools.cycle(['|', '/', '-', '\\']):
if done:
break
sys.stdout.write('\rComputing the matrix ' + c)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\r... ')
... | 2,063 | 687 |
from pathlib import PurePath
from elftools.elf.elffile import ELFFile
from .typing import get_class
import ctypes
def die_from_offset(cu, offset):
return [die for die in cu.iter_DIEs() if die.offset == offset][0]
def get_type_from_file(filename, name):
with open(str(filename), 'rb') as f:
elffile = EL... | 2,632 | 953 |
import os
from functools import partial
import lazy_object_proxy
def start_spark(app_name="Jupyter"):
def sc_lazy(spark):
return spark.sparkContext
def hc_lazy(spark):
return HiveContext(spark.sparkContext)
global sc
global hc
global sqlContext
global spark
import fin... | 2,305 | 562 |
"""
This file can be used to try a live prediction.
"""
import keras
import librosa
import numpy as np
class LivePredictions:
"""
Main class of the application.
"""
def __init__(self):
"""
Init method is used to initialize the main parameters.
"""
self.path = './model... | 1,534 | 458 |
import pygame
import __main__
from Modules.Globals import *
from Modules.NavWidgets.Battery import *
from Modules.NavWidgets.Bluetooth import *
from Modules.NavWidgets.Wifi import *
class Nav():
def __init__(self, parent):
self.visible = True
self.parent = parent
self.buttons = []
s... | 3,956 | 1,153 |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField
from wtforms.validators import DataRequired, Email, Length
from flask_wtf.file import FileField, FileAllowed, FileRequired
class SignUpForm(FlaskForm):
name = StringField('Name', validators=[DataR... | 1,463 | 413 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'executive.views.home', name='home'),
url(r'^cloudcontrol/ajax/', include('cloudcontrol.urlsajax')),
url(r'^cloudcontrol/', include('cloudcontrol.urls')),
url(r'^... | 358 | 119 |
"""
=================================================
Classify ALS diagnosis from white matter features
=================================================
Predict ALS diagnosis from white matter features. This example fetches the ALS
classification dataset from Sarica et al [1]_. This dataset contains tractometry
featu... | 5,356 | 1,805 |
# coding: utf-8
# Copyright (c) Materials Virtual Lab
# Distributed under the terms of the BSD License.
import itertools
import numpy as np
import pandas as pd
from monty.json import MSONable
from pymatgen.core.periodic_table import get_el_sp
from sklearn.base import TransformerMixin, BaseEstimator
class Bispectrum... | 7,004 | 1,975 |
from ImagePreprocessing.ImagePreprocessing import load_label_encoder, save_label_encoder, \
convert_labels_to_one_hot_vectors
from JetRecognizerPreprocessing import get_random_train_fighter_images_as_pixel_values_generator, \
get_random_validation_fighter_images_as_pixel_values_generator
from BatchLoopGenerator... | 4,505 | 1,588 |
# coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the... | 68,137 | 22,237 |
import os
import sys
here = sys.path[0]
sys.path.insert(0, os.path.join(here,'..'))
import time
from coap import coap
import logging_setup
SERVER_IP = '::1'
# open
c = coap.coap(udpPort=5000)
# retrieve value of 'test' resource
p = c.GET('coap://[{0}]/test'.format(SERVER_IP),)
print '====='
pri... | 455 | 200 |
import unittest
from color_gamma_analyzer.diapason import calculate_ranges
class TestCalculatingOfRanges(unittest.TestCase):
def setUp(self):
self.brightness_data = [0.56, 0.76, 0.12, 0.97, 0.121, 0.454, 0.656]
def test_calculating_diapason_ranges(self):
calculated_ranges_first = [
... | 1,469 | 581 |
# W roku 2050 Maksymilian odbywa podróż przez pustynię z miasta A do miasta B. Droga pomiędzy miastami
# jest linią prostą na której w pewnych miejscach znajdują się plamy ropy. Maksymilian porusza się
# 24-kołową cysterną, która spala 1 litr ropy na 1 kilometr trasy. Cysterna wyposażona jest w pompę
# pozwalającą zbie... | 3,470 | 1,415 |
from django.contrib import admin
from .models import Article ,Comment
# Register your models here.
admin.site.register(Article)
admin.site.register(Comment)
| 159 | 44 |
import os
from typing import Union
from aws_cdk import core
from aws_cdk.core import CfnOutput
from datajob import logger
from datajob.datajob_context import DataJobContext
from datajob.datajob_execution_input import DataJobExecutionInput
class DataJobStack(core.Stack):
STAGE_NAME = "stage"
def __init__(
... | 6,499 | 1,714 |
# encoding: utf-8
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def list_all_files(rootdir, key):
import os
_files = []
list = os.listdir(rootdir) # 列出文件夹下所有的目录与文件
... | 5,869 | 2,320 |
#!/usr/bin/env python
import hashlib
import lixian_hash_ed2k
import lixian_hash_bt
import os
def lib_hash_file(h, path):
with open(path, 'rb') as stream:
while True:
bytes = stream.read(1024*1024)
if not bytes:
break
h.update(bytes)
return h.hexdigest()
def sha1_hash_file(path):
return lib_hash_fil... | 1,994 | 959 |
class BaseAmqpException(Exception):
default_detail = "Occurred an unexpected error."
def __init__(self, detail=None):
self.detail = detail if detail is not None else self.default_detail
def __str__(self):
return self.detail
class AmqpInvalidUrl(BaseAmqpException):
default_detail = ... | 663 | 198 |
CONTENT_TYPE_JSON = 'application/json'
| 39 | 15 |
"""
Utility class for fesim
By: Mehdi Paak
"""
import os
import subprocess
def create_meshinput_file(vardict):
"""
generate temporary mesh data input file
to be read by salome_mesh.py script.
"""
try:
geofile = vardict['GEOFILE']
wrkdir = vardict['WRKDIR']
seg_a = vardict... | 5,130 | 1,814 |
# -*- coding: utf-8 -*-
"""
chemreac.util.grid
------------------
Grid related utilities for one-dimensional grid of arbitrary spacing.
"""
from __future__ import print_function, division
from math import log
import numpy as np
from ..units import get_derived_unit, to_unitless
def generate_grid(x0, xend, N, logx... | 2,455 | 890 |
#python:
from collections import namedtuple
import numpy as np
from scipy.constants import speed_of_light
import gprMax.input_cmd_funcs as gprmax_cmds
import aux_funcs
Point = namedtuple('Point', ['x', 'y', 'z'])
# ! Simulation model parameters begin
# * Naming parameters
simulation_name = 'Antenna in free spac... | 4,771 | 1,735 |
# Save Roam JSON Export file in same folder and run following code in terminal `python r2o.py my-roam-export.json`
import sys
import os
import json
from tqdm import tqdm
import re
from dateutil.parser import parse
from datetime import datetime
yaml = """---
title: {title}
created: {created}
---
"""
months = r"Jan... | 6,226 | 2,182 |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Canu(MakefilePackage):
"""A single molecule sequence assembler for genomes large and
... | 1,465 | 560 |
#!/usr/bin/python
# aggregate-combiner.py
import sys
answers = []
last_user_id = None
MEM_THRESHOLD = 1024 * 1024 * 1024 # 1 GB
def write(user, entries):
if len(entries) > 0:
print('{0}\t{1}'.format(user, ','.join(entries)))
for line in sys.stdin:
user_id, answer_id = line.strip().split('\t', 1)
... | 578 | 239 |
# -*- coding: utf-8 -*-
# Copyright 2010 flask-mongoalchemy authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from __future__ import absolute_import
from mongoalchemy import document
from flaskext.mongoalchemy import Document
from fla... | 646 | 208 |
#!/usr/bin/python3
import socket
#target machine's ip number
target_ip = '3.82.4.173'
#target machine's port number
target_port = 8888
#create UDP socket
# IPv4--(INET--INET6), type of socket UDP --(DGRAM--STREAM)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
msg = input("P... | 446 | 180 |
from neo4j import GraphDatabase,basic_auth
from neo4j.expections import ServiceUnavailable
import neo_native_app as neo4j
import json
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, Docker!'
@app.route('/init_neo_driver')
def db_init():
bolt ="bolt://127.0.0.0:7... | 601 | 235 |
# coding=utf-8
"""transcode_ab.py
"""
from __future__ import print_function
import sys, re,codecs
sys.path.append('../')
import transcoder
transcoder.transcoder_set_dir('../transcoder')
def transcode(x,tranin,tranout):
y = transcoder.transcoder_processString(x,tranin,tranout)
return y
if __name__=="__main__":
fi... | 733 | 288 |
from threading import Thread, Timer
from time import time
import logging
try:
import Adafruit_DHT
except:
pass
class OneWireEnv(Thread):
"""This class is for reading out one wire sensors with the rpi"""
def __init__(self, main, framework, update_interval=5000):
"""This starts the background ... | 3,361 | 878 |
"""
Flask app
"""
import pandas as pd
from flask import Flask
import json
app = Flask(__name__)
# runs in local host http://127.0.0.1:5000/latest/all
@app.route('/latest/<horizon>')
def weather(horizon):
"""
Reads json and outputs based on selected paramter
Horizon can be either "all" or an integer betw... | 1,073 | 365 |
"""Experimental modules and unexperimental model hooks."""
from .models import construct_model
from .modules import MetaMonkey
__all__ = ['construct_model', 'MetaMonkey']
| 173 | 48 |
# Generated by Django 4.0.1 on 2022-01-26 09:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('appointments', '0022_alter_appointment_end_time_and_more'),
]
operations = [
migrations.RemoveField(
model_name='appointmen... | 376 | 142 |
import itertools
def sieve(size):
is_prime = [True] * (size)
for i in range(2, size):
if is_prime[i]:
is_prime[i*i::i] = [False] * len(is_prime[i*i::i])
f.write(json.dumps(list(itertools.compress(range(size), is_prime))[2:]))
| 259 | 106 |
import cv2
import numpy as np
def showImage():
filename = "Images/lena.jpg"
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
cv2.imshow('image', img)
lut = np.arange(255, -1, -1, dtype='uint8')
ysize = img.shape[0]
xsize = img.shape[1]
for y in range(ysize):
for x i... | 535 | 230 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 33,051 | 10,294 |
# --------------
# Importing header files
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)
#Code starts here
census=np.concatenate((data,new_record))
a... | 1,340 | 667 |
#!/usr/bin/env python3
# tkpng - example of using tkinter and pypng to display pngs (albeit reduced quality)
# in nothing but pure python. Can use RGBA images, but the alpha is stripped.
# v0.3 - structure rearranged to make classes and functions for reuse
from array import *
from tkinter import *
import png
class Pn... | 3,247 | 912 |
"""
Copyright (c) 2018-2021 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 applicable law or agreed to i... | 2,083 | 655 |
import os
from . import BaseCommand
from ..i18n import _
class Command(BaseCommand):
name = os.path.splitext(os.path.basename(__file__))[0]
description = _('create an HTTP Live Stream (HLS) out of an existing '
'H.264/AAC stream')
quiet_fields = {
'localStreamNames': _('loca... | 5,724 | 1,646 |
# -*- coding: utf-8 -*-
# Copyright 2018 by dhrone. All Rights Reserved.
#
import time
from .iot import Iot
from .utility import get_utc_timestamp
from .objects import ASHO
class Interface(object):
interface = None
version = None
properties = None
def __init__(self,thing=None, uncertaintyInMillisec... | 23,581 | 6,509 |
import sqlite3
import json
import pandas as pd
import numpy as np
homepages = list(pd.read_csv('news_homepage_urls.csv')['news_url'])
conn = sqlite3.connect('./topics_url_crawls/topics_url_crawl4/crawl-data_all_topics4.sqlite')
c = conn.cursor()
res = [['image_url', 'content_length', 'req_id', 'visit_id', 'news_site... | 1,696 | 590 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CESNET.
#
# oarepo-fsm is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""Pytest helper methods."""
import copy
import uuid
from flask_security import login_user
from invenio_db import db... | 1,368 | 439 |
from html.parser import HTMLParser
from .test_data import TestData
class CodeforcesParser(HTMLParser):
"""A class which can parse Codeforces webpages for testcase data."""
def __init__(self):
HTMLParser.__init__(self)
self.in_input = False
self.in_output = False
self.in_pre = False
self.curr_... | 1,844 | 627 |
import json
from nonogram_solver.error import LengthError, ClueError, AxisError, SetSolutionError
class Nonogram:
"""Main nonogram class
Used to hold the data of the nonogram.
Also has some basic creation and helper functions.
"""
printable_values = {0: " ",
-1: "..",
... | 10,644 | 3,129 |
from app.api.routes import api | 30 | 9 |
#!/usr/bin/env python
"""Python wrapper module for the GROMACS make_ndx module
"""
import sys
import json
from command_wrapper import cmd_wrapper
import configuration.settings as settings
from tools import file_utils as fu
class MakeNdx(object):
"""Wrapper for the 5.1.2 version of the make_ndx module
Args:
... | 2,468 | 789 |
import autoarray as aa
import autoarray.plot as aplt
from os import path
import pytest
import numpy as np
import shutil
directory = path.dirname(path.realpath(__file__))
@pytest.fixture(name="plot_path")
def make_plot_path_setup():
return path.join(
"{}".format(path.dirname(path.realpath(__f... | 18,454 | 6,980 |
from __future__ import print_function
import os
import sys
import time
import traceback
import subprocess
from shutil import disk_usage, rmtree
from base64 import b64decode
pipWorking = False
gitWorking = False
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def checkGit():
global gitWorking
... | 5,866 | 1,642 |
from django import template
register = template.Library()
from ..models import Notification
@register.simple_tag
def unread_notification(user):
no = Notification.objects.filter(user=user, read=False).count()
if no >= 1:
return True
else:
return False | 280 | 76 |
import pytest
from ekorpkit import eKonf
@pytest.mark.local()
def test_fred():
cfg = eKonf.compose(config_group="io/fetcher=quandl")
cfg.series_name = "DFEDTAR"
cfg.series_id = ["DFEDTAR", "DFEDTARU"]
cfg.force_download = True
fred = eKonf.instantiate(cfg)
cfg = eKonf.compose(config_group="v... | 499 | 220 |
import os
import operator
from flask import Blueprint, redirect, render_template, url_for, request, session
from flask_socketio import SocketIO, emit, join_room, leave_room
from . import socketio
from .helper import *
from .generator import generate_room_code
from .database import *
MIN_PLAYER_COUNT = 4
app = Bluepri... | 16,111 | 4,855 |
#!/usr/bin/env python3
#
# This module requires HatSploit: https://hatsploit.netlify.app
# Current source: https://github.com/EntySec/HatSploit
#
from hatsploit.lib.module import Module
from hatsploit.utils.session import SessionTools
class HatSploitModule(Module, SessionTools):
details = {
'Name': "Uni... | 1,075 | 329 |
p = ('Curso', 'Video', 'Python')
cont = 0
contl = 0
while True:
while True:
if p[cont][contl] in 'AaEeIiOoUu':
print(p[cont][contl])
contl += 1
if contl >= len(p[cont]):
break
contl = 0
cont += 1
if cont >= len(p):
break
| 293 | 116 |
import requests
import time
from urllib.parse import urlparse, parse_qs
from selenium.common.exceptions import NoSuchElementException
def SolveCaptcha(api_key, site_key, url):
"""
Uses the 2Captcha service to solve Captcha's for you.
Captcha's are held in iframes; to solve the captcha, you need a part of... | 3,951 | 1,326 |
import re
import os.path as osp
import requests
# from fake_useragent import UserAgent
from bpyutils.db import get_connection
from bpyutils.util.proxy import get_random_requests_proxies
from bpyutils.util._dict import merge_dict
from bpyutils.util.imports import import_or_raise
from bpyutils.util.string ... | 3,350 | 1,142 |
from bclearer_source.b_code.common_knowledge.content_operation_types import ContentOperationTypes
from bclearer_source.b_code.common_knowledge.digitialisation_level_stereotype_matched_ea_objects import \
DigitalisationLevelStereotypeMatchedEaObjects
from bclearer_source.b_code.configurations.content_operation_confi... | 1,845 | 621 |
"""solution.py"""
import math
import os
import random
import re
import sys
import timeit
class SimpleXOR:
def xor(self, a, b):
return a ^ b
def dynamicArray(n, queries):
last_answer = 0
all_answer = []
arr = [[] for _ in range(n)]
xor = SimpleXOR()
for row in queries:
t = row... | 1,246 | 454 |
import re
import json
from reading_json import modification_json
from downloadable_file_fast import downloadable
def _get_nucleotide_contributions(line):
patterns = line.split(' ')
contribution = [{'A': 0, 'C': 0, 'T': 0, 'G': 0} for i in range(len(patterns[0]))]
for pattern in patterns:
# print p... | 9,644 | 3,034 |
import logging
import uuid
from jsonscribe import utils
class AttributeSetter(logging.Filter):
"""
Ensure that attributes exist on :class:`~logging.LogRecord` s.
:keyword dict add_fields: maps fields to create on
:class:`~logging.LogRecord` instances to their default
values
The valu... | 1,235 | 354 |
from ariadne import ObjectType
class Entity:
pass
def create_entity(name, key_resolvers, key_name):
object_type = ObjectType(name)
setattr(object_type, "key_resolver", key_resolvers)
object_type.set_field(key_name, key_resolvers)
return object_type
| 273 | 94 |
"""The script makes the sources to have same length,
as well as have the same sampling rate"""
from scipy.io import wavfile
import utilities as utl
# Read the .wav files as numpy arrays
rate1, data1 = wavfile.read("sourceX.wav")
rate2, data2 = wavfile.read("sourceY.wav")
# Plot the sounds as time series data
utl.plot... | 831 | 288 |
from swi_ml import activations
from swi_ml.regression.linear_regression import (
_BaseRegression,
L1_L2Regularisation,
)
class LogisticRegressionGD(_BaseRegression):
def __init__(
self,
num_iterations: int,
learning_rate: float,
multiply_factor=None,
l1_ratio=None,
... | 1,389 | 403 |
import json
from collections import defaultdict
from rest_framework import exceptions, request, response, serializers, viewsets
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from ee.clickhouse.client import sync_execute
from ee.clickhouse.sql.person ... | 1,721 | 487 |
from django.db import migrations
from api.audit_trail.enums import AuditType
def update_good_review_payload(apps, schema_editor):
"""
Convert old AuditType.verb with format to new AuditType.verb as enum value.
"""
if schema_editor.connection.alias != "default":
return
Audit = apps.get_mo... | 1,198 | 384 |
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | 2,882 | 873 |
def replace_all(replace_string, actual_string):
while replace_string in actual_string:
actual_string = actual_string.replace(replace_string, "")
return actual_string
print(replace_all(input(), input()))
# replace_string = input()
# actual_string = input()
#
# while replace_string in actual_string:
# ... | 412 | 123 |
# https://oj.leetcode.com/problems/wildcard-matching/
class Solution:
@classmethod
def _memorize(cls, f):
def helper(self, s, p):
key = s + '|' + p
if key not in self.memo:
self.memo[key] = f(self, s, p)
return self.memo[key]
return helper
def __init__(self):
self.memo = {}... | 2,201 | 878 |
#
# Copyright 2016 The BigDL 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 or agreed to in ... | 2,138 | 585 |
import random
import pandas as pd
import compare_bigrams
import sys
import os
import as_numeric
import quantify_copying
# The file that contains the base corpus
INPUT_FILE = "../corpus/cath8.txt"
# Each line should be a sentence, with the words separated by spaces
# Read the input file and obtain a list of list o... | 2,066 | 705 |
from baseTest.BaseTestObject import BaseTestObject
# The type Driver manager.
class DriverManager:
# Base Test Object.
baseTestObject = BaseTestObject
# The Base driver.
baseDriver = object()
# The Get driver.
getDriverSupplier = object()
# Instantiates a new Driver manager.
# @para... | 1,421 | 403 |
#!/usr/bin/python3
import os
from utils import (
get_page,
internet_on,
my_log,
post_dict_to_list,
read_posts_dict,
write_posts,
)
cdname = os.path.dirname(__file__)
filename = os.path.join(cdname, 'pkuhole.txt')
filename_bak = os.path.join(cdname, 'pkuholebak.txt')
if __name__ == '__main__'... | 2,406 | 816 |
import argparse
import os
from misc import logger
from misc import constants
from collections import defaultdict, OrderedDict
import numpy
import re
class ExecutionResult:
def __init__(self):
self.test_number = 0
self.execution_time = ExecutionTime()
class ExecutionTime:
def __init__(self, to... | 18,436 | 6,274 |
# -*- encoding: utf-8 -*-
from coderunner import test, Python, main
test(Python, "recursive.py", """
15
""", is_file=True)
main()
| 132 | 55 |
"""Test whether potential estimations between layers are similar."""
import os
from pathlib import Path
import pytest
import pandas as pd
from renewablepotentialslib.eligibility import Potential
TOLERANCE = 0.005 # 0.5%
BUILD_DIR = Path(os.path.abspath(__file__)).parent.parent / "build"
PATH_TO_CONTINENTAL_POTENTIA... | 2,406 | 890 |
from flask import Flask
from .ext import site
from .ext import config
from .ext import toolbar
from .ext import db
from .ext import migrate
from .ext import cli
def create_app():
"""Factory to create a Flask app based on factory pattern"""
app = Flask(__name__)
config.init_app(app)
db.init_app(app)
... | 429 | 142 |
# Created by SNEHAL at 21-04-2020
Feature: #Enter feature name here
# Enter feature description here
Scenario: # Enter scenario name here
# Enter steps here
| 161 | 54 |
"""
Odds and ends in support of tests
"""
import os
import pytest
import numpy as np
import copy
from astropy import time
from pypeit import arcimage
from pypeit import traceslits
from pypeit import wavecalib
from pypeit import wavetilts
from pypeit.masterframe import MasterFrame
from pypeit.core.wavecal import wavei... | 7,231 | 2,620 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom administration panels for tracking models.
"""
from __future__ import unicode_literals
from django.contrib import admin
from calaccess_processed import models
from calaccess_raw.admin.base import BaseAdmin
@admin.register(models.ProcessedDataVersion)
class Proc... | 1,041 | 315 |
#!/usr/bin/env python3
# coding: utf-8
from setuptools import setup
import os.path as path
info_name = 'screenpdf'
info_url = 'https://github.com/arthurazs/{}/'.format(info_name)
author_name = 'Arthur Zopellaro'
email = 'arthurazsoares@gmail.com'
try:
with open(path.abspath(path.join(info_name,
... | 2,735 | 844 |
# welcome blink and post
import time
import board
import digitalio
import microcontroller
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
for x in range(3):
led.value = False
time.sleep(0.2)
led.value = True
time.sleep(0.2)
print("This is a {}, running at {:.1f} MH... | 482 | 167 |
class Solution:
def maximalSquare(self, mat: List[List[str]]) -> int:
n = len(mat)
m = len(mat[0])
mx = 0
dp = [[0 for _ in range(m)] for _ in range(n)]
for i in range(n):
for j in range(m):
if i == 0 or j == 0:
dp[... | 597 | 247 |
# -*- coding: utf-8 -*-
#
# Copyright 2019 Marcel Bollmann <marcel@bollmann.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 r... | 3,481 | 999 |
# coding: utf-8
# In[ ]:
import mnist_loader as load
import neural_network as neuronet
import activation_functions as af
import optimisation_functions as of
import cost_functions as cf
import learningStep_generators as lg
import numpy as np
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
... | 8,150 | 3,140 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 16:35:40 2019
@author: asiddi24
"""
'''Four box model'''
import numpy as np
import gsw as gsw
import time
import matplotlib.pyplot as plt
def fourbox(N,Kv,AI,Mek,Aredi,M_s,D0,T0s,T0n,T0l,T0d,S0s,S0n,S0l,S0d,Fws,Fwn,epsilon):
Area = 3... | 8,005 | 4,022 |
import io
from django.core.management.base import BaseCommand
from rest_framework.parsers import JSONParser
from rest_framework.renderers import JSONRenderer
from api.models import Pet
from api.serializers import PetSerializer
class Command(BaseCommand):
"""Uploading pets from the command line to stdout in JSON... | 981 | 281 |
import numpy as np
def load_dataset(path):
# initialize the list of data and labels
data = []
labels = []
# retrieve data from CSV
for row in open(path):
# parse the label and image from the row
row = row.split(",")
label = ord(row[0]) - ord("A") # scale labels to be numbe... | 626 | 195 |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.v3_equipment_alert_level import (
v3EquipmentAlertLevel as v3EquipmentAlertLevel_,
)
__all__ = ["v3EquipmentAlertLevel"]
_resource = _ValueSet.parse_file(Path(... | 649 | 241 |
"""moderation cog"""
from discord.ext import commands
import discord
from utils.database import CursorDB
from utils.page import Pages, make_groups
from utils.utilities import basic_frame, basic_message
from utils.reactions import Reactions
class Moderator(commands.Cog, CursorDB, Pages):
"""
Commands for... | 3,284 | 1,004 |
#!/usr/bin/env python
import os.path
from mpi4py import MPI
import numpy as np
import pandas as pd
import tensorflow as tf
import configparser
import numba
import multiprocessing as mp
import sys
from concurrent.futures import ThreadPoolExecutor
from _migration import calculate_migration
@numba.njit(parallel=True)
... | 4,340 | 1,620 |
import json
import os
import unittest
from unittest.mock import Mock, patch
import requests_mock
from dateutil import relativedelta
from plugins.trakt.trakt import Trakt
from plugins.trakt import api
""" Presets copied from Trakt's API """
ACTIVITY_PRESET_EPISODE_1 = {
"watched_at": "2014-03-31T09:28:53.000Z"... | 13,622 | 4,754 |
import math
import numpy as np
SAMPLERATE = 48000
class ADSR:
def __init__(self, a=0.1, d=0.2, s=0.6, r=0.5):
self.timings = {
0 : 0,
1 : 1 / ((a * SAMPLERATE) + 1),
2 : -1 / ((d * SAMPLERATE) + 1),
3 : 0,
4 : -1 / ((r * SAMP... | 5,675 | 2,049 |
import pathlib
from flask import Flask, redirect, render_template, request, Response, url_for, session
import secrets
import json
from Predictions_using_trained_model import predictionsUsingTheTrainedModels
from predictionDatabaseOperations import PredictionDBOperations
from predictionPreprocessing import PredictionPr... | 4,077 | 1,081 |
def read_tweets(file):
""" (file open for reading) -> dict of {str: list of tweet tuples}
Return a dictionary with the names of the candidates
as keys, and tweet tuple in the form of (candidate, tweet text, date,
source, favorite count, retweet count)as values
"""
dic = {}
key = ""
... | 2,017 | 747 |
cond = 'S'
num = quant = soma = maior = menor =0
while cond in 'Ss':
num = int(input(' Informe um numero:'))
quant += 1
soma += num
cond = str(input('Quer Continuar?[S/N]')).upper().strip()[0]
if quant == 1:
maior = menor = num
else:
if num > maior:
maior = num
... | 607 | 222 |
from subprocess import call
import matplotlib.pyplot as plt
import numpy as np
import tqdm
from scipy import ndimage
def callCP(MFA, cp_p, cppipe_p):
"""Call CellProfiler (http://cellprofiler.org/) to perform cell segmentation. CellProfiler segmentation pipeline
is in the spaceM folder with the '.cppipe' exte... | 6,206 | 2,185 |
import os
import fire
def gen_camvid_txt():
camvid_train_list = []
camvid_val_list = []
camvid_test_list = []
camvid_train_img_folder = "data/CamVid/train"
camvid_val_img_folder = "data/CamVid/val"
camvid_test_img_folder = "data/CamVid/test"
camvid_train_img_list = os.listdir(camvid_trai... | 1,612 | 632 |