text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- # BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules # Copyright (C) 2020, Yoel Cortes-Pena <yoelcortes@gmail.com> # # This module is under the UIUC open-source license. See # github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt # for license details. """...
28,509
8,253
import cv2 import numpy as np image = cv2.imread('original.png') gray = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) blur = cv2.GaussianBlur(gray, (19, 19), 0) # Application d'un seuil pour obtenir une image binaire thresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN...
1,005
428
################################################################################ # Copyright 2019 Noblis, Inc # # # # Licensed under the Apache License, Version 2.0 (the "License"); ...
8,413
2,587
from PIL import Image, ImageFilter import numpy as np import glob from numpy import array import matplotlib.pyplot as plt from skimage import morphology import scipy.ndimage def sample_stack(stack, rows=2, cols=2, start_with=0, show_every=1, display1 = True): if (display1): new_list = [] new_list.a...
2,316
873
import json import numpy as np import tensorflow as tf import time from predict import Predictor if __name__ == "__main__": checkpoint = "logs/semantic_backup_full_submit_dec_10/best_model_epoch_275.ckpt" hyper_params = json.loads(open("semantic.json").read()) predictor = Predictor( checkpoint_pa...
2,191
719
from pymyorm.database import Database from config import db from models.user import User if __name__ == '__main__': Database.connect(**db) # # case 1 # all = User.find().select('count(*) as count', 'money').group('money').order('count asc').all() # for one in all: # print(one) all = User....
447
149
import os import json import logging from framework._utils import FunctionHook class CodeJamExtractCyclomaticComplexity(FunctionHook): ''' This method will extract cyclomatic complexity from submitted code. Need to run `extract language` first, since not every language has implement with the extr...
2,783
768
print(int(2.0)) print(float(2)) print(abs(-2.0)) print(abs(-2))
64
33
# import materia as mtr # import numpy as np # def test_point_group_C1(): # ctable = mtr.symmetry.C1().cayley_table() # assert (ctable == np.array([[0]])).all() # def test_point_group_Ci(): # ctable = mtr.symmetry.Ci().cayley_table() # assert (ctable == np.array([[0, 1], [1, 0]])).all()
310
134
from unittest.mock import patch, MagicMock from unittest import TestCase from ..crawler.pipeliner import pipeline from ..settings import URL_PROCESSO class Pipeline(TestCase): @patch('robotj.extrator.crawler.pipeliner.parse_itens', return_value={'d': 4}) @patch('robotj.extrator.crawler.pipeliner.pa...
1,948
741
from pathlib import Path import pytest from copy import deepcopy import os from mc.base import BaseConfig from mc import step @pytest.fixture() def config(): in_file = Path("tests/test_data/test_config.xml") return BaseConfig(in_file) def test_set_write_path(config): step.set_write_path(config, {'outpu...
3,943
1,265
#!/usr/bin/python import system import db import client import server import logging import json import base64 import os from aws_xray_sdk.core import patch_all if "AWS_REGION" in os.environ: patch_all() class LambdaCommon: def __init__(self, ddb_client=None): self.log = logging.getLogger("Lambda")...
15,552
4,856
try: import cStringIO as StringIO except ImportError: import StringIO import datetime import os import sys import unittest _src = os.path.join(os.path.dirname(__file__),"..", "src") if not _src in sys.path: sys.path.append(_src) import utils class DateTimeTests(unittest.TestCase): def test_isoforma...
2,575
1,016
import os import argparse from midv500.utils import download, unzip midv500_links = [ "ftp://smartengines.com/midv-500/dataset/01_alb_id.zip", "ftp://smartengines.com/midv-500/dataset/02_aut_drvlic_new.zip", "ftp://smartengines.com/midv-500/dataset/03_aut_id_old.zip", "ftp://smartengines.com/midv-500/d...
9,364
4,391
import traceback import pycountry import taxjar import frappe from erpnext import get_default_company from frappe import _ from frappe.contacts.doctype.address.address import get_company_address TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head") SHIP_ACCOUNT_HEAD = frappe.db.get_sin...
6,329
2,363
import unittest import numpy as np import numpy.testing as nptest import centerpoints.lib as lib class TestLibrary(unittest.TestCase): def setUp(self): # { dimension -> points } self.d_plus_2_points = {} for d in [3, 5, 10, 100]: # we need d+2 points, first take all bases ...
3,543
1,223
# test comment import os filename = input("File to format: ") os.system("gunzip "+filename) n = int(input("What number genome is this? ")) os.system("mv "+filename[:-3]+" genome"+str(n)+".fna") original = "genome"+str(n)+".fna" copy = "genome"+str(n)+"_copy.fna" filtered = "genome"+str(n)+"_filtered.fna" rem = ['>'] wi...
711
278
from villas.controller.components.manager import Manager from villas.controller.component import Component class GenericManager(Manager): def create(self, payload): component = Component.from_dict(payload.get('parameters')) try: self.add_component(component) except KeyError: ...
758
192
from protorpc.messages import Message, IntegerField, StringField import protopigeon class MessageOne(Message): one = IntegerField(1) two = IntegerField(2) class MessageTwo(Message): three = StringField(1) four = StringField(2) def test(): ComposedMessage = protopigeon.compose(MessageOne, Messa...
833
253
""" # !/usr/bin/env python # -*- coding: utf-8 -*- @Time : 2022/2/23 19:35 @Author : shengdl999links@gmail.com @ProjectName : udacity-program_self_driving_car_engineer_v1.0_source.0 @File : visualization.py """ import glob import os.path import matplotlib.pyplot as plt from matplotlib.patches import ...
1,503
588
from setuptools import setup long_description = 'TODO' # with open("README.md", "r") as rfd: # long_description = rfd.read() REQUIREMENTS = [r.strip() for r in open("requirements.txt").readlines()] setup( name='python-fakeports', version="0.1", packages=['python_fakeports'], url='', license='G...
898
309
from .BiomeDisplay import BiomeDisplay from .Chats import Chats from .PlayEffect import PlayEffect from .Reconnect import Reconnect from .SwapAck import SwapAck from .UseItemAck import UseItemAck
195
58
num_to_letters = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'], } class Solution: def letterCombinations(self,...
938
331
# Copyright 2014-2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library options from argparse import Action, SUPPRESS class RegistryAction(Action): def __init__(self, *args, **kwargs): kwargs['nargs'] = 1 self.dest = kwargs['dest'] ...
651
210
# MIT License # # Copyright (c) 2019 Arkadiusz Netczuk <dev.arnet@gmail.com> # # 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 # t...
4,453
1,291
#!/usr/bin/env python #-*- coding: utf-8 -*- #--------------------------------------------------------------------------------------------------- # --> Logic to handle scenarios #--------------------------------------------------------------------------------------------------- import imports from imports import * imp...
7,420
2,210
import dash import dash_html_components as html import dash_bootstrap_components as dbc import numpy as np from server import app from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate from components.cards import simple_info_card from components.dropdowns import dropdown_single fr...
7,980
2,095
def appendA(toAppend): newWord = toAppend + 'a' return newWord print(appendA(toAppend = raw_input("Enter a word to add an A letter: ")))
146
50
#!/usr/bin/python from __future__ import print_function import threading import boto3 import botocore import argparse from time import ctime ############### # Some Global Vars ############## lock = threading.Lock() awsaccts = [{'acct': 'acct1ID', 'name': 'master', 'cffile': 'location of clou...
16,119
4,296
import os from Config import Config from NIM.algorithms import WhaleOptimizationAlgorithm from NIM.algorithms.algorithm import logger if __name__ == '__main__': with open(Config.default_saved_scene_path, 'r') as f: data = f.read() m2d = eval(data) seed = 5 woa = WhaleOptimizationAlgorithm(m2...
882
298
''' File: COVIDZejunDatagraphs.py Author: Zejun Li Purpose: This file contains 12 different functions to make 5 different graphs about the COVID 19 in Idaho ''' import pandas as pd, numpy as np, matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime import datetime as dt def get_df(): ...
6,242
2,517
import pytest import json import datetime from scrapy.spiders import Spider import scrapy.exceptions from skyscraper.items import BasicItem from scrapy.exceptions import DropItem from skyscraper.pipelines.filesystem import DiskDeduplicationPipeline class MockDeduplication(): def __init__(self): self.s =...
1,118
359
__all__ = [ 'account', 'connect', 'locations', 'login', 'logout', ] from .windscribe import ( account, connect, locations, login, logout, )
180
66
# Generated by Django 3.2 on 2021-04-20 19:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [("videos", "0008_video_updated_timestamp")] operations = [ migrations.RenameField( model_name="video", old_name="updated_timestamp", new_name="updated" ...
335
116
# -*- coding:utf-8 -*- # &Author AnFany # 利用Sklearn包实现支持核函数回归 """ 第一部分:引入库 """ # 引入部分的北京PM2.5数据 import SVM_Regression_Data as rdata # 引入库包 from sklearn import svm import numpy as np import matplotlib.pyplot as plt from pylab import mpl mpl.rcParams['font.sans-serif'] = ['FangSong'] # 中文字体名称 mpl...
2,342
1,330
from os.path import dirname import unittest from .decorators import skip_if_no_mock from .helpers import mock from conda import history class HistoryTestCase(unittest.TestCase): def test_works_as_context_manager(self): h = history.History("/path/to/prefix") self.assertTrue(getattr(h, '__enter__'...
1,655
540
# This file is necessary to make this directory a package. from zojax.catalog.catalog import queryCatalog
107
28
# -*- encoding: utf-8 -*- import itertools try: from django.core.urlresolvers import reverse except ImportError: from django.urls import reverse from django.db.models.aggregates import Sum from django.template.defaultfilters import safe from django.utils.functional import cached_property from django_tables2 im...
6,066
2,082
#!/usr/bin/python3 import requests from requests.structures import CaseInsensitiveDict import json import getpass from pathlib import Path import hashlib import pandas as pd import gzip from multiprocessing import Process # Global variables #API_SERVER='https://dev-cloud.sleepdata.org/api/v1' API_SERVER='https://clo...
16,701
4,961
import numpy as np N = 100 R = 10000 R_range = range(R) size = (N, 3) C = np.zeros((N, 3)) k = 1 print ("100") print ("STEP: ", k) for i in range(N): print ("He ", C[i, 0], " ", C[i, 1], " ", C[i, 2]) k += 1 for j in range(R): A = np.random.uniform(-1, 1, size) B = np.sum(np.multiply(A, A), axis=1) B = np.sqrt(B)...
509
288
import os import matplotlib.pyplot as plt from skimage.io import imread def plot_corners(img, corners, show=True): """Display the image and plot all contours found""" plt.imshow(img, cmap='gray') plt.plot(corners[:,1], corners[:,0], 'r+', markeredgewidth=1.5, markersize=8) # Plot corners plt.axis('ima...
1,462
483
import os import sys import pytest import shutil from .test_utils import setup_env_vars, unset_env_vars, BACKUP_DEST_DIR, FAKE_HOME_DIR, DIRS sys.path.insert(0, "../shallow_backup") from shallow_backup.utils import copy_dir_if_valid TEST_TEXT_FILE = os.path.join(FAKE_HOME_DIR, 'test-file.txt') class TestCopyMethods:...
1,765
606
from collections import namedtuple import networkx as nx from mesa import Agent, Model class KillerAgent(Agent): def __init__(self, unique_id: int, model: Model, creator, pos: int, target_location: int, target_disease: str) -> None: super().__init__(unique_id, model) self.creator = creator ...
1,395
457
""" Given a base speed value and a list of percentages, calculates the speed value for each percentage """ def get_speeds(percents, base): speeds = [] for percent in percents: speeds.append(round(((int)(base) * ((int)(percent) / 100)))) print(speeds) return speeds
290
96
"""Base classes, context managers, and exceptions for MAGI actions.""" from abc import ABCMeta, abstractmethod import logging from openravepy import KinBody, Robot LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class SaveAndJump(object): """ Save the state of the environment and jump th...
11,762
2,998
from typing import List from core.exceptions.input_exceptions import (InputFormatException, InputTypeInconsistencyException) from core.model.graph import Graph from core.model.impl.fullOD import FullOD from core.model.impl.mapOD import MapOD from core.model.infrastructure ...
6,471
1,707
# encoding: utf-8 """ Ordinary Kriging interpolation is a linear estimation of regionalized variables. It assumes that the data change into a normal distribution, and considers that the expected value of regionalized variable Z is unknown. The interpolation process is similar to the weighted sliding average, an...
4,395
1,706
from .util import clear_proto_mask, is_proto_msg, add_proto_mask __all__ = [clear_proto_mask, is_proto_msg, add_proto_mask]
125
48
#!/usr/bin/python import rospy from arm.srv import IKService, IKServiceResponse rospy.init_node("asdf", anonymous=True) rospy.wait_for_service('IKService') srv = rospy.ServiceProxy('IKService', IKService) resp = srv([5, 16, 8, 0, 0, 0], None) print resp
260
111
from datetime import datetime from locale import * import scrapy from injector import Injector from scrapers.items import CoinMarketCapItem from scrapers.utils import UrlListGenerator setlocale(LC_NUMERIC, '') class CoinMarketCapSpider(scrapy.Spider): name = "cmc" custom_settings = { 'ITEM_PIPELINE...
1,410
452
from collections import OrderedDict from urllib.parse import urlparse import click import rethinkdb as r import redis import crawler.conf as conf # cli does not need to be thread-safe conn = r.connect(host=conf.RethinkDBConf.HOST, db=conf.RethinkDBConf.DB) domains = r.table('domains') @click.group...
4,361
1,385
# -8*- coding: utf-8 -*- import torch import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader, Dataset from torch.nn.parallel import DistributedDataParallel from torch.utils.data.distributed import DistributedSamp...
9,667
3,108
from django.urls import path from .views import * app_name = 'newsletter' urlpatterns = [ path('pixel/', my_image, name='pixel'), path('click/<str:uuid>/', click_redirect, name='click'), path('notification/', notification, name='notification'), path('sendtest/<str:slug>', sendtest, name='sendtest'), ...
373
123
n = int(input()) temp_n = n k=0 while True: a = int(temp_n / 10) b = temp_n % 10 c = (a + b) % 10 new = b*10 + c k += 1 if new == n: break temp_n = new print(k)
197
98
#!/usr/bin/env python """ cubic spline planner Author: Atsushi Sakai """ import math import numpy as np import bisect from scipy.spatial import distance class Spline: """ Cubic Spline class """ def __init__(self, x, y): self.b, self.c, self.d, self.w = [], [], [], [] self.x = x ...
6,491
2,639
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from behave import * from helpers.eventually import eventually @given('appliance is running') def appliance_running(context): @eventually(5) def wait_for_appliance_up(): assert context.appliance.running(), 'appliance did not start within 5 seconds' wait_for_ap...
333
111
from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.views import login, logout from django.conf import settings from django.views.static import serve from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/l...
1,211
412
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import subprocess as sp class Fonts: FONTS = [ "source-code-pro", "source-sans-pro", "source-serif-pro", "roboto", "roboto-mono", "roboto-slab", "open-sans", "open-sans-condensed", "lato", ...
1,469
543
from django.conf.urls import patterns, url from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView admin.autodiscover() from plag import views, const urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(...
5,142
1,498
import hmac import hashlib import json import uuid import httplib2 COINUT_URL = 'https://coinut.com/api/' class Coinut(): def __init__(self, user = None, api_key = None): self.user = user self.api_key = api_key self.http = httplib2.Http() def request(self, api, content = {}): ...
2,419
735
from typing import Any, Dict from ordered_set import OrderedSet from neighborly.core.ecs import Component from neighborly.core.engine import AbstractFactory, ComponentDefinition class Residence(Component): __slots__ = "owners", "former_owners", "residents", "former_residents", "_vacant" def __init__(self) ...
1,817
565
import threading import time import pandas as pd import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt import os import fnmatch import random import re import getpass import sys from rdflib import Graph from synbiohub_adapter.SynBioHubUtil import * from sbol import * """ This class will...
15,518
5,323
import os from six import iteritems from setuptools import setup from setuptools.command.develop import develop from setuptools.command.install import install import subprocess PACKAGE_NAME = 'drilsdown' SOURCES = { 'ipython_IDV': 'projects/ipython_IDV', 'idv_teleport': 'projects/IDV_teleport', 'ramadda_publi...
2,842
859
from datetime import datetime class Banco(): def __init__(self): self.cuentas = { '1':{ 'nombre': 'Marcos Martinez', 'balance': 173735, 'tipo': 1, 'movimientos': [] },'2':{ 'nombre': 'Alejandro Sanchez', 'balance': 1342, 'tipo': 0, 'movi...
2,129
752
# Generated by Django 3.1.7 on 2021-03-24 07:36 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("authentik_flows", "0016_auto_20201202_1307"), ("authentik_sources_saml", "0010_samlsource_pre_authentication_flow"),...
752
246
# Copyright 2015 NEC Corporation. All rights reserved. # # 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 ...
6,891
1,979
from __future__ import annotations from itertools import product from typing import Iterator day_num = 17 def part1(lines: Iterator[str]) -> int: probe = Target.from_str(next(lines)) mx = max(y for _, y in probe.get_possible()) return mx * (mx + 1) >> 1 def part2(lines: Iterator[str]) -> int: prob...
3,497
1,099
from conway import * def test_neighbors_at_origin(): result = [(1,1), (-1,-1), (0,1), (1,0), (-1,1), (1,-1), (-1,0), (0,-1)] nb = neighbors((0,0)) assert( set(result) == set(nb) ) def test_neighbors_at_negative_quadrant(): result = [(0, -1), (-2, -1), (-1, 0), (-1, -2), (0, 0), (0, -2), (-2, 0), (...
687
317
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: __init__.py @time: 2018-03-06 00:00 """ from __future__ import unicode_literals import eventlet eventlet.monkey_patch() from logging.config import dictConfig from config import current_config from flask import Flask from flask_...
5,426
2,086
#!/usr/bin/env python3 ########################################################################## # USAGE: import N50 # help(N50) # N50.main(~/stanford_swc/fasta-o-matic/fasta/normal.fa) # DESCRIPTION: Function that calculates N50 for a FASTA file # Created by Jennifer M Shelton ################################...
2,003
567
#!/usr/bin/env python3 __all__ = ('main_by_args','latex_main','latex_uuid','latex_tree') cmd_help=""" Command help: blob compile the blob(s) with --uuid=UUID, tree compile all the blobs starting from --uuid=UUID main_public compile the whole document, for the general public ...
34,017
11,441
# this script generates visualizer header import os visualizer_dir = 'extension/visualizer' visualizer_css = os.path.join(visualizer_dir, 'visualizer.css') visualizer_d3 = os.path.join(visualizer_dir, 'd3.js') visualizer_script = os.path.join(visualizer_dir, 'script.js') visualizer_header = os.path.join(visualizer_dir...
2,950
1,012
__all__ = ('KXAspectRatio', ) from kivy.uix.layout import Layout from kivy.properties import BoundedNumericProperty, OptionProperty HALIGN_TO_ATTR = { 'center': 'center_x', 'middle': 'center_x', 'left': 'x', 'right': 'right', } VALIGN_TO_ATTR = { 'center': 'center_y', 'middle': 'center_y', ...
1,945
674
import cv2 import numpy as np from matplotlib import pyplot as plt brightness = {"DARK": 0, "NORMAL": 1, "LIGHT": 2} contrast = {"HIGH": 2, "NORMAL": 1, "LOW": 0} class ImageSetup: def __init__(self): self.brightness = None self.contrast = None...
4,006
1,468
import random from models.game.bots.Bot import Bot from models.game.Board import Board class RandoMaxBot(Bot): """ Semi-random bot This is a minimax bot that scores moves randomly unless the end of the game is seen within a 2-ply lookahead """ def __init__(self, number, name=None): if name is...
3,799
1,073
#!/usr/bin/env python #-*- encoding:UTF-8 -*- """ Background: JJ and MM want to have a fine dinner, celebrating their annual bonuses. They make this rule: This dinner is on the person who gets more annual bonus. And the cost of the dinner is the diff of money they make mod 300, per capita. Requirement: Decide the mo...
1,924
722
#!/usr/bin/python from pytvmaze.tvmaze import *
49
22
from flask import Flask, request, jsonify from connection import get_sql_connection from product import get_all_products, insert_product, delete_product import json from flask_cors import CORS app = Flask(__name__) CORS(app) cnx = get_sql_connection() @app.route('/getProducts', methods=['GET']) def get_products(): ...
1,241
394
import random from api.config import restaurant_collection as restaurants def organize_restaurant_output(): output = [] for q in restaurants.find(): output.append({ "id" : str(q['_id']), 'name' : q['name'], 'neighborhood' : q['neighborhood'], 'cuisine' :...
555
168
class InvalidLimitException(Exception): """ Invalid number of matches requested """ pass class InvalidLeagueCodeException(Exception): """ The League code requested is either invalid or not supported """ pass class InvalidTeamCodeException(Exception): """ The Team Code requested...
351
86
""" code to call the snow model for a simple test case using brewster glacier data """ from __future__ import division import numpy as np import matplotlib.pylab as plt import datetime as dt from nz_snow_tools.util.utils import resample_to_fsca, nash_sut, mean_bias, rmsd, mean_absolute_error, coef_determ seb_dat = np...
6,187
3,422
from floodsystem.stationdata import build_station_list from floodsystem.station import inconsistent_typical_range_stations stations = build_station_list() incon_station=inconsistent_typical_range_stations(stations) incon_names=[] for station in incon_station: incon_names.append(station.name) incon_names.sort() prin...
336
107
from typing import Generic, TypeVar from typing_extensions import Final from yaga_ga.evolutionary_algorithm.individuals import IndividualStructure class InvalidOperatorError(ValueError): pass IndividualType = TypeVar("IndividualType") GeneType = TypeVar("GeneType") class GeneticOperator(Generic[IndividualTy...
507
141
# -*- coding: utf-8 -*- """ Created on Wed Dec 1 13:21:44 2021 This file holds the stimuli that are used in the world to represent cues. obs_time --> Stimulus representing time match_cifar --> Natural scenes for phase 1 learning obs_cifar --> Natural scenes for phase 2 learning match_alp...
3,973
1,465
print('ingrese el monto a pagar en aseo urbano') aseo=float(input()) print('ingrese el valor de lectura del mes anterior') ant=float(input()) print('ingrese el valor de lectura del mes actual') act=float(input()) cons=act-ant if 0<cons<=100: pago=cons*4600 print('debera pagar $',pago,'en luz electrica y',aseo,'...
675
295
import time import meilisearch from meilisearch.tests import BASE_URL, MASTER_KEY class TestSynonyms: client = meilisearch.Client(BASE_URL, MASTER_KEY) index = None new_synonyms = { 'hp': ['harry potter'] } default_synonyms = {} def setup_class(self): self.index = self.client.c...
1,040
327
from lexer import Lexer from parser import Parser if __name__ == "__main__": lexer = Lexer("exemplos/teste2.pasc") parser = Parser(lexer) parser.executa()
168
62
class Solution: def plusOne(self, digits: List[int]) -> List[int]: carry = 1 result = [] for digit in digits[::-1]: digit += carry result.append(digit % 10) carry = digit // 10 if carry: result.append(carry) return result[::...
324
99
from .mqtt import MQTTClient from .sql import * from .redis import *
69
24
from marshmallow import Schema, fields class RegisterUser(Schema): """Deserialize register user schema.""" email = fields.Email(required=True) """Email.""" first_name = fields.String(required=True) """First name.""" last_name = fields.String(required=True) """Last name.""" password...
1,275
385
"""Collection of tools for changing the text of your terminal.""" from coloredterm.coloredterm import ( Back, bg, colored, colors, cprint, fg, Fore, names, pattern_input, pattern_print, rand, Style ) __version__ = "0.1.9" __all__ = [ 'Back', 'bg', 'colored', ...
450
167
# Run from GAE remote API: # {GAE Path}\remote_api_shell.py -s {YourAPPName}.appspot.com # import export_as_csv import csv from google.appengine.ext import db from google.appengine.ext.db import GqlQuery def exportToCsv(query, csvFileName, delimiter): with open(csvFileName, 'wb') as csvFile: csvWriter ...
1,706
506
import plotly.figure_factory as figure_factory import statistics import random import pandas df = pandas.read_csv("data.csv") data = df["reading_time"].tolist() population_mean = statistics.mean(data) print("Population mean :", population_mean) def show_fig(mean_list): df = mean_list fig = fig...
950
338
from sqlite3 import Connection from ddtrace.util import deprecated @deprecated(message='Use patching instead (see the docs).', version='0.6.0') def connection_factory(*args, **kwargs): return Connection
209
58
#!/usr/bin/python3 # -*- coding: utf-8 -*- """Define function used on logging.""" import logging __KAFKA_DECORATOR_DEBUG__ = None def set_debug_level(level): """Set the level of log. Set logging level for all loggers create by get_logger function Parameters ---------- level: log level def...
801
268
#!/usr/bin/env python # coding:utf8 """ this module reads strings.csv, which contains all the strings, and lets the main app use it """ import sys import csv import os from flask import Markup import configparser config = configparser.RawConfigParser() path = '../hseling_api_diachrony_webvectors/hseling_api_diachron...
1,409
474
class node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.start=None #(self/head) def viewList(self):#this function print the whole list if self.start==None: print("list is empty") else: temp...
1,077
335
# -*- coding: utf-8 -*- """ Created on Thu Nov 10 20:21:46 2015 @author: derrick """ from __future__ import print_function, absolute_import, unicode_literals, division import glob import itertools import json import os import random import numpy as np import obspy import pandas as pd from six import string_types im...
40,603
11,897
from tarfile import SUPPORTED_TYPES import requests import re from bs4 import BeautifulSoup import json import HouseHunter.globals as Globals from HouseHunter.ad import * from pathlib import Path class Core(): def __init__(self, filename="ads.json"): self.filepath = Path().absolute().joinpath(filename) if...
4,850
1,461
# nice and clean closure notation def get_counter_neat(): def f(): f.x += 1 return f.x f.x = 0 return f # traditional, not_so_neat closure notation def get_counter_traditional(): x = [0] def f(): x[0] += 1 return x[0] return f #### EXAMPLE ######################...
582
223