text
string
size
int64
token_count
int64
from . import toolFuncs def DefineTrend(data, K): ''' Filter all the trend whose range less than K% ''' pairs = list(zip(data['Date'], data['Close'])) is_extreme = toolFuncs.extreme_point(data['Close'], K, recognition_method='height') output = [pairs[i] for i...
585
186
# Author: # Charles # Function: # Triplet loss function. import torch from torch.autograd import Function import sys sys.path.append('../') from utils.utils import * class TripletMarginLoss(Function): def __init__(self, margin): super(TripletMarginLoss, self).__init__() self.margin = margin # norm 2 self.p...
607
236
""" you have a string "ddaaiillyypprrooggrraammeerr". We want to remove all the consecutive duplicates and put them in a separate string, which yields two separate instances of the string "dailyprogramer". use this list for testing: input: "balloons" expected output: "balons" "lo" input: "ddaaiillyypprrooggrraammeerr"...
768
287
#!/usr/bin/env python3 import typing import PIL.Image from enum import Enum import re import preppipe.commontypes from preppipe.vnmodel import * class EngineSupport: """All engine support classes inherit this class, so that we can use reflection to query all supported engines""" pass # we define a...
6,485
2,290
from openprocurement.tender.limited.models import Tender def includeme(config): config.add_tender_procurementMethodType(Tender) config.scan("openprocurement.tender.limited.views")
190
62
from pprint import pprint import requests import base64 import json import argparse import sys p = argparse.ArgumentParser(description="New") p.add_argument('-f','--folder-name', required=True, help='Folder name of the images/metadata files') p.add_argument('-s','--start', required=False, help='Start ID to upload') p...
3,422
1,133
import logging from queue import Queue from redis_queue.queue import RedisQueue from runner.base import BaseRunner logger = logging.getLogger(__name__) class MemoryQueueRunner(BaseRunner): """Memory queue runner""" def create_queue(self, queue_name): return Queue(maxsize=2000) class ReisQueueRunn...
1,613
513
# -*- coding: utf-8 -*- from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecuritySignValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import SecurityAverageValueHolder from ultron.sentry.Analysis.TechnicalAnalysis.StatelessTechnicalAnalysers import S...
6,790
1,977
# from app.common.utils import * from sqlalchemy import desc from settings import Config from app.models import * from app.extensions import db from app.models.base import _BaseModel from app.common.message import DBError # 获取分页数据 def Pages(_request, _TABLE, _filter=None): page = get_page_value(_request) per...
17,015
5,052
from unittest import TestCase import mock from cloudshell.cp.azure.domain.services.vm_credentials_service import VMCredentialsService from cloudshell.cp.azure.models.vm_credentials import VMCredentials class TestVMCredentialsService(TestCase): def setUp(self): self.test_username = "test_username" ...
7,403
1,973
from sys import platform import pygame from handler.handler import Handler class Quit(Handler): def __init__(self, keyboard_manager, shutdown): self.keyboard_manager = keyboard_manager self.shutdown = shutdown def tick(self): if self.keyboard_manager.is_start(pygame.K_F4): ...
751
241
import requests import requests.exceptions import datetime import ujson as json import logging class DecisiveApiClient(object): HOST = 'https://ads.decisive.is'.strip('/') def __init__(self, api_key, host=None): self.session = requests.Session() self.session.auth = (api_key,'') s...
2,635
786
from flask import ( abort, current_app, flash, redirect, render_template, request, session, url_for, ) from flask_login import current_user, login_required from notifications_python_client.errors import HTTPError from notifications_utils.field import Field from notifications_utils.format...
38,284
11,866
#!/usr/bin/env python2 """ spelling.py Filter the output of 'lynx -dump' into a list of words to spell check. """ from __future__ import print_function from collections import Counter import optparse import re import sys def log(msg, *args): if args: msg = msg % args print(msg, file=sys.stderr) def SplitW...
3,094
1,077
#!/usr/bin/env python3 # Based on: https://github.com/facebookresearch/DeepSDF using MIT LICENSE (https://github.com/facebookresearch/DeepSDF/blob/master/LICENSE) # Copyright 2021-present Philipp Friedrich, Josef Kamysek. All Rights Reserved. import functools import json import logging import math import os import sig...
20,659
6,625
from distutils.core import setup setup( name = 'python-ethereumrpc', packages = ['python-ethereumrpc'], version = '0.1', description = 'A python interface for ethereum JSON-RPC service.', author = 'Nicolas Sandller', author_email = 'nicosandller@gmail.com', url = 'https://github.com/nicosandller/python-et...
498
187
# /robotafm/motor/interface.py # Main web interface, contains basic # information display # imports: import xml.dom.minidom from flask import Flask, render_template # constants: LANG = "./lang/rus.xml" # XML: load text strings from language file dom = xml.dom.minidom.parse(LANG) main_title = dom.getElem...
988
333
from eval_codalab_basic import eval_codalab_basic if __name__ == '__main__': # 1. run first round to prepare full memory eval_codalab_basic(output_suffix='online', skip_first_round_if_memory_is_ready=True) # 2. do offline evaluation when memory is ready eval_codalab_basic(output_suffix='offline')
317
112
UP = "U" DOWN = "D" ALLOWED_PATH_I = [UP, DOWN] def update_high_for_step(high: int, step: str) -> int: """Update the current high given a step""" if step == UP: high += 1 elif step == DOWN: high -= 1 return high def update_valley_count(valleys_count: int, high: int, pre...
922
331
from gpanel import * coordinates(-3, -3, 11, 11) line(0, 0, 8, 8) line(8, 0, 0, 8)
84
53
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root root.left, root.right = root.right, root.left self.invertTree(root.left) self.invertTree(root.right) return root class Solution: def invertTree(self, root: TreeNode) -> TreeNode: ...
682
194
preço = float(input('Preço: ')) print('''Preencha a forma de pagamento com: 1 - p/ À VISTA 2 - p/ CARTÃO 1x 3 - p/ CARTÃO 2x 4 - p/ CARTÃO 3x ou mais ''') pagto = str(input('Pagamento: ')).strip() if pagto == '1': preço = preço*0.9 elif pagto == '2': preço = preço*0.95 elif pagto == '4': preço = preço*1.2 p...
333
159
import logging import sys from .application import Application from .document import Document, Track, Event if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) app = Application(sys.argv) if '--debug' in sys.argv: # # Load a document. # # We absolutely MUST have ...
1,264
407
"""Module with core functionality for a single pipeline stage """ import pathlib import os import sys from textwrap import dedent import shutil import cProfile from abc import abstractmethod from . import errors from .monitor import MemoryMonitor from .config import StageConfig, cast_to_streamable SERIAL = "serial" ...
45,609
12,120
#!/usr/bin/env python import rospy import numpy as np import math from geometry_msgs.msg import PoseStamped, Transform from TrinaPointAndClick.msg import Marker, MarkerArray class Marker_Node(): """ This node listens to marker tracker data and keeps track of the pose of all markers seen during run-time. This n...
8,400
2,334
from mininet.topo import Topo from mininet.link import TCLink class Topology(Topo): def build(self): # Hosts and switches host1 = self.addHost('H1') host2 = self.addHost('H2') host3 = self.addHost('H3') host4 = self.addHost('H4') host5 = self.addHost('H5') ...
1,102
488
# -*- coding: utf-8 -*- """ Created on Thu Apr 12 23:00:28 2018 @author: wangshuai """ import urllib import urllib.request as urllib2 import http.cookiejar as cookielib import io import re import gzip from selenium import webdriver import datetime def get_Time(): begin = datetime.date(2016,1,1) end = datetime.d...
5,155
1,677
import tensorflow as tf class BaseSampler(object): def __init__(self, session=None): self._session = session or tf.get_default_session() def sample(self, variables, cost, gradient=None): raise NotImplementedError @property def session(self): return self._session @session...
392
110
from os import path, listdir import ocgis from flyingpigeon import subset from flyingpigeon import utils from flyingpigeon.ocgis_module import call def get_prediction(gam_model, ncs_indices): # mask=None """ predict the probabillity based on the gam_model and the given climate index datasets :param gam...
3,327
1,213
# Generated by Django 2.1.2 on 2018-10-18 15:36 from django.db import migrations, models from django.db.models import F def migr_code_to_identifier_0019_entrytype_identifier(apps, schema): EntryType = apps.get_model("jacc", "EntryType") EntryType.objects.all().update(identifier=F("code")) class Migration(m...
746
257
import pytest def test_locked_out_user(browser): browser.goto('http://www.saucedemo.com') browser.text_field(data_test='username').value = 'locked_out_user' browser.text_field(data_test='password').value ='secret_sauce' browser.button(type='submit').click() assert browser.button(class_name='erro...
342
113
from splicemachine.mlflow_support import * from splicemachine.mlflow_support.mlflow_support import _GORILLA_SETTINGS import gorilla import mlflow.onnx def _log_model(model, name='onnx_model', **flavor_options): mlflow.log_model(model, name=name, model_lib='onnx', **flavor_options) gorilla.apply(gorilla.Patch(mlfl...
403
157
## Shorty ## Copyright 2009 Joshua Roesslein ## See LICENSE ## @url short.to class Shortto(Service): def shrink(self, bigurl): resp = request('http://short.to/s.txt', {'url': bigurl}) return resp.read() def expand(self, tinyurl): resp = request('http://long.to/do.txt', {'url': tinyurl...
351
123
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical import numpy as np import gym from gym.spaces import Discrete, Box class MLP(nn.Module): def __init__(self, obs_dim, sizes, activation=nn.Tanh, output_activation=None): super(MLP, self).__init__()...
4,743
1,415
import asynmsg import struct import google.protobuf.message def protobuf_handler_config(msg_id, msg_cls=None): def wrapper(func): @asynmsg.message_handler_config(msg_id) def wrapper2(self, msg_id, msg_data): if msg_cls is None: proto_data = msg_data else: ...
2,334
733
import collections from thegame.abilities import Ability Vector = collections.namedtuple('Vector', ('x', 'y')) Vector.__doc__ = ''' A 2D vector. Used to represent a point and velocity in thegame ''' class _EntityAttribute: def __init__(self, doc=None): self.__doc__ = doc def __set_name__(self, kla...
6,402
1,883
import os import json # import wget from flask import ( Flask, jsonify, send_from_directory, request, redirect, url_for ) from flask_sqlalchemy import SQLAlchemy import werkzeug werkzeug.cached_property = werkzeug.utils.cached_property from werkzeug.utils import secure_filename from werkzeug.mi...
3,456
1,046
# Welcome to the wonderful world of police databases: MALE = "male" FEMALE = "female"
87
30
from django.shortcuts import render from django.http import HttpResponse from backups_operator.servers.models import Server # Create your views here. def home(request): servers = Server.objects.all() data = { 'servers': servers } return render(request, 'sources/home.html', data) def test(req...
472
136
import argparse import sys import subprocess import psutil def insepect_process(pid): """Determine 1. is the process running in the container 2. if it's true, ourput the container id and the user :return: """ assert psutil.pid_exists(pid), "The process doesn't exist" try: result = ...
1,460
469
ano = int(input('Digite o ano do seu carro: ')) idadecarro = 2022 - ano print('Carro novo' if idadecarro <=3 else 'Carro Velho')
128
52
""" implements a wrapper for loading live data from the serial connection and passing it to plotting """ import serial import time import struct import plotly.express as px try: from . import log_parser except ImportError: import log_parser # TODO: clean up CLI code class LiveLogFile(): def __init__(self, s...
3,531
1,093
import sys import dbops from pathlib import Path if len(sys.argv) < 2: print("Bucephalus Remove File Script") print("Usage: " + sys.argv[0] + " <identifier>") sys.exit() sys.argv.pop(0) ident = sys.argv.pop(0) if dbops.remove_record_by_id(ident) == None: print("*** Error: failed to remove record.")
313
119
import os def test_get_current_os_name(client_local): response = client_local.get_current_os_name_local() print(response) print(os.name) if os.name == 'nt': assert 'Windows' in response, 'Current OS name is not Windows' elif os.name == 'Linux': assert 'Linux' in response, 'Current...
440
139
""" ↓ Инициализация данных ↓ """ from PyQt5 import QtWidgets, QtCore from GUI.GUI_windows_source import TranslationLanguage from json import load, dump from functools import partial import copy from scripts.stylesheets import choosen_lang_style, not_chosen_lang_style class TranslationLa...
5,133
1,516
"""Map widget for Dear PyGui""" __version__ = "0.0.1"
55
25
from flask import ( Blueprint, request)#, flash, g, redirect, render_template, get_template_attribute, url_for, jsonify # ) # from werkzeug.exceptions import abort import requests # from demosaurus.db import get_db # import pandas as pd # from nltk.metrics import distance # import re # import numpy as np bp = B...
1,347
413
def ZoneAnalysis_FULL(SettingsDic): import MODZoneAnalysis import os diretorio=os.getcwd() # Análises das regioes com bacterias MODZoneAnalysis.DetVolume(diretorio, importstackRootName=SettingsDic['FolderName'], FirstStack=...
1,114
297
from django.http import HttpResponse from django.http.response import JsonResponse from django.shortcuts import render from rest_framework.serializers import Serializer from admin import settings import requests from rest_framework import viewsets from time import gmtime, strftime from Kusa.models import SteamUser from...
3,448
1,082
import os from redis import StrictRedis class Config(object): SECRET_KEY = os.environ.get('FLASK_SECRET') SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') SQLALCHEMY_TRACK_MODIFICATIONS = False SESSION_TYPE = 'redis' SESSION_REDIS = StrictRedis(host=os.environ.get('REDIS_HOST'), db=...
478
206
""" Generative language models. Classes ------- SMILESEncoderDecoder A generative recurrent neural network to encode-decode SMILES strings. SMILESEncoderDecoderFineTuner The fine-tuner of SMILESEncoderDecoder model. """ __all__ = ( 'SMILESEncoderDecoder', 'SMILESEncoderDecoderFineTuner', ) import jso...
15,928
4,783
from grappa import GrappaExperiment, MPIRunGrappaExperiment tpch_bigdatann = MPIRunGrappaExperiment({ 'trial': range(1, 3 + 1), #'qn': [x for x in range(8, 20 + 1) if x!=7 and x!=9 and x!=8 and x!=10 and x!=11], # exclude 7 that runs forever ...
2,351
702
import numpy as np from scipy.special import softmax np.set_printoptions(precision=6) def k_softmax(x): exp = np.exp(x) return exp / np.sum(exp, axis=1) if __name__ == "__main__": x = np.array([[1, 4.2, 0.6, 1.23, 4.3, 1.2, 2.5]]) print("Input Array: ", x) print("Softmax Array: ", k_softmax(x))...
362
163
import tensorflow as tf from tensorflow.keras.layers import Conv2D, ReLU, SeparableConv2D, Input, SpatialDropout2D, MaxPool2D, Concatenate, Conv2DTranspose, BatchNormalization from tensorflow.keras.regularizers import l1, l2 from models.net import Net from layers.kerasGroupNorm import GroupNormalization class Zeros(Ne...
707
232
"""PostDB class definition. PostDB encapsualte interactions (lookup, scan, insert) with the posts table. Typical usage example: from post import Post from post_db import PostDB post_db = PostDB(mode = "dev") post = Post( post_url = "https://www.example.com/", title = "Test", main_image...
7,008
1,986
# coding: utf-8 from slackbot.bot import respond_to from slacker import Slacker import slackbot_settings # @respond_to("疲れた") # @respond_to("つかれた") # def cheer(message): # message.reply("ファイト!") import MeCab import random import ChatBotScript import SentenceGenerator import datetime import webbrowser import time...
9,491
3,564
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T # # Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # ...
13,922
4,623
from PIL import Image import streamlit as st from streamlit_drawable_canvas import st_canvas from Streamlit_Pix2Pix_Generator import Generator import numpy as np import urllib.request from keras.preprocessing.image import load_img from keras.models import load_model import requests # Page intro st.title('Pix2Pix – See...
7,099
2,393
""" The MIT License (MIT) Copyright (c) 2017 SML 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, modify, merge, publish,...
4,584
1,442
""" .. module:: test_iterfunction :synopsis: Unit tests for iterfunction module """ import time import nutsflow.iterfunction as itf from six.moves import range def test_length(): assert itf.length(range(10)) == 10 assert itf.length([]) == 0 def test_interleave(): it1 = [1, 2] it2 = 'abc' it...
2,845
1,201
""" Alias convention tests. """ from io import BytesIO from json import loads from uuid import uuid4 from hamcrest import ( all_of, anything, assert_that, contains, equal_to, has_entries, has_entry, has_item, has_key, is_, is_not, ) from marshmallow import Schema, fields fr...
6,591
1,917
''' molecool.io package configure access to subpackage functions ''' from .pdb import open_pdb from .xyz import open_xyz, write_xyz
135
45
#!/usr/bin/env python import sys import json from flatten_dict import flatten as _flatten try: data = json.load(sys.stdin)['object'] except Exception as ex: print("Missing or invalid test data:", ex) sys.exit(1) try: results = json.load(open(sys.argv[1], "r"))['results'] except Exception as ex: p...
866
305
__all__ = [ 'make_aio_client', 'make_sync_client', 'TAsyncHTTPXClient', 'THTTPXClient', ] from .aio import TAsyncHTTPXClient, make_client as make_aio_client from .sync import THTTPXClient, make_client as make_sync_client from ._version import get_versions __version__ = get_versions()['version'] del ge...
331
115
import sys import random from kalc.model.system.base import ModularKind from typing import Set from kalc.model.system.primitives import Label, StatusNode from kalc.model.system.base import HasLabel from kalc.misc.util import cpuConvertToAbstractProblem, memConvertToAbstractProblem from kalc.misc.const import STATUS_NOD...
3,553
1,125
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, in_data, out_attributes, user_options, num_cores, outfile): import os from genomicode import filelib from genomicode import ...
6,154
1,866
# noinspection PyUnresolvedReferences import propnet.symbols from propnet.models import serialized, python, composite from propnet.core.registry import Registry # This is just to enable importing the model directly from this module for example code generation def _update_globals(): for name, model in Registry("mo...
792
245
import csv import re regex = re.compile('[^a-zA-Z]') def f7(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def clean_dataset(screen_name, n_tweets=300): # open CSV file all_words = [] with open('%s_tweets.csv' % screen_name,...
1,369
504
#!/usr/bin/python import sys import os from nltk.tokenize import TreebankWordTokenizer as Tokenizer from nltk.tag.perceptron import PerceptronTagger import operator from itertools import chain import nltk from sklearn.metrics import classification_report, confusion_matrix from sklearn.preprocessing import LabelBinariz...
4,690
1,385
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 import math import torch.nn as nn import torch from .GDN import GDN from .attention import Attention # class Analysis_transform(nn.Module): # def __init__(self, num_filters=128): # super(Analysis_transform, self).__init__() # self.co...
6,736
2,789
# -*- encoding: utf-8 -*- from app import db class ModelExample(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(250)) content = db.Column(db.Text) date = db.Column(db.DateTime) class User(db.Model): id = db.Column(db.Integer, primary_key = True) user = db.Column(db.St...
826
298
class DeviceServiceB(object): def __init__(self): self.serviceId = None self.reportedProps = None self.desiredProps = None self.eventTime = None self.serviceType = None def getServiceId(self): return self.serviceId def setServiceId(self, serviceId): ...
938
263
# -*- coding: utf-8 -*- from src.utils.get_data import load_data from src.utils.get_data import get_datasets from src.utils.get_data import concatenate_datasets from src.utils.dataset_balancer import balance_data import os import pandas as pd import unittest class TestDataBalancer(unittest.TestCase): def setUp(...
1,516
476
# # Yinhao Zhu, May 01, 2017 # """ Sparse GP regression, including variational GP and others. """ from __future__ import absolute_import import torch import numpy as np from torch.utils.data import TensorDataset, DataLoader from torch.distributions.transforms import LowerCholeskyTransform from ..model import Param f...
12,695
4,132
def test(): import spacy.matcher assert isinstance( matcher, spacy.matcher.Matcher ), "Você está inicializando o Comparador corretamente?" assert ( "Matcher(nlp.vocab)" in __solution__ ), "Você está inicializando o Comparador corretamente com o vocabulário compartilhado?" assert...
1,405
465
list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"] print list1, list2, list3 # 访问列表中的值 # 使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示: print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] # 更新列表 # 你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示: list = [] ...
1,638
1,076
import tkinter as tk import tkinter.font as tf from tkinter import ttk from tkinter import messagebox from tkinter.filedialog import askopenfilename, askdirectory import time import threading from functools import wraps from xyw_macro.utils import SingletonType from xyw_macro.contants import SLEEP_TIME class Notifi...
10,015
3,364
""" Utilities for testing """ import os import json TESTDATADIR = os.path.join(os.path.dirname(__file__), 'testdata') def get_pass(pass_name : str) -> str: """ Returns pass from test_credentials.json """ creds_path = os.path.join(os.path.dirname(__file__), 'test_credentials.json') with open(creds_path,...
1,206
390
from ballistics.collision.dispatch.config import DefaultCollisionConfiguration from ballistics.collision.dispatch.dispatcher import CollisionDispatcher
152
33
import os from webdriver_manager.driver import ChromeDriver from webdriver_manager.manager import DriverManager from webdriver_manager import utils class ChromeDriverManager(DriverManager): def __init__(self, version=None, os_type=utils.os_type()): # type: (str, str) -> None super(ChromeDriverMana...
750
226
from data_importers.management.commands import BaseDemocracyCountsCsvImporter class Command(BaseDemocracyCountsCsvImporter): council_id = "E09000005" addresses_name = "europarl.2019-05-23/Version 1/DC PD.csv" stations_name = "europarl.2019-05-23/Version 1/DC PS.csv" elections = ["europarl.2019-05-23"]...
321
143
MOVIE1 = { "title": "Guardians of the Galaxy", "year": 2014, "ids": { "trakt": 28, "slug": "guardians-of-the-galaxy-2014", "imdb": "tt2015381", "tmdb": 118340, }, } MOVIE2 = { "title": "Guardians of the Galaxy", "year": 2014, "ids": { "trakt": 28, ...
3,217
1,492
# 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. # -----------------------------------------------------...
2,689
867
import json import time import uuid from installed_clients.DataFileUtilClient import DataFileUtil from installed_clients.KBaseReportClient import KBaseReport from installed_clients.WorkspaceClient import Workspace as Workspace def log(message, prefix_newline=False): """Logging function, provides a hook to suppre...
7,580
2,053
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import tensorflow as tf def to_tf_tensor(ndarray, dtype = tf.float64): '''Converts the given multidimensional array to a tensorflow tensor. Args: ndarray (ndarray-like): parameter for conversion. dtype (type, optional)...
838
256
# this file describe sets data structures on python thisSet={"Car","Bike","Truk"} # Printing sets on terminal print(thisSet)
127
40
from multiprocessing import Pool import logging def multi_process(func, data, workers): logging.warning('Consuming list with %s workers' % workers) p = Pool(workers) try: # the timeout(.get(9999999) is a workaround for the KeyboardInterrupt. without that it just does not work. # Seem to be...
588
178
import os import yaml from HTMLScriptExtractor import HTMLScriptExtractor MIME_TYPE_MAP = { '.htm': 'text/html', '.html': 'text/html', '.js': 'text/javascript', '.vbs': 'text/vbscript', '.txt': 'text/plain', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg' } # input: # a function "mime_ty...
11,290
3,247
from rapidtest import Test, Case, TreeNode from solutions.lowest_common_ancestor_of_a_binary_search_tree import Solution with Test(Solution, post_proc=TreeNode.get_val) as test: root = TreeNode.from_iterable([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5]) Case(root, TreeNode(2), TreeNode(4), result=TreeNode(2)) C...
1,265
471
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: npu_utilization.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.prot...
12,087
4,630
from annotatelib.models import ( models, class_from_filename, table_name_from_filename, _get_column_description_from_object, _get_indices_description_from_oject ) import sqlite3 from orator import DatabaseManager import os import sys sys.path.insert(0, os.path.abspath( os.path.join(os.path.dirname(__fil...
4,409
1,349
__version__ = '0.0.1' def flatten_list(input_list): """ Flattens list with many nested lists. >>> flatten_list([1, [2, [3], [4]]]) [1, 2, 3, 4] """ result = [] for item in input_list: if isinstance(item, list): result.extend(flatten_list(item)) # yield from...
430
149
import os import keyring from prompt_toolkit import prompt KEY = ('slackcast', 'token') SLACKCAST_INSTALL_URL = os.environ.get( 'SLACKCAST_INSTALL_URL', 'https://slackcast.devtestit.com/install' ) def get_token(): # For testing token = os.environ.get('SLACKCAST_TOKEN', None) if token is None: ...
607
211
import progressbar from baidupcsapi import PCS class ProgressBar(): def __init__(self): self.first_call = True def __call__(self, *args, **kwargs): if self.first_call: self.widgets = [progressbar.Percentage(), ' ', progressbar.Bar(marker=progressbar.RotatingMarker('>')), ...
790
241
""" messages """ from .color import ENDC, FAIL, OKBLUE, YELLOW EXE_SCRIPT_ERR_MSG = '{0}[!]{1} An error occurred while executing script in Pipfile'.format( FAIL, ENDC ) KEYWORD_NOT_FOUND_MSG = "{0}[!]{1} {2}Pipfile{1} in {3}[scripts]{1} keyword not found!".format( FAIL, ENDC, OKBLUE, YELLOW ) FILE_NOT_FOUND_MS...
541
243
import sys import logging import pymysql import json import os #rds settings - Lambda role must have RDS access rds_host = os.environ['RDS_HOST'] # Set in Lambda Dashboard name = os.environ['DB_USERNAME'] password = os.environ['DB_PW'] db_name = os.environ['DB_NAME'] db_table = os.environ['DB_TABLE'] logger = loggin...
2,101
640
# Generated by Django 2.1.5 on 2019-03-29 05:54 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ACCNTS', '0011_asset_employeetax_income_liability'), ] operations = [ migrations.AddField( model_name='asset', ...
764
231
from django import forms from .models import Doacao class DoacaoForm(forms.ModelForm): class Meta: model = Doacao fields = ['nib', 'quantia',]
171
59
import requests from elasticsearch import Elasticsearch, client from elasticsearch.exceptions import RequestError es = Elasticsearch() # retrieve all QIDs from the populated reframe ES index body = { "_source": { "includes": ["qid"], }, "query": { "query_string": { "query": "...
1,707
588
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.urls import reverse_lazy from django.views.generic import (ListView, CreateView, TemplateView, ) from django.views.generic.detail import DetailView from django.views.generic.edit import (UpdateView, DeleteView, ) from blog.models impo...
3,049
903