text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
"""
STAD TEAM
~~~~~~~~~~
"""
from __future__ import absolute_import, unicode_literals, print_function
import win32print
import win32ui
from escpos import printer
from datetime import datetime
from .models import Mesas, DetalleOrden, Simbolos, Menu, Folio
from rest_framework.viewsets import M... | 8,820 | 2,913 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/dhardy92/thumbor_riak/
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2012 dhard92@github.com
from json import loads, dumps
from datetime import datetime, timedelta
from thumbo... | 4,856 | 1,582 |
import os
EXAMPLE_VARIABLE = os.getenv("EXAMPLE_VARIABLE")
| 60 | 27 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | 31,982 | 8,917 |
# Copyright (c) 2013-2020, Freja Nordsiek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | 2,656 | 898 |
'''
Author: Andrew-AbiMansour
DOC: Oct 21, 2019
This module defines a molecule for MD simulation/analysis
'''
from qcelemental.models import molecule as qc_molecule
from pydantic import Schema
from typing import Optional, Tuple, List
class Molecule(qc_molecule.Molecule):
angles: Optional[List[Tuple[int, int, int]]... | 1,040 | 356 |
# -*- coding: utf-8 -*-
import logging
import logging.config
from polaris_health import Error, config
__all__ = [ 'setup', 'setup_debug' ]
LOG = logging.getLogger(__name__)
LOG.addHandler(logging.NullHandler())
FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
class DatagramText(logging.handlers.Data... | 3,192 | 968 |
from dataclasses import dataclass
from enum import IntEnum
from typing import Any, Optional
from chia.protocols.protocol_message_types import ProtocolMessageTypes
from chia.util.ints import uint8, uint16
from chia.util.streamable import Streamable, streamable
class NodeType(IntEnum):
FULL_NODE = 1
HARVESTER =... | 722 | 245 |
"""
Test file for synchronized publications handlers.
"""
import pytest
from osbrain import Agent
from osbrain import run_agent
from osbrain.helper import wait_agent_attr
from .common import append_received
class ServerSyncPub(Agent):
def on_init(self):
self.received = []
self.bind('SYNC_PUB', a... | 4,147 | 1,235 |
# Generated by Django 2.0.4 on 2018-04-25 15:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0003_auto_20180424_1611'),
]
operations = [
migrations.AlterModelOptions(
name='event',
options={'ordering... | 598 | 205 |
import os
import yaml
from argparse import ArgumentParser
from os import path
from tirma.tirma import TIRMA
if __name__ == '__main__':
current_path = os.path.dirname(os.path.realpath(__file__))
ap = ArgumentParser(description='Sherlock Inject&Recovery tool')
ap.add_argument('--dir', default="./", help="W... | 1,543 | 493 |
import picoweb
import gpio
import network
import ujson
import wlanauto
app = picoweb.WebApp("SafeGate")
@app.route("/")
def index(req, resp):
yield from picoweb.start_response(resp)
htmFile = open('./static/gate.html','r')
for line in htmFile:
yield from resp.awrite(b""+line)
# yield from resp.... | 1,988 | 717 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import shutil
import glob
import click
import ruamel.yaml as yaml
import tensorflow as tf
from dnn_reco import misc
from dnn_reco.setup_manager import SetupManager
from dnn_reco.data_handler import DataHandler
from ... | 9,046 | 2,680 |
import numpy as np
import h5py
import keras
import keras.backend as K
from glob import glob
import json
import math, scipy
from scipy.optimize import linear_sum_assignment
import time
from collections import OrderedDict
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import keras
from neura... | 11,379 | 4,384 |
"""
Module containing utilities for layer inputs
"""
import itertools
import numpy as np
import tensorflow as tf
def get_reference_grid(grid_size: (tuple, list)) -> tf.Tensor:
"""
Generate a 3D grid with given size.
Reference:
- volshape_to_meshgrid of neuron
https://github.com/adalca/neurite... | 23,965 | 8,650 |
from ..repository import quantum, qrand_api_caller
from random import Random
from qulacs import QuantumState
from qulacs.gate import H
# クライアントがチートをするためのサービス。
class PostCheatStateService:
def __init__(
self,
random_impl: Random,
send_qubit_impl: qrand_api_caller.QRandApiRepository,
):
... | 1,120 | 457 |
import random
import math
from itertools import product
from ecc_types import *
def bitfield(n):
return [int(digit) for digit in bin(n)[2:]]
class AttackECC():
def __init__(self, ecc, gen_ed25519):
self.ecc = ecc
self.gen_data = gen_ed25519
self.to_divide = float(2**self.ecc.get_k())... | 1,655 | 639 |
from os import listdir
from os.path import exists, expanduser, isfile
import re
from subprocess import CalledProcessError, check_call
import logging
from pyudev import Context, Monitor
video_pattern = re.compile('missed-moment.*merged.*mp4')
MEDIA_DIR = '/missed_moment_media'
USB_MOUNT_DIR = '/missed_moment_usb'
USB_... | 2,456 | 799 |
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
from pkg_resources import parse_version
import kaitaistruct
from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO
if parse_version(kaitaistruct.__version__) < parse_version('0.9'):
raise Exception("Incompati... | 1,359 | 540 |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
# helper function for dropping columns with nan values.
def drop_high_nan(df, num_nans):
'''
drop columns with preselected number of nans
df = selected dataframe
num_nans = the number of nans as a threshold t... | 2,913 | 883 |
#!/usr/bin/env python3
# MIT License
# Copyright (c) 2019 Nircek
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy... | 4,963 | 1,536 |
# Python Standard Library Imports
# Third Party (PyPI) Imports
import rollbar
# HTK Imports
from htk.utils import htk_setting
from htk.utils.notifications import slack_notify
def failed_recaptcha_on_login(user, request=None):
extra_data = {
'user' : {
'id': user.id,
'username': u... | 1,082 | 344 |
# @Author: Manuel Rodriguez <valle>
# @Date: 2019-05-05T20:01:27+02:00
# @Email: valle.mrv@gmail.com
# @Last modified by: valle
# @Last modified time: 2019-05-09T01:17:25+02:00
# @License: Apache License v2.0
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
fr... | 2,348 | 815 |
import playsound
r1 = int(input('Segmento um: '))
r2 = int(input('Segmento dois: '))
r3 = int(input('Segmento três: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os segmentos acima, PODEM formar um triangulo', end=' ')
if r1 == r2 and r2 == r3:
playsound.playsound('rllx.mp3', tr)
... | 501 | 206 |
#!/usr/bin/env python
'''
Updates db will all info.json files found in the provided dir path.
This is gnerally used to update db periodically from all info.json files available in dataset
Params:
dataset_path - dir containing rosbag file to search for corresponding info.json files
Copyright (C) 2019 Intel Corpor... | 9,584 | 2,850 |
import findspark
findspark.init()
import pyspark
import random
sc = pyspark.SparkContext(appName="Pi")
num_samples = 100000000
def inside(p):
x, y = random.random(), random.random()
return x*x + y*y < 1
count = sc.parallelize(range(0, num_samples)).filter(inside).count()
pi = 4 * count / num_samples
print... | 336 | 133 |
# common utilities for other scripts
from tuf import repository_tool as rt
import os
import shutil
# shorthand to create keypairs
def write_and_import_keypair(keystorefolder, filename):
pathpriv = keystorefolder + '/{}_key'.format(filename)
pathpub = '{}.pub'.format(pathpriv)
rt.generate_and_write_ed2551... | 4,296 | 1,420 |
from colour import Color
from matplotlib.colors import LinearSegmentedColormap, to_hex
MET_PALETTES = dict(
Austria=dict(colors=("#a40000", "#16317d", "#007e2f", "#ffcd12", "#b86092", "#721b3e", "#00b7a7"), order=(1, 2, 3, 4, 6, 5, 7), colorblind=False),
Cassatt1=dict(colors=("#b1615c", "#d88782", "#e3aba7", "... | 10,223 | 5,641 |
import urllib.request
import os
def merge_dict_sum(dict1, dict2):
"""
Merge two dictionaries and add values of common keys.
Values of the input dicts can be any addable objects, like numeric, str, list.
"""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and ... | 1,186 | 388 |
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Parameter
from input.data_handler import DataHandler
class HavlicekDataHandler(DataHandler):
"""
Data encoding based on Havlicek et al. Nature 567, pp209–212 (2019). For quantum circuit diagram see Fig. 4 in
... | 1,096 | 384 |
#!/usr/bin/env python
import os
from os.path import basename, dirname, exists
from glob import glob
from random import seed, sample
from math import ceil
import shutil
from scipy.io import loadmat
DATA_PATH = 'data/'
VALID_RATIO = 0.2
seed(20171111)
info = loadmat(DATA_PATH + 'cars_annos.mat')
class_names = []
fo... | 1,951 | 716 |
"""
cloudalbum/tests/test_photos.py
~~~~~~~~~~~~~~~~~~~~~~~
Test cases for photos REST API
:description: CloudAlbum is a fully featured sample application for 'Moving to AWS serverless' training course
:copyright: © 2019 written by Dayoungle Jun, Sungshik Jou.
:license: MIT, see LICENSE for mor... | 4,318 | 1,393 |
from pathlib import Path
from tempfile import TemporaryDirectory
from wav_steganography.wav_file import WAVFile
from wav_to_mp3_to_wav.analyze_flipped_bits import find_matching_audio_file, convert_to_file_format_and_back
def compare_headers(file_path):
with TemporaryDirectory() as tmp_dir:
wav_file = WAV... | 932 | 318 |
import matplotlib.pyplot as plt
import numpy as np
"""
La funcion se encarga de buscar el valor de fuerza que le corresponde para ese valor f en el rango elegido
Buscavalor(max,rango,funcion):
max:valor obtenido de la funcion figual
rango: rango de la funcion de f de la FAM
funcion: es la funcion da... | 4,896 | 2,299 |
# implementation based on DeepLTL https://github.com/reactive-systems/deepltl
import tensorflow as tf
import dlsgs.transformer.positional_encoding as pe
from dlsgs.transformer.base import Transformer, TransformerEncoder
from dlsgs.transformer.common import create_padding_mask
class EncoderOnlyTransformer(Transform... | 2,883 | 864 |
# -----------------------------------------------------------------------
# configuration.py
# Author: Hari Raval
# -----------------------------------------------------------------------
# a Configuration object represents the parameters and settings used to generate an Amber test
class Configuration(object):
#... | 1,687 | 429 |
from typing import Union
from UE4Parse.BinaryReader import BinaryStream
class FNameEntryId:
Value: int
def __init__(self, reader: Union[BinaryStream, int]):
if isinstance(reader, BinaryStream):
self.Value = reader.readUInt32()
else:
self.Value = reader
| 305 | 87 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
url: https://github.com/Niger-Volta-LTI
download_url: archive/v{version}.tar.gz
package_data={'iranlowo': ['models/yo_adr_bahdanau_lstm_128_1_1_step_100000_release.pt']}
versioning="distance", # we start from 0.0.0 using v{major}.{minor}.0
"""
from setuptools impo... | 696 | 273 |
__all__ = [
'Particle',
'particles',
]
"""
Style: name: [mass(string),isQCD(bool)]
"""
particle_table = {
'u' : ['0' , True],
'ubar' : ['0' , True],
't' : ['mt', True],
'tbar' : ['mt', True],
'e' : ['0' , False],
'ebar' : ['0' , False],
... | 1,574 | 503 |
from abc import ABC, abstractmethod
class LabelStore(ABC):
"""This defines how to store prediction labels are stored for a scene.
"""
@abstractmethod
def save(self, labels):
"""Save.
Args:
labels - Labels to be saved, the type of which will be dependant on the type
... | 578 | 156 |
import pygame
class Shadow:
# shadow color
COLOR = (32, 32, 32, 192)
# unit size in pixels of a shadow
# length/width multiples are passed to the constructor
# to determine individual shadow size
U = 32
def __init__(self, posX, posY, width, length):
self.posX = pos... | 677 | 240 |
from src.util.dao import DAO
daos = {}
def getDao(collection_name: str):
"""Obtain a data access object of a collection. The purpose of the realization using the singleton pattern is
to avoid multiple data access objects for the same collection
parameters:
collection_name -- the name of the collec... | 533 | 142 |
'''
Test utilities
~~~~~~~~~~~~~~
Base test case class inherited by all test cases. Utility functions.
:copyright: Copyright 2011-2018 by Vlad Riscutia and contributors (see
CONTRIBUTORS file)
:license: FreeBSD, see LICENSE file
'''
import os
import shutil
import sys
from sphinx.cmd.build impo... | 2,125 | 682 |
from django.shortcuts import render
from django.contrib.auth import authenticate
from server.forms import PasswordForm, ProfileForm
from server.models import Action, Account, Message
from server import appointment
from server import views
from server import logger
from server import message
def profile_view(request)... | 4,122 | 1,053 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cloudshell.helpers.scripts.cloudshell_dev_helpers as dev_helpers
from cloudshell.api.cloudshell_api import InputNameValue
from cloudshell.workflow.orchestration.sandbox import Sandbox
from cloudshell.workflow.orchestration.setup.default_setup_orchestrator import... | 9,500 | 2,808 |
# Copyright (c) 2021 ING Wholesale Banking Advanced Analytics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, mo... | 2,470 | 781 |
"""Main application module"""
import os
import json
import jsend
import sentry_sdk
import falcon
from .resources.db import create_session
from .resources.welcome import Welcome
from .resources.submission import Submission
from .resources.export import Export, ExportStatus
from .resources.login import Login
def start_s... | 1,854 | 554 |
# -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.accounts.models import User
from apps.accounts.api.error_codes import AccountsErrorCodes
from apps.contrib.api.exceptions.base import SerializerFieldExceptionMixin
PASSWORD_MAX_LENGTH = User._meta.get_field('password').max_length # noqa: WPS43... | 1,458 | 451 |
"""
Views for endpoints that are not part of the biodata CRUD API
"""
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.conf import settings
from django.db import models
import django_rq
from rq.job import Job, NoSuchJobError, JobSt... | 3,013 | 928 |
#!/usr/bin/env python
import unittest
from clock import how_many_balls
from clock import minute_balls
from clock import five_minute_balls
from clock import hour_balls
from clock import run_ball_queue
class BallsTestCase(unittest.TestCase):
"""Tests for `ball-clock.py`."""
def test_how_many_balls_min_balls(self):... | 1,100 | 397 |
from colorfont import ColorFont
import pydoc
from mojo.UI import HelpWindow
doc = pydoc.HTMLDoc()
html = doc.document(ColorFont)
HelpWindow(htmlString=html)
html = doc.document(ColorGlyph)
HelpWindow(htmlString=html)
| 220 | 72 |
# !/usr/bin/env python
# _*_ coding:utf-8 _*_
from rest_framework import viewsets, permissions
from ops.serializers import *
from ops.models import *
from rest_framework import status
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framewor... | 25,617 | 7,734 |
from dynafile import Dynafile, Event
class Observer:
def __init__(self):
self.calls = []
def __call__(self, *args, **kwargs):
self.calls.append((args, kwargs))
@property
def latest(self):
return self.calls[-1] if self.calls else None
def test_put_item_schedules_event(tmp_pa... | 2,016 | 760 |
from django.urls.conf import path
from chat.views import MessageListView, MessageView
app_name = 'chat'
urlpatterns = [
path('', MessageListView.as_view(), name='message-home'),
path('<slug:pk>/', MessageView.as_view(), name='message'),
]
| 251 | 80 |
import numpy as np
import pytest
from conftest import channel1_path, channel_polarized_path, decay_names
import alldecays
@pytest.mark.parametrize("data_type", ["polarized", "unpolarized"])
def test_name_changes_work(data_type, channel1, channel_polarized):
channel = dict(polarized=channel_polarized, unpolarized... | 5,099 | 1,985 |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit
from django import forms
from django.forms.utils import ErrorList
from web.models import Municipality
from django.utils.translation import gettext_lazy as _
class MayorCandidatesFiltersForm(forms.Form):
municipality = ... | 1,614 | 467 |
from collections import deque
class DataBatcher:
def __init__(self, keyFunc, valFunc=None):
self.keyFunc = keyFunc
self.valFunc = valFunc
self.prevKey = None
self.batches = deque()
self.batch = None
def addData(self, data):
key = self.keyFunc(data)
... | 988 | 294 |
def print_backwards(*args, **kwargs):
print(kwargs)
for word in args[::-1]:
print(word[::-1], end=' ', **kwargs)
with open("backwards.txt", 'w') as backwards:
print_backwards("hellow", "all", "of", "my", "friends", file=backwards) | 253 | 91 |
"""
Chess Strategy
Vladimir is playing Keith in a two-game chess match. Winning a game scores one match point and drawing a game scores
a half match point. After the two games are played, the player with more match points is declared the champion.
If the two players are tied after two games, they continue playing until... | 1,309 | 436 |
def retangulo(lado_a,lado_b):
"""calcula a area de um retangulo"""
area= lado_a*lado_b
return area
def triangulo(base,altura):
"""calcula a area de um triangulo"""
area=(base*altura)/2
return area
def circulo(raio):
"""calcula a area de um circulo"""
area=3.14*(raio**2)
... | 1,329 | 524 |
# More info at: https://vald-phoenix.github.io/pylint-errors/
# pylint: disable=C0114
# pylint: disable=C0116
from datetime import datetime
import pytest
from go_over.goodreads import Book, BookRead, Bookshelf
# pylint: disable=C0301
# Line too long
BOOKS = [
{"Book Id": "00", "Title": "Book 0", "Author": "Cervan... | 4,261 | 1,733 |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
print(torch.cuda.is_available())
device=torch.device("cpu")
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
class PatNet(nn.Module):
## HYPERPARAMTERS
def __init__(self, nA, ... | 993 | 379 |
#! /usr/bin/env python
from __future__ import print_function
import argparse
import os
import sys
import struct
from numpy import empty, uint32,fromfile,uint16
# we avoid the use of backslashes to assist in templatising the code for Nextflow
TAB=unichr(9)
EOL=unichr(10)
FID_nSNPsRead = 1000
FID_IlluminaID ... | 11,125 | 3,865 |
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ...symbols import ORTH, NORM
from ...util import update_exc
_exc = {}
_abbrev_exc = [
# Weekdays abbreviations
{ORTH: "пн", NORM: "понедельник"},
{ORTH: "вт", NORM: "вторник"},
{ORTH: "ср", NORM: "среда"},
{ORTH: "чт", NORM: "четверг"},
{... | 18,090 | 8,221 |
from .resources import load_audio, load_audio_wavPCM, Microphone
from .parsers import SpectrogramAudioParser, InferenceSpectrogramAudioParser | 141 | 40 |
from sklearn.datasets import load_svmlight_file
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn import metrics
param_grid = {'C':[0.001,0.01,0.1,1,10,100]}
X,y = load_svmlight_file('MachineLearning/disorder.libsvm.dat')
X_train, X_test, y_train, y_test = tra... | 638 | 254 |
import numpy as np
import sys
import os
os.stat('pylib')
sys.path.append("pylib")
sys.path.append("pylib/utils")
import argparse
import tables
from pulp.utils.parallel import pprint
from pulp.utils.barstest import generate_bars_dict
from sklearn.neural_network.multilayer_perceptron import MLPClassifier
#%% -- General ... | 13,326 | 5,228 |
N = int(input())
K = int(input())
result = 1
for _ in range(N):
result = min(result * 2, result + K)
print(result)
| 120 | 49 |
import os
import sys
import warnings
from importlib import import_module
from django.apps import apps
from django.conf import settings
from django.core.management.commands.test import Command as TestCommand
from django_jenkins.runner import CITestSuiteRunner
def get_runner(settings, test_runner_class=None):
if ... | 5,869 | 1,585 |
"""
Tools to encapsulate generic receive connectors
"""
import logging
import time
import mqttsn.client as mqttsn
from collections import namedtuple
from .settings import UDP_URL, UDP_PORT
from .decorators import ensure_udp_connection
log = logging.getLogger('udpreceiver')
UDPMessage = namedtuple('UDPMessage', ['pay... | 2,303 | 691 |
#!/usr/bin/env python2
import os, sys, argparse, pylab, json
path = os.path.dirname(os.path.realpath(sys.argv[0]))
parser = argparse.ArgumentParser(description = 'Graphical view of marked locations')
parser.add_argument('--filename', type = str, help = 'File from which to read marks (defaults to marks.json)', default... | 4,860 | 1,834 |
import os
try:
from tox.config import default_factors
except ImportError:
default_factors = None
def pypy_version_monkeypatch():
"""Patch Tox to work with non-default PyPy 3 versions."""
# Travis virtualenv do not provide `pypy3`, which tox tries to execute.
# This doesnt affect Travis python ver... | 1,028 | 338 |
import numpy as np
# #=========================================================
# # Input Arguments
# #=========================================================
# with open("parameters.yml", 'r') as stream:
# D = yaml.safe_load(stream)
#
# for key in D:
# globals() [str(key)] = D[key]
# print('{}: {}'.for... | 8,072 | 2,335 |
"""This module contains the meta information of LoggingSyncOcns ExternalMethod."""
from ..ucscentralcoremeta import MethodMeta, MethodPropertyMeta
method_meta = MethodMeta("LoggingSyncOcns", "loggingSyncOcns", "Version142b")
prop_meta = {
"cookie": MethodPropertyMeta("Cookie", "cookie", "Xs:string", "Version142b... | 851 | 307 |
"""
find song if already downloaded in filesystem
"""
from dataclasses import dataclass
import os
from pathlib import Path
from typing import Optional, Union
import pickle
from utils import Song
@dataclass
class DownloadedSongs:
def __init__(self, songs_path: str = "karaoke-maker/data/downloads/"):
if so... | 6,351 | 1,811 |
from abc import ABC
from .view import View
from .model import Model
from .controller import Controller
class WaitingRoom(ABC):
Model = Model
View = View
Controller = Controller | 190 | 49 |
# -*- coding: utf-8 -*-
# This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK for Python.
# Please visit https://alexa.design/cookbook for additional examples on implementing slots, dialog management,
# session persistence, api calls, and more.
# This sample is built using the ... | 20,795 | 5,839 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^list/$', views.comment_list, name='comment_list'),
]
| 134 | 46 |
import numpy as np
import pandas as pd
import py2neo
import pickle
import os,sys
from scipy import sparse
def edges2adj(edges, raw_edges, year, pcount):
# Uniqify edges
def uniqify_edges(edges, pcount):
ccount = edges.groupby(["target"])["s_target"].nunique()
nodes = pd.DataFrame({"ccount": cc... | 7,960 | 2,919 |
import pytest
import pykka
class NestedWithNoMarker:
inner = "nested_with_no_marker.inner"
class NestedWithNoMarkerAndSlots:
__slots__ = ["inner"]
def __init__(self):
self.inner = "nested_with_no_marker_and_slots.inner"
@pykka.traversable
class NestedWithDecoratorMarker:
inner = "nested_... | 2,830 | 940 |
import pytest
from app.backend.task.task_manager import TaskManager
from app.backend.task.default_task import Task, DefaultTask
@pytest.fixture
def task_manager():
return TaskManager()
def test_start_task(task_manager):
task_manager.start_task(DefaultTask())
task_manager.start_task(DefaultTask())
pr... | 822 | 269 |
import pytest
from lyth.compiler.analyzer import Analyzer
from lyth.compiler.error import LythError
from lyth.compiler.error import LythSyntaxError
from lyth.compiler.lexer import Lexer
from lyth.compiler.parser import Parser
from lyth.compiler.scanner import Scanner
from lyth.compiler.symbol import Field
from lyth.co... | 8,007 | 2,834 |
import boto3
import os
import hashlib
import uuid
import calendar
import time
from decimal import Decimal
from boto3.dynamodb.conditions import Key
def lambda_handler(event, context):
debug = os.getenv('DEBUG') is '1'
hashed_passwd = hash_password(event['password'])
dynamodb = boto3.resource('dynamodb', region_n... | 1,418 | 493 |
# @Author: Narsi Reddy <cibitaw1>
# @Date: 2018-09-19T11:53:44-05:00
# @Email: sainarsireddy@outlook.com
# @Last modified by: narsi
# @Last modified time: 2019-01-03T21:57:01-06:00
# import torch
# if '0.4.' not in torch.__version__:
# raise Exception('Only works currently with PyTorch ver0.4.x')
| 307 | 147 |
from setuptools import setup
# these lines allow the version to be specified in Makefile.private
import os
version = os.environ.get("MODULEVER", "0.0")
setup(
name = 'dls_pmaclib',
version = version,
description = 'Module',
author = 'fgz73762',
author_email = 'fgz73762@rl.ac.uk', ... | 432 | 151 |
input = open('input.txt');
output = open('output.txt' , 'w');
tokens = input.readline().split(' ');
input.close();
output.write(str(int(tokens[0]) + int(tokens[1]) ** 2));
output.close();
| 188 | 72 |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_sssd_conf(host):
conf = host.file('/etc/sssd/sssd.conf')
assert conf.exists
assert conf.user == 'root'
assert conf.gro... | 776 | 274 |
# Generated by Django 2.2.5 on 2019-10-26 14:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('libros', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Pagina',
f... | 2,029 | 592 |
#
# Parsing operations - Operations such as file type detection and embedded file
# detection
#
# Copyright (c) 2019, Nobutaka Mantani
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#... | 24,886 | 8,545 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
import imagenet
from tensorflow.python.platform import gfile
from inception_v4 import inception_v4
from inception_v4 import inception_v4_arg_scope
from inception_v4 import ince... | 5,582 | 1,782 |
import cv2 as cv
import numpy as np
chessboard = [10, 7]
stereo_params = np.load('stereo_params.npz')
F = stereo_params['F']
left_params = np.load('left_params.npz')
left_intr = left_params['intr']
left_dist = left_params['dist']
right_params = np.load('right_params.npz')
right_intr = right_params['intr']
right_dis... | 2,037 | 959 |
import unittest
from geopy import exc
from geopy.compat import u
from geopy.point import Point
from geopy.geocoders import ArcGIS
from test.geocoders.util import GeocoderTestBase, env
class ArcGISTestCaseUnitTest(GeocoderTestBase):
def test_user_agent_custom(self):
geocoder = ArcGIS(
user_ag... | 2,775 | 986 |
from .resources import blp | 26 | 7 |
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
concant = sorted(nums1 + nums2)
pos = int((len(concant) + 1)/2) -1
if (len(concant) % 2) == 0:
median = (concant[pos] + concant[pos+1])/2
else:
median = concant[pos]
return float(median)
... | 466 | 199 |
import sys
from modelforge.logs import setup_logging
utmain = sys.modules['__main__']
if utmain.__package__ == "unittest" and utmain.__spec__ is None:
from collections import namedtuple
ModuleSpec = namedtuple("ModuleSpec", ["name"])
utmain.__spec__ = ModuleSpec("unittest.__main__")
del ModuleSpec
de... | 370 | 112 |
import tensorflow as tf
import cv2
import numpy as np
import os
import tensorflow.contrib.slim as slim # TensorFlow-Slim
# Number of classes=3(right, left,up)
# Defining training examples and labels
empty=[]
occupied=[]
examples=[]
error= 'error.txt'
error_file= open(error, 'w')
#Reading images
os.chdir('/home/ruchik... | 6,735 | 2,916 |
from __future__ import annotations
import datetime
import re
from typing import TYPE_CHECKING, Tuple, List, Union, Dict
from matchengine.internals.plugin_helpers.plugin_stub import (
QueryNodeTransformer,
QueryNodeClinicalIDsSubsetter
)
from matchengine.internals.typing.matchengine_types import (
QueryPar... | 7,308 | 2,262 |
class Result:
name: str
optimum: int
status: str
time: float
def __init__(self, name, optimum, status, time):
self.name = name
self.optimum = optimum
self.status = status
self.time = time | 241 | 75 |
"""
SSBJ test case - http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19980234657.pdf
Python implementation and OpenMDAO integration developed by
Sylvain Dubreuil and Remi Lafage of ONERA, the French Aerospace Lab.
"""
import numpy as np
from openmdao.api import Group, ExecComp, IndepVarComp
from ssbj_disciplines.... | 6,028 | 2,227 |
import os
import re
import requests
import boto3
import click
AWS_INSTANCE_DOC_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document'
class TagLoader(object):
def __init__(self, override_instance_doc=None, override_instance_id=None,
region=None):
self._override_instanc... | 3,098 | 924 |