content stringlengths 5 1.05M |
|---|
import argparse
import csv
import os
from utilities import create_folder
def dcase2017task4(args):
"""Create black list. Black list is a list of audio ids that will be
skipped in training.
"""
# Augments & parameters
workspace = args.workspace
# Black list from DCASE 2017 Task 4
t... |
{
"targets": [{
"target_name": "missing"
}]
}
|
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import logging
import os
import tempfile
import shutil
import subprocess
TOPIC_NAME = 'cron-stop-instances'
FUNCTION_SOURCE = """
import ba... |
from pathlib import Path
import multiprocessing
from trafficmonitor.trafficviewer import start
from trafficmonitor.helper_functions import create_path
class MitmProxy:
""" class for mitmproxy configuration """
def __init__(self):
# default command for mitmdump lib
self.command = ... |
import msvcrt
from elftools.common import *
from elftools.elf.elffile import ELFFile
with open('jnilibs/libnative-lib.so', 'rb') as f:
elf = ELFFile(f)
print(type(elf))
for seg in elf.iter_segments():
print(seg['p_type'], hex(seg['p_offset']), hex(seg['p_vaddr']), hex(seg['p_paddr']))
exit()
... |
import re
import collections
import supybot.utils
# http://ircv3.net/specs/core/message-tags-3.2.html#escaping-values
TAG_ESCAPE = [
('\\', '\\\\'), # \ -> \\
(' ', r'\s'),
(';', r'\:'),
('\r', r'\r'),
('\n', r'\n'),
]
unescape_tag_value = supybot.utils.str.MultipleReplacer(
dict(map(la... |
from lark import Lark
print_grammar = """
start : instruction+
instruction : "print" STRING [STRING] -> print
| "repeat" NUMBER code_block -> repeat
code_block : "{" instruction+ "}"
STRING: LETTER+
%import common.LETTER
%import common.INT -> NUMBER
%import common.WS
... |
#!/usr/bin/env python
"""The EE Python library."""
__version__ = '0.1.172'
# Using lowercase function naming to match the JavaScript names.
# pylint: disable=g-bad-name
# pylint: disable=g-bad-import-order
import collections
import datetime
import inspect
import numbers
import os
import six
from . import batch
fro... |
from LedAnimation import Animation, KeyFrame
from neopixel import *
import time
from random import randint
class RandBuildAnimation(Animation):
def BuildDef(self, strip, kwargs):
active = [0] * strip.numPixels()
colours = kwargs['colours']
delay = kwargs['delay']
while... |
from lxml import etree
if __name__ == "__main__":
h1 = etree.Element("h1")
h2 = etree.Element("h2")
h1.text = "s"
h2.text = "ss"
h1.set("class", "h")
h1.append(h2)
# print(dir(h1))
print(etree.tostring(h1, doctype="<!DOCTYPE html>"))
print(etree.tostring(h1, doctype=None)) |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2018 Peter Williams and collaborators.
# Licensed under the MIT License.
"""Solving radiation belt populations using the stochastic differential
equation approach.
"""
from __future__ import absolute_import, division, print_function
import numpy as np
from pwkit impo... |
from ..mapper import PropertyMapper, ApiInterfaceBase
from ..mapper.types import Timestamp, AnyType
__all__ = ['StoryAppAttribution', 'StoryAppAttributionInterface']
class StoryAppAttributionInterface(ApiInterfaceBase):
app_action_text: str
app_icon_url: str
content_url: str
id: int
link: str
... |
# Copyright 2020 IBM Corp.
#
# 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, sof... |
import unittest
import pandas as pd
from unittest.mock import patch
from sfdxmagic.functions import parse_magic_invocation, execute_query, execute_apex
class TestInvocation(unittest.TestCase):
def test_supports_out_var(self):
args = parse_magic_invocation("var -a -b")
assert args["variable"] == "v... |
import math
from arches.app.utils.date_utils import ExtendedDateFormat
from arches.app.utils.permission_backend import get_nodegroups_by_perm
from arches.app.search.elasticsearch_dsl_builder import (
Bool,
Match,
Query,
Nested,
Term,
Terms,
GeoShape,
Range,
MinAgg,
MaxAgg,
Ra... |
from QGrain.artificial._sample import *
from QGrain.artificial._setting import *
LOESS = [dict(shape=(0.0, 0.10), loc=(10.2, 0.1), scale=(1.1, 0.1), weight=(1.0, 0.1)),
dict(shape=(0.0, 0.10), loc=(7.5, 0.1), scale=(1.2, 0.1), weight=(2.0, 0.1)),
dict(shape=(0.0, 0.10), loc=(5.0, 0.2), scale=(1.0, 0.... |
# Generated by Django 3.0.5 on 2020-10-28 19:51
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("api", "0001_initial"),
migrations.swappable_dependency(settings... |
positive_rate_expr = ('a*exp(b*V)', ('a', 'b'))
negative_rate_expr = ('a*exp(-b*V)', ('a', 'b'))
constant_rate_expr = ('k', ('k'))
|
"""
Schemas for the Need Extension of Open-Needs Server
"""
from pydantic import BaseModel
from typing import Dict, Union, Optional
class NeedBaseSchema(BaseModel):
key: str
type: str
title: str
description: str | None
format: str | None
project_id: int
options: Dict[str, Union[float, str... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# string_trie_pattern_search_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the st... |
"""Some small utils."""
import logging
import os
import webbrowser
from distutils import spawn # pylint: disable=no-name-in-module
from typing import List
from PIL import Image
LOG = logging.getLogger(__name__)
def open_browser() -> None: # pragma: no cover
"""Open app in browser."""
LOG.info('Open brows... |
# Create an Dictionary Object called currentBook that has three attributes:
# Title , Author , Price
# Print out the dictionary object
# Print just the author of the currentBook
# Create a new attribute called ISBN (with some value)
# Print out all the values in the currentBook (using for loop)
currentBook = {
"Ti... |
from skimviz import start
start()
|
from pypy.conftest import gettestobjspace
class AppTestNumpy:
def setup_class(cls):
cls.space = gettestobjspace(usemodules=['micronumpy'])
def test_imports(self):
try:
import numpy # fails if 'numpypy' was not imported so far
except ImportError:
pass
i... |
import os, codecs
import pandas as pd
import numpy as np
%pylab inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('svg')
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt
!ls ../input/ -l
PATH = '../input/'
def bike_fence_forma... |
from tir import Webapp
import unittest
import time
class GTPA004(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAGTP', '15/04/2020', 'T1', 'D MG 01 ', '88')
inst.oHelper.Program('GTPA004')
def test_GTPA004_CT001(self):
... |
import base64
import os
import yaml
from flask import current_app
from github import Github, GithubException
from che_marketplace_backend.plugin import Plugin
METADATA_FILENAME = 'meta.yaml'
# Name of the repository on Github
PLUGIN_REGISTRY = 'eclipse/che-plugin-registry'
class Repository():
def __init__(self... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-01-17 10:21
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bims', '0107_biologicalcollectionrecord_source_collection'... |
__copyright__ = "Copyright 2016-2018, Netflix, Inc."
__license__ = "Apache, Version 2.0"
import numpy as np
class ListStats(object):
"""
>>> test_list = [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]
>>> ListStats.total_variation(test_list)
1.5555555555555556
>>> np.mean(test_list)
8.0
>>> np.median... |
import logging
import os
import string
import struct
class SimResult:
def __init__(self, path):
self._logger = logging.getLogger(__name__)
if os.path.isfile(path):
self._Path = path
self._vol = dict()
self._cur = dict()
self._logger.debug('SimResult ... |
import numpy as np
from matplotlib import pyplot as plt
from amical.analysis import pymask
def pymask_grid(input_data, ngrid=40, pa_prior=[0, 360], sep_prior=[0, 100], cr_prior=[1, 150],
err_scale=1., extra_error_cp=0., ncore=1, verbose=False):
cpo = pymask.cpo(input_data)
like_grid = pymask.... |
import base64
import hashlib
import binascii
from huaweisms.api.common import common_headers, ApiCtx, post_to_url, get_from_url
from .config import API_URL
def b64_sha256(data: str) -> str:
s256 = hashlib.sha256()
s256.update(data.encode('utf-8'))
dg = s256.digest()
hs256 = binascii.hexlify(dg)
... |
from src import *
def Main():
try:
while True:
time.sleep(7200)
check_if_connection_exist(network_path_server, password_for_network_path_server)
time.sleep(5)
path_for_G = create_path_folder(initial_path_for_G)
os.mkdir(path_for_G)
... |
a=int(input())
l=[]
for i in range(0,a):
l.append(int(input()))
l.sort(reverse = True)
print(l[0])
|
from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT
from cassandra.policies import DCAwareRoundRobinPolicy, TokenAwarePolicy, DowngradingConsistencyRetryPolicy, ConsistencyLevel, RoundRobinPolicy
from cassandra.query import tuple_factory
from pyspark.conf import SparkConf
from pyspark.sql impo... |
import numpy as np
import xml.etree.ElementTree as ET
class WindTurbines():
"""Set of multiple type wind turbines"""
def __init__(self, names, diameters, hub_heights, ct_funcs, power_funcs, power_unit):
"""Initialize WindTurbines
Parameters
----------
names : array_like
... |
from typing import Any, Dict
from . import caching as __caching, storage
from . import logging as __logging
from .infrastructure import page as __page
def get_page(template_path: str, data: Dict[str, Any] = {}) -> str:
from markdown_subtemplate.exceptions import InvalidOperationException
log = __logging.get_... |
import os
from dataflows import Flow, update_resource, set_primary_key, dump_to_sql
from dgp.core import BaseDataGenusProcessor
from dgp.config.consts import CONFIG_URL, CONFIG_TAXONOMY_ID
class ConfigStorerDGP(BaseDataGenusProcessor):
def __init__(self, config, context, lazy_engine):
super().__init__(... |
import itertools as it
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.multitest import multipletests
def read_all_chimeric_counts(h5_fns, sample_names, normalise=True):
chimeric_counts = {}
all_gene_non_chimeric_counts = {}
for sample, h5_fn in zip(sample_names, h5_f... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = ""
services_str = "/home/pi/Desktop/dashgo/src/dashgo_bringup/srv/ultrasonic.srv"
pkg_name = "dashgo_bringup"
dependencies_str = "std_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "std_msgs;/opt/ros/kinetic/share/std_msg... |
# Generated by Django 2.2.6 on 2019-12-16 16:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20191125_2123'),
]
operations = [
migrations.AlterField(
model_name='story',
name='initial_points'... |
from pathlib import Path
import pytest
from macpie.pandas import file_to_dataframe
current_dir = Path("tests/pandas/operators/filter_by_id/").resolve()
def test_filter_by_id():
df = file_to_dataframe(current_dir / "basic.xlsx")
# ids list with invalid integer should raise ValueError
ids = [1, 2, "hell... |
"""
None - A function that reaches the end of execution without a return statement
will always return None.
"""
def do_nothing():
pass
print(do_nothing()) # Out: None
"""
Defining a function with an arbitrary number of arguments
"""
def func(*args):
# args will be a tuple containing all values that are pass... |
"""
DATAQ USB Bulk driver level code
author: Valentyn Stadnytskyi
June 2018 - July 2020
"""
from numpy import nan, mean, std, asarray, array, concatenate, delete, round, vstack, hstack, zeros, transpose, split
from time import time, sleep
import sys
import os.path
import struct
from pdb import pm
from time... |
"""Single access point to all tools usable in hosts.
It is possible to create `HostToolsHelper` in host implementaion or
use singleton approach with global functions (using helper anyway).
"""
import avalon.api
from .lib import qt_app_context
class HostToolsHelper:
"""Create and cache tool windows in memory.
... |
# Another Logic
for x in range(5, 0, -1):
for y in range(5, 0, -1):
if x >= y:
print("*", end="")
else:
print(" ", end="")
print() |
# Copyright 2017 Battelle Energy Alliance, 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 t... |
"""
This is a dictionary of information about each product type.
the keys of the dictionary are the names of each product type. This will
translate into local file and/or directory names for various outputs of
pdr-tests: index files, data downloads, etc.
These selection rules are ideally for the _largest individual fi... |
from tkinter import *
from vue.base_frame import BaseFrame
from controller.order_controller import OrderController
class ListAdminOrderFrame(BaseFrame):
def __init__(self, order_controller : OrderController, master=None):
super().__init__(master)
self._order_controller = order_controller
self._orders = sel... |
#!/usr/bin/python
import sys
import os
import subprocess as sp
import shutil
from path import Path
# constants
TEMPLATE_FILE = 'project-config.template'
CWD = os.getcwd()
SWD = os.path.dirname(os.path.abspath(__file__))
ELASTIC = 'elasticsearch'
ELASTIC_URL = 'https://github.com/elastic/elasticsearch.git'
MAVEN = 'ma... |
#
# Copyright SAS Institute
#
# 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... |
from typing import cast
from src.const_settings import TOKENS_JSON_PATH
from src.custom_types import TokenTable
from src.utils import load_json_default
TOKEN_TABLE = cast(TokenTable, load_json_default(TOKENS_JSON_PATH))
|
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from csv import writer
import time
start_page = 1
pages_to_scrape = 1
sleep_time = 2
options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)
def load_page(page_num):
g... |
from utils.distance_metrics import manhattan_distance, eculidean_distance
from utils.search_algorithms import BFS, DFS, A_STAR
from puzzle.puzzle_state import PuzzleState
import math
import time
import resource
class PuzzleSolver(object):
def __init__(self, initial_state, goal, algorithm='bfs', heuristic= None):
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import mysql.connector
from mysql.connector import errorcode
def close_db(cursor, cnx):
cursor.close()
cnx.close()
def open_db():
config = {
'user': 'root',
'password': 'toor',
'host': '127.0.0.1',
'database': 'pythontest',
... |
import threading
import time
import subprocess
class mpstat(threading.Thread):
def __init__(self, callback):
"""Form the monitor and register the monitored metrics."""
super(mpstat, self).__init__()
self.stop_flag = False
self.interval = None
self.callback = callback
... |
#!/usr/bin/env python
# coding=utf-8
#
# Copyright (C) 2020 Florian Heller, florian.heller@uhasselt.be
#
# This program 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 2 of the License, or
# (a... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import os
import sys
from functools import partial
import xml.etree.ElementTree as ET
import lxml.etree as lxmlET
import yaml
from .frame_range_dlg_ui import *
# import frame_range_dlg_ui
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - for information on the respective copyright owner
# see the NOTICE file and/or the repository https://github.com/boschresearch/statestream
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... |
# This package is for Dr. Andrea's addtional brain image folder "EOR" shared in summer 2017. |
from __future__ import absolute_import, unicode_literals
import factory
from datetime import datetime
from physical.tests.factory import InstanceFactory, VolumeFactory
from backup.models import Snapshot
class SnapshotFactory(factory.DjangoModelFactory):
FACTORY_FOR = Snapshot
start_at = datetime.now()
ty... |
import pybullet as p
import time
p.connect(p.GUI)
p.setGravity(0, 0, -10)
p.setPhysicsEngineParameter(enableSAT=1)
p.loadURDF("cube_concave.urdf", [0, 0, -25],
globalScaling=50,
useFixedBase=True,
flags=p.URDF_INITIALIZE_SAT_FEATURES)
p.loadURDF("cube.urdf", [0, 0, 1], globalScaling=1,... |
import time
from sqlitedict import SqliteDict
from nonebot import get_driver
from requests import Session
from requests.cookies import create_cookie
from typing import Dict, Union, Any, List
from .config import Config
from .crypto import *
from .model import *
from .exception import NoLoginException
from .parser impo... |
import torch
import torch.nn as nn
import torch.optim as optim
from bert_pytorch import BERT
from utils import load_raw_math_data, load_vocab, make_weights_for_balanced_classes
from adabelief_pytorch import AdaBelief
from MathDataset import MathDataset
from torch.utils.data import Dataset, DataLoader
from tqdm im... |
import unittest
from pathlib import Path
import numpy as np
import torch
from PIL import Image
import frarch.datasets.transforms as t
DATA_FOLDER = Path("./tests/data/")
class TestImageTransforms(unittest.TestCase):
SYM_IMG = Image.fromarray(np.random.randint(0, 255, (100, 100, 3)).astype(np.uint8))
ASYM... |
from selenium.webdriver import Firefox
b = Firefox()
url = 'http://selenium.dunossauro.live/aula_06_a.html'
b.get(url)
# usando a atributo type [attr=valor]
# nome = b.find_element_by_css_selector('[type="text"]')
# senha = b.find_element_by_css_selector('[type="password"]')
# btn = b.find_element_by_css_selector('... |
"""Misc helper functions."""
import time
import logging
import socket
import functools
logger = logging.getLogger(__name__)
class TimeIt(object):
def __init__(self, description):
self.description = description
def __enter__(self):
self._start = time.time()
def __exit__(self, type, valu... |
# Generated by Django 4.0.2 on 2022-02-22 23:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("django_app_parameter", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="parameter",
name="is_globa... |
"""General utility functions.
"""
import copy
import os
import re
import socket
import threading
import uuid
from stomp.constants import *
# List of all host names (unqualified, fully-qualified, and IP
# addresses) that refer to the local host (both loopback interface
# and external interfaces). This is used for de... |
import hydra
from omegaconf import DictConfig
from trainers.agent_trainer import run
@hydra.main(config_path="configs/", config_name="experiment")
def main(cfg: DictConfig) -> None:
run(cfg.experiment_info, cfg.env, cfg.agent, cfg.memory, cfg.logging)
if __name__ == "__main__":
main()
|
# Generated by Django 3.1.6 on 2021-02-07 11:06
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20210207_1101'),
]
operations = [
migrations.AlterField(
model_name='animal',
name... |
from readers.parsers import OcrDataParser
import cv2
import pytesseract as ocr
from unittest import TestCase
class TestReportReader(TestCase):
def setUp(self):
with open('test/fixtures/ocr_data.txt', 'r') as data:
self.raw_data = data.read()
print(self.raw_data)
self.p... |
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# 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... |
#
# Copyright (C) 2016 UAVCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Pavel Kirienko <pavel.kirienko@zubax.com>
#
import logging
import multiprocessing
import os
import sys
import time
import tempfile
assert sys.version[0] == '3'
#
# Configurin... |
import sys
class CaptureStream(object):
def __init__(self):
self.contents = ""
def write(self, text):
self.contents += text
def close(self):
pass
def flush(self):
pass
# The class name here is lowercase as it is a context manager, which
# typically tend to me lower... |
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import TokenAuthentication
from rest_framework import filters
from . import ... |
import torch
import argparse
from glob import glob
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument('--type', type=str, default='0', help='fusion type') # 0: AvgTrim 1: DupTrim 2: Concat
opt = parser.parse_args()
assert(int(opt.type) >= 0 and int(opt.type) <= 2)
files = glob('I3D_RGB/*')
... |
#!/usr/bin/env python
import unittest
import inspect
class MagicTest(unittest.TestCase):
@classmethod
def _get_test_funcs(cls):
testcase_methods = dir(unittest.TestCase)
for m in inspect.classify_class_attrs(cls):
if m.kind == 'method' and \
m.defining_class == c... |
"""
Tests for public API v2 endpoints
"""
from flask import json
import os
import pytest
from common import daily_push_ny_wa_two_days
from app.api.public_v2 import ValuesCalculator, CoreData, datetime, State, Batch, db, pytz
def write_and_publish_data(client, headers, data_json_str):
# Write a batch containing... |
import json
from paprika.system.logger.Logger import Logger
from requests import post
from paprika.system.Traceback import Traceback
class Message:
def __init__(self):
pass
@staticmethod
def get_header(response, name):
for key in response.headers.keys():
if key.lower() == na... |
from setuptools import find_packages, setup
setup(
name="forge_pathplanner",
packages=find_packages(),
include_package_data=True,
python_requires=">=3.7",
url="https://github.com/uci-uav-forge/pathplanner",
author="Mike Sutherland",
license="MIT",
install_requires=[
"aiohttp==3.... |
import FWCore.ParameterSet.Config as cms
occupancyplots = cms.EDAnalyzer('OccupancyPlots',
multiplicityMaps = cms.VInputTag(cms.InputTag("ssclusmultprod")),
occupancyMaps = cms.VInputTag(cms.InputTag("ssclusoccuprod")),
wan... |
import os
def classify_giro_transaction(transactions_row):
if transactions_row['applicant_iban'] == os.environ.get('DKB_IBAN')\
or transactions_row['applicant_iban'] == os.environ.get('SPK_IBAN') \
or transactions_row['applicant_iban'] == os.environ.get('VISA_IBAN'):
return 'Intern... |
import os, sys
import torch
from matplotlib.pyplot import imsave
from nn_common import NumpyDataset
print(torch.__version__)
from ui_common import ui_common
import nn_common as common
import numpy as np
from torchvision.utils import save_image
import serial_port as comms
import time
ports = comms.serial_ports()
if ... |
#!/usr/bin/env python
import os
from os import listdir
import glob
import ntpath
from flask import Flask, render_template, request, send_from_directory
from flask.ext.babel import Babel, gettext, ngettext
app = Flask(__name__)
#app.config.from_pyfile('mysettings.cfg')
babel = Babel(app)
import ConfigParser
def Confi... |
from datetime import datetime, timedelta
from django.db.models import Q
from rest_framework import viewsets, mixins, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import Feedback
from .serializers import FeedbackSerializer, FeedbackCreateSeriali... |
# coding: utf-8
"""
Part of this code is based on a similar implementation present in FireWorks (https://pypi.python.org/pypi/FireWorks).
Work done by D. Waroquiers, A. Jain, and M. Kocher.
The main difference wrt the Fireworks implementation is that the QueueAdapter
objects provide a programmatic interface for settin... |
""" Some useful array utilities. """
from six.moves import range
import numpy as np
from itertools import product
#def to_slice(idxs):
#"""Convert an index array or list to a slice if possible. Otherwise,
#return the index array or list.
#"""
#if isinstance(idxs, slice):
#return idxs
#elif... |
"""
Implement a subset of the APL programming language.
Supports the monadic/dyadic functions +-×÷⌈⌊⊢⊣⍳<≤=≥>≠~⊂ ;
Supports (negative) integers/floats/complex numbers and vectors of those ;
Supports the monadic operators ⍨ and ¨ ;
Supports the dyadic operators ∘ (only functions as operands) and ⍥ ;
Supports parenthesiz... |
from elasticsearch import Elasticsearch
import ast
import nltk
import string
import sys
# specific json text parsing for this data-set. Must re-implement for other data sets
# Returns a list of review text
def pull_data(query_size=50):
es = Elasticsearch(['localhost:9200'], http_auth=('elastic','changeme'))
tr... |
#
# Copyright (c) 2019, 2020 Oracle and/or its affiliates. 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 r... |
"""Test wrong feature syntax."""
import os.path
import re
import sys
import mock
import pytest
from pytest_bdd import scenario, scenarios, given, when, then
from pytest_bdd.feature import features
from pytest_bdd import exceptions
@given('something')
def given_something():
pass
@when('something else')
def wh... |
import param
from nick_derobertis_site.common.component import HTMLComponent
from .carousel_model import CarouselModel
from nick_derobertis_site.landing.components.carousel.carousel_item.carousel_item_component import (
CarouselItemComponent,
)
class CarouselComponent(HTMLComponent):
model = param.ClassSelec... |
from django.conf.urls import url, include
from . import views
app_name = 'posts'
urlpatterns = [
url(r'^create/', views.create, name='create'),
url(r'^(?P<pk>[0-9]+)/upvote', views.upvote, name='upvote'),
url(r'^(?P<pk>[0-9]+)/downvote', views.downvote, name='downvote'),
url(r'^user/(?P<fk>[0-9]+)',... |
import os
import infra.basetest
def boot_armv5_cpio(emulator, builddir):
img = os.path.join(builddir, "images", "rootfs.cpio")
emulator.boot(arch="armv5", kernel="builtin",
options=["-initrd", img])
emulator.login()
class TestNoTimezone(infra.basetest.BRTest):
config = infra.baset... |
from scraper import do_scrape, get_df
import settings
import time
import sys
import traceback
if __name__ == "__main__":
while True:
print("{}: Starting scrape cycle".format(time.ctime()))
try:
x = do_scrape()
except KeyboardInterrupt:
print("Exiting....")
... |
from typing import Dict
def Main():
a: Dict[int, int] = {1: 15, 2: 14, 3: 13}
|
from django.conf.urls import *
from views import *
urlpatterns = patterns('',
url(r'^$', create, name='create.create'),
url(r'^([^//]+)/$', create, name='create.create'),
url(r'^([^//]+)/initSave$', initSave, name='create.initSave$'),
url(r'^([^//]+)/uploadSave$', uploadSave, name='create.upload... |
# Copyright 2021 Peng Cheng Laboratory (http://www.szpclab.com/) and FedLab Authors (smilelab.group)
# 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/LICEN... |
from flask import Flask, render_template, url_for, redirect, request, session, send_file
from werkzeug.utils import secure_filename
import os, os.path
import sys
import shutil
# full path to project
project_path = os.path.dirname(os.path.realpath(__file__))+"/"
#importing text detection
sys.path.append(project_path+"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.