content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from lxml import etree
from io import StringIO
from django.urls import path
from django.http import HttpResponse
from django.template import Template, Context, Engine, engines
def a(request):
xslt_root = etree.XML('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transf... | python |
from VisualisationPlugin import VisualisationPlugin
import pygame
import math
import logging
from DDRPi import FloorCanvas
class SineWaveVisualisationPlugin(VisualisationPlugin):
logger = logging.getLogger(__name__)
def __init__(self):
self.clock = pygame.time.Clock()
def configure(self, conf... | python |
import socket
sock = socket.socket()
address = "agps.u-blox.com"
port = 46434
print "Connecting to u-blox"
sock.connect((address, port))
print "Connection established"
print "Sending the request"
sock.send("cmd=full;user=korovkin@gmail.com;token=4HWt1EvhQUKJ2InFyaaZDw;lat=30.0;lon=30.0;pacc=10000;")
print "Sending th... | python |
import os.path as osp
from pathlib import Path
import pandas as pd
from jitenshea.stats import find_cluster
_here = Path(osp.dirname(osp.abspath(__file__)))
DATADIR = _here / 'data'
CENTROIDS_CSV = DATADIR / 'centroids.csv'
def test_find_cluster():
df = pd.read_csv(CENTROIDS_CSV)
df = df.set_index('cluste... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 22:40:34 2018
@author: boele
"""
# 03 read csv and find unique survey vessels...
# open csv file
f = open('fartoey_maaleoppdrag.csv', 'r')
data = f.read()
surveys_and_vessels = data.split('\n')
# print number of rows and show first 5 rows
print(len(su... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 11 13:59:21 2017
@author: tuur
"""
from __future__ import print_function
from dateutil import parser as dparser
from lib.evaluation import get_selective_rel_metrics, get_acc_from_confusion_matrix,save_confusion_matrix_from_metrics, viz_docs_rel_difference, save_entity_err... | python |
import pygame
from cell_class import *
import copy
vec = pygame.math.Vector2
CELL_SIZE = 20
class GameWindow:
def __init__(self, screen, x, y):
self.screen = screen
self.position = vec(x, y)
self.width, self.height = 600, 600
self.image = pygame.Surface((self.width, self.height))
... | python |
'''
Created on Jul 28, 2013
@author: akittredge
'''
import pandas as pd
import pymongo
class MongoDataStore(object):
def __init__(self, collection):
self._collection = collection
def __repr__(self):
return '{}(collection={})'.format(self.__class__.__name__,
... | python |
# -*- coding: utf-8 -*-
# Copyright 2018 Whitestack, LLC
# *************************************************************
# This file is part of OSM Monitoring module
# All Rights Reserved to Whitestack, LLC
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | python |
import json
from .miioservice import MiIOService
def twins_split(string, sep, default=None):
pos = string.find(sep)
return (string, default) if pos == -1 else (string[0:pos], string[pos+1:])
def string_to_value(string):
if string == 'null' or string == 'none':
return None
elif string == 'fa... | python |
import socket
import logging
logger = logging.getLogger(__name__)
class P2PSocket:
def __init__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
def bind(self, host, port):
logger.debug("Binding P2P socket to (%s, %i)", host, port)
self.s.bind((host, port))
self.s.setb... | python |
from django.shortcuts import render, get_object_or_404
from blog_posts.models import Post
from blog_posts.forms import PostForm
def index(request):
posts = Post.objects.all()
return render(request, 'administracao/index-admin.html', context ={"index": "Index",
... | python |
"""Algorithm for simulating a 2048 game using Monte-Carlo method."""
import random, _2048
SIMULATE_TIMES = 100000
DIRECTIONS = ('UP', 'DOWN', 'LEFT', 'RIGHT')
def simulate_to_end(game):
while game.get_state():
dircts = list(DIRECTIONS)
for i in xrange(3):
c = random.choice(dircts)
... | python |
# Define a procedure is_palindrome, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.
# Base Case: '' => True
# Recursive Case: if first and last characters don't match => False
# if they do match, is the middle a palindrome?
def is_palindrome(s):
#print is... | python |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import warnings
import mmcv
import numpy as np
import torch
from mmdet.core.visualization.image import imshow_det_bboxes
from ..builder import DETECTORS, build_backbone, build_head, build_neck
from .base import BaseDetector
INF = 1e8
@DETEC... | python |
#LordLynx
#Part of PygameLord
import pygame,os
from pygame.locals import*
pygame.init()
#Loading Objects
'''
Parse_Locations(file)
file: Your text file, use a .txt
# Like in Python will be ingored thusly follow this example
#Coment
./File/File
./File/Other File
...
'''
def Parse_Locations(file):
file = open(file,... | python |
from results_saver import LogWriter
from .ModelType import ModelType
from .lda_lsa_model_tester import LModelTester
from .naive_bayes_model_tester import NBModelTester
from .lsa_tester import LSAModelTester
from .svm_model_tester import SVMModelTester
from ..methods.Lda import Lda
from ..methods.Lsa import Lsa
from ..m... | python |
#!/usr/bin/env python3
import pathlib
import sys
sys.path += ['/opt/py', str(pathlib.Path.home() / 'py')]
import basedir
import shlex
import subprocess
def info_beamer_invocation():
custom_cmd = pathlib.Path.home() / '.config' / 'fenhl' / 'info-beamer'
if custom_cmd.exists():
return [str(custom_cmd)... | python |
import random
from app.core.utils import get_random_date
def build_demo_data():
"""
Helper method, just to demo the app
:return: a list of demo docs sorted by ranking
"""
samples = ["Messier 81", "StarBurst", "Black Eye", "Cosmos Redshift", "Sombrero", "Hoags Object",
"Andromeda", "Pi... | python |
#!/usr/bin/env python3
"""
Project Icarus
creator: derilion
date: 01.07.2019
version: 0.1a
"""
"""
TODO:
- Installer
- Database Structure
- Special Characters in *.ini
- Setup of skills
- Configuration of Clients
- multi language support
"""
# imports
from icarus.icarus import Icarus
# thread safe init
if __name_... | python |
import requests
import json
remote_url = ""
device_id = ""
bearer = ""
api_key = ""
app_id = ""
def url(endpoint):
return "{0}{1}".format(remote_url, endpoint)
def headers_with_headers(headers):
new_headers = {}
new_headers["Content-Type"] = "application/json"
new_headers["X-BLGREQ-UDID"] = devic... | python |
from .iotDualMotor import IotDualMotor
class IotEncodedMotor(IotDualMotor):
""" the base class for motor with encoder
The speed range from -100 to 100 with zero (less than minMovingSpeed) to stop the motor.
"""
def __init__(self, name, parent, minMovingSpeed=5):
""" construct a PiIotNode
... | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | python |
import sys
import argparse
from absynthe.graph_builder import TreeBuilder
def treeGeneration(numRoots: int = 2, numLeaves: int = 4,
branching: int = 2, numInnerNodes: int = 16):
loggerNodeTypes: str = "SimpleLoggerNode"
tree_kwargs = {TreeBuilder.KW_NUM_ROOTS: str(numRoots),
... | python |
import sys
import time
dy_import_module_symbols("shimstackinterface")
SERVER_IP = getmyip()
SERVER_PORT = 34829
UPLOAD_RATE = 1024 * 1024 * 15 # 15MB/s
DOWNLOAD_RATE = 1024 * 1024 * 128 # 15MB/s
DATA_TO_SEND = "HelloWorld" * 1024 * 1024
RECV_SIZE = 2**14 # 16384 bytes.
MSG_RECEIVED = ''
END_TAG = "@@END"
def launc... | python |
#%%
from pssr import pssr
from speech_recognition import UnknownValueError, RequestError, Recognizer
print('oi')
r = Recognizer() #recognizes audio, outputs transcript
ps = pssr.PSRecognizer() #PSRecognizer instance to listen and generate the audio
psmic = pssr.PSMic(nChannels=3) #ps eye mic array
with psmic as sour... | python |
from connect_four.envs import TwoPlayerGameEnvVariables
from connect_four.problem.connecting_group_manager import ConnectingGroupManager
class ConnectFourGroupManager(ConnectingGroupManager):
def __init__(self, env_variables: TwoPlayerGameEnvVariables):
super().__init__(env_variables, num_to_connect=4)
| python |
__author__ = 'Felix Simkovic'
__date__ = '2019-05-11'
__license__ = 'MIT License'
import os
import sys
APPLICATION_NAME = 'Pomodoro TaskWarrior'
if sys.platform.startswith('darwin'):
try:
from Foundation import NSBundle
bundle = NSBundle.mainBundle()
if bundle:
app_info = bun... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=C0103,C0111
import argparse
import sys
from snake.game import PureGame, GameConf
from snake.utils import dotdict
from snake.rl.coach import Coach
from snake.rl.nnet_wrapper import NNetWrapper
import logging
logging.basicConfig(level=logging.INFO)
sys.s... | python |
# flake8: noqa
# This file is autogenerated by /metadata-ingestion/scripts/avro_codegen.py
# Do not modify manually!
# fmt: off
from ......schema_classes import ChartKeyClass
from ......schema_classes import CorpGroupKeyClass
from ......schema_classes import CorpUserKeyClass
from ......schema_classes import Dashboard... | python |
# // Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT
# // file at the top-level directory of this distribution and at
# // https://github.com/go-vgo/robotgo/blob/master/LICENSE
# //
# // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# // http://www.apache.org/licenses/LICENSE-2.0> or... | python |
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
max_length = -1
visited = [False] * len(nums)
for i in range(0, len(nums)):
if visited[i]:
continue
start, count = nums[i], 0
visited[i] = True
... | python |
from typing import Dict, List
from elasticsearch_dsl.query import Q
from elasticsearch_dsl.response import Response
from elasticsearch_dsl.response.hit import Hit
from elasticsearch_dsl.search import Search
from flask_restful import Resource, reqparse
from meetup_search.models.group import Group
from .argument_valid... | python |
from a10sdk.common.A10BaseClass import A10BaseClass
class Crl(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param crl_sec: {"minLength": 1, "maxLength": 255, "type": "string", "description": "Secondary CRL File Name or URL (http://www.example.com/ocsp) (only .der file... | python |
"""
Noop migration to test rollback
"""
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('oauth_dispatch', '0010_noop_migration_to_test_rollback'),
]
operations = [
migrations.RunSQL(migrations.RunSQL.noop, reverse_sql=migrations.RunSQL.noop)
... | python |
from senscritiquescraper.utils import survey_utils
def test_get_category_from_survey(survey_movie):
if survey_utils.get_category_from_survey(survey_movie) != "films":
raise AssertionError()
def test_get_rows_from_survey(survey_movie):
rows = survey_utils.get_rows_from_survey(survey_movie)
if len... | python |
from jira.exceptions import JIRAError
from tests.conftest import JiraTestCase
class VersionTests(JiraTestCase):
def test_create_version(self):
name = "new version " + self.project_b
desc = "test version of " + self.project_b
release_date = "2015-03-11"
version = self.jira.create_ve... | python |
# -*- coding: utf-8 -*-
import logging
from _pytest.main import EXIT_OK, EXIT_NOTESTSCOLLECTED, EXIT_INTERRUPTED # NOQA
def assert_fnmatch_lines(output, matches):
if isinstance(output, str):
output = output.split('\n')
missing = []
for match in matches:
if match not in output:
... | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Deformable ConvNets v2: More Deformable, Better Results
# Modified by: RainbowSecret(yuyua@microsoft.com)
# Select Seg Model for img segmentation.
import pdb
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from collections import O... | python |
class LoggerError(Exception):
""" Base class for all logger error classes.
All exceptions raised by the benchmark runner library should inherit from this class. """
pass
class MethodError(LoggerError):
"""
This class is fot method error
"""
def __init__(self, method_name, exception):
... | python |
# Generated by Django 3.1.7 on 2021-12-24 18:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracker', '0005_movie_poster'),
]
operations = [
migrations.AddField(
model_name='movie',
name='cast',
f... | python |
"""Coding Quiz: Check for Prime Numbers
Prime numbers are whole numbers that have only two factors: 1 and the number itself. The first few prime numbers are 2, 3, 5, 7.
For instance, 6 has four factors: 1, 2, 3, 6.
1 X 6 = 6
2 X 3 = 6
So we know 6 is not a prime number.
In the following coding environment, write cod... | python |
import timm
import torchvision.models as models
""""
timm_models = [
'adv_inception_v3',
'cait_m36_384',
'cait_m48_448',
'cait_s24_224',
'cait_s24_384',
'cait_s36_384',
'cait_xs24_384',
'cait_xxs24_224',
'cait_xxs24_384',
'cait_xxs36_224',
'cait_xxs36_384',
'coat_lite_min... | python |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
"""
Service monitor to instantiate/scale/monitor services like firewall, LB, ...
"""
import sys
reload(sys)
sys.setdefaultencoding('UTF8')
import gevent
from gevent import monkey
monkey.patch_all(thread=not 'unittest' in sys.modules)
from cfgm_comm... | python |
from .db.models import ModelWorker
from .db.connection import DbEngine
ModelWorker.metadata.create_all(DbEngine)
| python |
import string
def encotel(frase):
teclado = {
'abc' : '2',
'def' : '3',
'ghi': '4',
'jkl': '5',
'mno' : '6',
'pqrs' : '7',
'tuv' : '8',
'wxyz' : '9',
}
numeros = []
for letra in frase:
if letra not in string.letters:
numeros.append(letra)
continue
numeros.extend([teclado[chave... | python |
import itertools
import beatbox
import pandas as pd
def query_salesforce(line, query=''):
"""Runs SQL statement against a salesforce, using specified user,password and security token and beatbox.
If no user,password and security token has been given, an error will be raised
Examples::
... | python |
#!/usr/bin/env python3
import functools
import logging
import queue
import threading
class AsyncCaller:
'''Singleton class which executes function calls in separate thread'''
class _Caller:
class Thread(threading.Thread):
def __init__(self, queue, error_handler):
self.queue... | python |
from pyson0.json0diff import diff
from pyson0.json0 import TypeJSON | python |
import uuid
import json
import os
import pytest
import postgraas_server.backends.docker.postgres_instance_driver as pid
import postgraas_server.backends.postgres_cluster.postgres_cluster_driver as pgcd
import postgraas_server.configuration as configuration
from postgraas_server.backends.exceptions import PostgraasApiE... | python |
import argparse
import ibapi
from ib_tws_server.codegen.asyncio_client_generator import AsyncioWrapperGenerator
from ib_tws_server.codegen import *
from ib_tws_server.api_definition import *
import logging
import os
import shutil
import sys
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
def generate(out... | python |
import unittest
from cornflow_client.airflow import dag_utilities as du
from unittest.mock import Mock, patch
class DagUtilities(unittest.TestCase):
@patch("cornflow_client.airflow.dag_utilities.CornFlow")
def test_env_connection_vars(self, CornFlow):
secrets = Mock()
conn_uris = [
... | python |
import http
import json
from unittest import mock
import pytest
from sqlalchemy import orm
from todos import crud, db, serializers
from todos.db import models
@pytest.fixture()
def exemplary_event_path_parameters(exemplary_task_model: models.Task) -> dict:
return {"task_id": exemplary_task_model.id}
@pytest.f... | python |
'''Standard Simple feedforward model
feedforward takes in a single image
Model-specific config.py options: (inherits from models.base_net):
'batch_size': An int. The number of input bundle to use in a batch
'hidden_size': An int. The size of representation size before FC layer
In metri... | python |
"""
"""
PROMPT_COLORS = {
"purple": '\033[95m',
"blue": '\033[94m',
"green": '\033[92m',
"yellow": '\033[93m',
"red": '\033[91m',
"bold": '\033[1m',
"underline": '\033[4m'}
PROMPT_TAILER = '\033[0m'
class ColoredPrinter(object):
def __init__(self, color):
if not color in P... | python |
import math
import os
import random
import re
import sys
n = int(input())
arr = list(map(int, input().rstrip().split()))
numSwaps = 0
i = 0
while(i < len(arr)-1):
if arr[i] != i+1:
tmp = arr[i]
arr[i], arr[tmp-1] = arr[tmp-1], arr[i]
numSwaps += 1
else:
i += 1
print(numSwaps)... | python |
"""
This is a reST markup explaining the following code, compatible with
`Sphinx Gallery <https://sphinx-gallery.github.io/>`_.
"""
# You can convert the file to a Jupyter notebook using the
# sphx_glr_python_to_jupyter.py utility from Sphinx Gallery.
import math
sin = math.sin(0.13587)
print(sin)
#%%
# And a sum w... | python |
import os.path
from os import listdir
import re
from numpy.distutils.core import setup
def find_version(*paths):
fname = os.path.join(os.path.dirname(__file__), *paths)
with open(fname) as fp:
code = fp.read()
match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", code, re.M)
if match:
... | python |
# Simulate a Thomas cluster process on a rectangle.
# Author: H. Paul Keeler, 2018.
# Website: hpaulkeeler.com
# Repository: github.com/hpaulkeeler/posts
# For more details, see the post:
# hpaulkeeler.com/simulating-a-thomas-cluster-point-process/
import numpy as np; # NumPy package for arrays, random number ... | python |
#
# (c) 2019, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible_collections.cisco.ios.tests.unit.compat.mock import patch
from ansible_collections.ci... | python |
# Generated by Django 4.0 on 2021-12-29 18:47
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('games', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='game',
... | python |
#! /usr/bin/env python3
import sys
f = sys.stdin
s = f.read()
words = s.split()
n = len(words)
d = {}
for w in words:
if w in d:
d[w] += 1
else:
d[w] = 1
def foo(s):
return d[s]
#sorted_keys = sorted(d.keys(), key=foo, reverse=True)
sorted_keys = sorted(d.keys(), key = lambda x: d[x],... | python |
# -*- coding: utf-8 -*-
""" Generic tests for all animations.
These tests run against all animation classes found in
earthstar.effects.animations.*.
"""
import glob
import os
import pytest
import earthstar.effects.animations as animations
from earthstar.effects.engine import EffectEngine
from earthstar.fra... | python |
import pandas as pd
import os
import sys
in_dir = sys.argv[1]
types = ['Right', 'Left']
out_df_base = 'russian_combined_{}'
files = [os.path.join(in_dir, f) for f in os.listdir(in_dir)
if f.lower().endswith('.csv')]
# dfs = [pd.read_csv(f) for f in files]
for type in types:
outdir = type.lower()
if ... | python |
""" Contains all the models that can be used to impute missing data. """
from .daema import Daema
from .holoclean import Holoclean
from .mida import MIDA
from .miss_forest import MissForestImpute
from .baseline_imputations import MeanImputation, Identity
MODELS = {
"DAEMA": Daema,
"Holoclean": Holoclean,
... | python |
from django.contrib import admin
from .models import AdminlteLog, AdminlteLogType
admin.site.register(AdminlteLog)
admin.site.register(AdminlteLogType)
| python |
from libsvm.python.svmutil import *
from libsvm.python.svm import *
import os
import struct
import numpy
dic={}
#数据加载函数,kind值标明了读取文件的类型
def loadforSVM(path, kind='train'):
labels_path = os.path.join(path,'%s-labels.idx1-ubyte'% kind)
images_path = os.path.join(path,'%s-images.idx3-ubyte'% kind)
wi... | python |
from abc import abstractmethod, ABC
from typing import Callable, TypeVar
T = TypeVar("T")
class Policy(ABC):
@abstractmethod
def execute(self, function: Callable[[], T]) -> T:
"""
Accepts lambda function and execute it with pre-defined policy parameters
Example: p.execute(lambda: api.... | python |
# Generated by Django 4.0.2 on 2022-03-06 06:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0002_challenges_game_delete_choice_delete_question_and_more'),
]
operations = [
migrations.AddField(
model_name='game',... | python |
import os, sys, time
sys.path.append(os.getcwd())
import torch
import torchvision
from torch import nn
from torch import autograd
from torch import optim
import torch.nn.functional as F
import time
import tflib as lib
import tflib.save_images
import tflib.mnist
import tflib.cifar10
import tflib.plot
#import tflib.in... | python |
# @Author: Anas Mazouni <Stormix>
# @Date: 2017-05-17T23:59:31+01:00
# @Email: madadj4@gmail.com
# @Project: PluralSight Scraper V1.0
# @Last modified by: Stormix
# @Last modified time: 2017-05-18T17:08:22+01:00
import selenium as sl
import os,time,inspect
from sys import platform
from selenium import webdriver
f... | python |
''' Learning rate schedulers. '''
import json
import torch
import torch.optim.lr_scheduler as lr_sched
from typing import Any
from cosine_scheduler import CosineLRWithRestarts
def step(optimizer, last_epoch, step_size=10, gamma=0.1, **_) -> Any:
return lr_sched.StepLR(optimizer, step_size=step_size, gamma=gam... | python |
#!/usr/bin/python
# encoding: utf-8
"""
@author: Ian
@file: serializers.py.py
@time: 2019-04-30 12:23
"""
from rest_framework import serializers
from snippets.models import Snippet
from dicproj.models import Dic, CsvFile
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
... | python |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import app.core.patch
# La solución planteada tiene ventajas y desventajas. Como ventaja, se usa el
# sistema de autenticación d... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" run_file2db is a tool to migrate a labeled dataset in a pickle file to a
mongo db.
It must be invoked using
python run_file2db.py <project_folder>
Created on Dec, 2016
@autor: Jesus Cid.
"""
import ast
import time
import sys
import os
import... | python |
from django.contrib.auth.models import User
from django.db import models
import datetime as dt
from tinymce.models import HTMLField
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if ... | python |
"""
This code is based on these codebases associated with Yuta Saito's research.
- Unbiased Recommender Learning from Missing-Not-At-Random Implicit Feedback: https://github.com/usaito/unbiased-implicit-rec-real
- Unbiased Pairwise Learning from Biased Implicit Feedback: https://github.com/usaito/unbiased-pairwise-rec
... | python |
def is_super(connection):
with connection.cursor() as cursor:
cursor.execute('show grants for current_user()')
query_result = cursor.fetchone()
return 'SUPER' in query_result
| python |
from pixiedust.display.app import *
@PixieApp
class TestEntity():
@route()
def main_screen(self):
return """
<h1><center>Simple PixieApp with dynamically computed dataframe</center></h1>
<div pd_entity="compute_pdf('prefix')" pd_options="handlerId=dataframe" pd_render_onload></div>
... | python |
# --coding:utf-8--
#
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License,
# attached with Common Clause Condition 1.0, found in the LICENSES directory.
import pytest
from nebula2.graph import ttypes
from tests.common.nebula_test_suite import NebulaTestSuite
... | python |
from os import environ
from .app_settings import *
SECRET_KEY=environ.get('SECRET_KEY')
STATIC_ROOT=environ.get('STATIC_ROOT')
ALLOWED_HOSTS = list(environ.get('ALLOWED_HOSTS', default='').split(','))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': environ.get('DB_NAME... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-23 08:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cms', '0020_old_tree_cleanup'),
('articles', '0002... | python |
class Solution:
# Solution using Mancher's Algorithm
@staticmethod
def longest_palindromic(s: str) -> str:
if(type(s) != str):
raise ValueError(f"{type(s)} not allowed only string type is allowed")
def adjust_string(s: str) -> str: # method to adjus... | python |
#!/usr/bin/env python
# coding=utf-8
# ====================================================
#
# File Name : pc_nd_conv_plot.py
# Creation Date : 17-04-2018
# Created By : Min-Ye Zhang
# Contact : stevezhang@pku.edu.cn
#
# ====================================================
from __future__ import print_f... | python |
sandwich_orders = ['pastrami', 'fish', 'pastrami', 'cabbage', 'pastrami', 'sala', 'pig', 'chicken']
finished_sandwich_orders = []
print(sandwich_orders)
print("'pastrami' soled out!")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
while sandwich_orders:
finished ... | python |
import tensorflow as tf
import src.lib as tl
class DNN:
def __init__(self,conf_data):
n_classes = len(conf_data["classes_list"])
data_size = conf_data["size"]
self.name = "selector"
self.show_kernel_map = []
with tf.name_scope('Input'):
self.input = tf.placehol... | python |
"""
Wrap Google Prediction API into something that looks
kind of like the standard scikit-learn interface to
learning models.
Derived from Google API example code examples found here:
https://github.com/google/google-api-python-client
@author: Jed Ludlow
"""
from __future__ import print_function
import argparse
i... | python |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation
# {"feature": "Coupon", "instances": 8147, "metric_value": 0.4744, "depth": 1}
if obj[0]>1:
# {"feature": "Education", "instances": 5889, "metric_value": 0.4676, "depth": 2}
if obj[1]>1:
# {"feature": "Occupation", "instances": 3337,... | python |
from typing import Callable, Dict, Optional
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from kornia.metrics import accuracy, mean_average_precision, mean_iou
from .trainer import Trainer
from .utils import Configuration
class ImageClassifierTrainer(Trainer):
"""Module to be used ... | python |
# Created on Mar 07, 2021
# author: Hosein Hadipour
# contact: hsn.hadipour@gmail.com
import os
output_dir = os.path.curdir
str_feedback1 = lambda a24, b15, b0, b1, b2: a24 + ' + ' + b15 + ' + ' + b0 + ' + ' + b1 + '*' + b2
str_feedback2 = lambda b6, a27, a0, a1, a2: b6 + ' + ' + a27 + ' + ' + a0 + ' + ' + a1 + '*'... | python |
from django.utils.translation import ugettext_lazy as _
from django.contrib.comments.models import CommentFlag
from django.contrib.comments.admin import CommentsAdmin
from django.contrib import admin
from scipy_central.comments.models import SpcComment
class SpcCommentAdmin(CommentsAdmin):
"""
Custom admin in... | python |
# 3.11 随机选择
import random
values = [1,2,3,4,5,6]
for i in range(0, 4):
print(random.choice(values))
for i in range(0, 4):
print(random.sample(values, 2))
random.shuffle(values)
print(values)
for i in range(0, 10):
print(random.randint(0, 10))
for i in range(0, 3):
print(random.random())
print(random.ge... | python |
import json
from pytorch_pretrained_bert import cached_path
from pytorch_pretrained_bert import OpenAIGPTTokenizer
from keras_gpt_2 import load_trained_model_from_checkpoint, get_bpe_from_files, generate
tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt')
url = "s3://datasets.huggingface.co/personachat/person... | python |
import unittest
import pandas as pd
import os
from requests import Response
from computerMetricCollector.metricsCollector.StorageAPI import store_to_database
from computerMetricCollector.crypto import encrypt_data
from computerMetricCollector.test.crypto import read_key, decrypt_data
from computerMetricCollector... | python |
import unittest
from util.bean import deepNaviReqToNaviModel
from model import DeepNaviReq
import time
def generateReq():
req = DeepNaviReq()
req.time = int(time.time() * 1000)
print()
# magnetic = req.magneticList.add()
# magnetic.x = 1
# magnetic.y = 2
# magnetic.z = 3
accelerometer = ... | python |
# Generated by Django 2.1.11 on 2019-12-03 21:08
from django.db import migrations
from qatrack.qatrack_core.dates import (
format_as_date,
format_datetime,
parse_date,
parse_datetime,
)
def datestrings_to_dates(apps, schema):
TestInstance = apps.get_model("qa", "TestInstance")
for ti in Te... | python |
#!/usr/bin/env python
"""Software Carpentry Windows Installer
Helps mimic a *nix environment on Windows with as little work as possible.
The script:
* Installs nano and makes it accessible from msysgit
* Provides standard nosetests behavior for msysgit
To use:
1. Install Python, IPython, and Nose. An easy way to ... | python |
import sqlalchemy as sa
from sqlalchemy import orm
from data.db_session import BaseModel
import datetime
class Post(BaseModel):
__tablename__ = 'posts'
__repr_attrs__ = ["title", "tournament"]
serialize_only = (
"id",
"title",
"content",
"status",
"now",
"t... | python |
from geniusweb.issuevalue.Bid import Bid
from geniusweb.issuevalue.Domain import Domain
from geniusweb.issuevalue.Value import Value
from geniusweb.profile.utilityspace.LinearAdditive import LinearAdditive
from tudelft.utilities.immutablelist.AbstractImmutableList import AbstractImmutableList
from tudelft.utilities.i... | python |
import discord
from discord.ext import commands
from WhiteFox.core.config.config import Config
class WhiteFox(commands.Bot):
def __init__(self, token=None, client_id=None, prefixes=None):
self.configs = None
self._init_configs()
if token is not None:
self.configs.discord.toke... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.