text stringlengths 38 1.54M |
|---|
#!/usr/bin/python3
"""
1
"""
from fabric.api import local
from datetime import datetime
from os import mkdir
def do_pack():
""" compress web_static """
try:
mkdir("versions")
except:
pass
path = datetime.now().strftime("versions/web_static_%Y%m%d%H%M%S.tgz")
r = local("tar -c ... |
# -*- coding: utf-8 -*-
from odoo.tests import common
from odoo.exceptions import ValidationError
import logging
_logger = logging.getLogger(__name__)
class TestTransfert(common.TransactionCase):
def setUp(self):
super(TestTransfert, self).setUp()
# cree l'entrepot
self.entrepot = self... |
"""Routines for encoding/decoding marker numbers about code holes
When rendered onto a marker, some numbers look too much like other
numbers. Therefore, libkoki does not use some marker numbers. To
maintain library usability, marker numbers are shifted around these
gaps.
Definitions:
* User-friendly code: The mark... |
from math import *
def calcAngle(h,m):
if (h == 12):
h = 0
if (m == 60):
m = 0
hour_angle = 0.5 * (h * 60 + m)
minute_angle = 6 * m
angle = abs(hour_angle - minute_angle)
angle = min(360 - angle, angle)
return radians(angle... |
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/chatnlu')
agent = Agent.load('./models/dialogue', interpreter=nlu_interpreter)
while True:
statement = unicode(raw_input("User: "))
print ("bot: " + agent.handle_messag... |
"""
身份验证
"""
# username = input('请输入用户名')
# password = input('请输入密码')
# if username == 'admin' and password == '123456':
# print('欢迎回家')
# else:
# print('密码错误')
"""
分段函数
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
"""
# x = float(input('请输入未知数x:'))
# if x > 1:
# y = 3 * x... |
#!/usr/bin/env python
import numpy as np
import qptraj.qpStruct as qpst
from numpy.polynomial import polynomial as poly
from cvxopt import matrix, solvers
class WayPoints:
"""
In xyzY mode,
pass a list of waypoints as numpy array
with shape (n_waypointss, 4)
"""
def __init__(self, wps=None, time_interval... |
def main():
import sys
N,S=list(map(int,sys.stdin.readline().split()))
def dfs(a,idx,tup):
if a==S and idx==N:
print(' '.join([str(x) for x in tup]))
return
for i in range(tup[-1] if tup else 1,51):
if a+i<=S:
if tup:
df... |
from design_baselines.data import StaticGraphTask
from design_baselines.logger import Logger
from design_baselines.utils import spearman
from design_baselines.coms_original.trainers import ConservativeMaximumLikelihood
from design_baselines.coms_original.trainers import TransformedMaximumLikelihood
from design_baseline... |
# save result to use later
def use_later(result):
global saved_result
saved_result = [0] * 12
u = input("Do you wish to save this result for later use? ")
if u == 'yes' or u == 'ye' or u == 'y':
saved_result = result
else:
return
def transpose(row):
x = int((input("Transpositi... |
'''
四:自省的威力.
自省是指代码可以查看内存中以对象形式存在的其它模块和类.获取它们的信息.并对它们进行操作.
本章包含以下内容:
1.可选参数和命名参数的使用. -> params.py
2.使用type,str, dir和其他内置函数. -> build-function.py
3.通过getattr获取对象引用. -> getattr.py
4.过滤列表 [mapping-expression for element in source-list if filter-expression] -> list_filter.py
5.and 和 or 的特殊使用. bool ? a : b 三目运算. and_or.p... |
from tkinter import *
import tkinter.messagebox
import math
window=Tk()
window.title('SCIENTIFIC CALCULATOR')
window.configure(background='maroon')
window.resizable(width= False , height= False)
window.geometry('480x568+0+0')
calc=Frame(window)
calc.grid()
menubar=Menu(calc)
#=... |
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
app_name = "adminbase"
urlpatterns = [
url(r'^', include('dashboard.urls', namespace='dashboard')),
url(r'^', include('game.urls', namespace='game')),
url(r'^admin/', admin.site.u... |
def IsYearLeap(year):
if year < 1582:
return True
if year % 100 == 0:
return True
elif year % 4 != 0:
return False
elif year % 400 == 0:
return False
else:
return False
#
# your code is already here (from Lab 3.3.12.1)
#
def DaysInMonth(year,m... |
import trendet
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# from io import StringIO
# import StringIO
import pandas as pd
import io
from datetime import datetime
# written differently then plot function because it needs to be calculated for all
# stocks while plotting is only for specific... |
#Write a function that returns the number of digits in a number.
def countDigits(x):
var1 = len(str(x))
return var1
|
import pygame, random, sys
from pygame.locals import *
fps = 15
win_wt = 640
win_ht = 480
cell_sz = 20
assert win_wt%cell_sz == 0, "qwerty"
assert win_ht%cell_sz == 0, "qwerty"
cell_wt = int(win_wt/cell_sz)
cell_ht = int(win_ht/cell_sz)
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
... |
Join = input('Would you like to join me?')
if Join == 'yes' or 'Yes':
print("Great," + myName + '!')
else:
print ("Sorry for asking...")
|
# Copyright (c) 2018, Manfred Moitzi
# License: MIT License
import sys
import ezdxf
def print_layout(layout):
dxf = layout.dxf_layout.dxf
print("#LAYOUT: {}".format(layout.name))
print("##PLOT SETTINGS:")
print("(1) page_setup_name: {} ".format(dxf.plot_configuration_file))
print("(2) plot_config... |
'''
Reverse an array
'''
def reverseArray(arr):
return arr[::-1]
# or, return arr.reverse()
arr = [1, 2, 3, 4]
arr = reverseArray(arr)
print(arr)
|
"""add verified by
Revision ID: a9b02ffedfb7
Revises: 4dc8f9e0ce7a
Create Date: 2020-05-09 16:30:44.861974
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a9b02ffedfb7'
down_revision = '4dc8f9e0ce7a'
branch_labels = None
depends_on = None
def upgrade():
... |
# -*- encoding: utf-8 -*-
from openerp import fields, models, exceptions, api, _
import base64
import csv
import cStringIO
from openerp.exceptions import except_orm, Warning, RedirectWarning
class TiposNotacredito(models.Model):
_name = "tipo.nota.debito.factura"
name = fields.Char("Tipo de Nota")
cuenta... |
{
'name': 'Sample Addin',
'description': 'Provides a sample add-in.',
'author': 'JamesGreenAU',
'depends': ['base'],
'application': True,
'summary': "Provides a sample add-in.",
'website': "https://deepdark.net",
'license': "Other proprietary", # Valid types are here: http://useopenerp.com/v8/model/ir-m... |
# encoding=utf-8
from abc import ABCMeta, abstractmethod
class JsonSerializable(metaclass=ABCMeta):
@abstractmethod
def as_structure(self): # pragma: no cover
"""
:returns Structure suitable for JSON serialisation.
:rtype: dict
"""
raise NotImplementedError()
@sta... |
#!/usr/bin/env python
from bearlibterminal import terminal
from clubsandwich.blt.state import blt_state
from clubsandwich.director import Scene
from clubsandwich.geom import Size
from clubsandwich.ui import (
FirstResponderContainerView,
)
class UIScene(Scene):
"""
:param list|View views: One or more subv... |
from django.conf.urls import url
from jenkinsapi.views import JenkinsSearchNode,JekinsAddNode
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
url(r"^node/list/$",JenkinsSearchNode.as_view(),name="jenkins_search_node"),
url(r"^node/add/$",csrf_exempt(JekinsAddNode.as_view()),name="jenkins_a... |
# -*- coding: utf-8 -*-
# @PRODUCTION MODULE
from pygeotoolbox.sharedtools import listToSqlStr, printRows
import postgis
from workflow import WorkflowItem
import sharedtools.config as config
def validateDatabaseConnection():
import psycopg2
try:
paramString = postgis.buildConnectionParams(config.d... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
@staticmethod
def get_length(head: ListNode) -> int:
node = head
cnt = 0
while node is not None:
node = node.next
... |
#n = int(input())
h = n // 60**2
n = n - h * 60**2
m = n // 60
n = n - m*60
s = n
print('{}:{}:{}'.format(h, m, s))
|
from django.http import HttpResponse
from django.template import RequestContext, loader
from .models import Tool
def index(request):
tools_list = Tool.objects.all()
template = loader.get_template('hello/index.html')
context = RequestContext(request, {
'tools_list': tools_list,
})
return Ht... |
from app.utilities.data import Data
from app.engine.objects.unit import UnitObject
from app.engine.objects.tilemap import TileMapObject
from app.events.regions import Region
from app.data.level_units import UnitGroup
# Main Level Object used by engine
class LevelObject():
def __init__(self):
self.nid: str... |
__author__ = 'wgf'
__date__ = ' 上午12:00'
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory
class EchoServer(Protocol):
def dataReceived (self, data): #将收到的数据返回给客户端
self.transport.write(data)
self.transport.loseConnection()
print (data)
facto... |
import sys
_module = sys.modules[__name__]
del sys
coco = _module
config = _module
demo = _module
model = _module
nms = _module
build = _module
nms_wrapper = _module
pth_nms = _module
roialign = _module
roi_align = _module
build = _module
crop_and_resize = _module
roi_align = _module
utils = _module
visualize = _module... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Virtual Cable S.L.
# 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 notice,
#... |
'''utils for env-switcher
'''
import json
import config
import base64
import codecs
def dict_to_json(d_dict, json_name):
'''write dict to json
'''
with codecs.open(json_name, 'w', 'utf-8') as writer:
json.dump(d_dict, writer, indent=4)
def json_to_dict(json_name):
'''fetch dict from json
... |
# 28. Implement strStr()
class Solution(object):
# brute-force 1
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
lh , ln = len(haystack), len(needle)
if ln == 0: return 0
for i in range(lh - ln + 1):
... |
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
#This is a simple example for a custom action which utters "Hello World!"
from typing import Any, Text, Dict, List
... |
from django import forms
from django.contrib.auth.backends import get_user_model
from .models import Month, Day
User = get_user_model()
class MonthAddForm(forms.ModelForm):
user = forms.ModelChoiceField(User.objects.filter(is_superuser=False))
class Meta:
model = Month
fields... |
"""
This is your project's master URL configuration, it defines the set of "root" URLs for the entire project
https://docs.djangoproject.com/en/1.6/topics/http/urls/
"""
from django.conf.urls import patterns, url, include
from django.contrib import admin
# https://docs.djangoproject.com/en/dev/ref/contrib/admin/#disc... |
# Generated by Django 3.0 on 2021-05-09 09:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blogcms', '0009_auto_20210509_0746'),
]
operations = [
migrations.AlterField(
model_name='post',
name='excerpt',
... |
class ECG:
def __init__(self, t_list=None, v_list=None, delta_t=None, minutes=1.0):
self.t_list = t_list
self.v_list = v_list
self.duration = t_list[len(t_list)-1]
self.delta_t = delta_t
self.num_beats = 0
self.beats = None
self.voltage_extremes = ()
s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-07 18:46
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('django_app', '0002_auto_20171107_1434'),
]
operati... |
"""
This module contains functions devoted to finding recursive components of
the graph formed by an Avro schema.
Recursion only occurs for named types which contain a reference to their own
name. Only a few types can have names: records, enums, and fixeds.
In addition, only a few types can contain a reference to a n... |
import numpy as np
import matplotlib.pyplot as plt
from random import choice
from pyprind import ProgPercent
def find_factorization(x):
def loss(x, n, m):
return 1*abs(x - n*m) + 2*abs(n - m)
def solve(x):
(n_min, m_min), loss_min = (None, None), float('inf')
for n in range(1, x + 1):
... |
import json
import urllib
from flask import Flask, request, session
import requests
app = Flask(__name__)
API_KEY = 'XHJK73jsad753dGKNLCUWD6D57dx'
NEW_API = 'http://api.vionel.com/{0}'
def auth(path, headers=None, data=None):
new_api = NEW_API
url = new_api.format(path)
print "url: {0}".format(url)
... |
import webapp2
from load import *
class LoadAllPage(webapp2.RequestHandler):
def code(self):
c = "<html><body>"
c += "1. <a href='/a/load_players?batch_size=100'>Load Players</a><br>"
c += "2. <a href='/a/load_teams?batch_size=100'>Load Teams</a><br>"
c += "3. <a hre... |
#
# @lc app=leetcode id=13 lang=python
#
# [13] Roman to Integer
#
# @lc code=start
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
symbol = {'I':1, 'V':5 , 'X':10 , 'L':50 , 'C':100 , 'D':500 , 'M': 1000}
tmp = 0
i=len(s)-1... |
# coding=utf-8
"""
Given a sequence, find the length of the longest palindromic subsequence in it.
if the given sequence is “BBABCBCAB”, then the output should be 7 as
“BABCBAB” is the longest palindromic subseuqnce in it.
“BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence,
but not the longest... |
__author__ = 'praveen'
from parser.ctgov import ClinicalTrial_Parser as CT_Parser
from textAnnotator.conceptMatching import DictionaryMapping
from textAnnotator.filters import ConceptFilters
from dictionary.umls import UMLSDict
from util.log import strd_logger
from multiprocessing import Process
from util.load import l... |
from django.db import models
from datetime import datetime
# Create your models here.
class Categoria(models.Model):
Nombre = models.CharField(max_length=20,null=True,default='Ninguno')
def __str__(self):
return self.Nombre
class Producto(models.Model):
Categoria = models.ForeignKey(Categoria, on_delete=mo... |
import signal
from sys import exit
import autopy
import skywriter
import os
width, height = autopy.screen.get_size()
@skywriter.touch()
def touch(position):
if(position=='south'):
print("broadcast music")
os.system('mplayer 2233.mp3')
if(position=='north'):
print('pause')
@skywri... |
import urllib.request
import json
from pprint import pprint
hostname = "localhost"
port = "8081"
search_id_url = f"http://{hostname}:{port}/api/contact/search/id"
search_name_url = f"http://{hostname}:{port}/api/contact/search/name"
add_contact_url = f"http://{hostname}:{port}/api/contact/"
headers = {
"Content-Ty... |
# SPDX-FileCopyrightText: 2020 Lukas Schrangl <lukas.schrangl@tuwien.ac.at>
#
# SPDX-License-Identifier: BSD-3-Clause
from .main_window import MainWindow # noqa F401
|
from googleapiclient.discovery import build
import json
import sys
import googleapiclient.discovery
# Run on GCP
gce_service = build('compute', 'v1')
# -------------------------------------------------------------
def delete_reservation(request):
request_json = request.get_json()
project = request_json['pro... |
from collections import deque
def solution2(tickets):
answer = []
tickets.sort(key=lambda x:x[1])
road=deque()
start='ICN'
road.append(start)
while tickets:
for i in tickets:
if i[0]==start:
road.append(i[1])
start=i[1]
tick... |
n = int(input())
box = [0] + list(map(int, input().split()))
count = [1] * (n+1)
for i in range(2, n+1):
for j in range(i-1, 0, -1):
if box[j] < box[i]:
count[i] = max(count[i], count[j]+1)
print(max(count))
|
import unittest
from shutil import rmtree
from os import getcwd, mkdir
from os.path import join, isfile, isdir
from random import uniform, randint
import gensim
from nltk.corpus import stopwords
stopwords = set(stopwords.words("english"))
LabeledSentence = gensim.models.doc2vec.LabeledSentence
from data_gathering i... |
import cv2
import numpy as np
'''
Author Name: Manas Gupta
Date : 4:35 AM 2/7/2020
Description : This code will just identify all the red objects nearby seen through camera
'''
cap=cv2.VideoCapture(1)
#cap=cv2.VideoCapture(0)
''' if you are using your webcam change your camera to 0
I used my mobile camera to test t... |
'''
We have seen issue with multiple threads accessing a shared resource in threading2.py
This program addresses the issue by using thread synchronization which ensures that only one thread has access to common resource at a given point of time
this is achieved by acquiring the lock, perform the operation and then rele... |
#Example
import ui
import dbg
import app
import player
import wndMgr
import renderTarget
class Dialog1(ui.Window):
RENDER_TARGET_INDEX = 1
def __init__(self):
ui.Window.__init__(self)
self.max_pos_x = wndMgr.GetScreenWidth()
self.max_pos_y = wndMgr.GetScreenHeight()
self.BuildWindow()
def __del__(self):... |
# -*- coding: utf-8 -*-
from django import forms
from .models import Account
class PaymentForm(forms.Form):
origin_account = forms.ChoiceField(choices=[])
dest_account = forms.ChoiceField(choices=[])
amount = forms.DecimalField(label="Amount({})".format('£'), max_digits=10)
def __init__(self, *args,... |
def f():
return 3
def test_function_pass():
assert f() == 3
def test_function_failure():
assert f() == 4
|
from enum import Enum
class BaseEnum(Enum):
@classmethod
def has_value(cls, value):
return value in cls._value2member_map_
@classmethod
def all_key_value_str(self) -> str:
return BaseEnum.key_value_str(list(self))
@classmethod
def key_value_str(cls, selected_enumlist) -> str... |
from utils import util
import math
class MapManager(object):
#singleton implementation
instance = None
def __init__(self):
if not MapManager.instance:
MapManager.instance = MapManager.__MapManager()
def __getattr__(self, name):
return getattr(self.instance, name)
class __MapManager():
MAP = []
... |
from pathlib import Path
import torch
import netron
from algorithm.multi.ddpg import Actor, Critic
from algorithm.utils import get_multi_agent
from config import config, params
from make_env import make_env
import numpy as np
algorithm = "ddpg"
env = make_env(config["scenario"])
state_dim = env.observation_space[0... |
from functions_smc import *
import pickle
N_particles = 2500
#epsilon = np.array([2.,1.])
if True:
epsilon = np.array([2.,1.5,1,0.5,0.2,0.1,0.08,0.065,0.05,0.04,0.03,0.02,0.01])
smc_abc_rqmc = smc_sampler_abc(epsilon, N_particles, delta, y_star, simulator, random_sequence_rqmc, uniform_kernel, 2)
smc_abc_rqmc.initi... |
# _*_ coding: utf-8 _*_;
# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import Http404
from village.models import *
from tagging.models import TaggedItem
from django.http import HttpResponseRedirect
from django.co... |
#!/usr/bin/env python3
#Se pide al usuario el numero de mes
mes = int(input("Ingresa el numero del mes: "))
#Se valida si el numero ingresado es igual a la fecha
if mes == 1:
print("El mes",mes,"es Enero")
elif mes == 2:
print("El mes",mes, "es Febrero")
elif mes == 3:
print("El mes",mes,"es Marzo")
elif ... |
from functools import lru_cache
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy_utils.functions import database_exists, create_database
from ..settings import get_settings
@lru_cache()
def get_engine():
# determines driver
settings = get_settings... |
class Animal:
def _init_(self,name,age):
self.name=name
self.age=age
print("Name:",self.name)
print("Age:",self.age)
class Dog():
def dogmod(self,mod,color):
self.mod=mod
self.color=color
print("Mode:",self.mod)
print("Color:",self.color)
class Pom... |
import os
import sys
import shutil
import glob
import argparse
import pandas as pd
import glob2
import md5
import random
from os.path import dirname, join, realpath, split, abspath
import logging
logging.basicConfig(filename='debug.log',level=logging.DEBUG)
sys.path.insert(1, '/Users/skhaz/google-cloud-sdk/platfor... |
'''
This code demonstrates a session inside a dialogflow bot for parsing intents
Web Demo:
https://bot.dialogflow.com/3b6b0c55-7d58-4273-be17-12256f0dbc6c
'''
import requests
import os
import dialogflow
from google.api_core.exceptions import InvalidArgument
import json
ENDPOINT = ""
DEVICE_LABEL = ""
VARIABL... |
# coding: utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import xlrd
browser = webdriver.Chrome("C:/Users/User/Downloads/chromedriver_win323/chromedriver.exe")
browser.get('http://www.gmail.com')
emailEl... |
import pandas
import numpy
#defining a dictionary with Lists
MyDictData = {'First Semester Marks':[97, 83, numpy.nan, 95],
'Second Semester Marks': [85, 45, 56, numpy.nan],
'Third Semester Marks':[numpy.nan, 40, 80, 98]}
#creating a dataframe from the dictionary
MyDataFrame = pandas.DataFrame(MyDictDa... |
from django.contrib import admin
from .models import subject, Ebook, Paper, Lecture
# Register your models here.
admin.site.register(subject)
admin.site.register(Ebook)
admin.site.register(Paper)
admin.site.register(Lecture)
|
# https://atcoder.jp/contests/abc203/tasks/abc203_d
# import sys
# input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10 ** 7)
N, K = map(int, input().split())
A = [[int(i) for i in input().split()] for _ in range(N)]
lim = (K*K)//2 + 1
ng, ok = -1, 10**10 # case 0 is ok
while ng+1 < ok:
mid = (ng + ok)/... |
#!/usr/bin/env python3
import json
import requests
# Vars
output_file="snippets/resource-types.json"
# specs from us-east-1 https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html
url="https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json"
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 10:51:40 2020
@author: admin
"""
import numpy as np
import dill
def make_lick_snips(d, pre=5, post=15):
""" Makes snips of licks aligned to each distractor
Args
d: dictionary with lick data (key='licks') and distractor timestamps (key='distractors')... |
#-*-coding:utf-8-*-
import unittest
from page.addUser import *
from page.parklogin import *
from selenium import webdriver
class AddTest(unittest.TestCase,AddUser,Login):
def setUp(self):
self.driver=webdriver.Firefox()
self.driver.maximize_window()
self.driver.implicitly_wait(50)
s... |
class Store():
open = 9
close = 10
def hours(self):
return "We're open from {} to {}.".format(self.open, self.close)
|
from numpy import argmax
from matplotlib import pyplot
from keras.datasets import cifar10
from keras.utils import to_categorical
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers ... |
"""Error types for maths package."""
class InvalidArgumentError(Exception):
def __init__(self, message, errors):
super().__init__(message)
self.errors = errors
class Vector3ArgumentError(InvalidArgumentError):
"""Error raised when a Vector3 type argument is expected."""
def __init__(self... |
import numpy as np
import matplotlib.pyplot as plt
def GraphCumulativeRegret(num_steps, algorithm_regret_by_step, approaches):
display_every = int(num_steps / 100)
plt.figure()
for algo in range(len(approaches)):
mean_regret_by_step = np.mean(
np.cumsum(algorithm_regret_by_step[algo... |
from majormode.utils.namegen import NameGeneratorFactory
from gen_planet import entity
class Moon(entity.Entity):
language = NameGeneratorFactory.Language.Roman
left_padding = '<8'
class MoonSet(entity.BaseEntity):
left_padding = '<4'
def __init__(self, parent, num_children=None):
super().... |
import time
from collections import defaultdict
class CarePackage:
def get_value(self, index, mode):
if mode == "0":
return self.program[self.program[index]]
elif mode == '2':
return self.program[self.relative_base + self.program[index]]
return self.program[index]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Describes the EGLIBC heap mechanisms.
Work-in-progress.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pwndbg.arch
import pwndbg.events
did_warn_once = Fa... |
# Smp q tiver 1 exercício q diz q o último valor é um arquivo final ou valor EOF use esse método
while True:
try:
lampadas = input() # Letras das lampadas
inutil = int(input()) # valor descartado nesse método
data = input().split() # Posições da lampada
except EOFError:
... |
'''
ACI APIC AppCreator
@contact: aciappcenter-support@cisco.com
@version: 1.1
'''
from __future__ import print_function
import argparse
import json
import os
import re
import readline
import shutil
import signal
import sys
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
import logging
import aci_app_validat... |
"""Module for authenticating devices connecting to a faucet network"""
import logging
import sys
import os
import yaml
from forch.forchestrator import configure_logging
from forch.utils import proto_dict, dict_proto
from forch.proto.authentication_pb2 import AuthResult
LOGGER = logging.getLogger('authenticator')
AU... |
"""Blogly application."""
from flask import Flask, request, render_template, redirect, flash, session
from flask_debugtoolbar import DebugToolbarExtension
from models import db, connect_db, User
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:myPassword@localhost:5433/blogly' #@ ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 15 19:53:16 2019
@author: diaa
"""
|
from django.shortcuts import render, redirect, get_object_or_404
from dashboard.models import (
Audio,
Video,
Pdf,
Testimony,
PrayerRequest,
Feedback,
Notification,
)
from transaction_engine.models import Transaction
from accounts.models import WelfareContributor, Profile, Leader
from django... |
import pandas as pd
from csv_to_json.transforms.transform_functions.column_functions import *
def test_default():
df = pd.DataFrame.from_dict({'generic_string': ['foo', None]})
sub_map = {'defaultValue': 'bar'}
df['operation_col'] = df['generic_string']
df = default(
sub_map, df, 'generic_stri... |
"""
K-V Store++
PUT(K, V), DELETE(K), GET(K), GETRANDOM()-> return a value but with a probability of 1/size of the store
Design a data structure that supports following operations in O(1) time.
insert/put(x): Inserts an item x to the data structure if not already present.
remove/delete(x): Removes an item x from the... |
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
self.digit_to_num = {'2':['a', 'b', 'c'], '3':['d','e','f'], '4':['g', 'h', 'i'], '5':['j','k', 'l'], '6':['m','n','o'], '7':... |
import falcon
from {{ cookiecutter.package_name }}.webapi import containers
from {{ cookiecutter.package_name }}.webapi import resources
def add_routes(app: falcon.API, container: containers.Main) -> None:
app.add_route('/v1/alert/ping', resources.monitoring.Ping())
|
import numpy as np
import os
import sys
import wave
sys.path.append(os.path.join(os.getcwd(), "utils"))
from data_utils import get_zero_string
class LabelFile():
def __init__(self,num,stem="data_rec_",path="/Users/zachyamaoka/Documents/de3_audio/data_real_label/"):
self.PATH = path
self.file_stem ... |
import pathlib
import itertools
from collections import Counter, defaultdict
def main():
textos_spam = carga('textos_spam.txt')
textos_ham = carga('textos_ham.txt')
cantidad_spam, vocabulario_spam = obtener_vocab(textos_spam)
cantidad_ham, vocabulario_ham = obtener_vocab(textos_ham)
cantidad_total ... |
import pytest
@pytest.mark.skip
def test_order_with_respect_to():
"""
When we ask fore ordering, we get it as expected
"""
pass
@pytest.mark.skip
def test_get_admin_url():
"""
We can get admin urls for Model classes, instances, or app.model strings
"""
pass
@pytest.mark.skip
def te... |
a=1
b=0
while a<=100:
b=b+a
a+=1
print b
#or
a=1
b=0
for i in range(1,101):
b=b+a
a=a+1
print b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.