content stringlengths 5 1.05M |
|---|
from pyspark import SparkConf
from pyspark.sql import SparkSession, Window
from pyspark.sql.types import ArrayType, StructField, StructType, StringType, IntegerType, DecimalType, FloatType
from pyspark.sql.functions import udf, collect_list, struct, explode
from decimal import Decimal
import random
import pandas as pd
... |
from ...utils import constants
import pandas as pd
import geopandas as gpd
import numpy as np
import shapely
import pytest
from contextlib import ExitStack
from ...core.trajectorydataframe import TrajDataFrame
from ...models.gravity import Gravity
from ...models.epr import EPR, DensityEPR, SpatialEPR, Ditras
from ...m... |
"""Verbose names."""
# pylint: disable=invalid-name
from django.db import migrations, models
class Migration(migrations.Migration):
"""Verbose names."""
dependencies = [
('IoT_DataMgmt', '0091_rename_logical_data_type')
]
operations = [
migrations.AlterModelOptions(
n... |
import pandas as pd
import numpy as np
import PIL
from PIL import Image
import pickle
import random
import matplotlib.pyplot as plt
import json
from ast import literal_eval as make_tuple
from operator import itemgetter
from collections import Counter
import math
'''
1. Read each fold for each age group
2. Add counts o... |
import numpy as np
import pandas as pd
def fit(x,y):
matrix_a = []
for i in range(len(x.columns)+1):
line = []
if i == 0:
for j in range(len(x.columns)+1):
if j == 0:
line.append(len(x))
else:
line.append(sum(x.... |
from thatlib import lines
print(lines(__file__))
|
"""
Collections
===========
This module contains some data structures used in :mod:`relentless` as an
alternative to Python's general purpose containers, for ease of use in constructing
potentials and performing computations during the optimization workflow.
.. autosummary::
:nosignatures:
FixedKeyDict
P... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.homeRecipes, name='home'),
path('recipes/', views.recipes, name='recipes'),
path('about/', views.about, name='about'),
] |
class Table(object):
"""Base class for all Table classes."""
def __init__(self, connection, classname):
"""
:param connection: a connection instance.
:param classname: the name of the class for which the crown functions.
:return:
"""
self.classname = classname
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [("django_pesapal", "0002_transaction_payment_status")]
operations = [
migrations.AddField(
model_name="transaction",
... |
import argparse
import os
from utils import get_logger, make_date_dir
from data_utils import load_data_from_csv, batch_loader
import numpy as np
from time import time
def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument("-m", "--model", type=str, default="LSTNet",
... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_equal, assert_array_almost_equal
from scipy.sparse import csgraph
def test_weak_connections():
Xde = np.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
Xsp = ... |
name = "opt" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test functionality of ci/build_matrix.py"""
import dataclasses
import importlib.util
import json
import string
import sys
from pathlib import Path
# Load the build_matrix.py file using importlib.
# See https://docs.python.org/3/library/importlib.html#importing-a-source... |
import os
import shutil
import tempfile
import pytest
from django.core.exceptions import ValidationError
from paper_uploads import validators
from .dummy import make_dummy_file, make_dummy_image
class TestExtensionValidator:
def test_format_extension_list(self):
validator = validators.ExtensionValidator... |
from webdav.exceptions import *
from webdav.urn import Urn
from os.path import exists
class ConnectionSettings:
def is_valid(self):
pass
def valid(self):
try:
self.is_valid()
except OptionNotValid:
return False
else:
return True
class Web... |
# Copyright 2012 Jeffrey R. Spies
# License: Apache License, Version 2.0
# Website: http://jspi.es/benchmark
from . import __VERSION__, __URL__
from .Benchmark import Benchmark
import time
import platform
import os
import sys
class BenchmarkProgram(object):
def __init__(self, module="__main__", **kwargs):
... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.test
collection = db.students
count = collection.find().count()
print(count) |
import django_tables2 as tables
from django_tables2.utils import A # alias for Accessor
from website.apps.core.models import Source, Culture, Language
# Note, due to the current version of django_tables2 not merging in Meta classes
# https://github.com/bradleyayers/django-tables2/issues/85
# The work around is to in... |
# -*- coding: utf-8 -*-
import fs
from fs.base import FS
from malibu.text import parse_uri
from peewee import (
AutoField,
TextField,
)
from tubedlapi.model import BaseModel
from tubedlapi.model.fields import EncryptedBlobField
class Destination(BaseModel):
id = AutoField(primary_key=True)
name = T... |
# some training parameters
EPOCHS = 200
BATCH_SIZE = 32
NUM_CLASSES = 2
image_height = 256
image_width = 192
channels = 1
save_model_dir = "saved_model_static/model"
dataset_dir = "dataset_parametric/"
train_dir = dataset_dir + "train"
valid_dir = dataset_dir + "valid"
test_dir = dataset_dir + "test/"
# choose a netwo... |
import torch
import torch.nn as nn
import torch.jit as jit
from torch.nn import Parameter
from torch.nn import functional as F
from parametrization import Parametrization
import math
import time
class MomentumLSTM(nn.Module):
def __init__(self, input_size, hidden_size, mu, epsilon, bias=True):
super(Mo... |
import flask
import data.db_session as db_session
from data.source import Location, Query, DataView, Subtype, LocationType, RequestMethod
from services.select_services import get_objects, search_object
from services.save_services import save_object
from flask_login import login_required
from decorators.admin import is_... |
"""
I’ll be using the Zippopotam.us REST API.
This API takes a country code and a zip code and returns
location data associated with that country and zip code.
For example, a GET request to http://api.zippopotam.us/us/90210
"""
from fastapi import FastAPI
import requests
from fastapi.testclient import TestClient
ap... |
data = open("input.txt", "r").readlines()
polymer = data[0]
pair_insertion = {}
for line in data[2:]:
[token, replacement] = line.strip().split(" -> ")
pair_insertion[token] = replacement
result = [i for i in polymer.strip()]
for step in range(0, 10):
next = []
for i, si in enumerate(result):
... |
import arcade
import json
from typing import List, Dict
with open("leaderboard.json", "r") as f:
prim_data = json.load(f)
def msort(l: List[int]) -> List[int]:
# base case
if len(l) < 2:
return l
left_side = msort(l[:len(l) // 2])
right_side = msort(l[len(l) // 2:])
sorted_list = []
... |
import argparse
import unittest
from ffwd.ffwd_send import tag_type
class TestFFWDSend(unittest.TestCase):
def test_tag_type(self):
self.assertEquals(('hello', 'world'), tag_type("hello:world"))
self.assertEquals(('hello', 'world:two'), tag_type("hello:world:two"))
with self.assertRaises... |
import collections
import json
import logging
import argparse
from .. import init_logging
def main(args_):
parser = argparse.ArgumentParser()
parser.add_argument("files",
type=str,
nargs='*',
help="JSON files to summarize.")
args ... |
import logging
from importlib import import_module
from pyrite import settings
log = logging.getLogger(__name__)
DEFAULT_THEME = 'dark'
def __getattr__(name):
"""Intercept lookups of theme attributes and load from the currently
active theme based on user settings.
Client code can reference theme attri... |
'''
Created on May 23, 2016
@author: John
'''
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
words = line.split()
if len(words) < 5 : continue
if words[0] != "From" : continue
when = words[5]
tics = when.split(":")... |
# Copyright 2015 cybojenix <anthonydking@slimroms.net>
#
# 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 ... |
import torch
from torch import nn, einsum
import torch.nn.functional as F
import math
from einops import rearrange, repeat
from einops.layers.torch import Rearrange
from module import FeedForward, ConvAttention, PreNorm
import numpy as np
class Transformer(nn.Module):
def __init__(self, depth, dim, heads, dim_he... |
import os
import json
import database
from exceptions import *
import datetime
class TimeReportHandler(object):
"""
Main class to handle information about projects and Employees ("using" projects)
"""
def __init__(self):
self.db = get_db_connection()
self.active_employee = None
... |
from __future__ import division
##############################################################################
#
# Copyright (c) 2009-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/... |
#/usr/bin/python
import shutil
template_directory = "originals/template-card"
ID_FROM = 1
ID_TO = 50
brightsign_ids = map(lambda x:"%02d"%(x,), range(ID_FROM,ID_TO+1))
for bsid in brightsign_ids:
shutil.copytree(template_directory, bsid)
current_sync_filename = bsid+"/current-sync.xml"
with open(current_... |
# -*- coding: utf-8 -*-
"""
This module provides a variety of transforms that transform the AST
into a final form ready for code generation.
Below follows an explanation and justification of the design of the main
compilation stages in numba.
We start with a Python AST, compiled from source code or decompiled from
by... |
# Copyright 2020 ewan xu<ewan_xu@outlook.com>
#
# 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 agree... |
"""
Measure resonators, one at a time, with the readout tone centered in the filterbank bin.
"""
from __future__ import division
import time
import numpy as np
from kid_readout.roach import analog, calculate, hardware_tools, tools
from kid_readout.measurement import acquire, basic
from kid_readout.equipment import h... |
def test_InStock_cost():
"""
Tests if cost value is received correctly
when condition is In Stock on www.beswalmarttbuy.com.
"""
def test_OutOfStock_cost():
"""
Tests if cost value is received correctly
when condition is Out of Stock on www.walmart.com.
"""
|
#!/usr/bin/env python3
"""
**Description**
Helper functions for OpenAI Gym environments.
"""
import operator
from functools import reduce
from collections import OrderedDict
from gym.spaces import Box, Discrete, Dict, Tuple
def is_vectorized(env):
return hasattr(env, 'num_envs') and env.num_envs > 1
def i... |
from scipy import eye, kron, diag
# Define the basis for the liouvillian
# Axes: _XY, __Z
_XY, __Z = (
diag([1.0, 1.0, 0.0]),
diag([0.0, 0.0, 1.0]),
)
# States: B, C or A & B & C
___B, ___C, _ABC = (
diag([0.0, 1.0, 0.0]),
diag([0.0, 0.0, 1.0]),
diag([1.0, 1.0, 1.0]),
)
# Auto-relaxation rates
R... |
import os
import sys
import glob # Only for python 3.5+
import generate_txt_from_pydocs as gen_txt
''' Use Example:
python generate_txt_from_python_progs.py [SOURCE_FILE_DIR] [TARGET_DIRECTORY]
'''
def gen_txt_from_python_files(source_path, target_directory):
os.system('mkdir ' + target_directory)
target_... |
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
map = Basemap(projection='poly',
lon_0=0.0, lat_0=0,
llcrnrlon=-80.,llcrnrlat=-40,urcrnrlon=80.,urcrnrlat=40.)
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
m... |
from keystoneclient.auth.identity import v3
from keystoneclient import session
from keystoneclient.v3 import client as keystoneclient
from subprocess import call, Popen, PIPE
import requests
import json
import testtools
keystone_url = "http://10.4.13.14:35357/v3"
cinder_url = "http://10.4.13.14:8776/v2/"
quota_url = "... |
"""
Copyright (C) 2021 NVIDIA Corporation. All rights reserved.
Licensed under The MIT License (MIT)
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 limitat... |
import numpy as np
import math
from solarpy import irradiance_on_plane
from pyephem_sunpath.sunpath import sunpos
# Function to return a solar irradiance in [W/m^2]
# @params: installation - installation object from class Installation
# clouds_dict - dict with datetime and clouds forecast from get_hourly_f... |
"""Remove applicable_date from form_distribution
Revision ID: 4aaa5ba83bf5
Revises: 24d87e41078e
Create Date: 2020-02-17 13:48:43.408752
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '4aaa5ba83bf5'
down_revision = '24... |
import numpy as np
from collections import defaultdict
from scipy.sparse import csr_matrix
import pickle as pkl
import os
import sys
from collections import Counter
import random
def align_relation(dataset):
rel_list_0, rel_list_1, rel_list_2 = [], [], []
assign_dict = defaultdict(list)
file0 = dataset + "... |
# Generated by Django 3.2.12 on 2022-03-15 07:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('menu', '0011_alter_size_size'),
]
operations = [
migrations.AddField(
model_name='size',
name='price',
... |
# Generated by Django 2.2 on 2019-05-14 13:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
('topics', '0036_auto_20190513_2253'),
]
operations = [
migrations.Rename... |
# Generated by Django 2.2.24 on 2022-01-09 18:58
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0004_product_date'),
]
operations = [
migrations.AlterField(
model_name='product',
name=... |
rom pylayers.antprop.antenna import *
A = Antenna(typ='azel',param={'filename':'antenna.ant','pol':'V'})
|
months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"]
def clean_value(inp):
inp = inp*100
inp ="{0:.2f}".format(inp)
return inp
def clean_aditya(data):
for item in data:
actual_date = item["Date"].split("-")
day = actual_date[0]
month = months.index(actual_date[1]) + 1
year = ... |
import pytest
import numpy as np
import gym
from lagom.envs import RecordEpisodeStatistics
from lagom.envs import NormalizeObservation
from lagom.envs import NormalizeReward
from lagom.envs import TimeStepEnv
@pytest.mark.parametrize('env_id', ['CartPole-v0', 'Pendulum-v0'])
@pytest.mark.parametrize('deque_size', [2... |
from youtube_dl import YoutubeDL
import os, sys
sys.path.append(os.getcwd())
from db.db_pool_handler import InstantDBPool
from PIL import Image
from utils.snow_id import HSIS
from tenacity import retry, wait_random
import json, pymysql, time, traceback, shutil
class VideoDownload(object):
def __init__(self):
... |
"""Common database code used by multiple `covid_hosp` scrapers."""
# standard library
from contextlib import contextmanager
import math
# third party
import mysql.connector
import pandas as pd
# first party
import delphi.operations.secrets as secrets
class Database:
def __init__(self,
connection,... |
from sqlalchemy import Column, Integer, String
from .Base import Base
class Genre(Base):
__tablename__ = 'genres'
id = Column(Integer, primary_key=True)
name = Column(String(200))
|
"""
Declare and configure the models for the courses application
"""
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from cms.extensions.extension_pool import extension_pool
from ..core.models... |
################################################################################
# populate_obs_instrument_VGISS_prof.py
#
# Routines to populate fields specific to VGISS.
################################################################################
import pdsfile
from config_data import *
import import_util
from... |
from gsse_python_client.series import Series
import numbers
class TimeWindows:
def __init__(self, timewindows):
self.timewindows = []
for timewindow in timewindows:
self.timewindows.append(TimeWindow(timewindow))
def __getitem__(self, item):
return self.timewindows[item]
... |
"""
This module contains the plugin interface that you need to implement
for writing new plugins.
Plugins are regular python packages that contains a set of setuptools
entrypoints that expose the available plugins.
Basically you need to define a dictionary where the keys are the possible
entrypoints (one per plugin t... |
#
# Autogenerated by Thrift Compiler (0.13.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive impo... |
from pandas import DataFrame
class Compiler:
"""
Deals with Writing to files using Information gained from crawling
"""
@staticmethod
def decompile(data: DataFrame, load_file: str, save_file_path: str, prefix: str):
"""
Saves data given in data frames as a new file each to the gi... |
import os
import numpy as np
from PIL import Image, ImageFilter
import pandas as pd
import pymesh
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
# Lighting noise transform
class TransLightning(object):
def __init__(self, alphastd, eigval, eigvec):
self.alphastd =... |
"""Platform Models."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
from .OrderItems import OrderItems
from .Filters import Filters
from .PlatformOrderPage import PlatformOrderPage
from .AppliedFilters import Applie... |
# Generated by Django 3.2.6 on 2021-11-03 10:24
import cloudinary.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('review', '0004_auto_20211014_1426'),
]
operations = [
migrations.AlterField(
model_name='review',... |
import numpy as np
import cv2
import os
class Arducam():
_name = 'Arducam'
def _read_frame(self):
ret = False
while ret == False:
ret, image = self._cam.read()
# split
left = image[0:self.image_size_[1], 0:self.image_size_[0]]
right = image[0:self.image_siz... |
# -*- coding: utf-8 -*-
# Path to Bochs debugger. Bochs must be compiled with --enable-debugger and --with-nogui.
default_bochs = 'bochs'
|
import time
import tweepy
from data import Data
from flask import Flask, render_template
app = Flask(__name__)
data = Data()
@app.route("/")
def index():
return render_template(
"index.html",
herd=data.getHerd(),
vaccinations=data.getVacc(),
casesDeaths=data.getCasesDeaths(),
... |
import functools
from rest_framework.response import Response
class BasePermissionDecorator(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, obj_type):
return functools.partial(self.__call__, obj)
def error(self, data):
return Response({"error": "permission-denied", "d... |
from collections import deque
class AnyPoppableDeque(deque):
def __init__(self):
super().__init__()
def pop_at_any_pos(self, pos):
value = self[pos]
del self[pos]
return value
class RangeParam(object):
def __init__(self, block_id=None, headers=None):
self.block_i... |
""" drivers and functions for I/O
"""
from __future__ import unicode_literals
from builtins import open, str
import os
import time
import json
import subprocess
from itertools import chain
from itertools import starmap
from functools import partial
import pandas
from .strid import canonical as canonical_species_identif... |
from .base import Base
from abc import abstractmethod
class Routing(Base):
def __init__(self, di):
super().__init__(di)
@abstractmethod
def handler_classes(self, configuration):
pass
@abstractmethod
def handle(self, input_output):
pass
def build_handler(self, handler... |
"""Logging utilities."""
import logging
def all_loggers(root=True, placeholders=False):
"""Yield all loggers."""
logger_manager = logging.Logger.manager
if root:
yield 'root', logger_manager.root
for name, logger in logger_manager.loggerDict.iteritems():
if placeholders or isinstance(l... |
import requests
import json
import sys
import uuid
# from marconi.tests.functional import helpers
# from endpoints import IDENTITY_URL,MARCONI_URL
# from authentication import auth
MARCONI_URL = 'http://127.0.0.1:8888/v1/queues/'
# Create Queue
def create_queue(queue_name,custom_uuid):
Final_URL = MARCONI_URL+'{0... |
# 2015-07-04
# W = 16
W = 2 * 10 ** 3
# num_best = 0
# max_profit = 0
# n = 4
n = 500
class SolutionContainer:
def __init__(self, max_profit, best_set, num_best):
self.max_profit = max_profit
self.best_set = best_set
self.num_best = num_best
def getMaxProfit(self):
return self.max_profi... |
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
# -*- coding: utf-8 -*-
"""
Function implementation test.
Usage: resilient-circuits selftest -l fn_api_void
"""
import logging
LOG = logging.getLogger(__name__)
from resilient_lib import RequestsCommon, validate_fields
from fn_api_void.lib.apivoid_helper imp... |
__author__ = 'wjimenez'
|
# Copyright 2018 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
# =============================================================================
"""Benchmarks for TensorFlow.js Layers.
These benchmarks compa... |
''' 1. Ignore if it already exists '''
# Search @ class.AniImageBox
def __init__(self, layer = "UI"):
Window.__init__(self, layer)
# Add below
if app.ENABLE_SLOT_MACHINE_SYSTEM:
self.end_frame_event = None
self.key_frame_event = None
''' 2. Ignore if it already exists '''
# Search @ class.AniImageBox
def ... |
import os
import sys
import shutil
from pathlib import Path
from typing import Iterator
import numpy as np
from jina import Document
file_dir = Path(__file__).parent
sys.path.append(str(file_dir.parent))
def random_docs(num_docs, chunks_per_doc=5, embed_dim=10, jitter=1, start_id=0, embedding=True) -> Iterator['Do... |
# coding: utf-8
"""
UCS Starship API
This is the UCS Starship REST API
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class TechsupportmanagementTechSupportStatus(object):
"""... |
#
# @lc app=leetcode id=72 lang=python3
#
# [72] Edit Distance
#
# https://leetcode.com/problems/edit-distance/description/
#
# algorithms
# Hard (40.50%)
# Likes: 2795
# Dislikes: 44
# Total Accepted: 213.4K
# Total Submissions: 526.3K
# Testcase Example: '"horse"\n"ros"'
#
# Given two words word1 and word2, fi... |
from django.test import TestCase
from django.db import IntegrityError
from django.utils import timezone
from django.contrib.auth.models import User
from ostinato.blog.models import BlogEntryBase
from ..models import Entry
from .utils import create_objects
class BlogEntryBaseTestCase(TestCase):
def test_model_... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
image = models.ImageField(upload_to='images/', null=True, blank=True)
bio = mo... |
"""
Plan pieces that may be useful for assembling plans.
This is the LCLS counterpart to `bluesky.plan_stubs`.
The plans in this module are not meant to be run individually, instead these
are intended as building blocks for other complete plans.
"""
import logging
from bluesky.plan_stubs import subscribe
from bluesk... |
def area(larg, comp):
a = larg * comp
print('A área de um terreno de {:.2f} x {:.2f} é de {:.2f} m².'.format(larg, comp, a))
# Programa principal
print('{:=^55}'.format(' Controle de Terrenos '))
l = float(input('LARGURA (M): '))
c = float(input('COMPRIMENTO (M):'))
area(l, c)
print('=' * 55)
|
class Solution:
# @param A : list of list of integers
# @param B : list of integers
# @param C : list of integers
# @param D : list of integers
# @param E : list of integers
# @return a list of integers
def solve(self, A, B, C, D, E):
sum = []
print(A)
for i in range(... |
import json
import random
def random_color():
hex_characters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
color_string = ""
return color_string.join(random.choices(hex_characters, k=6))
def get_dict_from_json(name):
json_file = open(name, "r")
json_string = ... |
#! /usr/bin/python3
import os
from N4Tools import Design
commands = [
'sudo apt-get install python3-setuptools',
'apt list --upgradable',
'sudo apt install git',
'git clone https://github.com/kivy/buildozer.git',
'cd buildozer && sudo python3 setup.py install',
'sudo apt update',
'sudo apt ... |
from PIL import Image
from PIL.ExifTags import TAGS
import time
def get_date(exifinfo):
if 36867 in exifinfo: # 36867:DateTimeOriginal
exifdate = exifinfo[36867]
elif 36868 in exifinfo: # 36868:DateTimeDigitized
exifdate = exifinfo[36868]
elif 306 in exifinfo: # 306:DateTime
exi... |
with open("task2.txt") as file:
data = file.read()
print(data.replace("\n", ""))
|
from django.apps import AppConfig
class EventappConfig(AppConfig):
name = 'EventApp'
|
import json
import time
import boto3
from botocore.exceptions import (
ClientError, NoCredentialsError, ParamValidationError
)
from .exceptions import (
BucketNameAlreadyInUse, CannotGetCurrentUser, CannotListAccountAliases,
CredentialsNotFound, InvalidBucketName, InvalidUserName, UserNameTaken
)
POLICY... |
def already_existing1():
pass
def already_existing2():
pass
def already_existing3():
pass
|
import os
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print ('Error: Creating directory. ' + directory)
# Example
createFolder('./data/')
# Creates a folder in the current directory called data |
DATA = [
{
'name': 'Facundo',
'age': 72,
'organization': 'Platzi',
'position': 'Technical Mentor',
'language': 'python',
},
{
'name': 'Luisana',
'age': 33,
'organization': 'Globant',
'position': 'UX Designer',
'language': 'javas... |
#!/usr/bin/env python
"""
This module contains functions to construct classifiers, get their param
distributions for a grid search, get top features and other
smaller utility functions.
"""
__all__ = [
"supported_estimators",
"publication_ensemble",
"get_parameter_distribution_for_model",
"make_classi... |
import numpy as np
import tensorflow as tf
from tensorflow.contrib.framework.python.ops import arg_scope, add_arg_scope
from blocks.helpers import int_shape, get_name
# @add_arg_scope
# def conv2d(inputs, num_filters, kernel_size, strides=1, padding='SAME', nonlinearity=None, bn=True, kernel_initializer=None, kernel_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.