text string | size int64 | token_count int64 |
|---|---|---|
"""All Modules"""
from .nft import NftModule as NftModuleV2
from .nft_v1 import *
from .nft_types import *
from .currency import *
from .market import *
from .pack import *
from .collection import CollectionModule
from .bundle import *
| 236 | 73 |
"""Tests of parsing GLNs."""
import pytest
from biip import ParseError
from biip.gln import Gln
from biip.gs1 import GS1Prefix
def test_parse() -> None:
gln = Gln.parse("1234567890128")
assert gln == Gln(
value="1234567890128",
prefix=GS1Prefix(value="123", usage="GS1 US"),
payload="123456789012",
check_digit=8,
)
def test_parse_strips_surrounding_whitespace() -> None:
gln = Gln.parse(" \t 1234567890128 \n ")
assert gln.value == "1234567890128"
def test_parse_value_with_invalid_length() -> None:
with pytest.raises(ParseError) as exc_info:
Gln.parse("123")
assert (
str(exc_info.value)
== "Failed to parse '123' as GLN: Expected 13 digits, got 3."
)
def test_parse_nonnumeric_value() -> None:
with pytest.raises(ParseError) as exc_info:
Gln.parse("123456789o128")
assert (
str(exc_info.value)
== "Failed to parse '123456789o128' as GLN: Expected a numerical value."
)
def test_parse_with_invalid_check_digit() -> None:
with pytest.raises(ParseError) as exc_info:
Gln.parse("1234567890127")
assert (
str(exc_info.value)
== "Invalid GLN check digit for '1234567890127': Expected 8, got 7."
)
def test_as_gln() -> None:
gln = Gln.parse(" \t 1234567890128 \n ")
assert gln.as_gln() == "1234567890128"
| 1,394 | 616 |
from django.shortcuts import render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.views.decorators.csrf import csrf_exempt
import json
from django.core import serializers
# Create your views here.
from django.http import HttpResponse
from django.http.response import JsonResponse
from web import models
def hello(request):
# return HttpResponse("hello world!")
context = {}
# 数据绑定
context['hello'] = 'Hello world!'
# 将绑定的数据传入前台
return render(request, 'hello.html', context)
@csrf_exempt
def index(request):
if request.method == 'POST':
pass
else:
xmu_news_list = models.News.objects.order_by('-release_time').all()
jwc_news_list = models.jwc_News.objects.order_by('-release_time').all()
xsc_news_list = models.xsc_News.objects.order_by('-release_time').all()
xmu_news_paginator = Paginator(xmu_news_list, 10) #show 20 news per page
jwc_news_paginator = Paginator(jwc_news_list, 10)
xsc_news_paginator = Paginator(xsc_news_list, 10)
# print("p.count:"+str(paginator.count))
# print("p.num_pages:"+str(paginator.num_pages))
# print("p.page_range:"+str(paginator.page_range))
source = request.GET.get("source")
page = request.GET.get('page')
xmu_news = xmu_news_paginator.get_page(1)
jwc_news = jwc_news_paginator.get_page(1)
xsc_news = xsc_news_paginator.get_page(1)
if(source == 'xmu'):
xmu_news = xmu_news_paginator.get_page(page)
elif(source == 'jwc'):
jwc_news = jwc_news_paginator.get_page(page)
elif (source == 'xsc'):
xsc_news = xsc_news_paginator.get_page(page)
# print("p.number:"+str(news.number))
return render(request, 'index.html', {'li':xmu_news, 'jwc_li':jwc_news, 'xsc_li': xsc_news})
@csrf_exempt
def get_page(request):
if request.method == 'GET':
source = request.GET.get('source')
num_page = request.GET.get('page')
all_news_list = models.News.objects.order_by('-release_time').all()
paginator = Paginator(all_news_list, 20) # show 20 news per page
# print("p.count:"+str(paginator.count))
# print("p.num_pages:"+str(paginator.num_pages))
# print("p.page_range:"+str(paginator.page_range))
# page = request.GET.get('page')
news = paginator.get_page(num_page)
return HttpResponse()
@csrf_exempt
def get_detail(request):
if request.method == 'POST':
id = request.POST.get("id")
source = request.POST.get("source")
print("source: {0}, news_id: {1}".format(source, str(id)))
# 此处用get会报错,用filter比较方便
if (source == 'xmu'):
item = models.News.objects.filter(id=id)
models.News.objects.filter(id=id).update(read_status=2)
elif (source == 'jwc'):
item = models.jwc_News.objects.filter(id=id)
models.jwc_News.objects.filter(id=id).update(read_status=2)
elif (source == 'xsc'):
item = models.xsc_News.objects.filter(id=id)
models.xsc_News.objects.filter(id=id).update(read_status=2)
item = item
# print(item)
# print(item[0])
#
json_item = serializers.serialize("json", item)
# print(json_item)
#
json_item = json.loads(json_item)
print("Data from get_detail(). 数据从get_detail()获取")
return JsonResponse(json_item[0]['fields'], safe=False)
| 3,523 | 1,259 |
import torch
from torch.utils.data import Dataset
class PCAMDataset(Dataset):
def __init__(self, root, phase, voxel_size, num_points):
super(PCAMDataset, self).__init__()
self.root = root
self.phase = phase
self.voxel_size = voxel_size
self.num_points = num_points
def __len__(self):
return len(self.files)
| 362 | 124 |
from selenipupser import element
query = element('[name=q]')
| 62 | 22 |
"""!
@brief Integration-test runner for tests of oscillatory and neural networks.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import unittest
from pyclustering.tests.suite_holder import suite_holder
# Generate images without having a window appear.
import matplotlib
matplotlib.use('Agg')
from pyclustering.nnet.tests.integration import it_hhn as nnet_hhn_integration_tests
from pyclustering.nnet.tests.integration import it_legion as nnet_legion_integration_tests
from pyclustering.nnet.tests.integration import it_pcnn as nnet_pcnn_integration_tests
from pyclustering.nnet.tests.integration import it_som as nnet_som_integration_tests
from pyclustering.nnet.tests.integration import it_sync as nnet_sync_integration_tests
from pyclustering.nnet.tests.integration import it_syncpr as nnet_syncpr_integration_tests
from pyclustering.nnet.tests.integration import it_syncsegm as nnet_syncsegm_integration_tests
class nnet_integration_tests(suite_holder):
def __init__(self):
super().__init__()
nnet_integration_tests.fill_suite(self.get_suite())
@staticmethod
def fill_suite(integration_nnet_suite):
integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_hhn_integration_tests))
integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_legion_integration_tests))
integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_pcnn_integration_tests))
integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_som_integration_tests))
integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_sync_integration_tests))
integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_syncpr_integration_tests))
integration_nnet_suite.addTests(unittest.TestLoader().loadTestsFromModule(nnet_syncsegm_integration_tests))
| 2,017 | 649 |
from records_mover.utils import beta, BetaWarning
import unittest
from unittest.mock import patch
@patch('records_mover.utils.warnings')
class TestBeta(unittest.TestCase):
def test_beta(self, mock_warnings):
@beta
def my_crazy_function():
return 123
out = my_crazy_function()
self.assertEqual(out, 123)
mock_warnings.warn.assert_called_with('Call to beta function my_crazy_function - '
'interface may change in the future!',
category=BetaWarning,
stacklevel=2)
| 658 | 176 |
import graphene
from graphql import GraphQLError
from graphql_relay import from_global_id
from django.contrib.auth import get_user_model
from creator.organizations.models import Organization
from creator.organizations.queries import OrganizationNode
from creator.events.models import Event
User = get_user_model()
class CreateOrganizationInput(graphene.InputObjectType):
""" Schema for creating a new study """
name = graphene.String(
required=True, description="The name of the organization"
)
description = graphene.String(
required=False, description="The description of the organization"
)
website = graphene.String(
required=False, description="The url of the organization's website"
)
email = graphene.String(
required=False, description="The email address of the organization"
)
image = graphene.String(
required=False,
description="The url of the display image for the organization",
)
class CreateOrganizationMutation(graphene.Mutation):
""" Mutation to create a new organization """
class Arguments:
""" Arguments for creating a new organization """
input = CreateOrganizationInput(
required=True, description="Attributes for the new organization"
)
organization = graphene.Field(OrganizationNode)
def mutate(self, info, input):
"""
Create a new organization and add the requesting user to it.
"""
user = info.context.user
if not user.has_perm("organizations.add_organization"):
raise GraphQLError("Not allowed")
organization = Organization(**input)
organization.clean_fields()
organization.save()
organization.members.add(user)
return CreateOrganizationMutation(organization=organization)
class UpdateOrganizationInput(graphene.InputObjectType):
""" Schema for updating an organization """
name = graphene.String(
required=True, description="The name of the organization"
)
description = graphene.String(
required=False, description="The description of the organization"
)
website = graphene.String(
required=False, description="The url of the organization's website"
)
email = graphene.String(
required=False, description="The email of the organization"
)
image = graphene.String(
required=False, description="A display image for the organization"
)
class UpdateOrganizationMutation(graphene.Mutation):
""" Mutation to update an organization """
class Arguments:
""" Arguments for creating a new organization """
id = graphene.ID(
required=True, description="The ID of the organization to update"
)
input = UpdateOrganizationInput(
required=True, description="Attributes for the new organization"
)
organization = graphene.Field(OrganizationNode)
def mutate(self, info, id, input):
"""
Update an organization.
"""
user = info.context.user
if not user.has_perm("organizations.change_organization"):
raise GraphQLError("Not allowed")
_, organization_id = from_global_id(id)
try:
organization = Organization.objects.get(pk=organization_id)
except Organization.DoesNotExist:
raise GraphQLError(
f"Organization {organization_id} does not exist"
)
for attr, value in input.items():
setattr(organization, attr, value)
organization.clean_fields()
organization.save()
return UpdateOrganizationMutation(organization=organization)
class AddMemberMutation(graphene.Mutation):
""" Mutation to add a member to an organization """
class Arguments:
""" Arguments to add a member to an organization """
organization = graphene.ID(
required=True, description="The ID of the organization to update"
)
user = graphene.ID(
required=True,
description="The ID of the user to add the to the organization",
)
organization = graphene.Field(OrganizationNode)
def mutate(self, info, organization, user):
"""
Add a member to an organization
"""
user_id = user
user = info.context.user
if not user.has_perm("organizations.change_organization"):
raise GraphQLError("Not allowed")
try:
_, organization_id = from_global_id(organization)
organization = Organization.objects.get(pk=organization_id)
except Organization.DoesNotExist:
raise GraphQLError(
f"Organization {organization_id} does not exist"
)
try:
_, user_id = from_global_id(user_id)
member = User.objects.get(id=int(user_id))
except (User.DoesNotExist, TypeError):
raise GraphQLError(f"User {user_id} does not exist.")
if not member.organizations.filter(pk=organization_id).exists():
organization.members.add(member)
message = (
f"{user.display_name} added {member.display_name} "
f"to organization {organization.name}"
)
event = Event(
organization=organization,
description=message,
event_type="MB_ADD",
)
else:
raise GraphQLError(
f"User {member.display_name} is already a member of "
f"organization {organization.name}."
)
organization.save()
if not user._state.adding:
event.user = user
event.save()
return AddMemberMutation(organization=organization)
class RemoveMemberMutation(graphene.Mutation):
""" Mutation to remove a member from an organization """
class Arguments:
""" Arguments to remove a member from an organization """
organization = graphene.ID(
required=True, description="The ID of the organization to update"
)
user = graphene.ID(
required=True,
description="The ID of the user to remove the to the organization",
)
organization = graphene.Field(OrganizationNode)
def mutate(self, info, organization, user):
"""
Remove a member from an organization
"""
user_id = user
user = info.context.user
if not user.has_perm("organizations.change_organization"):
raise GraphQLError("Not allowed")
try:
_, organization_id = from_global_id(organization)
organization = Organization.objects.get(pk=organization_id)
except Organization.DoesNotExist:
raise GraphQLError(
f"Organization {organization_id} does not exist"
)
try:
_, user_id = from_global_id(user_id)
member = User.objects.get(id=int(user_id))
except (User.DoesNotExist, TypeError):
raise GraphQLError(f"User {user_id} does not exist.")
if member.organizations.filter(pk=organization_id).exists():
organization.members.remove(member)
message = (
f"{user.display_name} removed {member.display_name} "
f"from organization {organization.name}"
)
event = Event(
organization=organization,
description=message,
event_type="MB_REM",
)
else:
raise GraphQLError(
f"User {member.display_name} is not a member of "
f"organization {organization.name}."
)
organization.save()
if not user._state.adding:
event.user = user
event.save()
return RemoveMemberMutation(organization=organization)
class Mutation:
create_organization = CreateOrganizationMutation.Field(
description="Create a new organization"
)
update_organization = UpdateOrganizationMutation.Field(
description="Update an organization"
)
add_member = AddMemberMutation.Field(
description="Add a member to an organization"
)
remove_member = RemoveMemberMutation.Field(
description="Remove a member from an organization"
)
| 8,444 | 2,155 |
"""
Mag Square
#always do Detective work nm what
UNDERSTAND
-nxn matrix of distinctive pos INT from 1 to n^2
-Sum of any row, column, or diagonal of length n is always equal to the same
number: "Mag" constant
-Given: 3x3 matrix s of integers in the inclusive range [1,9]
we can convert any digit a to any other digit b in the range [1,9]
at cost of |a-b|
-Given s, convert it into a magic square at minimal cost. Print this cost to a new line
-constraints: resulting magic square must contain distinct integers on inclusive range [1,9]
input= array (3x3 matrix) of s intes, in range[1,9] (convert any digit a to any digit b in range [1,9] at cost |a-b| abs value a-b)
output= minimal cost |a-b|, 1 integer
input:
5* 3 4
1 5 8*
6 4* 2
OUTPUT:
8* 3 4
1 5 9*
6 7* 2
input [[5,3,4],[1,5,8],[6,4,2]]
12 14 12
output [[8,3,4],[1,5,9],[6,7,2]]
15 15 15
if [i][i] + [i+1][i] + [i+2][i] //C
[i][i] + [i][i+1] + [i][i+2] && //R
[i][i] + [i+1][i+2] + [i+2][i+2] //D
oputput took 3 replacements at cost of |5-8| + |8-9| + |4-7| = 7
3 1 3
row, column, diagonal
row1 = s[0][0] [0][1] [0][2]
2 = s[1][0], [1][1], [2][2]
3 [2][0] [2][1] [2][2]
#i do it the way you want it done, when you want it done lord
#when i say i dont have money for something you ask me for, lack of faith
# do you help me to your own hurt? put me first
#my strength is in you your laws ty, consistently give all the time
input:
4 8* 2 |9-8| 1 // 14R, 15D, 14C
4* 5 7 |3-4| 1 // 16RM, 14MC
6* 1 6 |8-6| 2 // 13R, 13D, 15C
input [[4,8,2],[4,5,7],[6,1,6]]
14 16 13
output [[4,9,2],[3,5,7],[8,1,6]]
15 15 15
totla min =4
PLAN
EXECUTE
REFLECT
*/
/*
input:
5* 3 4
1 5 8*
6 4* 2
OUTPUT:
8* 3 4
1 5 9*
6 7* 2
input [[5,3,4],[1,5,8],[6,4,2]]
12 14 12
output [[8,3,4],[1,5,9],[6,7,2]]
15 15 15
if [i][i] + [i+1][i] + [i+2][i] //C
[i][i] + [i][i+1] + [i][i+2] && //R
[i][i] + [i+1][i+2] + [i+2][i+2] //D
*/
function Sq(arr) {
let i = 0;
let col1 = arr[i][i] + arr[i+1][i] + arr[i+2][i]
let col2 = arr[i][i+1] + arr[i+1][i+1] + arr[i+2][i+1]
let col3 = arr[i][i+2] + arr[i+1][i+2] + arr[i+2][i+2]
let row1 = arr[i][i] + arr[i][i+1] + arr[i][i+2]
let row2 = arr[i+1][i] + arr[i+1][i+1]+ arr[i+1][i+2]
let row3=arr[i+2][i] + arr[i+2][i+1]+ arr[i+2][i+2]
let dia = arr[i][i] + arr[i+1][i+1] + arr[i+2][i+2]
let dia2 = arr[i][i+2] + arr[i+1][i+1] + arr[i+2][i]
//console.log("col1:", col1, "col2:", col2, "col3:", col3+ "\n" + "row1:", row1, "row2:", row2, "row3:", row3 + "\n" + "diag:", dia, "diag2:", dia2)
console.log(col1 - col3)
}
Sq([[5,3,4],[1,5,8],[6,4,2]])
//
//1=? what makes the col/row/diag thats not the primary sums, equal to primary sum
//2== how to find the col/row/diag thats diff than main prim sum
// store all sums of each col/rows/diags in list
// find most freq sum
// if col/row/diag != mostfreqsum, then store in tracker array diffSum=[]
//diffSum 14, 14
// mostfreqsum - each tracker:colX/rowX/diagX
// store ^ all difference in track variable
col1: 12 col2: 12 col3: 14
row1: 12 row2: 14 row3: 12
diag: 12 diag2: 15
"""
import statistics
def Sq(arr):
i=0
store=[]
dict1 = {}
keys = ["col1", "col2", "col3", "row1", "row2", "row3", "diag", "diag2"]
col1 = arr[i][i] + arr[i+1][i] + arr[i+2][i]
col2 = arr[i][i+1] + arr[i+1][i+1] + arr[i+2][i+1]
col3 = arr[i][i+2] + arr[i+1][i+2] + arr[i+2][i+2]
row1 = arr[i][i] + arr[i][i+1] + arr[i][i+2]
row2 = arr[i+1][i] + arr[i+1][i+1]+ arr[i+1][i+2]
row3=arr[i+2][i] + arr[i+2][i+1]+ arr[i+2][i+2]
dia = arr[i][i] + arr[i+1][i+1] + arr[i+2][i+2]
dia2 = arr[i][i+2] + arr[i+1][i+1] + arr[i+2][i]
print("col1:", col1, "col2:", col2, "col3:", col3, "\n" + "row1:", row1, "row2:", row2, "row3:", row3, "\n" + "diag:", dia, "diag2:", dia2)
store.append([col1, col2, col3, row1,row2, row3, dia, dia2])
for i in keys:
for x in store[0]:
dict1[i] = x
t= dict1["col1"]
#print("dict", t)
counter =0
num = store[0][0]
track={}
for key,value in dict1.items():
if value not in track:
track[value]=0
else:
track[value]+=1
mostfreq= max(dict1, key=lambda k:dict1[k])
maxtra= max(track, key=track.get)
print("h",mostfreq,maxtra)
# if store.count(num) < 3, get average from list
# FIND mean of store
"""
mything= sorted(store[0])
print(mything)
mymean= statistics.median(mything)
rmean= round(mymean)
print(mymean, rmean)
myl= [rmean-x for x in store[0] if x != rmean]
mysum= abs(sum(myl))
print(myl, mysum)
"""
#return mysum
Sq([[4,9,2],[3,5,7],[8,1,5]]) #1 | 4,835 | 2,417 |
import re
def parse_genome_id(genome):
genome_id = re.search("GCA_[0-9]*.[0-9]", genome).group()
return genome_id
def rm_duplicates(seq):
"""Remove duplicate strings during renaming
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def clean_up_name(name):
rm_words = re.compile(r"((?<=_)(sp|sub|substr|subsp|str|strain)(?=_))")
name = re.sub(" +", "_", name)
name = rm_words.sub("_", name)
name = re.sub("_+", "_", name)
name = re.sub("[\W]+", "_", name)
name = rm_duplicates(filter(None, name.split("_")))
name = "_".join(name)
return name
def rename_genome(genome, assembly_summary):
"""Rename FASTAs based on info in the assembly summary
"""
genome_id = parse_genome_id(genome)
infraspecific_name = assembly_summary.at[genome_id, "infraspecific_name"]
organism_name = assembly_summary.at[genome_id, "organism_name"]
if type(infraspecific_name) == float:
infraspecific_name = ""
isolate = assembly_summary.at[genome_id, "isolate"]
if type(isolate) == float:
isolate = ""
assembly_level = assembly_summary.at[genome_id, "assembly_level"]
name = "_".join(
[genome_id, organism_name, infraspecific_name, isolate, assembly_level]
)
name = clean_up_name(name) + ".fna.gz"
return name
| 1,371 | 507 |
"""Sample Fetch script from DuneAnalytics"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from src.duneapi.api import DuneAPI
from src.duneapi.types import Network, QueryParameter, DuneQuery
from src.duneapi.util import open_query
@dataclass
class Record:
"""Arbitrary record with a few different data types"""
string: str
integer: int
decimal: float
time: datetime
@classmethod
def from_dict(cls, obj: dict[str, str]) -> Record:
"""Constructs Record from Dune Data as string dict"""
return cls(
string=obj["block_hash"],
integer=int(obj["number"]),
decimal=float(obj["tx_fees"]),
# Dune timestamps are UTC!
time=datetime.strptime(obj["time"], "%Y-%m-%dT%H:%M:%S+00:00"),
)
def fetch_records(dune: DuneAPI) -> list[Record]:
"""Initiates and executes Dune query, returning results as Python Objects"""
sample_query = DuneQuery.from_environment(
raw_sql=open_query("./example/query.sql"),
name="Sample Query",
network=Network.MAINNET,
parameters=[
QueryParameter.number_type("IntParam", 10),
QueryParameter.date_type("DateParam", datetime(2022, 3, 10, 12, 30, 30)),
QueryParameter.text_type("TextParam", "aba"),
],
)
results = dune.fetch(sample_query)
return [Record.from_dict(row) for row in results]
if __name__ == "__main__":
records = fetch_records(DuneAPI.new_from_environment())
print("First result:", records[0])
| 1,598 | 498 |
from typing import Optional
from bottle import request, route, run
import uvicorn
from arnold import config
from arnold.output.speaker import Speaker
API_CONFIG = config.API
# Module class instances, rather than init everytime
speaker = Speaker()
# TODO (qoda): Make this super generic
@route('/health')
def health():
return {'success': True}
@route('/output/speaker', method='POST')
def speak():
phrase = request.json.get('phrase', 'No input')
speaker.say(phrase)
return {'success': True}
def runserver(host: Optional[str] = None, port: Optional[int] = None):
host = host or API_CONFIG['host']
port = port or API_CONFIG['port']
run(host=host, port=port)
| 696 | 220 |
#!/usr/bin/env python
"""
Process a sample tweet fetched using streaming API.
Usage:
$ ipython -i FILENAME
>>> data = main()
>>> data.keys() # Then explore the `data` object in ipython.
['contributors', 'truncated', 'text', 'is_quote_status',
'in_reply_to_status_id', 'id', 'favorite_count', 'source',
'retweeted', 'coordinates', 'timestamp_ms', 'entities',
'in_reply_to_screen_name', 'id_str', 'retweet_count',
'in_reply_to_user_id', 'favorited', 'retweeted_status',
'user', 'geo', 'in_reply_to_user_id_str', 'lang',
'created_at', 'filter_level', 'in_reply_to_status_id_str',
'place']
>>> data['text']
'RT @twice_ph: [TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4\u2026 '
>>> print(data['text'])
RT @twice_ph: [TWICETAGRAM] 170701
오랜만에 #두부한모
저희는 잘 있어요 우리 #ONCE 는?
#ONCE 가 보고싶다
뒤엔 상큼주의 쯔위가 찍어준 사진ㅋㅋㅋ
#TWICE #트와이스…
If copying from the command line into Python, characters need to be escaped
or the prefix `r` must be applied to the string.
Alternatives which I couldn't get to work fully:
https://stackoverflow.com/questions/22394235/invalid-control-character-with-python-json-loads
https://stackoverflow.com/questions/7262828/python-how-to-convert-string-literal-to-raw-string-literal
"""
import json
def main():
# No line breaks, straight from API
x = r'{"created_at":"Sat Jul 01 08:43:29 +0000 2017","id":881070742980313088,"id_str":"881070742980313088","text":"RT @twice_ph: [TWICETAGRAM] 170701\n\\uc624\\ub79c\\ub9cc\\uc5d0 #\\ub450\\ubd80\\ud55c\\ubaa8 \n\\uc800\\ud76c\\ub294 \\uc798 \\uc788\\uc5b4\\uc694 \\uc6b0\\ub9ac #ONCE \\ub294?\n#ONCE \\uac00 \\ubcf4\\uace0\\uc2f6\\ub2e4\n\n\\ub4a4\\uc5d4 \\uc0c1\\ud07c\\uc8fc\\uc758 \\ucbd4\\uc704\\uac00 \\ucc0d\\uc5b4\\uc900 \\uc0ac\\uc9c4\\u314b\\u314b\\u314b \n#TWICE #\\ud2b8\\uc640\\uc774\\uc2a4\\u2026 ","source":"\\u003ca href="http:\\/\\/twitter.com\\/download\\/android" rel="nofollow"\\u003eTwitter for Android\\u003c\\/a\\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":3722867834,"id_str":"3722867834","name":"Amazing Twice","screen_name":"metdew1","location":"\\ub300\\ud55c\\ubbfc\\uad6d \\uc11c\\uc6b8","url":null,"description":"I\'m a korean. My age too old. \nBut really really like TWICE. World ONCE\nfamily i alway thanks your support to\nTWICE. Wish good luck alway with U.","protected":false,"verified":false,"followers_count":977,"friends_count":1204,"listed_count":59,"favourites_count":114142,"statuses_count":100351,"created_at":"Tue Sep 29 06:19:21 +0000 2015","utc_offset":-25200,"time_zone":"Pacific Time (US & Canada)","geo_enabled":false,"lang":"ko","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http:\\/\\/abs.twimg.com\\/images\\/themes\\/theme1\\/bg.png","profile_background_image_url_https":"https:\\/\\/abs.twimg.com\\/images\\/themes\\/theme1\\/bg.png","profile_background_tile":false,"profile_link_color":"9266CC","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http:\\/\\/pbs.twimg.com\\/profile_images\\/858888732539207681\\/89mbzS98_normal.jpg","profile_image_url_https":"https:\\/\\/pbs.twimg.com\\/profile_images\\/858888732539207681\\/89mbzS98_normal.jpg","profile_banner_url":"https:\\/\\/pbs.twimg.com\\/profile_banners\\/3722867834\\/1494858108","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Sat Jul 01 06:10:54 +0000 2017","id":881032343829463040,"id_str":"881032343829463040","text":"[TWICETAGRAM] 170701\n\\uc624\\ub79c\\ub9cc\\uc5d0 #\\ub450\\ubd80\\ud55c\\ubaa8 \n\\uc800\\ud76c\\ub294 \\uc798 \\uc788\\uc5b4\\uc694 \\uc6b0\\ub9ac #ONCE \\ub294?\n#ONCE \\uac00 \\ubcf4\\uace0\\uc2f6\\ub2e4\n\n\\ub4a4\\uc5d4 \\uc0c1\\ud07c\\uc8fc\\uc758 \\ucbd4\\uc704\\uac00 \\ucc0d\\uc5b4\\uc900 \\uc0ac\\uc9c4\\u314b\\u314b\\u314b \n#TWICE #\\ud2b8\\uc640\\uc774\\uc2a4\\u2026 https:\\/\\/t.co\\/9CPNYQiwcq","display_text_range":[0,140],"source":"\\u003ca href="http:\\/\\/twitter.com\\/download\\/android" rel="nofollow"\\u003eTwitter for Android\\u003c\\/a\\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":3779372892,"id_str":"3779372892","name":"TWICE PHILIPPINES \\u2728","screen_name":"twice_ph","location":"Philippines \\ud544\\ub9ac\\ud540","url":null,"description":"Philippine-based support group for TWICE. Officially affiliated with JYPNPH and PKCI http:\\/\\/facebook.com\\/groups\\/TWICEPH\\u2026 ... http:\\/\\/facebook.com\\/TWICEPH\\/","protected":false,"verified":false,"followers_count":7071,"friends_count":224,"listed_count":72,"favourites_count":523,"statuses_count":12448,"created_at":"Sun Oct 04 09:05:12 +0000 2015","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"FFFFFF","profile_background_image_url":"http:\\/\\/pbs.twimg.com\\/profile_background_images\\/722977345053712385\\/naASDMjX.jpg","profile_background_image_url_https":"https:\\/\\/pbs.twimg.com\\/profile_background_images\\/722977345053712385\\/naASDMjX.jpg","profile_background_tile":true,"profile_link_color":"FF3485","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":true,"profile_image_url":"http:\\/\\/pbs.twimg.com\\/profile_images\\/863338740629905408\\/tO_19lHj_normal.jpg","profile_image_url_https":"https:\\/\\/pbs.twimg.com\\/profile_images\\/863338740629905408\\/tO_19lHj_normal.jpg","profile_banner_url":"https:\\/\\/pbs.twimg.com\\/profile_banners\\/3779372892\\/1494670969","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"[TWICETAGRAM] 170701\n\\uc624\\ub79c\\ub9cc\\uc5d0 #\\ub450\\ubd80\\ud55c\\ubaa8 \n\\uc800\\ud76c\\ub294 \\uc798 \\uc788\\uc5b4\\uc694 \\uc6b0\\ub9ac #ONCE \\ub294?\n#ONCE \\uac00 \\ubcf4\\uace0\\uc2f6\\ub2e4\n\n\\ub4a4\\uc5d4 \\uc0c1\\ud07c\\uc8fc\\uc758 \\ucbd4\\uc704\\uac00 \\ucc0d\\uc5b4\\uc900 \\uc0ac\\uc9c4\\u314b\\u314b\\u314b \n#TWICE #\\ud2b8\\uc640\\uc774\\uc2a4 \nhttps:\\/\\/t.co\\/NHPtfkruR4 https:\\/\\/t.co\\/WRv9qP8Mk2","display_text_range":[0,129],"entities":{"hashtags":[{"text":"\\ub450\\ubd80\\ud55c\\ubaa8","indices":[26,31]},{"text":"ONCE","indices":[46,51]},{"text":"ONCE","indices":[55,60]},{"text":"TWICE","indices":[92,98]},{"text":"\\ud2b8\\uc640\\uc774\\uc2a4","indices":[99,104]}],"urls":[{"url":"https:\\/\\/t.co\\/NHPtfkruR4","expanded_url":"https:\\/\\/www.instagram.com\\/p\\/BV_i2J_gx1w\\/","display_url":"instagram.com\\/p\\/BV_i2J_gx1w\\/","indices":[106,129]}],"user_mentions":[],"symbols":[],"media":[{"id":881032307179573248,"id_str":"881032307179573248","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":680,"h":680,"resize":"fit"},"medium":{"w":960,"h":960,"resize":"fit"},"large":{"w":960,"h":960,"resize":"fit"}}},{"id":881032328272683008,"id_str":"881032328272683008","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"large":{"w":734,"h":734,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":734,"h":734,"resize":"fit"},"small":{"w":680,"h":680,"resize":"fit"}}}]},"extended_entities":{"media":[{"id":881032307179573248,"id_str":"881032307179573248","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoONykU0AAT3d6.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":680,"h":680,"resize":"fit"},"medium":{"w":960,"h":960,"resize":"fit"},"large":{"w":960,"h":960,"resize":"fit"}}},{"id":881032328272683008,"id_str":"881032328272683008","indices":[130,153],"media_url":"http:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","media_url_https":"https:\\/\\/pbs.twimg.com\\/media\\/DDoOPBJUIAAlDMF.jpg","url":"https:\\/\\/t.co\\/WRv9qP8Mk2","display_url":"pic.twitter.com\\/WRv9qP8Mk2","expanded_url":"https:\\/\\/twitter.com\\/twice_ph\\/status\\/881032343829463040\\/photo\\/1","type":"photo","sizes":{"large":{"w":734,"h":734,"resize":"fit"},"thumb":{"w":150,"h":150,"resize":"crop"},"medium":{"w":734,"h":734,"resize":"fit"},"small":{"w":680,"h":680,"resize":"fit"}}}]}},"retweet_count":1,"favorite_count":40,"entities":{"hashtags":[{"text":"\\ub450\\ubd80\\ud55c\\ubaa8","indices":[26,31]},{"text":"ONCE","indices":[46,51]},{"text":"ONCE","indices":[55,60]},{"text":"TWICE","indices":[92,98]},{"text":"\\ud2b8\\uc640\\uc774\\uc2a4","indices":[99,104]}],"urls":[{"url":"https:\\/\\/t.co\\/9CPNYQiwcq","expanded_url":"https:\\/\\/twitter.com\\/i\\/web\\/status\\/881032343829463040","display_url":"twitter.com\\/i\\/web\\/status\\/8\\u2026","indices":[106,129]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"ko"},"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"\\ub450\\ubd80\\ud55c\\ubaa8","indices":[40,45]},{"text":"ONCE","indices":[60,65]},{"text":"ONCE","indices":[69,74]},{"text":"TWICE","indices":[106,112]},{"text":"\\ud2b8\\uc640\\uc774\\uc2a4","indices":[113,118]}],"urls":[{"url":"","expanded_url":null,"indices":[120,120]}],"user_mentions":[{"screen_name":"twice_ph","name":"TWICE PHILIPPINES \\u2728","id":3779372892,"id_str":"3779372892","indices":[3,12]}],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"ko","timestamp_ms":"1498898609286"}'
# With link breaks from formatting - see http://jsonviewer.stack.hu/
y = r"""{
"id": 881070742980313088,
"created_at": "Sat Jul 01 08:43:29 +0000 2017",
"id_str": "881070742980313088",
"text": "RT @twice_ph: [TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4\u2026 ",
"source": "\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e",
"truncated": false,
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 3722867834,
"id_str": "3722867834",
"name": "Amazing Twice",
"screen_name": "metdew1",
"location": "\ub300\ud55c\ubbfc\uad6d \uc11c\uc6b8",
"url": null,
"description": "I'm a korean. My age too old. \nBut really really like TWICE. World ONCE\nfamily i alway thanks your support to\nTWICE. Wish good luck alway with U.",
"protected": false,
"verified": false,
"followers_count": 977,
"friends_count": 1204,
"listed_count": 59,
"favourites_count": 114142,
"statuses_count": 100351,
"created_at": "Tue Sep 29 06:19:21 +0000 2015",
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": false,
"lang": "ko",
"contributors_enabled": false,
"is_translator": false,
"profile_background_color": "000000",
"profile_background_image_url": "http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png",
"profile_background_image_url_https": "https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png",
"profile_background_tile": false,
"profile_link_color": "9266CC",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": false,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/858888732539207681\/89mbzS98_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/858888732539207681\/89mbzS98_normal.jpg",
"profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/3722867834\/1494858108",
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": null,
"notifications": null
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": {
"created_at": "Sat Jul 01 06:10:54 +0000 2017",
"id": 881032343829463040,
"id_str": "881032343829463040",
"text": "[TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4\u2026 https:\/\/t.co\/9CPNYQiwcq",
"display_text_range": [
0,
140
],
"source": "\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e",
"truncated": true,
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 3779372892,
"id_str": "3779372892",
"name": "TWICE PHILIPPINES \u2728",
"screen_name": "twice_ph",
"location": "Philippines \ud544\ub9ac\ud540",
"url": null,
"description": "Philippine-based support group for TWICE. Officially affiliated with JYPNPH and PKCI http:\/\/facebook.com\/groups\/TWICEPH\u2026 ... http:\/\/facebook.com\/TWICEPH\/",
"protected": false,
"verified": false,
"followers_count": 7071,
"friends_count": 224,
"listed_count": 72,
"favourites_count": 523,
"statuses_count": 12448,
"created_at": "Sun Oct 04 09:05:12 +0000 2015",
"utc_offset": null,
"time_zone": null,
"geo_enabled": false,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"profile_background_color": "FFFFFF",
"profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/722977345053712385\/naASDMjX.jpg",
"profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/722977345053712385\/naASDMjX.jpg",
"profile_background_tile": true,
"profile_link_color": "FF3485",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": true,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/863338740629905408\/tO_19lHj_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/863338740629905408\/tO_19lHj_normal.jpg",
"profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/3779372892\/1494670969",
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": null,
"notifications": null
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"extended_tweet": {
"full_text": "[TWICETAGRAM] 170701\n\uc624\ub79c\ub9cc\uc5d0 #\ub450\ubd80\ud55c\ubaa8 \n\uc800\ud76c\ub294 \uc798 \uc788\uc5b4\uc694 \uc6b0\ub9ac #ONCE \ub294?\n#ONCE \uac00 \ubcf4\uace0\uc2f6\ub2e4\n\n\ub4a4\uc5d4 \uc0c1\ud07c\uc8fc\uc758 \ucbd4\uc704\uac00 \ucc0d\uc5b4\uc900 \uc0ac\uc9c4\u314b\u314b\u314b \n#TWICE #\ud2b8\uc640\uc774\uc2a4 \nhttps:\/\/t.co\/NHPtfkruR4 https:\/\/t.co\/WRv9qP8Mk2",
"display_text_range": [
0,
129
],
"entities": {
"hashtags": [
{
"text": "\ub450\ubd80\ud55c\ubaa8",
"indices": [
26,
31
]
},
{
"text": "ONCE",
"indices": [
46,
51
]
},
{
"text": "ONCE",
"indices": [
55,
60
]
},
{
"text": "TWICE",
"indices": [
92,
98
]
},
{
"text": "\ud2b8\uc640\uc774\uc2a4",
"indices": [
99,
104
]
}
],
"urls": [
{
"url": "https:\/\/t.co\/NHPtfkruR4",
"expanded_url": "https:\/\/www.instagram.com\/p\/BV_i2J_gx1w\/",
"display_url": "instagram.com\/p\/BV_i2J_gx1w\/",
"indices": [
106,
129
]
}
],
"user_mentions": [
],
"symbols": [
],
"media": [
{
"id": 881032307179573248,
"id_str": "881032307179573248",
"indices": [
130,
153
],
"media_url": "http:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg",
"media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg",
"url": "https:\/\/t.co\/WRv9qP8Mk2",
"display_url": "pic.twitter.com\/WRv9qP8Mk2",
"expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 960,
"h": 960,
"resize": "fit"
},
"large": {
"w": 960,
"h": 960,
"resize": "fit"
}
}
},
{
"id": 881032328272683008,
"id_str": "881032328272683008",
"indices": [
130,
153
],
"media_url": "http:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg",
"media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg",
"url": "https:\/\/t.co\/WRv9qP8Mk2",
"display_url": "pic.twitter.com\/WRv9qP8Mk2",
"expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1",
"type": "photo",
"sizes": {
"large": {
"w": 734,
"h": 734,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"medium": {
"w": 734,
"h": 734,
"resize": "fit"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
}
}
}
]
},
"extended_entities": {
"media": [
{
"id": 881032307179573248,
"id_str": "881032307179573248",
"indices": [
130,
153
],
"media_url": "http:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg",
"media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoONykU0AAT3d6.jpg",
"url": "https:\/\/t.co\/WRv9qP8Mk2",
"display_url": "pic.twitter.com\/WRv9qP8Mk2",
"expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 960,
"h": 960,
"resize": "fit"
},
"large": {
"w": 960,
"h": 960,
"resize": "fit"
}
}
},
{
"id": 881032328272683008,
"id_str": "881032328272683008",
"indices": [
130,
153
],
"media_url": "http:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg",
"media_url_https": "https:\/\/pbs.twimg.com\/media\/DDoOPBJUIAAlDMF.jpg",
"url": "https:\/\/t.co\/WRv9qP8Mk2",
"display_url": "pic.twitter.com\/WRv9qP8Mk2",
"expanded_url": "https:\/\/twitter.com\/twice_ph\/status\/881032343829463040\/photo\/1",
"type": "photo",
"sizes": {
"large": {
"w": 734,
"h": 734,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"medium": {
"w": 734,
"h": 734,
"resize": "fit"
},
"small": {
"w": 680,
"h": 680,
"resize": "fit"
}
}
}
]
}
},
"retweet_count": 1,
"favorite_count": 40,
"entities": {
"hashtags": [
{
"text": "\ub450\ubd80\ud55c\ubaa8",
"indices": [
26,
31
]
},
{
"text": "ONCE",
"indices": [
46,
51
]
},
{
"text": "ONCE",
"indices": [
55,
60
]
},
{
"text": "TWICE",
"indices": [
92,
98
]
},
{
"text": "\ud2b8\uc640\uc774\uc2a4",
"indices": [
99,
104
]
}
],
"urls": [
{
"url": "https:\/\/t.co\/9CPNYQiwcq",
"expanded_url": "https:\/\/twitter.com\/i\/web\/status\/881032343829463040",
"display_url": "twitter.com\/i\/web\/status\/8\u2026",
"indices": [
106,
129
]
}
],
"user_mentions": [
],
"symbols": [
]
},
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"filter_level": "low",
"lang": "ko"
},
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"entities": {
"hashtags": [
{
"text": "\ub450\ubd80\ud55c\ubaa8",
"indices": [
40,
45
]
},
{
"text": "ONCE",
"indices": [
60,
65
]
},
{
"text": "ONCE",
"indices": [
69,
74
]
},
{
"text": "TWICE",
"indices": [
106,
112
]
},
{
"text": "\ud2b8\uc640\uc774\uc2a4",
"indices": [
113,
118
]
}
],
"urls": [
{
"url": "",
"expanded_url": null,
"indices": [
120,
120
]
}
],
"user_mentions": [
{
"screen_name": "twice_ph",
"name": "TWICE PHILIPPINES \u2728",
"id": 3779372892,
"id_str": "3779372892",
"indices": [
3,
12
]
}
],
"symbols": [
]
},
"favorited": false,
"retweeted": false,
"filter_level": "low",
"lang": "ko",
"timestamp_ms": "1498898609286"
}
"""
# Works on y, but not x
data = json.loads(y)
print((json.dumps(data, indent=4)))
return data
if __name__ == "__main__":
main()
| 27,430 | 11,751 |
i = 0
vsota = 0
while i < 1000:
if i % 3 == 0:
vsota += i
elif i % 5 == 0:
vsota += i
i += 1
print(vsota)
| 144 | 78 |
"""Regex pattern constants"""
import re
URL_PATTERN = re.compile(r'(http[s]?://(?:[a-zA-Z]|[0-9]|[$-;?-_=@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)')
NUMBER_PATTERN = re.compile(r'(\.\d+|\d[,\d]*(?:\.\d+)?)')
UNIT_PATTERN_TUPLE = [
# [length]
('inch', re.compile(r' *("|inch|inches|ins?)(?!\w)')),
('foot', re.compile(r' *(\'|foot|feet|ft)(?!\w)')),
('mile', re.compile(r' *(miles?|mi)(?!\w)')),
('yard', re.compile(r' *(yards?|yr?d)(?!\w)')),
('centimeter', re.compile(r' *(centimeters?|centimetres?|cms?)(?!\w)')),
('meter', re.compile(r' *(meters?|metres?|mt?r?s?)(?!\w)')),
('kilometer', re.compile(r' *(kilometers?|kilometres?|kms?)(?!\w)')),
# [length ** 3]
('gallon', re.compile(r' *(gallons?|gal)(?!\w)')),
('liter', re.compile(r' *(liters?|litres?|lt?r?s?)(?!\w)')),
# [mass]
('ounce', re.compile(r' *(ounces?|oz)(?!\w)')),
('pound', re.compile(r' *(pounds?|lbs?)(?!\w)')),
('gram', re.compile(r' *(grams?|gr?m?s?)(?!\w)')),
('kilogram', re.compile(r' *(kilograms?|kgs?)(?!\w)')),
# [temperature]
('celsius', re.compile(r' *(°|degrees?|degs?)? *([Cc]|[CcSs]el[sc]ius)(?!\w)')),
('fahrenheit', re.compile(r' *(°|degrees?|degs?)? *([Ff]|[Ff]h?ah?rh?enheit)(?!\w)')),
('kelvin', re.compile(r' *(°|degrees?|degs?)? *([Kk]|[Kk]el[vb]in)(?!\w)')),
('rankine', re.compile(r' *(°|degrees?|degs?)? *([Rr]|[Rr]ankine?)(?!\w)')),
]
SPECIAL_UNIT_PATTERN_TUPLE = ('footinches', re.compile(r'(\.\d+|\d[,\d]*(?:\.\d+)?)\'(\.\d+|\d[,\d]*(?:\.\d+)?)"?'))
DICE_PATTERN = re.compile(r'(?:([+-])\ ?)?(?:(\d*)?d(\d+)(?:\ ?(k[hl]\d+))?|(\d+))')
CHANNEL_URL_PATTERN = re.compile(r'https:\/\/(?:ptb\.)?discord(?:app)?\.com\/channels(?:\/\d{18}){3}')
DISCORD_EMOJI_PATTERN = re.compile(r'(<:[\w_]{1,32}:\d{18}>)')
HTML_TAG_OR_ENTITY_PATTERN = re.compile(r'<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
| 1,886 | 1,024 |
from apis.resources.users import user
| 38 | 11 |
import os
import textwrap
from pprint import pprint
#import cloudmesh.pi.cluster
from cloudmesh.pi.cluster.Installer import Installer
from cloudmesh.pi.cluster.Installer import Script
from cloudmesh.common.Host import Host
from cloudmesh.common.Printer import Printer
from cloudmesh.common.console import Console
from cloudmesh.common.parameter import Parameter
from cloudmesh.common.util import banner
# see also: https://github.com/cloudmesh/cloudmesh-pi-cluster/tree/master/cloudmesh/cluster/spark
class Spark(Installer):
def __init__(self, master=None, workers=None):
"""
:param master:
:param workers:
"""
self.master = master
self.workers = workers
self.java_version = "11"
self.version = "2.4.5"
self.user = "pi"
self.script = Script()
self.service = "spark"
#self.port = 6443
self.hostname = os.uname()[1]
self.scripts()
def scripts(self):
self.script["spark.check"] = """
hostname
uname -a
"""
self.script["spark.test"] = """
sh $SPARK_HOME/sbin/start-all.sh
$SPARK_HOME/bin/run-example SparkPi 4 10
sh $SPARK_HOME/sbin/stop-all.sh
"""
self.script["spark.setup.master"] = """
sudo apt-get update
sudo apt-get install default-jdk
sudo apt-get install scala
cd ~
sudo wget http://mirror.metrocast.net/apache/spark/spark-{version}/spark-{version}-bin-hadoop2.7.tgz -O sparkout.tgz
sudo tar -xzf sparkout.tgz
sudo cp ~/.bashrc ~/.bashrc-backup
sudo chmod 777 ~/spark-{version}-bin-hadoop2.7/conf
sudo cp /home/pi/spark-{version}-bin-hadoop2.7/conf/slaves.template /home/pi/spark-{version}-bin-hadoop2.7/conf/slaves
"""
self.script["spark.setup.worker"] = """
sudo apt-get update
sudo apt-get install default-jdk
sudo apt-get install scala
cd ~
sudo tar -xzf sparkout.tgz
sudo cp ~/.bashrc ~/.bashrc-backup
"""
self.script["copy.spark.to.worker"] = """
scp /bin/spark-setup-worker.sh {user}@self.workers:
scp ~/sparkout.tgz {user}@{worker}:
ssh {user}@{worker} sh ~/spark-setup-worker.sh
"""
self.script["spark.uninstall2.4.5"] = """
sudo apt-get remove openjdk-11-jre
sudo apt-get remove scala
cd ~
sudo rm -rf spark-2.4.5-bin-hadoop2.7
sudo rm -f sparkout.tgz
sudo cp ~/.bashrc-backup ~/.bashrc
"""
self.script["update.bashrc"] = """
# ################################################
# SPARK BEGIN
#
#JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-armhf/
#SCALA_HOME
export SCALA_HOME=/usr/share/scala
export PATH=$PATH:$SCALA_HOME/bin
#SPARK_HOME
export SPARK_HOME=~/spark-2.4.5-bin-hadoop2.7
export PATH=$PATH:$SPARK_HOME/bin
#
# SPARK END
# ################################################
"""
script["spark.setup.worker.sh"] = """
#!/usr/bin/env bash
sudo apt-get update
sudo apt-get install default-jdk
sudo apt-get install scala
cd ~
sudo tar -xzf sparkout.tgz
cat ~/.bashrc ~/spark-bashrc.txt > ~/temp-bashrc
sudo cp ~/.bashrc ~/.bashrc-backup
sudo cp ~/temp-bashrc ~/.bashrc
sudo rm ~/temp-bashrc
sudo chmod 777 ~/spark-{version}-bin-hadoop2.7/
"""
return self.script
def execute(self, arguments):
"""
pi spark setup --master=MASTER --workers=WORKER
pi spark start --master=MASTER --workers=WORKER
pi spark stop --master=MASTER --workers=WORKER
pi spark test --master=MASTER --workers=WORKER
pi spark check --master=MASTER --worker=WORKER
:param arguments:
:return:
"""
self.dryrun = arguments["--dryrun"]
master = Parameter.expand(arguments.master)
workers = Parameter.expand(arguments.workers)
if len(master) > 1:
Console.error("You can have only one master")
master = master[0]
# find master and worker from arguments
if arguments.master:
hosts.append(arguments.master)
if arguments.workers:
hosts = Parameter.expand(arguments.workers)
if workers is not None and master is None:
Console.error("You need to specify at least one master or worker")
return ""
# do the action on master amd workers found
if arguments.setup:
self.setup(master, workers)
elif arguments.start:
self.start(master, workers)
elif arguments.stop:
self.stop(master, workers)
elif arguments.test:
self.test(master, workers)
elif arguments.check:
self.check(master, workers)
def run(self,
script=None,
hosts=None,
username=None,
processors=4,
verbose=False):
results = []
if type(hosts) != list:
hosts = Parameter.expand(hosts)
for command in script.splitlines():
if hosts == None:
hosts = ""
if command.startswith("#") or command.strip() == "":
print(command)
elif len(hosts) == 1 and hosts[0] == self.hostname:
command = command.format(user=self.user, version=self.version, host=host, hostname=hostname)
print(hosts, "->", command)
if self.dryrun:
Console.info(f"Executiong command >{command}<")
else:
os.system(command)
elif len(hosts) == 1 and hosts[0] != self.hostname:
host = hosts[0]
command = command.format(user=self.user, version=self.version, host=host, hostname=hostname)
print(hosts, "->", command, hosts)
if self.dryrun:
Console.info(f"Executiong command >{command}<")
else:
os.system(f"ssh {host} {command}")
else:
#@staticmethod
#def run(hosts=None,
# command=None,
# execute=None,
# processors=3,
# shell=False,
# **kwargs):
if self.dryrun:
executor = print
else:
executor = os.system
result = Host.ssh(hosts=hosts,
command=command,
username=username,
key="~/.ssh/id_rsa.pub",
processors=processors,
executor=executor,
version=self.version, # this was your bug, you did not pass this along
user=self.user # this was your bug, you did not pass this along
)
results.append(result)
if verbose:
pprint(results)
for result in results:
print(Printer.write(result, order=['host', 'stdout']))
return results
def run_script(self, name=None, hosts=None):
banner(name)
print("self.script = ")
pprint(self.script)
results = self.run(script=self.script[name], hosts=hosts, verbose=True)
def setup(self, master= None, workers=None):
#
# SETUP THE MASTER
#
banner(f"Setup Master: {master}")
self.run_script(name="sparksetup", hosts=self.master)
#os.system("sudo apt-get update")
if "SPARK_HOME" not in os.environ:
Console.error("$SPARK_HOME is not set")
return ""
spark_home = os.environ("SPARK_HOME")
filename = "{spark_home}/conf/slaves"
banner(f"Updating file: {filename}")
filename =
if not self.dryrun:
Installer.add_script(fileanme, "{user}@{worker}")
banner(f"Setup bashrc: {master}")
print(Spark.update_bashrc())
#
# SETUP THE WORKER. STEP 1: GET THE FILES FROM MASTER
#
banner(f"Get files from {master}")
print(self.create_spark_setup_worker())
self.run_script(name="copy.spark.to.worker", hosts=self.workers)
#
# SETUP THE WORKER. SETUP BASHRC ON WORKERS
#
print(self.create_spark_bashrc_txt())
print(self.update_slaves())
# Print created cluster
#self.view()
# raise NotImplementedError
def start(self, master=None, hosts=None):
# Setup Spark on the master
if master is not None:
if type(master) != list:
master = Parameter.expand(master)
banner(f"Start Master: {master[0]}")
os.system("sh $SPARK_HOME/sbin/start-all.sh")
# command = Installer.oneline(f"""
# sh $SPARK_HOME/sbin/start-all.sh -
# """)
# raise NotImplementedError
def test(self, master=None, hosts=None):
banner(f"Listing $SPARK_HOME from {master[0]}")
os.system("ls $SPARK_HOME")
os.system("$SPARK_HOME/bin/run-example SparkPi 4 10")
def stop(self, master=None, hosts=None):
# Stop Spark on master and all workers
if master is not None:
if type(master) != list:
master = Parameter.expand(master)
#
# TODO - bug I should be able to run this even if I am not on master
#
banner(f"Start Master: {master[0]}")
os.system("sh $SPARK_HOME/sbin/stop-all.sh")
#command = Installer.oneline(f"""
# sh $SPARK_HOME/sbin/stop-all.sh -
# """)
# raise NotImplementedError
def update_bashrc(self):
"""
Add the following lines to the bottom of the ~/.bashrc file
:return:
"""
banner("Updating ~/.bashrc file")
script = textwrap.dedent(self.script["update.bashrc"])
Installer.add_script("~/.bashrc", script)
def create_spark_setup_worker(self):
"""
This file is created on master and copied to worker, then executed on worker from master
:return:
"""
banner("Creating the spark.setup.worker.sh file")
script = self.script["spark.setup.worker.sh"]
if self.dryrun:
print (script)
else:
f = open("/home/pi/spark-setup-worker.sh", "w+")
#f.write("test")
f.close()
Installer.add_script("~/spark-setup-worker.sh", script)
def create_spark_bashrc_txt(self):
"""
Test to add at bottome of ~/.bashrc. File is created on master and copied to worker
:return:
"""
script = self.script["update.bashrc"]
if self.dryrun:
print (script)
else:
f = open("/home/pi/spark-bashrc.txt", "w+")
#f.write("test")
f.close()
Installer.add_script("~/spark-bashrc.txt", script)
| 11,873 | 3,399 |
#!/usr/bin/py
# -*- coding: utf-8 -*-
"""
@author: Cem Rıfkı Aydın
Constant parameters to be leveraged across the program.
"""
import os
COMMAND = "cross_validate"
# Dimension size of embeddings
EMBEDDING_SIZE = 100
#Language can be either "turkish" or "english"
LANG = "turkish"
DATASET_PATH = os.path.join("input", "Sentiment_dataset_turk.csv") # Sentiment_dataset_tr.csv; test_tr.csv
CONTEXT_WINDOW_SIZE = 5
""" Word embedding type can be one of the following:
corpus_svd: SVD - U vector
lexical_svd: Dictionary, SVD - U vector
supervised: Four context delta idf score vector
ensemble: Combination of the above three embeddings
clustering: Clustering vector
word2vec: word2vec
"""
EMBEDDING_TYPE = "ensemble"
# Number of cross-validation
CV_NUMBER = 10
# Concatenation of the maximum, average, and minimum delta-idf polarity scores with the average document vector.
USE_3_REV_POL_SCORES = True
# The below variables are used only if the command "train_and_test_separately" is chosen.
TRAINING_FILE_PATH = os.path.join("input", "Turkish_twitter_train.csv")
TEST_FILE_PATH = os.path.join("input", "Turkish_twitter_test.csv")
# The below file name for the model trained could also be used given that
# model parameters (e.g. embedding size and type) are the same.
MODEL_FILE_NAME = 'finalized_model.sav'
| 1,321 | 467 |
from mathy_core import ExpressionParser
expression = ExpressionParser().parse("4 + 2")
assert expression.evaluate() == 6
| 122 | 34 |
# Setup file for package overlapping_namespace
from setuptools import setup
setup(name="overlapping_namespace",
version="0.1.0",
install_requires=["wheel", "quark==0.0.1", "org_example_foo==0.1.0"],
setup_requires=["wheel"],
py_modules=[],
packages=['org', 'org.example', 'org.example.bar', 'overlapping_namespace_md'])
| 352 | 125 |
"""
This file contains function to separate out video and audio using ffmpeg.
It consists of two functions to split and merge video and audio
using ffmpeg.
"""
import os
from torpido.config.constants import (CACHE_DIR, CACHE_NAME,
IN_AUDIO_FILE, OUT_AUDIO_FILE,
OUT_VIDEO_FILE, THUMBNAIL_FILE)
from torpido.exceptions import AudioStreamMissingException, FFmpegProcessException
from torpido.ffpbar import Progress
from torpido.tools.ffmpeg import split, merge, thumbnail
from torpido.tools.logger import Log
class FFMPEG:
"""
FFMPEG helper function to make use of the subprocess module to run command
to trim and split video files. The std out logs are parsed to generate a progress
bar to show the progress of the command that is being executed.
Attributes
----------
__input_file_name : str
input video file name
__input_file_path : str
input video file name
__output_video_file_name : str
output video file name
__input_audio_file_name : str
original splatted audio file name
__output_audio_file_name : str
de-noised audio file name
__output_file_path : str
same as the input file path
__intro : str
name of the intro video file
__outro : str
name of the outro video file
__extension : str
name of the extension of the input file
__progress_bar : tqdm
object of tqdm to display a progress bar
"""
def __init__(self):
self.__input_file_name = self.__input_file_path = self.__output_video_file_name = self.__input_audio_file_name = None
self.__output_audio_file_name = self.__output_file_path = self.__thumbnail_file = self.__intro = None
self.__outro = self.__extension = self.__progress_bar = None
def set_intro_video(self, intro):
""" Sets the intro video file """
self.__intro = intro
def set_outro_video(self, outro):
""" Sets the outro video file """
self.__outro = outro
def get_input_file_name_path(self):
""" Returns file name that was used for processing """
if self.__input_file_name is not None:
return os.path.join(self.__input_file_path, self.__input_file_name)
def get_output_file_name_path(self):
""" Returns output file name generated from input file name """
if self.__output_video_file_name is not None:
return os.path.join(self.__output_file_path, self.__output_video_file_name)
def get_input_audio_file_name_path(self):
""" Returns name and path of the input audio file that is split from the input video file """
if self.__input_audio_file_name is not None:
return os.path.join(self.__output_file_path, self.__input_audio_file_name)
def get_output_audio_file_name_path(self):
""" Returns the output audio file name and path that is de-noised """
if self.__output_audio_file_name is not None:
return os.path.join(self.__output_file_path, self.__output_audio_file_name)
def split_video_audio(self, input_file):
"""
Function to split the input video file into audio file using FFmpeg. Progress bar is
updated as the command is run
Note : No new video file is created, only audio file is created
Parameters
----------
input_file : str
input video file
Returns
-------
bool
returns True if success else Error
"""
if os.path.isfile(input_file) is False:
Log.e("File does not exists")
return False
# storing all the references
self.__input_file_path = os.path.dirname(input_file)
self.__output_file_path = self.__input_file_path
self.__input_file_name = os.path.basename(input_file)
# get the base name without the extension
base_name, self.__extension = os.path.splitext(self.__input_file_name)
self.__output_video_file_name = "".join([base_name, OUT_VIDEO_FILE, self.__extension])
self.__input_audio_file_name = base_name + IN_AUDIO_FILE
self.__output_audio_file_name = base_name + OUT_AUDIO_FILE
self.__thumbnail_file = base_name + THUMBNAIL_FILE
# call ffmpeg tool to do the splitting
try:
Log.i("Splitting the video file.")
self.__progress_bar = Progress()
for log in split(input_file,
os.path.join(self.__output_file_path, self.__input_audio_file_name)):
self.__progress_bar.display(log)
if not os.path.isfile(os.path.join(self.__output_file_path, self.__input_audio_file_name)):
raise AudioStreamMissingException
self.__progress_bar.complete()
print("----------------------------------------------------------")
return True
# no audio in the video
except AudioStreamMissingException:
Log.e(AudioStreamMissingException.cause)
self.__progress_bar.clear()
return False
def merge_video_audio(self, timestamps):
"""
Function to merge the processed files using FFmpeg. The timestamps are used the trim
the original video file and the audio stream is replaced with the de-noised audio
file created by `Auditory`
Parameters
----------
timestamps : list
list of start and end timestamps
Returns
-------
bool
True id success else error is raised
"""
if self.__input_file_name is None or self.__output_audio_file_name is None:
Log.e("Files not found for merging")
return False
# call ffmpeg tool to merge the files
try:
self.__progress_bar = Progress()
Log.i("Writing the output video file.")
for log in merge(os.path.join(self.__output_file_path, self.__input_file_name),
os.path.join(self.__output_file_path, self.__output_audio_file_name),
os.path.join(self.__output_file_path, self.__output_video_file_name),
timestamps,
intro=self.__intro,
outro=self.__outro):
self.__progress_bar.display(log)
if not os.path.isfile(os.path.join(self.__output_file_path, self.__output_video_file_name)):
raise FFmpegProcessException
self.__progress_bar.complete()
print("----------------------------------------------------------")
return True
except FFmpegProcessException:
Log.e(FFmpegProcessException.cause)
self.__progress_bar.clear()
return False
def gen_thumbnail(self, time):
"""
Generates the thumbnail from the timestamps. Since, the timestamps contains the best
of all the video, so picking a random int (sec) from a video and saving the frame
as the thumbnail, Later some kind of peak rank from the input data can be picked.
Notes
-----
To pick the max rank we can use the sum rank and easily get the max value and use
it to generate the thumbnail for the video.
"""
# call ffmpeg tool to merge the files
try:
self.__progress_bar = Progress()
Log.i("Writing the output video file.")
for log in thumbnail(os.path.join(self.__output_file_path, self.__input_file_name),
os.path.join(self.__output_file_path, self.__thumbnail_file),
time):
self.__progress_bar.display(log)
if not os.path.isfile(os.path.join(self.__output_file_path, self.__thumbnail_file)):
raise FFmpegProcessException
self.__progress_bar.complete()
print("----------------------------------------------------------")
return True
except FFmpegProcessException:
Log.e(FFmpegProcessException.cause)
self.__progress_bar.clear()
return False
def clean_up(self):
"""
Deletes extra files created while processing, deletes the ranking files
cache, etc.
"""
# processing is not yet started for something went wrong
if self.__input_file_name is not None:
# original audio split from the video file
if os.path.isfile(os.path.join(self.__output_file_path, self.__input_audio_file_name)):
os.unlink(os.path.join(self.__output_file_path, self.__input_audio_file_name))
# de-noised audio file output of Auditory
if os.path.isfile(os.path.join(self.__output_file_path, self.__output_audio_file_name)):
os.unlink(os.path.join(self.__output_file_path, self.__output_audio_file_name))
# cache storage file
if os.path.isfile(os.path.join(CACHE_DIR, CACHE_NAME)):
os.unlink(os.path.join(CACHE_DIR, CACHE_NAME))
del self.__progress_bar
Log.d("Clean up completed.")
| 9,285 | 2,494 |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.callback import CallbackBase
from ansible.utils.color import stringc
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'human'
def __init__(self):
super(CallbackModule, self).__init__()
self.line = ""
def v2_runner_on_failed(self, result, ignore_errors=False):
if 'exception' in result._result:
if self._display.verbosity < 3:
# extract just the actual error message from the exception text
error = result._result['exception'].strip().split('\n')[-1]
msg = "An exception occurred during task execution. To see the full traceback, use -vvv. The error was: %s" % error
else:
msg = "An exception occurred during task execution. The full traceback is:\n" + result._result['exception']
self._display.display("> " + msg, color='red')
# finally, remove the exception from the result so it's not shown every time
del result._result['exception']
self._display.display(" > %s" % (self._dump_results(result._result)), color='red')
def v2_runner_on_ok(self, result):
if result._result.get('changed', True):
self._display.display(self.line, color='green')
self._handle_warnings(result._result)
self.line = ""
def v2_runner_on_skipped(self, result):
self.line = ""
def v2_runner_on_unreachable(self, result):
self._display.display(self.line + "> UNREACHABLE!", color='yellow')
def v2_playbook_on_play_start(self, play):
self._display.display(self.line + " RUNNING PLAYBOOK...", color='yellow')
def v2_playbook_on_task_start(self, task, is_conditional):
self.line = " " + task.get_name().strip()
def v2_on_file_diff(self, result):
if 'diff' in result._result:
self._display.display(" " + self._get_diff(result._result['diff']))
| 2,108 | 634 |
import planetClass
def createSomePlanets():
aPlanet=planetClass.Planet("Zorks",2000,30000,100000,5)
bPlanet=planetClass.Planet("Zapps",1000,20000,200000,17)
print(aPlanet.getName() + " has a radius of " + str(aPlanet.getRadius()))
planetList=[aPlanet,bPlanet]
for planet in planetList:
print(planet.getName() + " has a mass of " + str(planet.getMass()))
for planet in planetList:
print(planet.getName() + " has " + str(planet.getMoons()) + " moons.")
print(bPlanet.getName() + " has a circumference of " + str(bPlanet.getCircumference()))
createSomePlanets()
| 605 | 234 |
import json
f = open('Thesis_v3/scripts/fastapi/web/static/data/escuelas.json')
data = json.load(f)
| 101 | 42 |
import numpy as np
from systemrl.agents.q_learning import QLearning
import matplotlib.pyplot as plt
from helper import decaying_epsilon, evaluate_interventions
from tqdm import tqdm
#This is not converging
def mincost(env, human_policy, min_performance, agent, num_episodes=1000, max_steps=1000):
print("mincost")
episode_returns_ = []
for episodes in tqdm(range(num_episodes)):
env.reset()
state = env.state
is_end = False
returns = 0
returns_ = 0
count = 0
epsilon = decaying_epsilon(episodes, num_episodes)
while not is_end and count < max_steps:
count += 1
if np.random.random() < epsilon:
action = np.random.randint(agent.num_actions)
else:
action = agent.get_action(state)
next_state, reward, is_end = env.step(action)
returns += reward
if is_end == True or count >= max_steps:
if returns < min_performance:
reward_ = -100
elif action == human_policy[state]:
reward_ = 0
else:
reward_ = -1
agent.train(state, action, reward_, next_state)
state = next_state
returns_ += reward_
episode_returns_.append(returns_)
return evaluate_interventions(env, human_policy, agent)
| 1,410 | 406 |
"""All algorithms used by geoio-server"""
import math
import functools
import geojson
def angle(point_1, point_2):
"""calculates the angle between two points in radians"""
return math.atan2(point_2[1] - point_1[1], point_2[0] - point_1[0])
def convex_hull(collection):
"""Calculates the convex hull of an geojson feature collection."""
features_or_geometries = []
if collection["type"] == "GeometryCollection":
features_or_geometries = collection["geometries"]
elif collection["type"] == "FeatureCollection":
features_or_geometries = collection["features"]
if features_or_geometries is None or len(features_or_geometries) == 0:
raise Exception("No features or geometries where found")
features_or_geometries_mapper = lambda feature_or_geometry: list(geojson.utils.coords(feature_or_geometry))
coordinates_reducer = lambda a, b: a + b
coordinates_list = list(map(features_or_geometries_mapper, features_or_geometries))
points = list(functools.reduce(coordinates_reducer, coordinates_list))
if len(points) < 3:
raise Exception("Can not calculate convex hull of less then 3 input points.")
points = list(set(points))
points = sorted(points, key=lambda point: (point[1], point[0]))
point0 = points.pop(0)
points = list(map(lambda point: (point[0], point[1], angle(point0, point)), points))
points = list(sorted(points, key=lambda point: point[2]))
points.insert(0, point0)
hull = [points[0], (points[1][0], points[1][1])]
i = 2
points_count = len(points)
while i < points_count:
stack_length = len(hull)
point_1 = hull[stack_length-1]
point_2 = hull[stack_length-2]
point_i = points[i]
discrimnante = (point_2[0] - point_1[0]) * (point_i[1] - point_1[1]) - (point_i[0] - point_1[0]) * (point_2[1] - point_1[1])
if discrimnante < 0 or stack_length == 2:
hull.append((point_i[0], point_i[1]))
i = i+1
else:
hull.pop()
return geojson.Polygon(hull)
| 2,076 | 708 |
import numpy as np
def modified_bisection(f, a, b, eps=5e-6):
"""
Function that finds a root using modified Bisection method for a given function f(x).
On each iteration instead of the middle of the interval, a random number is chosen as the next guess for the
root.
The function finds the root of f(x) with a predefined absolute accuracy epsilon.
The function excepts an interval [a,b] in which is known that the function f has a root.
If the function f has multiple roots in this interval then Bisection method converges randomly to one of them.
If in the interval [a,b] f(x) doesn't change sign (Bolzano theorem can not be applied) the function returns nan
as root and -1 as the number of iterations.Also the function checks if either a or b is a root of f(x), if both
are then the function returns the value of a.
Parameters
----------
f : callable
The function to find a root of.
a : float
The start of the initial interval in which the function will find the root of f(x).
b : float
The end of the initial interval in which the function will find the root of f(x).
eps : float
The target accuracy.
The iteration stops when the length of the current interval divided by 2 to the power of n+1 is below eps.
Default value is 5e-6.
Returns
-------
root : float
The estimated value for the root.
iterations_num : int
The number of iterations.
"""
# check if Bolzano theorem can not be applied or a is larger than b
if f(a) * f(b) > 0 or a > b:
return np.nan, -1
elif f(a) == 0: # check if a is root of f
return a, 0
elif f(b) == 0: # or b is root of f
return b, 0
# Modified Bisection algorithm
iterations_num = 0
while abs(b - a) >= eps:
current_root = np.random.uniform(a, b) # each iteration root approximation is a random number from a uniform
# distribution
if f(a) * f(current_root) < 0: # find out where Bolzano theorem still can be applied and update the interval
# [a,b]
b = current_root
else:
a = current_root
iterations_num += 1
current_root = np.random.uniform(a, b)
return current_root, iterations_num
| 2,495 | 667 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from collections import OrderedDict
from django.core.urlresolvers import reverse
from django.db import models
from django.db.transaction import atomic
from django.template.defaultfilters import slugify
from django.utils.crypto import get_random_string
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.html import format_html, format_html_join
from django.utils.translation import ugettext_lazy as _
from dynamic_forms.actions import action_registry
from dynamic_forms.conf import settings
from dynamic_forms.fields import TextMultiSelectField
from dynamic_forms.formfields import formfield_registry
@python_2_unicode_compatible
class FormModel(models.Model):
name = models.CharField(_('Name'), max_length=50, unique=True)
submit_url = models.CharField(_('Submit URL'), max_length=100, unique=True,
help_text=_('The full URL path to the form. It should start '
'and end with a forward slash (<code>/</code>).'))
success_url = models.CharField(_('Success URL'), max_length=100,
help_text=_('The full URL path where the user will be '
'redirected after successfully sending the form. It should start '
'and end with a forward slash (<code>/</code>). If empty, the '
'success URL is generated by appending <code>done/</code> to the '
'“Submit URL”.'), blank=True, default='')
actions = TextMultiSelectField(_('Actions'), default='',
choices=action_registry.get_as_choices())
form_template = models.CharField(_('Form template path'), max_length=100,
default='dynamic_forms/form.html',
choices=settings.DYNAMIC_FORMS_FORM_TEMPLATES)
success_template = models.CharField(_('Success template path'),
max_length=100, default='dynamic_forms/form_success.html',
choices=settings.DYNAMIC_FORMS_SUCCESS_TEMPLATES)
allow_display = models.BooleanField(_('Allow display'), default=False,
help_text=_('Allow a user to view the input at a later time. This '
'requires the “Store in database” action to be active. The sender '
'will be given a unique URL to recall the data.'))
recipient_email = models.EmailField(_('Recipient email'), blank=True,
null=True, help_text=_('Email address to send form data.'))
class Meta:
ordering = ['name']
verbose_name = _('Dynamic form')
verbose_name_plural = _('Dynamic forms')
def __str__(self):
return self.name
def get_fields_as_dict(self):
"""
Returns an ``OrderedDict`` (``SortedDict`` when ``OrderedDict is not
available) with all fields associated with this form where their name
is the key and their label is the value.
"""
return OrderedDict(self.fields.values_list('name', 'label').all())
def save(self, *args, **kwargs):
"""
Makes sure that the ``submit_url`` and -- if defined the
``success_url`` -- end with a forward slash (``'/'``).
"""
if not self.submit_url.endswith('/'):
self.submit_url = self.submit_url + '/'
if self.success_url:
if not self.success_url.endswith('/'):
self.success_url = self.success_url + '/'
else:
self.success_url = self.submit_url + 'done/'
super(FormModel, self).save(*args, **kwargs)
@python_2_unicode_compatible
class FormFieldModel(models.Model):
parent_form = models.ForeignKey(FormModel, on_delete=models.CASCADE,
related_name='fields')
field_type = models.CharField(_('Type'), max_length=255,
choices=formfield_registry.get_as_choices())
label = models.CharField(_('Label'), max_length=255)
name = models.SlugField(_('Name'), max_length=50, blank=True)
_options = models.TextField(_('Options'), blank=True, null=True)
position = models.SmallIntegerField(_('Position'), blank=True, default=0)
class Meta:
ordering = ['parent_form', 'position']
unique_together = ("parent_form", "name",)
verbose_name = _('Form field')
verbose_name_plural = _('Form fields')
def __str__(self):
return _('Field “%(field_name)s” in form “%(form_name)s”') % {
'field_name': self.label,
'form_name': self.parent_form.name,
}
def generate_form_field(self, form):
field_type_cls = formfield_registry.get(self.field_type)
field = field_type_cls(**self.get_form_field_kwargs())
field.contribute_to_form(form)
return field
def get_form_field_kwargs(self):
kwargs = self.options
kwargs.update({
'name': self.name,
'label': self.label,
})
return kwargs
@property
def options(self):
"""Options passed to the form field during construction."""
if not hasattr(self, '_options_cached'):
self._options_cached = {}
if self._options:
try:
self._options_cached = json.loads(self._options)
except ValueError:
pass
return self._options_cached
@options.setter
def options(self, opts):
if hasattr(self, '_options_cached'):
del self._options_cached
self._options = json.dumps(opts)
def save(self, *args, **kwargs):
if not self.name:
self.name = slugify(self.label)
given_options = self.options
field_type_cls = formfield_registry.get(self.field_type)
invalid = set(self.options.keys()) - set(field_type_cls._meta.keys())
if invalid:
for key in invalid:
del given_options[key]
self.options = given_options
super(FormFieldModel, self).save(*args, **kwargs)
@python_2_unicode_compatible
class FormModelData(models.Model):
form = models.ForeignKey(FormModel, on_delete=models.SET_NULL,
related_name='data', null=True)
value = models.TextField(_('Form data'), blank=True, default='')
submitted = models.DateTimeField(_('Submitted on'), auto_now_add=True)
display_key = models.CharField(_('Display key'), max_length=24, null=True,
blank=True, db_index=True, default=None, unique=True,
help_text=_('A unique identifier that is used to allow users to view '
'their sent data. Unique over all stored data sets.'))
class Meta:
verbose_name = _('Form data')
verbose_name_plural = _('Form data')
def __str__(self):
return _('Form: “%(form)s” on %(date)s') % {
'form': self.form,
'date': self.submitted,
}
def save(self, *args, **kwargs):
with atomic():
if self.form.allow_display and not self.display_key:
dk = get_random_string(24)
while FormModelData.objects.filter(display_key=dk).exists():
dk = get_random_string(24)
self.display_key = dk
super(FormModelData, self).save(*args, **kwargs)
@property
def json_value(self):
return OrderedDict(sorted(json.loads(self.value).items()))
def pretty_value(self):
try:
value = format_html_join('',
'<dt>{0}</dt><dd>{1}</dd>',
(
(force_text(k), force_text(v))
for k, v in self.json_value.items()
)
)
return format_html('<dl>{0}</dl>', value)
except ValueError:
return self.value
pretty_value.allow_tags = True
@property
def show_url(self):
"""
If the form this data set belongs to has
:attr:`~FormModel.allow_display` ``== True``, return the permanent URL.
If displaying is not allowed, return an empty string.
"""
if self.form.allow_display:
return reverse('dynamic_forms:data-set-detail',
kwargs={'display_key': self.display_key})
return ''
@property
def show_url_link(self):
"""
Similar to :attr:`show_url` but wraps the display key in an `<a>`-tag
linking to the permanent URL.
"""
if self.form.allow_display:
return format_html('<a href="{0}">{1}</a>', self.show_url, self.display_key)
return ''
| 8,454 | 2,458 |
#!/usr/bin/python
import sys
import os
import string
#print sys.argv
frontend = "../cparser/parser.exe"
flags = "-fprint-results"
pta_cmd = "%s %s" % (frontend, flags)
prefix = ""
prefix_size = int(sys.argv[1])
for x in sys.argv[2:(2+prefix_size)]:
prefix = " %s %s" % (prefix, x)
filelist = ""
for x in sys.argv[2:]:
filelist = "%s %s" % (filelist, x)
# this computes the points to set size for the prefix list
output = os.popen(pta_cmd + prefix + " 2> /dev/null | grep \"Number of things pointed to:\" ")
try:
total = int(string.split((output.readlines()[0]))[5])
except:
sys.stderr.write("Warning: failed to analyze some files\n")
exit
output = os.popen(pta_cmd + filelist + (" -fbt%d" %prefix_size) + " 2> /dev/null | grep \"Number of things pointed to:\" ")
try:
total2 = int(string.split((output.readlines()[0]))[5])
except:
sys.stderr.write("Warning: failed to analyze some files\n")
exit
print "Total number of things pointed to (%d files): %d" % (prefix_size,total)
print "Total number of things pointed to (%d files): with backtracking: %d" % (prefix_size,total2)
if (total != total2):
print "A backtracking test failed"
sys.exit(1)
else:
sys.exit(0)
| 1,215 | 442 |
"""Create views using Pumpwood pattern."""
import os
import pandas as pd
import simplejson as json
from io import BytesIO
from django.conf import settings
from django.http import HttpResponse
from rest_framework.parsers import JSONParser
from rest_framework import viewsets, status
from rest_framework.response import Response
from werkzeug.utils import secure_filename
from pumpwood_communication import exceptions
from pumpwood_communication.serializers import PumpWoodJSONEncoder
from django.db.models.fields import NOT_PROVIDED
from pumpwood_djangoviews.renderer import PumpwoodJSONRenderer
from pumpwood_djangoviews.query import filter_by_dict
from pumpwood_djangoviews.action import load_action_parameters
from pumpwood_djangoviews.aux.map_django_types import django_map
from django.db.models.fields.files import FieldFile
def save_serializer_instance(serializer_instance):
is_valid = serializer_instance.is_valid()
if is_valid:
return serializer_instance.save()
else:
raise exceptions.PumpWoodException(serializer_instance.errors)
class PumpWoodRestService(viewsets.ViewSet):
"""Basic View-Set for pumpwood rest end-points."""
_view_type = "simple"
renderer_classes = [PumpwoodJSONRenderer]
#####################
# Route information #
endpoint_description = None
dimentions = {}
icon = None
#####################
service_model = None
storage_object = None
microservice = None
trigger = False
# List fields
serializer = None
list_fields = None
foreign_keys = {}
file_fields = {}
# Front-end uses 50 as limit to check if all data have been fetched,
# if change this parameter, be sure to update front-end list component.
list_paginate_limit = 50
@staticmethod
def _allowed_extension(filename, allowed_extensions):
extension = 'none'
if '.' in filename:
extension = filename.rsplit('.', 1)[1].lower()
if "*" not in allowed_extensions:
if extension not in allowed_extensions:
return [(
"File {filename} with extension {extension} not " +
"allowed.\n Allowed extensions: {allowed_extensions}"
).format(filename=filename, extension=extension,
allowed_extensions=str(allowed_extensions))]
return []
def list(self, request):
"""
View function to list objects with pagination.
Number of objects are limited by
settings.REST_FRAMEWORK['PAGINATE_BY']. To get next page, use
exclude_dict['pk__in': [list of the received pks]] to get more
objects.
Use to limit the query .query.filter_by_dict function.
:param request.data['filter_dict']: Dictionary passed as
objects.filter(**filter_dict)
:type request.data['filter_dict']: dict
:param request.data['exclude_dict']: Dictionary passed as
objects.exclude(**exclude_dict)
:type request.data['exclude_dict']: dict
:param request.data['order_by']: List passed as
objects.order_by(*order_by)
:type request.data['order_by']: list
:return: A list of objects using list_serializer
"""
try:
request_data = request.data
limit = request_data.pop("limit", None)
list_paginate_limit = limit or self.list_paginate_limit
fields = request_data.pop("fields", None)
list_fields = fields or self.list_fields
arg_dict = {'query_set': self.service_model.objects.all()}
arg_dict.update(request_data)
query_set = filter_by_dict(**arg_dict)[:list_paginate_limit]
return Response(self.serializer(
query_set, many=True, fields=list_fields).data)
except TypeError as e:
raise exceptions.PumpWoodQueryException(message=str(e))
def list_without_pag(self, request):
"""List data without pagination.
View function to list objects. Basicaley the same of list, but without
limitation by settings.REST_FRAMEWORK['PAGINATE_BY'].
:param request.data['filter_dict']: Dictionary passed as
objects.filter(**filter_dict)
:type request.data['filter_dict']: dict
:param request.data['exclude_dict']: Dictionary passed as
objects.exclude(**exclude_dict)
:type request.data['exclude_dict']: dict
:param request.data['order_by']: List passed as
objects.order_by(*order_by)
:type request.data['order_by']: list
:return: A list of objects using list_serializer
.. note::
Be careful with the number of the objects that will be retrieved
"""
try:
request_data = request.data
fields = request_data.pop("fields", None)
list_fields = fields or self.list_fields
arg_dict = {'query_set': self.service_model.objects.all()}
arg_dict.update(request_data)
query_set = filter_by_dict(**arg_dict)
return Response(self.serializer(
query_set, many=True, fields=list_fields).data)
except TypeError as e:
raise exceptions.PumpWoodQueryException(
message=str(e))
def retrieve(self, request, pk=None):
"""
Retrieve view, uses the retrive_serializer to return object with pk.
:param int pk: Object pk to be retrieve
:return: The representation of the object passed by
self.retrive_serializer
:rtype: dict
"""
obj = self.service_model.objects.get(pk=pk)
return Response(self.serializer(obj, many=False).data)
def retrieve_file(self, request, pk: int):
"""
Read file without stream.
Args:
pk (int): Pk of the object to save file field.
file_field(str): File field to receive stream file.
Returns:
A stream of bytes with da file.
"""
if self.storage_object is None:
raise exceptions.PumpWoodForbidden(
"storage_object not set")
file_field = request.query_params.get('file-field', None)
if file_field not in self.file_fields.keys():
msg = (
"'{file_field}' must be set on file_fields "
"dictionary.").format(file_field=file_field)
raise exceptions.PumpWoodForbidden(msg)
obj = self.service_model.objects.get(id=pk)
file_path = getattr(obj, file_field)
if isinstance(file_path, FieldFile):
file_path = file_path.name
if file_path is None:
raise exceptions.PumpWoodObjectDoesNotExist(
"field [{}] not found at object".format(file_field))
file_data = self.storage_object.read_file(file_path)
file_name = os.path.basename(file_path)
response = HttpResponse(content=BytesIO(file_data["data"]))
response['Content-Type'] = file_data["content_type"]
response['Content-Disposition'] = \
'attachment; filename=%s' % file_name
return response
def delete(self, request, pk=None):
"""
Delete view.
:param int pk: Object pk to be retrieve
"""
obj = self.service_model.objects.get(pk=pk)
return_data = self.serializer(obj, many=False).data
obj.delete()
return Response(return_data, status=200)
def delete_many(self, request):
"""
Delete many data using filter.
:param request.data['filter_dict']: Dictionary passed as
objects.filter(**filter_dict)
:type request.data['filter_dict']: dict
:param request.data['exclude_dict']: Dictionary passed as
objects.exclude(**exclude_dict)
:type request.data['exclude_dict']: dict
:return: True if delete is ok
"""
try:
arg_dict = {'query_set': self.service_model.objects.all()}
arg_dict.update(request.data)
query_set = filter_by_dict(**arg_dict)
query_set.delete()
return Response(True, status=200)
except TypeError as e:
raise exceptions.PumpWoodQueryException(
message=str(e))
def remove_file_field(self, request, pk: int) -> bool:
"""
Remove file field.
Args:
pk (int): pk of the object.
Kwargs:
No kwargs for this function.
Raises:
PumpWoodForbidden: If file_file is not in file_fields keys of the
view.
PumpWoodException: Propagates exceptions from storage_objects.
"""
file_field = request.query_params.get('file_field', None)
if file_field not in self.file_fields.keys():
raise exceptions.PumpWoodForbidden(
"file_field must be set on self.file_fields dictionary.")
obj = self.service_model.objects.get(id=pk)
file = getattr(obj, file_field)
if file is None:
raise exceptions.PumpWoodObjectDoesNotExist(
"field [{}] not found at object".format(file_field))
else:
file_path = file.name
setattr(obj, file_field, None)
obj.save()
try:
self.storage_object.delete_file(file_path)
return Response(True)
except Exception as e:
raise exceptions.PumpWoodException(str(e))
def save(self, request):
"""
Save and update object acording to request.data.
Object will be updated if request.data['pk'] is not None.
:param dict request.data: Object representation as
self.retrive_serializer
:raise PumpWoodException: 'Object model class diferent from
{service_model} : {service_model}' request.data['service_model']
not the same as self.service_model.__name__
"""
request_data: dict = None
if "application/json" in request.content_type.lower():
request_data = request.data
else:
request_data = request.data.dict()
for k in request_data.keys():
if k not in self.file_fields.keys():
request_data[k] = json.loads(request_data[k])
data_pk = request_data.get('pk')
saved_obj = None
for field in self.file_fields.keys():
request_data.pop(field, None)
# update
if data_pk:
data_to_update = self.service_model.objects.get(pk=data_pk)
serializer = self.serializer(
data_to_update, data=request_data,
context={'request': request})
saved_obj = save_serializer_instance(serializer)
response_status = status.HTTP_200_OK
# save
else:
serializer = self.serializer(
data=request_data, context={'request': request})
saved_obj = save_serializer_instance(serializer)
response_status = status.HTTP_201_CREATED
# Uploading files
object_errors = {}
for field in self.file_fields.keys():
field_errors = []
if field in request.FILES:
file = request.FILES[field]
file_name = secure_filename(file.name)
field_errors.extend(self._allowed_extension(
filename=file_name,
allowed_extensions=self.file_fields[field]))
filename = "{}___{}".format(saved_obj.id, file_name)
if len(field_errors) != 0:
object_errors[field] = field_errors
else:
model_class = self.service_model.__name__.lower()
file_path = '{model_class}__{field}/'.format(
model_class=model_class, field=field)
storage_filepath = self.storage_object.write_file(
file_path=file_path, file_name=filename,
data=file.read(),
content_type=file.content_type,
if_exists='overide')
setattr(saved_obj, field, storage_filepath)
if object_errors != {}:
message = "error when saving object: " \
if data_pk is None else "error when updating object: "
payload = object_errors
message_to_append = []
for key, value in object_errors.items():
message_to_append.append(key + ", " + str(value))
message = message + "; ".join(message_to_append)
raise exceptions.PumpWoodObjectSavingException(
message=message, payload=payload)
saved_obj.save()
if self.microservice is not None and self.trigger:
# Process ETLTrigger for the model class
self.microservice.login()
if data_pk is None:
self.microservice.execute_action(
"ETLTrigger", action="process_triggers", parameters={
"model_class": self.service_model.__name__.lower(),
"type": "create",
"pk": None,
"action_name": None})
else:
self.microservice.execute_action(
"ETLTrigger", action="process_triggers", parameters={
"model_class": self.service_model.__name__.lower(),
"type": "update",
"pk": saved_obj.pk,
"action_name": None})
# Overhead, serializando e deserializando o objecto
return Response(
self.serializer(saved_obj).data, status=response_status)
def get_actions(self):
"""Get all actions with action decorator."""
# this import works here only
import inspect
function_dict = dict(inspect.getmembers(
self.service_model, predicate=inspect.isfunction))
method_dict = dict(inspect.getmembers(
self.service_model, predicate=inspect.ismethod))
method_dict.update(function_dict)
actions = {
name: func for name,
func in method_dict.items()
if getattr(func, 'is_action', False)}
return actions
def list_actions(self, request):
"""List model exposed actions."""
actions = self.get_actions()
action_descriptions = [
action.action_object.to_dict()
for name, action in actions.items()]
return Response(action_descriptions)
def list_actions_with_objects(self, request):
"""List model exposed actions acording to selected objects."""
actions = self.get_actions()
action_descriptions = [
action.action_object.description
for name, action in actions.items()]
return Response(action_descriptions)
def execute_action(self, request, action_name, pk=None):
"""Execute action over object or class using parameters."""
parameters = request.data
actions = self.get_actions()
rest_action_names = list(actions.keys())
if action_name not in rest_action_names:
message = (
"There is no method {action} in rest actions "
"for {class_name}").format(
action=action_name,
class_name=self.service_model.__name__)
raise exceptions.PumpWoodForbidden(
message=message, payload={"action_name": action_name})
action = getattr(self.service_model, action_name)
if pk is None and not action.action_object.is_static_function:
msg_template = (
"Action [{action}] at model [{class_name}] is not "
"a classmethod and not pk provided.")
message = msg_template.format(
action=action_name,
class_name=self.service_model.__name__)
raise exceptions.PumpWoodActionArgsException(
message=message, payload={"action_name": action_name})
if pk is not None and action.action_object.is_static_function:
msg_template = (
"Action [{action}] at model [{class_name}] is a"
"classmethod and pk provided.")
message = msg_template.format(
action=action_name,
class_name=self.service_model.__name__)
raise exceptions.PumpWoodActionArgsException(
message=message, payload={"action_name": action_name})
object_dict = None
action = None
if pk is not None:
model_object = self.service_model.objects.filter(pk=pk).first()
if model_object is None:
message_template = (
"Requested object {service_model}[{pk}] not found.")
temp_service_model = \
self.service_model.__name__
message = message_template.format(
service_model=temp_service_model, pk=pk)
raise exceptions.PumpWoodObjectDoesNotExist(
message=message, payload={
"service_model": temp_service_model, "pk": pk})
action = getattr(model_object, action_name)
object_dict = self.serializer(
model_object, many=False, fields=self.list_fields).data
else:
action = getattr(self.service_model, action_name)
loaded_parameters = load_action_parameters(action, parameters, request)
result = action(**loaded_parameters)
if self.microservice is not None and self.trigger:
self.microservice.login()
self.microservice.execute_action(
"ETLTrigger", action="process_triggers", parameters={
"model_class": self.service_model.__name__.lower(),
"type": "action", "pk": pk, "action_name": action_name})
return Response({
'result': result, 'action': action_name,
'parameters': parameters, 'object': object_dict})
@classmethod
def cls_search_options(cls):
fields = cls.service_model._meta.get_fields()
all_info = {}
# f = fields[10]
for f in fields:
column_info = {}
################################################################
# Do not create relations between models in search description #
is_relation = getattr(f, "is_relation", False)
if is_relation:
continue
################################################################
# Getting correspondent simple type
column_type = f.get_internal_type()
python_type = django_map.get(column_type)
if python_type is None:
msg = (
"Type [{column_type}] not implemented in map dictionary "
"django type -> python type")
raise NotImplementedError(
msg.format(column_type=column_type))
# Getting default value
default = None
f_default = getattr(f, 'default', None)
if f_default != NOT_PROVIDED and f_default is not None:
if callable(f_default):
default = f_default()
else:
default = f_default
primary_key = getattr(f, "primary_key", False)
help_text = str(getattr(f, "help_text", ""))
db_index = getattr(f, "db_index", False)
unique = getattr(f, "unique", False)
column = None
if primary_key:
column = "pk"
else:
column = f.column
column_info = {
'primary_key': primary_key,
"column": column,
"doc_string": help_text,
"type": python_type,
"nullable": f.null,
"default": default,
"indexed": db_index or primary_key,
"unique": unique}
# Get choice options if avaiable
choices = getattr(f, "choices", None)
if choices is not None:
column_info["type"] = "options"
column_info["in"] = [
{"value": choice[0], "description": choice[1]}
for choice in choices]
# Set autoincrement for primary keys
if primary_key:
column_info["column"] = "pk"
column_info["default"] = "#autoincrement#"
column_info["doc_string"] = "object primary key"
# Ajust type if file
file_field = cls.file_fields.get(column)
if file_field is not None:
column_info["type"] = "file"
column_info["permited_file_types"] = file_field
all_info[column] = column_info
# Adding description for foreign keys
for key, item in cls.foreign_keys.items():
column = getattr(cls.service_model, key, None)
if column is None:
msg = (
"Foreign Key incorrectly configured at Pumpwood View. "
"[{key}] not found on [{model}]").format(
key=key, model=str(cls.service_model))
raise Exception(msg)
primary_key = getattr(column.field, "primary_key", False)
help_text = str(getattr(column.field, "help_text", ""))
db_index = getattr(column.field, "db_index", False)
unique = getattr(column.field, "unique", False)
null = getattr(column.field, "null", False)
# Getting default value
default = None
f_default = getattr(f, 'default', None)
if f_default != NOT_PROVIDED and f_default is not None:
if callable(f_default):
default = f_default()
else:
default = f_default
column_info = {
'primary_key': primary_key,
"column": key,
"doc_string": help_text,
"type": "foreign_key",
"nullable": null,
"default": default,
"indexed": db_index or primary_key,
"unique": unique}
if isinstance(item, dict):
column_info["model_class"] = item["model_class"]
column_info["many"] = item["many"]
elif isinstance(item, str):
column_info["model_class"] = item
column_info["many"] = False
else:
msg = (
"foreign_key not correctly defined, check column"
"[{key}] from model [{model}]").format(
key=key, model=str(cls.service_model))
raise Exception(msg)
all_info[key] = column_info
return all_info
def search_options(self, request):
"""
Return options to be used in list funciton.
:return: Dictionary with options for list parameters
:rtype: dict
.. note::
Must be implemented
"""
return Response(self.cls_search_options())
def fill_options(self, request):
"""
Return options for object update acording its partial data.
:param dict request.data: Partial object data.
:return: A dictionary with options for diferent objects values
:rtype: dict
.. note::
Must be implemented
"""
return Response(self.cls_search_options())
class PumpWoodDataBaseRestService(PumpWoodRestService):
"""This view extends PumpWoodRestService, including pivot function."""
_view_type = "data"
model_variables = []
"""Specify which model variables will be returned in pivot. Line index are
the model_variables - columns (function pivot parameter) itens."""
expected_cols_bulk_save = []
"""Set the collumns needed at bulk_save."""
def pivot(self, request):
"""
Pivot QuerySet data acording to columns selected, and filters passed.
:param request.data['filter_dict']: Dictionary passed as
objects.filter(**filter_dict)
:type request.data['filter_dict']: dict
:param request.data['exclude_dict']: Dictionary passed as
objects.exclude(**exclude_dict)
:type request.data['exclude_dict']: dict
:param request.data['order_by']: List passed as
objects.order_by(*order_by)
:type request.data['order_by']: list
:param request.data['columns']: Variables to be used as pivot collumns
:type request.data['columns']: list
:param request.data['format']: Format used in
pandas.DataFrame().to_dict()
:type request.data['columns']: str
:return: Return database data pivoted acording to columns parameter
:rtyoe: panas.Dataframe converted to disctionary
"""
columns = request.data.get('columns', [])
format = request.data.get('format', 'list')
model_variables = request.data.get('variables')
show_deleted = request.data.get('show_deleted', False)
model_variables = model_variables or self.model_variables
if type(columns) != list:
raise exceptions.PumpWoodException(
'Columns must be a list of elements.')
if len(set(columns) - set(model_variables)) != 0:
raise exceptions.PumpWoodException(
'Column chosen as pivot is not at model variables')
index = list(set(model_variables) - set(columns))
filter_dict = request.data.get('filter_dict', {})
exclude_dict = request.data.get('exclude_dict', {})
order_by = request.data.get('order_by', {})
if hasattr(self.service_model, 'deleted'):
if not show_deleted:
filter_dict["deleted"] = False
arg_dict = {'query_set': self.service_model.objects.all(),
'filter_dict': filter_dict,
'exclude_dict': exclude_dict,
'order_by': order_by}
query_set = filter_by_dict(**arg_dict)
try:
filtered_objects_as_list = list(
query_set.values_list(*(model_variables)))
except TypeError as e:
raise exceptions.PumpWoodQueryException(message=str(e))
melted_data = pd.DataFrame(
filtered_objects_as_list, columns=model_variables)
if len(columns) == 0:
return Response(melted_data.to_dict(format))
if melted_data.shape[0] == 0:
return Response({})
else:
if "value" not in melted_data.columns:
raise exceptions.PumpWoodException(
"'value' column not at melted data, it is not possible"
" to pivot dataframe.")
pivoted_table = pd.pivot_table(
melted_data, values='value', index=index,
columns=columns, aggfunc=lambda x: tuple(x)[0])
return Response(
pivoted_table.reset_index().to_dict(format))
def bulk_save(self, request):
"""
Bulk save data.
Args:
data_to_save(list): List of dictionaries which must have
self.expected_cols_bulk_save.
Return:
dict: ['saved_count']: total of saved objects.
"""
data_to_save = request.data
if data_to_save is None:
raise exceptions.PumpWoodException(
'Post payload must have data_to_save key.')
if len(self.expected_cols_bulk_save) == 0:
raise exceptions.PumpWoodException('Bulk save not avaiable.')
pd_data_to_save = pd.DataFrame(data_to_save)
pd_data_cols = set(list(pd_data_to_save.columns))
if len(set(self.expected_cols_bulk_save) - pd_data_cols) == 0:
objects_to_load = []
for d in data_to_save:
new_obj = self.service_model(**d)
objects_to_load.append(new_obj)
self.service_model.objects.bulk_create(objects_to_load)
return Response({'saved_count': len(objects_to_load)})
else:
template = 'Expected columns and data columns do not match:' + \
'\nExpected columns:{expected}' + \
'\nData columns:{data_cols}'
raise exceptions.PumpWoodException(template.format(
expected=set(self.expected_cols_bulk_save),
data_cols=pd_data_cols,))
| 29,178 | 7,709 |
from .base import Base
class Heavy(Base):
def complete_init(self):
super().complete_init()
self.force_regroup = True
if self.unit.use_ammo:
self.smart_range_retarget = True
def process(self, dt):
super().process(dt)
| 273 | 88 |
import shutil
import unittest
import tempfile
import pandas as pd
from kgtk.cli_entry import cli_entry
from kgtk.exceptions import KGTKException
class TestKGTKImportConceptNet(unittest.TestCase):
def setUp(self) -> None:
self.temp_dir=tempfile.mkdtemp()
def tearDown(self) -> None:
shutil.rmtree(self.temp_dir)
def test_kgtk_import_conceptnet(self):
cli_entry("kgtk", "import-conceptnet", "--english_only", "-i", "data/conceptnet.csv", "-o", f'{self.temp_dir}/conceptnet.tsv')
df = pd.read_csv(f'{self.temp_dir}/conceptnet.tsv', sep='\t')
self.assertEqual(len(df), 77) # Make sure that there are 77 rows with English nodes out of the total 100
self.assertEqual(df['node2'][0], '/c/en/1') # Make sure that the first node2 is the expected one
self.assertEqual(len(df.columns), 9)
relations = df['relation'].unique()
| 899 | 321 |
from .scrape import Scrape
from .helper import Helper | 53 | 17 |
# Written by Will Cromar
# Python 3.6
from collections import deque
# DX/DY array. In order of precedence, we'll move
# left, right, up, and down
DX = [-1, 1, 0, 0]
DY = [0, 0, -1, 1]
# Constants for types of spaces
EMPTY = '.'
LADDER = '#'
CHUTE = '*'
START = 'S'
EXIT = 'E'
# Primary business functions. Includes several helpers
def solve(grid, l, w, h):
# Generator that gives all adjacent spots to the given one
def adjacent(x, y, z):
# print("call to adj w/", (x, y, z))
for dx, dy in zip(DX, DY):
# print(x + dx, y + dy, z)
yield x + dx, y + dy, z
# True if the result is in bounds, false otherwise
def inBounds(x, y, z):
return x >= 0 and y >= 0 and z >= 0 and x < w and y < l and z < h
# Gives all adjacent nodes that are in bounds
def moves(x, y, z):
# Get all adjacent nodes and then filter them
return filter(lambda triplet: inBounds(*triplet), adjacent(x, y, z))
# Follow a chute to the bottom
def chuteBottom(x, y, z):
# While the spot below us is still a chute, keep moving down levels
while z > 0 and grid[z - 1][y][x] == CHUTE:
z -= 1
return x, y, z
# Gives vertically adjacent spots that have ladders
def ladderSpots(x, y, z):
# If there's a ladder above us, yield it
if z < h - 1 and grid[z + 1][y][x] == LADDER:
yield x, y, z + 1
# Likewise, yield ladders below us
if z > 0 and grid[z - 1][y][x] == LADDER:
yield x, y, z - 1
# Searches for the start symbol and returns an ordered triplet
# or None
def findStart():
for z, level in enumerate(grid):
for y, row in enumerate(level):
if START in row:
return row.find(START), y, z
# Finally, we can move on to our breadth-first search
# This will store which spots we've seen before
seen = set()
# Will store an ordered triplet and a number of steps
q = deque()
# Find the starting position and add it to the queue w/ 0 steps
start = findStart()
seen.add(start)
q.append(start)
# Run BFS until the queue empties
while len(q) > 0:
# Unpack the data from the queue
triplet = q.popleft()
x, y, z = triplet
# If we've found the exit, we're done!
if grid[z][y][x] == EXIT:
return True
# If we stepped on a chute, fall
if grid[z][y][x] == CHUTE:
next = chuteBottom(x, y, z)
if next not in seen:
seen.add(next)
q.appendleft(next)
# If we're not at the bottom of the chute, then we
# can't move anywhere else
if next != triplet:
continue
# If we stepped on a ladder, see where we can go
if grid[z][y][x] == LADDER:
for next in ladderSpots(x, y, z):
if next not in seen:
seen.add(next)
q.append(next)
# Otherwise, explore our "slice" of the map
for next in moves(x, y, z):
if next not in seen:
seen.add(next)
q.append(next)
return False
# Number of test cases
n = int(input())
# Process each test case
for case in range(n):
# Get the dimensions of the grid
l, w, h = map(int, input().strip().split())
# Read it in
grid = []
for _ in range(h):
slice = []
for _ in range(l):
slice.append(input().strip())
grid.append(slice)
# I reverse the list to make z = 0 correspond to the lowest
# slice on the map
grid.reverse()
# Determine if there is a path from start to end
ans = solve(grid, l, w, h)
# If there is, print "Yes", otherwise, "No"
print("Map #%d: %s" % (case + 1, "Yes" if ans else "No"))
| 4,030 | 1,396 |
import fitsio
import fsfits
from argparse import ArgumentParser
import json
import numpy
ap = ArgumentParser()
ap.add_argument('--check', action='store_true', default=False,
help="Test if output contains identical information to input")
ap.add_argument('input')
ap.add_argument('output')
ns = ap.parse_args()
def main():
fin = fitsio.FITS(ns.input)
if ns.check:
fout = fsfits.FSHR.open(ns.output)
else:
fout = fsfits.FSHR.create(ns.output)
with fout:
for hdui, hdu in enumerate(fin):
header = hdu.read_header()
header = dict(header)
type = hdu.get_exttype()
if hdu.has_data():
if type in (
'BINARY_TBL',
'ASCII_TBL'):
data = hdu[:]
elif type in ('IMAGE_HDU'):
data = hdu[:, :]
else:
data = None
if ns.check:
block = fout["HDU-%04d" % hdui]
with block:
for key in header:
assert header[key] == block.metadata[key]
if data is not None:
assert (block[...] == data).all()
else:
assert block[...] is None
else:
if data is not None:
block = fout.create_block("HDU-%04d" % hdui,
data.shape, data.dtype)
else:
block = fout.create_block("HDU-%04d" % hdui,
(0,), None)
with block:
block.metadata.update(header)
if data is not None:
block[...] = data
main()
| 1,789 | 506 |
from tkinter import Entry, Listbox, StringVar
import sys, tkinter, subprocess
from window_switcher.aux import get_windows
class Window:
FONT = ('Monospace', 11)
ITEM_HEIGHT = 22
MAX_FOUND = 10
BG_COLOR = '#202b3a'
FG_COLOR = '#ced0db'
def resize(self, items):
if self.resized:
return
self.root.geometry('{0}x{1}'.format(self.width, self.height + items * Window.ITEM_HEIGHT))
self.resized = True
def __init__(self, root, width, height):
self.root = root
self.width = width
self.height = height
self.all_windows = []
self.resized = False
# master.geometry(500)
root.title("window switcher")
root.resizable(width=False, height=False)
root.configure(background=Window.BG_COLOR)
# ugly tkinter code below
sv = StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: self.on_entry(sv))
self.main_entry = Entry(
root,
font=Window.FONT,
width=1000,
textvariable=sv,
bg=Window.BG_COLOR,
fg=Window.FG_COLOR,
insertbackground=Window.FG_COLOR,
bd=0
)
self.main_entry.grid(row=0, column=0, padx=10)
self.main_entry.focus_set()
self.listbox = Listbox(
root,
height=Window.ITEM_HEIGHT,
font=Window.FONT,
highlightthickness=0,
borderwidth=0,
bg=Window.BG_COLOR,
fg=Window.FG_COLOR,
selectbackground='#2c3c51',
selectforeground='#cedaed'
)
self.listbox.grid(row=1, column=0, sticky='we', padx=10, pady=10)
# key bindings
self.main_entry.bind('<Control-a>', self.select_all)
self.main_entry.bind('<Up>', self.select_prev)
self.main_entry.bind('<Down>', self.select_next)
self.main_entry.bind('<Return>', self.select_window)
self.root.bind('<Escape>', lambda e: sys.exit())
# self.resize(Window.MAX_FOUND)
self.initial_get(None)
def initial_get(self, event):
self.all_windows = get_windows()
self.find_windows('')
def select_all(self, event):
# select text
self.main_entry.select_clear()
self.main_entry.select_range(0, 'end')
# move cursor to the end
self.main_entry.icursor('end')
return 'break'
def find_windows(self, text):
text = text.lower()
found = [window for window in self.all_windows if window['name'].find(text) != -1]
# print(found)
self.found = found
self.listbox.delete(0, 'end')
for i, item in enumerate(found):
if i >= Window.MAX_FOUND:
break
self.listbox.insert('end', item['name'])
self.resize(min(len(found), Window.MAX_FOUND))
# select first element
self.listbox.selection_set(0)
def select_next(self, event):
if len(self.found) == 0:
return
idx = self.listbox.curselection()[0]
max = self.listbox.size()
idx += 1
if idx >= max:
idx = 0
self.listbox.selection_clear(0, 'end')
self.listbox.selection_set(idx)
def select_prev(self, event):
if len(self.found) == 0:
return
idx = self.listbox.curselection()[0]
max = self.listbox.size()
idx -= 1
if idx < 0:
idx = max - 1
self.listbox.selection_clear(0, 'end')
self.listbox.selection_set(idx)
def select_window(self, event):
idx = self.listbox.curselection()[0]
id = self.found[idx]['id']
# switch to window and exit
# wmctrl -ia <id`>
subprocess.call(['wmctrl', '-ia', id])
# print(subprocess.check_output(['wmctrl', '-ia', id]).decode('utf-8'))
sys.exit(0)
def on_entry(self, newtext):
search_test = newtext.get()
self.find_windows(search_test)
return True
| 4,086 | 1,350 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: imu_samples.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='imu_samples.proto',
package='app.udp_comm',
syntax='proto3',
serialized_options=None,
serialized_pb=_b('\n\x11imu_samples.proto\x12\x0c\x61pp.udp_comm\"\xce\x01\n\nImuSamples\x12\x1b\n\x13time_of_validity_us\x18\x01 \x01(\x12\x12\x12\n\ntimestamps\x18\x02 \x03(\x12\x12\x14\n\x0c\x61\x63\x63\x65l_x_mpss\x18\x03 \x03(\x02\x12\x14\n\x0c\x61\x63\x63\x65l_y_mpss\x18\x04 \x03(\x02\x12\x14\n\x0c\x61\x63\x63\x65l_z_mpss\x18\x05 \x03(\x02\x12\x12\n\ngyro_x_dps\x18\x06 \x03(\x02\x12\x12\n\ngyro_y_dps\x18\x07 \x03(\x02\x12\x12\n\ngyro_z_dps\x18\x08 \x03(\x02\x12\x11\n\ttemp_degc\x18\t \x03(\x02\x62\x06proto3')
)
_IMUSAMPLES = _descriptor.Descriptor(
name='ImuSamples',
full_name='app.udp_comm.ImuSamples',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='time_of_validity_us', full_name='app.udp_comm.ImuSamples.time_of_validity_us', index=0,
number=1, type=18, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='timestamps', full_name='app.udp_comm.ImuSamples.timestamps', index=1,
number=2, type=18, cpp_type=2, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='accel_x_mpss', full_name='app.udp_comm.ImuSamples.accel_x_mpss', index=2,
number=3, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='accel_y_mpss', full_name='app.udp_comm.ImuSamples.accel_y_mpss', index=3,
number=4, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='accel_z_mpss', full_name='app.udp_comm.ImuSamples.accel_z_mpss', index=4,
number=5, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='gyro_x_dps', full_name='app.udp_comm.ImuSamples.gyro_x_dps', index=5,
number=6, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='gyro_y_dps', full_name='app.udp_comm.ImuSamples.gyro_y_dps', index=6,
number=7, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='gyro_z_dps', full_name='app.udp_comm.ImuSamples.gyro_z_dps', index=7,
number=8, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='temp_degc', full_name='app.udp_comm.ImuSamples.temp_degc', index=8,
number=9, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=36,
serialized_end=242,
)
DESCRIPTOR.message_types_by_name['ImuSamples'] = _IMUSAMPLES
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ImuSamples = _reflection.GeneratedProtocolMessageType('ImuSamples', (_message.Message,), dict(
DESCRIPTOR = _IMUSAMPLES,
__module__ = 'imu_samples_pb2'
# @@protoc_insertion_point(class_scope:app.udp_comm.ImuSamples)
))
_sym_db.RegisterMessage(ImuSamples)
# @@protoc_insertion_point(module_scope)
| 5,292 | 2,165 |
"""This module contains the general information for BiosVfSgxLePubKeyHash ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class BiosVfSgxLePubKeyHashConsts:
VP_SGX_LE_PUB_KEY_HASH0_PLATFORM_DEFAULT = "platform-default"
VP_SGX_LE_PUB_KEY_HASH1_PLATFORM_DEFAULT = "platform-default"
VP_SGX_LE_PUB_KEY_HASH2_PLATFORM_DEFAULT = "platform-default"
VP_SGX_LE_PUB_KEY_HASH3_PLATFORM_DEFAULT = "platform-default"
class BiosVfSgxLePubKeyHash(ManagedObject):
"""This is BiosVfSgxLePubKeyHash class."""
consts = BiosVfSgxLePubKeyHashConsts()
naming_props = set([])
mo_meta = {
"classic": MoMeta("BiosVfSgxLePubKeyHash", "biosVfSgxLePubKeyHash", "Sgx-Le-PubKeyHash", VersionMeta.Version421a, "InputOutput", 0xff, [], ["admin"], ['biosPlatformDefaults', 'biosSettings'], [], [None]),
}
prop_meta = {
"classic": {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version421a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
"vp_sgx_le_pub_key_hash0": MoPropertyMeta("vp_sgx_le_pub_key_hash0", "vpSgxLePubKeyHash0", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []),
"vp_sgx_le_pub_key_hash1": MoPropertyMeta("vp_sgx_le_pub_key_hash1", "vpSgxLePubKeyHash1", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []),
"vp_sgx_le_pub_key_hash2": MoPropertyMeta("vp_sgx_le_pub_key_hash2", "vpSgxLePubKeyHash2", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x40, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []),
"vp_sgx_le_pub_key_hash3": MoPropertyMeta("vp_sgx_le_pub_key_hash3", "vpSgxLePubKeyHash3", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x80, None, None, r"""[0-9a-fA-F]{1,16}""", ["platform-default"], []),
},
}
prop_map = {
"classic": {
"childAction": "child_action",
"dn": "dn",
"rn": "rn",
"status": "status",
"vpSgxLePubKeyHash0": "vp_sgx_le_pub_key_hash0",
"vpSgxLePubKeyHash1": "vp_sgx_le_pub_key_hash1",
"vpSgxLePubKeyHash2": "vp_sgx_le_pub_key_hash2",
"vpSgxLePubKeyHash3": "vp_sgx_le_pub_key_hash3",
},
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.status = None
self.vp_sgx_le_pub_key_hash0 = None
self.vp_sgx_le_pub_key_hash1 = None
self.vp_sgx_le_pub_key_hash2 = None
self.vp_sgx_le_pub_key_hash3 = None
ManagedObject.__init__(self, "BiosVfSgxLePubKeyHash", parent_mo_or_dn, **kwargs)
| 3,394 | 1,377 |
from configparser import ConfigParser
import boto3
class S3Client:
@staticmethod
def get_client(config: ConfigParser):
return boto3.Session(
profile_name=config.get('S3', 'profile', fallback='default')
).client('s3')
| 256 | 77 |
import os
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), 'rb') as readme:
README = readme.read()
setup(
name='getsize',
version='0.1',
packages=find_packages(exclude=('tests',)),
include_package_data=True,
license='MIT License',
description='Command Line Tools For Get File and Directory Size',
long_description=README.decode('utf-8'),
url='https://github.com/naritotakizawa/getsize',
author='Narito Takizawa',
author_email='toritoritorina@gmail.com',
classifiers=[
"Environment :: Console",
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
"Programming Language :: Python :: 3",
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
"Topic :: Software Development :: Libraries :: Python Modules",
],
tests_require = ['pytest', 'pytest-cov'],
cmdclass = {'test': PyTest},
entry_points={'console_scripts': [
'pysize = getsize.main:main',
]},
) | 1,791 | 568 |
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DockWidgetPluginBase(object):
def setupUi(self, DockWidgetPluginBase):
DockWidgetPluginBase.setObjectName("DockWidgetPluginBase")
DockWidgetPluginBase.resize(232, 141)
self.dockWidgetContents = QtWidgets.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.gridLayout = QtWidgets.QGridLayout(self.dockWidgetContents)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(self.dockWidgetContents)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
# DockWidgetPluginBase.setWidget(self.dockWidgetContents)
self.retranslateUi(DockWidgetPluginBase)
QtCore.QMetaObject.connectSlotsByName(DockWidgetPluginBase)
def retranslateUi(self, DockWidgetPluginBase):
_translate = QtCore.QCoreApplication.translate
DockWidgetPluginBase.setWindowTitle(_translate("DockWidgetPluginBase", "Test DockWidget"))
self.label.setText(_translate("DockWidgetPluginBase", "Replace this QLabel\n"
"with the desired\n"
"plugin content."))
| 1,194 | 375 |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='attention-memory-task',
version='0.1.0',
description='Attention and Memory Experiment',
long_description='This repository contains the Psychopy code for a psychology experiment exploring the relationship between covert attention and recognition memory.',
author='Contextual Dynamics Laboratory',
author_email='contextualdynamics@gmail.com',
url='https://github.com/ContextLab/attention-memory-task',
license=license,
packages=find_packages(exclude=('tests'))
)
| 684 | 207 |
from numpy import *
import matplotlib.pyplot as plt
import time
from LogReg import trainLogRegres, showLogRegres, predicTestData
# from sklearn.datasets import make_circles
# from sklearn.model_selection import train_test_split
# from sklearn.metrics import accuracy_score
import csv
def loadTrainData():
train_x = []
train_y = []
# fileIn = open('/Users/martinzhang/Desktop/testSet.txt')
# for line in fileIn.readlines():
# lineArr = line.strip().split()
# train_x.append([1, float(lineArr[0]), float(lineArr[1])])
# train_y.append(float(lineArr[2]))
# # return mat(train_x), mat(train_y).transpose()
# for userA, relation in range(relation_dic):
# for userB in range(userlist):
# if user not in relation:
# label = 0
# else:
# label = 1
# train_x.append([1, float(lineArr[0]), float(lineArr[1])])
# train_y.append(label)
# return mat(train_x), mat(train_y).transpose()
with load('/Users/martinzhang/Desktop/compressed_test_7features.npz') as fd:
temp_matrix = fd["temptest"]
# d = [0, 1, 2, 3, 4, 5, 6]
length =10336114
a = ones(length)
temp_matrix_x = temp_matrix[0:length, 0:7]
result = insert(temp_matrix_x, 0, values=a, axis=1)
temp_matrix_y = temp_matrix[0:length, 7]
return mat(result), mat(temp_matrix_y).transpose()
def loadTestData():
# test_list = []
# test_id = []
test_x = []
# test_y = []
# file_path = open('/Users/martinzhang/Desktop/ml_data/test-public.txt')
index = -1
for line in file_path.readlines():
index += 1
if index == 0:
pass
else:
line_content = line.strip().split()
data_id = line_content[0]
data_source = line_content[1]
data_sink = line_content[2]
# test_list.append([data_id, data_source, data_sink])
# test_id.append(data_id)
test_x.append([data_id, data_source, data_sink])
# test_x
if index == 100:
return mat(test_x)
#
#
## step 1: load data
print("step 1: load data...")
train_x, train_y = loadTrainData()
# for item in train_x:
# print item
# test_list = loadTestData()
# for test_data in test_list:
# test_x = train_x
# test_y = train_y
# test_x = loadTestData()
## step 2: training...
print("step 2: training...")
opts = {'alpha': 0.01, 'maxIter': 1, 'optimizeType': 'gradDescent'}
optimalWeights = trainLogRegres(train_x, train_y, opts)
# print(optimalWeights.transpose().tolist()[0])
# for line in optimalWeights:
# print(line[0])
print(optimalWeights.transpose().tolist()[0][1])
print(shape(optimalWeights))
## step 3: predicting
# print("step 3: predicting...")
# accuracy = predicTestData(optimalWeights, test_x, test_y)
# ## step 4: show the result
# print("step 4: show the result...")
# print('The classify accuracy is: %.3f%%' % (accuracy * 100))
# showLogRegres(optimalWeights, train_x, train_y)
# test = loadTestData()
# for item in test:
# print(item)
# def testCSV():
# test_y = []
# # csvfile = open('/Users/martinzhang/Desktop/ml_data/result.csv', 'wb')
# with open('/Users/martinzhang/Desktop/ml_data/result.csv', 'w') as csvfile:
# writer = csv.writer(csvfile)
# for i in range(0, 100):
# # predict = float(sigmoid(test_x[i, 1:] * weights)[0, 0])
# wwwww='ggg'
# # bytes(wwwww, encoding="utf8")
# writer.writerow((i, wwwww))
# csvfile.close()
# print('finishing!')
#
# testCSV()
| 3,659 | 1,317 |
import pyautogui as pg
# 间隔2秒钟将鼠标移动到坐标为100,100的位置
pg.FAILSAFE = False #关掉保护措施,不设置会报下面附录的错误
pg.moveTo(x=100, y=100, duration=2)
pg.click() #鼠标左键点击一次, 这个函数有很多参数,参见以下,可以玩看看
#pg.click(x=None, y=None, clicks=1, interval=0.0, button='left', duration=0.0, tween=pg.linear)
'''
第一次执行的时候报了这个错误,搜了一下貌似要关掉
Exception has occurred: FailSafeException
PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen. To disable this fail-safe, set pyautogui.FAILSAFE to False. DISABLING FAIL-SAFE IS NOT RECOMMENDED.
File "F:\codehub\WInAutomation\Pyautogui_tutorial\mousecontrolscipt.py", line 4, in <module>
pg.moveTo(x=100, y=100, duration=2)
'''
# 鼠标移动到相对位置
# 用2秒钟的时间,将鼠标移动到现在鼠标所在位置的相对移动,向右移动10,向下移动10
pg.move.Rel(xOffset=10, yOffset=10, duration = 2)
#一般不用pyautogui.click()这个函数,因为记不住参数,使用下面封装好的参数比较快
#双击
pg.doubleClick()
#triple click
pg.tripleClick()
#右击
pg.rightClick()
#中击
pg.middleClick()
# 鼠标当前位置滚轮滚动
pg.scroll()
# 鼠标拖拽
pg.dragTo(x=427, y=535, duration=3, button='left')
# 鼠标相对拖拽
pg.dragRel(xOffset=100, yOffset=100, duration=3, button='left', mouseDownUp=False)
#鼠标移到x=1796, y=778位置按下
pg.mouseDown(x=1796, y=778, button='left')
#鼠标移到x=2745, y=778位置松开(与mouseDown组合使用选中)
pg.mouseUp(x=2745, y=778, button='left', duration=5)
| 1,303 | 827 |
import os
import naming as n
reload(n)
import maya.cmds as mc
import System.utils as utils
reload(utils)
CLASS_NAME = 'ModuleA'
TITLE = 'Module A'
DESCRIPTION = 'Test desc for module A'
ICON = os.environ['RIGGING_TOOL_ROOT'] + '/Icons/_hand.xpm'
#cNamer = n.Name(type='blueprint', mod=CLASS_NAME)
class ModuleA:
def __init__(self, sName):
# module namespace name initialized
self.moduleName = CLASS_NAME
self.userSpecifiedName = sName
self.moduleNamespace = self.moduleName + '__' + self.userSpecifiedName
self.containerName = self.moduleNamespace + ":module_container"
self.jointInfo = [['root_joint', [0.0,0.0,0.0]], ['end_joint',[4.0,0.0,0.0]]]
print 'init module namespace: ', self.moduleNamespace
def install(self):
print '\n== MODULE install class {} using namespace {}'.format(CLASS_NAME, self.moduleNamespace)
# check if one already exists and increment the index if it does
mc.namespace(setNamespace=':')
mc.namespace(add=self.moduleNamespace)
self.jointsGrp = mc.group(em=True, n=self.moduleNamespace+':joints_grp')
self.hierarchyRepGrp = mc.group(em=True, n=self.moduleNamespace+':hierarchyRep_grp')
self.orientationControlGrp = mc.group(em=True, n=self.moduleNamespace+':orientationControls_grp')
self.moduleGrp = mc.group([self.jointsGrp, self.hierarchyRepGrp], n=self.moduleNamespace+':module_grp')
mc.container(n=self.containerName, addNode=[self.moduleGrp], includeHierarchyBelow=True)
mc.select(cl=True)
# create the joints in self.jointInfo
index = 0
joints = []
for joint in self.jointInfo:
jointName = joint[0]
jointPos = joint[1]
parentJoint = ''
if index > 0: # in case this is not the root joint, select the parent joint name
parentJoint = self.moduleNamespace+':'+self.jointInfo[index-1][0]
mc.select(parentJoint, r=True)
# create the joint and add it to the container
jointName_full = mc.joint(n=self.moduleNamespace+':'+jointName, p=jointPos)
joints.append(jointName_full)
mc.setAttr(jointName_full+'.v', 0)
utils.addNodeToContainer(self.containerName, jointName_full, ihb=True)
mc.container(self.containerName, edit=True, publishAndBind=[jointName_full+'.rotate', jointName+'_R'])
mc.container(self.containerName, edit=True, publishAndBind=[jointName_full+'.rotateOrder', jointName+'_RO'])
# orient the parent joint to the newly created joint
if index > 0:
mc.joint(parentJoint, edit=True, orientJoint='xyz', sao='yup')
index += 1
mc.parent(joints[0], self.jointsGrp, absolute=True)
# prepare the parent translation control group
self.initializeModuleTransforn(self.jointInfo[0][1])
# create translation controls for the joints
translationControls = []
for joint in joints:
translationControls.append(self.createTranslationControlAtJoint(joint))
rootJoint_pCon = mc.pointConstraint(translationControls[0], joints[0], mo=False, n=joints[0]+'_pCon')
utils.addNodeToContainer(self.containerName, rootJoint_pCon)
# setup stretchy joint segement
for index in range(len(joints) - 1):
self.setupStretchyJointSegment(joints[index], joints[index+1])
# NON DEFAULT FUNCTIONALITY
self.createOrientationControl(joints[0], joints[1])
utils.forceSceneUpdate()
# lock the container
mc.lockNode(self.containerName, lock=True, lockUnpublished=True)
def createTranslationControlAtJoint(self, joint):
# import the control sphere
posControlFile = os.environ['RIGGING_TOOL_ROOT'] + '/ControlObjects/Blueprint/translation_control.ma'
mc.file(posControlFile, i=True)
# go through and rename all the nodes based on the joint
container = mc.rename('translation_control_container', joint+'_translation_control_container')
utils.addNodeToContainer(self.containerName, container) # add it all to this instance's container
for node in mc.container(container, q=True, nodeList=True):
mc.rename(node, joint+'_'+node, ignoreShape=True)
# position the control
control = joint+'_translation_control'
# parent it to the initialized transform control group
mc.parent(control, self.moduleTransform, absolute=True)
# match the control to the joint poision
jointPos = mc.xform(joint, q=True, ws=True, t=True)
mc.xform(control, ws=True, absolute=True, t=jointPos)
# publish attributes
niceName = utils.stripLeadingNamespace(joint)[1]
attrName = niceName + '_T'
mc.container(container, edit=True, publishAndBind=[control+'.t', attrName])
mc.container(self.containerName, edit=True, publishAndBind=[container+'.'+attrName, attrName])
return control
def getTranslationControl(self, jointName):
return jointName + '_translation_control'
def setupStretchyJointSegment(self, parentJoint, childJoint):
# setup 2 joints to have an IK and stretchy joint in the segment
parentTranslationControl = self.getTranslationControl(parentJoint)
childTranslationControl = self.getTranslationControl(childJoint)
pvLoc = mc.spaceLocator(n=parentTranslationControl+'pvLoc')[0]
pvLocGrp = mc.group(pvLoc, n=pvLoc+'_pConGrp')
mc.parent(pvLocGrp, self.moduleGrp, absolute=True)
parentConst = mc.parentConstraint(parentTranslationControl, pvLocGrp, mo=False)[0]
mc.setAttr(pvLoc+'.v', 0)
mc.setAttr(pvLoc+'.ty', -0.5)
dIkNodes = utils.basicStretchyIK(parentJoint,
childJoint,
sContainer=self.containerName,
bMinLengthLock=False,
poleVectorObj=pvLoc,
sScaleCorrectionAttr=None)
ikHandle = dIkNodes['ikHandle']
rootLoc = dIkNodes['rootLoc']
endLoc = dIkNodes['endLoc']
child_pCon = mc.pointConstraint(childTranslationControl, endLoc, mo=False, n=endLoc+'_pCon')[0]
utils.addNodeToContainer(self.containerName, [pvLocGrp,child_pCon], ihb=True)
for node in [ikHandle, rootLoc, endLoc]:
mc.parent(node, self.jointsGrp)
mc.setAttr(node+'.v', 0)
self.createHierarchyRepresentation(parentJoint, childJoint)
def createHierarchyRepresentation(self, parentJoint, childJoint):
# run the createStretchyObject and parent to grp
nodes = self.createStretchyObject('/ControlObjects/Blueprint/hierarchy_representation.ma',
'hierarchy_representation_container',
'hierarchy_representation',
parentJoint,
childJoint)
constrainedGrp = nodes[2]
mc.parent(constrainedGrp, self.hierarchyRepGrp, r=True)
def createStretchyObject(self, objectRelativeFilePath, objectContainerName, objectName, parentJoint, childJoint):
# import the prepared hierarchy representation geo, connect their scale and constrain to the joints
objFile = os.environ['RIGGING_TOOL_ROOT'] + objectRelativeFilePath
mc.file(objFile, i=True)
objContainer = mc.rename(objectContainerName, parentJoint+'_'+objectContainerName)
for node in mc.container(objContainer, q=True, nodeList=True):
mc.rename(node, parentJoint+'_'+node, ignoreShape=True)
obj = parentJoint+'_'+objectName
constrainedGrp = mc.group(em=True, n=obj+'_parentConstraint_grp')
mc.parent(obj, constrainedGrp, absolute=True)
pCon = mc.parentConstraint(parentJoint, constrainedGrp, mo=False)[0]
mc.connectAttr(childJoint+'.tx', constrainedGrp+'.sx')
sCon = mc.scaleConstraint(self.moduleTransform, constrainedGrp, skip=['x'], mo=False)[0]
utils.addNodeToContainer(objContainer, [constrainedGrp, pCon, sCon], ihb=True)
utils.addNodeToContainer(self.containerName, objContainer)
return(objContainer, obj, constrainedGrp)
def initializeModuleTransforn(self, rootPos):
controlGrpFile = os.environ['RIGGING_TOOL_ROOT']+'/ControlObjects/Blueprint/controlGroup_control.ma'
mc.file(controlGrpFile, i=True)
self.moduleTransform = mc.rename('controlGroup_control', self.moduleNamespace+':module_transform')
mc.xform(self.moduleTransform, ws=True, absolute=True, t=rootPos)
utils.addNodeToContainer(self.containerName, self.moduleTransform, ihb=True)
# setup global scaling
mc.connectAttr(self.moduleTransform+'.sy', self.moduleTransform+'.sx')
mc.connectAttr(self.moduleTransform+'.sy', self.moduleTransform+'.sz')
mc.aliasAttr('globalScale', self.moduleTransform+'.sy')
mc.container(self.containerName, e=True, publishAndBind=[self.moduleTransform+'.translate', 'module_transform_T'])
mc.container(self.containerName, e=True, publishAndBind=[self.moduleTransform+'.rotate', 'module_transform_R'])
mc.container(self.containerName, e=True, publishAndBind=[self.moduleTransform+'.globalScale', 'module_transform_globalScale'])
def deleteHierarchyRepresentation(self, parentJoint):
hierarchyContainer = parentJoint + '_hierarchy_representation_container'
mc.delete(hierarchyContainer)
def createOrientationControl(self, parentJoint, childJoint):
self.deleteHierarchyRepresentation(parentJoint)
nodes = self.createStretchyObject('/ControlObjects/Blueprint/orientation_control.ma',
'orientation_control_container',
'orientation_control',
parentJoint,
childJoint)
orientationContainer = nodes[0]
orientationControl = nodes[1]
constrainedGrp = nodes[2]
mc.parent(constrainedGrp, self.orientationControlGrp, relative=True)
parentJoint_noNs = utils.stripAllNamespaces(parentJoint)[1]
attrName = parentJoint_noNs + '_orientation'
#childJoint_noNs= utils.stripAllNamespaces(child)[1]
mc.container(orientationContainer, e=True, publishAndBind=[orientationControl+'.rx', attrName])
mc.container(self.containerName, e=True, publishAndBind=[orientationContainer+'.'+attrName, attrName])
return orientationControl | 9,683 | 3,594 |
from unittest import TestCase
from mock import Mock
from ingest.exporter.metadata import MetadataResource, MetadataService, MetadataParseException, MetadataProvenance
class MetadataResourceTest(TestCase):
def test_provenance_from_dict(self):
# given:
uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d'
data = {
'uuid': {'uuid': uuid_value},
'submissionDate': 'a submission date',
'updateDate': 'an update date',
'dcpVersion': '2019-12-02T13:40:50.520Z',
'content': {
'describedBy': 'https://some-schema/1.2.3'
}
}
# when:
metadata_provenance = MetadataResource.provenance_from_dict(data)
# then:
self.assertIsNotNone(metadata_provenance)
self.assertEqual(uuid_value, metadata_provenance.document_id)
self.assertEqual('a submission date', metadata_provenance.submission_date)
self.assertEqual('2019-12-02T13:40:50.520Z', metadata_provenance.update_date)
def test_provenance_from_dict_fail_fast(self):
# given:
uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d'
data = {'uuid': uuid_value, # unexpected structure structure
'submissionDate': 'a submission date',
'updateDate': 'an update date'}
# then:
with self.assertRaises(MetadataParseException):
# when
MetadataResource.provenance_from_dict(data)
def test_from_dict(self):
# given:
uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d'
data = self._create_test_data(uuid_value)
# when:
metadata = MetadataResource.from_dict(data)
# then:
self.assertIsNotNone(metadata)
self.assertEqual('biomaterial', metadata.metadata_type)
self.assertEqual(data['content'], metadata.metadata_json)
self.assertEqual(data['dcpVersion'], metadata.dcp_version)
# and:
self.assertEqual(uuid_value, metadata.uuid)
def test_from_dict_provenance_optional(self):
# given:
uuid = '566be204-a684-4896-bda7-8dbb3e4fc65c'
data_no_provenance = self._create_test_data(uuid)
del data_no_provenance['submissionDate']
# and:
data = self._create_test_data(uuid)
# when:
metadata_no_provenance = MetadataResource.from_dict(data_no_provenance, require_provenance=False)
metadata = MetadataResource.from_dict(data, require_provenance=False)
# then:
self.assertIsNotNone(metadata_no_provenance)
self.assertEqual(uuid, metadata_no_provenance.uuid)
self.assertIsNone(metadata_no_provenance.provenance)
# and:
self.assertIsNotNone(metadata.provenance)
def test_from_dict_fail_fast_with_missing_info(self):
# given:
data = {}
# then:
with self.assertRaises(MetadataParseException):
# when
MetadataResource.from_dict(data)
def test_to_bundle_metadata(self):
# given:
uuid_value = '3f3212da-d5d0-4e55-b31d-83243fa02e0d'
data = self._create_test_data(uuid_value)
metadata = MetadataResource.from_dict(data)
# and:
data_no_provenance = self._create_test_data(uuid_value)
del data_no_provenance['submissionDate']
metadata_no_provenance = MetadataResource.from_dict(data_no_provenance, require_provenance=False)
self.assertIsNone(metadata_no_provenance.provenance)
# when
bundle_metadata = metadata.to_bundle_metadata()
bundle_metadata_no_provenance = metadata_no_provenance.to_bundle_metadata()
# then:
self.assertTrue('provenance' in bundle_metadata)
self.assertTrue(bundle_metadata['provenance'] == metadata.provenance.to_dict())
self.assertTrue(set(data['content'].keys()) <= set(
bundle_metadata.keys())) # <= operator checks if a dict is subset of another dict
# and:
self.assertIsNotNone(bundle_metadata_no_provenance)
self.assertEqual(metadata_no_provenance.metadata_json['describedBy'],
bundle_metadata_no_provenance['describedBy'])
@staticmethod
def _create_test_data(uuid_value):
return {'type': 'Biomaterial',
'uuid': {'uuid': uuid_value},
'content': {'describedBy': "http://some-schema/1.2.3",
'some': {'content': ['we', 'are', 'agnostic', 'of']}},
'dcpVersion': '6.9.1',
'submissionDate': 'a date',
'updateDate': 'another date'}
def test_get_staging_file_name(self):
# given:
metadata_resource_1 = MetadataResource(metadata_type='specimen',
uuid='9b159cae-a1fe-4cce-94bc-146e4aa20553',
metadata_json={'description': 'test'},
dcp_version='5.1.0',
provenance=MetadataProvenance('9b159cae-a1fe-4cce-94bc-146e4aa20553',
'some date', 'some other date', 1, 1))
metadata_resource_2 = MetadataResource(metadata_type='donor_organism',
uuid='38e0ee7c-90dc-438a-a0ed-071f9231f590',
metadata_json={'text': 'sample'},
dcp_version='1.0.7',
provenance=MetadataProvenance('38e0ee7c-90dc-438a-a0ed-071f9231f590',
'some date', 'some other date', '2', '2'))
# expect:
self.assertEqual('specimen_9b159cae-a1fe-4cce-94bc-146e4aa20553.json',
metadata_resource_1.get_staging_file_name())
self.assertEqual('donor_organism_38e0ee7c-90dc-438a-a0ed-071f9231f590.json',
metadata_resource_2.get_staging_file_name())
class MetadataServiceTest(TestCase):
def test_fetch_resource(self):
# given:
ingest_client = Mock(name='ingest_client')
uuid = '301636f7-f97b-4379-bf77-c5dcd9f17bcb'
raw_metadata = {'type': 'Biomaterial',
'uuid': {'uuid': uuid},
'content': {'describedBy': "http://some-schema/1.2.3",
'some': {'content': ['we', 'are', 'agnostic', 'of']}},
'dcpVersion': '2019-12-02T13:40:50.520Z',
'submissionDate': 'a submission date',
'updateDate': 'an update date'
}
ingest_client.get_entity_by_callback_link = Mock(return_value=raw_metadata)
# and:
metadata_service = MetadataService(ingest_client)
# when:
metadata_resource = metadata_service.fetch_resource(
'hca.domain.com/api/cellsuspensions/301636f7-f97b-4379-bf77-c5dcd9f17bcb')
# then:
self.assertEqual('biomaterial', metadata_resource.metadata_type)
self.assertEqual(uuid, metadata_resource.uuid)
self.assertEqual(raw_metadata['content'], metadata_resource.metadata_json)
self.assertEqual(raw_metadata['dcpVersion'], metadata_resource.dcp_version)
self.assertEqual(raw_metadata['submissionDate'], metadata_resource.provenance.submission_date)
self.assertEqual(raw_metadata['dcpVersion'], metadata_resource.provenance.update_date)
| 7,652 | 2,483 |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torchvision as tv
import matplotlib.pyplot as plt
import cv2
from torch.utils.tensorboard import SummaryWriter
import time
from collections import deque
import random
import copy
from utils import xsobel, ysobel
class Cell(nn.Module):
def __init__(self, net_arch, last_activation = lambda x: x):
super().__init__()
self.layers = nn.ModuleList([nn.Linear(a, b) for a, b in zip(net_arch[:-1], net_arch[1:])])
self.last_activation = last_activation
def forward(self, x, stochastic=True, p_dropout=0.5):
h = th.cat((x, xsobel(x), ysobel(x)), dim=1)
h = h.transpose(1, -1)
for lay in self.layers[:-1]:
h = F.relu(lay(h))
h = self.layers[-1](h)
h = h.transpose(1, -1)
h = th.nn.functional.dropout2d(h, p=p_dropout, training=stochastic)
return h | 919 | 327 |
"""
Prototype Delivery Workflow.
"""
import os
import sys
import glob
import logging
import ska_sdp_config
import dask
import distributed
from google.oauth2 import service_account
from google.cloud import storage
# Initialise logging
logging.basicConfig()
LOG = logging.getLogger("delivery")
LOG.setLevel(logging.INFO)
def ee_dask_deploy(config, pb_id, image, n_workers=1, buffers=[], secrets=[]):
"""Deploy Dask execution engine.
:param config: configuration DB handle
:param pb_id: processing block ID
:param image: Docker image to deploy
:param n_workers: number of Dask workers
:param buffers: list of buffers to mount on Dask workers
:param secrets: list of secrets to mount on Dask workers
:return: deployment ID and Dask client handle
"""
# Make deployment
deploy_id = "proc-{}-dask".format(pb_id)
values = {"image": image, "worker.replicas": n_workers}
for i, b in enumerate(buffers):
values["buffers[{}]".format(i)] = b
for i, s in enumerate(secrets):
values["secrets[{}]".format(i)] = s
deploy = ska_sdp_config.Deployment(
deploy_id, "helm", {"chart": "dask", "values": values}
)
for txn in config.txn():
txn.create_deployment(deploy)
# Wait for scheduler to become available
scheduler = deploy_id + "-scheduler." + os.environ["SDP_HELM_NAMESPACE"] + ":8786"
client = None
while client is None:
try:
client = distributed.Client(scheduler, timeout=1)
except:
pass
return deploy_id, client
def ee_dask_remove(config, deploy_id):
"""Remove Dask EE deployment.
:param config: configuration DB handle
:param deploy_id: deployment ID
"""
for txn in config.txn():
deploy = txn.get_deployment(deploy_id)
txn.delete_deployment(deploy)
def upload_directory_to_gcp(sa_file, bucket_name, src_dir, dst_dir):
"""Recursively upload contents of directory to Google Cloud Platform
:param sa_file: service account JSON file
:param bucket_name: name of the bucket on GCP
:param src_dir: local source directory
:param dst_dir: destination directory in GCP bucket
"""
# Recursively list everything in directory
src_list = sorted(glob.glob(src_dir + "/**", recursive=True))
# Get connection to GCP bucket
credentials = service_account.Credentials.from_service_account_file(sa_file)
client = storage.Client(credentials=credentials, project=credentials.project_id)
bucket = client.bucket(bucket_name)
# Upload files (ignoring directories)
for src_name in src_list:
if not os.path.isdir(src_name):
dst_name = dst_dir + "/" + src_name[len(src_dir) + 1 :]
blob = bucket.blob(dst_name)
blob.upload_from_filename(src_name)
def deliver(client, parameters):
"""Delivery function
:param client: Dask distributed client
:param parameters: parameters
"""
sa = parameters.get("service_account")
bucket = parameters.get("bucket")
buffers = parameters.get("buffers", [])
if sa is None or bucket is None:
return
sa_file = "/secret/{}/{}".format(sa.get("secret"), sa.get("file"))
tasks = []
for b in buffers:
src_dir = "/buffer/" + b.get("name")
dst_dir = b.get("destination")
tasks.append(
dask.delayed(upload_directory_to_gcp)(sa_file, bucket, src_dir, dst_dir)
)
client.compute(tasks, sync=True)
def main(argv):
"""Workflow main function."""
pb_id = argv[0]
config = ska_sdp_config.Config()
for txn in config.txn():
txn.take_processing_block(pb_id, config.client_lease)
pb = txn.get_processing_block(pb_id)
LOG.info("Claimed processing block %s", pb_id)
# Parse parameters
n_workers = pb.parameters.get("n_workers", 1)
buffers = [b.get("name") for b in pb.parameters.get("buffers", [])]
secrets = [pb.parameters.get("service_account", {}).get("secret")]
# Set state to indicate workflow is waiting for resources
LOG.info("Setting status to WAITING")
for txn in config.txn():
state = txn.get_processing_block_state(pb_id)
state["status"] = "WAITING"
txn.update_processing_block_state(pb_id, state)
# Wait for resources_available to be true
LOG.info("Waiting for resources to be available")
for txn in config.txn():
state = txn.get_processing_block_state(pb_id)
ra = state.get("resources_available")
if ra is not None and ra:
LOG.info("Resources are available")
break
txn.loop(wait=True)
# Set state to indicate workflow is running
for txn in config.txn():
state = txn.get_processing_block_state(pb_id)
state["status"] = "RUNNING"
txn.update_processing_block_state(pb_id, state)
# Deploy Dask EE
LOG.info("Deploying Dask EE")
image = "artefact.skao.int/ska-sdp-wflow-delivery:{}".format(
pb.workflow.get("version")
)
deploy_id, client = ee_dask_deploy(
config, pb.id, image, n_workers=n_workers, buffers=buffers, secrets=secrets
)
# Run delivery function
LOG.info("Starting delivery")
deliver(client, pb.parameters)
LOG.info("Finished delivery")
# Remove Dask EE deployment
LOG.info("Removing Dask EE deployment")
ee_dask_remove(config, deploy_id)
# Set state to indicate processing is finished
for txn in config.txn():
state = txn.get_processing_block_state(pb_id)
state["status"] = "FINISHED"
txn.update_processing_block_state(pb_id, state)
config.close()
if __name__ == "__main__":
main(sys.argv[1:])
| 5,708 | 1,843 |
from RLUtilities.LinearAlgebra import vec3
from RLUtilities.Maneuvers import Drive
class UtilitySystem:
def __init__(self, choices, prev_bias=0.15):
self.choices = choices
self.current_best_index = -1
self.prev_bias = prev_bias
def evaluate(self, bot):
best_index = -1
best_score = 0
for i, ch in enumerate(self.choices):
score = ch.utility(bot)
if i == self.current_best_index:
score += self.prev_bias # was previous best choice bias
if score > best_score:
best_score = score
best_index = i
if best_index != self.current_best_index:
self.reset_current()
# New choice
self.current_best_index = best_index
return self.choices[self.current_best_index], best_score
def reset_current(self):
if self.current_best_index != -1:
reset_method = getattr(self.choices[self.current_best_index], "reset", None)
if callable(reset_method):
reset_method()
def reset(self):
self.reset_current()
self.current_best_index = -1
class Atba:
def __init__(self, bot):
pass
def utility(self, bot):
return 0.5
def execute(self, bot):
bot.renderer.draw_string_3d(bot.info.my_car.pos, 1, 1, "Atba", bot.renderer.white())
drive = Drive(bot.info.my_car, bot.info.ball.pos, 1500)
drive.step(0.01666)
bot.controls = drive.controls
| 1,527 | 488 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 01/07/2015
Updated: 06/04/2018
# Description
Contains the abstract class BinaryHeap.
# References
- Slides by prof. A. Carzaniga
- Chapter 13 of Introduction to Algorithms (3rd ed.)
- http://www.math.clemson.edu/~warner/M865/HeapDelete.html
- https://docs.python.org/3/library/exceptions.html#NotImplementedError
- http://effbot.org/pyfaq/how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it.htm
- https://en.wikipedia.org/wiki/Heap_(data_structure)
- https://arxiv.org/pdf/1012.0956.pdf
- http://pymotw.com/2/heapq/
- http://stackoverflow.com/a/29197855/3924118
"""
import io
import math
from abc import ABC, abstractmethod
__all__ = ["BinaryHeap", "build_pretty_binary_heap"]
class BinaryHeap(ABC):
"""Abstract class to represent binary heaps.
This binary heap allows duplicates.
It's the responsibility of the client to ensure that inserted elements are
comparable among them.
Their order also defines their priority.
Public interface:
- size
- is_empty
- clear
- add
- contains
- delete
- merge
MinHeap, MaxHeap and MinMaxHeap all derive from this class."""
def __init__(self, ls=None):
self.heap = [] if not isinstance(ls, list) else ls
self._build_heap()
@property
def size(self) -> int:
"""Returns the number of elements in this heap.
Time complexity: O(1)."""
return len(self.heap)
def is_empty(self) -> bool:
"""Returns true if this heap is empty, false otherwise.
Time complexity: O(1)."""
return self.size == 0
def clear(self) -> None:
"""Removes all elements from this heap.
Time complexity: O(1)."""
self.heap.clear()
def add(self, x: object) -> None:
"""Adds object x to this heap.
This algorithm proceeds by placing x at an available leaf of this heap,
then bubbles up from there, in order to maintain the heap property.
Time complexity: O(log n)."""
if x is None:
raise ValueError("x cannot be None")
self.heap.append(x)
if self.size > 1:
self._push_up(self.size - 1)
def contains(self, x: object) -> bool:
"""Returns true if x is in this heap, false otherwise.
Time complexity: O(n)."""
if x is None:
raise ValueError("x cannot be None")
return self._index(x) != -1
def delete(self, x: object) -> None:
"""Removes the first found x from this heap.
If x is not in this heap, LookupError is raised.
Time complexity: O(n)."""
if x is None:
raise ValueError("x cannot be None")
i = self._index(x)
if i == -1:
raise LookupError("x not found")
# self has at least one element.
if i == self.size - 1:
self.heap.pop()
else:
self._swap(i, self.size - 1)
self.heap.pop()
self._push_down(i)
self._push_up(i)
def merge(self, o: "Heap") -> None:
"""Merges this heap with the o heap.
Time complexity: O(n + m)."""
self.heap += o.heap
self._build_heap()
@abstractmethod
def _push_down(self, i: int) -> None:
"""Classical "heapify" operation for heaps."""
pass
@abstractmethod
def _push_up(self, i: int) -> None:
"""Classical reverse-heapify operation for heaps."""
pass
def _build_heap(self) -> list:
"""Builds the heap data structure using Robert Floyd's heap construction
algorithm.
Floyd's algorithm is optimal as long as complexity is expressed in terms
of sets of functions described via the asymptotic symbols O, Θ and Ω.
Indeed, its linear complexity Θ(n), both in the worst and best case,
cannot be improved as each object must be examined at least once.
Floyd's algorithm was invented in 1964 as an improvement of the
construction phase of the classical heap-sort algorithm introduced
earlier that year by Williams J.W.J.
Time complexity: Θ(n)."""
if self.heap:
for index in range(len(self.heap) // 2, -1, -1):
self._push_down(index)
def _index(self, x: object) -> int:
"""Returns the index of x in this heap if x is in this heap, otherwise
it returns -1.
Time complexity: O(n)."""
for i, node in enumerate(self.heap):
if node == x:
return i
return -1
def _swap(self, i: int, j: int) -> None:
"""Swaps elements at indexes i and j.
Time complexity: O(1)."""
assert self._is_good_index(i) and self._is_good_index(j)
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
def _left_index(self, i: int) -> int:
"""Returns the left child's index of the node at index i, if it exists,
otherwise this function returns -1.
Time complexity: O(1)."""
assert self._is_good_index(i)
left = i * 2 + 1
return left if self._is_good_index(left) else -1
def _right_index(self, i: int) -> int:
"""Returns the right child's index of the node at index i, if it exists,
otherwise this function returns -1.
Time complexity: O(1)."""
assert self._is_good_index(i)
right = i * 2 + 2
return right if self._is_good_index(right) else -1
def _parent_index(self, i: int) -> int:
"""Returns the parent's index of the node at index i.
If i = 0, then -1 is returned, because the root has no parent.
Time complexity: O(1)."""
assert self._is_good_index(i)
return -1 if i == 0 else (i - 1) // 2
def _is_good_index(self, i: int) -> bool:
"""Returns true if i is in the bounds of elf.heap, false otherwise.
Time complexity: O(1)."""
return False if (i < 0 or i >= self.size) else True
def __str__(self):
return str(self.heap)
def __repr__(self):
return build_pretty_binary_heap(self.heap)
def build_pretty_binary_heap(heap: list, total_width=36, fill=" ") -> str:
"""Returns a string (which can be printed) representing heap as a tree.
To increase/decrease the horizontal space between nodes, just
increase/decrease the float number h_space.
To increase/decrease the vertical space between nodes, just
increase/decrease the integer number v_space.
Note: v_space must be an integer.
To change the length of the line under the heap, you can simply change the
line_length variable."""
if not isinstance(heap, list):
raise TypeError("heap must be an list object")
if len(heap) == 0:
return "Nothing to print: heap is empty."
output = io.StringIO()
last_row = -1
h_space = 3.0
v_space = 2
for i, heap_node in enumerate(heap):
if i != 0:
row = int(math.floor(math.log(i + 1, 2)))
else:
row = 0
if row != last_row:
output.write("\n" * v_space)
columns = 2 ** row
column_width = int(math.floor((total_width * h_space) / columns))
output.write(str(heap_node).center(column_width, fill))
last_row = row
s = output.getvalue() + "\n"
line_length = total_width + 15
s += ('-' * line_length + "\n")
return s
| 7,516 | 2,433 |
from .views import API
from django.urls import path
urlpatterns = [
path('', API.as_view()),
]
| 106 | 37 |
# -*- coding: utf-8 -*-
from trytond.pool import PoolMeta
from trytond.model import fields
from trytond.pyson import Eval, Bool, Not
__all__ = ['Product']
__metaclass__ = PoolMeta
class Product:
"Product"
__name__ = 'product.product'
country_of_origin = fields.Many2One(
'country.country', 'Country of Origin',
)
customs_value = fields.Numeric(
"Customs Value",
states={
'invisible': Bool(Eval('use_list_price_as_customs_value')),
'required': Not(Bool(Eval('use_list_price_as_customs_value')))
}, depends=['use_list_price_as_customs_value'],
)
use_list_price_as_customs_value = fields.Boolean(
"Use List Price As Customs Value ?"
)
customs_value_used = fields.Function(
fields.Numeric("Customs Value Used"),
'get_customs_value_used'
)
customs_description = fields.Text(
"Customs Description",
states={
'invisible': Bool(Eval("use_name_as_customs_description")),
'required': Not(Bool(Eval("use_name_as_customs_description")))
},
depends=["use_name_as_customs_description"]
)
use_name_as_customs_description = fields.Boolean(
"Use Name as Customs Description ?"
)
customs_description_used = fields.Function(
fields.Text("Customs Description Used"),
"get_customs_description_used"
)
@classmethod
def get_customs_description_used(cls, products, name):
return {
product.id: (
product.name if product.use_name_as_customs_description else
product.customs_description
)
for product in products
}
@staticmethod
def default_use_name_as_customs_description():
return True
@staticmethod
def default_use_list_price_as_customs_value():
return True
@classmethod
def get_customs_value_used(cls, products, name):
return {
product.id: (
product.list_price if product.use_list_price_as_customs_value
else product.customs_value
)
for product in products
}
| 2,190 | 664 |
from ParadoxTrading.Chart import Wizard
from ParadoxTrading.Fetch.ChineseFutures import FetchDominantIndex
from ParadoxTrading.Indicator import RSI
fetcher = FetchDominantIndex()
market = fetcher.fetchDayData('20100701', '20170101', 'rb')
rsi = RSI(14).addMany(market).getAllData()
wizard = Wizard()
price_view = wizard.addView('price', _view_stretch=3)
price_view.addLine('market', market.index(), market['closeprice'])
sub_view = wizard.addView('sub')
sub_view.addLine('rsi', rsi.index(), rsi['rsi'])
wizard.show()
| 523 | 203 |
import fractions
from pprint import pprint
lcm_limit = 32
octave_limit = 4
candidates = [(x, y) for x in range(1, lcm_limit + 1) for y in range(1, lcm_limit + 1)]
candidates = [c for c in candidates
if fractions.gcd(c[0], c[1]) == 1
and c[0] * c[1] <= lcm_limit
and 1 / octave_limit <= c[0] / c[1] <= octave_limit]
candidates.sort(key=lambda c: c[0] / c[1])
pprint(candidates)
print(len(candidates)) | 406 | 185 |
#
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
curr = dummyHead = ListNode(0)
curr.next = head
while curr.next and curr.next.next:
l = curr.next
r = l.next
curr.next, r.next, l.next = r, l, r.next
curr = l
return dummyHead.next
# @lc code=end
| 573 | 205 |
#######################################################
#
# CEOControl.py
# Python implementation of the Class CEOControl
# Generated by Enterprise Architect
# Created on: 16-5��-2019 12:06:10
# Original author: ����
#
#######################################################
from Models.Statement import Statement
from Models.Contract import Contract
from Controllers.User import User
from Controllers.Login import Login
class CEOControl(User):
def __init__(self,ID):
super().__init__()
self.__identity = 'ceo'
self.__ID = ID
self.m_Statement = Statement()
self.__contractCon = Contract()
def set_contract_ceoaffirm_by_id(self,user_id, ceoaffirm):
self.__contractCon.set_contract_ceoaffirm_by_id(user_id, ceoaffirm)
def set_contract_ceosign_by_id(self,user_id, ceosign):
self.__contractCon.set_contract_ceosign_by_id(user_id, ceosign)
def check_all_information(self):
pass
def get_all_contracts(self):
return self.m_Statement.contracts
def get_all_receipts(self):
return self.m_Statement.receipts
def get_all_receivable(self):
return self.m_Statement.receivable
def confirm_contract(self):
pass
def login(self,name,password,identity):
super().login(name,password,identity)
def registration(self):
pass
def remind_arrearage(self):
pass
def remind_expiration_con(self):
pass
def sign_contract(self):
pass
if __name__ == '__main__':
ceo = CEOControl()
ceo.login('as',12,'ceo') | 1,593 | 526 |
import abc
import pathlib
from importlib import util as importlib_util
from typing import Optional, Protocol
from plugins.models import MPlugin
class TopNavProtocol(Protocol):
@property
def public_has_top_nav(self) -> bool:
"""Does this plugin have public facing top nav?"""
return False
class Plugin(abc.ABC, TopNavProtocol):
name: str
description: str
# A unique namespaced identifier for the plugin
identifier: str
def is_enabled(self) -> bool:
return MPlugin.objects.filter(identifier=self.identifier).values_list("enabled", flat=True).first() or False
@property
def plugin_module(self) -> str:
"""Return the python module path to the plugin's module"""
return ".".join(self.__module__.split(".")[:-1])
@property
def settings_url(self) -> str:
"""The main URL for configuring the plugin.
Plugins that do not provide any configuration via the admin should return a blank string.
"""
return ""
def render_navigation(
self,
*,
context,
render_location: str,
) -> str:
"""Render the public facing navigation menu item."""
return ""
@property
def urls(self) -> Optional[str]:
"""Return the path to the _public_ url configuration for a plugin"""
# TODO: Make this check for a urls.py and return None if not exists
return f"{self.plugin_module}.urls"
@property
def admin_urls(self) -> Optional[str]:
"""Return the path to the _admin_ url configuration for a plugin"""
return f"{self.plugin_module}.admin_urls"
@property
def has_migrations(self) -> bool:
"""Check if a plugin has migration directory.
Uses pathlib instead of importlib to avoid importing modules.
"""
module_spec = importlib_util.find_spec(self.__module__)
if not module_spec or not module_spec.origin:
return False
migration_module = pathlib.Path(module_spec.origin).parent / "migrations"
return migration_module.is_dir()
| 2,104 | 570 |
# Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если
# фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите
# численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
earnings = float(input("Укажите сумму выручки: "))
expenses = float(input("Укажите сумму расходов: "))
if earnings > expenses: # если прибыль больше расходов
employee = int(input("Сколько служащих в вашей организации: "))
global_Profit = earnings - expenses # выручка
employee_Profit = global_Profit / employee # сколько денег зарабатывает один сотрудник
print(f"Фирма в прибыли {global_Profit:.2f}¥, с рентабельностью {earnings / expenses:.2f}%")
print(f"Примерно {employee_Profit:.2f}¥ зарабатывает для вас каждый служащий.")
elif earnings == expenses:
print("У вас бестолковая организация, она работает 'в ноль'.")
else:
print("У вас убытки.")
| 1,102 | 422 |
import os
from abc import ABCMeta, abstractmethod
from types import MappingProxyType
import dask.dataframe
import pandas as pd
class AbstractDataFrameFormat:
"""
Provides helper functions to serialize and deserialize pandas and
dask dataframes.
Instances of such classes can define their own default options via the
constructor. If none are specified, the library default are taken as
default options. Default options can be overwritten in the calling
functions.
"""
__metaclass__ = ABCMeta
def __init__(self, default_reading_options=None,
default_writing_options=None):
self.default_reading_options = default_reading_options
self.default_writing_options = default_writing_options
@abstractmethod
def read_df(self, file_path, options=None):
raise NotImplementedError
@abstractmethod
def write_df(self, df, file_path, options=None):
raise NotImplementedError
@abstractmethod
def read_dask_df(self, directory, options=None):
raise NotImplementedError
@abstractmethod
def write_dask_df(self, ddf, directory, options=None,
compute=False):
raise NotImplementedError
@abstractmethod
def format_extension(self):
raise NotImplementedError
@abstractmethod
def _library_default_reading_options(self):
raise NotImplementedError
@abstractmethod
def _library_default_writing_options(self):
raise NotImplementedError
def get_default_reading_options(self):
"""
Default options used, if no options are passed in the read functions
:return: dictionary with options
"""
if self.default_reading_options:
return self.default_reading_options
return self._library_default_reading_options()
def get_default_writing_options(self):
"""
Default options used, if no options are passed in the write functions
:return: dictionary with options
"""
if self.default_writing_options:
return self.default_writing_options
return self._library_default_writing_options()
@staticmethod
def _get_effective_options(params, defaults):
if not params:
effective_params = defaults
else:
effective_params = dict(defaults, **params)
return effective_params
class ParquetDataFrameFormat(AbstractDataFrameFormat):
DEFAULT_ENGINE = 'pyarrow'
def read_df(self, file_path, options=None):
e = ParquetDataFrameFormat._get_effective_options(options,
self.get_default_reading_options())
return pd.read_parquet(file_path, **e)
def write_df(self, df, file_path, options=None):
e = self._get_effective_options(options,
self.get_default_writing_options())
df.to_parquet(file_path, **e)
def read_dask_df(self, directory, options=None):
in_pattern = os.path.join(directory,
'*.{}'.format(self.format_extension()))
e = ParquetDataFrameFormat._get_effective_options(options,
self.get_default_reading_options())
return dask.dataframe.read_parquet(str(in_pattern), **e)
def write_dask_df(self, ddf, directory, options=None,
compute=False):
e = ParquetDataFrameFormat._get_effective_options(options,
self.get_default_writing_options())
return ddf.to_parquet(str(directory), compute=compute, **e)
def format_extension(self):
return "parquet"
def _library_default_reading_options(self):
return MappingProxyType({'engine': self.DEFAULT_ENGINE})
def _library_default_writing_options(self):
return MappingProxyType({'engine': self.DEFAULT_ENGINE,
'compression': 'snappy'})
class HdfDataFrameFormat(AbstractDataFrameFormat):
DEFAULT_KEY = 'data'
def read_df(self, file_path, options=None):
eff = HdfDataFrameFormat._get_effective_options(options,
self.get_default_reading_options())
return pd.read_hdf(file_path, **eff)
def write_df(self, df, file_path, options=None):
eff = HdfDataFrameFormat._get_effective_options(options,
self.get_default_writing_options())
df.to_hdf(file_path, **eff)
def read_dask_df(self, directory, options=None):
in_pattern = os.path.join(directory,
'*.{}'.format(self.format_extension()))
e = HdfDataFrameFormat._get_effective_options(options,
self.get_default_reading_options())
return dask.dataframe.read_hdf(str(in_pattern), **e)
def write_dask_df(self, ddf, directory, options=None,
compute=False):
e = HdfDataFrameFormat._get_effective_options(options,
self.get_default_writing_options())
out_pattern = os.path.join(directory,
'part-*.{}'.format(self.format_extension()))
return ddf.to_hdf(out_pattern, compute=compute, **e)
def format_extension(self):
return 'h5'
def _library_default_reading_options(self):
return MappingProxyType({'mode': 'r', 'key': self.DEFAULT_KEY})
def _library_default_writing_options(self):
return MappingProxyType({'key': self.DEFAULT_KEY, 'format': 'table',
'complib': 'blosc:lz4', 'complevel': 5})
| 5,825 | 1,555 |
print("This program calculates the area of a trapezoid.")
height = float(input("Enter height of trapezoid:"))
top_base_length = float(input("Enter top length of trapezoid:"))
bottom_base_length = float(input("Enter bottom length of trapezoid:"))
area_of_trapezoid = .5 * (top_base_length + bottom_base_length) * height
print ("The area of the trapezoid is," , area_of_trapezoid) | 378 | 125 |
"""Define actions decorator."""
import inspect
import pandas as pd
from typing import cast
from datetime import date, datetime
from typing import Callable
from pumpwood_communication.exceptions import PumpWoodActionArgsException
class Action:
"""Define a Action class to be used in decorator action."""
def __init__(self, func: Callable, info: str, auth_header: str = None):
"""."""
signature = inspect.signature(func)
function_parameters = signature.parameters
parameters = {}
is_static_function = True
for key in function_parameters.keys():
if key in ['self', 'cls', auth_header]:
if key == "self":
is_static_function = False
continue
param = function_parameters[key]
if param.annotation == inspect.Parameter.empty:
if inspect.Parameter.empty:
param_type = "Any"
else:
param_type = type(param.default).__name__
else:
param_type = param.annotation \
if type(param.annotation) == str \
else param.annotation.__name__
parameters[key] = {
"required": param.default is inspect.Parameter.empty,
"type": param_type
}
if param.default is not inspect.Parameter.empty:
parameters[key]['default_value'] = param.default
self.action_name = func.__name__
self.is_static_function = is_static_function
self.parameters = parameters
self.info = info
self.auth_header = auth_header
def to_dict(self):
"""Return dict representation of the action."""
return {
"action_name": self.action_name,
"is_static_function": self.is_static_function,
"info": self.info,
"parameters": self.parameters}
def action(info: str = "", auth_header: str = None):
"""
Define decorator that will convert the function into a rest action.
Args:
info: Just an information about the decorated function that will be
returned in GET /rest/<model_class>/actions/.
Kwargs:
request_user (str): Variable that will receive logged user.
Returns:
func: Action decorator.
"""
def action_decorator(func):
func.is_action = True
func.action_object = Action(
func=func, info=info, auth_header=auth_header)
return func
return action_decorator
def load_action_parameters(func: Callable, parameters: dict, request):
"""Cast arguments to its original types."""
signature = inspect.signature(func)
function_parameters = signature.parameters
# Loaded parameters for action run
return_parameters = {}
# Errors found when processing the parameters
errors = {}
# Unused parameters, passed but not in function
unused_params = set(parameters.keys()) - set(function_parameters.keys())
# The request user parameter, set the logged user
auth_header = func.action_object.auth_header
if len(unused_params) != 0:
errors["unused args"] = {
"type": "unused args",
"message": list(unused_params)}
for key in function_parameters.keys():
# pass if arguments are self and cls for classmethods
if key in ['self', 'cls']:
continue
# If arguent is the request user one, set with the logged user
if key == auth_header:
token = request.headers.get('Authorization')
return_parameters[key] = {'Authorization': token}
continue
param_type = function_parameters[key]
par_value = parameters.get(key)
if par_value is not None:
try:
if param_type.annotation == date:
return_parameters[key] = pd.to_datetime(par_value).date()
elif param_type.annotation == datetime:
return_parameters[key] = \
pd.to_datetime(par_value).to_pydatetime()
else:
return_parameters[key] = param_type.annotation(par_value)
# If any error ocorrur then still try to cast data from python
# typing
except Exception:
try:
return_parameters[key] = return_parameters[key] = cast(
param_type.annotation, par_value)
except Exception as e:
errors[key] = {
"type": "unserialize",
"message": str(e)}
# If parameter is not passed and required return error
elif param_type.default is inspect.Parameter.empty:
errors[key] = {
"type": "nodefault",
"message": "not set and no default"}
# Raise if there is any error in serilization
if len(errors.keys()) != 0:
template = "[{key}]: {message}"
error_msg = "error when unserializing function arguments:\n"
error_list = []
for key in errors.keys():
error_list.append(template.format(
key=key, message=errors[key]["message"]))
error_msg = error_msg + "\n".join(error_list)
raise PumpWoodActionArgsException(
status_code=400, message=error_msg, payload={
"arg_errors": errors})
return return_parameters
| 5,498 | 1,395 |
# A binary linear classifier for MNIST digits.
#
# Poses a binary classification problem - is this image showing digit D (for
# some D, for example "4"); trains a linear classifier to solve the problem.
#
# Eli Bendersky (http://eli.thegreenplace.net)
# This code is in the public domain
from __future__ import print_function
import argparse
import numpy as np
import sys
from mnist_dataset import *
from regression_lib import *
if __name__ == '__main__':
argparser = argparse.ArgumentParser()
argparser.add_argument('--type',
choices=['binary', 'logistic'],
default='logistic',
help='Type of classification: binary (yes/no result)'
'or logistic (probability of "yes" result).')
argparser.add_argument('--set-seed', default=-1, type=int,
help='Set random seed to this number (if > 0).')
argparser.add_argument('--nsteps', default=150, type=int,
help='Number of steps for gradient descent.')
argparser.add_argument('--recognize-digit', default=4, type=int,
help='Digit to recognize in training.')
argparser.add_argument('--display-test', default=-1, type=int,
help='Display this image from the test data '
'set and exit.')
argparser.add_argument('--normalize', action='store_true', default=False,
help='Normalize data: (x-mu)/sigma.')
argparser.add_argument('--report-mistakes', action='store_true',
default=False,
help='Report all mistakes made in classification.')
args = argparser.parse_args()
if args.set_seed > 0:
np.random.seed(args.set_seed)
# Load MNIST data into memory; this may download the MNIST dataset from
# the web if not already on disk.
(X_train, y_train), (X_valid, y_valid), (X_test, y_test) = get_mnist_data()
if args.display_test > -1:
display_mnist_image(X_test[args.display_test],
y_test[args.display_test])
sys.exit(1)
if args.normalize:
print('Normalizing data...')
X_train_normalized, mu, sigma = feature_normalize(X_train)
X_train_augmented = augment_1s_column(X_train_normalized)
X_valid_augmented = augment_1s_column((X_valid - mu) / sigma)
X_test_augmented = augment_1s_column((X_test - mu) / sigma)
else:
X_train_augmented = augment_1s_column(X_train)
X_valid_augmented = augment_1s_column(X_valid)
X_test_augmented = augment_1s_column(X_test)
# Convert y_train to binary "is this a the digit D", with +1 for D, -1
# otherwise. Also reshape it into a column vector as regression_lib expects.
D = args.recognize_digit
print('Training for digit', D)
y_train_binary = convert_y_to_binary(y_train, D)
y_valid_binary = convert_y_to_binary(y_valid, D)
y_test_binary = convert_y_to_binary(y_test, D)
# Hyperparameters.
LEARNING_RATE = 0.08
REG_BETA=0.03
if args.type == 'binary':
print('Training binary classifier with hinge loss...')
lossfunc = lambda X, y, theta: hinge_loss(X, y,
theta, reg_beta=REG_BETA)
else:
print('Training logistic classifier with cross-entropy loss...')
lossfunc = lambda X, y, theta: cross_entropy_loss_binary(
X, y, theta, reg_beta=REG_BETA)
n = X_train_augmented.shape[1]
gi = gradient_descent(X_train_augmented,
y_train_binary,
init_theta=np.random.randn(n, 1),
lossfunc=lossfunc,
batch_size=256,
nsteps=args.nsteps,
learning_rate=LEARNING_RATE)
for i, (theta, loss) in enumerate(gi):
if i % 50 == 0 and i > 0:
print(i, loss)
# We use predict_binary for both binary and logistic classification.
# See comment on predict_binary to understand why it works for
# logistic as well.
yhat = predict_binary(X_train_augmented, theta)
yhat_valid = predict_binary(X_valid_augmented, theta)
print('train accuracy =', np.mean(yhat == y_train_binary))
print('valid accuracy =', np.mean(yhat_valid == y_valid_binary))
print('After {0} training steps...'.format(args.nsteps))
print('loss =', loss)
yhat_valid = predict_binary(X_valid_augmented, theta)
yhat_test = predict_binary(X_test_augmented, theta)
print('valid accuracy =', np.mean(yhat_valid == y_valid_binary))
print('test accuracy =', np.mean(yhat_test == y_test_binary))
# For logistic, get predicted probabilities as well.
if args.type == 'logistic':
yhat_test_prob = predict_logistic_probability(X_test_augmented, theta)
if args.report_mistakes:
for i in range(yhat_test.size):
if yhat_test[i][0] != y_test_binary[i][0]:
print('@ {0}: predict {1}, actual {2}'.format(
i, yhat_test[i][0], y_test_binary[i][0]), end='')
if args.type == 'logistic':
print('; prob={0}'.format(yhat_test_prob[i][0]))
else:
print('')
| 5,426 | 1,673 |
from views import displayUserProfile
| 37 | 8 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
(https://www.kaggle.com/c/ashrae-energy-prediction).
Train shape:(590540,394),identity(144233,41)--isFraud 3.5%
Test shape:(506691,393),identity(141907,41)
############### TF Version: 1.13.1/Python Version: 3.7 ###############
"""
import os
import math
import random
import warnings
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
warnings.filterwarnings('ignore')
# make all processes deterministic/固定随机数生成器的种子
# environ是一个字符串所对应环境的映像对象,PYTHONHASHSEED为其中的环境变量
# Python会用一个随机的种子来生成str/bytes/datetime对象的hash值;
# 如果该环境变量被设定为一个数字,它就被当作一个固定的种子来生成str/bytes/datetime对象的hash值
def set_seed(seed=0):
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
# reduce memory for dataframe/优化dataframe数据格式,减少内存占用
def reduce_mem_usage(df, verbose=True):
numerics = ["int16", "int32", "int64", "float16", "float32", "float64"]
start_mem = df.memory_usage().sum() / 1024**2
for col in df.columns:
col_type = df[col].dtypes
if col_type in numerics:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == "int":
if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
df[col] = df[col].astype(np.int8)
elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
df[col] = df[col].astype(np.int16)
elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
df[col] = df[col].astype(np.int32)
elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
df[col] = df[col].astype(np.int64)
else:
if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
df[col] = df[col].astype(np.float16)
elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
df[col] = df[col].astype(np.float32)
else:
df[col] = df[col].astype(np.float64)
end_mem = df.memory_usage().sum() / 1024**2
reduction = 100*(start_mem-end_mem)/start_mem
if verbose:
print("Default Mem. {:.2f} Mb, Optimized Mem. {:.2f} Mb, Reduction {:.1f}%".
format(start_mem, end_mem, reduction))
return df
if __name__ == "__main__":
print("========== 1.Set random seed ...")
SEED = 42
set_seed(SEED)
LOCAL_TEST = False
print("========== 2.Load csv data ...")
dir_data_csv = os.getcwd() + "\\great-energy-predictor\\"
train_df = pd.read_csv(dir_data_csv + "\\train.csv")
infer_df = pd.read_csv(dir_data_csv + "\\test.csv")
build_df = pd.read_csv(dir_data_csv + "\\building_metadata.csv")
train_weat_df = pd.read_csv(dir_data_csv + "\\weather_train.csv")
infer_weat_df = pd.read_csv(dir_data_csv + "\\weather_test.csv")
print('#' * 30)
print('Main data:', list(train_df), train_df.info())
print('#' * 30)
print('Buildings data:', list(build_df), build_df.info())
print('#' * 30)
print('Weather data:', list(train_weat_df), train_weat_df.info())
print('#' * 30)
for df in [train_df, infer_df, train_weat_df, infer_weat_df]:
df["timestamp"] = pd.to_datetime(df["timestamp"])
for df in [train_df, infer_df]:
df["DT_M"] = df["timestamp"].dt.month.astype(np.int8)
df["DT_W"] = df["timestamp"].dt.weekofyear.astype(np.int8)
df["DT_D"] = df["timestamp"].dt.dayofyear.astype(np.int16)
df["DT_hour"] = df["timestamp"].dt.hour.astype(np.int8)
df["DT_day_week"] = df["timestamp"].dt.dayofweek.astype(np.int8)
df["DT_day_month"] = df["timestamp"].dt.day.astype(np.int8)
df["DT_week_month"] = df["timestamp"].dt.day / 7
df["DT_week_month"] = df["DT_week_month"].apply(lambda x: math.ceil(x)).astype(np.int8)
print("========== 3.ETL tran categorical feature [String] ...")
build_df['primary_use'] = build_df['primary_use'].astype('category')
build_df['floor_count'] = build_df['floor_count'].fillna(0).astype(np.int8)
build_df['year_built'] = build_df['year_built'].fillna(-999).astype(np.int16)
le = LabelEncoder()
build_df['primary_use'] = build_df['primary_use'].astype(str)
build_df['primary_use'] = le.fit_transform(build_df['primary_use']).astype(np.int8)
do_not_convert = ['category', 'datetime64[ns]', 'object']
for df in [train_df, infer_df, build_df, train_weat_df, infer_weat_df]:
original = df.copy()
df = reduce_mem_usage(df)
for col in list(df):
if df[col].dtype.name not in do_not_convert:
if (df[col] - original[col]).sum() != 0:
df[col] = original[col]
print('Bad transformation', col)
print('#' * 30)
print('Main data:', list(train_df), train_df.info())
print('#' * 30)
print('Buildings data:', list(build_df), build_df.info())
print('#' * 30)
print('Weather data:', list(train_weat_df), train_weat_df.info())
print('#' * 30)
print("========== 4.Save pkl ...")
train_df.to_pickle("train.pkl")
infer_df.to_pickle("infer.pkl")
build_df.to_pickle("build.pkl")
train_weat_df.to_pickle("weather_train.pkl")
infer_weat_df.to_pickle("weather_infer.pkl")
| 5,409 | 2,190 |
import matplotlib.pyplot as plt
from base.base_trainer import BaseTrainer
from base.base_dataset import BaseADDataset
from base.base_net import BaseNet
import seaborn as sns
from torch.utils.data.dataloader import DataLoader
from sklearn.metrics import roc_auc_score, confusion_matrix, average_precision_score, roc_curve, precision_recall_curve
import logging
import time
import torch
import torch.optim as optim
import numpy as np
class DeepSADTrainer(BaseTrainer):
def __init__(self, c, eta: float, optimizer_name: str = 'adam', lr: float = 0.001, n_epochs: int = 150,
lr_milestones: tuple = (), batch_size: int = 128, weight_decay: float = 1e-6, device: str = 'cuda',
n_jobs_dataloader: int = 0):
super().__init__(optimizer_name, lr, n_epochs, lr_milestones, batch_size, weight_decay, device,
n_jobs_dataloader)
# Deep SAD parameters
self.c = torch.tensor(c, device=self.device) if c is not None else None
self.eta = eta
# Optimization parameters
self.eps = 1e-6
# Results
self.train_time = None
self.test_auc = None
self.test_auprc = None
self.test_confusion_matrix = None
self.test_time = None
self.test_scores = None
self.roc_x = None
self.roc_y = None
self.prec = None
self.rec = None
def train(self, dataset: BaseADDataset, net: BaseNet):
logger = logging.getLogger()
# Get train data loader
train_loader, _ = dataset.loaders(batch_size=self.batch_size, num_workers=self.n_jobs_dataloader)
# Set device for network
net = net.to(self.device)
# Set optimizer (Adam optimizer for now)
optimizer = optim.Adam(net.parameters(), lr=self.lr, weight_decay=self.weight_decay)
# Set learning rate scheduler
scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=self.lr_milestones, gamma=0.1)
# Initialize hypersphere center c (if c not loaded)
if self.c is None:
logger.info('Initializing center c...')
self.c = self.init_center_c(train_loader, net)
logger.info('Center c initialized.')
# Training
logger.info('Starting training...')
start_time = time.time()
net.train()
for epoch in range(self.n_epochs):
scheduler.step()
if epoch in self.lr_milestones:
logger.info(' LR scheduler: new learning rate is %g' % float(scheduler.get_lr()[0]))
epoch_loss = 0.0
n_batches = 0
epoch_start_time = time.time()
for data in train_loader:
inputs, _, semi_targets, _ = data
inputs, semi_targets = inputs.to(self.device), semi_targets.to(self.device)
# Zero the network parameter gradients
optimizer.zero_grad()
# Update network parameters via backpropagation: forward + backward + optimize
outputs = net(inputs)
dist = torch.sum((outputs - self.c) ** 2, dim=1)
losses = torch.where(semi_targets == 0, dist, self.eta * ((dist + self.eps) ** semi_targets.float()))
loss = torch.mean(losses)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
n_batches += 1
# log epoch statistics
epoch_train_time = time.time() - epoch_start_time
logger.info(f'| Epoch: {epoch + 1:03}/{self.n_epochs:03} | Train Time: {epoch_train_time:.3f}s '
f'| Train Loss: {epoch_loss / n_batches:.6f} |')
self.train_time = time.time() - start_time
logger.info('Training Time: {:.3f}s'.format(self.train_time))
logger.info('Finished training.')
return net
def test(self, dataset: BaseADDataset, net: BaseNet):
logger = logging.getLogger()
# Get test data loader
_, test_loader = dataset.loaders(batch_size=self.batch_size, num_workers=self.n_jobs_dataloader)
# Set device for network
net = net.to(self.device)
# Testing
logger.info('Starting testing...')
epoch_loss = 0.0
n_batches = 0
start_time = time.time()
idx_label_score = []
net.eval()
with torch.no_grad():
for data in test_loader:
inputs, labels, semi_targets, idx = data
inputs = inputs.to(self.device)
labels = labels.to(self.device)
semi_targets = semi_targets.to(self.device)
idx = idx.to(self.device)
outputs = net(inputs)
dist = torch.sum((outputs - self.c) ** 2, dim=1)
losses = torch.where(semi_targets == 0, dist, self.eta * ((dist + self.eps) ** semi_targets.float()))
loss = torch.mean(losses)
scores = dist
# Save triples of (idx, label, score) in a list
idx_label_score += list(zip(idx.cpu().data.numpy().tolist(),
labels.cpu().data.numpy().tolist(),
scores.cpu().data.numpy().tolist()))
epoch_loss += loss.item()
n_batches += 1
self.test_time = time.time() - start_time
self.test_scores = idx_label_score
score_array = np.array(self.test_scores, dtype=np.int32)
# Get predictions
prediction_array = np.array([int(abs(p - 1) < abs(p)) for p in list(score_array[:, 2])], dtype=np.int32)
gt_array = score_array[:, 1]
# Compute AUC
_, labels, scores = zip(*idx_label_score)
labels = np.array(labels)
scores = np.array(scores)
self.test_auc = roc_auc_score(labels, scores)
self.test_auprc = average_precision_score(labels, scores)
self.roc_x, self.roc_y, _ = roc_curve(labels, scores)
self.prec, self.rec, _ = precision_recall_curve(labels, scores)
self.test_confusion_matrix = confusion_matrix(gt_array, prediction_array)
sns.heatmap(self.test_confusion_matrix, annot=True, fmt='.2%')
plt.savefig("cm_deepsad.png")
plt.close()
# Log results
logger.info('Test Loss: {:.6f}'.format(epoch_loss / n_batches))
logger.info('Test AUROC: {:.2f}%'.format(100. * self.test_auc))
logger.info('Test AUPRC: {:.2f}%'.format(100. * self.test_auprc))
logger.info('Test Time: {:.3f}s'.format(self.test_time))
logger.info('Finished testing.')
####### ROC and AUC ############
lw = 2
plt.figure()
####### ROC ############
plt.plot(self.roc_x, self.roc_y, color='darkorange',
lw=lw, label='ROC curve (AUC = %0.2f)' % self.test_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--', label="No-skill classifier")
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate ')
plt.ylabel('True Positive Rate ')
plt.title('ROC (Receiver Operating Characteristic curve)')
plt.legend(loc="lower right")
plt.show()
plt.savefig('roc_auc.png')
plt.close()
####### PR ############
plt.figure()
plt.plot(self.prec, self.rec, color='darkorange',
lw=lw, label='PR curve (AUC = %0.2f)' % self.test_auprc)
plt.plot([0, 1], [0.0526, 0.0526], color='navy', lw=lw, linestyle='--', label="No-skill classifier")
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('Recall ')
plt.ylabel('Precision ')
plt.title('PRC (Precision-Recall curve)')
plt.legend(loc="lower right")
plt.show()
plt.savefig('pr_auc.png')
plt.close()
def init_center_c(self, train_loader: DataLoader, net: BaseNet, eps=0.1):
"""Initialize hypersphere center c as the mean from an initial forward pass on the data."""
n_samples = 0
c = torch.zeros(net.rep_dim, device=self.device)
net.eval()
with torch.no_grad():
for data in train_loader:
# get the inputs of the batch
inputs, _, _, _ = data
inputs = inputs.to(self.device)
outputs = net(inputs)
n_samples += outputs.shape[0]
c += torch.sum(outputs, dim=0)
c /= n_samples
# If c_i is too close to 0, set to +-eps. Reason: a zero unit can be trivially matched with zero weights.
c[(abs(c) < eps) & (c < 0)] = -eps
c[(abs(c) < eps) & (c > 0)] = eps
return c
| 8,774 | 2,864 |
from .load_image import load_image
from .normalize_image import normalize_image
from .remove_artefacts import remove_artefacts, fill_small_white_blobs, fill_small_black_blobs
from .padding import trim_padding, add_padding
from .inpaint import inpaint
from .darken import darken
from .difference_of_gaussians_pyramid import difference_of_gaussians_pyramid
from .compute_linear_coefficients import compute_linear_coefficients
from .get_projected_points import get_projected_points
from .polar2cartesian import polar2cartesian
from .simmetry import trim_flip, simmetry_loss, get_simmetry_axis
from .fill_lower_max import fill_lower_max
from .median_mask import median_mask
from .rotate_image import rotate_image
from .thumbnail import get_thumbnail
from .peaks_and_valleys import valleys_cut
from .retinex import automated_msrcr
from .demosaicking import demosaicking
__all__ = [
"load_image",
"normalize_image",
"remove_artefacts",
"trim_padding",
"add_padding",
"inpaint",
"darken",
"difference_of_gaussians_pyramid",
"compute_linear_coefficients",
"get_projected_points",
"polar2cartesian",
"fill_small_white_blobs",
"fill_small_black_blobs",
"get_simmetry_axis",
"trim_flip",
"fill_lower_max",
"median_mask",
"simmetry_loss",
"rotate_image",
"get_thumbnail",
"valleys_cut",
"get_simmetry_axis",
"automated_msrcr",
"demosaicking",
]
| 1,430 | 501 |
#!/usr/bin/env python
# coding:utf8
# @Date : 2018/8/27
# @Author : Koon
# @Link : chenzeping.com
# When I wrote this, only God and I understood what I was doing. Now, God only knows.
class Subject(object):
def request(self):
print("Subject instance has been created")
class RealSubject(Subject):
def request(self):
print("RealSubject instance has been created")
class Proxy(Subject):
def __init__(self, subject):
self._subject = subject
def request(self):
self._subject.request()
if __name__ == "__main__":
proxy = Proxy(RealSubject())
proxy.request()
| 625 | 197 |
from .base import BaseTest
from authors.apps.articles.models import Article
from rest_framework.views import status
import json
class CommentsLikeDislikeTestCase(BaseTest):
"""test class for liking and disliking comments """
def create_article(self, token, article):
""" Method to create an article"""
return self.client.post(self.ARTICLES, self.test_article_data,
HTTP_AUTHORIZATION=self.token, format='json')
def create_comment(self, token, slug, test_comment_data):
""" Method to create an article then comment"""
self.client.post(self.ARTICLES, self.test_article_data,
HTTP_AUTHORIZATION=self.token, format='json')
return self.client.post('/api/articles/test-title12/comment/', self.test_comment_data,
HTTP_AUTHORIZATION=self.token, format='json')
def test_like_comment(self):
"""Test test the liking of a comment"""
# article created
response = self.create_article(self.token, self.test_article_data)
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
# creating a comment
slug = response.data['slug']
response = self.create_comment(self.token, slug, self.test_comment_data)
comment_id = response.data["id"]
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
# like a comment
response = self.client.put('/api/articles/test-title12/comment/' + str(comment_id) + '/like/',
HTTP_AUTHORIZATION=self.token, format='json')
self.assertEquals(status.HTTP_200_OK, response.status_code)
def test_unlike_comment(self):
"""Test test the liking of a comment"""
response = self.create_article(self.token, self.test_article_data)
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
slug = response.data['slug']
response = self.create_comment(self.token, slug, self.test_comment_data)
comment_id = response.data["id"]
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
response = self.client.put('/api/articles/test-title12/comment/' + str(comment_id) + '/like/',
HTTP_AUTHORIZATION=self.token, format='json')
self.assertEquals(status.HTTP_200_OK, response.status_code)
def test_like_missing_article(self):
"""Test test the liking of a comment"""
response = self.create_article(self.token, self.test_article_data)
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
slug = response.data['slug']
response = self.create_comment(self.token, slug, self.test_comment_data)
comment_id = response.data["id"]
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
response = self.client.put('/api/articles/me/comment/' + str(comment_id) + '/dislike/',
HTTP_AUTHORIZATION=self.token,
format='json'
)
self.assertEquals(status.HTTP_404_NOT_FOUND, response.status_code)
def test_like_missing_comment(self):
"""Test test the liking of a comment"""
response = self.create_article(self.token, self.test_article_data)
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
slug = response.data['slug']
response = self.create_comment(self.token, slug, self.test_comment_data)
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
response = self.client.put('/api/articles/test-title12/comment/99/dislike/',
HTTP_AUTHORIZATION=self.token,
format='json'
)
self.assertEquals(status.HTTP_404_NOT_FOUND, response.status_code)
def test_like_comment_if_article_does_not_exist(self):
"""Test test the liking of a comment in an article that does not exist"""
slug = 'test-title12'
response = self.create_comment(self.token, slug, self.test_comment_data)
comment_id = response.data["id"]
self.assertEquals(status.HTTP_201_CREATED, response.status_code)
# like a comment
response = self.client.put('/api/articles/test-title123/comment/' + str(comment_id) + '/like/',
HTTP_AUTHORIZATION=self.token,
format='json'
)
self.assertEquals(response.data['Error'], 'The article does not exist')
| 4,680 | 1,371 |
import socket
import numpy
import cv2
import threading
import os
BUFFER_SIZE = 4096*10
currentPort = 50001
buf = b''
class capture():
def __init__(self,port):
self.port = port
def recive(self):
global buf
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
while True:
s.bind(("0.0.0.0", self.port))
try:
data,address = s.recvfrom(BUFFER_SIZE)
if not data:
break
buf = buf + data
finally:
s.close()
narray=numpy.frombuffer(buf,dtype='uint8')
buf = b""
return cv2.imdecode(narray,1)
def show(self):
while True:
img = self.recive()
cv2.imshow('Capture',img)
if cv2.waitKey(100) & 0xFF == ord('q'):
break
img = ''
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as portInfo:
portInfo.bind(("0.0.0.0",50000))
portInfo.listen()
print("aitayo")
while True:
(connection, client) = portInfo.accept()
print("kita!")
try:
data = connection.recv(800)
if data == b"OpenPortRequest":
print('recive')
connection.send(currentPort.to_bytes(2,"big"))
cap = capture(currentPort)
th = threading.Thread(target=cap.show)
th.daemon = True
th.start()
finally:
connection.close() | 1,577 | 481 |
"""
Forum signal receivers
======================
This module defines signal receivers.
"""
from django.db.models import F
from django.dispatch import receiver
from machina.apps.forum.signals import forum_viewed
@receiver(forum_viewed)
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs):
""" Handles the update of the link redirects counter associated with link forums. """
if forum.is_link and forum.link_redirects:
forum.link_redirects_count = F('link_redirects_count') + 1
forum.save()
| 565 | 162 |
for t in range(int(input())):
r,c,k = map(int , input().split())
circuit_board = []
for i in range(r):
circuit_board.append(list(map(int,input().split())))
| 185 | 66 |
# Copyright (C) 2018 Verizon. 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from rest_framework import serializers
from .vnf_instance_subscription_filter import VnfInstanceSubscriptionFilter
from lcm.nf.const import NOTIFICATION_TYPES, LCM_OPERATION_TYPES, LCM_OPERATION_STATE_TYPES
class LifeCycleChangeNotificationsFilter(serializers.Serializer):
notificationTypes = serializers.ListField(
child=serializers.ChoiceField(required=True, choices=NOTIFICATION_TYPES),
help_text="Match particular notification types",
allow_null=False,
required=False)
operationTypes = serializers.ListField(
child=serializers.ChoiceField(required=True, choices=LCM_OPERATION_TYPES),
help_text="Match particular VNF lifecycle operation types for the " +
"notification of type VnfLcmOperationOccurrenceNotification.",
allow_null=False,
required=False)
operationStates = serializers.ListField(
child=serializers.ChoiceField(required=True, choices=LCM_OPERATION_STATE_TYPES),
help_text="Match particular LCM operation state values as reported " +
"in notifications of type VnfLcmOperationOccurrenceNotification.",
allow_null=False,
required=False)
vnfInstanceSubscriptionFilter = VnfInstanceSubscriptionFilter(
help_text="Filter criteria to select VNF instances about which to notify.",
required=False,
allow_null=False)
| 1,978 | 548 |
def TravelThrewTreeNodes(currentTreeNode, leftDirections, encodedSign):
# Überprüfung, ob die letzte Stelle erreicht wurde. Sollte dies nicht der Fall sein so wird weiter durch den
# Baum navigiert
if not len(leftDirections) == 1:
# Speicherung der nächsten Richtung
nextDirection = leftDirections[0]
# Löschen der aktuellen Richtung von den übrigen Richtungen
leftDirections = leftDirections[1:]
# Überprüfung, ob vom aktuellen TreeNode in Richtung 0 navigiert werden soll
if nextDirection == '0':
if not CheckIfChildrenTreeNodeAlreadyExists(currentTreeNode.zero):
# Die gewünschte Richtung existiert noch nicht, daher wird ein neuer TreeNode für diese
# Richtung erstellt
currentTreeNode.AddTreeNode(True)
TravelThrewTreeNodes(currentTreeNode.zero, leftDirections, encodedSign)
elif nextDirection == '1':
if not CheckIfChildrenTreeNodeAlreadyExists(currentTreeNode.one):
# Die gewünschte Richtung existiert noch nicht, daher wird ein neuer TreeNode für diese Richtung
# erstellt
currentTreeNode.AddTreeNode(False)
TravelThrewTreeNodes(currentTreeNode.one, leftDirections, encodedSign)
else:
# Es wurde die letzte Stelle erreicht. Damit kann das kodierte Zeichen an seine vorgesehene Stelle gespeichert
# werden
# Überprüfung, ob vom aktuellen TreeNode in Richtung 0 navigiert werden soll
if leftDirections == '0':
# Erstelle einen neuen TreeNode für diese Richtung und speichere als Wert das kodierte Zeichen
currentTreeNode.AddTreeNode(True, encodedSign)
elif leftDirections == '1':
# Erstelle einen neuen TreeNode für diese Richtung und speichere als Wert das kodierte Zeichen
currentTreeNode.AddTreeNode(False, encodedSign)
def CheckIfChildrenTreeNodeAlreadyExists(childrenTreeNode):
# Existiert das abzufragende Kind-Objekt bereits, so wird True zurückgegeben
if childrenTreeNode is not None:
return True
else:
return False
| 2,213 | 611 |
skills_list = [
"actionscript",
"ado.net",
"ajax",
"akka",
"algorithm",
"amazon-ec2",
"amazon-s3",
"amazon-web-services",
"android",
"angular",
"angularjs",
"ansible",
"ant",
"apache",
"apache-camel",
"apache-kafka",
"apache-poi",
"apache-spark",
"apache-spark-sql",
"apache2",
"applet",
"arduino",
"asp.net",
"asp.net-core",
"asp.net-core-mvc",
"asp.net-mvc",
"assembly",
"asynchronous",
"automation",
"awk",
"azure",
"backbone.js",
"beautifulsoup",
"bigdata",
"bootstrap",
"c#",
"c++",
"cakephp",
"cassandra",
"chef",
"ckeditor",
"clang",
"clojure",
"cocoa",
"coffeescript",
"coldfusion",
"concurrency",
"content-management-system",
"continuous-integration",
"cordova",
"cryptography",
"css",
"cucumber",
"cuda",
"cursor",
"cygwin",
"cypher",
"d3.js",
"dart",
"data-binding",
"data-structures",
"database",
"database-design",
"datatables",
"deep-learning",
"delphi",
"dependency-injection",
"deployment",
"design",
"design-patterns",
"django",
"dns",
"docker",
"dplyr",
"drupal",
"ejb",
"elasticsearch",
"eloquent",
"emacs",
"ember.js",
"entity-framework",
"erlang",
"event-handling",
"excel",
"excel-vba",
"express",
"express.js",
"expressjs",
"extjs",
"f#",
"facebook-graph-api",
"firebase",
"flask",
"flex",
"flexbox",
"fortran",
"frameworks",
"functional-programming",
"git",
"glassfish",
"go",
"golang",
"google-analytics",
"google-api",
"google-app-engine",
"google-apps-script",
"google-bigquery",
"google-chrome",
"google-chrome-extension",
"google-cloud-datastore",
"google-cloud-messaging",
"google-cloud-platform",
"google-drive-sdk",
"google-maps",
"gps",
"gradle",
"grails",
"groovy",
"gruntjs",
"gson",
"gtk",
"gulp",
"gwt",
"hadoop",
"handlebars.js",
"haskell",
"hbase",
"hdfs",
"heroku",
"hibernate",
"highcharts",
"hive",
"html",
"html5",
"hyperlink",
"ibm-mobilefirst",
"iis",
"image-processing",
"imagemagick",
"ionic-framework",
"ionic2",
"itext",
"jackson",
"jasmine",
"java",
"java-8",
"java-ee",
"java-me",
"javafx",
"javascript",
"jax-rs",
"jaxb",
"jboss",
"jdbc",
"jenkins",
"jersey",
"jetty",
"jframe",
"jmeter",
"jms",
"jni",
"join",
"joomla",
"jpa",
"jpanel",
"jqgrid",
"jquery",
"jsf",
"jsf-2",
"json",
"json.net",
"jsoup",
"jsp",
"jtable",
"junit",
"jupyter-notebook",
"jvm",
"kendo-grid",
"kendo-ui",
"keras",
"knockout.js",
"kotlin",
"kubernetes",
"laravel",
"linq",
"log4j",
"lua",
"lucene",
"machine-learning",
"macros",
"magento",
"mapreduce",
"matlab",
"matplotlib",
"matrix",
"maven",
"memory-management",
"mercurial",
"meteor",
"mockito",
"model-view-controller",
"mongodb",
"mongoose",
"multiprocessing",
"multithreading",
"mysql",
"neo4j",
"network-programming",
"networking",
"neural-network",
"nginx",
"nhibernate",
"nlp",
"node.js",
"nosql",
"numpy",
"oauth",
"object",
"objective-c",
"odbc",
"odoo",
"oop",
"opencv",
"openssl",
"oracle",
"pandas",
"perl",
"phantomjs",
"php",
"playframework",
"plsql",
"postgresql",
"powershell",
"prolog",
"pthreads",
"pyqt",
"pyspark",
"python",
"qml",
"qt",
"rabbitmq",
"raspberry-pi",
"razor",
"react-native",
"react-redux",
"react-router",
"reactjs",
"realm",
"recursion",
"redirect",
"redis",
"redux",
"refactoring",
"reference",
"reflection",
"regex",
"registry",
"requirejs",
"responsive-design",
"rest",
"rss",
"ruby",
"ruby-on-rails",
"rust",
"rxjs",
"sails.js",
"salesforce",
"sas",
"sass",
"scala",
"scikit-learn",
"scipy",
"scrapy",
"scripting",
"security",
"selenium",
"selenium-webdriver",
"seo",
"servlets",
"sharepoint",
"shell",
"silverlight",
"smtp",
"soap",
"socket.io",
"sockets",
"solr",
"sonarqube",
"speech-recognition",
"spring",
"sql",
"sql-server",
"sqlalchemy",
"sqlite",
"sqlite3",
"svn",
"swift",
"swing",
"swt",
"symfony",
"synchronization",
"telerik",
"tensorflow",
"three.js",
"titanium",
"tkinter",
"tomcat",
"twitter-bootstrap",
"typescript",
"vagrant",
"vb.net",
"vb6",
"vba",
"vbscript",
"version-control",
"vim",
"visual-c++",
"vue.js",
"vuejs2",
"wamp",
"wcf",
"web",
"web-applications",
"web-crawler",
"web-scraping",
"web-services",
"webdriver",
"websocket",
"websphere",
"woocommerce",
"wordpress",
"wpf",
"wsdl",
"wso2",
"wxpython",
"x86",
"xamarin",
"xaml",
"xampp",
"xcode",
"xml",
"xml-parsing",
"xmlhttprequest",
"xmpp",
"xna",
"xsd",
"xslt",
"yii",
"yii2",
"zend-framework",
]
skillset = set(skills_list)
| 5,633 | 2,260 |
# handler module centralize the control
| 40 | 9 |
def escape_team_names(mystr):
"""
temporary fix for solving ? characters in bad team names encoding
from LFP's ICS calendar
"""
mystr = mystr.replace('N?MES','NÎMES')
mystr = mystr.replace('SAINT-?TIENNE','SAINT-ÉTIENNE')
mystr = mystr.replace('H?RAULT', 'HÉRAULT')
return mystr | 313 | 116 |
def grid_scan_xpcs():
folder = "301000_Chen34"
xs = np.linspace(-9350, -9150, 2)
ys = np.linspace(1220, 1420, 2)
names=['PSBMA5_200um_grid']
energies = [2450, 2472, 2476, 2490]
x_off = [0, 60, 0, 60]
y_off = [0, 0, 60, 60]
xxs, yys = np.meshgrid(xs, ys)
dets = [pil1M]
for name in names:
for ener, xof, yof in zip(energies, x_off, y_off):
yield from bps.mv(energy, ener)
yield from bps.sleep(10)
for i, (x, y) in enumerate(zip(xxs.ravel(), yys.ravel())):
pil1M.cam.file_path.put(f"/ramdisk/images/users/2019_3/%s/1M/%s_pos%s"%(folder, name, i))
yield from bps.mv(piezo.x, x+xof)
yield from bps.mv(piezo.y, y+yof)
name_fmt = '{sample}_{energy}eV_pos{pos}'
sample_name = name_fmt.format(sample=name, energy=ener, pos = '%2.2d'%i)
sample_id(user_name='Chen', sample_name=sample_name)
yield from bps.sleep(5)
det_exposure_time(0.03, 30)
print(f'\n\t=== Sample: {sample_name} ===\n')
pil1M.cam.acquire.put(1)
yield from bps.sleep(5)
pv = EpicsSignal('XF:12IDC-ES:2{Det:1M}cam1:Acquire', name="pv")
while pv.get() == 1:
yield from bps.sleep(5)
yield from bps.mv(energy, 2475)
yield from bps.mv(energy, 2450)
def NEXAFS_SAXS_S_edge(t=1):
dets = [pil300KW]
name = 'sample_thick_waxs'
energies = [2450, 2480, 2483, 2484, 2485, 2486, 2500]
det_exposure_time(t,t)
name_fmt = '{sample}_{energy}eV_wa{wa}'
waxs_an = np.linspace(0, 26, 5)
yss = np.linspace(1075, 1575, 5)
for wax in waxs_an:
yield from bps.mv(waxs, wax)
for e, ys in zip(energies, yss):
yield from bps.mv(energy, e)
yield from bps.mv(piezo.y, ys)
sample_name = name_fmt.format(sample=name, energy=e, wa = '%3.1f'%wax)
sample_id(user_name='Chen', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2475)
yield from bps.mv(energy, 2450)
def grid_scan_static():
names=['PSBMA30_10um_static']
x_off = -36860+np.asarray([-200, 200])
y_off = 1220+np.asarray([-100, 0, 100])
energies = np.linspace(2500, 2450, 51)
xxs, yys = np.meshgrid(x_off, y_off)
dets = [pil300KW, pil1M]
for name in names:
for i, (x, y) in enumerate(zip(xxs.ravel(), yys.ravel())):
yield from bps.mv(piezo.x, x)
yield from bps.mv(piezo.y, y)
energies = energies[::-1]
yield from bps.sleep(2)
for ener in energies:
yield from bps.mv(energy, ener)
yield from bps.sleep(0.1)
name_fmt = '{sample}_{energy}eV_pos{pos}_xbpm{xbpm}'
sample_name = name_fmt.format(sample=name, energy=ener, pos = '%2.2d'%i, xbpm='%3.1f'%xbpm3.sumY.value)
sample_id(user_name='Chen', sample_name=sample_name)
det_exposure_time(0.1, 0.1)
yield from bp.count(dets, num=1)
def nexafs_S_edge_chen(t=1):
dets = [pil300KW]
det_exposure_time(t,t)
waxs_arc = [45.0]
name_fmt = 'nexafs_sampletest1_4_{energy}eV_wa{wax}_bpm{xbpm}'
for wa in waxs_arc:
for e in energies:
yield from bps.mv(energy, e)
yield from bps.sleep(1)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(energy='%6.2f'%e, wax = wa, xbpm = '%4.3f'%bpm)
sample_id(user_name='WC', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2490)
yield from bps.mv(energy, 2470)
yield from bps.mv(energy, 2450)
def waxs_S_edge_chen_2020_3(t=1):
dets = [pil300KW, pil1M]
names = ['sampleA1', 'sampleB1', 'sampleB2', 'sampleB3', 'sampleC4', 'sampleC5', 'sampleE8', 'sampleD1', 'sampleD2', 'sampleD3', 'sampleD4',
'sampleD5', 'sampleC8', 'sampleF1', 'sampleF2', 'sampleE1', 'sampleE3', 'sampleE4', 'sampleE5', 'sampleD8', 'sampleF8']
x = [43800, 28250, 20750, 13350, 5150, -5660, -10900, -18400, -26600, -34800, -42800, 42300, 34400, 26700, 18800, 11200, 2900, -5000, -12000,
-20300, -27800, ]
y = [-4900, -5440, -5960, -5660, -5660, -5660, -5880, -4750, -5450, -5000, -4450, 6950, 6950, 6950, 7450, 7200, 7400, 8250, 8250,
8250, 7750]
energies = [2450.0, 2474.0, 2475.0, 2476.0, 2477.0, 2478.0, 2479.0, 2482.0, 2483.0, 2484.0, 2485.0, 2486.0, 2487.0, 2490.0, 2500.0]
waxs_arc = np.linspace(0, 13, 3)
for name, xs, ys in zip(names, x, y):
yield from bps.mv(piezo.x, xs)
yield from bps.mv(piezo.y, ys+30)
for wa in waxs_arc:
yield from bps.mv(waxs, wa)
det_exposure_time(t,t)
name_fmt = '{sample}_rev_{energy}eV_wa{wax}_bpm{xbpm}'
for e in energies[::-1]:
yield from bps.mv(energy, e)
yield from bps.sleep(1)
bpm = xbpm2.sumX.value
sample_name = name_fmt.format(sample=name, energy='%6.2f'%e, wax = wa, xbpm = '%4.3f'%bpm)
sample_id(user_name='GF', sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.count(dets, num=1)
yield from bps.mv(energy, 2480)
yield from bps.mv(energy, 2460) | 6,054 | 2,687 |
"""Plotting support"""
def source_attribution(ax, text ):
ax.text(0, -.05, text, fontsize=14,
horizontalalignment='left', verticalalignment='top',
transform=ax.transAxes) | 199 | 65 |
import sublime
import sublime_plugin
import re
import webbrowser
from .lib.hl7Event import *
from .lib.hl7Segment import *
from .lib.hl7TextUtils import *
hl7EventList = hl7Event("","")
hl7EventList = hl7EventList.loadEventList()
hl7SegmentList = hl7Segment("","")
hl7SegmentList = hl7SegmentList.loadSegmentList()
STATUS_BAR_HL7 = 'StatusBarHL7'
# On selection modified it will update the status bar
class selectionModifiedListener(sublime_plugin.EventListener):
def on_selection_modified(self, view):
line = getLineTextBeforeCursorPosition(self, view, sublime)
fullLine = getLineAtCursorPosition(self, view)
# Get the first 3 letters of the line
segment = fullLine[:3]
if hl7Segment.getSegmentByCode(self, segment, hl7SegmentList) != None:
statusBarText = '[ ' + segment + ' '
fieldList = re.split(r'(?<!\\)(?:\\\\)*\|', line)
fieldCounter = len(fieldList)
if segment != 'MSH':
statusBarText += str(fieldCounter-1)
else:
statusBarText += str(fieldCounter)
isComponentRequired = False
isSubComponentRequired = False
fullField = getFieldAtCursorPosition(self, view, sublime)
# Level of detail required
if fieldHasComponents(self, fullField) == True:
isComponentRequired = True
if fieldHasSubComponents(self, fullField) == True:
isComponentRequired = True
isSubComponentRequired = True
if isComponentRequired == True:
field = fieldList[-1]
componentList = re.split(r'(?<!\\)(?:\\\\)*\^', field)
componentCounter = len(componentList)
statusBarText += '.' + str(componentCounter)
if isSubComponentRequired == True:
subComponent = componentList[-1]
subComponentList = re.split(r'(?<!\\)(?:\\\\)*\&', subComponent)
subComponentCounter = len(subComponentList)
statusBarText += '.' + str(subComponentCounter)
statusBarText += ' ]'
#sublime.status_message('\t' + statusBarText + ' '*20)
view.set_status(STATUS_BAR_HL7, statusBarText)
else:
#sublime.status_message('')
view.erase_status(STATUS_BAR_HL7)
# Double click on keywords (segments / events)
class doubleClickKeywordListener(sublime_plugin.EventListener):
def on_text_command(self, view, cmd, args):
if cmd == 'drag_select' and 'event' in args:
event = args['event']
isEvent = True
pt = view.window_to_text((event['x'], event['y']))
text = []
if view.sel():
for region in view.sel():
print(view.substr(view.word(region)))
if region.empty():
text.append(view.substr(view.word(region)))
def asyncMessagePopup():
desc = ""
for eventItem in hl7EventList:
regex = "(\^)"
filler = "_"
codeWithoutCircunflex = re.sub(regex, filler, text[0])
if (eventItem.code == codeWithoutCircunflex):
desc = eventItem.description
for segmentItem in hl7SegmentList:
regex = "(\^)"
filler = "_"
codeWithoutCircunflex = re.sub(regex, filler, text[0])
if (segmentItem.code == codeWithoutCircunflex):
desc = segmentItem.description
if (len(desc) > 0):
if(getComponentAtCursorPosition(self, view, sublime) == text[0]):
view.show_popup('<b style="color:#33ccff;">' + desc + '</b>', location=pt)
sublime.set_timeout_async(asyncMessagePopup)
else:
text.append(view.substr(region))
# Searchs an event or segment on caristix web-site
class hl7searchCommand(sublime_plugin.WindowCommand):
def run(self):
window = self.window
view = window.active_view()
sel = view.sel()
region1 = sel[0]
selectionText = view.substr(region1)
isValid = 0
URL = "http://hl7-definition.caristix.com:9010/HL7%20v2.5.1/Default.aspx?version=HL7 v2.5.1&"
for eventItem in hl7EventList:
regex = "(\^)"
filler = "_"
codeWithoutCircunflex = re.sub(regex, filler, selectionText)
if (eventItem.code == codeWithoutCircunflex):
URL = URL + "triggerEvent=" + eventItem.code
isValid = 1
for segmentItem in hl7SegmentList:
if (segmentItem.code == selectionText):
URL = URL + "segment=" + segmentItem.code
isValid = 1
if (isValid == 1):
webbrowser.open_new(URL)
# Inspects an entire line
class hl7inspectorCommand(sublime_plugin.TextCommand):
def run(self, edit):
#Popup layout
header = ""
body = ""
segmentCode = ""
#Segment
selectedSegment = self.view.substr(self.view.line(self.view.sel()[0]))
fields = selectedSegment.split('|')
fields = re.split(r'(?<!\\)(?:\\\\)*\|', selectedSegment)
fieldId = 0
componentId = 1
subComponentId = 1
for segmentItem in hl7SegmentList:
if (segmentItem.code == fields[0]):
header = segmentItem.code + " - " + segmentItem.description
segmentCode = segmentItem.code
header = '<b style="color:#33ccff;">' + header + '</b>'
for field in fields:
if (field != ""):
if(field != "^~\&"):
components = re.compile(r'(?<!\\)(?:\\\\)*\^').split(field)
totalCircunflex = field.count("^")
for component in components:
if(component != ""):
subComponents = re.compile(r'(?<!\\)(?:\\\\)*&').split(component)
if(len(subComponents) > 1):
for subComponent in subComponents:
if(subComponent != ""):
regex = "(<)"
filler = "<"
subComponent = re.sub(regex, filler, subComponent)
regex = "(>)"
filler = ">"
subComponent = re.sub(regex, filler, subComponent)
body = body + '<br>' + str(fieldId) + "." + str(componentId) + "."+ str(subComponentId) + " - " + subComponent
subComponentId = subComponentId + 1
subComponentId = 1
else:
regex = "(<)"
filler = "<"
component = re.sub(regex, filler, component)
regex = "(>)"
filler = ">"
component = re.sub(regex, filler, component)
till = re.compile(r'(?<!\\)(?:\\\\)*~').split(component)
if segmentCode == 'MSH' and fieldId > 1:
fieldCounter = fieldId + 1
else:
fieldCounter = fieldId
if(totalCircunflex > 0):
for tillItem in till:
body = body + '<br>' + str(fieldCounter) + "." + str(componentId) + " - " + tillItem
else:
for tillItem in till:
body = body + '<br>' + str(fieldCounter) + " - " + tillItem
componentId = componentId + 1
componentId = 1
else:
if len(selectedSegment) > 3:
if selectedSegment[3] == '|':
body = body + '<br>' + str(1) + " - " + selectedSegment[3] + "\n"
if len(fields) > 0:
body = body + '<br>' + str(2) + " - " + fields[1] + "\n"
fieldId = fieldId + 1
message = header + body
message = message.replace("\&", "\&")
self.view.show_popup(message, on_navigate=print)
# Cleans an HL7 message from reduntant information and idents it
class hl7cleanerCommand(sublime_plugin.TextCommand):
def run(self, edit):
content = self.view.substr(sublime.Region(0, self.view.size()))
for segmentItem in hl7SegmentList:
regex = "(\^M)" + segmentItem.code
filler = "\n" + segmentItem.code
content = re.sub(regex, filler, content)
for segmentItem in hl7SegmentList:
regex = "(\^K)" + segmentItem.code
filler = "\n" + segmentItem.code
content = re.sub(regex, filler, content)
#remove any empty space before each segment
for segmentItem in hl7SegmentList:
regex = "\ {1,}" + segmentItem.code
filler = "" + segmentItem.code
content = re.sub(regex, filler, content)
#when there is no space before
for segmentItem in hl7SegmentList:
regex = "(\|){1,}(?<=[a-zA-Z0-9|])" + segmentItem.code + "(\|){1,}"
filler = "|\n" + segmentItem.code + "|"
content = re.sub(regex, filler, content)
#last two ^M at the end of content followed by new line
content = re.sub("(\^M\^\\\\\^M)\n", "\n", content)
#last two ^M at the end of content followed by end of content
content = re.sub("(\^M\^\\\\\^M)$", "\n", content)
#last ^M with new line
regex = "(\^M)\n"
filler = "\n"
content = re.sub(regex, filler, content)
#last ^M with end of content
regex = "(\^M)$"
filler = "\n"
content = re.sub(regex, filler, content)
#last two ^M at the end of content followed by new line with empty space before
content = re.sub("(\^M\^\\\\\^M)\ {1,}\n", "\n", content)
#last two ^M at the end of content followed by end of content with empty space before
content = re.sub("(\^M\^\\\\\^M)\ {1,}$", "\n", content)
#last ^M with new line with empty space before
regex = "(\^M)\ {1,}\n"
filler = "\n"
content = re.sub(regex, filler, content)
#last ^M with end of content with empty space before
regex = "(\^M)\ {1,}$"
filler = "\n"
content = re.sub(regex, filler, content)
#extra circumflex ^
content = re.sub("(\^{1,})[|]", "|", content)
#extra pipes | followed by new lines
content = re.sub("\|{2,}\n", "|\n", content)
#extra pipes | followed by end of content
content = re.sub("\|{2,}$", "|\n", content)
#empty lines at the beginning of the text
content = re.sub("^(\n){1,}", "", content)
#blank spaces at the beginning of the text
content = re.sub("^ {1,}", "", content)
self.view.insert(edit, 0, content + "\n\n\n")
| 9,298 | 3,954 |
# https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/
# graph, dfs
class Solution:
def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
| 218 | 76 |
#!/usr/bin/python3
import argparse
import time
import cv2
import glob
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from multiprocessing.dummy import Pool as ThreadPool
sys.path.append(Path(__file__).resolve().parent.parent.as_posix()) # repo path
sys.path.append(Path(__file__).resolve().parent.as_posix()) # file path
from params import *
LABEL_DATAFRAME = pd.DataFrame(columns=['raw_value', 'color', 'coco_names_index'],
data=[
# [ 4, (220, 20, 60), 0],
[18, (250, 170, 30), 9],
[12, (220, 220, 0), 80]])
LABEL_COLORS = np.array([
# (220, 20, 60), # Pedestrian
# (0, 0, 142), # Vehicle
(220, 220, 0), # TrafficSign -> COCO INDEX
(250, 170, 30), # TrafficLight
])
COCO_NAMES = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat',
'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',
'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite',
'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana',
'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard',
'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear',
'hair drier', 'toothbrush', 'traffic sign']
class YoloLabel:
def __init__(self, data_path, debug=False):
self.data_path = data_path
self.data_output_path = Path(data_path) / "../yolo_dataset"
self.data_output_path = Path(os.path.abspath(self.data_output_path.as_posix()))
print(self.data_output_path)
self.image_out_path = self.data_output_path / "images" / "train"
self.label_out_path = self.data_output_path / "labels" / "train"
self.image_rgb = None
self.image_seg = None
self.preview_img = None
self.rec_pixels_min = 150
self.debug = debug
self.thread_pool = ThreadPool()
def process(self):
img_path_list = sorted(glob.glob(self.data_path + '/*.png'))
img_seg_path_list = sorted(glob.glob(self.data_path + '/seg' + '/*.png'))
start = time.time()
self.thread_pool.starmap(self.label_img, zip(img_path_list, img_seg_path_list))
# for rgb_img, seg_img in zip(img_path_list, img_seg_path_list):
# self.label_img(rgb_img, seg_img)
self.thread_pool.close()
self.thread_pool.join()
print("cost: {}s".format(time.time()-start))
def label_img(self, rgb_img_path, seg_img_path):
success = self.check_id(rgb_img_path, seg_img_path)
if not success:
return
image_rgb = None
image_seg = None
image_rgb = cv2.imread(rgb_img_path, cv2.IMREAD_COLOR)
image_seg = cv2.imread(seg_img_path, cv2.IMREAD_UNCHANGED)
if image_rgb is None or image_seg is None:
return
image_rgb = cv2.cvtColor(image_rgb, cv2.COLOR_RGBA2RGB)
image_seg = cv2.cvtColor(image_seg, cv2.COLOR_BGRA2RGB)
img_name = os.path.basename(rgb_img_path)
height, width, _ = image_rgb.shape
labels_all = []
for index, label_info in LABEL_DATAFRAME.iterrows():
seg_color = label_info['color']
coco_id = label_info['coco_names_index']
mask = (image_seg == seg_color)
tmp_mask = (mask.sum(axis=2, dtype=np.uint8) == 3)
mono_img = np.array(tmp_mask * 255, dtype=np.uint8)
preview_img = image_rgb
# self.preview_img = self.image_seg
# cv2.imshow("seg", self.preview_img)
# cv2.imshow("mono", mono_img)
# cv2.waitKey()
contours, _ = cv2.findContours(mono_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
labels = []
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w * h < self.rec_pixels_min:
continue
# cv2.rectangle(self.preview_img, (x, y), (x + w, y + h), (0, 255, 0), 1)
# cv2.imshow("rect", self.preview_img)
# cv2.waitKey()
max_y, max_x, _ = image_rgb.shape
if y + h >= max_y or x + w >= max_x:
continue
# Draw label info to image
cv2.putText(preview_img, COCO_NAMES[coco_id], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36, 255, 12), 1)
cv2.rectangle(image_rgb, (x, y), (x + w, y + h), (0, 255, 0), 1)
label_info = "{} {} {} {} {}".format(coco_id,
float(x + (w / 2.0)) / width,
float(y + (h / 2.0)) / height,
float(w) / width,
float(h) / height)
labels.append(label_info)
# cv2.imshow("result", self.preview_img)
# cv2.imshow("test", self.preview_img[y:y+h, x:x+w, :])
# cv2.waitKey()
if len(labels) > 0:
labels_all += labels
if len(labels_all) > 0:
os.makedirs(self.label_out_path, exist_ok=True)
os.makedirs(self.image_out_path, exist_ok=True)
# print("image\t\t\twidth\theight\n{}\t{}\t{}".format(img_name, width, height))
# print("Got {} labels".format(len(labels_all)))
cv2.imwrite(self.image_out_path.as_posix() + '/' + os.path.splitext(img_name)[0] + '.jpg', image_rgb)
# print(self.image_rgb.shape)
with open(self.label_out_path.as_posix() + '/' + os.path.splitext(img_name)[0] + '.txt', "w") as f:
for label in labels_all:
f.write(label)
f.write('\n')
# print("Label output path: {}".format(self.label_out_path))
self.dump_yaml(self.data_output_path.as_posix())
# print("******")
return
def check_id(self, rgb_img_path, seg_img_path):
img_name = os.path.splitext(os.path.basename(rgb_img_path))[0]
seg_name = os.path.splitext(os.path.basename(seg_img_path))[0]
if img_name != seg_name:
print("Img name error: {} {}".format(img_name, seg_name))
return False
else:
return True
def dump_yaml(self, dataset_path):
dict_file = {
'path': dataset_path,
'train': 'images/train',
'val': 'images/train',
'test': '',
'nc': len(COCO_NAMES),
'names': COCO_NAMES
}
with open(dataset_path + '/../yolo_coco_carla.yaml', 'w') as file:
yaml.dump(dict_file, file)
def main():
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument(
'--record_id',
default='record2021_1106_0049',
help='record_id of raw data')
argparser.add_argument(
'--debug',
default=False
)
args = argparser.parse_args()
debug = args.debug
data_path = RAW_DATA_PATH / Path(args.record_id)
print(data_path)
vehicle_data_list = glob.glob(data_path.as_posix() + '/vehicle*' + '/vehicle*')
for vehicle_data_path in vehicle_data_list:
yolo_label_manager = YoloLabel(vehicle_data_path, debug)
yolo_label_manager.process()
return
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('\nCancelled by user. Bye!')
except RuntimeError as e:
print(e)
| 8,220 | 2,869 |
#!/usr/bin/python
# Copyright 2011 Google 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 by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# unittest requires method names starting in 'test'
# pylint:disable=invalid-name
#
# Refactored, originally from: platform/gfmedia/device_test.py
"""Unit tests for device.py."""
__author__ = 'jnewlin@google.com (John Newlin)'
import os
import shutil
import tempfile
import google3
import tornado.testing
import acs_config
from wvtest import unittest
class AcsConfigTest(tornado.testing.AsyncTestCase, unittest.TestCase):
"""Tests for acs_config.py."""
def setUp(self):
super(AcsConfigTest, self).setUp()
self.old_ACSCONTACT = acs_config.ACSCONTACT
self.old_ACSCONNECTED = acs_config.ACSCONNECTED
self.old_SET_ACS = acs_config.SET_ACS
acs_config.SET_ACS = 'testdata/acs_config/set-acs'
self.scriptout = tempfile.NamedTemporaryFile()
os.environ['TESTOUTPUT'] = self.scriptout.name
def tearDown(self):
super(AcsConfigTest, self).tearDown()
acs_config.ACSCONTACT = self.old_ACSCONTACT
acs_config.ACSCONNECTED = self.old_ACSCONNECTED
acs_config.SET_ACS = self.old_SET_ACS
self.scriptout = None # File will delete itself
def testSetAcs(self):
ac = acs_config.AcsConfig()
self.assertEqual(ac.GetAcsUrl(), 'bar')
ac.SetAcsUrl('foo')
self.assertEqual(self.scriptout.read().strip(), 'cwmp foo')
def testClearAcs(self):
ac = acs_config.AcsConfig()
ac.SetAcsUrl('')
self.assertEqual(self.scriptout.read().strip(), 'cwmp clear')
def testAcsAccess(self):
tmpdir = tempfile.mkdtemp()
acscontact = os.path.join(tmpdir, 'acscontact')
self.assertRaises(OSError, os.stat, acscontact) # File does not exist yet
acs_config.ACSCONTACT = acscontact
acsconnected = os.path.join(tmpdir, 'acsconnected')
self.assertRaises(OSError, os.stat, acsconnected)
acs_config.ACSCONNECTED = acsconnected
ac = acs_config.AcsConfig()
acsurl = 'this is the acs url'
# Simulate ACS connection attempt
ac.AcsAccessAttempt(acsurl)
self.assertTrue(os.stat(acscontact))
self.assertEqual(open(acscontact, 'r').read(), acsurl)
self.assertRaises(OSError, os.stat, acsconnected)
# Simulate ACS connection success
ac.AcsAccessSuccess(acsurl)
self.assertTrue(os.stat(acscontact))
self.assertTrue(os.stat(acsconnected))
self.assertEqual(open(acsconnected, 'r').read(), acsurl)
# cleanup
shutil.rmtree(tmpdir)
if __name__ == '__main__':
unittest.main()
| 3,004 | 1,066 |
import os
from cryptography.fernet import Fernet
def encrypt_password(password: str, key):
f = Fernet(key)
return str(f.encrypt(bytes(password, 'utf-8')), 'utf-8')
def decrypt_password(password: str, key):
f = Fernet(key)
return str(f.decrypt(bytes(password, 'utf-8')), 'utf-8')
KEY = os.environ.get("DASH_APP_KEY") | 337 | 128 |
# This empty file makes the sphinxcontrib namespace package work.
# It is the only file included in the 'sphinxcontrib' conda package.
# Conda packages which use the sphinxcontrib namespace do not include
# this file, but depend on the 'sphinxcontrib' conda package instead.
| 275 | 72 |
import boto3
import os
import requests
class ApiTestClient():
api_endpoint: str
some_metadata = {
'timestamp': '123123',
'command_id': '456346234',
'issued_by': 'test@test.com'
}
some_events = [
{ "type": "init", "foo": "bar" },
{ "type": "update", "foo": "baz" },
]
def __init__(self, sam_stack_name=None):
if not sam_stack_name:
sam_stack_name = os.environ.get("AWS_SAM_STACK_NAME")
if not sam_stack_name:
raise Exception(
"Cannot find env var AWS_SAM_STACK_NAME. \n"
"Please setup this environment variable with the stack name where we are running integration tests."
)
client = boto3.client("cloudformation")
try:
response = client.describe_stacks(StackName=sam_stack_name)
except Exception as e:
raise Exception(
f"Cannot find stack {sam_stack_name}. \n" f'Please make sure stack with the name "{sam_stack_name}" exists.'
) from e
stacks = response["Stacks"]
stack_outputs = stacks[0]["Outputs"]
api_outputs = [output for output in stack_outputs if output["OutputKey"] == "ApiEndpoint"]
if not api_outputs:
raise Exception(f"Cannot find output ApiEndpoint in stack {sam_stack_name}")
self.api_endpoint = api_outputs[0]["OutputValue"] + '/'
def commit(self, stream_id, events=None, metadata=None, last_changeset_id=None, last_event_id=None):
expected_last_changeset = ""
expected_last_event = ""
if last_changeset_id is not None:
try:
expected_last_changeset = int(last_changeset_id)
except ValueError:
expected_last_changeset = last_changeset_id
if last_event_id is not None:
try:
expected_last_event = int(last_event_id)
except ValueError:
expected_last_event = last_event_id
url = self.api_endpoint + f'streams/{stream_id}?expected_last_changeset={expected_last_changeset}&expected_last_event={expected_last_event}'
payload = { }
if events:
payload["events"] = events
if metadata:
payload["metadata"] = metadata
return requests.post(url, json=payload)
def query_changesets(self, stream_id, from_changeset=None, to_changeset=None):
url = self.api_endpoint + f'streams/{stream_id}/changesets?&from={from_changeset or ""}&to={to_changeset or ""}'
return requests.get(url)
def query_events(self, stream_id, from_event=None, to_event=None):
url = self.api_endpoint + f'streams/{stream_id}/events?&from={from_event or ""}&to={to_event or ""}'
return requests.get(url)
def version(self):
return requests.get(self.api_endpoint + "version") | 2,941 | 878 |
import eventlet
import json
import rest_lib
import urllib
import logging as log
from openstack_dashboard.dashboards.project.connections import bsn_api
eventlet.monkey_patch()
URL_TEST_PATH = ('applications/bcf/test/path/controller-view'
'[src-tenant=\"%(src-tenant)s\"]'
'[src-segment=\"%(src-segment)s\"]'
'[src-ip=\"%(src-ip)s\"]'
'[dst-ip=\"%(dst-ip)s\"]')
class ControllerCluster(object):
"""
Controller interfaces for a big switch controller cluster
"""
def __init__(self, controllers=bsn_api.controllers, port=bsn_api.port):
self.controllers = tuple(controllers)
self.port = port
self.cookie = None
self.origin = 'neutron'
@property
def active_controller(self):
pool = eventlet.greenpool.GreenPool()
coroutines = {}
active = None
standby_offline = []
for controller in self.controllers:
coroutines[controller] = pool.spawn(self.auth, controller)
while coroutines:
completed = None
for controller in coroutines.keys():
if coroutines[controller].dead:
completed = controller
break
eventlet.sleep(0.1)
if completed:
coro = coroutines.pop(completed)
try:
cookie = coro.wait()
url = 'core/controller/role'
res = rest_lib.get(cookie, url, controller,
self.port)[2]
if 'active' in res:
active = controller
self.cookie = cookie
else:
standby_offline.append((cookie, controller))
self.logout(cookie, controller)
except:
standby_offline.append(('', controller))
if active:
pool.spawn(self.cleanup_remaining, standby_offline, coroutines)
return active
# none responded in time, return first in list
return self.controllers[0]
def cleanup_remaining(self, finished, waiting):
for cookie, controller in finished:
if not cookie:
continue
self.logout(cookie, controller)
for controller in waiting.keys():
try:
cookie = waiting[controller].wait()
self.logout(cookie, controller)
except:
pass
def auth(self, server, username=bsn_api.username,
password=bsn_api.password):
login = {"user": username, "password": password}
host = "%s:%d" % (server, self.port)
log.info("PRE AUTH: Host: %s\t user: %s password: %s"
% (server, username, password))
ret = rest_lib.request("/api/v1/auth/login", prefix='',
method='POST', data=json.dumps(login),
host=host)
session = json.loads(ret[2])
if ret[0] != 200:
raise Exception(session["error_message"])
if ("session_cookie" not in session):
raise Exception("Failed to authenticate: session cookie not set")
return session["session_cookie"]
def logout(self, cookie, controller):
url = "core/aaa/session[auth-token=\"%s\"]" % cookie
ret = rest_lib.delete(cookie, url, controller, self.port)
log.info("LOGOUT Session: cookie: %s" % cookie)
return ret
def getTestPath(self, src, dst):
url = (URL_TEST_PATH %
{'src-tenant': src['tenant'],
'src-segment': src['segment'],
'src-ip': src['ip'],
'dst-ip': dst['ip']})
controller = self.active_controller
ret = rest_lib.get(self.cookie, url,
controller, self.port)
data = list()
if ret[0] in range(200, 300):
data = json.loads(ret[2])
return data
| 4,076 | 1,101 |
#
# PySNMP MIB module ROHC-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/ROHC-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:27:00 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( Integer, OctetString, ObjectIdentifier, ) = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
( ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
( ifIndex, ) = mibBuilder.importSymbols("IF-MIB", "ifIndex")
( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
( ModuleCompliance, ObjectGroup, NotificationGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
( ObjectIdentity, iso, Unsigned32, Gauge32, mib_2, MibIdentifier, Integer32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter64, Counter32, NotificationType, ModuleIdentity, IpAddress, ) = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "iso", "Unsigned32", "Gauge32", "mib-2", "MibIdentifier", "Integer32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter64", "Counter32", "NotificationType", "ModuleIdentity", "IpAddress")
( TimeInterval, DisplayString, TruthValue, TextualConvention, DateAndTime, ) = mibBuilder.importSymbols("SNMPv2-TC", "TimeInterval", "DisplayString", "TruthValue", "TextualConvention", "DateAndTime")
rohcMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 112)).setRevisions(("2004-06-03 00:00",))
if mibBuilder.loadTexts: rohcMIB.setLastUpdated('200406030000Z')
if mibBuilder.loadTexts: rohcMIB.setOrganization('IETF Robust Header Compression Working Group')
if mibBuilder.loadTexts: rohcMIB.setContactInfo('WG charter:\n http://www.ietf.org/html.charters/rohc-charter.html\n\n Mailing Lists:\n General Discussion: rohc@ietf.org\n To Subscribe: rohc-request@ietf.org\n In Body: subscribe your_email_address\n\n Editor:\n Juergen Quittek\n NEC Europe Ltd.\n Network Laboratories\n Kurfuersten-Anlage 36\n\n\n\n 69221 Heidelberg\n Germany\n Tel: +49 6221 90511-15\n EMail: quittek@netlab.nec.de')
if mibBuilder.loadTexts: rohcMIB.setDescription('This MIB module defines a set of basic objects for\n monitoring and configuring robust header compression.\n The module covers information about running instances\n of ROHC (compressors or decompressors) at IP interfaces.\n\n Information about compressor contexts and decompressor\n contexts has different structure for different profiles.\n Therefore it is not provided by this MIB module, but by\n individual modules for different profiles.\n\n Copyright (C) The Internet Society (2004). The\n initial version of this MIB module was published\n in RFC 3816. For full legal notices see the RFC\n itself or see:\n http://www.ietf.org/copyrights/ianamib.html')
class RohcChannelIdentifier(Unsigned32, TextualConvention):
displayHint = 'd'
subtypeSpec = Unsigned32.subtypeSpec+ValueRangeConstraint(1,4294967295)
class RohcChannelIdentifierOrZero(Unsigned32, TextualConvention):
displayHint = 'd'
subtypeSpec = Unsigned32.subtypeSpec+ValueRangeConstraint(0,4294967295)
class RohcCompressionRatio(Unsigned32, TextualConvention):
displayHint = 'd'
rohcObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 1))
rohcConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 2))
rohcInstanceObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 1, 1))
rohcChannelTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 1, 1), )
if mibBuilder.loadTexts: rohcChannelTable.setDescription('This table lists and describes all ROHC channels\n per interface.')
rohcChannelEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "ROHC-MIB", "rohcChannelID"))
if mibBuilder.loadTexts: rohcChannelEntry.setDescription('An entry describing a particular script. Every script that\n is stored in non-volatile memory is required to appear in\n\n\n\n this script table.\n\n Note, that the rohcChannelID identifies the channel\n uniquely. The ifIndex is part of the index of this table\n just in order to allow addressing channels per interface.')
rohcChannelID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 2), RohcChannelIdentifier())
if mibBuilder.loadTexts: rohcChannelID.setDescription("The locally arbitrary, but unique identifier associated\n with this channel. The value is REQUIRED to be unique\n per ROHC MIB implementation independent of the associated\n interface.\n\n The value is REQUIRED to remain constant at least from one\n re-initialization of the entity's network management system\n to the next re-initialization. It is RECOMMENDED that the\n value persist across such re-initializations.")
rohcChannelType = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("notInUse", 1), ("rohc", 2), ("dedicatedFeedback", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcChannelType.setDescription('Type of usage of the channel. A channel might be currently\n not in use for ROHC or feedback, it might be in use as\n a ROHC channel carrying packets and optional piggy-backed\n feedback, or it might be used as a dedicated feedback\n channel exclusively carrying feedback.')
rohcChannelFeedbackFor = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 4), RohcChannelIdentifierOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcChannelFeedbackFor.setDescription('The index of another channel of this interface for which\n the channel serves as feedback channel.\n\n If no feedback information is transferred on this channel,\n then the value of this ID is 0. If the channel type is set\n to notInUse(1), then the value of this object must be 0.\n If the channel type is rohc(2) and the value of this object\n is a valid channel ID, then feedback information is\n piggy-backed on the ROHC channel. If the channel type is\n dedicatedFeedback(3), then feedback is transferred on this\n channel and the value of this object MUST be different from\n 0 and MUST identify an existing ROHC channel.')
rohcChannelDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 5), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcChannelDescr.setDescription('A textual description of the channel.')
rohcChannelStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcChannelStatus.setDescription('Status of the channel.')
rohcInstanceTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 1, 2), )
if mibBuilder.loadTexts: rohcInstanceTable.setDescription('This table lists properties of running instances\n of robust header compressors and decompressors\n at IP interfaces. It is indexed by interface number,\n the type of instance (compressor or decompressor),\n and the ID of the channel used by the instance as\n ROHC channel.\n\n Note that the rohcChannelID uniquely identifies an\n instance. The ifIndex and rohcInstanceType are part\n of the index, because it simplifies accessing instances\n per interface and for addressing either compressors or\n decompressors only.')
rohcInstanceEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "ROHC-MIB", "rohcInstanceType"), (0, "ROHC-MIB", "rohcChannelID"))
if mibBuilder.loadTexts: rohcInstanceEntry.setDescription('An entry describing a particular instance\n of a robust header compressor or decompressor.')
rohcInstanceType = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("compressor", 1), ("decompressor", 2),)))
if mibBuilder.loadTexts: rohcInstanceType.setDescription('Type of the instance of ROHC. It is either a\n compressor instance or a decompressor instance.')
rohcInstanceFBChannelID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 4), RohcChannelIdentifierOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceFBChannelID.setDescription('Identifier of the channel used for feedback.\n If no feedback channel is used, the value of\n this object is 0 .')
rohcInstanceVendor = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 5), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceVendor.setDescription('An object identifier that identifies the vendor who\n provides the implementation of robust header description.\n This object identifier SHALL point to the object identifier\n directly below the enterprise object identifier\n {1 3 6 1 4 1} allocated for the vendor. The value must be\n the object identifier {0 0} if the vendor is not known.')
rohcInstanceVersion = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0,32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceVersion.setDescription('The version number of the implementation of robust header\n compression. The zero-length string shall be used if the\n implementation does not have a version number.\n\n\n\n\n It is suggested that the version number consist of one or\n more decimal numbers separated by dots, where the first\n number is called the major version number.')
rohcInstanceDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 7), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceDescr.setDescription('A textual description of the implementation.')
rohcInstanceClockRes = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 8), Unsigned32()).setUnits('milliseconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceClockRes.setDescription('This object indicates the system clock resolution in\n units of milliseconds. A zero (0) value means that there\n is no clock available.')
rohcInstanceMaxCID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 9), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1,16383))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceMaxCID.setDescription('The highest context ID number to be used by the\n compressor. Note that this parameter is not coupled to,\n but in effect further constrained by,\n rohcChannelLargeCIDs.')
rohcInstanceLargeCIDs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 10), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceLargeCIDs.setDescription('When retrieved, this boolean object returns false if\n the short CID representation (0 bytes or 1 prefix byte,\n covering CID 0 to 15) is used; it returns true, if the\n embedded CID representation (1 or 2 embedded CID bytes\n covering CID 0 to 16383) is used.')
rohcInstanceMRRU = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 11), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceMRRU.setDescription('Maximum reconstructed reception unit. This is the\n size of the largest reconstructed unit in octets that\n the decompressor is expected to reassemble from\n segments (see RFC 3095, Section 5.2.5). Note that this\n size includes the CRC. If MRRU is negotiated to be 0,\n no segment headers are allowed on the channel.')
rohcInstanceContextStorageTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 12), TimeInterval().clone(360000)).setUnits('centi-seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: rohcInstanceContextStorageTime.setDescription('This object indicates the default maximum amount of time\n information on a context belonging to this instance is kept\n as entry in the rohcContextTable after the context is\n expired or terminated. The value of this object is used\n to initialize rohcContexStorageTime object when a new\n context is created.\n Changing the value of an rohcInstanceContextStorageTime\n instance does not affect any entry of the rohcContextTable\n created previously.\n ROHC-MIB implementations SHOULD store the set value of this\n object persistently.')
rohcInstanceStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceStatus.setDescription('Status of the instance of ROHC.')
rohcInstanceContextsTotal = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceContextsTotal.setDescription('Counter of all contexts created by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.')
rohcInstanceContextsCurrent = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 15), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceContextsCurrent.setDescription('Number of currently active contexts created by this\n instance.')
rohcInstancePackets = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstancePackets.setDescription('Counter of all packets passing this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.')
rohcInstanceIRs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceIRs.setDescription('The number of all IR packets that are either sent\n or received by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n\n\n\n value of ifCounterDiscontinuityTime.')
rohcInstanceIRDYNs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceIRDYNs.setDescription('The number of all IR-DYN packets that are either sent\n or received by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.')
rohcInstanceFeedbacks = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceFeedbacks.setDescription('The number of all feedbacks that are either sent\n or received by this instance.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime.')
rohcInstanceCompressionRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 2, 1, 20), RohcCompressionRatio()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcInstanceCompressionRatio.setDescription('This object indicates the compression ratio so far over all\n packets on the channel served by this instance. The\n compression is computed over all bytes of the IP packets\n including the IP header but excluding all lower layer\n headers.')
rohcProfileTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 1, 3), )
if mibBuilder.loadTexts: rohcProfileTable.setDescription('This table lists a set of profiles supported by the\n instance.')
rohcProfileEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1), ).setIndexNames((0, "ROHC-MIB", "rohcChannelID"), (0, "ROHC-MIB", "rohcProfile"))
if mibBuilder.loadTexts: rohcProfileEntry.setDescription('An entry describing a particular profile supported by\n the instance. It is indexed by the rohcChannelID\n identifying the instance and by the rohcProfile.')
rohcProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,65535)))
if mibBuilder.loadTexts: rohcProfile.setDescription("Identifier of a profile supported. For a listing of\n possible profile values, see the IANA registry for\n 'RObust Header Compression (ROHC) Profile Identifiers'\n at http://www.iana.org/assignments/rohc-pro-ids")
rohcProfileVendor = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 3), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcProfileVendor.setDescription('An object identifier that identifies the vendor who\n provides the implementation of robust header description.\n This object identifier SHALL point to the object identifier\n directly below the enterprise object identifier\n {1 3 6 1 4 1} allocated for the vendor. The value must be\n the object identifier {0 0} if the vendor is not known.')
rohcProfileVersion = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 4), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0,32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcProfileVersion.setDescription('The version number of the implementation of robust header\n compression. The zero-length string shall be used if the\n implementation does not have a version number.\n\n It is suggested that the version number consist of one or\n more decimal numbers separated by dots, where the first\n number is called the major version number.')
rohcProfileDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 5), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcProfileDescr.setDescription('A textual description of the implementation.')
rohcProfileNegotiated = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 1, 3, 1, 6), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcProfileNegotiated.setDescription('When retrieved, this boolean object returns true\n if the profile has been negotiated to be used at\n the instance, i.e., is supported also be the\n corresponding compressor/decompressor.')
rohcContextTable = MibTable((1, 3, 6, 1, 2, 1, 112, 1, 2), )
if mibBuilder.loadTexts: rohcContextTable.setDescription('This table lists and describes all compressor contexts\n per instance.')
rohcContextEntry = MibTableRow((1, 3, 6, 1, 2, 1, 112, 1, 2, 1), ).setIndexNames((0, "ROHC-MIB", "rohcChannelID"), (0, "ROHC-MIB", "rohcContextCID"))
if mibBuilder.loadTexts: rohcContextEntry.setDescription('An entry describing a particular compressor context.')
rohcContextCID = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,16383)))
if mibBuilder.loadTexts: rohcContextCID.setDescription('The context identifier (CID) of this context.')
rohcContextCIDState = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("unused", 1), ("active", 2), ("expired", 3), ("terminated", 4),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextCIDState.setDescription("State of the CID. When a CID is assigned to a context,\n its state changes from `unused' to `active'. The active\n context may stop operation due to some explicit\n signalling or after observing no packet for some specified\n time. In the first case then the CID state changes to\n `terminated', in the latter case it changes to `expired'.\n If the CID is re-used again for another context, the\n state changes back to `active'.")
rohcContextProfile = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0,65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextProfile.setDescription('Identifier of the profile for this context.\n The profile is identified by its index in the\n rohcProfileTable for this instance. There MUST exist a\n corresponding entry in the rohcProfileTable using the\n value of rohcContextProfile as second part of the index\n (and using the same rohcChannelID as first part of the\n index).')
rohcContextDecompressorDepth = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextDecompressorDepth.setDescription('This object indicates whether reverse decompression, for\n example as described in RFC 3095, Section 6.1, is used\n on this channel or not, and if used, to what extent.\n\n\n\n\n Its value is only valid for decompressor contexts, i.e.,\n if rohcInstanceType has the value decompressor(2). For\n compressor contexts where rohcInstanceType has the value\n compressor(1), the value of this object is irrelevant\n and MUST be set to zero (0).\n\n The value of the reverse decompression depth indicates\n the maximum number of packets that are buffered, and thus\n possibly be reverse decompressed by the decompressor.\n A zero (0) value means that reverse decompression is not\n used.')
rohcContextStorageTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 6), TimeInterval()).setUnits('centi-seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: rohcContextStorageTime.setDescription('The value of this object specifies how long this row\n can exist in the rohcContextTable after the\n rohcContextCIDState switched to expired(3) or\n terminated(4). This object returns the remaining time\n that the row may exist before it is aged out. The object\n is initialized with the value of the associated\n rohcContextStorageTime object. After expiration or\n termination of the context, the value of this object ticks\n backwards. The entry in the rohcContextTable is destroyed\n when the value reaches 0.\n\n The value of this object may be set in order to increase or\n reduce the remaining time that the row may exist. Setting\n the value to 0 will destroy this entry as soon as the\n rochContextCIDState has the value expired(3) or\n terminated(4).\n\n Note that there is no guarantee that the row is stored as\n long as this object indicates. In case of limited CID\n space, the instance may re-use a CID before the storage\n time of the corresponding row in rohcContextTable reaches\n the value of 0. In this case the information stored in this\n row is not anymore available.')
rohcContextActivationTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 7), DateAndTime().clone(hexValue="0000000000000000")).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextActivationTime.setDescription("The date and time when the context started to be able to\n compress packets or decompress packets, respectively.\n The value '0000000000000000'H is returned if the context\n has not been activated yet.")
rohcContextDeactivationTime = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 8), DateAndTime().clone(hexValue="0000000000000000")).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextDeactivationTime.setDescription("The date and time when the context stopped being able to\n compress packets or decompress packets, respectively,\n because it expired or was terminated for other reasons.\n The value '0000000000000000'H is returned if the context\n has not been deactivated yet.")
rohcContextPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextPackets.setDescription('The number of all packets passing this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.')
rohcContextIRs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextIRs.setDescription('The number of all IR packets sent or received,\n respectively, by this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n\n\n\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.')
rohcContextIRDYNs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextIRDYNs.setDescription('The number of all IR-DYN packets sent or received,\n respectively, by this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.')
rohcContextFeedbacks = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextFeedbacks.setDescription('The number of all feedbacks sent or received,\n respectively, by this context.\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.')
rohcContextDecompressorFailures = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextDecompressorFailures.setDescription('The number of all decompressor failures so far in this\n context. The number is only valid for decompressor\n contexts, i.e., if rohcInstanceType has the value\n decompressor(2).\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.')
rohcContextDecompressorRepairs = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextDecompressorRepairs.setDescription('The number of all context repairs so far in this\n context. The number is only valid for decompressor\n contexts, i.e., if rohcInstanceType has the value\n decompressor(2).\n\n Discontinuities in the value of this counter can\n occur at re-initialization of the management\n system, and at other times as indicated by the\n value of ifCounterDiscontinuityTime. For checking\n ifCounterDiscontinuityTime, the interface index is\n required. It can be determined by reading the\n rohcChannelTable.')
rohcContextAllPacketsRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 15), RohcCompressionRatio()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextAllPacketsRatio.setDescription('This object indicates the compression ratio so far over all\n packets passing this context. The compression is computed\n over all bytes of the IP packets including the IP header\n but excluding all lower layer headers.')
rohcContextAllHeadersRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 16), RohcCompressionRatio()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextAllHeadersRatio.setDescription('This object indicates the compression ratio so far over all\n packet headers passing this context. The compression is\n computed over all bytes of all headers that are subject to\n compression for the used profile.')
rohcContextAllPacketsMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 17), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextAllPacketsMeanSize.setDescription('This object indicates the mean compressed packet size\n of all packets passing this context. The packet size\n includes the IP header and payload but excludes all lower\n layer headers. The mean value is given in byte rounded\n to the next integer value.')
rohcContextAllHeadersMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 18), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextAllHeadersMeanSize.setDescription('This object indicates the mean compressed packet header size\n of all packets passing this context. The packet header size\n is the sum of the size of all headers of a packet that are\n subject to compression for the used profile. The mean value\n is given in byte rounded to the next integer value.')
rohcContextLastPacketsRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 19), RohcCompressionRatio()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextLastPacketsRatio.setDescription('This object indicates the compression ratio\n concerning the last 16 packets passing this context\n or concerning all packets passing this context\n if they are less than 16, so far. The compression is\n computed over all bytes of the IP packets including the IP\n header but excluding all lower layer headers.')
rohcContextLastHeadersRatio = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 20), RohcCompressionRatio()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextLastHeadersRatio.setDescription('This object indicates the compression ratio concerning the\n headers of the last 16 packets passing this context or\n concerning the headers of all packets passing this context\n if they are less than 16, so far. The compression is\n computed over all bytes of all headers that are subject to\n compression for the used profile.')
rohcContextLastPacketsMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 21), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextLastPacketsMeanSize.setDescription('This object indicates the mean compressed packet size\n concerning the last 16 packets passing this context or\n concerning all packets passing this context if they are\n less than 16, so far. The packet size includes the IP\n header and payload but excludes all lower layer headers.\n The mean value is given in byte rounded to the next\n integer value.')
rohcContextLastHeadersMeanSize = MibTableColumn((1, 3, 6, 1, 2, 1, 112, 1, 2, 1, 22), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rohcContextLastHeadersMeanSize.setDescription('This object indicates the mean compressed packet header size\n concerning the last 16 packets passing this context or\n concerning all packets passing this context if they are\n less than 16, so far. The packet header size is the sum of\n the size of all headers of a packet that are subject to\n compression for the used profile. The mean value is given\n in byte rounded to the next integer value.')
rohcCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 2, 1))
rohcGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 112, 2, 2))
rohcCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 112, 2, 1, 1)).setObjects(*(("ROHC-MIB", "rohcInstanceGroup"), ("ROHC-MIB", "rohcContextGroup"), ("ROHC-MIB", "rohcStatisticsGroup"), ("ROHC-MIB", "rohcTimerGroup"), ("ROHC-MIB", "rohcContextStatisticsGroup"),))
if mibBuilder.loadTexts: rohcCompliance.setDescription('The compliance statement for SNMP entities that implement\n the ROHC-MIB.\n\n Note that compliance with this compliance\n statement requires compliance with the\n ifCompliance3 MODULE-COMPLIANCE statement of the\n IF-MIB (RFC2863).')
rohcInstanceGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 2)).setObjects(*(("ROHC-MIB", "rohcChannelType"), ("ROHC-MIB", "rohcChannelFeedbackFor"), ("ROHC-MIB", "rohcChannelDescr"), ("ROHC-MIB", "rohcChannelStatus"), ("ROHC-MIB", "rohcInstanceFBChannelID"), ("ROHC-MIB", "rohcInstanceVendor"), ("ROHC-MIB", "rohcInstanceVersion"), ("ROHC-MIB", "rohcInstanceDescr"), ("ROHC-MIB", "rohcInstanceClockRes"), ("ROHC-MIB", "rohcInstanceMaxCID"), ("ROHC-MIB", "rohcInstanceLargeCIDs"), ("ROHC-MIB", "rohcInstanceMRRU"), ("ROHC-MIB", "rohcInstanceStatus"), ("ROHC-MIB", "rohcProfileVendor"), ("ROHC-MIB", "rohcProfileVersion"), ("ROHC-MIB", "rohcProfileDescr"), ("ROHC-MIB", "rohcProfileNegotiated"),))
if mibBuilder.loadTexts: rohcInstanceGroup.setDescription('A collection of objects providing information about\n ROHC instances, used channels and available profiles.')
rohcStatisticsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 4)).setObjects(*(("ROHC-MIB", "rohcInstanceContextsTotal"), ("ROHC-MIB", "rohcInstanceContextsCurrent"), ("ROHC-MIB", "rohcInstancePackets"), ("ROHC-MIB", "rohcInstanceIRs"), ("ROHC-MIB", "rohcInstanceIRDYNs"), ("ROHC-MIB", "rohcInstanceFeedbacks"), ("ROHC-MIB", "rohcInstanceCompressionRatio"),))
if mibBuilder.loadTexts: rohcStatisticsGroup.setDescription('A collection of objects providing ROHC statistics.')
rohcContextGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 5)).setObjects(*(("ROHC-MIB", "rohcContextCIDState"), ("ROHC-MIB", "rohcContextProfile"), ("ROHC-MIB", "rohcContextDecompressorDepth"),))
if mibBuilder.loadTexts: rohcContextGroup.setDescription('A collection of objects providing information about\n ROHC compressor contexts and decompressor contexts.')
rohcTimerGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 6)).setObjects(*(("ROHC-MIB", "rohcInstanceContextStorageTime"), ("ROHC-MIB", "rohcContextStorageTime"), ("ROHC-MIB", "rohcContextActivationTime"), ("ROHC-MIB", "rohcContextDeactivationTime"),))
if mibBuilder.loadTexts: rohcTimerGroup.setDescription('A collection of objects providing statistical information\n about ROHC compressor contexts and decompressor contexts.')
rohcContextStatisticsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 112, 2, 2, 7)).setObjects(*(("ROHC-MIB", "rohcContextPackets"), ("ROHC-MIB", "rohcContextIRs"), ("ROHC-MIB", "rohcContextIRDYNs"), ("ROHC-MIB", "rohcContextFeedbacks"), ("ROHC-MIB", "rohcContextDecompressorFailures"), ("ROHC-MIB", "rohcContextDecompressorRepairs"), ("ROHC-MIB", "rohcContextAllPacketsRatio"), ("ROHC-MIB", "rohcContextAllHeadersRatio"), ("ROHC-MIB", "rohcContextAllPacketsMeanSize"), ("ROHC-MIB", "rohcContextAllHeadersMeanSize"), ("ROHC-MIB", "rohcContextLastPacketsRatio"), ("ROHC-MIB", "rohcContextLastHeadersRatio"), ("ROHC-MIB", "rohcContextLastPacketsMeanSize"), ("ROHC-MIB", "rohcContextLastHeadersMeanSize"),))
if mibBuilder.loadTexts: rohcContextStatisticsGroup.setDescription('A collection of objects providing statistical information\n about ROHC compressor contexts and decompressor contexts.')
mibBuilder.exportSymbols("ROHC-MIB", rohcProfileVendor=rohcProfileVendor, rohcInstanceEntry=rohcInstanceEntry, rohcContextDecompressorDepth=rohcContextDecompressorDepth, rohcInstanceIRs=rohcInstanceIRs, rohcChannelID=rohcChannelID, rohcContextTable=rohcContextTable, rohcContextDeactivationTime=rohcContextDeactivationTime, rohcInstanceContextsCurrent=rohcInstanceContextsCurrent, rohcInstanceTable=rohcInstanceTable, rohcInstanceMaxCID=rohcInstanceMaxCID, rohcInstanceFBChannelID=rohcInstanceFBChannelID, RohcChannelIdentifierOrZero=RohcChannelIdentifierOrZero, rohcContextFeedbacks=rohcContextFeedbacks, rohcMIB=rohcMIB, rohcTimerGroup=rohcTimerGroup, rohcContextDecompressorRepairs=rohcContextDecompressorRepairs, rohcInstanceContextStorageTime=rohcInstanceContextStorageTime, rohcInstanceGroup=rohcInstanceGroup, RohcCompressionRatio=RohcCompressionRatio, rohcContextPackets=rohcContextPackets, rohcInstanceLargeCIDs=rohcInstanceLargeCIDs, rohcStatisticsGroup=rohcStatisticsGroup, rohcProfileVersion=rohcProfileVersion, rohcContextLastPacketsMeanSize=rohcContextLastPacketsMeanSize, rohcChannelDescr=rohcChannelDescr, rohcObjects=rohcObjects, rohcContextIRs=rohcContextIRs, rohcContextAllHeadersMeanSize=rohcContextAllHeadersMeanSize, rohcInstancePackets=rohcInstancePackets, rohcContextDecompressorFailures=rohcContextDecompressorFailures, rohcCompliances=rohcCompliances, rohcInstanceStatus=rohcInstanceStatus, rohcContextLastPacketsRatio=rohcContextLastPacketsRatio, rohcInstanceVendor=rohcInstanceVendor, rohcContextLastHeadersMeanSize=rohcContextLastHeadersMeanSize, rohcContextProfile=rohcContextProfile, rohcChannelEntry=rohcChannelEntry, rohcInstanceVersion=rohcInstanceVersion, rohcInstanceFeedbacks=rohcInstanceFeedbacks, rohcContextStorageTime=rohcContextStorageTime, rohcContextAllPacketsMeanSize=rohcContextAllPacketsMeanSize, rohcChannelTable=rohcChannelTable, rohcContextActivationTime=rohcContextActivationTime, rohcContextIRDYNs=rohcContextIRDYNs, rohcContextCID=rohcContextCID, rohcInstanceClockRes=rohcInstanceClockRes, rohcContextCIDState=rohcContextCIDState, rohcProfile=rohcProfile, rohcContextLastHeadersRatio=rohcContextLastHeadersRatio, rohcInstanceCompressionRatio=rohcInstanceCompressionRatio, rohcProfileDescr=rohcProfileDescr, rohcGroups=rohcGroups, rohcChannelStatus=rohcChannelStatus, rohcCompliance=rohcCompliance, rohcProfileNegotiated=rohcProfileNegotiated, PYSNMP_MODULE_ID=rohcMIB, RohcChannelIdentifier=RohcChannelIdentifier, rohcProfileEntry=rohcProfileEntry, rohcChannelType=rohcChannelType, rohcContextGroup=rohcContextGroup, rohcInstanceMRRU=rohcInstanceMRRU, rohcInstanceIRDYNs=rohcInstanceIRDYNs, rohcContextEntry=rohcContextEntry, rohcChannelFeedbackFor=rohcChannelFeedbackFor, rohcContextStatisticsGroup=rohcContextStatisticsGroup, rohcContextAllHeadersRatio=rohcContextAllHeadersRatio, rohcProfileTable=rohcProfileTable, rohcConformance=rohcConformance, rohcInstanceType=rohcInstanceType, rohcInstanceContextsTotal=rohcInstanceContextsTotal, rohcInstanceDescr=rohcInstanceDescr, rohcInstanceObjects=rohcInstanceObjects, rohcContextAllPacketsRatio=rohcContextAllPacketsRatio)
| 40,407 | 13,431 |
from autogluon.features.generators import DatetimeFeatureGenerator
def test_datetime_feature_generator(generator_helper, data_helper):
# Given
input_data = data_helper.generate_multi_feature_full()
generator_1 = DatetimeFeatureGenerator()
generator_2 = DatetimeFeatureGenerator(features = ['hour'])
expected_feature_metadata_in_full = {
('datetime', ()): ['datetime'],
('object', ('datetime_as_object',)): ['datetime_as_object'],
}
expected_feature_metadata_full_1 = {('int', ('datetime_as_int',)): [
'datetime',
'datetime.year',
'datetime.month',
'datetime.day',
'datetime.dayofweek',
'datetime_as_object',
'datetime_as_object.year',
'datetime_as_object.month',
'datetime_as_object.day',
'datetime_as_object.dayofweek'
]}
expected_feature_metadata_full_2 = {('int', ('datetime_as_int',)): [
'datetime',
'datetime.hour',
'datetime_as_object',
'datetime_as_object.hour',
]}
expected_output_data_feat_datetime = [
1533140820000000000,
1301322000000000000,
1301322000000000000,
1524238620000000000,
1524238620000000000,
-5364662400000000000,
7289654340000000000,
1301322000000000000,
1301322000000000000
]
expected_output_data_feat_datetime_year = [
2018,
2011, # blank and nan values are set to the mean of good values = 2011
2011,
2018,
2018,
1800,
2200,
2011, # 2700 and 1000 are out of range for a pandas datetime so they are set to the mean
2011 # see limits at https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.max.html
]
expected_output_data_feat_datetime_hour = [
16,
14,
14,
15,
15,
0,
23,
14,
14
]
# When
output_data_1 = generator_helper.fit_transform_assert(
input_data=input_data,
generator=generator_1,
expected_feature_metadata_in_full=expected_feature_metadata_in_full,
expected_feature_metadata_full=expected_feature_metadata_full_1,
)
assert list(output_data_1['datetime'].values) == list(output_data_1['datetime_as_object'].values)
assert expected_output_data_feat_datetime == list(output_data_1['datetime'].values)
assert expected_output_data_feat_datetime_year == list(output_data_1['datetime.year'].values)
output_data_2 = generator_helper.fit_transform_assert(
input_data=input_data,
generator=generator_2,
expected_feature_metadata_in_full=expected_feature_metadata_in_full,
expected_feature_metadata_full=expected_feature_metadata_full_2,
)
assert list(output_data_2['datetime'].values) == list(output_data_2['datetime_as_object'].values)
assert expected_output_data_feat_datetime == list(output_data_2['datetime'].values)
assert expected_output_data_feat_datetime_hour == list(output_data_2['datetime.hour'].values)
| 3,085 | 1,101 |
#!/usr/bin/env python
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0"
import common as cm
import tensorflow as tf
import numpy as np
import math
from scipy import stats
from Bio.Seq import Seq
half_size = 500
batch_size = 128
scan_step = 1
seq_len = 1001
out = []
os.chdir(open("../data_dir").read().strip())
fasta = cm.parse_genome("data/genomes/hg19.fa")
# fasta = pickle.load(open("fasta.p", "rb"))
background = {}
background["RPLP0_CE_bg"] = ["chr12", "-", 120638861 - 1, 120639013 - 1]
background["ACTB_CE_bg"] = ["chr7", "-", 5570183 - 1, 5570335 - 1]
background["C14orf166_CE_bg"] = ["chr14", "+", 52456090 - 1, 52456242 - 1]
our_scores = []
real_scores = []
new_graph = tf.Graph()
with tf.Session(graph=new_graph) as sess:
tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], "models/model_predict")
saver = tf.train.Saver()
saver.restore(sess, "models/model_predict/variables/variables")
input_x = tf.get_default_graph().get_tensor_by_name("input_prom:0")
y = tf.get_default_graph().get_tensor_by_name("output_prom:0")
kr = tf.get_default_graph().get_tensor_by_name("kr:0")
in_training_mode = tf.get_default_graph().get_tensor_by_name("in_training_mode:0")
with open('data/Supplemental_Table_S7.tsv') as file:
next(file)
for line in file:
vals = line.split("\t")
fa = vals[25].strip()
if(vals[3] in background.keys()):
bg = background[vals[3]]
strand = bg[1]
real_score = float(vals[23])
if math.isnan(real_score):
continue
real_scores.append(real_score)
if (strand == "+"):
fa_bg = fasta[bg[0]][bg[2] - (half_size - 114): bg[2] - (half_size - 114) + seq_len]
faf = fa_bg[:half_size - 49] + fa + fa_bg[half_size + 115:]
else:
fa_bg = fasta[bg[0]][bg[2] - (half_size - 49): bg[2] - (half_size - 49) + seq_len]
fa_bg = str(Seq(fa_bg).reverse_complement())
faf = fa_bg[:half_size - 114] + fa + fa_bg[half_size + 50:]
predict = sess.run(y,
feed_dict={input_x: [cm.encode_seq(faf)], kr: 1.0, in_training_mode: False})
score = predict[0][0] - predict[0][1]
score = math.log(1 + score / (1.0001 - score))
our_scores.append(score)
out.append(str(real_score) + "," + str(score))
real_scores = np.asarray(real_scores)
corr = stats.pearsonr(np.asarray(our_scores), np.asarray(real_scores))[0]
print(corr)
with open("figures_data/synth.csv", 'w+') as f:
f.write('\n'.join(out)) | 2,785 | 1,096 |
from strong_but_simple_passwords import views
def test_index_http_ok(client):
response = client.get("/")
assert response.status_code == 200
def test_empty_post(monkeypatch, client):
a_random_sentence = "A random sentence."
monkeypatch.setattr(views, "get_random_sentence", lambda: a_random_sentence)
response = client.post("/")
assert response.status_code == 200
assert a_random_sentence in str(response.data)
def test_strong_password(client):
payload = {"input_sentence": "A very long input sentence for a strong password"}
response = client.post("/", data=payload)
assert response.status_code == 200
assert b"Congratulations!" in response.data
assert b"centuries" in response.data
| 740 | 235 |
#!/usr/bin/env python3
import sys
def search(query, data):
query = query.replace('-',' ')
words = set(query.upper().split())
for code, char, name in data:
name = name.replace('-',' ')
if words <= set(name.split()):
yield f'{code}\t{char}\t{name}'
def reader():
with open('UnicodeData.txt') as _file:
for line in _file:
code, name = line.split(';')[:2]
char = chr(int(code, 16))
yield f'U+{code}', char, name
def main(*words):
if len(words) < 1:
print("Please provide one word or more", file=sys.stderr)
return
query = ' '.join(words)
index = -1
for index, line in enumerate(search(query, reader())):
print(line)
if index == -1:
print("No results", file=sys.stderr)
if __name__ == "__main__":
main(*sys.argv[1:])
| 865 | 293 |
import json
from django.shortcuts import render, redirect, HttpResponse
# Create your views here.
from django.urls import reverse
from app01 import models
from app01.models import Book, Publish, Author, AuthorDetail
def books(request):
book_list = Book.objects.all()
publish_list = Publish.objects.all()
author_list = Author.objects.all()
return render(request, 'books.html', {'book_list': book_list, 'publish_list': publish_list, 'author_list': author_list})
def add_book(request):
if request.method == 'GET':
publish_list = Publish.objects.all()
author_list = Author.objects.all()
return render(request, 'book_add.html', {'publish_list': publish_list, 'author_list': author_list})
else:
title = request.POST.get('title')
price = request.POST.get('price')
pub_date = request.POST.get('pub_date')
publish = request.POST.get('publish')
authors = request.POST.getlist('authors')
book = Book.objects.create(title=title, price=price, pub_date=pub_date, publish_id=publish)
book.authors.add(*authors)
return redirect('/books/')
def del_book(request):
book_id = request.POST.get('id_book')
print(book_id)
ret = Book.objects.filter(id=book_id).delete()
if ret:
return HttpResponse('True')
else:
return HttpResponse('False')
def up_book(request, book_id):
if request.method == 'GET':
book_up_list = Book.objects.filter(id=book_id)
publish_list = Publish.objects.all()
author_list = Author.objects.all()
book = Book.objects.filter(id=book_id).values('publish')[0]
author = Book.objects.filter(id=book_id).values('authors')[0]
publish_name = Publish.objects.filter(id=book['publish']).first()
author_name = Author.objects.filter(id=author['authors']).first()
return render(request, 'up_book.html',
{'book_up_list': book_up_list, 'publish_list': publish_list, 'author_list': author_list,
'publish_name': publish_name, 'author_name': author_name})
else:
title = request.POST.get('title')
price = request.POST.get('price')
pub_date = request.POST.get('pub_date')
publish = request.POST.get('publish')
authors = request.POST.getlist('authors')
# a_list = {'author_id': authors}
print(authors)
date_list = {'title': title, 'price': price, 'pub_date': pub_date, 'publish_id': publish}
Book.objects.filter(id=book_id).update(**date_list)
book = Book.objects.filter(id=book_id).first()
book.authors.set(authors)
return redirect(reverse('books'))
def publishs(request):
publish_list = Publish.objects.all()
return render(request, 'publishs.html', {'publish_list': publish_list})
def add_publish(request):
if request.method == 'GET':
return render(request, 'publish_add.html')
else:
name = request.POST.get('name')
email = request.POST.get('email')
Publish.objects.create(name=name, email=email)
return redirect('/publishs/')
def del_publish(request, publish_id):
Publish.objects.filter(id=publish_id).delete()
return redirect('/publishs/')
def up_publish(request, publish_id):
if request.method == 'GET':
publish = Publish.objects.filter(id=publish_id)
return render(request, 'up_publish.html', {'publish': publish})
else:
publish = request.POST.dict()
del publish['csrfmiddlewaretoken']
Publish.objects.filter(id=publish_id).update(**publish)
return redirect('/publishs/')
def authors(request):
author_list = Author.objects.all()
return render(request, 'authors.html', {'author_list': author_list})
def add_author(request):
if request.method == 'GET':
return render(request, 'author_add.html')
else:
name = request.POST.get('name')
age = request.POST.get('age')
email = request.POST.get('email')
tel = request.POST.get('tel')
tels = AuthorDetail.objects.create(tel=tel)
author = Author.objects.create(name=name, age=age, email=email, ad=tels)
return redirect('/authors/')
def del_author(request, author_id):
author = Author.objects.filter(id=author_id)
ad_id = author.values('ad_id')[0]['ad_id']
author.delete()
AuthorDetail.objects.filter(id=ad_id).delete()
return redirect('/authors/')
def up_author(request, author_id):
if request.method == 'GET':
author = Author.objects.filter(id=author_id)
return render(request, 'up_author.html', {'author': author})
else:
name = request.POST.get('name')
age = request.POST.get('age')
email = request.POST.get('email')
tel = request.POST.get('tel')
author = Author.objects.filter(id=author_id)
author.update(name=name, age=age, email=email)
AuthorDetail.objects.filter(id=author.values('ad_id')[0]['ad_id']).update(tel=tel)
return redirect('/authors/')
def ajax_add_book(request):
authors_list = []
title = request.POST.get('title')
price = str(format(int(request.POST.get('price')), '.2f'))
pub_date = request.POST.get('pub_date')
publish = request.POST.get('publish')
authors = request.POST.getlist('authors')
book = Book.objects.create(title=title, price=price, pub_date=pub_date, publish_id=publish)
print(price)
book.authors.add(*authors)
count_book = Book.objects.all().count()
publish_name = Publish.objects.filter(id=publish).first()
authors_name = Author.objects.filter(id__in=authors)
for i in authors_name:
authors_list.append(i.name)
data_dict = {
'pd': 'true',
'book_id': book.id,
'count_book': count_book,
'title': title,
'price': price,
'pub_date': pub_date,
'publish_name': publish_name.name,
'authors': authors_list
}
# print(authors, publish)
if book:
data_dict['pd'] = 'true'
else:
data_dict['pd'] = 'false'
return HttpResponse(json.dumps(data_dict)) | 6,154 | 1,916 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Talk with a model using a Slack channel.
# Examples
```shell
parlai interactive_slack --token xoxb-... --task blended_skill_talk:all -mf zoo:blenderbot2/blenderbot2_400M/model --search-server http://localhost:5000```
"""
from os import getenv
from pprint import pformat
from parlai.scripts.interactive import setup_args
from parlai.core.agents import create_agent
from parlai.core.worlds import create_task
from parlai.core.script import ParlaiScript, register_script
import parlai.utils.logging as logging
from parlai.agents.local_human.local_human import LocalHumanAgent
try:
from slack import RTMClient
except ImportError:
raise ImportError('The slackclient package must be installed to run this script')
SHARED = {}
SLACK_BOT_TOKEN = getenv('SLACK_BOT_TOKEN')
def setup_slack_args(shared):
"""
Build and parse CLI opts.
"""
parser = setup_args()
parser.description = 'Interactive chat with a model in a Slack channel'
parser.add_argument(
'--token',
default=SLACK_BOT_TOKEN,
metavar='SLACK_BOT_TOKEN',
help='A legacy Slack bot token to use for RTM messaging',
)
return parser
@RTMClient.run_on(event='message')
async def rtm_handler(rtm_client, web_client, data, **kwargs):
"""
Handles new chat messages from Slack.
Does the following to let the user know immediately that the agent is working since it takes a while
Adds the :eyes: reaction to let the user
Sets the status of the bot to typing
Runs the agent on the given text
Returns the model_response text to the channel where the message came from.
Removes the :eyes: reaction
Only works on user messages, not messages from other bots
"""
global SHARED
if 'bot_profile' in data:
# Dont respond to bot messages (eg the one this app generates)
return
logging.info(f'Got new message {pformat(data)}')
channel = data['channel']
web_client.reactions_add(channel=channel, name='eyes', timestamp=data['ts'])
reply = {'episode_done': False, 'text': data['text']}
SHARED['agent'].observe(reply)
logging.info('Agent observed')
await rtm_client.typing(channel=channel)
model_response = SHARED['agent'].act()
logging.info('Agent acted')
web_client.chat_postMessage(channel=channel, text=model_response['text'])
logging.info(f'Sent response: {model_response["text"]}')
web_client.reactions_remove(channel=channel, name='eyes', timestamp=data['ts'])
def interactive_slack(opt):
global SHARED
if not opt.get('token'):
raise RuntimeError(
'A Slack bot token must be specified. Must be a legacy bot app token for RTM messaging'
)
human_agent = LocalHumanAgent(opt)
agent = create_agent(opt, requireModelExists=True)
agent.opt.log()
agent.opt['verbose'] = True
SHARED['opt'] = agent.opt
SHARED['agent'] = agent
SHARED['world'] = create_task(SHARED.get('opt'), [human_agent, SHARED['agent']])
SHARED['client'] = client = RTMClient(token=opt['token'])
logging.info('Slack client is starting')
client.start()
@register_script('interactive_slack', aliases=['slack'], hidden=True)
class InteractiveSlack(ParlaiScript):
@classmethod
def setup_args(cls):
return setup_slack_args(SHARED)
def run(self):
return interactive_slack(self.opt)
if __name__ == '__main__':
InteractiveSlack.main()
| 3,642 | 1,147 |
'''
Includes content from another template. If you assign any keyword arguments,
those will be available in the scope of that template.
'''
import os
from plywood import Plywood
from plywood.values import PlywoodValue
from plywood.exceptions import InvalidArguments
from plywood.env import PlywoodEnv
@PlywoodEnv.register_runtime()
def include(states, scope, arguments, block):
if len(arguments.args) != 1:
raise InvalidArguments('`include` only accepts one argument')
if len(block.lines):
raise InvalidArguments('`include` does not accept a block')
restore_scope = {}
delete_scope = []
if isinstance(scope['self'], PlywoodValue):
context = scope['self'].python_value(scope)
else:
context = scope['self']
if len(arguments.kwargs):
kwargs = dict(
(item.key.get_name(), item.value)
for item in arguments.kwargs
)
for key, value in kwargs.items():
if key in context:
restore_scope[key] = context[key]
else:
delete_scope.append(key)
context[key] = value
if '__env' in scope:
env = scope['__env']
else:
env = PlywoodEnv({'separator': ' '})
template_name = arguments.args[0].python_value(scope)
plywood = None
for path in scope['__paths']:
template_path = os.path.join(path, template_name) + '.ply'
if template_path in env.includes:
plywood = env.includes[template_path]
elif os.path.exists(template_path):
retval = ''
with open(template_path) as f:
input = f.read()
plywood = Plywood(input)
env.includes[template_path] = plywood
# scope is not pushed/popped - `include` adds its variables to the local scope.
if plywood:
break
if not plywood:
raise Exception('Could not find template: {0!r}'.format(template_name))
retval = plywood.run(context, env)
if len(arguments.kwargs):
for key, value in restore_scope.items():
context[key] = value
for key in delete_scope:
del context[key]
return states, retval
@PlywoodEnv.register_startup()
def startup(plywood, scope):
if plywood.options.get('paths'):
scope['__paths'] = plywood.options.get('paths')
elif plywood.options.get('path'):
scope['__paths'] = [plywood.options.get('path')]
else:
scope['__paths'] = [os.getcwd()]
| 2,542 | 718 |
"""Handle M3U files generation"""
import os
import logging
def generate(software, out_dir, suffix, dry_run):
"""Generate M3U file for the given software into out_dir"""
m3u_filename = software.name + (suffix if suffix else '') + '.m3u'
if not dry_run:
m3u_fd = open(os.path.join(out_dir, m3u_filename), 'w')
for i in software.images():
image_rel_path = os.path.relpath(i.path, out_dir)
if not dry_run:
m3u_fd.write((image_rel_path + '\n'))
if not dry_run:
m3u_fd.close()
logging.info('Created M3U file for %s (%i image files)',
software.name, len(software.images()))
def generate_all(softwares, out_dir, suffix, dry_run):
"""Generate M3U file for the list of softwares into out_dir"""
if not dry_run:
if not out_dir.exists():
out_dir.mkdir(parents=True)
multi_images_softwares = (x for x in softwares if x.nb_images() > 1)
for i in multi_images_softwares:
try:
generate(i, out_dir, suffix, dry_run)
except UnicodeEncodeError:
logging.warning("Unicode error while processing %s", ascii(i.name))
| 1,178 | 402 |
class Solution(object):
def XXXUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return []
nums.sort()
n = len(nums)
visited = [0] * n
res = []
def helper1(temp_list, length):
# if length == n and temp_list not in res:
# res.append(temp_list)
if length == n:
res.append(temp_list)
for i in range(n):
if visited[i] or (i > 0 and nums[i] == nums[i - 1] and not visited[i - 1]):
continue
visited[i] = 1
helper1(temp_list + [nums[i]], length + 1)
visited[i] = 0
def helper2(nums, temp_list, length):
if length == n and temp_list not in res:
res.append(temp_list)
for i in range(len(nums)):
helper2(nums[:i] + nums[i + 1:], temp_list + [nums[i]], length + 1)
helper1([],0)
# helper2(nums, [], 0)
return res
| 860 | 400 |
import os
import sys
import shutil
import io
# if you got module not found errors, uncomment these. PyCharm IDE does not need it.
# get the abs version of . and .. and append them to this process's path.
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('.'))
#print sys.path
import unittest
import subprocess
import testutils as tu
import libuvs.systemdefaults as sdef
from libuvs import uvsmanager
class TestUVSCli(unittest.TestCase):
repo_root_path = None
repo_root_cksums_file = None
# This will run once for all tests in this class,
@classmethod
def setUpClass(cls):
super(TestUVSCli, cls).setUpClass()
cwd = os.getcwd()
print "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> setUpClass() called from cwd: " + str(cwd)
tests_folder_abs_path = os.path.dirname(tu.find_file_within_this_project('test_uvscli.py'))
print "Found tests directory path to be: " + str(tests_folder_abs_path)
cls.repo_root_path = os.path.join(tests_folder_abs_path, 'ignoreme')
cls.repo_root_cksums_file = os.path.join(tests_folder_abs_path, "ignoreme_md5sums")
print "repo root path: " + cls.repo_root_path
print "repo root cksums file: " + cls.repo_root_cksums_file
@classmethod
def tearDownClass(cls):
super(TestUVSCli, cls).tearDownClass()
print "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> tearDownClass() called"
#cls.remove_test_repo()
@classmethod
def remove_test_repo(cls):
""" Delete all files set up for test repo. """
print "remove_test_repo() called, deleting everything that was set up for test repo"
try:
shutil.rmtree(cls.repo_root_path)
except:
print "could not delete repo root path, skipping."
try:
os.remove(cls.repo_root_cksums_file)
except:
print "could not delete repo root cksum file, skipping."
@classmethod
def empty_test_repo(cls):
""" Clear the test repo, that is delete the checked out copy, but not delete the uvs internal files. """
print "empty_test_repo() called, emptying the checked out files at test repo, but not uvs internals."
# delete everything at repo_root_path except uvs internal files.
repo_root_members = os.listdir(cls.repo_root_path)
paths_to_remove = []
dont_remove = set()
dont_remove.add(sdef.TEMP_DIR_NAME)
dont_remove.add(sdef.SHADOW_FOLDER_NAME)
dont_remove.add(sdef.SHADOW_DB_FILE_NAME)
for repo_root_member in repo_root_members:
if repo_root_member not in dont_remove:
paths_to_remove.append(os.path.join(cls.repo_root_path, repo_root_member))
for path in paths_to_remove:
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.isfile(path):
os.remove(path)
# setUp will run once before every test case
def setUp(self):
pass
# tearDown will run once after every test case
def tearDown(self):
pass
def test_cli_init_twice_wont_overwrite(self):
# delete previous test repo if it existed.
self.remove_test_repo()
if not os.path.exists(self.repo_root_path):
os.makedirs(self.repo_root_path)
test_pass = '123'
init_cmd = ['uvs', 'init']
p = subprocess.Popen(init_cmd, stdin=subprocess.PIPE, cwd=self.repo_root_path)
p.stdin.write(test_pass)
p.stdin.close()
# wait for process to terminate, note that wait is not safe to call
# if we had set stdout or stderr to PIPE as well as stdin.
exit_code = p.wait()
print "$ " + str(init_cmd[0]) + " " + str(init_cmd[1]) + "\nexit code: " + str(exit_code)
self.assertEquals(exit_code, 0)
# -------------------------------------------------------------------------- init again check exit code.
p = subprocess.Popen(init_cmd, stdin=subprocess.PIPE, cwd=self.repo_root_path)
p.stdin.write(test_pass)
p.stdin.close()
# wait for process to terminate, note that wait is not safe to call
# if we had set stdout or stderr to PIPE as well as stdin.
exit_code = p.wait()
result = "# doing it 2nd time. it should not be allowed. expect non-zero exit code.\n$ " + str(init_cmd[0])
result += " " + str(init_cmd[1]) + "\nexit code: " + str(exit_code)
print result
self.assertNotEquals(exit_code, 0)
def test_cli_init_then_make_one_commit_then_recover(self):
# delete previous test repo if it existed.
self.remove_test_repo()
# this should a folder called ignoreme resident on the same location where this file (test_uvscli.py) resides
print "creating test uvs repo at: " + self.repo_root_path
if not os.path.exists(self.repo_root_path):
os.makedirs(self.repo_root_path)
# make and populate the repo root ith some random dirs and files to
# be treated as a test uvs repository.
tu.populate_directory_with_random_files_and_subdirs(dirpath=self.repo_root_path)
# now save md5 of what we created.
cmd = "find " + self.repo_root_path
cmd += " -type f -print0 | xargs -0 md5sum > " + self.repo_root_cksums_file
subprocess.call(cmd, shell=True)
# ---------------------------------------------------------------------------- Repo ready to go
test_pass = '123'
init_cmd = ['uvs', 'init']
# p = subprocess.Popen('cat', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
#p = subprocess.Popen(['uvs', 'init'], stdin=subprocess.PIPE, shell=True)
p = subprocess.Popen(init_cmd, stdin=subprocess.PIPE, cwd=self.repo_root_path)
p.stdin.write(test_pass)
p.stdin.close()
# wait for process to terminate, note that wait is not safe to call if we had set stdout or stderr to PIPE
# as well as stdin.
exit_code = p.wait()
print "$ " + str(init_cmd[0]) + " " + str(init_cmd[1]) + "\nexit code: " + str(exit_code)
self.assertEquals(exit_code, 0)
# TODO delete the files and check them back out again then verify using md5
def _disabled_test_init_then_make_one_commit_then_recover(self):
test_pass = "123"
# ---------------- init uvs repo on self.repo_root_path
uvsmanager.init_new_uvs_repo_overwrite(repo_pass=test_pass, repo_root_path=self.repo_root_path)
# ---------------- make a commit
uvsmgr = uvsmanager.UVSManager(repo_pass=test_pass, repo_root_path=self.repo_root_path)
snapid = uvsmgr.take_snapshot(snapshot_msg='test commit', author_name="n/a", author_email="n/a")
# ---------------- delete the checked out copy.
self.empty_test_repo()
# ---------------- now checkout last commit
uvsmgr.checkout_reference_at_repo_root(snapshot_ref=snapid, clear_dest=True)
# ---------------- now check to see if we recovered correctly.
check_cmd = "md5sum -c " + self.repo_root_cksums_file
# if exit code is non-zero (md5 failed) check output should raise error.
# subprocess.check_output(check_cmd, shell=True)
# call will return the exit code.
blackhole = open(os.devnull, 'wb')
check_cmd_exit_code = subprocess.call(check_cmd, stdout=blackhole, stderr=blackhole, shell=True)
self.assertEquals(check_cmd_exit_code, 0)
if __name__ == '__main__':
unittest.main() | 7,635 | 2,515 |
segundos_str = int(input("Por favor, entre com o número de segundos que deseja converter:"))
dias=segundos_str//86400
segs_restantes1=segundos_str%86400
horas=segs_restantes1//3600
segs_restantes2=segs_restantes1%3600
minutos=segs_restantes2//60
segs_restantes_final=segs_restantes2%60
print(dias,"dias,",horas, "horas,",minutos, "minutos e", segs_restantes_final, "segundos.") | 388 | 179 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 15:37:10 2020
Copyright 2020 by Hadrien Montanelli.
"""
# %% Imports.
# Standard library imports:
import numpy as np
# Chebpy imports:
from chebpy.cheb import chebpts, coeffs2vals, vals2coeffs
# %% Transforms (1D) on [-1,1].
f = lambda x: np.exp(-10*x**2)
n = 100
x = chebpts(n)
error = coeffs2vals(vals2coeffs(f(x))) - f(x)
print(f'Error (1D): {np.max(np.abs(error)):.2e}')
# %% Transforms (1D) on [0,2].
f = lambda x: np.exp(-10*x**2)
n = 100
x = chebpts(n, [0, 2])
error = coeffs2vals(vals2coeffs(f(x))) - f(x)
print(f'Error (1D): {np.max(np.abs(error)):.2e}')
# %% Transforms (2D) on [-1,1]x[-1,1].
f = lambda x, y: np.exp(-10*(x**2 + y**2))
n = 100
x = chebpts(n)
y = chebpts(n)
X, Y = np.meshgrid(x, y)
values = f(X, Y)
coeffs = vals2coeffs(vals2coeffs(values).T).T
values2 = coeffs2vals(coeffs2vals(coeffs).T).T
error = values2 - values
print(f'Error (2D): {np.max(np.abs(error)):.2e}')
# %% Transforms (2D) on [0,2]x[-1,0].
f = lambda x, y: np.exp(-10*(x**2 + y**2))
n = 100
x = chebpts(n, [0, 2])
y = chebpts(n, [-1, 0])
X, Y = np.meshgrid(x, y)
values = f(X, Y)
coeffs = vals2coeffs(vals2coeffs(values).T).T
values2 = coeffs2vals(coeffs2vals(coeffs).T).T
error = values2 - values
print(f'Error (2D): {np.max(np.abs(error)):.2e}') | 1,323 | 693 |
import urllib
import StringIO
import gzip
from difflib import Differ
from binascii import unhexlify
import Image
src = urllib.urlopen('http://huge:file@www.pythonchallenge.com/pc/return/deltas.gz').read()
file = gzip.GzipFile(fileobj=StringIO.StringIO(src))
left = []
right = []
for line in file.readlines():
left.append(line[0:53])
right.append(line[56:109])
file.close()
d = Differ()
result = list(d.compare(left, right))
pic1 = ''
pic2 = ''
pic3 = ''
for line in result:
if line[0] == ' ':
pic1 += line[1:].replace(' ', '').replace('\n', '')
elif line[0] == '+':
pic2 += line[1:].replace(' ', '').replace('\n', '')
elif line[0] == '-':
pic3 += line[1:].replace(' ', '').replace('\n', '')
Image.open(StringIO.StringIO(unhexlify(pic1))).show()
Image.open(StringIO.StringIO(unhexlify(pic2))).show()
Image.open(StringIO.StringIO(unhexlify(pic3))).show()
| 870 | 348 |