content stringlengths 5 1.05M |
|---|
# Auto generated by 'inv collect-airflow'
from airfly._vendor.airflow.sensors.base import BaseSensorOperator
class CassandraRecordSensor(BaseSensorOperator):
table: "str"
keys: "typing.Dict[str, str]"
cassandra_conn_id: "str"
|
import warnings
import matplotlib
warnings.filterwarnings('ignore', category=matplotlib.MatplotlibDeprecationWarning)
warnings.filterwarnings('ignore', category=UserWarning)
import os
import acopy
import samepy
import tsplib95
import networkx as nx
import matplotlib.pyplot as plt
import copy
from acopy.plugins impor... |
###
#
# Lenovo Redfish examples - Set BMC vlan id
#
# Copyright Notice:
#
# Copyright 2018 Lenovo Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/li... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
requirements = [
'Click>=6.7',
'bioblend',
'wrapt',
'pyyaml',
'justbackoff',
'xunit-wrapper',
'future... |
## Remove duplicate words
## 7 kyu
## https://www.codewars.com//kata/5b39e3772ae7545f650000fc
def remove_duplicate_words(s):
s = s.split()
unique_words = []
for word in s:
if word not in unique_words:
unique_words.append(word)
return ' '.join(unique_words) |
import pytest
from feeds.util import epoch_ms
def test_epoch_ms():
'''
Just make sure it's an int with 13 digits. Be more rigorous later. At least, before year 2287.
'''
t = epoch_ms()
assert len(str(t)) == 13 |
from django.db import models
# Create your models here.
class materias(models.Model):
id = models.AutoField(primary_key=True)
esporte = models.CharField(
max_length=255,
null=False,
blank=False
)
class Meta:
db_table = "materias" |
from onegov.fsi.collections.course_event import CourseEventCollection
from onegov.fsi.models import CourseSubscription, CourseAttendee, CourseEvent, \
Course
from onegov.user import User
def test_locked_course_event_reservations(client_with_db):
client = client_with_db
client.login_admin()
session = c... |
#!/usr/bin/env python3
"""
This receives text from stdin and does a sentiment analysis on each line
"""
import sys
import nltk
from nltk.corpus import stopwords
def read_lines_stdin():
lines = []
for line in sys.stdin:
lines.append(line)
[line.replace('\n', '') for line in lines]
return lines... |
import json
import pytest
from django.http import HttpResponse
from jcasts.shared.htmx import with_hx_trigger
class TestWithHxTrigger:
@pytest.fixture
def response(self):
return HttpResponse()
def test_no_data(self, response):
response = with_hx_trigger(response, "")
assert "HX... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Sensor
from sites.serializers import SensorSerializer
SENSOR_URL = reverse('sites:sensor-list')
class... |
import os
import sys
from setuptools import setup, find_packages
if os.getuid() != 0:
print('ERROR: Need to run as root')
sys.exit(1)
print('INFO: Checking and installing requirements')
os.system('! dpkg -S python-imagingtk && apt-get -y install python-imaging-tk')
print('INFO: Generating the requirements f... |
import machine
import pyb
import lvgl as lv
import os
pyb.country('US') # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU
pyb.main('main.py') # main script to run after this one
pyb.usb_mode('VCP+MSC') # act as a serial and a storage device
lv.init() # LVGL needs to be initialized before it's used |
import getpass
import os
import sys
import consulate
from fabric.api import run, local, cd, env, roles, execute
import requests
CODE_DIR = '/home/deploy/www/iodocs'
env.forward_agent = True
consul = consulate.Session()
def group_map():
ansible_group_list = consul.kv.find('ansible/groups')
ansible_group_m... |
#!/usr/bin/env python3
# Enumerate a certificate and trust chain
import contextlib
import datetime
import socket
import sys
import json
from OpenSSL import SSL
@contextlib.contextmanager
def open_tls_socket(hostname):
port = 443
if ":" in hostname:
(hostname, port) = hostname.split(":")
port ... |
# Generated by Django 3.0 on 2019-12-18 11:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hatvp', '0009_auto_20191217_2147'),
]
operations = [
migrations.RemoveField(
model_name='exercices',
name='date_fin',
... |
# encoding:utf-8
import requests
import time
from lxml import etree
import json
class TemporaryEmail:
"""临时邮箱
使用http://24mail.chacuo.net/10分钟邮箱,
监听并返回收到的邮件内容,用以接受验证码
"""
def __init__(self):
self.headers = {
'Pragma': 'no-cache',
'Origin': 'http://24... |
from sympy import symbols, sin, cos
from ga import Ga
from printer import Format, xpdf
Format()
(u, v) = uv = symbols('u,v',real=True)
(g2d, eu, ev) = Ga.build('e_u e_v', coords=uv)
print '#$A$ is a general 2D linear transformation'
A2d = g2d.lt('A')
print 'A =', A2d
print '\\f{\\det}{A} =', A2d.det()
print '\\f{\... |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(os.path.join(os.path.abspath(os.pardir), 'sample'))
import sample
|
"""Divide a raster by the m^2 area of the wgs84 pixel."""
import logging
import math
import sys
from osgeo import gdal
import numpy
import pygeoprocessing
pixel_size = 0.083
lat = 0
logging.basicConfig(
stream=sys.stdout,
level=logging.DEBUG,
format=(
'%(asctime)s (%(relativeCreated)d) %(processN... |
from setuptools import setup, find_packages
import os,sys
def readme():
with open('README.md') as f:
return f.read()
# Hackishly inject a constant into builtins to enable importing of the
# package before the library is built.
import sys
if sys.version_info[0] < 3:
import __builtin__ as builtins
else:... |
import tensorflow as tf
import numpy as np
class BaseLogger:
"""
Creates a summary writer for tensorboard logging.
Args:
name (string): Name of the model.
log_dir (string): Path that indicates which dataset is used.
"""
def __init__(self, name, log_dir):
self.name = name
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
sys.path.append('/home/osboxes/github/mininet-wifi')
from math import sqrt
from time import sleep, time
from future.utils import iteritems
from mininet import... |
def logged(function):
def wrapper(*args):
retval = f'you called {function.__name__}{args}\n'
retval += f'it returned {function(*args)}'
return retval
return wrapper
@logged
def func(*args):
return 3 + len(args)
@logged
def sum_func(a, b):
return a + b
print(func(4, 4, 4))
p... |
from __future__ import absolute_import
from page_object.page_object import PageObject
from page_object.page_factory import on, visit
from page_object.browser import Browser
|
from src import __version__, __version_info__
def test_version():
assert len(__version__) == 6
def test_version_info():
assert len(__version_info__) == 3
|
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog, QLabel, QTextEdit, QComboBox, QMainWindow
from PyQt5.QtGui import QPixmap
import cv2 as cv
import os
import tempfile
from pupil import Pupil
class Window(QWidget):
def __init__(self):
super()... |
# Modified version of https://github.com/snorkel-team/snorkel-tutorials/blob/master/spam/utils.py
import glob
import os
import subprocess
from collections import OrderedDict
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
def load_spam_dataset(load_train_labels: bool = Fa... |
import os
import logging
import smtplib
import base64
try:
from ConfigParser import ConfigParser
except:
from configparser import ConfigParser
try:
from email.MIMEMultipart import MIMEMultipart
except:
from email.mime.multipart import MIMEMultipart
try:
from email.MIMEText import MIMEText
except:
... |
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 1 Module Part 3 - Practice Quiz
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Scripting examples encountered during the Module Part 3 Practice Quiz:
# 01. Fill in the correct Python command to put “M... |
# -*- coding:utf-8 -*-
from spiders.baidu import BaiduSpider
from spiders.douban import DoubanSpider
class BaiduPipeline(object):
def process_item(self, item, spider):
if isinstance(spider, BaiduSpider):
print(u"BaiduSpider item:{}".format(item.data))
return item
class DoubanPipelin... |
from pylab import *
rc("font", size=16, family="serif", serif="Computer Sans")
rc("text", usetex=True)
num = 41
mu = linspace(100, 120, num)
prior1 = 0.5/(num-1)*ones(num)
prior1[-1] = 0.5
prior2 = exp(-0.5*((mu - 120.)/5)**2)
prior2[0:(num-1)] *= 0.7/sum(prior2[0:(num-1)])
prior2[-1] = 0.3
prior3 = 1./(1. + ((mu ... |
import requests
import json
# Change this vars as you need
bookstack_url = "https://wiki.bookstack.local" # Bookstack Base URL
header = {'Authorization': 'Token <<TokenID>>:<<TokenSecret>>'} # API Token
verify_ssl = True # Set to False if you have a selfsigned certificate
# create the structure of the bo... |
""" Actions that can be performed on the database. """
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, drop_database, create_database
from . import schema as db
def delete_db(uri, **create_engine_kwargs):
"""Deletes database if it exists.
Args:
uri: Database connecti... |
import pygame
from controller.ai.execution_template.bfs import BFS
from controller.ai.execution_template.dfs import DFS
from controller.ai.execution_template.iterative_deepening import IterativeDeepening
from controller.events.event_manager_strategy.home_event_manager import HomeEventManager
from controller.menu_state... |
from any_board_game.components.cards import Card as Card_
class Card(Card_):
def __gt__(self, other):
# Compare two cards
# If same suit, biggest suit wins, otherwise the spade wins
if self.state['suit'] == other.state['suit']:
return self.state['value'] > other.state['value']
... |
hrsraw = raw_input("Enter Hours:")
hrs = float(hrsraw)
rateraw = raw_input("Enter Rate:")
rate = float(rateraw)
if hrs < 40 :
gross = rate * hrs
elif hrs > 40 :
extragross = (hrs - 40) * (rate * 1.5)
gross = rate * 40
gross = extragross + gross
print gross
|
#!/usr/bin/python
import pygame
pygame.mixer.init()
pygame.mixer.music.load("whizzer.wav")
pygame.mixer.music.play()
tcnt = 0
while pygame.mixer.music.get_busy() == True:
tcnt +=1
print("We are in a loop: %s" % tcnt)
continue
|
# Copyright (c) 2017-2022 The Molecular Sciences Software Institute, Virginia Tech
#
# 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 l... |
d = 1
i = 2
def hh()
print'666'
a = 6
|
import functools
import json
import parse
import requests
from sretoolbox.utils import retry
class SentryClient:
ORGANIZATION = "sentry"
def __init__(self, host, token):
self.host = host
self.auth_token = token
@retry()
def _do_sentry_api_call_(self, method, path, slugs, payload=Non... |
from tensorflow.keras.models import Model, load_model
from tensorflow.keras import preprocessing
import numpy as np
from utils.Preprocess import Preprocess
p = Preprocess(word2index_dic='../../train_tools/dict/chatbot_dict.bin',
userdic='../../utils/user_dic.tsv')
new_sentence = '오늘 오전 13시 2분에 탕수육 주문 ... |
def power_t(x,n=2):
s=1
while n>0:
n-=1
s*=x
return s
|
# encoding: utf-8
# module PySide.QtGui
# from C:\Python27\lib\site-packages\PySide\QtGui.pyd
# by generator 1.147
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
class QTableWidgetItem(__Shiboken.Object):
# no doc
def background(self, *args, **kwargs): # real signatu... |
from ch01.creativity.c_1_13 import reverse
from ch01.creativity.c_1_14 import has_odd_product_pair
from ch01.creativity.c_1_15 import are_distinct
from ch01.creativity.c_1_20 import my_shuffle
from ch01.creativity.c_1_21 import reverse_read
|
import ivy
import sys
try:
import shortcodes
except ImportError:
shortcodes = None
# Use a single parser instance to parse all files.
parser = None
# The bare 'shortcodes' attribute for custom settings is deprecated.
if shortcodes:
@ivy.filters.register('node_text')
def render(text, node):
... |
# copied and adpated from https://github.com/tensorflow/models/blob/master/official/transformer/model/embedding_layer.py
import tensorflow as tf
class EmbeddingSharedWeights(tf.layers.Layer):
"""Calculates input embeddings and pre-softmax linear with shared weights."""
def __init__(self, scope, vocab_size, hidden... |
from .logger import Logger |
import torch
import numpy as np
import os
from torch.nn.functional import interpolate
from torch.utils.data import DataLoader
import torch.optim as optim
from sklearn import metrics
from dataset import ESMH
from models import *
from utils import *
import torch.backends.cudnn as cudnn
import argparse
np.set_printoption... |
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
cl... |
import re
import collections
from collections import Counter
def json_save(data, f_name):
import json
json = json.dumps(data)
with open(f_name +".json","w") as f:
f.write(json)
def json_read(f_name):
import json
with open(f_name) as f:
return json.load(f)
def get_filelist():
... |
{
"distance_charge": 4.8e-08,
"distance_charge_all": [
14.0641263108,
12.8600114364,
6.8261429168,
2.8385734177,
1.7976439088,
0.3930232044,
0.3185748414,
0.0207838885,
0.0293630023,
0.0033425889,
0.0038933844,
0.0002397749,
6.58407e-05,
4.8137e-... |
from gazenet.utils.registrar import *
@FaceDetectorRegistrar.register
class DlibFaceDetection(object):
def __init__(self):
import face_recognition
self.__face_recognition__ = face_recognition
def detect_frames(self, video_frames_list, match_face=None, **kwargs):
# loading the features... |
"""Server for multithreaded UI."""
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
class UIServer(object):
"""Server that handles comunications to different UI clients."""
def __init__(self, main, host='localHost', port=2243, bufferSize=1024, maxThreads=2):
"""Constuctor.... |
# Copyright (c) 2020, Kis Imre. All rights reserved.
# SPDX-License-Identifier: MIT
import unittest
from rpibaremetal.packet import Packet
class TestPacket(unittest.TestCase): #pylint: disable=too-many-public-methods
""" This class is responsible for testing Packet class. """
U8 = 0x12
U16 = 0x1234
U3... |
from django.urls import path
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', views.index, name = 'index'),
pa... |
from rest_framework.routers import DefaultRouter
from editors.content.views import (
CommunityViewSet,
EditViewSet,
ProjectVideoViewSet,
ProjectViewSet,
)
router = DefaultRouter()
router.register("project", viewset=ProjectViewSet, basename="project")
router.register("community", viewset=CommunityViewS... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : config.py
@Desc :
@Project : english_reading
@Contact : thefreer@outlook.com
@License : (C)Copyright 2018-2020, ZJH
@WebSite : zjh567.github.io
@Modify Time @Author @Version
------------ ------- ... |
from setuptools import setup
package_name = 'ldcp_node'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
insta... |
import numpy as np
import sympy
from sympy import Matrix
DOF = 2
def name_ind(i):
if i >=0 and i < DOF:
return 'c1'
elif i >= DOF and i < 2*DOF:
return 'c2'
elif i >= 2*DOF and i < 3*DOF:
return 'c3'
else:
raise
sympy.var('A, le, xi')
sympy.var('rho, E, nu, c, s')
N1 ... |
"""
UI component loaded on the 'Datasets' tab.
Functions:
get_component():
returns a component containing the input dropdown
and a graph plot for each dataset we have.
attach_callbacks():
attaches the callback for the dropdown.
Classes:
None
"""
import dash_core_components as dcc
i... |
from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
import os, sys
import numpy as np
import matplotlib.pyplot as plt
from scipy import loadtxt
data = loadtxt('energies.dat')
chi, phi, E = data[:,1], data[:,2], data[:,3]
chi_bins, phi_bins = ... |
from escpos.printer import Usb
from escpos import *
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import unicodedata
import datetime
import subprocess
def set_patlite_progress(progress):
if progress == 0:
subprocess.call(' '.join(['rsh', '192.168.10.1', '-l', 'pi', 'alert', ... |
# -*- coding: utf-8 -*-
# data
provinceList_json = '{"1": ["北京","beijing"],"2": ["天津","tianjin"],"3": ["河北","hebei"],"4": ["山西","shanxi"],"5": ["内蒙古","neimenggu"],"6": ["辽宁","liaoning"],"7": ["吉林","jilin"],"8": ["黑龙江","heilongjiang"],"9": ["上海","shanghai"],"10": ["江苏","jiangsu"],"11": ["浙江","zhejiang"],"12": ["安徽",... |
# -*- coding: utf-8 -*-
import collections
from lexical_analyzer_helpers import *
def get_top_words_in_path(path, name_type, speech_part, top_size=10):
if name_type not in ["variable", "function_definition"]:
raise ValueError(name_type + " not supported. Available types: [variable, function_definition]"... |
import decimal
D = decimal.Decimal
decimal.getcontext().prec = 16
dq = D(".00000001")
df = D(".1")
du = D(".001")
currencies = ['ltc', 'usd', 'lsd']
def priceConv(price, typ):
if typ == 1:
return D(str(price)) * D('100000000')
else:
return D(str(price)) / D('100000000')
#
#
# ... |
# for i in range(4):
# if i == 3:
# print('有3')
# break
# else:
# print('111')
# class Person:
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def say(self):
# print('我是{},今年{}岁'.format(self.name, self.age))
# class Student(Person):
# def __init... |
# -*- coding: utf-8 -*-
'''
File name: code\silver_dollar_game\sol_344.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #344 :: Silver dollar game
#
# For more information see:
# https://projecteuler.net/problem=344
# Problem Statement
'... |
# coding=utf-8
"""
remind.py - Sopel Reminder Module
Copyright 2011, Sean B. Palmer, inamidst.com
Licensed under the Eiffel Forum License 2.
https://sopel.chat
"""
from __future__ import unicode_literals, absolute_import, print_function, division
import os
import re
import time
import threading
import collections
imp... |
import pandas as pd
import numpy as np
import sys
from sklearn.metrics import roc_auc_score, precision_recall_fscore_support
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import RandomForestClassifier
from time import time
import pickle
... |
"""
Module containing all the actual console scripts of the project.
"""
import sys
import os
import json
from multiprocessing import Process
from pprint import pprint
import click
import matplotlib
import numpy as np
import shutil
from ufotest.config import PATH, get_config_path, Config
from ufotest.exceptions impor... |
from unittest import mock
from typing import Dict
from fastapi.testclient import TestClient
from app.core.config import settings
@mock.patch('app.utils.message_bus.quick_send')
def test_message_bus_default(
mock_send, client: TestClient, api_key_headers: Dict[str, str]) -> None:
_topic = "test"
param... |
# coding=utf-8
import csv
import logging
from unit.exporters.base import BaseExporter
from unit.particle import Particle
class CsvExporter(BaseExporter):
"""
Exports particles as CSV format into given fileobj.
"""
def export(self):
writer = csv.writer(
self._file_obj,
... |
from appJar import gui
import _thread
#import driveGUI
from driveGUI import calc_steering,reset_stop_flag,set_stop_flag,set_autonomer_modus,set_manueller_modus,lese_von_ST,set_Gaspedal_Stellung,show_Frame,get_model_steering_angle,set_Fummelfaktor_Stellwinkel
app = gui("control panel","550x550")
import time
Start=Fa... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from flaskblog.config import Config
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_mana... |
'''22. Sabe-se que o quilowatt de energia custa um quinto do salário mínimo. Faça um programa que
receba o valor do salário mínimo e a quantidade de quilowatts consumida por uma residência.
Calcule e mostre:
o valor de cada quilowatt;
o valor a ser pago por essa residência;
o valor a ser pago com desconto de 15%.'''... |
# -*- coding: utf-8 -*-
UNICA_BASE_URL = "http://www.unica.fi"
UNICA_RESTAURANTS = []
def append_to(list, this):
list.append(this)
UNICA_ASSARI = {
"name": "Assarin ullakko",
"id": "assarin_ullakko",
"url_fi": UNICA_BASE_URL + "/fi/ravintolat/assarin-ullakko/",
"url_en": UNICA_BASE_URL + "/en/re... |
### https://github.com/RomelTorres/alpha_vantage
from key import KEY
symbol = "GOOGL"
def intrday_timeseries(key, symbol):
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key=KEY, output_format="pandas", indexing_type="date")
# Get json object with the intraday data and another with the ... |
from pyspark import SparkContext, SparkConf
if __name__ == "__main__":
'''
"in/nasa_19950701.tsv" file contains 10000 log lines from one of NASA's apache server for July 1st, 1995.
"in/nasa_19950801.tsv" file contains 10000 log lines for August 1st, 1995
Create a Spark program to generate a new R... |
from validator_views import BaseValidatorView
from payload_validator import CreateTeamValidator
class CreateTeam(BaseValidatorView):
payload_validator = CreateTeamValidator
|
#!/usr/bin/python3.7
import argparse
import base64
import hashlib
import json
import re
import os
import yaml
from PIL import Image
import common
import oauth2
SECRET_KEY_LENGTH = 16
BASE_IMG = "map_base{}.png"
CLOUD_IMG = "cloud{}.png"
def upload_file(path, options, processor=None):
ext = os.path.splitext(path... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
RemoteRenderer
A QGIS plugin
Communicates with other programs via websockets and renders requested extents
-------------------
begin ... |
import pytest
import re
class TestMismatchedBrackets:
def test_it_knows_about_mismatched_square_from_parenthesis(self):
original = """
def wat(self:
pass
things = "]"
def things]self:
pass
"""
expected = re.escape(
"Trying to c... |
# Generated by Django 3.2.3 on 2021-07-13 08:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0012_alter_user_name'),
('authentication', '0003_auto_20210709_1926'),
]
operations = [
migrations.RenameModel(
old_nam... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from profiles.models import Profile
from protocols.models import Protocol, Step, Action, Component
# from steps.models import Step
from organization.models import Organization, Membership
from prot... |
from graphviz import Digraph
from model.process import Process
dot = Digraph(comment='Microservices Process Roadmap', format='png')
process = Process()
process.build(dot)
dot.render('images/microservices-process-roadmap.gv')
|
# 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, software
# d... |
# pattern.py -- Rename pattern
"""Pattern base module"""
import re
import os
from morph.errors import (
PatternModeError,
)
MODE_APPEND = "append"
MODE_REPLACE = "replace"
MODE_INSERT = "insert"
MODES = [MODE_APPEND, MODE_REPLACE, MODE_INSERT]
def generatePattern(pat, mode=MODE_APPEND):
if isinstance(pat,... |
# 数据库吧code拿出来
import pymysql
def get_code(problem_id, problem_name, challenge=False):
if challenge:
sql = "SELECT pc.code from problem_code pc join problem p WHERE p.id = pc.problem_id and p.title=%s"
else:
sql = "SELECT code_python FROM dim_subject_problem WHERE id=%s"
tup_code = execut... |
#!/usr/bin/env python
"""
############################################
Similiar Item Analysis Module Work Book View
############################################
"""
# -*- coding: utf-8 -*-
#
# rtk.analyses.similiar_item.gui.gtk.WorkBook.py is part of The RTK
# Project
#
# All rights reserved.
# Copyright 2... |
import numpy as np # type: ignore
def load_data(filename: str) -> np.array:
with open(filename) as f:
X = f.readlines()
# remove \n at end of line
X = [x.strip() for x in X]
return np.array(X, dtype=np.str)
def do_step_right(pos: int, step: int, width: int) -> int:
"""Takes current posi... |
# Copyright 2017 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 json
import sys
from google.appengine.ext import ndb
from dashboard import post_data_handler
from dashboard.models import histogram
class GetDiagn... |
from __future__ import unicode_literals
from frappe import _
def get_data(data):
non_standard_fieldnames=data['non_standard_fieldnames']
non_standard_fieldnames['Job Order CT']='sales_order_reference'
data['non_standard_fieldnames']=non_standard_fieldnames
transactions=data['transactions']
transactions[3].updat... |
#!/usr/bin/env python3
import sys
maxval = 0
maxfile = None
for line in sys.stdin:
data = line.strip().split("\t")
if len(data) != 2:
continue
k, v = data
if maxval < int(k):
maxval = int(k)
maxfile = v
if maxfile:
print('{0}\t{1}'.format(maxfile, maxval))
|
#!/usr/bin/env python3
# Apache License, Version 2.0
import argparse
import os
import shutil
import subprocess
import sys
import time
import tempfile
class COLORS_ANSI:
RED = '\033[00;31m'
GREEN = '\033[00;32m'
ENDC = '\033[0m'
class COLORS_DUMMY:
RED = ''
GREEN = ''
ENDC = ''
COLORS = COL... |
from model import Nu_NN
import torch
import numpy as np
from math import exp
class Algo_Param():
def __init__(self, gamma=0.9):
self.gamma = gamma
class Wasserstein():
def __init__(self, nu_param, algo_param, lamda_lr=0.0003, deterministic_env=True, averege_next_nu = True,
discrete... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .basic_modules import *
class AttentionModule(nn.Module):
"""
Corresponding CLEVR programs: 'filter_<att>'
Output: attention
"""
def __init__(self, **kwargs):
super().__init__()
self.dim_v = kwargs['dim_v']
... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.dist3}.
"""
from __future__ import division
import os
from twisted.trial.unittest import TestCase
from twisted.python.dist3 import modulesToInstall
class ModulesToInstallTests(TestCase):
"""
Tests for L{... |
from utils import JsonUtil
from pprint import pprint
import numpy as np
import re
from keras.utils.data_utils import get_file
from keras.layers.embeddings import Embedding
from keras.layers import Dense, Merge, Dropout, RepeatVector, merge
from keras.layers import recurrent, Input, Bidirectional, LSTM, Lambda
... |
import os
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
"""Get the environment variable or return exception."""
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the {} environment variable".format(var_name)
raise Improper... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.