content
stringlengths
0
894k
type
stringclasses
2 values
""" Run MWEP Usage: main.py --config_path=<config_path>\ --project=<project>\ --path_event_types=<path_event_types>\ --path_mapping_wd_to_sem=<path_mapping_wd_to_sem>\ --languages=<languages>\ --wikipedia_sources=<wikipedia_sources>\ --verbose=<verbose> Options: --config_path=<config_path> ...
python
# -*- mode: python -*- # -*- coding: utf-8 -*- ## # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache Li...
python
import logging from heisen.config import settings class ExtraFields(logging.Filter): def filter(self, record): for key, value in getattr(settings, 'EXTERNAL_FIELDS', {}).items(): setattr(record, key, value) return True class AbsoluteModuleName(logging.Filter): def filter(self, ...
python
from core.commands import * def execute_from_command_line(argv=None): """ A simple method that runs something from command line. argv[1] is the command argv[2] is the remaining command or project name """ if argv[1] == 'createproject': createproject(argv[2])
python
""" generate-bus-data.py Module for automatically generating a simulated bus data set. """ import os import json import xlrd from tqdm import tqdm from grid import Grid # Module local to this project. def str_ascii_only(s): ''' Convert a string to ASCII and strip it of whitespace pre-/suffix. ''' re...
python
#!/usr/bin/python # -*- coding: utf-8 -*- import os import cv2 import xml.etree.ElementTree as ET import numpy as np def get_data(input_path, mode): all_imgs = [] classes_count = {} class_mapping = {} visualise = False # data_paths = [os.path.join(input_path,s) for s in ['VOC2007', 'VOC2012']] ...
python
from django.db import models # Create your models here. class UserInfo(models.Model): """ 用户表 """ username = models.CharField(max_length=32, verbose_name="用户名", unique=True) phone = models.CharField(max_length=11, verbose_name="手机号", unique=True) email = models.EmailField(max_length=32, verbose_name="...
python
"""discard columns in web chapter 1 objectives Revision ID: f1be4ab05a41 Revises: a4ac4ebb0084 Create Date: 2022-01-01 17:33:05.304824 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'f1be4ab05a41' down_revision = 'a4ac4ebb0084' branch_labels = None depends_on ...
python
#!/usr/bin/python # coding=utf-8 # # This script reformats a list of leaked names import anomdns from anomdns import anonymizer key = "blahh" anom = anonymizer() anom.set_key(key) test = [ "WWW.GOOGLEAPIS.COM.DAVOLINK", "IB.TIKTOKV.COM.DAVOLINK", "YOUTUBE.COM.DAVOLINK", "MTALK.GOOGLE.COM.DAVOLINK", "US.PERF...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-04 09:09 from __future__ import unicode_literals import aether.odk.api.models from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import django.utils.timez...
python
#!/usr/bin/env python from __future__ import print_function from os import path, getcwd from runana.run import execute, print_time, generate_list def main(): input_file = 'config.nml' chain_iters = setup_replacers() scratch_base = path.expanduser('~/test_run/runana/integrate_test') pro...
python
#!/usr/bin/env python # # Author: Thamme Gowda [tg (at) isi (dot) edu] # Created: 2019-11-11 import argparse import sys import logging as log import io import collections as coll from nlcodec.utils import make_n_grams, make_n_grams_all from nlcodec import load_scheme, EncoderScheme from pathlib import Path import json...
python
version https://git-lfs.github.com/spec/v1 oid sha256:db80e7c15180793b640419d93a414f5ab56bd0fa3c44275e9d251fc513face49 size 14291
python
#!/usr/bin/env python from __future__ import absolute_import import argparse import yaml from pymongo import MongoClient from pymongo.errors import OperationFailure ## ## Reads users and collections from a yaml file. ## ## User passwords will be set to [username]_pw. ## def create_users(client, databases): for ...
python
from django.conf.urls import url from django.urls import include from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import routers, permissions, authentication from environments.views import SDKIdentities, SDKTraits from features.views import SDKFeatureStates from organisations...
python
dia= float(input("Digite o dia do seu nascimento ")) mes= input("Digite o mês do seu nascimento") ano= float(input("Digite o ano do seu nascimento")) print("{}/{}/{} dia do nascimento".format(dia,mes,ano))
python
#!/usr/bin/env python3 from constr import * import sys f = open(sys.argv[1]) s = f.read() c = parse(s) # print(f"BEFORE: {c}") d = dnf(c) # print(f"DNF: {d}") app = approx(c) act = actual(d) # print(f"APPROX: {app}") # print(f"ACTUAL: {act}") if app != act: sys.stderr.write(f"* FAILED: {sys.argv[1]} (got {app...
python
from requests import get, put import json def kelvin_to_mired(kelvin): return int(1000000 / kelvin) def secs_to_lsecs(secs): return secs * 10 class RestObject(object): def __init__(self, object_id='', bridge=None): self.object_id = object_id self.rest_group = 'unknown' self.bri...
python
import cv2 class PlateDisplay(): # create an annotated image with plate boxes, char boxes, and labels def labelImage(self, image, plateBoxes, charBoxes, charTexts): (H, W) = image.shape[:2] # loop over the plate text predictions for (plateBox, chBoxes, charText) in zip(plateBoxes, charBoxes, charText...
python
import os randomkey = "f0f18c4e0b04edaef0126c9720fd" if randomkey not in os.environ: print("Intentionally missing random unknown env-var") os.environ[randomkey] = "999" print(os.environ[randomkey]) print(os.environ["PATH"])
python
from schematics.types import BooleanType from openprocurement.tender.core.procedure.models.bid import ( PostBid as BasePostBid, PatchBid as BasePatchBid, Bid as BaseBid, ) from openprocurement.tender.core.models import ( ConfidentialDocumentModelType, validate_parameters_uniq, ) from openprocurement...
python
from django.http import HttpResponse def index(request): return HttpResponse("<h1>Hola, mundo.</h1>") def vista(request): return HttpResponse('<ul><li>URL: {}</li><li>Método: {}</li><li>Codificación: {}</li><li>Argumentos: {}</li></li></ul>'.format(request.path, request.method, request.encoding, request.GET.d...
python
from .base import KaffeError from .core import GraphBuilder, DataReshaper, NodeMapper from . import tensorflow
python
import pygame import time class Config: def __init__(self): self.quit = False self.pause = False self.dir_l = False self.dir_r = False self.dir_u = False self.dir_d = False self.mouse_pos = None self.mouse_pos_x = None self.mouse_pos_y = None self.bullets = [] self.mbd = { # Mouse Bu...
python
import json import requests from insightconnect_plugin_runtime.exceptions import PluginException import time from requests import Response class ZscalerAPI: def __init__(self, url: str, api_key: str, username: str, password: object, logger: object): self.url = url.rstrip("/") self.url = f"{self.ur...
python
from test_utils import run_query def test_quadbin_fromgeogpoint_no_srid(): """Computes quadbin for point with no SRID""" result = run_query( 'SELECT QUADBIN_FROMGEOGPOINT(ST_MAKEPOINT(40.4168, -3.7038), 4)' ) assert result[0][0] == 5209574053332910079 def test_quadbin_fromgeogpoint_4326_srid...
python
''' Entry point for gunicorn to serve REST API ''' import falcon import worker application = falcon.API() api = application worker = worker.Resource() api.add_route('/worker', worker)
python
from output.models.ms_data.particles.particles_da002_xsd.particles_da002 import ( A, Doc, Foo, ) __all__ = [ "A", "Doc", "Foo", ]
python
# -*- coding:utf-8 -*- import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='helloQueue') def callback(ch, method, properties, body): print(" [>>>]Receive %r" % body) channel.basic_consume(callback, queue='hello...
python
# Copyright 2018 (c) Herbert Shin https://github.com/initbar/sipd # # This source code is licensed under the MIT license. import logging import threading import time from collections import deque from src.rtp.server import SynchronousRTPRouter # from multiprocessing import Queue try: from Queue import Queue exc...
python
class Solution(object): def partitionLabels(self, S): """ :type S: str :rtype: List[int] """ dictionary = {} index = -1 counter = [] for char in S: if char not in dictionary: index += 1 dictionary[char] = i...
python
from functools import reduce from pathlib import Path import pytoml as toml def get_sphinx_configuration(project_dir): """Read the Sphinx configuration from ``pyproject.toml```.""" try: project = toml.loads((Path(project_dir) / 'pyproject.toml').read_text()) return reduce(lambda a, b: a[b], '...
python
import os import uuid from django.utils import timezone from django.db import models from django.utils.deconstruct import deconstructible # from main.models import User from api.models import path_and_rename_image_share from projects.models import Projects from django.utils.translation import gettext_lazy as _ @dec...
python
#!/usr/local/bin/python # encoding: utf-8 """ Documentation for crowdedText can be found here: http://crowdedText.readthedocs.org/en/stable Usage: crowdedText [-s <pathToSettingsFile>] -h, --help show this help message -s, --settings the settings file """ ################# GLOBAL IMPORTS...
python
import random class RandomList(list): def get_random_element(self): element = random.choice(self) self.remove(element) return element
python
for _ in range(int(input())): basic = int(input()) if basic < 1500: print(basic + (basic * 0.10) + (basic * 0.90)) elif basic >= basic: print(basic + 500 + (basic * 0.98))
python
# Copyright (c) 2019 PaddlePaddle Authors. 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 by appli...
python
import os import time from random import choice from typing import Optional from .paths import VERIFY_DIR # 声明验证码取字范围 chars = "ABDEFGHJKLMNPQRTUYabdefghjkmnpqrty123456789" EXPIRE_LIMIT_MINUTE = 5 def gen_code(length: int = 4) -> str: code = "" for _ in range(length): code += choice(chars) return...
python
import numpy as np from pydrake.all import (InverseKinematics, RotationMatrix, MultibodyPlant, PiecewiseQuaternionSlerp, PiecewisePolynomial) from pydrake.solvers import mathematicalprogram as mp def calc_iwa_trajectory_for_point_tracking(plant: MultibodyPlant, ...
python
#!/usr/bin/python3 from testlib import * if __name__ == '__main__': """ Checker with points Answer scored to the size of the intersection divided by the size of the union of the sets of options, checked by used and correct choices. More info: https://en.wikipedia.org/wiki/Jaccard_index This ...
python
import csv import io from urllib.request import urlopen from django.core.management.base import BaseCommand from web.foi_requests import models ESICS_URL = 'https://raw.githubusercontent.com/vitorbaptista/dataset-sics-brasil/master/data/sics-brasil.csv' # noqa: E501 class Command(BaseCommand): help = 'Load n...
python
from setuptools import setup # The text of the README file with open('README.md') as f: rm = f.read() # This call to setup() does all the work setup( name="boaf", version="0.0.1", description="Birds Of A Feather - Clustering in Python", long_description=rm, long_description_content_type="text...
python
from wallaby import * import constants as c import actions as a import servos as s def drive(lPer, rPer, dTime): motor(c.lMotor, lPer) motor(c.rMotor, rPer) msleep(dTime) ao() def freezeBoth(): # Careful when using this function in a loop, as we saw. That last msleep() causes some confusion. -LMB ...
python
# -*- coding: utf-8 -*- import ctypes EnumWindows = ctypes.windll.user32.EnumWindows EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) GetWindowText = ctypes.windll.user32.GetWindowTextW GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW IsWind...
python
""" Sample plugin for locating stock items / locations. Note: This plugin does not *actually* locate anything! """ import logging from plugin import InvenTreePlugin from plugin.mixins import LocateMixin logger = logging.getLogger('inventree') class SampleLocatePlugin(LocateMixin, InvenTreePlugin): """ A ...
python
from django.shortcuts import render from django.db.models import Q from api.v1.tools.paginator import customPagination # serializers imports from django.utils import timezone from datetime import datetime from django.db import DatabaseError, transaction from django.db import IntegrityError, transaction from django.con...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import time import unittest from mock import call from mock import patch from mock import MagicMock as Mock import pyrax from pyrax.manager import BaseManager from pyrax.clouddns import assure_domain from pyrax.clouddns import CloudDNSClient from pyrax.clou...
python
#!/usr/bin/env python # encoding: utf-8 """ ========================================================================================= Implementation of Sideways Information Passing graph (builds it from a given ruleset) """ import itertools # import os # import sys # import unittest from hashlib import md5 from FuXi...
python
"""Base configuration. Attributes: config_yaml (str): Base configuration as YAML code. config_dict (dict): Base configuration as Python dictionary. Here is the complete base configuration present as a string in the :obj:`config_yaml` attribute:: {} """ import textwrap import yaml config_yaml = """# Base ...
python
from django.contrib.contenttypes.models import ContentType from waldur_core.core.utils import DryRunCommand from waldur_mastermind.marketplace.models import Resource from waldur_mastermind.marketplace_openstack import utils from waldur_openstack.openstack.models import Tenant class Command(DryRunCommand): help =...
python
import sys import os node_block = [] file = open("profile_node.xml", 'r') line = file.readline() while line: node_block.append(line) line= file.readline() file.close() open("profile_output.xml", 'w+') header = '<rspec xmlns="http://www.geni.net/resources/rspec/3" xmlns:emulab="http://www.protogeni.net/resou...
python
from django import forms from django.utils.translation import gettext_lazy as _ from .models import CustomUser class SignUpForm(forms.ModelForm): password = forms.CharField( label=_('Password'), widget=forms.PasswordInput ) confirm_password = forms.CharField( label=_('Repeat pass...
python
import os import sys from sklearn.externals import joblib import json import numpy as np DIR_CS231n = '/Users/clement/Documents/MLearning/CS231/assignment2/' conf = {} # Model instance conf['input_dim'] = (3, 32, 32) conf['num_filters'] = [16, 32, 64, 128] conf['filter_size'] = 3 conf['hidden_dim'] = [500, 500] conf...
python
#!/usr/bin/env python3 # Copyright (c) 2019 Stephen Farrell, stephen.farrell@cs.tcd.ie # # 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 th...
python
#!/usr/bin/python import sys # a brittle XML parser, with the advantage that memory consumption is constant. class XMLParser: def __init__(self): self.tagstate="" self.currenttag="" def parse(self, buf): events=[] for c in buf: if c=="<": self.tagst...
python
# encoding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, HEADRequest, unified_strdate, url_basename, qualities, ) class CanalplusIE(InfoExtractor): IE_DESC = 'canalplus.fr, piwiplus.fr and d8.tv' _VALID_UR...
python
import tweepy import pandas as pd from flask import Flask, render_template, request from config import CONFIG CONSUMER_KEY = CONFIG["CONSUMER_KEY"] CONSUMER_SECRET = CONFIG["CONSUMER_SECRET"] ACCESS_TOKEN = CONFIG["ACCESS_TOKEN"] ACCESS_SECRET = CONFIG["ACCESS_SECRET"] auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUME...
python
from youtube_dl import YoutubeDL from youtubesearchpython import VideosSearch from colorama import Fore from multiprocessing import Process from pyfiglet import figlet_format import base64,json,random,os playlists = {} songs = {} pla_l = [] son_l = [] alldata = {} config = {} def search(content,limit): return_di...
python
"""***************** Cadastral Parcels ***************** Definition ========== Areas defined by cadastral registers or equivalent. Description =========== The INSPIRE Directive focuses on the geographical part of cadastral data. In the INSPIRE context, cadastral parcels will be mainly used as locators for geo-inform...
python
# Generated by Django 3.0.2 on 2020-01-09 14:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('club', '0029_question'), ] operations = [ migrations.AlterField( model_name='question', name='answer', f...
python
import asyncio import dataclasses import enum from typing import Dict, Optional, Set, Tuple from supriya.clocks import AsyncTempoClock, Moment from ..bases import Event from .bases import ApplicationObject from .parameters import ParameterGroup, ParameterObject class Transport(ApplicationObject): ### CLASS VAR...
python
import string import random import sympy as sp import math chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + "{}_" nr_per_page = 7 nr_st = len(chars) ** nr_per_page m = sp.nextprime(nr_st) def n2st(n, amount_of_digits = nr_per_page): if amount_of_digits == 0: return "" ch = c...
python
from django.contrib.auth.models import User from django.db.models import Q from django.test import TestCase from django.urls import reverse_lazy from model_mommy import mommy from gear.models import Weapon from player.models import Player class TestRoutes(TestCase): """Integration tests.""" def setUp(self):...
python
#!/bin/python from roomai.algorithms.crm import CRMPlayer from roomai.algorithms.crm import CRMAlgorithm
python
import os import hyperopt import pandas as pd from hyperopt import fmin, tpe, STATUS_OK, Trials from hyperopt import hp from hyperopt.pyll import scope from sklearn.linear_model import LinearRegression from xgboost import XGBRegressor from src.utils.memory_managment import save_object def trainXGBoost(train_x, trai...
python
import unittest import mock import requests_cache from ddt import ddt, data from nose.tools import assert_equals from nose.tools import assert_false from nose.tools import assert_is_not_none from nose.tools import assert_not_equals from nose.tools import assert_true import pub from app import logger from open_locatio...
python
#!/usr/bin/env python3 from ev3dev.ev3 import * import time m1 = LargeMotor('outC') m2 = LargeMotor('outD') arq = open("Dados.txt", "w") arq.write(" Leituras: \n\n") arq.close() def salvar(x): arq = open("Dados.txt", "a") s = "%d, %d\n" %(x[0], x[1]) arq.write(s) arq.close() m1.run_forever(speed_sp=...
python
""" This :mod: `features` module includes methods to generate, select new features for the dataset. """ from .feature_generation import GoldenFeatures from .feature_generation import FeatureInteraction from .feature_selection import TreeBasedSelection from .feature_selection import forward_step_selection from .helpers...
python
""" A collection of utility functions and classes. Originally, many (but not all) were from the Python Cookbook -- hence the name cbook. This module is safe to import from anywhere within matplotlib; it imports matplotlib only at runtime. """ import collections import collections.abc import contextlib import functoo...
python
#!/usr/bin/python import os import sys import traceback sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from django.core import mail from travelist import models try: task = models.BackgroundTask.objects.filter(frequency=models.BackgroundTaskFrequency.HOURLY).order_by('id')[0] except IndexError:...
python
"""Stores helper functions of the routes.py module Author: Matthias van den Belt """ def format_size(size: int) -> str: """Formats the size of a file into MB Input: - size: size of a file in bytes Output: - formatted string showing the size of the file in MB """ return "%3.1f MB"...
python
class Config(object): pass class ProdConfig(Config): pass class DevConfig(Config): DEBUG = True class DevConfig(Config): debug = True SQLALCHEMY_DATABASE_URI = "YOUR URI" #SQLALCHEMY_ECHO = True.
python
#%% import os import glob import numpy as np import scipy as sp import pandas as pd import re import git # Import libraries to parallelize processes from joblib import Parallel, delayed # Import matplotlib stuff for plotting import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib as mpl # Seabor...
python
import six from django.contrib.admin.options import InlineModelAdmin from baya import RolesNode as g from baya.admin.sites import NestedGroupsAdminSite from baya.permissions import requires from baya.permissions import ALLOW_ALL from baya.tests.admin import BlagEntryInline from baya.tests.admin import ProtectedPhotoBl...
python
#!/usr/bin/env python3 from pathlib import Path import cv2 import depthai as dai import numpy as np import time import glob import os from lxml import etree as ET from tqdm import tqdm def to_planar(arr: np.ndarray, shape: tuple) -> list: return [val for channel in cv2.resize(arr, shape).transpose(2, 0, 1) for y_...
python
#open images, subprocess, irfan view #Author: Todor import os print (os.curdir) f = open("termlist.txt", 'rt') list = f.readlines() f.close() print(list) import subprocess cwdNow = r"S:\Code\Python\\"; for n in list: subprocess.call([r"C:\Program Files\IrfanView\i_view32.exe", n.strip()], cwd=cwdNow) ...
python
from PIL import Image from scipy import fftpack import numpy from bitstream import BitStream from numpy import * import huffmanEncode import sys zigzagOrder = numpy.array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42, 49,56,57,50,43,36,29,22,...
python
import base64 code="CmltcG9ydCBweW1vbmdvCmltcG9ydCByYW5kb20KaW1wb3J0IHJlCmltcG9ydCBzdHJpbmcKaW1wb3J0IHN5cwppbXBvcnQgZ2V0b3B0CmltcG9ydCBwcHJpbnQKCiMgQ29weXJpZ2h0IDIwMTIKIyAxMGdlbiwgSW5jLgojIEF1dGhvcjogQW5kcmV3IEVybGljaHNvbiAgIGFqZUAxMGdlbi5jb20KIwojIElmIHlvdSBhcmUgYSBzdHVkZW50IGFuZCByZWFkaW5nIHRoaXMgY29kZSwgdHVybiBiYWNr...
python
def sc_kmeans(input_dict): """ The KMeans algorithm clusters data by trying to separate samples in n groups of equal variance, minimizing a criterion known as the inertia <inertia> or within-cluster sum-of-squares. This algorithm requires the number of clusters to be specified. It scales well to large ...
python
from nltk.corpus import movie_reviews from nltk.corpus import stopwords from nltk import FreqDist import string sw = set(stopwords.words('english')) punctuation = set(string.punctuation) def isStopWord(word): return word in sw or word in punctuation review_words = movie_reviews.words() filtered = [w.lower() fo...
python
# Dwolla Secret Stuff apiKey = '' apiSecret = '' token = '' pin = ''
python
# coding: utf-8 import yaml from os.path import dirname, join from unittest import TestCase, main from hamcrest import assert_that, equal_to from graph_matcher import Isomorphic from utils import cached_method from patterns import ( AbstractFactory as AbstractFactoryPattern, Decorator as DecoratorPattern, ...
python
from mock import mock from tests.base import BaseTestCase, MockRequests from mod_home.models import CCExtractorVersion, GeneralData from mod_test.models import Test, TestPlatform, TestType from mod_regression.models import RegressionTest from mod_customized.models import CustomizedTest from mod_ci.models import Blocked...
python
from rest_framework import serializers from todos.models import TodoList, Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ("id", "description", "deadline", "completion_date", "assignee",) class TaskCreateSerializer(serializers.ModelSerializer): class ...
python
import json import requests class CollecTorFile: def __init__(self, path, size, last_modified): self.path = path self.size = size self.last_modified = last_modified def __repr__(self): return (f"<CollecTorFile path={self.path} size={self.size} " f"last_modified...
python
import numpy as np from mapel.main.objects.Instance import Instance class Graph(Instance): def __init__(self, experiment_id, instance_id, alpha=1, model_id=None, edges=None): super().__init__(experiment_id, instance_id, alpha=alpha, model_id=model_id) self.edges = edges self.num_nodes...
python
# -*- coding: utf-8 -*- """ Dummy backend for unsupported platforms. """ # system imports import uuid from typing import Optional # local imports from .base import Notification, DesktopNotifierBase class DummyNotificationCenter(DesktopNotifierBase): """A dummy backend for unsupported platforms""" def __ini...
python
def search(nums: list, target: int) -> int: l = len(nums) middle = l // 2 if l == 1: if nums[0] == target: return 0 else: return -1 while l >= 1: if middle == 0: middle = 1 if nums[middle - 1] == target: return middle - 1 ...
python
def test(): # Test assert("True == False" in __solution__ or "True==False" in __solution__ or "True ==False" in __solution__ or "True== False" in __solution__ ), "اجابة خاطئة: في النقطة الاولى لم تقم بعملية المقارنة بشكل صحيح" assert("-2*10 != 20" in __solution__ or "-2*10!=20" in __solution__ o...
python
import math class Solution: def findComplement(self, num): """ :type num: int :rtype: int """ result = ~num if result < 0: result = result + int(math.pow(2, math.ceil(math.log2(-result)))) return result if __name__ == '__main__': sol = Solu...
python
from ..broker import Broker class DevicePropertyBroker(Broker): controller = "device_properties" def show(self, **kwargs): """Shows the details for the specified device property. **Inputs** | ``api version min:`` None | ``api version max:`` None | ...
python
#!/usr/bin/python3 import sys try: import weasyprint print("0") sys.exit(0) except ImportError: print("1") sys.exit(1)
python
# import the necessary packages import numpy as np import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", help = "path to the image") args = vars(ap.parse_args()) # load the image image = cv2.imread(args["image"]) # define the...
python
from protocol_utils import ndict __all__ = [ ndict, ]
python
''' randomize my own dataset for 2d training with respect to the same data of choy. ''' import os, sys import yaml nowpath = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(nowpath)) from common.dataset import ShapeNetV2, Sun2012pascal from common.geometry import View, Camera sys.path.append(...
python
# Adafruit IO HTTP API - Group Interactions # Documentation: https://io.adafruit.com/api/docs/#groups # adafruit_circuitpython_adafruitio with an esp32spi_socket import board import busio from digitalio import DigitalInOut import adafruit_esp32spi.adafruit_esp32spi_socket as socket from adafruit_esp32spi import adafrui...
python
from FreeTAKServer.model.SpecificCoT.SendRoute import SendRoute from FreeTAKServer.controllers.configuration.LoggingConstants import LoggingConstants from FreeTAKServer.controllers.CreateLoggerController import CreateLoggerController from FreeTAKServer.model.RestMessages.RestEnumerations import RestEnumerations import ...
python
"""empty message Revision ID: 99f650dc0924 Revises: b4c1dfa70233 Create Date: 2019-03-23 19:02:35.328537 """ # revision identifiers, used by Alembic. revision = '99f650dc0924' down_revision = 'b4c1dfa70233' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic ...
python
from arm.logicnode.arm_nodes import * class WorldVectorToLocalSpaceNode(ArmLogicTreeNode): """Transform world coordinates into object local coordinates. @seeNode Vector to Object Orientation @seeNode Get World Orientation @seeNode Vector From Transform """ bl_idname = 'LNWorldVectorToLocalSpac...
python
from django import forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from .models import Block, BlocklistSubmission from .utils import splitlines def _get_matching_guids_and_errors(guids): error_list = [] matching = list(Block.objects.filter(guid_...
python