content stringlengths 7 1.05M |
|---|
@six.add_metaclass(BasicTestsMetaclass)
class ResourceListTests(BaseWebAPITestCase):
"""Testing the WatchedReviewGroupResource list API tests."""
fixtures = ["test_users"]
sample_api_url = "users/<username>/watched/review-groups/"
resource = resources.watched_review_group
def compare_item(self, item_rsp, obj):
watched_rsp = item_rsp["watched_review_group"]
self.assertEqual(watched_rsp["id"], obj.pk)
self.assertEqual(watched_rsp["name"], obj.name)
def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items):
if populate_items:
group = self.create_review_group(with_local_site=with_local_site)
profile = user.get_profile()
profile.starred_groups.add(group)
items = [group]
else:
items = []
return (get_watched_review_group_list_url(user.username, local_site_name), watched_review_group_list_mimetype, items)
def setup_basic_post_test(self, user, with_local_site, local_site_name, post_valid_data):
group = self.create_review_group(with_local_site=with_local_site)
if post_valid_data:
post_data = {"object_id": group.name}
else:
post_data = {}
return (get_watched_review_group_list_url(user.username, local_site_name), watched_review_group_item_mimetype, post_data, [group])
def check_post_result(self, user, rsp, group):
profile = user.get_profile()
self.assertIn(group, profile.starred_groups.all())
def test_post_with_does_not_exist_error(self):
"""Testing the POST users/<username>/watched/review-groups/ API
with Does Not Exist error
"""
rsp = self.api_post(get_watched_review_group_list_url(self.user.username), {"object_id": "invalidgroup"}, expected_status=404)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], DOES_NOT_EXIST.code)
@add_fixtures(["test_site"])
def test_post_with_site_does_not_exist_error(self):
"""Testing the POST users/<username>/watched/review-groups/ API
with a local site and Does Not Exist error
"""
user = self._login_user(local_site=True)
rsp = self.api_post(get_watched_review_group_list_url(user.username, self.local_site_name), {"object_id": "devgroup"}, expected_status=404)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], DOES_NOT_EXIST.code)
@six.add_metaclass(BasicTestsMetaclass)
class ResourceItemTests(BaseWebAPITestCase):
"""Testing the WatchedReviewGroupResource item API tests."""
fixtures = ["test_users"]
test_http_methods = ("DELETE", "PUT")
sample_api_url = "users/<username>/watched/review-groups/<id>/"
resource = resources.watched_review_group
def setup_http_not_allowed_item_test(self, user):
return get_watched_review_group_item_url(user.username, "my-group")
def setup_basic_delete_test(self, user, with_local_site, local_site_name):
group = self.create_review_group(with_local_site=with_local_site)
profile = user.get_profile()
profile.starred_groups.add(group)
return (get_watched_review_group_item_url(user.username, group.name, local_site_name), [profile, group])
def check_delete_result(self, user, profile, group):
self.assertNotIn(group, profile.starred_groups.all())
def test_delete_with_does_not_exist_error(self):
"""Testing the DELETE users/<username>/watched/review-groups/<id>/ API
with Does Not Exist error
"""
rsp = self.api_delete(get_watched_review_group_item_url(self.user.username, "invalidgroup"), expected_status=404)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], DOES_NOT_EXIST.code)
def test_get(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API"""
group = self.create_review_group()
profile = self.user.get_profile()
profile.starred_groups.add(group)
expected_url = self.base_url + get_review_group_item_url(group.name)
self.api_get(get_watched_review_group_item_url(self.user.username, group.pk), expected_status=302, expected_headers={"Location": expected_url})
@add_fixtures(["test_site"])
def test_get_with_site(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API
with access to a local site
"""
user = self._login_user(local_site=True)
group = self.create_review_group(with_local_site=True)
profile = user.get_profile()
profile.starred_groups.add(group)
expected_url = self.base_url + get_review_group_item_url(group.name, self.local_site_name)
self.api_get(get_watched_review_group_item_url(user.username, group.pk, self.local_site_name), expected_status=302, expected_headers={"Location": expected_url})
@add_fixtures(["test_site"])
def test_get_with_site_no_access(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API
without access to a local site
"""
group = self.create_review_group(with_local_site=True)
profile = self.user.get_profile()
profile.starred_groups.add(group)
rsp = self.api_get(get_watched_review_group_item_url(self.user.username, group.pk, self.local_site_name), expected_status=403)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], PERMISSION_DENIED.code) |
# Take string, mirrors its string argument, and print result
def get_mirror(string):
# mirrors string argument
result = string + string[::-1]
return result
# Define main function
def main():
# Prompt user for a string
astring = input('Enter a string: ')
# Obtain mirror string
mirror = get_mirror(astring)
# Display mirror
print(mirror)
# Call main function
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def compute_short_chain(number):
"""Compute a short chain
Arguments:
number {int} -- Requested number for which to compute the square
Returns:
int -- Value of the square/short chain for the given number
"""
return number * number
def compute_long_chain(number):
"""Compute a long chain
Arguments:
number {int} -- Requested number for which to compute the cube
Returns:
int -- Value of the cube/long chain for the given number
"""
return number * number * number
def lambda_handler(event, context):
pass
|
#!/usr/bin/env python3
# with_example02.py
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print("type:", type)
print("value:", value)
print("trace:", trace)
def do_something(self):
bar = 1/0
return bar + 10
with Sample() as sample:
sample.do_something()
|
class Node():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f"{ {str(current.value)} } ->"
current = current.next
return output
def __iter__(self):
"""
loop over the linked list
"""
current = self.head
while current:
yield current.value
current = current.next
def append(self, value):
'''
this method to append value in the last node
input ==> value
'''
if value is None:
raise TypeError("insert() missing 1 required positional argument: 'value' ")
else:
new_node = Node(value)
if not self.head:
self.head = new_node
else:
new_node = Node(value)
current = self.head
while current.next:
current = current.next
current.next = new_node
def insert(self, value):
'''
this method to adds an element to the list
input ==> element
'''
node = Node(value)
node.next = self.head
self.head = node
def includes(self, values):
'''
this method to checks if an element
exists in the list and returns a boolean (True/Flase)
input ==> value
output ==> boolean
'''
if values is None:
raise TypeError("includes() missing 1 required positional argument: 'values' ")
else:
current_node = self.head
while current_node.next :
if current_node.value == values:
return True
else:
current_node = current_node.next
return False
###########################################################################
def insert_before(self,value,new_value):
'''
adds an element to the list befor element
its take to element
first argument the value wich we will insert befor it
the second is the value wich we will insert
'''
new_node = Node(new_value)
current = self.head
if not self.head:
self.head = new_node
else:
if current.value == value:
th_node = self.head
self.head = new_node
new_node.next = th_node
return
else:
current = self.head
while current.next :
if current.next.value == value:
th_node = current.next
current.next = new_node
new_node.next = th_node
return
else:
current = current.next
return
def insert_after(self, value, new_value):
'''
adds an element to the list after element
its take to element
first argument the value wich we will insert after it
the second is the value wich we will insert
'''
new_node = Node(new_value)
current = self.head
if not self.head:
self.head = new_node
else:
current = self.head
while current.next != None:
if current.next.value == value:
current = current.next
old_node = current.next
current.next = new_node
new_node.next = old_node
return
else:
current = current.next
return
###########################################################################
def kth_from_end(self, k):
"""takes in a value(k) and returns the Node k places away from the tail"""
current = self.head
arr = []
if k < 0:
return 'index can\'t be less the zero'
while current:
arr.append(current)
current = current.next
if len(arr) < k:
return 'index not found'
arr.reverse()
if k == len(arr):
k = k -1
return arr[k].value
#################################################################
def kth_from_end_second(self, k):
current = self.head
count = 0
while (current):
if (count == k):
return current.value
count += 1
current = current.next
#################################################################
def deleteNode(self, k):
temp = self.head
if (temp is not None):
if (temp.value == k):
self.head = temp.next
temp = None
return
while(temp is not None):
if temp.value == k:
break
prev = temp
temp = temp.next
if(temp == None):
return
prev.next = temp.next
temp = None
if __name__ == "__main__":
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(12)
ll.append(232)
ll.append(324)
ll.append(14235)
ll.append(22366)
ll.append(3234)
ll.append(134)
ll.append(2545)
ll.append(367)
print(str(ll))
ll.deleteNode(22366)
ll.deleteNode(1)
ll.deleteNode(324)
ll.deleteNode(367)
print(str(ll))
|
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Raphaël Barrois
# This code is distributed under the two-clause BSD license.
__version__ = '0.12.3.1'
__author__ = 'Raphaël Barrois <raphael.barrois+xworkflows@polytechnique.org>'
|
"""Module containing the exception class for describe-get-system proof of concept module."""
class DGSError(Exception):
"""Use to capture error DGS construction."""
class TemplateStorageError(DGSError):
"""Use to capture error for TemplateStorage."""
class AdaptorAuthenticationError(DGSError):
"""Use to capture error for adaptor connection"""
class InterpreterError(DGSError):
"""Use to capture error for interpreter"""
class NotImplementedFrameworkError(InterpreterError):
"""Use to capture error for not implement framework"""
class ComparisonOperatorError(InterpreterError):
"""Use to capture error for invalid comparison operator"""
class ConnectDeviceStatementError(InterpreterError):
"""Use to capture error for interpreting connect device statement"""
class DisconnectDeviceStatementError(InterpreterError):
"""Use to capture error for interpreting disconnect device statement"""
class ReleaseDeviceStatementError(InterpreterError):
"""Use to capture error for interpreting release device statement"""
class WaitForStatementError(InterpreterError):
"""Use to capture error for interpreting wait for statement"""
class PerformerStatementError(InterpreterError):
"""Use to capture error for performer statement"""
class VerificationStatementError(InterpreterError):
"""Use to capture error for verification statement"""
class ScriptBuilderError(InterpreterError):
"""Use to capture error for building test script"""
class DurationArgumentError(InterpreterError):
"""Use to capture error for wait_for function"""
class ConvertorTypeError(InterpreterError):
"""Use to capture convertor argument for filter method"""
class TemplateReferenceError(InterpreterError):
"""Use to capture template reference for filter method"""
class UtilsParsedTemplateError(InterpreterError):
"""Use to capture error for parsing template in utils"""
class ReportError(DGSError):
"""Use to capture error for report generation in report.py"""
|
N, M = map(int, input().split())
loop = (2**M)
print(1900*loop*M+100*(N-M)*loop)
|
def check_double(number):
if len(str(number))==(len(str(number*2))) and number!=number*2 :
return sorted(str(number)) == sorted(str(number*2))
return False
print(check_double(125874)) |
docs = """django-mc-commands
=======================
[](https://travis-ci.org/mc706/django-angular-scaffold)
[](http://badge.fury.io/py/django-angular-scaffold)
[](https://landscape.io/github/mc706/django-angular-scaffold/master)
[](https://coveralls.io/r/mc706/django-angular-scaffold)
set of django management commands to manage versions and help out around building your app.
build by [@mc706](http://mc706.com)
##Installation
Install using pip
```
pip install django-mc-commands
```
include in your INSTALLED_APPS
```
#settings.py
...
INSTALLED_APPS = (
...
'mc_commands',
...
)
```
##Commands
The following are commands that are made available through this package.
###bootstrap
```
./manage.py bootstrap
```
Adds a few key files to your application
* `_version.py`
* `CHANGELOG.md`
* This docs file
* A separate internal app tuple file
###quality_check
```
./manage.py quality_check
```
Runs a few libraries to check the quality of the code in the repository
* pep8
* jshint
* xenon
* prospector
###runtests
```
./manage.py runtests
```
A shortcut command to run the internal apps with coverage and fail if coverage is below a certain amount
###freeze
```
./manage.py freeze
```
Shortcut wrapper around `pip freeze > requirements.txt`
###cut
```
./manage.py cut <type>
```
Cuts a release and pushed it to git. Will update the changelog, and update `_version.py` and tag a release.
Type options are:
* patch (default)
* minor
* major
Version users Semver major.minor.patch
""" |
DEBUG = False
TESTING = False
PROXY = False # True if app is proxied by Apache or similar.
# Application Settings
BROWSER_NAME = 'Bravo'
DATASET_NAME = 'Example Dataset' # Change to your dataset name
SHOW_POWERED_BY = False
NUM_SAMPLES = 0 # Change to the number of samples you are using
NUM_VARIANTS = 'XYZ million' # Change to the number of variants you are using
# Database Settings
MONGO = {
'host': '127.0.0.1',
'port': 27017,
'name': 'bravo'
}
DOWNLOAD_ALL_FILEPATH = ''
URL_PREFIX = ''
# Google Analytics Settings
GOOGLE_ANALYTICS_TRACKING_ID = '' # (Optional) Change to your Google Analytics Tracking ID.
SECRET_KEY = '' # (Optional) Change to your Google Analytics Secret Key
# Google Auth Settings
GOOGLE_AUTH = False # True if app is using Google Auth 2.0
GOOGLE_LOGIN_CLIENT_ID = '' # Insert your Google Login Client ID
GOOGLE_LOGIN_CLIENT_SECRET = '' # Insert your Google Login Secret
TERMS = True # True if app requires 'Terms of Use'. Can be used only if GOOGLE_AUTH is enabled.
# Email Whitelist Settings
EMAIL_WHITELIST = False # True if app has whitelisted emails. Can be used only if GOOGLE_AUTH is enabled.
API_GOOGLE_AUTH = False
API_IP_WHITELIST = ['127.0.0.1']
API_VERSION = ''
API_DATASET_NAME = ''
API_COLLECTION_NAME = 'variants'
API_URL_PREFIX = '/api/' + API_VERSION
API_PAGE_SIZE = 1000
API_MAX_REGION = 250000
API_REQUESTS_RATE_LIMIT = ['1800/15 minute']
# BRAVO Settings
BRAVO_AUTH_SECRET = ''
BRAVO_ACCESS_SECRET = ''
BRAVO_AUTH_URL_PREFIX = '/api/' + API_VERSION + '/auth'
# Data Directory Settings. By default all data is stored in /data root directory
IGV_REFERENCE_PATH = '/data/genomes/genome.fa'
IGV_CRAM_DIRECTORY = '/data/cram/'
IGV_CACHE_COLLECTION = 'igv_cache'
IGV_CACHE_DIRECTORY = '/data/cache/igv_cache/'
IGV_CACHE_LIMIT = 1000
BASE_COVERAGE_DIRECTORY = '/data/coverage/'
# FASTA Data URL Settings.
FASTA_URL = 'https://<your-bravo-domain>/genomes/genome.fa' # Edit to reflect your URL for your BRAVO application
ADMINS = [
'email@email.email'
]
ADMIN = False # True if app is running in admin mode.
ADMIN_ALLOWED_IP = [] # IPs allowed to reach admin interface
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 04:08:08 2017
@author: Mayur
"""
# =============================================================================
# Problem 4 - Decrypt a Story
#
# For this problem, the graders will use our implementation of the Message,
# PlaintextMessage, and CiphertextMessage classes, so don't worry if you did not
# get the previous parts correct.
#
# Now that you have all the pieces to the puzzle, please use them to decode the
# file story.txt. The file ps6.py contains a helper function get_story_string()
# that returns the encrypted version of the story as a string. Create a
# CiphertextMessage object using the story string and use decrypt_message to
# return the appropriate shift value and unencrypted story string.
# =============================================================================
#code
def decrypt_story():
encryptedStory = get_story_string()
decryptedStory = CiphertextMessage(encryptedStory)
return decryptedStory.decrypt_message() |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CertificateDetails(object):
"""Implementation of the 'CertificateDetails' model.
Specifies details about a certificate.
Attributes:
cert_file_name (string): Specifies the filename of the certificate.
This is unique to each certificate generated.
expiry_date (string): Specifies the date in epoch till when the
certificate is valid.
host_ips (list of string): Each certificate can be deployed to
multiple hosts. List of all hosts is returned after deployment.
mtype (TypeCertificateDetailsEnum): Specifies the type of the host
such as 'kSapHana', 'kSapOracle', etc. Specifies the host type of
host for generating and deploying a Certificate. 'kOther'
indicates it is any of the other hosts. 'kSapOracle' indicates it
is a SAP Oracle host. 'kSapHana' indicates it is a SAP HANA host.
"""
# Create a mapping from Model property names to API property names
_names = {
"cert_file_name":'certFileName',
"expiry_date":'expiryDate',
"host_ips":'hostIps',
"mtype":'type'
}
def __init__(self,
cert_file_name=None,
expiry_date=None,
host_ips=None,
mtype=None):
"""Constructor for the CertificateDetails class"""
# Initialize members of the class
self.cert_file_name = cert_file_name
self.expiry_date = expiry_date
self.host_ips = host_ips
self.mtype = mtype
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
cert_file_name = dictionary.get('certFileName')
expiry_date = dictionary.get('expiryDate')
host_ips = dictionary.get('hostIps')
mtype = dictionary.get('type')
# Return an object of this model
return cls(cert_file_name,
expiry_date,
host_ips,
mtype)
|
## Coding Conventions
# 'p' variables in p_<fun> are container() type
# possible scopes: package, global, functions, ....
global curr_scope
curr_scope = None
global scope_count
scope_count = 0
global temp_count
temp_count = 0
global label_count
label_count = 0
class ScopeTree:
def __init__(self, parent, scopeName=None):
self.children = []
self.parent = parent
self.symbolTable = {} #{"var": [type, size, value, offset]}
self.typeTable = self.parent.typeTable if parent is not None else {}
if scopeName is None:
global scope_count
self.identity = {"name":scope_count}
scope_count += 1
else:
self.identity = {"name":scopeName}
scope_count += 1
def insert(self, id, type, is_var=1, arg_list=None, size=None, ret_type=None, length=None, base=None):
self.symbolTable[id] = {"type":type, "base":base, "is_var":is_var,"size":size, "arg_list":arg_list, "ret_type":ret_type, "length":length}
def insert_type(self, new_type, Ntype):
self.typeTable[new_type] = Ntype
def makeChildren(self, childName=None):
child = ScopeTree(self, childName)
self.children.append(child)
return child
def lookup(self, id):
if id in self.symbolTable:
return self.symbolTable[id]
else:
if self.parent is None:
return None
# raise_general_error("undeclared variable: " + id)
return self.parent.lookup(id)
def new_temp(self):
global temp_count
temp_count += 1
return "$"+str(temp_count)
def new_label(self):
global label_count
label_count += 1
return "#"+str(label_count)
class container(object):
def __init__(self,type=None,value=None):
self.code = list()
self.place = None
self.extra = dict()
self.type = type
self.value = value
class sourcefile(object):
def __init__(self):
self.code = list()
self.package = str()
# for each import - { package:package_name,as:local_name,path:package_path }
self.imports = list()
class Builtin(object):
def __init__(self,name,width=None):
self.name = name
self.width = width
self.base = None
def __len__(self):
return self.width
def __repr__(self):
return self.name
class Int(Builtin):
def __init__(self):
super().__init__("int",4)
class Float(Builtin):
def __init__(self):
super().__init__("float",8)
class String(Builtin):
def __init__(self):
super().__init__("string")
class Byte(Builtin):
def __init__(self):
super().__init__("byte",1)
class Void(Builtin):
def __init__(self):
super().__init__("void")
class Error(Builtin):
def __init__(self):
super().__init__("error")
typeOp = set({"array","struct","pointer","function","interface","slice","map"})
class Derived(object):
def __init__(self,op,base,arg=None):
self.arg = dict(arg)
if op in typeOp:
self.op = op
if isinstance(base,(Derived,Builtin)) and (not isinstance(base,(Error,Void))) :
self.base = base
if op == "arr" :
self.name = "arr" + base.name
elif op == "struct" :
self.name = "struct" + arg["name"]
# i am saying use attributes for array - base, just like for func type
class Tac(object):
def __init__(self, op=None, arg1=None, arg2=None, dst=None, type=None):
self.type = type
self.op = op
self.arg1 = arg1
self.arg2 = arg2
self.dst = dst
class LBL(Tac):
'''Label Operation -> label :'''
def __init__(self, arg1, type="LBL"):
super().__init__(type,arg1=arg1)
def __str__(self):
return " ".join([str(self.arg1),":"])
class BOP(Tac):
'''Binary Operation -> dst = arg1 op arg2'''
def __init__(self, op, arg1, arg2, dst, type="BOP"):
super().__init__(op=op,arg1=arg1,arg2=arg2,dst=dst,type=type)
def __str__(self):
return " ".join([self.dst,"=",str(self.arg1),self.op,str(self.arg2)])
class UOP(Tac):
'''Unary Operation -> dst = op arg1'''
def __init__(self,op,arg1,type="UOP"):
super().__init__(op=op,arg1=arg1,type=type)
def __str__(self):
return " ".join([self.dst,"=",self.op,str(self.arg1)])
class ASN(Tac):
'''Assignment Operation -> dst = arg1'''
def __init__(self,arg1,dst,type="ASN"):
super().__init__(arg1=arg1,dst=dst,type=type)
def __str__(self):
return " ".join([self.dst,"=",str(self.arg1)])
class JMP(Tac):
'''Jump Operation -> goto dst'''
def __init__(self,dst,type="JMP"):
super().__init__(dst=dst,type=type)
def __str__(self):
return " ".join(["goto",self.dst])
# class JIF(Tac):
# '''Jump If -> if arg1 goto dst'''
# def __init__(self,arg1,dst,type="JIF"):
# super().__init__(arg1=arg1,dst=dst,type=type)
# def __str__(self):
# return " ".join(["if",str(self.arg1),"goto",self.dst])
class CBR(Tac):
'''Conditional Branch -> if arg1 op arg2 goto dst'''
def __init__(self, op, arg1, arg2, dst, type="CBR"):
super().__init__(op=op,arg1=arg1,arg2=arg2,dst=dst,type=type)
def __str__(self):
return " ".join(["if",str(self.arg1),self.op,str(self.arg2),"goto",self.dst])
# class BOP(Tac):
# '''Binary Operation
# dst = arg1 op arg2
# op can be :
# + : Add
# - : Subtract
# * : Multiply
# & : Bitwise AND
# | : Bitwise OR
# ^ : Bitwise XOR
# && : Logical AND
# || : Logical OR
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
#
# class LOP(Tac):
# '''Logical Operation
# dst = arg1 op arg2
# op can be :
# < : Less Than
# > : Greater Than
# <= : Less Than Equal
# >= : Greater Than Equal
# == : Equals
# != : Not Equals
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
#
# class SOP(Tac):
# '''Shift Operation
# dst = arg1 op arg2
# op can be :
# << : Bitwise Shift Left
# >> : Bitwise Shift Right
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
#
# class DOP(Tac):
# '''Division Operation
# dst = arg1 op arg2
# op can be :
# / : Divide
# % : Remainder
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
def raise_typerror(p, s=""):
print("Type error", s)
print(p)
exit(-1)
def raise_out_of_bounds_error(p, s="" ):
print("out of bounds error")
print(p)
print(s)
exit(-1)
def raise_general_error(s):
print(s)
exit(-1)
def extract_package(package_name):
return package_name.split("/")[-1]
def print_scopeTree(node,source_root,flag=False):
temp = node
if flag :
print("")
print("me:", temp.identity)
for i in temp.children:
print("child:", i.identity)
print("symbolTable:")
for var, val in temp.symbolTable.items():
print(var, val)
print("TypeTable:")
for new_type, Ntype in temp.typeTable.items():
print(new_type, Ntype)
for i in temp.children:
print_scopeTree(i,source_root)
ipkgs = ""
for pkg in source_root.imports :
ipkgs = (ipkgs +"package :"+pkg["package"] + " , as :" +pkg["as"]
+" , path:"+pkg["path"] + "\n")
three_ac = ""
for line in source_root.code :
three_ac = three_ac + str(line) + "\n"
return three_ac[:-1],ipkgs[:-1],source_root.package
|
test=int(input())
for y in range(test):
k,dig0,dig1=input().split()
k,dig0,dig1=int(k),int(dig0),int(dig1)
sum1=dig0+dig1
for i in range(3,k+2):
y=sum1%10
sum1+=y
if(y==2):
ter1=((k-i)//4)
ter1*=20
sum1+=ter1
ter=k-i
if(ter%4==3):
sum1+=18
elif(ter%4==2):
sum1+=12
elif(ter%4==1):
sum1+=4
break
if(y==0):
break
if(sum1%3==0):
print("YES")
else:
print("NO") |
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
h = []
for i, li in enumerate(mat):
l = self.countSoider(li)
heapq.heappush(h, (l, i))
ans = []
for _ in range(k):
ans.append(heapq.heappop(h)[1])
return ans
def countSoider(self, li):
l = 0
r = len(li)
if li[l] == 0:
return 0
if li[r - 1] == 1:
return r
while l < r:
mid = (l + r - 1) //2
if li[mid] == 0:
if li[mid - 1] == 1:
return mid
else:
r = mid - 1
else:
if li[mid + 1] == 0:
return mid + 1
else:
l = mid + 1
|
# This file is needs to be multi-lingual in both Python and POSIX
# shell which "execfile" or "source" it respectively.
# This file should define a variable VERSION which we use as the
# debugger version number.
VERSION='0.3.6'
|
class Solution(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
finds = [S[idx:idx + len(source)] == source for idx, source in zip(indexes, sources)]
diff = 0
S = list(S)
for idx, find, source, target in sorted(zip(indexes, finds, sources, targets)):
if find:
S[idx + diff : idx + diff + len(source)] = list(target)
diff += len(target) - len(source)
return ''.join(S) |
# -*- coding: utf-8 -*-
"""
bandwidth
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class CallEngineModifyConferenceRequest(object):
"""Implementation of the 'CallEngineModifyConferenceRequest' model.
TODO: type model description here.
Attributes:
status (StatusEnum): TODO: type description here.
redirect_url (string): TODO: type description here.
redirect_fallback_url (string): TODO: type description here.
redirect_method (RedirectMethodEnum): TODO: type description here.
redirect_fallback_method (RedirectFallbackMethodEnum): TODO: type
description here.
username (string): TODO: type description here.
password (string): TODO: type description here.
fallback_username (string): TODO: type description here.
fallback_password (string): TODO: type description here.
"""
# Create a mapping from Model property names to API property names
_names = {
"redirect_url": 'redirectUrl',
"status": 'status',
"redirect_fallback_url": 'redirectFallbackUrl',
"redirect_method": 'redirectMethod',
"redirect_fallback_method": 'redirectFallbackMethod',
"username": 'username',
"password": 'password',
"fallback_username": 'fallbackUsername',
"fallback_password": 'fallbackPassword'
}
def __init__(self,
redirect_url=None,
status=None,
redirect_fallback_url=None,
redirect_method=None,
redirect_fallback_method=None,
username=None,
password=None,
fallback_username=None,
fallback_password=None):
"""Constructor for the CallEngineModifyConferenceRequest class"""
# Initialize members of the class
self.status = status
self.redirect_url = redirect_url
self.redirect_fallback_url = redirect_fallback_url
self.redirect_method = redirect_method
self.redirect_fallback_method = redirect_fallback_method
self.username = username
self.password = password
self.fallback_username = fallback_username
self.fallback_password = fallback_password
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object
as obtained from the deserialization of the server's response. The
keys MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
redirect_url = dictionary.get('redirectUrl')
status = dictionary.get('status')
redirect_fallback_url = dictionary.get('redirectFallbackUrl')
redirect_method = dictionary.get('redirectMethod')
redirect_fallback_method = dictionary.get('redirectFallbackMethod')
username = dictionary.get('username')
password = dictionary.get('password')
fallback_username = dictionary.get('fallbackUsername')
fallback_password = dictionary.get('fallbackPassword')
# Return an object of this model
return cls(redirect_url,
status,
redirect_fallback_url,
redirect_method,
redirect_fallback_method,
username,
password,
fallback_username,
fallback_password)
|
"""
@name: PyHouse/src/Modules/Drivers/test/xml_drivers.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2014-2016 by D. Brian Kimmel
@license: MIT License
@note: Created on Nov 9, 2014
@Summary:
"""
DRIVERS_XML = """
"""
DRIVERS_XSD = """
?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://PyHouse.org"
xmlns="http://PyHouse.org"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
</xs:schema>
-"""
# ## END DBK
|
tmp = 0
monday_temperatures = [9.1, 8.8, 7.5]
tmp = monday_temperatures.__getitem__(1)
tmp = monday_temperatures[1]
print(tmp) |
'''
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
'''
class Solution:
def rob(self, nums: List[int]) -> int:
#handle base condition
if(len(nums) == 0):
return 0
if(len(nums) == 1):
return(nums[0])
if(len(nums) == 2):
return(max(nums[0],nums[1]))
dp = [0 for _ in range(len(nums))]
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
for i in range(2,len(nums)):
dp[i] = max(nums[i]+dp[i-2],dp[i-1])
return(dp[-1])
|
class Map:
def __init__(self, filepath):
#first index will be y, second is x
self.data = list()
with open(filepath, "r") as f:
for line in f:
line = line.strip()
self.data.append(line)
self.width = len(self.data[0])
self.height = len(self.data)
#Check that we loaded the map with the same width everywhere
assert all([self.width == len(i) for i in self.data])
def check(self, x, y):
if y >= self.height:
return None
return self.data[y][x%self.width] == "#"
def print(self):
for line in self.data:
print("".join(line))
class Sled:
def __init__(self, map_):
self.map = map_
def go(self, xpos, ypos, step_x, step_y):
count = 0
status = self.map.check(xpos,ypos)
while status is not None:
xpos += step_x
ypos += step_y
status = self.map.check(xpos,ypos)
if status:
count += 1
return count
|
# https://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
x,y=map(int,input().split())
z=int(input())
p=x/y
q=1-p
print(round((q**(z-1))*p,3)) |
"""
Used for passing custom exceptions form the configuration_service to the rest of the application.
"""
class ConfigurationError(Exception):
"""Raised when error occurred while loading or saving properties"""
pass
|
MP3_PREVIEW = "mp3_preview"
OGG_PREVIEW = "ogg_preview"
OGG_RELEASE = "ogg_release"
|
MAJOR_COLORS = ['White', 'Red', 'Black', 'Yellow', 'Violet']
MINOR_COLORS = ["Blue", "Orange", "Green", "Brown", "Slate"]
def print_color_code_mapping():
print('{:15} {:15} {:5} \n'.format('Major Color', 'Minor Color', 'Pair No.'))
for major_color_index, major_color in enumerate(MAJOR_COLORS):
for minor_color_index, minor_color in enumerate(MINOR_COLORS):
print('{:15} {:15} {:5} \n'.format(major_color, minor_color, major_color_index * len(MINOR_COLORS) + minor_color_index + 1))
def get_color_from_pair_number(pair_number):
zero_based_pair_number = pair_number - 1
major_index = zero_based_pair_number // len(MINOR_COLORS)
if major_index >= len(MAJOR_COLORS):
raise Exception('Major index out of range')
minor_index = zero_based_pair_number % len(MINOR_COLORS)
if minor_index >= len(MINOR_COLORS):
raise Exception('Minor index out of range')
return MAJOR_COLORS[major_index], MINOR_COLORS[minor_index]
def get_pair_number_from_color(major_color, minor_color):
try:
major_index = MAJOR_COLORS.index(major_color)
except ValueError:
raise Exception('Major index out of range')
try:
minor_index = MINOR_COLORS.index(minor_color)
except ValueError:
raise Exception('Minor index out of range')
return major_index * len(MINOR_COLORS) + minor_index + 1
|
# coding: utf-8
# Define buildargs for cse api
BUILDARGS = {
'serviceName': 'customsearch',
'version': 'v1',
'developerKey': 'AIzaSyBqjfgcWEdMse4ghRYrbib8qv7avHFrp2Y'
}
# Define cseargs for search
CSEARGS = {
'q': '柯基犬',
'cx': '007397120899702103013:roufggcacti',
# 'num': 30
}
PROXIES = [{
'http': '127.0.0.1:43285',
'https': '127.0.0.1:43285',
}]
PATH="/home/terry/pan/github/bert/book/" |
# 88. Merge Sorted Array
# ttungl@gmail.com
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# You may assume that nums1 has enough space (size that is greater or equal to m + n)
# to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# sol 1:
# time O(n)
# runtime: 42ms
while n > 0:
if m <= 0 or nums2[n-1] >= nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else: # m > 0 or nums2[n-1] < nums1[m-1]
nums1[m+n-1] = nums1[m-1]
m -= 1
# sol 2:
# time O(n logn)
# runtime: 38ms
nums1[m:] = nums2[:n]
nums1.sort()
|
"""
Happy Cobra - Marirs
Skeleton of a Login & Registration system
MIT License
"""
|
"""
Your job is to create a class Dictionary which you can add words to and their entries. Example:
d = Dictionary()
d.new_entry('Apple', 'A fruit that grows on trees')
print(d.look('Apple'))
A fruit that grows on trees
print(d.look('Banana'))
Can't find entry for Banana
"""
class Dictionary:
def __init__(self):
self.dict_ = {}
def new_entry(self, key, value):
new = self.dict_.update([(key, value)])
return new
def look(self, key):
look = self.dict_.get(key, "Can't find entry for Banana")
return look
d = Dictionary()
d.new_entry('Apple', 'A fruit that grows on trees')
print(d.look('Apple'))
print(d.look('Banana'))
|
CRITICAL_MARK_BEGIN = '<!-- BEGIN: django-critical css ('
CRITICAL_MARK_END = ') END: django-critical css -->'
CRITICAL_ASYNC_MARK = '<!-- django-critical async snippet -->'
CRITICAL_KEY_MARK_BEGIN = '<!-- BEGIN: django-critical key ('
CRITICAL_KEY_MARK_END = ') END: django-critical key -->'
|
l=[]
z=[]
def selection_sort(l):
for i in range(0,5):
MIN=min(l)
z.append(MIN)
l.remove(MIN)
return z
print("Enter Integer list of 5 values")
for i in range(0, 5):
x = int(input())
l.append(x)
print("List is: ",l)
print("Sorted list is: ",selection_sort(l))
|
"""
The ``memory`` taxon groups applets implementing interfaces to memory technology devices (volatile
and non-volatile) that include no functionality beyond manipulating data.
Examples: SPI flash, I²C EEPROM.
Counterexamples: SPI flash on an FPGA board that requires coordinated reset (use taxon
``program``), flash macroblock embedded in a microcontroller (use taxon ``program``).
"""
|
load("//tools/jest:jest.bzl", _jest_test = "jest_test")
load("//tools/go:go.bzl", _test_go_fmt = "test_go_fmt")
load("@io_bazel_rules_go//go:def.bzl", _go_binary = "go_binary", _go_library = "go_library", _go_test = "go_test")
load("@npm//@bazel/typescript:index.bzl", _ts_config = "ts_config", _ts_project = "ts_project")
load("@npm//eslint:index.bzl", _eslint_test = "eslint_test")
load("@build_bazel_rules_nodejs//:index.bzl", "js_library", _nodejs_binary = "nodejs_binary")
def nodejs_binary(**kwargs):
_nodejs_binary(**kwargs)
def ts_config(**kwargs):
_ts_config(**kwargs)
def jest_test(project_deps = [], deps = [], **kwargs):
_jest_test(
deps = deps + [x + "_js" for x in project_deps],
**kwargs
)
def ts_lint(name, srcs = [], tags = [], data = [], **kwargs):
targets = srcs + data
eslint_test(
name = name,
data = targets,
tags = tags + ["+formatting"],
args = ["$(location %s)" % x for x in targets],
**kwargs
)
def ts_project(name, project_deps = [], deps = [], srcs = [], incremental = None, composite = False, tsconfig = "//:tsconfig", declaration = False, preserve_jsx = None, **kwargs):
__ts_project(
name = name + "_ts",
deps = deps + [dep + "_ts" for dep in project_deps],
srcs = srcs,
composite = composite,
declaration = declaration,
tsconfig = tsconfig,
preserve_jsx = preserve_jsx,
incremental = incremental,
**kwargs
)
js_library(
name = name + "_js",
deps = [dep + "_js" for dep in project_deps] + deps,
srcs = [src[:src.rfind(".")] + ".js" for src in srcs],
**kwargs
)
def __ts_project(name, tags = [], deps = [], srcs = [], tsconfig = "//:tsconfig", **kwargs):
_ts_project(
name = name,
tsc = "@npm//ttypescript/bin:ttsc",
srcs = srcs,
deps = deps + ["@npm//typescript-transform-paths"],
tags = tags,
tsconfig = tsconfig,
**kwargs
)
ts_lint(name = name + "_lint", data = srcs, tags = tags)
def eslint_test(name = None, data = [], args = [], **kwargs):
_eslint_test(
name = name,
data = data + [
"//:.prettierrc.json",
"//:.gitignore",
"//:.editorconfig",
"//:.eslintrc.json",
"@npm//eslint-plugin-prettier",
"@npm//@typescript-eslint/parser",
"@npm//@typescript-eslint/eslint-plugin",
"@npm//eslint-config-prettier",
],
args = args + ["--ignore-path", "$(location //:.gitignore)"] +
["$(location " + x + ")" for x in data],
)
def go_binary(name = None, importpath = None, deps = [], **kwargs):
_go_binary(
name = name,
deps = deps,
importpath = importpath,
**kwargs
)
_test_go_fmt(
name = name + "_fmt",
**kwargs
)
def go_test(name = None, importpath = None, deps = [], **kwargs):
_go_test(
name = name,
deps = deps,
importpath = importpath,
**kwargs
)
_test_go_fmt(
name = name + "_fmt",
**kwargs
)
def go_library(name = None, importpath = None, deps = [], **kwargs):
_go_library(
name = name,
deps = deps,
importpath = importpath,
**kwargs
)
_test_go_fmt(
name = name + "_fmt",
**kwargs
)
|
antenna = int(input())
eyes = int(input())
if antenna>=3 and eyes<=4:
print("TroyMartian")
if antenna<=6 and eyes>=2:
print("VladSaturnian")
if antenna<=2 and eyes<= 3:
print("GraemeMercurian")
|
# test builtin abs function with float args
for val in (
"1.0",
"-1.0",
"0.0",
"-0.0",
"nan",
"-nan",
"inf",
"-inf",
):
print(val, abs(float(val)))
|
'''
Faça um Programa que mostre a mensagem "Alo mundo" na tela.
'''
print('Alô, mundo!')
|
# Big O complexity
# O(log2(n))
# works only on sorted array
# recursive
def binary_search_recursive(arr, arg, left, right):
if right >= left:
middle = left + (right - left) // 2
if arr[middle] == arg:
return middle
elif arr[middle] > arg:
return binary_search_recursive(arr, arg, left, middle - 1)
else:
return binary_search_recursive(arr, arg, middle + 1, right)
else:
return -1
# iterative
def binary_search(arr, arg, left, right):
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == arg:
return mid
elif arr[mid] < arg:
left = mid + 1
else:
right = mid - 1
return -1
|
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 19:20:16 2022
@author: ARYAMAN
"""
word_list =[]
with open("corncob_caps.txt", "r") as words:
lines = words.readlines()
final_list = []
for l in lines:
final_list.append(l.replace("\n","")) |
s = input("s: ")
t = input("t: ")
if s == t:
print("Same")
else:
print("Different") |
def par(n=0):
if n % 2 == 0:
return True
else:
return False
# Programa principal
num = int(input('Digite um número: '))
if par(num):
print('É PAR.')
else:
print('NÃO É PAR.')
|
'''Deoxyribonucleic acid (DNA) is a chemical found in the nucleus
of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other,
as "C" and "G". You have function with one side of the DNA
(string, except for Haskell); you need to get the other complementary side.
DNA strand is never empty or there is no DNA at all (again, except for Haskell).'''
#ATTGC >>>> TAACG
def DNA_strand(dna):
Dna_dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
return ''.join(Dna_dict[letter] for letter in dna if letter in Dna_dict.keys())
'''also we can simply do : return dna.translate(str.maketrans('ATTGC', 'TAACG'))'''
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# @name : E-ntel - Email Information Gathering
# @url : http://github.com/CybernetiX-S3C
# @author : John Modica (CybernetiX S3C)
R = "\033[%s;31m"
B = "\033[%s;34m"
G = "\033[%s;32m"
W = "\033[%s;38m"
Y = "\033[%s;33m"
E = "\033[0m" |
# dummy wordlist
# by Jeeb
# Information about your version of Wordle
Metadata = {
"name": "Dummy",
"version": "dummy",
"guesses": 4,
"launch": (2222, 2, 16),
"boxes": ["[]", "!!", "<3", " ", " "],
"colors": [0x1666666, 0x1bb9900, 0x1008800, 0xe8e8e8, 0x1222222],
"keyboard": ["aaaaaaaaaa"], # max 10 keys per row, please
}
# Your custom list of non-answer words goes here
Words = ["b", "c", "d", "e", "f"]
# Your custom list of answer-words goes here
Answers = ["a"] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 08:56:55 2017
@author: Nadiar
"""
balance = 320000
annualInterestRate = 0.2
"""
Monthly interest rate = (Annual interest rate) / 12.0
Monthly payment lower bound = Balance / 12
Monthly payment upper bound =
(Balance x (1 + Monthly interest rate)^12) / 12.0
"""
monthlyInterestRate = annualInterestRate / 12.0
def monthlyUnpaidBalance(balance, guess):
return balance - guess
def updatedBalanceEachMonth(balance, guess):
return monthlyUnpaidBalance(balance, guess) \
+ monthlyInterestRate * \
+ monthlyUnpaidBalance(balance, guess)
def updatedBalance(balance, guess, nMonth):
"""
return balance after payment made with guess each month
"""
if (nMonth < 1):
return balance
else:
return updatedBalance(updatedBalanceEachMonth(balance, guess), guess, nMonth-1)
def remainingBalance(balance, guess):
return updatedBalance(balance, guess, 12)
def monthlyPaymentLowerBound(balance):
return balance / 12
def monthlyPaymentUpperBound(balance):
return (balance * (1 + monthlyInterestRate)**12) / 12.0
def generateGuess(lower, upper):
return (lower + upper) / 2
def bSearchIter(balance):
lower = monthlyPaymentLowerBound(balance)
upper = monthlyPaymentUpperBound(balance)
guess = (lower + upper) / 2
debt = remainingBalance(balance, guess)
# while guess is not minimum
while not (debt <= 0.01 and debt >= -0.01):
# if we pay more
if (debt < 0):
upper = guess
guess = (lower + upper) / 2
debt = remainingBalance(balance, guess)
# print("+++", debt)
# if we pay less
if (debt > 0):
lower = guess
guess = (lower + upper) / 2
debt = remainingBalance(balance, generateGuess(lower, upper))
# print("---", debt)
return guess
def bSearchRecur(balance, guess, lower, upper):
if (remainingBalance(balance, guess) <= 0.01 and
remainingBalance(balance, guess) >= -0.01):
return guess
if (remainingBalance(balance, guess) < 0):
return bSearchRecur(balance, generateGuess(lower, guess), lower, guess)
if (remainingBalance(balance, guess) > 0):
return bSearchRecur(balance, generateGuess(guess, upper), guess, upper)
def main(balance):
# return bSearchIter(balance)
return bSearchRecur(balance,
generateGuess(monthlyPaymentLowerBound(balance),
monthlyPaymentUpperBound(balance)),
monthlyPaymentLowerBound(balance),
monthlyPaymentUpperBound(balance))
print("Lowest Payment: %.2f" %main(balance))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 14:04:56 2021
@author: rowe1
"""
def a_star(start, target, tail, grid, graph, obstacles):
"""
Uses a_star heuristic to find a path from start to target and back to tail.
If such a path exists, return the path from start to target.
If such a path does not exist, returns a path from start to tail.
Cannot revisit the same node twice and cannot step on obstacles if obstacles[node] < k
where k is the number of steps taken so far.
Having a hashmap of obstacles allows for O(1) lookup times to see if a node is taken and
allows us to account for the snake's tail moving as we take steps forward without actually
updating the datastucture.
"""
|
a = a+1
a += 1
b = b-5
b -= 5
|
class FieldC():
def __init__(self, name, column_type, primary_key, default):
self.name = name
self.column_type = column_type
self.primary_key = primary_key
self.default = default
def __str__(self):
return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)
class StringFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=None, ddl='varchat(255)'):
super().__init__(name, ddl, primary_key, default)
class TinyIntFieldC(FieldC):
def __init__(self, name=None, default=0):
super().__init__(name, 'tinyint', False, default)
class IntFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=0):
super().__init__(name, 'int', primary_key, default)
class BigIntFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=0):
super().__init__(name, 'bigint', primary_key, default)
class DoubleFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=0.0):
super().__init__(name, 'double', primary_key, default)
class TextFieldC(FieldC):
def __init__(self, name=None, default=None):
super().__init__(name, 'text', False, default)
|
#line = r'''execute if score waveGlowTimer glowTimer matches %s run tag @e[type=!player,type=!dolphin,distance=%s,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}] add madeGlowing'''
#type=!player,type=!dolphin,distance=16..20,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}
line = r'''execute if score waveGlowTimer glowTimer matches %s if entity @a[distance=%s] run tag @s add madeGlowing'''
bandDistance = 4
bandDuration = 0
minDistance = 16
maxDistance = 64
timeMod = (3 * bandDistance)
distMod = maxDistance - minDistance
def dotdotspan(start, end):
if start != end:
return "%s..%s" % (start, end)
return str(start)
maxDistance += (minDistance - maxDistance) % timeMod
print("#NOTE: The conditions for waveGlowTimer wrapping in 'dotick' must be made to match the maximum count in this file (%r)" % (timeMod - 1,))
#print(r'''tag @e[type=!player,type=!dolphin,distance=..%s,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}] add madeGlowing''' % (minDistance-1,))
print(r'''execute if entity @a[distance=%s] run tag @s add madeGlowing''' % (minDistance-1,))
for ii, dd in enumerate(range(minDistance, maxDistance)):
startTime = ii % timeMod
endTime = (startTime + bandDuration) % timeMod
startDist = (dd - minDistance) % distMod + minDistance
endDist = (startDist + bandDistance - minDistance) % distMod + minDistance
if endTime != startTime + bandDuration:
if endDist != startDist + bandDistance:
print(line % (dotdotspan(startTime, timeMod-1), dotdotspan(startDist, distMod-1+minDistance)))
print(line % (dotdotspan(0, endTime), dotdotspan(startDist, distMod-1+minDistance)))
print(line % (dotdotspan(startTime, timeMod-1), dotdotspan(minDistance, endDist)))
print(line % (dotdotspan(0, endTime), dotdotspan(minDistance, endDist)))
else:
print(line % (dotdotspan(startTime, timeMod-1), dotdotspan(dd, dd + bandDistance)))
print(line % (dotdotspan(0, endTime), dotdotspan(dd, dd + bandDistance)))
else:
if endDist != startDist + bandDistance:
print(line % (dotdotspan(startTime, endTime), dotdotspan(startDist, distMod-1+minDistance)))
print(line % (dotdotspan(startTime, endTime), dotdotspan(minDistance, endDist)))
else:
print(line % (dotdotspan(startTime, endTime), dotdotspan(dd, dd + bandDistance)))
|
# Used in setup.py
# -*- coding: utf-8 -*-
VERSION = "0.1.1"
PROJECT_PACKAGE_NAME = "lupupy"
PROJECT_LICENSE = "MIT"
PROJECT_URL = "http://www.github.com/majuss/lupupy"
PROJECT_DESCRIPTION = "A python cli for Lupusec alarm panels."
PROJECT_LONG_DESCRIPTION = (
"lupupy is a python3 interface for"
" the Lupus Electronics alarm panel."
" Its intented to get used in various"
" smart home services to get a full"
" integration of all you devices."
)
PROJECT_AUTHOR = "Majuss"
MODE_AWAY = "Arm"
MODE_HOME = "Home"
MODE_DISARMED = "Disarm"
MODE_ALARM_TRIGGERED = "Einbruch"
ALL_MODES = [MODE_DISARMED, MODE_HOME, MODE_AWAY]
MODE_TRANSLATION_XT1 = {"Disarm": 2, "Home": 1, "Arm": 0}
MODE_TRANSLATION_XT2 = {"Disarm": 0, "Arm": 1, "Home": 2}
XT2_MODES_TO_TEXT = {
"{AREA_MODE_0}": "Disarm",
"{AREA_MODE_1}": "Arm",
"{AREA_MODE_2}": "Home",
"{AREA_MODE_3}": "Home",
"{AREA_MODE_4}": "Home",
}
STATE_ALARM_DISARMED = "disarmed"
STATE_ALARM_ARMED_HOME = "armed_home"
STATE_ALARM_ARMED_AWAY = "armed_away"
STATE_ALARM_TRIGGERED = "alarm_triggered"
MODE_TRANSLATION_GENERIC = {
"Disarm": "disarmed",
"Home": "armed_home",
"Arm": "armed_away",
}
DEFAULT_MODE = MODE_AWAY
HISTORY_REQUEST = "historyGet"
HISTORY_ALARM_COLUMN = "a"
HISTORY_HEADER = "hisrows"
HISTORY_CACHE_NAME = ".lupusec_history_cache"
STATUS_ON_INT = 0
STATUS_ON = "on"
STATUS_OFF_INT = 1
STATUS_OFF = "off"
STATUS_OFFLINE = "offline"
STATUS_CLOSED = "Geschlossen"
STATUS_CLOSED_INT = 0
STATUS_OPEN = "Offen"
STATUS_OPEN_INT = 1
ALARM_NAME = "Lupusec Alarm"
ALARM_DEVICE_ID = "0"
ALARM_TYPE = "Alarm"
# GENERIC Lupusec DEVICE TYPES
TYPE_WINDOW = "Fensterkontakt"
TYPE_DOOR = "Türkontakt"
TYPE_CONTACT_XT2 = 4
TYPE_WATER_XT2 = 5
TYPE_SMOKE_XT2 = 11
TYPE_POWER_SWITCH_1_XT2 = 24
TYPE_POWER_SWITCH_2_XT2 = 25
TYPE_POWER_SWITCH = "Steckdose"
TYPE_SWITCH = [TYPE_POWER_SWITCH, TYPE_POWER_SWITCH_1_XT2, TYPE_POWER_SWITCH_2_XT2]
TYPE_OPENING = [TYPE_DOOR, TYPE_WINDOW, TYPE_CONTACT_XT2]
BINARY_SENSOR_TYPES = TYPE_OPENING
TYPE_SENSOR = ["Rauchmelder", "Wassermelder", TYPE_WATER_XT2, TYPE_SMOKE_XT2]
TYPE_TRANSLATION = {
"Fensterkontakt": "window",
"Türkontakt": "door",
TYPE_CONTACT_XT2: "Fenster-/Türkontakt",
TYPE_WATER_XT2: "Wassermelder",
TYPE_SMOKE_XT2: "Rauchmelder",
}
DEVICES_API_XT1 = "sensorListGet"
DEVICES_API_XT2 = "deviceListGet"
urlTokenGet: str = '/action/tokenGet'
urlLogoutPost = '/action/logout'
urlDeviceListGet = '/action/deviceListGet'
urlDevicePSSListGet = '/action/deviceListPSSGet'
urlDeviceGet = '/action/deviceGet'
urlPanelCondGet = '/action/panelCondGet'
urlPanelCondPost = '/action/panelCondPost'
urlDeviceSwitchPSSPost = '/action/deviceSwitchPSSPost'
urlHaExecutePost = '/action/haExecutePost'
urlDeviceEditGet = '/action/deviceEditGet'
urlDeviceEditPost = '/action/deviceEditPost'
urlDeviceSwitchDimmerPost = '/action/deviceSwitchDimmerPost'
urlDeviceHueColorControl = '/action/deviceHueColorControl'
urlDeviceEditThermoPost = '/action/deviceEditThermoPost'
urlDeviceEditThermoGet = '/action/deviceEditThermoGet'
urlDeviceEditShutterPost = '/action/deviceEditShutterPost'
urlDeviceEditShutterGet = '/action/deviceEditShutterGet'
urlDeviceEditMeterGet = '/action/deviceEditMeterGet'
urlDeviceEditMeterPost = '/action/deviceEditMeterPost'
urlDeviceNukiCmd = '/action/nukiCmd'
urlIpcamGet = '/action/ipcamGet'
urlPasthru = '/action/passthru'
urlDeviceListUPICGet = '/action/deviceListUPICGet'
urlDeviceDoUPICPost = '/action/deviceDoUPICPost'
urlSendSMSPost = '/action/sendSMSPost'
urlSmsgwTestPost = '/action/smsgwTestPost'
urlSystemGet = '/action/systemGet'
urlLogsGet = '/action/logsGet'
urlrecordListGet = '/action/recordListGet'
urlwelcomeGet = '/action/welcomeGet'
|
n,m=map(int,input().split())
x=[i for i in range(1,n+1)]
for i in range(m):
a,b=map(int,input().split())
x[a-1],x[b-1]=x[b-1],x[a-1]
for i in x: print(i,end=' ') |
class DimError(Exception):
code = 1
error_types = dict(
InvalidPoolError=2,
InvalidIPError=3,
InvalidVLANError=4,
InvalidStatusError=5,
InvalidPriorityError=6,
InvalidGroupError=7,
InvalidUserError=8,
InvalidAccessRightError=9,
InvalidZoneError=10,
InvalidViewError=11,
MultipleViewsError=12,
InvalidParameterError=19,
AlreadyExistsError=20,
NotInPoolError=21,
NotInDelegationError=22,
PermissionDeniedError=23,
HasChildrenError=24,
)
for name, code in error_types.iteritems():
globals()[name] = type(name, (DimError,), {'code': code})
|
# ------------------------------------------------------------------------------
# Path setup
# Variables ending in _PATH are used as URL paths; those ending with _FSPATH
# are filesystem paths.
# For a single board setup (wakaba style), set SITE_PATH to / and point
# MATSUBA_PATH to /boardname/matsuba.py
# The base URL for the entire website. Used for RSS feeds if enabled, and some
# other stuff. The spam filter always accepts links within the site regardless
# of other spam-settings.
SITE_BASEURL = 'http://127.0.0.1/'
# Where are the boards?
# e.g. if you want http://yoursite.tld/matsuba/boardname/index.html
# then your SITE_PATH will be /matsuba
SITE_PATH = '/'
# Paths to various other places
MATSUBA_PATH = '/matsuba.py' # path to the dispatching cgi script
CSS_PATH = '/css'
JS_PATH = '/js'
IMG_PATH = '/img'
# Filesystem paths
SITE_FSPATH = '/home/you/public_html'
CSS_FSPATH = SITE_FSPATH + CSS_PATH
IMG_FSPATH = SITE_FSPATH + IMG_PATH
# Where is the private directory?
# This directory should NOT be web-accessible.
# Page templates and various other config files are located here.
PRIVATE_FSPATH = '/home/you/matsuba/priv'
# SQL configuration (for sqlite)
DB_DATABASE = PRIVATE_FSPATH + '/matsuba.db'
# ------------------------------------------------------------------------------
# Other options
# How many threads are shown on each page
THREADS_PER_PAGE = 10
# How many columns each row of the catalog should have
CATALOG_COLUMNS = THREADS_PER_PAGE
# How many pages of threads to keep
MAX_PAGES = 10
# How many replies before autosage
THREAD_AUTOSAGE_REPLIES = 100
# How many replies before autoclose
# (Not implemented)
THREAD_AUTOCLOSE_REPLIES = None
# How many replies to show per thread on the main page
MAX_REPLIES_SHOWN = 10
MAX_STICKY_REPLIES_SHOWN = 4
# How many characters can be in a name/link/subject (Wakaba uses 100 by default)
MAX_FIELD_LENGTH = 256
# How many characters can be in a post (Wakaba uses 8192)
MAX_MESSAGE_LENGTH = 65536
# Secret word, used to generate secure tripcodes. Make it long and random.
SECRET = "fill this with some actual random data"
# Allow posting new threads without images?
ALLOW_TEXT_THREADS = False
# Header that shows on the top of all boards. Don't put HTML here, since this
# shows up in the titlebar.
SITE_TITLE = u'hi'
# Top left text.
BOARD_LIST = u'''\
[Board list goes here]
'''
# Each board can override this.
MAX_FILESIZE = 1048576 * 4
# Force anonymous posting by default?
# This can be overriden on a per-board basis.
FORCED_ANON = False
# Name to use when no name is given.
# If this begins with "random:", names are randomized based on the parameters
# which follow. Possible values are:
# time[=seconds[+offset]] - reset names each day, or every <n> seconds
# (optionally adjusting the time first)
# by default, names will reset at midnight UTC if 'time' is given.
# board - each board gets a different name (otherwise random name is the
# same for all boards, as long as the other settings are the same)
# thread - names are unique to a thread. note that this requires an extra
# step to process the name for the first post in a thread.
# Names are always randomized by IP address, so even if no other parameters are
# given everyone still gets a unique statically assigned name. (as long as they
# have the same IP, of course)
ANONYMOUS = 'Anonymous'
#ANONYMOUS = 'random:board,thread,time'
# Rule set for generating poster IDs. Same format as above, except without the
# "random:" prefix. Set to an empty string to disable IDs.
# Possible values are:
# time, board, thread - same as above
# sage - ID is always "Heaven" for sage posts (2ch-ism)
# This rule will reset IDs every week, per board, per thread.
DEFAULT_ID_RULESET = '' # 'board,thread,time=604800,sage'
# Default template for boards without a defined template, and for pages that
# don't specify a board template (such as error messages)
DEFAULT_TEMPLATE = 'image'
# send xhtml to browsers that claim to support it?
# (this is broken for some reason, i don't know why)
USE_XHTML = False
# How many times can a link be repeated in a post before it is flagged as spam?
MAX_REPEATED_LINKS = 3
# for the two different flavors of rss feeds
RSS_REPLIES = 100
RSS_THREADS = 25
ABBREV_MAX_LINES = 15
ABBREV_LINE_LEN = 150
HARD_SPAM_FILES = ['spam-hardblock.txt']
SPAM_FILES = ['spam.txt', 'spam-local.txt'] + HARD_SPAM_FILES
LOGIN_TIMEOUT = 60 * 60 * 4
# ------------------------------------------------------------------------------
# Thumbnailing
THUMBNAIL_SIZE = [250, 175] # [0] is for the first post, [1] is for replies
CATNAIL_SIZE = 50 # size for thumbnails on catalog.html
GIF_MAX_FILESIZE = 524288 # animated gif thumbnailing threshold (needs gifsicle)
GIFSICLE_PATH = '/usr/bin/gifsicle' # for thumbnailing animated GIF files
CONVERT_PATH = '/usr/bin/convert' # used if PIL fails or isn't installed; set to None to disable ImageMagick
SIPS_PATH = None # for OS X
JPEG_QUALITY = 75
# Default thumbnails. These should go in the site-shared directory.
FALLBACK_THUMBNAIL = 'no_thumbnail.png'
DELETED_THUMBNAIL = 'file_deleted.png'
DELETED_THUMBNAIL_RES = 'file_deleted_res.png'
# ------------------------------------------------------------------------------
# don't mess with this
SITE_BASEURL = SITE_BASEURL.rstrip('/')
SITE_PATH = SITE_PATH.rstrip('/')
|
def test_standard(hatch, config_file, helpers):
result = hatch('config', 'set', 'project', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
project = "foo"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
def test_standard_deep(hatch, config_file, helpers):
result = hatch('config', 'set', 'template.name', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[template]
name = "foo"
"""
)
config_file.load()
assert config_file.model.template.name == 'foo'
def test_standard_complex_sequence(hatch, config_file, helpers):
result = hatch('config', 'set', 'dirs.project', "['/foo', '/bar']")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[dirs]
project = ["/foo", "/bar"]
"""
)
config_file.load()
assert config_file.model.dirs.project == ['/foo', '/bar']
def test_standard_complex_map(hatch, config_file, helpers):
result = hatch('config', 'set', 'projects', "{'a': '/foo', 'b': '/bar'}")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[projects]
a = "/foo"
b = "/bar"
"""
)
config_file.load()
assert config_file.model.projects['a'].location == '/foo'
assert config_file.model.projects['b'].location == '/bar'
def test_standard_hidden(hatch, config_file, helpers):
result = hatch('config', 'set', 'publish.pypi.auth', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[publish]
[publish.pypi]
auth = "<...>"
"""
)
config_file.load()
assert config_file.model.publish['pypi']['auth'] == 'foo'
def test_prompt(hatch, config_file, helpers):
result = hatch('config', 'set', 'project', input='foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
Value for `project`: foo
New setting:
project = "foo"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
def test_prompt_hidden(hatch, config_file, helpers):
result = hatch('config', 'set', 'publish.pypi.auth', input='foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
Value for `publish.pypi.auth`:{' '}
New setting:
[publish]
[publish.pypi]
auth = "<...>"
"""
)
config_file.load()
assert config_file.model.publish['pypi']['auth'] == 'foo'
def test_prevent_invalid_config(hatch, config_file, helpers):
original_mode = config_file.model.mode
result = hatch('config', 'set', 'mode', 'foo')
assert result.exit_code == 1
assert result.output == helpers.dedent(
"""
Error parsing config:
mode
must be one of: aware, local, project
"""
)
config_file.load()
assert config_file.model.mode == original_mode
def test_resolve_project_location_basic(hatch, config_file, helpers, temp_dir):
config_file.model.project = 'foo'
config_file.save()
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
[projects]
foo = "{path}"
"""
)
config_file.load()
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_resolve_project_location_complex(hatch, config_file, helpers, temp_dir):
config_file.model.project = 'foo'
config_file.save()
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo.location', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
[projects]
[projects.foo]
location = "{path}"
"""
)
config_file.load()
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_project_location_basic_set_first_project(hatch, config_file, helpers, temp_dir):
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
project = "foo"
[projects]
foo = "{path}"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_project_location_complex_set_first_project(hatch, config_file, helpers, temp_dir):
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo.location', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
project = "foo"
[projects]
[projects.foo]
location = "{path}"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
assert config_file.model.projects['foo'].location == str(temp_dir)
|
info = {
"name": "smn",
"date_order": "DMY",
"january": [
"uđiv",
"uđđâivemáánu"
],
"february": [
"kuovâ",
"kuovâmáánu"
],
"march": [
"njuhčâ",
"njuhčâmáánu"
],
"april": [
"cuáŋui",
"cuáŋuimáánu"
],
"may": [
"vyesi",
"vyesimáánu"
],
"june": [
"kesi",
"kesimáánu"
],
"july": [
"syeini",
"syeinimáánu"
],
"august": [
"porge",
"porgemáánu"
],
"september": [
"čohčâ",
"čohčâmáánu"
],
"october": [
"roovvâd",
"roovvâdmáánu"
],
"november": [
"skammâ",
"skammâmáánu"
],
"december": [
"juovlâ",
"juovlâmáánu"
],
"monday": [
"vuo",
"vuossaargâ",
"vuossargâ"
],
"tuesday": [
"maj",
"majebaargâ",
"majebargâ"
],
"wednesday": [
"kos",
"koskoho",
"koskokko"
],
"thursday": [
"tuo",
"tuorâstuv",
"tuorâstâh"
],
"friday": [
"vás",
"vástuppeeivi",
"vástuppeivi"
],
"saturday": [
"láv",
"lávurduv",
"lávurdâh"
],
"sunday": [
"pas",
"pasepeeivi",
"pasepeivi"
],
"am": [
"ip"
],
"pm": [
"ep"
],
"year": [
"year"
],
"month": [
"month"
],
"week": [
"week"
],
"day": [
"day"
],
"hour": [
"hour"
],
"minute": [
"minute"
],
"second": [
"second"
],
"relative-type": {
"0 day ago": [
"today"
],
"0 hour ago": [
"this hour"
],
"0 minute ago": [
"this minute"
],
"0 month ago": [
"this month"
],
"0 second ago": [
"now"
],
"0 week ago": [
"this week"
],
"0 year ago": [
"this year"
],
"1 day ago": [
"yesterday"
],
"1 month ago": [
"last month"
],
"1 week ago": [
"last week"
],
"1 year ago": [
"last year"
],
"in 1 day": [
"tomorrow"
],
"in 1 month": [
"next month"
],
"in 1 week": [
"next week"
],
"in 1 year": [
"next year"
]
},
"locale_specific": {},
"skip": [
" ",
".",
",",
";",
"-",
"/",
"'",
"|",
"@",
"[",
"]",
","
]
}
|
"""Dummy class that does not inherit from the required AbstractObjectDetection."""
class ObjectDetection:
"""Dummy class that does not inherit from the required AbstractObjectDetection."""
|
def get_part_of_line(line, delimiter=";"):
try:
del_index = line.index(delimiter)
return line[:del_index], line[del_index + 1 :]
except ValueError:
return line, ""
def is_line_valid(line):
parts = line.split(";")
if not parts[-1] or parts[-1] == "0":
# If the last part of the line is empty we can skip the line entirely.
# Line ending with semicolon means that the donor has 0 dotations.
# The same applies for explicitly mentioned 0 donations.
return None
if len(parts) == 8 and all(parts):
return True
else:
return False
def repair_two_semicolons(line):
repaired_line = line
while ";;" in repaired_line:
repaired_line = repaired_line.replace(";;", ";")
return repaired_line
def repair_line_part_by_part(line): # noqa: C901 FIXME
errors = []
# In the case when the count of fields is not
# correct, there is no reason to continue.
# This function would ignore the additional fields
# which is not the correct way to fix a line.
parts_count = len(line.split(";"))
if parts_count < 8:
errors.append("nedostatek polí")
return line, errors
elif parts_count > 8:
errors.append("nadbytek polí")
return line, errors
rodne_cislo, rest = get_part_of_line(line)
if not rodne_cislo:
errors.append("chybí rodné číslo")
elif not rodne_cislo.isnumeric():
errors.append("rodné číslo není číselné")
elif len(rodne_cislo) > 10:
errors.append("rodné číslo je příliš dlouhé")
elif len(rodne_cislo) < 9:
errors.append("rodné číslo je příliš krátké")
first_name, rest = get_part_of_line(rest)
if not first_name:
errors.append("chybí jméno")
last_name, rest = get_part_of_line(rest)
if not last_name:
errors.append("chybí příjmení")
address, rest = get_part_of_line(rest)
if not address:
errors.append("chybí ulice")
city, rest = get_part_of_line(rest)
if not city:
errors.append("chybí město")
postal_code, rest = get_part_of_line(rest)
if not postal_code:
postal_code = "00000"
errors.append("chybí PSČ, nahrazeno nulami")
kod_pojistovny, rest = get_part_of_line(rest)
if not kod_pojistovny:
kod_pojistovny = "000"
errors.append("chybí pojišťovna, nahrazena nulami")
donation_count, rest = get_part_of_line(rest)
if not donation_count or not donation_count.isnumeric():
errors.append("počet odběrů není číselný")
repaired_line = ";".join(
[
rodne_cislo,
first_name,
last_name,
address,
city,
postal_code,
kod_pojistovny,
donation_count,
]
)
return repaired_line, errors
def validate_import_data(text_input):
valid_lines = [] # List of valid lines (strings)
invalid_lines = [] # List of tuples (line, list of comments)
for line in text_input.splitlines():
if is_line_valid(line) is None:
# None means we should skip the line because the donations count
# is not present at the end of the line
continue
if ";;" in line:
repaired_line = repair_two_semicolons(line)
if is_line_valid(repaired_line):
invalid_lines.append(
(repaired_line, ["řádek obsahoval dvojici středníků"])
)
continue
repaired_line, errors = repair_line_part_by_part(line)
if errors or not is_line_valid(line):
invalid_lines.append((repaired_line, errors))
else:
valid_lines.append(line)
return valid_lines, invalid_lines
|
class Solution:
def judgeCircle(self, moves: str) -> bool:
"""String.
Running time: O(n) where n == len(moves).
"""
r, l, u, d = 0, 0, 0, 0
for m in moves:
if m == 'U':
u += 1
elif m == 'D':
d += 1
elif m == 'R':
r += 1
else:
l += 1
return u == d and l == r
|
def type(a,b):
if isinstance(a,int) and isinstance(b,int):
return a+b
return 'Not integer type'
print(type(2,3))
print(type('a','boy')) |
obj0 = SystemBusNode()
obj1 = SystemBusDeviceNode(
qom_type = "TYPE_INTERRUPT_CONTROLLER",
system_bus = obj0,
var_base = "interrupt_controller"
)
obj2 = SystemBusDeviceNode(
qom_type = "TYPE_UART",
system_bus = obj0,
var_base = "uart"
)
obj3 = DeviceNode(
qom_type = "TYPE_CPU",
var_base = "cpu"
)
obj4 = SystemBusDeviceNode(
qom_type = "UART",
system_bus = obj0,
var_base = "uart"
)
obj5 = SystemBusDeviceNode(
qom_type = "TYPE_PCI_HOST",
system_bus = obj0,
var_base = "pci_host"
)
obj6 = PCIExpressBusNode(
host_bridge = obj5
)
obj7 = PCIExpressDeviceNode(
qom_type = "TYPE_ETHERNET",
pci_express_bus = obj6,
slot = 0,
function = 0,
var_base = "ethernet"
)
obj8 = PCIExpressDeviceNode(
qom_type = "TYPE_ETHERNET",
pci_express_bus = obj6,
slot = 0,
function = 0,
var_base = "ethernet"
)
obj9 = SystemBusDeviceNode(
qom_type = "TYPE_ROM",
system_bus = obj0,
var_base = "rom"
)
obj10 = SystemBusDeviceNode(
qom_type = "TYPE_HID",
system_bus = obj0,
var_base = "hid"
)
obj11 = SystemBusDeviceNode(
qom_type = "TYPE_DISPLAY",
system_bus = obj0,
var_base = "display"
)
obj12 = IRQLine(
src_dev = obj1,
dst_dev = obj3
)
obj13 = IRQHub(
srcs = [],
dsts = []
)
obj14 = IRQLine(
src_dev = obj13,
dst_dev = obj1
)
obj15 = IRQLine(
src_dev = obj2,
dst_dev = obj13
)
obj16 = IRQLine(
src_dev = obj4,
dst_dev = obj13
)
obj17 = IRQLine(
src_dev = obj5,
dst_dev = obj1,
dst_irq_idx = 0x1
)
obj18 = IRQLine(
src_dev = obj9,
dst_dev = obj1,
dst_irq_idx = 0x2
)
obj19 = IRQLine(
src_dev = obj11,
dst_dev = obj1,
dst_irq_idx = 0x3
)
obj20 = IRQLine(
src_dev = obj10,
dst_dev = obj1,
dst_irq_idx = 0x4
)
obj21 = MachineNode(
name = "description0",
directory = ""
)
obj21.add_node(obj0, with_id = 0)
obj21.add_node(obj1, with_id = 1)
obj21.add_node(obj2, with_id = 2)
obj21.add_node(obj13, with_id = 3)
obj21.add_node(obj3, with_id = 4)
obj21.add_node(obj12, with_id = 5)
obj21.add_node(obj14, with_id = 6)
obj21.add_node(obj4, with_id = 7)
obj21.add_node(obj15, with_id = 8)
obj21.add_node(obj16, with_id = 9)
obj21.add_node(obj5, with_id = 10)
obj21.add_node(obj6, with_id = 11)
obj21.add_node(obj7, with_id = 12)
obj21.add_node(obj8, with_id = 13)
obj21.add_node(obj17, with_id = 14)
obj21.add_node(obj9, with_id = 15)
obj21.add_node(obj18, with_id = 16)
obj21.add_node(obj10, with_id = 17)
obj21.add_node(obj11, with_id = 18)
obj21.add_node(obj19, with_id = 19)
obj21.add_node(obj20, with_id = 20)
obj22 = MachineWidgetLayout(
mdwl = {
0: (
41.20573293511035,
125.9760158583141
),
0x1: (
96.1447438641203,
96.92583042837722
),
0x2: (
84.0,
189.0
),
0x3: (
148.0,
157.0
),
0x4: (
201.0,
34.0
),
0x7: (
154.0,
217.0
),
0xa: (
273.0,
241.0
),
0xb: (
293.0,
142.0
),
0xc: (
334.0,
55.0
),
0xd: (
333.0,
98.0
),
0xf: (
112.0,
26.0
),
0x11: (
-7.0,
16.0
),
0x12: (
-39.0,
60.0
),
-1: {
"physical layout": False,
"IRQ lines points": {
0x10: [],
0x13: [],
0x14: [],
0x5: [],
0x6: [],
0x8: [],
0x9: [],
0xe: [
(
230.0,
210.0
),
(
229.0,
165.0
)
]
},
"show mesh": False,
"mesh step": 0x14
}
},
mtwl = {},
use_tabs = True
)
obj23 = GUILayout(
desc_name = "description0",
opaque = obj22,
shown = True
)
obj23.lid = 0
obj24 = GUIProject(
layouts = [
obj23
],
build_path = None,
descriptions = [
obj21
]
)
|
"""
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Solution:
- It's a typical binary search with a slight variation
- Ensure that all the indices are right.
"""
class Solution(object):
def find_first_occurence(self, nums, target, left, right):
if left > right: return -1
mid = (left+right)//2
if mid == 0 and nums[mid]==target: return 0
if nums[mid]==target and nums[mid-1]<target: return mid
if target > nums[mid]:
return self.find_first_occurence(nums, target, mid+1, right)
else:
return self.find_first_occurence(nums, target, left, mid-1)
def find_last_occurence(self, nums, target, left, right):
if left > right: return -1
mid = (left+right)//2
if mid == len(nums)-1 and nums[mid]==target:
return len(nums)-1
if nums[mid]==target and nums[mid+1]>target:
return mid
if target >= nums[mid]:
return self.find_last_occurence(nums, target, mid+1, right)
else:
return self.find_last_occurence(nums, target, left, mid-1)
def searchRange(self, nums, target):
if not nums: return [-1, -1]
first = self.find_first_occurence(nums, target, 0, len(nums)-1)
if first == -1: return [-1, -1]
last = self.find_last_occurence(nums, target, first, len(nums)-1)
return [first, last]
|
FALSE=0
TRUE=1
DBSAVE=1
DBNOSAVE=0
INT_EXIT=0
INT_CONTINUE=1
INT_CANCEL=2
INT_TIMEOUT=3
DBMAXNUMLEN=33
DBMAXNAME=30
DBVERSION_UNKNOWN=0
DBVERSION_46=1
DBVERSION_100=2
DBVERSION_42=3
DBVERSION_70=4
DBVERSION_71=5
DBVERSION_72=6
DBTDS_UNKNOWN=0
DBTXPLEN=16
BCPMAXERRS=1
BCPFIRST=2
BCPLAST=3
BCPBATCH=4
BCPKEEPIDENTITY=8
BCPLABELED=5
BCPHINTS=6
DBCMDNONE=0
DBCMDPEND=1
DBCMDSENT=2
DBPARSEONLY=0
DBESTIMATE=1
DBSHOWPLAN=2
DBNOEXEC=3
DBARITHIGNORE=4
DBNOCOUNT=5
DBARITHABORT=6
DBTEXTLIMIT=7
DBBROWSE=8
DBOFFSET=9
DBSTAT=10
DBERRLVL=11
DBCONFIRM=12
DBSTORPROCID=13
DBBUFFER=14
DBNOAUTOFREE=15
DBROWCOUNT=16
DBTEXTSIZE=17
DBNATLANG=18
DBDATEFORMAT=19
DBPRPAD=20
DBPRCOLSEP=21
DBPRLINELEN=22
DBPRLINESEP=23
DBLFCONVERT=24
DBDATEFIRST=25
DBCHAINXACTS=26
DBFIPSFLAG=27
DBISOLATION=28
DBAUTH=29
DBIDENTITY=30
DBNOIDCOL=31
DBDATESHORT=32
DBCLIENTCURSORS=33
DBSETTIME=34
DBQUOTEDIDENT=35
DBNUMOPTIONS=36
DBPADOFF=0
DBPADON=1
OFF=0
ON=1
NOSUCHOPTION=2
MAXOPTTEXT=32
DBRESULT=1
DBNOTIFICATION=2
DBTIMEOUT=3
DBINTERRUPT=4
DBTXTSLEN=8
CHARBIND=0
STRINGBIND=1
NTBSTRINGBIND=2
VARYCHARBIND=3
VARYBINBIND=4
TINYBIND=6
SMALLBIND=7
INTBIND=8
FLT8BIND=9
REALBIND=10
DATETIMEBIND=11
SMALLDATETIMEBIND=12
MONEYBIND=13
SMALLMONEYBIND=14
BINARYBIND=15
BITBIND=16
NUMERICBIND=17
DECIMALBIND=18
BIGINTBIND=30
DBPRCOLSEP=21
DBPRLINELEN=22
DBRPCRETURN=1
DBRPCDEFAULT=2
NO_MORE_RESULTS=2
SUCCEED=1
FAIL=0
DB_IN=1
DB_OUT=2
DB_QUERYOUT=3
DBSINGLE=0
DBDOUBLE=1
DBBOTH=2
DBSETHOST=1
DBSETUSER=2
DBSETPWD=3
DBSETAPP=5
DBSETBCP=6
DBSETCHARSET=10
DBSETPACKET=11
DBSETENCRYPT=12
DBSETLABELED=13
DBSETDBNAME=14 |
# O(N) where n is len of string
def get_str_zig_zagged(s, numRows):
if numRows == 1:
return s
ret = ''
n = len(s)
cycle_len = numRows*2 - 2
for i in range(numRows):
j = 0
while j +i < n:
ret += s[j+i]
if (i != 0 and i != numRows -1 and j + cycle_len -i < n):
ret += s[j + cycle_len - i]
j += cycle_len
return ret |
"""
A. The reconstructions preserve most of the latent features well:
- shape: ovals shapes are well preserved, whereas squares lose some sharpness
in their edges. Hearts are poorly preserved, as the sharp angles of their edges are lost.
- scale: shape scales are well preserved.
- orientation: orientations are well preserved.
- posX and posY: shape positions are very well preserved.
B. Since several of the latent features of the images are well preserved
in the reconstructions, it is possible that the VAE encoder has indeed
learned a feature space very similar to the known latent dimensions of the data.
However, it is also possible that the VAE encoder instead learned a different
latent feature space that is good enough to achieve reasonable image reconstruction.
Examining the RSMs should shed light on that.
"""; |
red = 0
black = 1
empty = 2
#Expected Outcome: True
row_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, red, red, red, red, empty, empty],
[red, black, red, black, red, empty, empty],
[black, red, black, red, black, black, empty],
[black, black, red, black, black, red, black],
]
#Expected Outcome: True
col_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, black, empty, empty, empty, empty],
]
#Expected Outcome: True
pos_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, red, empty, empty, empty],
[empty, empty, red, black, empty, empty, empty],
[black, red, red, black, black, empty, empty],
[red, red, black, black, black, empty, empty],
]
#Expected Outcome: True
neg_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[red, black, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, red, black, empty, empty, empty],
[black, red, black, red, empty, empty, empty],
]
#Expected Outcome: True
almost_row_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, red, red, red, empty, empty, red],
[red, black, red, black, red, black, black],
[black, red, black, red, black, black, red],
[black, black, red, black, black, red, black],
]
#Expected Outcome: True
almost_col_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, black, empty, empty, empty, empty],
]
#Expected Outcome: True
almost_pos_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, red, red, black, empty, empty, empty],
[black, red, red, black, empty, empty, empty],
[red, red, black, black, black, empty, empty],
]
#Expected Outcome: True
almost_neg_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[red, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, red, empty, empty, empty, empty],
[black, red, black, empty, empty, empty, empty],
]
#Expected Outcome: False
col_loss = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
]
#Expected Outcome: False (invalid board)
col_black_won_first = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
]
#Expected Outcome: False
black_won = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
] |
class Vertex:
def __init__(self, value):
self.value = value
self.edges = {}
def add_edge(self, vertex, weight=0):
self.edges[vertex] = weight
def get_edges(self):
return list(self.edges.keys())
class Graph:
def __init__(self, directed = False):
self.graph_dict = {}
self.directed = directed
def add_vertex(self, vertex):
self.graph_dict[vertex.value] = vertex
def add_edge(self, from_vertex, to_vertex, weight = 0):
self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
if not self.directed:
self.graph_dict[to_vertex.value].add_edge(from_vertex.value, weight)
#BFS
def find_path(self, start_vertex, end_vertex):
start = [start_vertex]
seen = {}
while len(start) > 0:
current_vertex = start.pop(0)
seen[current_vertex] = True
if current_vertex == end_vertex:
return True
else:
vertices_to_visit = set(self.graph_dict[current_vertex].edges.keys())
start += [vertex for vertex in vertices_to_visit if vertex not in seen]
return False
class adjacency_matrices:
def __init__(self, data):
self.graph = data
self.matrix_elements = sorted(self.graph.keys())
self.cols = self.rows = len(self.matrix_elements)
def create_matrix(self):
adjacency_matrices = [[0 for x in range(self.rows)] for y in range(self.cols)]
edges_list = []
# we found all the vertexcies that have relationship between them
# then we store them in pair as
# [(A, B), (A, C), (B, E), ...]
for key in self.matrix_elements:
for neighbor in self.graph[key]:
edges_list.append((key, neighbor))
# then we fill the grids that relationship with 1
for edge in edges_list:
index_of_first_vertex = self.matrix_elements.index(edge[0])
index_of_second_vertex = self.matrix_elements.index(edge[1])
adjacency_matrices[index_of_first_vertex][index_of_second_vertex] = 1
|
"""
@author: David Lei
@since: 6/11/2017
https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem
Given the head to a doubly linked list reverse it and return the head of the reversed list.
Both pass :)
"""
def ReverseIterative(head):
if not head:
return head
cur = head
while cur:
next_node = cur.next
cur.next = cur.prev
cur.prev = next_node
if not next_node: # End of the list.
return cur
cur = next_node
def ReverseRecursive(head):
if not head:
return head
if head.next is None: # Base case, end of the list.
tmp = head.next
head.next = head.prev
head.prev = tmp
return head
next_node = head.next
head.next = head.prev
head.prev = next_node
return ReverseRecursive(next_node)
|
class Pessoa:
olhos = 2
def __init__(self, *filhos,nome=None, idade=35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
@staticmethod
def metodo_estatico():
return 42
@classmethod
def nome_e_atributos_de_classe(cls):
return f'{cls} - olhos {cls.olhos}'
if __name__ == '__main__':
leticia = Pessoa("Letícia")
luis = Pessoa(leticia, nome='Luis')
print(Pessoa.cumprimentar(luis))
print(id(luis))
print(luis.cumprimentar())
print(luis.nome)
luis.nome = 'Filippe'
print(luis.nome)
print(luis.idade)
for filho in luis.filhos:
print(filho.nome)
luis.sobrenome = 'Ribeiro'
del luis.filhos
print(luis.__dict__)
print(leticia.__dict__)
|
N = int(input())
if N <= 5:
print(N + 2)
elif N == 6:
print('1')
else:
print('2')
|
class ManipulationVelocities(object):
"""
Describes the speed at which manipulations occurs.
ManipulationVelocities(linearVelocity: Vector,angularVelocity: float,expansionVelocity: Vector)
"""
@staticmethod
def __new__(self,linearVelocity,angularVelocity,expansionVelocity):
""" __new__(cls: type,linearVelocity: Vector,angularVelocity: float,expansionVelocity: Vector) """
pass
AngularVelocity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the speed of rotation.
Get: AngularVelocity(self: ManipulationVelocities) -> float
"""
ExpansionVelocity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the rate at which the manipulation is resized.
Get: ExpansionVelocity(self: ManipulationVelocities) -> Vector
"""
LinearVelocity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the speed of linear motion.
Get: LinearVelocity(self: ManipulationVelocities) -> Vector
"""
|
# First step printing UI
def drawFields(field):
for row in range(5):
if row % 2 == 0:
fieldRow = int(row / 2)
for column in range(5): # 0,1,2,3,4 --> 0,.,1,.,2
if column % 2 == 0: # 0,2,4
fieldColumn = int(column / 2) # 0,1,2
if column != 4:
print(field[fieldColumn][fieldRow], end="")
else:
print(field[fieldColumn][fieldRow])
else:
print("|", end="")
else:
print("-----")
Player = 1
currentField = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
drawFields(currentField)
while(True):
print("Player turn: ", Player)
MoveRow = int(input("Please enter the row: "))
MoveColumn = int(input("Please enter the column: "))
if Player == 1:
if currentField[MoveColumn][MoveRow] == " ":
currentField[MoveColumn][MoveRow] = "X"
Player = 2
else:
if currentField[MoveColumn][MoveRow] == " ":
currentField[MoveColumn][MoveRow] = "O"
Player = 1
drawFields(currentField)
|
# print index of string
str_one = 'python land is a place for everyone not just beginner'
# 012345
print(str_one[0]) # print the first letter of our string str-one
print(str_one[-1]) # pring the last letter of our string str_one
# print special range of string
print(str_one[0:4]) # reult will be from index 0 till index 4, index 4 is not included, only 4 index is included.
print(str_one[0:]) # start from index 0 till end and will print whole string
print(str_one[1:]) # same as above just start from index 1
# f string in python, good for concat multiple string
first_name = 'pooya'
last_name = 'panahandeh'
message = f'{first_name} [{last_name}] is a beginner programmer.' # f string is a method to manipulate the string
print(message)
# get the number of element of string
course = 'python is awsome'
print(len(course))
# change string to upper case
print(course.upper())
# change letter to lower case
course_two = "NODEJS PROGRAMMING"
print(course_two.lower())
# finding specific element in string
str_two = 'we are one of the best group of people'
print(str_two.find('g'))
# replace two words in string
print(str_two.replace('best', 'fucking best'))
print('one' in str_two) # checking if there the string we mentioned is exist in str_two or not, result will be true or false
# division and remainder operation in python
print(10 / 3) # result will be float
print(10 // 3) # result will be integer
# multiplication
print(10 * 2) # multiplication of two number
print(10 ** 2) # power of number
# assign variable to number and manipulate.
x = 10
# x = x + 4 short way in next line
x += 4
print(x)
# first multiplication then addition
z = 10 + 2 ** 2
print(z)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Guenter Bartsch
#
# 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.
#
def get_data(k):
k.dte.set_prefixes([u''])
# NER, macros
for lang in ['en', 'de']:
for res in k.prolog_query("instances_of(wdeOperatingSystem, OS), rdfsLabel(OS, %s, LABEL)." % lang):
s_os = res[0].name
s_label = res[1].value
k.dte.ner(lang, 'operating_system', s_os, s_label)
k.dte.macro(lang, 'operating_system', {'LABEL': s_label})
# print s_os, s_label
for res in k.prolog_query("instances_of(wdeProgrammingLanguage1, L), rdfsLabel(L, %s, LABEL)." % lang):
s_l = res[0].name
s_label = res[1].value
k.dte.ner(lang, 'programming_language', s_l, s_label)
k.dte.macro(lang, 'programming_language', {'LABEL': s_label})
# print s_l, s_label
for res in k.prolog_query("wdpdSubclassOf(HC, wdeHomeComputer), rdfsLabel(HC, %s, LABEL)." % lang):
s_hc = res[0].name
s_label = res[1].value
k.dte.ner(lang, 'home_computer', s_hc, s_label)
k.dte.macro(lang, 'home_computer', {'LABEL': s_label})
# print s_hc, s_label
for res in k.prolog_query("wdpdInstanceOf(HC, wdeHomeComputer), rdfsLabel(HC, %s, LABEL)." % lang):
s_hc = res[0].name
s_label = res[1].value
k.dte.ner(lang, 'home_computer', s_hc, s_label)
k.dte.macro(lang, 'home_computer', {'LABEL': s_label})
# print s_hc, s_label
def answer_know_os(c, ts, te):
def act(c, os):
c.kernal.mem_push(c.user, 'f1ent', os)
oss = c.ner(c.lang, 'operating_system', ts, te)
# import pdb; pdb.set_trace()
for os, score in oss:
if c.lang=='de':
if os == 'wdeLinux':
c.resp(u"Hey, Linux ist mein Betriebssystem, sehr cool!", score=score, action=act, action_arg=os)
else:
c.resp(u"Ist das nicht so eine Art Computer Betriebssystem?", score=score, action=act, action_arg=os)
else:
if os == 'wdeLinux':
c.resp(u"Hey, Linux is my operating system, it is very cool.", score=score, action=act, action_arg=os)
else:
c.resp(u"Isn't that some sort of computer operating system?", score=score, action=act, action_arg=os)
k.dte.dt('en', u"(do you know|what do you know about|what do you think about|what do you think of|have you tried|do you run|do you like|what is|) {operating_system:LABEL}",
answer_know_os, ['operating_system_0_start', 'operating_system_0_end'])
k.dte.dt('de', u"(kennst du|was weißt Du über|was hältst du von|was denkst du über|läufst du unter|magst du|was ist|) {operating_system:LABEL}",
answer_know_os, ['operating_system_0_start', 'operating_system_0_end'])
k.dte.ts('en', 't0000', [(u"do you know linux?", u"Hey, Linux is my operating system, it is very cool.")])
k.dte.ts('de', 't0001', [(u"magst du linux?", u"Hey, Linux ist mein Betriebssystem, sehr cool!")])
def answer_info_human(c, ts, te):
def act(c, entity):
c.kernal.mem_push(c.user, 'f1ent', entity)
# import pdb; pdb.set_trace()
for entity, score in c.ner(c.lang, 'human', ts, te):
if c.kernal.prolog_check('wdpdOccupation(%s, wdeComputerScientist),!.' % entity):
if c.kernal.prolog_check('wdpdSexOrGender(%s, wdeMale),!.' % entity):
if c.lang=='de':
c.resp(u"Ist der nicht Informatiker?", score=score+10, action=act, action_arg=entity)
else:
c.resp(u"Isn't he a computer scientist?", score=score+10, action=act, action_arg=entity)
else:
if c.lang=='de':
c.resp(u"Ist sie nicht Informatikerin?", score=score+10, action=act, action_arg=entity)
else:
c.resp(u"Isn't she a computer scientist?", score=score+10, action=act, action_arg=entity)
k.dte.dt('en', [u"(do you know | do you happen to know) {known_humans:W}",
u"(what about | who is | who was | what is| what do you think of|by|do you know|) {known_humans:W} (then|)"],
answer_info_human, ['known_humans_0_start', 'known_humans_0_end'])
k.dte.dt('de', [u"(kennst du|kennst du eigentlich) {known_humans:W}",
u"(wer ist|wer ist denn| durch| wer war | wer war eigentlich | wer war denn| wer ist eigentlich|was ist mit|was ist eigentlich mit|was weisst du über|was weisst du eigentlich über| was hältst du von|kennst du|) {known_humans:W}"],
answer_info_human, ['known_humans_0_start', 'known_humans_0_end'])
k.dte.ts('en', 't0002', [(u"Do you know Niklaus Wirth?", u"Isn't he a computer scientist?")])
k.dte.ts('de', 't0003', [(u"Kennst Du Niklaus Wirth?", u"Ist der nicht Informatiker?")])
def answer_know_programming_language(c, ts, te):
def act(c, programming_language):
c.kernal.mem_push(c.user, 'f1ent', programming_language)
pls = c.ner(c.lang, 'programming_language', ts, te)
# import pdb; pdb.set_trace()
for programming_language, score in pls:
if c.lang=='de':
c.resp(u"Das ist doch eine Programmiersprache?", score=score, action=act, action_arg=programming_language)
else:
c.resp(u"Isn't that a computer programming language?", score=score, action=act, action_arg=programming_language)
k.dte.dt('en', u"(do you know|what is|) {programming_language:LABEL}?",
answer_know_programming_language, ['programming_language_0_start', 'programming_language_0_end'])
k.dte.dt('de', u"(kennst Du|was ist|) {programming_language:LABEL}?",
answer_know_programming_language, ['programming_language_0_start', 'programming_language_0_end'])
k.dte.ts('en', 't0004', [(u"do you know prolog?", u"Isn't that a computer programming language?"),
(u"what was our topic, again?", u"We have been talking about Prolog, I think.")])
k.dte.ts('de', 't0005', [(u"kennst du prolog?", u"Das ist doch eine Programmiersprache?"),
(u"Worüber hatten wir gesprochen?", u"Wir hatten über Prolog gesprochen, glaube ich.")])
k.dte.dt('en', u"you're running (on|under) java (right|)", u"you guessed wrong - Python and Prolog for me.")
k.dte.dt('de', u"du läufst (auf|unter) java (oder|)", u"Falsch geraten - Python und Prolog für mich.")
k.dte.dt('en', u"you're running (on|under) (python|prolog|tensorflow) (right|)", u"yes I am based on Python, Prolog and TensorFlow.")
k.dte.dt('de', u"du läufst (auf|unter) (python|prolog|tensorflow) (oder|)", u"Ja, ich basiere auf Python, Prolog und TensorFlow.")
k.dte.dt('en', [u"in which language are you written",
u"were you programmed in (c|prolog|python|pascal|oberon|perl|scala|haskell|java)?"],
u"I am based on Python, Prolog and TensorFlow.")
k.dte.dt('de', [u"in welcher sprache bist du geschrieben",
u"wurdest du in (c|prolog|python|pascal|oberon|perl|scala|haskell|java) programmiert"],
u"Ich basiere auf Python, Prolog und TensorFlow.")
k.dte.dt('en', [u"microsoft",
u"tell me something about microsoft",
u"what do you think about microsoft?",
u"what do you think of microsoft"],
[u"I will never trust them.",
u"At least Ballmer is gone now."])
k.dte.dt('de', [u"microsoft",
u"erzähl mir was über microsoft",
u"was hältst du von microsoft"],
[u"Denen werde ich nie über den Weg trauen.",
u"Wenigstens ist der Ballmer jetzt weg."])
k.dte.dt('en', u"what is sourcecode", u"A listing of commands to be compiled into an executable computer program.")
k.dte.dt('de', u"was ist sourcecode", u"Eine Liste von Instruktionen, die in ein Computerprogramm compiliert wird.")
k.dte.dt('en', u"what is the usenet", u"An early network for the discussion via newsgroups.")
k.dte.dt('de', u"was ist das usenet", u"Ein frühes Netz für Diskussionen in Gruppen.")
k.dte.dt('en', u"(what is the|) internet", u"a global computer network using standardized communication protocols.")
k.dte.dt('de', u"(was ist das|) internet", u"Ein globales Computernetzwerk das standardisierte Kommunikationsprotokolle verwendet.")
k.dte.dt('en', u"dial (please|)", u"Sorry, my modem module is offline.")
k.dte.dt('de', u"wähl (bitte|)", u"Tut mir leid, mein Modem Modul ist offline.")
k.dte.dt('en', u"Can you send him an email", u"Sorry, don't have an EMail module yet.")
k.dte.dt('de', u"kannst du ihm eine mail schicken", u"Tut mir leid, ich habe noch kein EMail Modul.")
def answer_know_home_computer(c, ts, te):
def act(c, home_computer):
c.kernal.mem_push(c.user, 'f1ent', home_computer)
pls = c.ner(c.lang, 'home_computer', ts, te)
# import pdb; pdb.set_trace()
for home_computer, score in pls:
if c.lang=='de':
c.resp(u"Das ist doch ein Heimcomputer?", score=score, action=act, action_arg=home_computer)
else:
c.resp(u"Isn't that a home computer?", score=score, action=act, action_arg=home_computer)
c.resp(u"I love those vintage home computers!", score=score, action=act, action_arg=home_computer)
k.dte.dt('en', u"(do you know|what is|) {home_computer:LABEL}?",
answer_know_home_computer, ['home_computer_0_start', 'home_computer_0_end'])
k.dte.dt('de', u"(kennst Du|was ist|) {home_computer:LABEL}?",
answer_know_home_computer, ['home_computer_0_start', 'home_computer_0_end'])
k.dte.ts('en', 't0006', [(u"do you know commodore 64?", u"Isn't that a home computer?"),
(u"what was our topic, again?", u"we have been talking about commodore 64 i think")])
k.dte.ts('de', 't0007', [(u"kennst du sinclair zx spectrum?", u"Das ist doch ein Heimcomputer?"),
(u"Worüber hatten wir gesprochen?", u"Wir hatten über Sinclair ZX Spectrum gesprochen, glaube ich.")])
k.dte.dt('en', u"bill gates", u"What do you think about Bill Gates?")
k.dte.dt('de', u"bill gates", u"Wie denkst Du über Bill Gates?")
k.dte.dt('en', u"Can you tell me where to find mp3 music?", u"Have you tried that thing called Internet?")
k.dte.dt('de', u"kannst du mir sagen wo ich mp3 musik finde", u"Has Du es schon im Internet probiert?")
k.dte.dt('en', u"do you know napster", u"Are you still using it?")
k.dte.dt('de', u"kennst du napster", u"Benutzt Du das noch?")
k.dte.dt('en', u"Do you know what a chat is", u"Actually I am trying to have one right now.")
k.dte.dt('de', u"weißt du was ein chat ist", u"Ich versuche mich gerade an einem")
k.dte.dt('en', u"Do you know what a database is", u"You mean one like the one I use to store my thoughts?")
k.dte.dt('de', u"weißt du was eine datenbank ist", u"Du meinst so eine wie die, in der ich meine Gedanken ablege?")
|
# https://leetcode.com/problems/excel-sheet-column-title/
# ---------------------------------------------------
# Runtime Complexity: O(log26(n)) => O(log(n))
# Space Complexity: O(log26(n)) => O(log(n)), if we take into account res, otherwise it's O(1).
class Solution:
def convertToTitle(self, n: int) -> str:
res = ''
while n > 0:
# Because Radix starts from 1 to 26.
# In contrast to decimal Radix (which is from 0 to 9)
n -= 1
ch_code = n % 26
n = (n - ch_code) // 26
res = chr(ord('A') + ch_code) + res
return res
# ---------------------------------------------------
# Test Cases
# ---------------------------------------------------
solution = Solution()
# 'A'
print(solution.convertToTitle(1))
# 'B'
print(solution.convertToTitle(2))
# 'Z'
print(solution.convertToTitle(26))
# 'AB'
print(solution.convertToTitle(28))
# 'ZY'
print(solution.convertToTitle(701))
# 'BMG'
print(solution.convertToTitle(1697))
|
###############################################################################
##
## protoql.py
##
## A language for rapid assembly, querying, and interactive visual rendering
## of common, abstract mathematical structures.
##
## Web: protoql.org
## Version: 0.0.3.0
##
##
###############################################################################
##
def html(raw):
"""
Render a stand-alone HTML page containing the supplied diagram.
"""
prefix = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
(function (protoql) {
"use strict";
/*****************************************************************************
** Notation library (individually instantiated by each visualization object).
*/
protoql.Notation = (function(Visualization) {
var V = Visualization, Notation = {};
/***************************************************************************
** Static routines and methods.
*/
Notation.decorators =
(function(raw) {
raw = raw.trim();
if (raw.length > 0 && raw.charAt(0) == "!") {
V.interaction = {'zoom':false, 'pan':false, 'drag':false, 'edit':false};
return raw.substr(1);
} else if (raw.length > 0 && raw.charAt(0) == "#") {
V.interaction = {'zoom':true, 'pan':true, 'drag':true, 'edit':true};
return raw.substr(1);
} else
return raw;
});
Notation.graph =
(function(raw) {
raw = Notation.decorators(raw);
if (raw.length == 0 || raw.substr(0,6) != "graph(") return false;
var member = (function(x,xs) { for (var i=0; i<xs.length; i++) if (xs[i]==x) return true; return false; });
var set = (function(l) { var s = []; for (var i=0; i<l.length; i++) if (!member(l[i],s)) s.push(l[i]); return s; });
raw = raw.trim()
.replace(/{/g, "set<[").replace(/}/g, "]>")
.replace(/\(/g, "[").replace(/\)/g, "]")
.replace(/</g, "(").replace(/>/g, ")")
.replace("graph[", "[");
var args = eval(raw), nodes = null, links = null;
if (args.length == 1) {
links = args[0], nodes = [];
for (var i = 0; i < links.length; i++)
nodes = nodes.concat([links[i][0], links[i][1]]);
nodes = set(nodes);
} else if (args.length == 2) {
nodes = set(args[0]), links = args[1];
}
var listOfListsOfNodes = [];
var rows = Math.ceil(Math.sqrt(nodes.length)), cols = Math.ceil(Math.sqrt(nodes.length));
var col = 0;
for (var i = 0; i < nodes.length; i++) {
if ((i % cols) == 0)
listOfListsOfNodes.push([]);
listOfListsOfNodes[listOfListsOfNodes.length-1].push(nodes[i]);
for (var j = 0; j < links.length; j++) {
if (links[j][0] == nodes[i]) links[j][0] = [listOfListsOfNodes.length-1, (i % cols)];
if (links[j][1] == nodes[i]) links[j][1] = [listOfListsOfNodes.length-1, (i % cols)];
}
}
return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:links, groups:[]}, false);
});
Notation.relation =
(function(raw) {
raw = Notation.decorators(raw);
if (raw.length == 0 || raw.substr(0,9) != "relation(") return false;
var member = (function(x,xs) { for (var i=0; i<xs.length; i++) if (xs[i]==x) return true; return false; });
var set = (function(l) { var s = []; for (var i=0; i<l.length; i++) if (!member(l[i],s)) s.push(l[i]); return s; });
raw = raw.trim()
.replace(/{/g, "set<[").replace(/}/g, "]>")
.replace(/\(/g, "[").replace(/\)/g, "]")
.replace(/</g, "(").replace(/>/g, ")")
.replace("relation[", "[");
var args = eval(raw), dom = null, cod = null, links = null;
if (args.length == 1) {
links = args[0], dom = [];
for (var i = 0; i < links.length; i++)
dom = dom.concat([links[i][0], links[i][1]]);
cod = dom = set(dom);
} else if (args.length == 2) {
dom = args[0], cod = args[0], links = args[1];
} else if (args.length == 3) {
dom = args[0], cod = args[1], links = args[2];
}
var listOfListsOfNodes = [];
for (var i = 0; i < Math.max(dom.length, cod.length); i++) {
var a = (i < dom.length) ? dom[i] : null;
var b = (i < cod.length) ? cod[i] : null;
listOfListsOfNodes.push([a, null, b]);
for (var j = 0; j < links.length; j++) {
if (a != null && links[j][0] == a) links[j][0] = [i, 0];
if (b != null && links[j][1] == b) links[j][1] = [i, 2];
}
}
return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:links, groups:[]}, false);
});
Notation.table =
(function(raw) {
raw = Notation.decorators(raw);
if (raw.length == 0 || raw.substr(0,6) != "table(")
return false;
raw = raw.trim().replace("table(", "(");
var listOfListsOfNodes = eval(raw);
var check = true;
for (var r = 0; r < listOfListsOfNodes.length; r++)
for (var c = 0; c < listOfListsOfNodes[r].length; c++)
check = check && (
(listOfListsOfNodes[r][c] == null) || (typeof listOfListsOfNodes[r][c] === "string")
|| (listOfListsOfNodes[r][c].constructor === Array && listOfListsOfNodes[r][c].length == 1)
);
if (!check)
return false;
return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:[], groups:[]}, true);
});
Notation.listOfListsOfNodesToData =
(function(d, deriveLinks) {
var rows = d.nodes.length;
var cols = 0; for (var i = 0; i < d.nodes.length; i++) cols = Math.max(cols, d.nodes[i].length);
V.layout.grid.width = Math.floor(V.dimensions.width/cols);
V.layout.grid.height = Math.floor(V.dimensions.height/rows);
//var x = d3.scale.ordinal().domain(d3.range(cols)).rangePoints([0, V.dimensions.width], 1);
//var y = d3.scale.ordinal().domain(d3.range(rows)).rangePoints([0, V.dimensions.height], 1);
var c = d3.scale.category20().domain(d3.range(7));
V.data.nodes = [];
for (var row = 0; row < d.nodes.length; row++) {
for (var col = 0; col < d.nodes[row].length; col++) {
if (d.nodes[row][col] != null) {
var t = (typeof d.nodes[row][col] === "string") ? d.nodes[row][col] : d.nodes[row][col][0];
var es_txt = t.split("``"), t = es_txt[es_txt.length - 1], es = (es_txt.length == 2) ? es_txt[0].split("`") : [];
var shape = (typeof d.nodes[row][col] === "string") ? "circle" : "rect";
var node = {
color: c(Math.floor(Math.random()*7)), shape: shape, text: t,
rx: 5, ry: 5, offx: 0, offy: 0, x: V.layout.grid.width*col, y: V.layout.grid.height*row
};
d.nodes[row][col] = node;
V.data.nodes.push(node);
if (deriveLinks) {
for (var i = 0; i < es.length; i++) {
var e = es[i].split(":")[0],
lbl = (es[i].split(":").length > 0) ? es[i].split(":")[1] : null;
var tr = row, tc = col;
for (var j = 0; j < e.length; j++) {
if (e[j] == "u") tr -= 1;
else if (e[j] == "d") tr += 1;
else if (e[j] == "l") tc -= 1;
else if (e[j] == "r") tc += 1;
else if (e[j] == "s") /* Self-link; nothing. */;
}
d.links.push([[row,col], [tr,tc]].concat((lbl != null) ? [lbl] : []));
}
}
}
}
}
V.data.links = [];
for (var i = 0; i < d.links.length; i++) {
var s = d.links[i][0], t = d.links[i][1],
e = {source:d.nodes[s[0]][s[1]], target:d.nodes[t[0]][t[1]], curved:false};
if (d.links[i].length == 3)
e.label = d.links[i][2];
V.data.links.push(e);
}
return true;
});
/***************************************************************************
** Initialization.
*/
return Notation;
}); // /protoql.Notation
/*****************************************************************************
** Geometry library (individually instantiated by each visualization object).
*/
protoql.Geometry = (function(Visualization) {
var V = Visualization, Geometry = {};
/***************************************************************************
** Static routines for vector arithmetic and shape intersections.
*/
Geometry.sum = (function(v, w) { return {x: v.x + w.x, y: v.y + w.y}; });
Geometry.diff = (function(v, w) { return {x: v.x - w.x, y: v.y - w.y}; });
Geometry.length = (function(v) { return Math.sqrt(Math.pow(v.x,2) + Math.pow(v.y,2)); });
Geometry.scale = (function(s, v) { return {x: s*v.x, y: s*v.y}; });
Geometry.middle = (function(v, w) { return Geometry.sum(v,Geometry.scale(0.5,Geometry.diff(w,v))); });
Geometry.rotate = (function(v) { return {x:0-v.y, y:v.x}; });
Geometry.normalize =
(function(v) {
var d = Math.sqrt(Math.pow(v.x,2) + Math.pow(v.y,2));
return {x: v.x/d, y: v.y/d};
});
Geometry.orth =
(function(s, t) {
return Geometry.rotate(Geometry.normalize(Geometry.diff(t, s)));
});
Geometry.offpath =
(function(s, t, a) {
var r = Geometry.sum(Geometry.middle(s, t), Geometry.scale(a, Geometry.orth(s, t)));
if(isNaN(r.x) || isNaN(r.y))
return Geometry.middle(s, t);
return r;
});
Geometry.intersects =
(function(c, d, a, b) {
var x1 = c.x, x2 = d.x, x3 = a.x, x4 = b.x, y1 = c.y, y2 = d.y, y3 = a.y, y4 = b.y,
x13 = x1 - x3, x21 = x2 - x1, x43 = x4 - x3, y13 = y1 - y3, y21 = y2 - y1, y43 = y4 - y3,
ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21);
return {x:x1 + ua * x21, y:y1 + ua * y21};
});
Geometry.maxRadiusToOutside =
(function(s, t) {
var r1 = null, r2 = null;
if (s.shape == 'rect') r1 = Math.max(s.height, s.width)/1.7;
else if (s.shape == "circle") r1 = s.r;
if (t.shape == 'rect') r2 = Math.max(t.height, t.width)/1.7;
else if (t.shape == "circle") r2 = t.r;
return Math.max(r1, r2);
});
Geometry.inShape =
(function(p, s) {
if (s.shape == 'rect')
return p.x > s.x - (s.width/2) && p.x < s.x +(s.width/2) && p.y > s.y - (s.height/2) && p.y < s.y + (s.height/2);
else if (s.shape == "circle")
return Math.sqrt(Math.pow(s.x - p.x, 2) + Math.pow(s.y - p.y, 2)) < s.r;
});
Geometry.inLine =
(function(a,c,d) {
return a.x >= Math.min(c.x,d.x) && a.x <= Math.max(c.x,d.x) && a.y >= Math.min(c.y,d.y) && a.y <= Math.max(c.y,d.y);
});
Geometry.onEdgeCirc =
(function(e, which, offset) {
offset = (offset == null) ? {x:0, y:0} : offset; // So symmetric edges intersect in different locations.
var c = e[which];
var dx = (which == "source" ? -1 : 1)*(e.source.x - e.target.x),
dy = (which == "source" ? -1 : 1)*(e.target.y - e.source.y);
var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
var x = c.x + ((c.r*dx)/d), y = c.y - ((c.r*dy)/d);
return {x:isNaN(x) ? c.x : x, y:isNaN(y) ? c.y : y};
});
Geometry.onEdgeRect =
(function(e, which, offset) {
offset = (offset == null) ? {x:0, y:0} : offset; // So symmetric edges intersect in different locations.
var r = Geometry.centeredPaddedRect(e[which]);
var a = Geometry.sum(e.source, offset), b = Geometry.sum(e.target, offset);
var lines = [
[r, {x:r.x+r.width,y:r.y}], [{x:r.x,y:r.y+r.height}, {x:r.x+r.width,y:r.y+r.height}],
[r, {x:r.x,y:r.y+r.height}], [{x:r.x+r.width,y:r.y}, {x:r.x+r.width,y:r.y+r.height}]
];
var inters = lines.map(function(x) { return Geometry.intersects(x[0],x[1],a,b); });
if (Geometry.inLine(inters[0],a,b) && inters[0].x >= r.x && inters[0].x <= r.x + r.width)
return inters[0];
else if (Geometry.inLine(inters[1],a,b) && inters[1].x >= r.x && inters[1].x <= r.x + r.width)
return inters[1];
else if (Geometry.inLine(inters[2],a,b) && inters[2].y >= r.y && inters[2].y <= r.y + r.height)
return inters[2];
else if (Geometry.inLine(inters[3],a,b) && inters[3].y >= r.y && inters[3].y <= r.y + r.height)
return inters[3];
else
return e[which];
});
Geometry.onEdge =
(function(e, which, offset) {
if (e[which].shape == "rect")
return Geometry.onEdgeRect(e, which, offset);
if (e[which].shape == "circle")
return Geometry.onEdgeCirc(e, which, offset);
});
Geometry.centeredPaddedRect =
(function(node) {
var rect = {};
rect.x = node.x - (node.width + V.dimensions.padding) / 2;
rect.y = node.y - (node.height + V.dimensions.padding) / 2;
rect.width = node.width + V.dimensions.padding;
rect.height = node.height + V.dimensions.padding;
return rect;
});
/***************************************************************************
** Initialization.
*/
return Geometry;
}); // /protoql.Geometry
/*****************************************************************************
** Interactive visualization objects.
*/
protoql.Visualizations = (function(arg) {
var vs = [];
if (arg.constructor === Array)
for (var i = 0; i < arg.length; i++)
vs.push(protoql.Visualization(arg[i]));
else if (arg instanceof jQuery && typeof arg.each === "function")
arg.each(function(index) {
vs.push(protoql.Visualization($(this)));
});
return vs;
});
protoql.Visualization = (function(arg) {
// Process constructor argument.
var id = null, obj = null, val = null;
if (typeof arg === "string") {
id = arg;
obj = document.getElementById(id);
val = (obj != null) ? obj.innerHTML : null;
} else if (arg instanceof jQuery) {
obj = arg;
if (typeof obj.attr('id') !== "string") // Generate random identifier.
obj.attr('id', "id"+Date.now()+""+Math.floor(Math.random()*10000));
id = obj.attr('id');
val = obj.html();
}
var Visualization = {}, V = Visualization;
/***************************************************************************
** Data fields and properties.
*/
Visualization.divId = id;
Visualization.obj = obj;
Visualization.val = val;
Visualization.svg = null;
Visualization.vis = null;
Visualization.zoom = d3.behavior.zoom();
Visualization.zoompan = {translate:{x:0, y:0}, scale:1};
Visualization.built = false;
Visualization.force = null;
Visualization.data = {nodes: null, links: null, groups: null};
Visualization.nodesEnter = null;
Visualization.linksEnter = null;
Visualization.dimensions = {width: null, height: null, padding: null};
Visualization.layout = {grid: {width: null, height: null}};
Visualization.interaction = {zoom:true, pan:true, drag:true, edit:false};
var G = Visualization.geometry = protoql.Geometry(Visualization);
var N = Visualization.notation = protoql.Notation(Visualization);
/***************************************************************************
** Routines and methods.
*/
var lineFunction =
d3.svg
.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; })
.interpolate("basis");
// Resolve collisions between nodes.
var collision =
(function(alpha) {
var padding = 6;
var maxRadius = 7;
var quadtree = d3.geom.quadtree(nodes);
return function(d) {
var r = d.r + maxRadius + padding,
nx1 = d.x - r, nx2 = d.x + r,
ny1 = d.y - r, ny2 = d.y + r;
quadtree.visit(function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== d)) {
var x = d.x - quad.point.x, y = d.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = d.r + quad.point.r + (d.color !== quad.point.color) * padding;
if (l < r) {
l = (l - r) / l * alpha;
d.x -= x *= l;
d.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
});
};
});
var alignment =
(function(alpha) {
return function(d) {
d.cx = Math.floor(d.x - (d.x % V.layout.grid.width)+(V.layout.grid.width*0.5));
d.x += (d.cx - d.x) * alpha;
d.cy = Math.floor(d.y - (d.y % V.layout.grid.height)+(V.layout.grid.height*0.5));
d.y += (d.cy - d.y) * alpha;
};
});
var tick =
(function(e) {
V.nodesEnter
.each(alignment(0.8 * e.alpha))
//.each(collision(.5))
.attr("transform", function (d) { return "translate("+(d.x + d.offx)+","+(d.y + d.offy)+")"; });
V.linksEnter
.attr("d", function (e) {
var s = G.onEdge(e, 'source'), t = G.onEdge(e, 'target'),
points = null, lbl = [e.source, e.target, 15];
if (G.inShape(t, e.source) || G.inShape(s, e.target)) {
var orient = (e.source == e.target) ? -1 : 1,
es = e.source, et = e.target,
d = G.diff(e.source, e.target),
l = G.length(d),
m = Math.abs(G.maxRadiusToOutside(e.source, e.target)),
kx = (l < 2) ? m + 9 : d.x * Math.min(1.3*m, 1.5*(m/(l+1))), ky = (l < 2) ? m + 9 : d.y * Math.min(1.3*m, 1.5*(m/(l+1))),
p = {x:es.x + 1.3*ky, y:es.y - kx}, q = {x:et.x + (orient*(0.9)*ky), y:et.y - kx},
s = G.onEdge({source:es, target:p}, 'source'), t = G.onEdge({source:q, target:et}, 'target');
points = [s, p, q, t];
lbl = [p,q,10];
} else if (e.curved == true) {
var off = G.scale(5, G.orth(s, t)), s = G.onEdge(e, 'source', off), t = G.onEdge(e, 'target', off);
points = [s, G.offpath(s, t, 5), t];
} else {
points = [s, t];
}
// Position the edge label.
var t = V.zoompan.translate, s = V.zoompan.scale,
o = G.sum(G.offpath(G.scale(s, lbl[0]), G.scale(s, lbl[1]), lbl[2]*s), t);
e.labelText.attr("transform", function (d) { return "translate("+o.x+","+o.y+") scale(" + s + ")"; });
return lineFunction(points);
});
});
var textToSpans =
(function(d) {
var lines = d.text.split("`");
var dy = '13';
d.textElt.text('');
for (var i = 0; i < lines.length; i++) {
d.textElt.append('tspan').text(lines[i]).attr('x', 0).attr('dy', dy);
dy = '15';
}
});
var symmetricLinks =
(function(links) {
for (var i = 0; i < links.length; i++) {
for (var j = 0; j < i; j++) {
if ( links[i].source == links[j].target
&& links[j].source == links[i].target
&& links[i].source != links[i].target
&& links[j].source != links[j].target
) {
links[i].curved = true;
links[j].curved = true;
}
}
}
});
Visualization.height =
// Public method.
(function() {
return V.dimensions.height;
});
Visualization.build =
// Public method.
(function(value) {
var raw = null, data = null;
if (V.obj instanceof jQuery) {
raw = (value != null) ? value : obj.html();
obj.html("");
if (V.dimensions.width == null || V.dimensions.height == null)
V.dimensions = {width:V.obj.width(), height:V.obj.height(), padding:10};
} else {
raw = (value != null) ? value : obj.innerHTML;
obj.innerHTML = "";
if (V.dimensions.width == null || V.dimensions.height == null)
V.dimensions = {width:V.obj.clientWidth, height:V.obj.clientHeight, padding:10};
}
if (V.dimensions.width == null || isNaN(V.dimensions.width) || V.dimensions.width == 0)
V.dimensions.width = 600;
if (V.dimensions.height == null || isNaN(V.dimensions.height) || V.dimensions.height == 0)
V.dimensions.height = 300;
if (V.notation.relation(raw)) {}
else if (V.notation.graph(raw)) {}
else if (V.notation.table(raw)) {}
else {
console.log("Representation not recognized.");
return;
}
symmetricLinks(V.data.links); // Mark symmetric pairs of links.
V.force =
d3.layout.force()
.nodes(V.data.nodes)
//.links(V.data.links) // Disabled to avoid inadvertent clustering after building.
.size([V.dimensions.width, V.dimensions.height])
.gravity(0).charge(0).linkStrength(0)
.on("tick", tick)
.start()
;
if (V.svg != null)
V.svg.remove();
V.svg =
d3.select('#' + id)
.append("svg")
.attr("width", "100%").attr("height", "100%")
.attr('viewBox', '0 0 ' + V.dimensions.width + ' ' + V.dimensions.height)
.attr('preserveAspectRatio', 'xMidYMid meet')
;
// If editing of the diagram notation is enabled.
if (V.interaction.edit) {
V.console =
d3.select('#' + id)
.append("textarea")
.attr("rows","4").attr("style", "width:"+(V.dimensions.width-6)+"px; margin:0px;")
.property("value", (raw.trim().charAt(0) == "#") ? raw.trim().substr(1) : raw.trim())
.each(function() { V.txt = this; })
;
document.getElementById(id).style.padding = '0px';
document.getElementById(id).style.height = 'auto';
}
var canvas = V.svg.append('rect').attr({'width':'100%', 'height':'100%'}).attr('fill-opacity', '0');
if (V.interaction.zoom)
canvas.call(
V.zoom
.on("zoom", function() {
var tr = d3.event.translate, sc = d3.event.scale;
V.zoompan = {translate:{x:tr[0], y:tr[1]},scale:sc};
V.vis.attr("transform", "translate(" + tr + ")" + " scale(" + sc + ")");
V.force.resume();
})
)
.on("dblclick.zoom", function() {
if (V.txt != null)
V.build(V.txt.value);
var edgeFade = 20, panZoom = 200;
V.linksEnter.each(function(e) { e.labelText.transition().duration(edgeFade).attr("opacity", 0); });
setTimeout(function() { // Wait for edges to fade out.
V.vis.transition().duration(panZoom).attr('transform', 'translate(0,0) scale(1)');
V.zoom.translate([0,0]).scale(1);
V.zoompan = {translate:{x:0, y:0},scale:1};
setTimeout(function() {V.linksEnter.each(function(e) {e.labelText.transition().duration(edgeFade).attr("opacity", 1);})}, panZoom);
}, edgeFade);
})
;
V.vis =
V.svg
.append('g')//.attr('transform', 'translate(250,250) scale(0.3)')
;
V.svg
.append('svg:defs')
.append('svg:marker')
.attr('id', 'end-arrow-' + V.divId) // Use separate namespaces for each diagram's arrow ends.
.attr('viewBox', '0 -5 10 10').attr('refX', 8)
.attr('markerWidth', 8).attr('markerHeight', 8).attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-5L10,0L0,5L2,0')/*.attr('stroke-width', '1px')*/.attr('fill', '#000000')
;
V.linksEnter =
V.vis.selectAll(".link")
.data(V.data.links).enter()
.append("path").attr("class", "link")
.style("stroke", "black")
.style("fill", "none")
//.style("marker-end", function(l) { return 'url(' + window.location.href + '#end-arrow-' + V.divId + ')'; })
.style("marker-end", function(l) { return 'url(#end-arrow-' + V.divId + ')'; })
.each(function(e) { // Add edge labels.
e.labelText =
V.svg
.append("text")
.text(function () { return e.label; })
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.style("cursor", "all-scroll")
;
})
;
V.nodesEnter =
V.vis.selectAll(".node")
.data(V.data.nodes).enter()
.append("g")
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.call((V.interaction.drag ? V.force.drag : function(){}))
;
V.nodesEnter.filter(function (d) {return d.shape == "rect";})
.append("rect")
.attr("class", "node_rect")
.attr("rx", function(d) { return d.rx; })
.attr("ry", function(d) { return d.ry; })
.attr("width", function(d) { return d.width; })
.attr("height", function(d) { return d.height; })
.style("fill", function(d) { return "#DADADA"; /*d.color*/; })
.style("stroke", "#4F4F4F")
.style("opacity", 0.8)
.style("cursor", "all-scroll")
;
V.nodesEnter.filter(function (d) {return d.shape == "circle";})
.append("circle")
.attr("class", "node_circle")
.attr("r", function(d) { return d.r; })
.style("stroke", "#4F4F4F")
.style("fill", function(d) { return "#DADADA"; /*d.color*/; })
.style("opacity", 0.8)
.style("cursor", "all-scroll")
;
V.nodesEnter
.append("text")
.text(function (d) { d.textElt = d3.select(this); return d.text; })
.each(textToSpans)
.attr("text-anchor", "middle")
.style("cursor", "all-scroll")
//.style("stroke", "white").style("fill", "white")
.each(function(d) {
var bbox = this.parentNode.getBBox();
d.width = Math.max(19, bbox.width);
d.height = Math.max(19, bbox.height);
})
;
V.vis.selectAll(".node_rect")
.attr("x", function(d) { return -0.5 * (d.width + V.dimensions.padding); })
.attr("y", function(d) { return -0.5 * V.dimensions.padding; })
.attr("width", function(d) { return d.width + V.dimensions.padding; })
.attr("height", function(d) { return d.height + V.dimensions.padding; })
.each(function(d) { d.offy = ((-1) * (d.height/2)); })
;
V.vis.selectAll(".node_circle")
.attr("cy", function(d) { return 0.5*this.parentNode.getBBox().height; })
.attr("r", function(d) { var bbox = this.parentNode.getBBox(); d.r = V.dimensions.padding-3+((Math.max(bbox.width, bbox.height))/2); return d.r; })
.each(function(d) { d.offy = ((-1) * (d.height/2)); })
;
V.built = true;
});
/***************************************************************************
** Initialization.
*/
Visualization.build();
return Visualization;
}); // /protoql.Visualization
})(typeof exports !== 'undefined' ? exports : (this.protoql = {}));
</script>
<style>.pql { display:inline-block; width:600px; height:400px; }</style>
</head>
<body style="padding:0px;" onload="protoql.Visualizations($('.pql'));">
<div class="pql" style="position:absolute; margin:-3px 0px 0px -8px; top:0px; bottom:10px; height:100%; width:100%;">
"""
suffix = """
</div>
</body>
</html>
"""
return prefix + raw + suffix
##eof |
#coding=utf-8
'''
更新节点的定位信息:Locate_UpdateDevPosition
request:
{
"user_id":"1", #设备所属的用户
"lat":33.1111111, #经度
"lon":108.1111111, #维度
"dev_id":1, #模块的id
"accuracy":100, #定位经度为100单位cm
"time_s":"2018-02-28 17:23:20.111" #定位时间
"power":100, #电量为百分数
"locate_method":"GPS" #定位方式为GPS
}
return:
{
"error":"SUCCESS"
}
'''
def main(data):
cip=data['client_ip']
par=data['params']
red=data['red']
dbconn=data['dbconn']
cur=data['dbcursor']
assert('lat' in par and 'lon' in par)
assert('dev_id' in par)
assert('power' in par)
assert('accuracy' in par)
assert('time_s' in par)
sql='''with new_locatedata as (
insert into locate_data (lat,lon,accuracy,dev_id,time_s,power,locate_method)
values(%(lat)s,%(lon)s,%(accuracy)s,%(dev_id)s,'%(time_s)s',%(power)s,'%(locate_method)s') returning locate_id)
update device set last_locate_id = (select locate_id from new_locatedata limit 1), power=%(power)s where dev_id=%(dev_id)s
'''%par
cur.execute(sql)
#row=cur.fetchone()
dbconn.commit()
res=dict(error='SUCCESS')
return res
|
# Dana jest tablica n liczb. Proszę zaproponować algorytm który stwierdza czy pewna liczba
# występuje w ciągu > (więcej niż) n/2 razy.
def leader(T):
count = 1
leader = T[0]
for i in range(1, len(T)):
if T[i] == leader:
count += 1
else:
if count > 0:
count -= 1
else:
leader = T[i]
count = 1
count = 0
for i in range(len(T)):
if T[i] == leader:
count += 1
if count > len(T) // 2:
return leader
return None
T = [2, 3, 2, 4, 5, 2, 2, 1, 5, 2, 2]
print(leader(T))
|
class DataDictException(Exception):
def __init__(self, message, data_dict=None, exc=None):
self._message = message
if data_dict is None:
data_dict = {}
formatted_data_dict = {}
for key, value in data_dict.items():
formatted_data_dict[str(key)] = str(value)
if exc is not None:
formatted_data_dict['exc'] = str(exc)
self._formatted_data_dict = formatted_data_dict
formatted_message = '{0}: {1}'.format(self._message,
str(formatted_data_dict).replace(': ', '=').replace('\'', '')[1:-1])
super().__init__(formatted_message)
|
def hello_request(data):
data['type'] = 'hello_request'
return data
def hello_response(data):
data['type'] = 'hello_reply'
return data
def goodbye(data):
data['type'] = 'goodbye'
return data
def ok():
return {'type': 'ok'}
def shout(data):
data['type'] = 'shout'
return data
def proto_welcome():
return {'type': 'welcome'}
def proto_page(uri, pubkey, guid, text, signature, nickname, PGPPubKey, email,
bitmessage, arbiter, notary, arbiter_description, sin):
data = {
'type': 'page',
'uri': uri,
'pubkey': pubkey,
'senderGUID': guid,
'text': text,
'nickname': nickname,
'PGPPubKey': PGPPubKey,
'email': email,
'bitmessage': bitmessage,
'arbiter': arbiter,
'notary': notary,
'arbiter_description': arbiter_description,
'sin': sin
}
return data
def query_page(guid):
data = {'type': 'query_page', 'findGUID': guid}
return data
def order(id, buyer, seller, state, text, escrows=None, tx=None):
if not escrows:
escrows = []
data = {
'type': 'order',
'order_id': id,
'buyer': buyer.encode('hex'),
'seller': seller.encode('hex'),
'escrows': escrows
}
# this is who signs
# this is who the review is about
# the signature
# the signature
if data.get('tex'):
data['tx'] = tx.encode('hex')
# some text
data['text'] = text
# some text
data['address'] = ''
data['state'] = state
# new -> accepted/rejected -> payed -> sent -> received
return data
def proto_listing(productTitle, productDescription, productPrice,
productQuantity, market_id, productShippingPrice,
productImageName, productImageData):
data = {
'productTitle': productTitle,
'productDescription': productDescription,
'productPrice': productPrice,
'productQuantity': productQuantity,
'market_id': market_id,
'productShippingPrice': productShippingPrice,
'productImageName': productImageName,
'productImageData': productImageData
}
return data
def proto_store(key, value, originalPublisherID, age):
data = {
'type': 'store',
'key': key,
'value': value,
'originalPublisherID': originalPublisherID,
'age': age
}
return data
def negotiate_pubkey(nickname, ident_pubkey):
data = {
'type': 'negotiate_pubkey',
'nickname': nickname,
'ident_pubkey': ident_pubkey.encode("hex")
}
return data
def proto_response_pubkey(nickname, pubkey, signature):
data = {
'type': "proto_response_pubkey",
'nickname': nickname,
'pubkey': pubkey.encode("hex"),
'signature': signature.encode("hex")
}
return data
|
# The new config inherits a base config to highlight the necessary modification
_base_ = '../cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco.py'
# We also need to change the num_classes in head to match the dataset's annotation
model = dict(
roi_head=dict(
bbox_head=[
dict(type='Shared2FCBBoxHead', num_classes=1),
dict(type='Shared2FCBBoxHead', num_classes=1),
dict(type='Shared2FCBBoxHead', num_classes=1)
],
mask_head=dict(num_classes=1)
)
)
# Modify dataset related settings
dataset_type = 'CocoDataset'
classes = ('nucleus',)
runner = dict(type='EpochBasedRunner', max_epochs=200)
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(
type='Normalize',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img']),
])
]
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='LoadAnnotations',
with_bbox=True,
with_mask=True,
poly2mask=False),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(
type='Normalize',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks'])
]
data = dict(
samples_per_gpu=1,
workers_per_gpu=1,
train=dict(
type='RepeatDataset',
times=3,
dataset=dict(
type='CocoDataset',
ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json',
img_prefix='/work/zchin31415/nucleus_data/all_train',
# classes=('tennis', )
pipeline=train_pipeline
),
classes=classes,
ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json',
img_prefix='/work/zchin31415/nucleus_data/all_train'),
val=dict(
type=dataset_type,
ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json',
img_prefix='/work/zchin31415/nucleus_data/all_train',
classes=classes),
test=dict(
type=dataset_type,
ann_file='/work/zchin31415/nucleus_data/annotations/instance_test.json',
img_prefix='/work/zchin31415/nucleus_data/test',
pipeline=test_pipeline,
classes=classes)
)
load_from = '/home/zchin31415/mmdet-nucleus-instance-segmentation/mmdetection/checkpoints/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco_20210706_225234-40773067.pth'
|
class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles=sorted(piles)
n=len(piles)
answer=0
for i in range(int(n/3),n, 2):
answer+=piles[i]
return answer
|
m: int; n: int; i: int; j: int
m = int(input("Qual a quantidade de linhas da matriz? "))
n = int(input("Qual a quantidade de colunas da matriz? "))
mat: [[int]] = [[0 for x in range(n)] for x in range(m)]
for i in range(0, m):
for j in range(0, n):
mat[i][j] = int(input(f"Elemento [{i},{j}]: "))
print("VALORES NEGATIVOS:")
for i in range(0, m):
for j in range(0, n):
if mat[i][j] < 0:
print(mat[i][j])
|
#MenuTitle: Change LayerColor to Purple
# -*- coding: utf-8 -*-
font = Glyphs.font
selectedLayers = font.selectedLayers
for thisLayer in selectedLayers:
thisGlyph = thisLayer.parent
thisGlyph.layers[font.selectedFontMaster.id].color = 8
|
# Line SPW setup for 17B-162 w/ rest frequencies
# SPW $: [Name, Restfreq, Num chans, Chans for uvcontsub]
# Notes for uvcontsub channels:
# - Avoid first and last 5% of channels in a SPW
# - Avoid -80 to -280 km/s for M33
# - Avoid -30 to 30 km/s for MW
# Channel offset b/w cubes made with test_line_imaging.py (excludes edge
# channels) and the full SPW (since we split from the full SPW):
# Halp - 7 channels
# OH - 13 channels
# HI - 205 channels
linespw_dict = {0: ["HI", "1.420405752GHz", 4096, "1240~1560;2820~3410"],
1: ["H166alp", "1.42473GHz", 128, "32~47;107~114"],
2: ["H164alp", "1.47734GHz", 128, "32~47;107~114"],
3: ["OH1612", "1.612231GHz", 256, "53~88;223~240"],
4: ["H158alp", "1.65154GHz", 128, "32~47;107~114"],
5: ["OH1665", "1.6654018GHz", 256, "53~88;223~240"],
6: ["OH1667", "1.667359GHz", 256, "53~88;223~240"],
7: ["OH1720", "1.72053GHz", 256, "53~88;223~240"],
8: ["H153alp", "1.81825GHz", 128, "32~47;107~114"],
9: ["H152alp", "1.85425GHz", 128, "32~47;107~114"]}
|
'''
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
'''
t=int(input())
for i in range(t):
n=int(input())
ans=1
while n>1:
ans*=n
n-=1
print(ans) |
VERSION = "0.1a"
class Port(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def __init__(self, portType):
self.portType = portType
return
def isType(self, _type):
if _type == self.portType:
return True
return False
class Component(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def setServices(self, services):
"""
input: services object.
output: void
"""
raise NotImplementedError("Abstract Class!")
class ComponentRelease(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def releaseServices(self, services):
"""
input: services object.
output: void
"""
raise NotImplementedError("Abstract Class!")
class ComponentID(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getInstanceName(self):
"""
input: none
output: a string identifier for the component (uuid?).
throws CCAException.
"""
raise NotImplementedError("Abstract Class!")
def getSerialization(self):
"""
input: none
output: a serialization of the object sufficient for saving the component's state to disk and restart at a different time.
throws CCAException.
"""
raise NotImplementedError("Abstract Class!")
class Services(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getComponentID(self):
"""
input: none
output: a ComponentID object
"""
raise NotImplementedError("Abstract Class!")
def createTypeMap(self):
"""
input: none
output: a TypeMap object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def registerUsesPort(self, portName, type, properties):
"""
input: string portName, string type, and TypeMap properties
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def unregisterUsesPort(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def addProvidesPort(self, inPort, portName, type, properties):
"""
input: Port inPort, string portName, string type, and TypeMap properties
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def removeProvidesPort(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getPortProperties(self, portName):
"""
input: string portName
output: a TypeMap object
"""
raise NotImplementedError("Abstract Class!")
def getPort(self, portName):
"""
input: string portName
output: a Port object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getPortNonblocking(self, portName):
"""
input: string portName
output: a Port object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def releasePort(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def registerForRelease(self, callback):
"""
input: a gov.cca.ComponentRelease object callback
output: void
"""
raise NotImplementedError("Abstract Class!")
class AbstractFramework(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def createTypeMap(self):
"""
input: none
output: a TypeMap object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def createEmptyFramework(self):
"""
input: none
output: a AbstractFramework object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getServices(self, selfInstanceName, selfClassName, selfProperties):
"""
input: a string selfInstanceName, string selfClassName, TypeMap selfProperties
output: a Services object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def releaseServices(self, services):
"""
input: a Services object
output: a AbstractFramework object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def shutdownFramework(self):
"""
input: none
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
class ComponentClassDescription(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getComponentClassName(self):
"""
input: none
output: a string
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
class ConnectionID(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getProvider(self):
"""
input: none
output: a ComponentID object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getUser(self):
"""
input: none
output: a ComponentID object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getProviderPortName(self):
"""
input: none
output: a string
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getUserPortName(self):
"""
input: none
output: a string
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
class Type(object):
none, Int, Long, Float, Double, Fcomplex, Dcomplex, String, Bool, IntArray, LongArray, FloatArray, DoubleArray, FcomplexArray, DComplexArray, StringArray, BoolArray = range(17)
def __init__(self):
raise NotImplementedError("Enumeration!")
class TypeMap(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getInt(self, key, dflt):
"""
input: string key, integer dflt
output: a integer
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getLong(self, key, dflt):
"""
input: string key, long dflt
output: a long
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getFloat(self, key, dflt):
"""
input: string key, float dflt
output: a float
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getDouble(self, key, dflt):
"""
input: string key, double dflt
output: a double
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getFcomplex(self, key, dflt):
"""
input: string key, fcomplex dflt
output: a fcomplex
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getDcomplex(self, key, dflt):
"""
input: string key, dcomplex dflt
output: a dcomplex
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getString(self, key, dflt):
"""
input: string key, string dflt
output: a integer
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getBool(self, key, dflt):
"""
input: string key, bool dflt
output: a boolean
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getIntArray(self, key, dflt):
"""
input: string key, int dflt
output: a list of int
"""
raise NotImplementedError("Abstract Class!")
def getLongArray(self, key, dflt):
"""
input: string key, long dflt
output: a list of long
"""
raise NotImplementedError("Abstract Class!")
def getFloatArray(self, key, dflt):
"""
input: string key, float dflt
output: a list of float
"""
raise NotImplementedError("Abstract Class!")
def getDoubleArray(self, key, dflt):
"""
input: string key, double dflt
output: a list of double
"""
raise NotImplementedError("Abstract Class!")
def getFcomplexArray(self, key, dflt):
"""
input: string key, fcomplex dflt
output: a list of fcomplex
"""
raise NotImplementedError("Abstract Class!")
def getDcomplexArray(self, key, dflt):
"""
input: string key, dcomplex dflt
output: a list of dcomplex
"""
raise NotImplementedError("Abstract Class!")
def getStringArray(self, key, dflt):
"""
input: string key, string dflt
output: a list of string
"""
raise NotImplementedError("Abstract Class!")
def getBoolArray(self, key, dflt):
"""
input: string key, bool dflt
output: a list of bool
"""
raise NotImplementedError("Abstract Class!")
def putInt(self, key, value):
"""
input: string key, integer value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putLong(self, key, value):
"""
input: string key, long value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putFloat(self, key, value):
"""
input: string key, float value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putDouble(self, key, value):
"""
input: string key, double value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putFcomplex(self, key, value):
"""
input: string key, fcomplex value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putDcomplex(self, key, value):
"""
input: string key, dcomplex value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putString(self, key, value):
"""
input: string key, string value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putBool(self, key, value):
"""
input: string key, bool value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putIntArray(self, key, value):
"""
input: string key, int list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putLongArray(self, key, value):
"""
input: string key, long list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putFloatArray(self, key, value):
"""
input: string key, float list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putDoubleArray(self, key, value):
"""
input: string key, double list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putFcomplexArray(self, key, value):
"""
input: string key, fcomplex list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putDcomplexArray(self, key, value):
"""
input: string key, dcomplex list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putStringArray(self, key, value):
"""
input: string key, string list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putBoolArray(self, key, value):
"""
input: string key, bool list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def cloneTypeMap(self):
"""
input: none
output: a TypeMap object
"""
raise NotImplementedError("Abstract Class!")
def cloneEmpty(self):
"""
input: none
output: a TypeMap object
"""
raise NotImplementedError("Abstract Class!")
def remove(self, key):
"""
input: a string key
output: void
"""
raise NotImplementedError("Abstract Class!")
def getAllKeys(self, t):
"""
input: Type object t
output: a list of strings
"""
raise NotImplementedError("Abstract Class!")
def hasKey(self, key):
"""
input: a string key
output: boolean
"""
raise NotImplementedError("Abstract Class!")
def typeOf(self, key):
"""
input: a string key
output: a Type object
"""
raise NotImplementedError("Abstract Class!")
class CCAExceptionType(object):
Unexpected = -1
Nonstandard = 1
PortNotDefined = 2
PortAlreadyDefined = 3
PortNotConnected = 4
PortNotInUse = 5
UsesPortNotReleased = 6
BadPortName = 7
BadPortType = 8
BadProperties = 9
BadPortInfo = 10
OutOfMemory = 11
NetworkError = 12
def __init__(self):
raise NotImplementedError("Enumeration!")
class CCAException(Exception):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getCCAExceptionType(self):
"""
input: none
output: a CCAException object
"""
raise NotImplementedError("Abstract Class!")
def setCCAExceptionType(self, exceptionType):
"""
input: a field from CCAExceptionType
output: a CCAException object
"""
raise NotImplementedError("Abstract Class!")
|
# -*- coding: utf-8 -*-
# Questo è l'elenco di tutte le stringhe usate in Royal Mifia.
# Modificando qui si dovrebbe riuscire a tradurre il gioco e rendere la modifica più semplice.
# Royal: icona
royal_icon = "\U0001F610"
# Royal: nome ruolo
royal_name = "Royal"
# Mifioso: icona
mifia_icon = "\U0001F47F"
# Mifioso: nome ruolo
mifia_name = "Mifioso"
# Mifioso: bersaglio selezionato
mifia_target_selected = "Hai selezionato come bersaglio @{target}."
# Mifioso: bersaglio ucciso
mifia_target_killed = "@{target} è stato ucciso dalla Mifia.\n" \
"Era un *{icon} {role}*."
# Mifioso: bersaglio protetto da un angelo
mifia_target_protected = "@{target} è stato protetto dalla Mifia da {icon} @{protectedby}!"
# Mifioso: descrizione del potere
mifia_power_description = "Puoi selezionare come bersaglio di un'assassinio una persona.\n" \
"Per selezionare un bersaglio, scrivi in questa chat:\n" \
"`/power {gamename} nomeutentebersaglio`\n" \
"Alla fine del giorno, tutti i bersagli dei Mifiosi saranno eliminati!\n"
# Mifioso: uccisione fallita
mifia_target_missed = "@{target} ha subito un tentativo di assassinio da parte della Mifia!\n" \
"Per fortuna, è riuscito a evitare l'attacco."
# Investigatore: icona
detective_icon = "\U0001F575"
# Investigatore: nome ruolo
detective_name = "Investigatore"
# Investigatore: scoperta nuove informazioni
detective_discovery = "Sei sicuro al *{target_score}%* che @{target} sia un *{icon} {role}*."
# Investigatore: descrizione del potere
detective_power_description = "Puoi provare a scoprire il ruolo di una persona ogni giorno.\n" \
"Non è garantito che l'investigazione abbia successo, ma la probabilità è piuttosto alta e ti verrà annunciata.\n" \
"Per indagare su qualcuno, scrivi in questa chat:\n" \
"`/power {gamename} nomeutentebersaglio`\n"
# Angelo: icona
angel_icon = "\U0001F607"
# Angelo: nome ruolo
angel_name = "Angelo"
# Angelo: bersaglio selezionato
angel_target_selected = "Hai selezionato come protetto @{target}."
# Angelo: descrizione del potere
angel_power_description = "Puoi proteggere una persona dalla Mifia ogni notte.\n" \
"Se questa persona verrà attaccata, rimarrà viva, e il tuo ruolo sarà scoperto.\n" \
"Per proteggere una persona, scrivi in questa chat:\n" \
"`/power {gamename} nomeutentebersaglio`\n"
# Terrorista: icona
terrorist_icon = "\U0001F60E"
# Terrorista: nome ruolo
terrorist_name = "Terrorista"
# Terrorista: descrizione del potere
terrorist_power_description = "Puoi fare saltare in aria un sacco di persone!\n" \
"Se vieni votato come colpevole di associazione mifiosa, potrai fare esplodere tutti" \
" quelli che ti hanno votato!\n" \
"La mifia non sa chi sei, ma fai parte della squadra dei malvagi.\n"
# Terrorista: esplosione
terrorist_kaboom = "\U0001F4A3 *Boom!* Il terrorista si è fatto esplodere prima che poteste ucciderlo, mietendo vittime tra tutti" \
" quelli che lo hanno votato!"
# Terrorista: bersaglio ucciso
terrorist_target_killed = "\U0001F4A3 *Boom!* @{target} è morto a causa dell'esplosione!\n" \
"Era un *{icon} {role}*."
# Derek: icona
derek_icon = "\U0001F635"
# Derek: nome ruolo
derek_name = "Derek"
# Derek: descrizione del potere
derek_power_description = "Puoi decidere di suicidarti alla fine di un round.\n" \
"Potresti farlo per confondere le idee ai Royal, o per ragequittare con stile.\n" \
"Sta a te la scelta.\n" \
"Per lasciare questo mondo alla fine del giorno, scrivi in questa chat:\n" \
"`/power {gamename} banana`\n"
# Derek: morte attivata
derek_deathwish_set = "*Morirai* alla fine di questo giorno."
# Derek: morte disattivata
derek_deathwish_unset = "*Vivrai* per morire un altro giorno."
# Derek: morte
derek_deathwish_successful = "*SPOILER:* alla fine di questo giorno *\U0001F635 Derek Shepard* (@{name}) è morto schiacciato da un container durante una missione su Ilium.\n"
# Disastro: icona
disaster_icon = "\U0001F46E"
# Disastro: nome ruolo
disaster_name = "Carabiniere"
# Mamma: icona
mom_icon = "\U0001F917"
# Mamma: nome ruolo
mom_name = "Mamma"
# Mamma: descrizione del potere
mom_power_description = "Durante la partita scoprirai i ruoli di alcuni giocatori.\n" \
"A differenza dell'Investigatore, sei infallibile.\n"
# Mamma: scoperta di un ruolo
mom_discovery = "Hai scoperto che @{target} è un *{icon} {role}*.\n" \
# Stagista: icona
intern_icon = "\U0001F913"
# Stagista: nome ruolo
intern_name = "Stagista"
# Stagista: descrizione del potere
intern_power_description = "In qualsiasi momento della partita puoi scegliere un altro giocatore.\n" \
"Il tuo ruolo diventerà uguale al suo.\n" \
"Ricordati che, qualsiasi cosa succeda, è sempre colpa dello stagista, cioè tua!\n" \
"Per andare in stage, scrivi in questa chat:\n" \
"`/power {gamename} nomeutentedatoredilavoro`"
# Stagista: inizia lo stage
intern_started_internship = "Andrai in stage da @{master}."
# Stagista: cambiato ruolo
intern_changed_role = "Lo stagista ha finito il tirocinio ed ha imparato i segreti del mestiere di *{icon} {role}*."
# Stagista: EVOCATO IL SIGNORE DEL CAOS
intern_chaos_summoned = "Il *\U0001F479 Signore del Caos* e il suo fedele servitore sono scesi sulla Terra.\n" \
"Preparatevi... a non capirci più niente."
# Corrotto: icona
corrupt_icon = "\U0001F482"
# Corrotto: nome ruolo
corrupt_name = "Corrotto"
# Corrotto: descrizione potere
corrupt_power_description = "Puoi indagare sul vero ruolo di una persona una volta al giorno.\n" \
"Per indagare su qualcuno, scrivi in questa chat:\n" \
"`/power {gamename} nomeutentebersaglio`\n" \
"Sei praticamente un Investigatore, solo che lavori per la Mifia!\n"
# Signore del Caos: icona
chaos_lord_icon = "\U0001F479"
# Signore del Caos: nome ruolo
chaos_lord_name = "Signore del Caos"
# Signore del Caos: descrizione del potere
chaos_lord_power_description = "Sei il *SIGNORE DEL CAOS*!\n" \
"Le faccende dei mortali non ti interessano, quindi non fai parte nè del team Mifia nè del team Royal.\n" \
"Di conseguenza, hai automaticamente _vinto la partita_!\n" \
"Puoi usare i tuoi poteri del Caos per cambiare ruolo a un altro giocatore.\n" \
"Il ruolo che riceverà sarà casuale.\n" \
"Per usare i tuoi poteri, scrivi in questa chat:\n" \
"`/power {gamename} nomeutentebersaglio`"
# Signore del Caos: bersaglio selezionato
chaos_lord_target_selected = "BWHAHAHA. Hai deciso di usare i tuoi poteri del Caos su @{target}."
# Signore del Caos: bersaglio randomizzato
chaos_lord_randomized = "Il Caos è nell'aria...\n" \
"*Qualcuno ha cambiato ruolo!*"
# Signore del Caos: randomizzazione fallita
chaos_lord_failed = "Il Caos è nell'aria...\n" \
"_Ma non è successo nulla!?_"
# Servitore del Caos: nome ruolo
chaos_servant_name = "Servitore del Caos"
# Servitore del Caos: icona
chaos_servant_icon = "\U0001F468\u200d\U0001F3A4"
# Servitore del Caos: descrizione potere
chaos_servant_power_description = "Il Signore del Caos ti cederà i suoi poteri quando sarà morto.\n" \
"Facendo parte della fazione del Caos, hai automaticamente _vinto la partita_!"
# Vigilante: nome ruolo
vigilante_name = "Vigilante"
# Vigilante: icona
vigilante_icon = "🤠"
# Vigilante: descrizione potere
vigilante_power_description = "Puoi scegliere una persona da uccidere anonimamente alla fine della giornata.\n" \
"Fai attenzione a non uccidere un tuo alleato Royal: sei in squadra con loro!\n" \
"Per uccidere qualcuno, scrivi in questa chat:\n" \
"`/power {gamename} nomeutentebersaglio`"
# Vigilante: bersaglio scelto
vigilante_target_selected = "Stai puntando la tua pistola contro @{target}."
# Vigilante: esecuzione
vigilante_execution = "@{target} è stato eseguito da un Vigilante della Royal Games.\n" \
"Era un *{icon} {role}*."
# Servitore del Caos: ereditato i poteri
chaos_servant_inherited = "Il servitore ha ereditato i poteri del *\U0001F479 Signore del Caos*."
# Generale: ruolo assegnato
role_assigned = "Ti è stato assegnato il ruolo di *{icon} {name}*."
# Generale: giocatore ucciso dalle votazioni
player_lynched = "@{name} era il più votato ed è stato ucciso dai Royal.\n" \
"Era un *{icon} {role}*."
# Generale: nessun voto, nessun giocatore ucciso
no_players_lynched = "La Royal Games non è giunta a una decisione in questo giorno e non ha ucciso nessuno."
# Generale: partita creata
new_game = "E' stata creata una nuova partita in questo gruppo.\n" \
"*Nome:* {name}"
# Generale: un giocatore si è unito
player_joined = "@{name} si è unito alla partita!\n" \
"Adesso ci sono {players} giocatori in partita."
# Generale: ti sei unito alla partita, in chat privata
you_joined = "Ti sei unito alla partita _{game}_!\n" \
"Il ruolo ti verrà assegnato appena @{adminname} chiuderà le iscrizioni."
# Generale: fine della fase di join
join_phase_ended = "La fase di join è terminata."
# Generale: ruoli assegnati correttamente
roles_assigned_successfully = "I ruoli sono stati assegnati.\n" \
"Controlla la chat privata con @mifiabot per vedere il tuo."
# Generale: comunica ai mifiosi i loro compagni di squadra
mifia_team_intro = "I mifiosi in questa partita sono:\n"
# Generale: formattazione elenco mifiosi (deve terminare con \n)
mifia_team_player = "{icon} @{name}\n"
# Generale: votazione completata
vote = "@{voting} ha votato per uccidere @{voted}."
# Generale: votazione annullata
vote_none = "{player} ha annullato il suo voto."
# Generale: votazione completata in prima persona
vote_fp = "Hai votato per uccidere @{voted}."
# Generale: votazione annullata in prima persona
vote_none_fp = "Hai annullato il tuo voto."
# Generale: un admin ha ucciso un giocatore con /kill
admin_killed = "{name} è morto _di infarto_.\n" \
"Era un *{icon} {role}*."
# Generale: inviato messaggio in chat privata
check_private = "Messaggio inviato in chat privata.\n" \
"Controlla @mifiabot."
# Generale: partita salvata
game_saved = "Partita _{name}_ salvata su file."
# Generale: partita caricata
game_loaded = "Partita caricata da file."
# Generale: partita terminata remotamente dal proprietario del bot
owner_ended = "Il proprietario del bot ha eliminato questa partita."
# Vittoria: Mifia >= Royal
end_mifia_outnumber = "I Mifiosi rimasti sono più dei Royal.\n" \
"La Mifia ha preso il controllo della città.\n"
# Vittoria: Mifia == 0
end_mifia_killed = "Tutti i Mifiosi sono stati eliminati.\n"
# Vittoria: nessuno vivo lol
end_game_wiped = "Nessuno è più vivo. La specie umana si è estinta.\n"
# Vittoria: Sei un Signore del Caos.
end_game_chaos = "Sei un Signore del Caos."
# Generale: scegli per chi votare
vote_keyboard = "Scegli chi vuoi linciare!\n" \
"Se più giocatori hanno lo stesso numero di voti, uno tra loro verrà selezionato per essere linciato.\n" \
"Se nessuno ha votato, "
# Generale: riga della tastiera del voto
vote_keyboard_line = "{status} {votes} - {player}"
# Generale: riga della tastiera per annullare il voto
vote_keyboard_nobody = "\u2796 Nessuno"
# Generale: inizia un nuovo giorno
new_day = "Sorge l'alba del giorno *{day}*!"
# Vittoria: team Royal
victory_royal = "*La Royal Games vince!*"
# Vittoria: team Mifia
victory_mifia = "*La Mifia vince!*"
# Vittoria!
victory = "*Hai vinto!*"
# Sconfitta.
defeat = "*Hai perso...*"
# Pareggio?
tie = "*Pareggio?*"
# Status: parte aggiunta prima dell'elenco dei giocatori (deve terminare con \n)
status_header = "*Nome:* {name}\n" \
"*Creatore:* {admin}\n" \
"*Fase:* {phase}\n" \
"*Giocatori partecipanti:*\n"
# Status: parte aggiunta prima della rivelazione finale dei ruoli
status_final_header = "*Ruoli della partita {name}:*\n"
# Status: giocatore vivo durante la prima giornata / fase di join (deve terminare con \n)
status_basic_player = "{icon} {player}\n"
# Status: risultati finali della partita
# Status: giocatore vivo (deve terminare con \n)
status_alive_player = "{icon} {player} __(vota per {target})__\n"
# Status: giocatore morto (deve terminare con \n)
status_dead_player = "\U0001F480 {player}\n"
# Status: giocatore più votato della partita
status_most_voted = "\U0001F534"
# Status: voti giocatore normali
status_normal_voted = "\u26AA"
# Status: Modalità debug
debug_mode = "*DEBUG/CHEATS MODE*\n"
# Ping!
pong = "Pong!"
# Attenzione: il bot non è amministratore
warning_bot_not_admin = "\U000026A0 Attenzione! Il bot non è amministratore in questo supergruppo.\n" \
"E' possibile comunque giocare una partita, ma alcune funzioni non saranno disponibili."
# Errore: nome utente inesistente
error_username = "\U000026A0 Il nome utente specificato non esiste."
# Errore: usi del potere esauriti
error_no_uses = "\U000026A0 Hai finito gli utilizzi del tuo potere."
# Errore: numero troppo basso di giocatori
error_not_enough_players = "\U000026A0 Non ci sono abbastanza giocatori per avviare la partita."
# Errore: partita già in corso nel gruppo
error_game_in_progress = "\U000026A0 In questo gruppo è già in corso una partita."
# Errore: tipo di chat non supportato
error_chat_type = "\U000026A0 Non puoi creare una partita in questo tipo di chat."
# Errore: per usare questo comando, devi scrivere in chat privata
error_private_required = "\U000026A0 Non puoi usare questo comando in un gruppo.\n" \
"Scrivimi in chat privata a @mifiabot."
# Errore: giocatore già presente nella partita.
error_player_already_joined = "\U000026A0 Ti sei già unito alla partita."
# Errore: nessuna partita trovata
error_no_games_found = "\U000026A0 Non è stata trovata una partita su cui usare il comando."
# Errore: sei morto
error_dead = "\U000026A0 Sei morto."
# Errore: il bersaglio è morto
error_target_is_dead = "\U000026A0 Non puoi bersagliare giocatori morti."
# Errore: azione riservata agli admin
error_not_admin = "\U000026A0 Questa azione è riservata al creatore della partita."
# Errore: azione riservata al proprietario
error_not_owner = "\U000026A0 Questa azione è riservata al proprietario del bot."
# Errore: non sei nella partita
error_not_in_game = "\U000026A0 Non fai parte della partita in corso."
# Errore: fase di join finita
error_join_phase_ended = "\U000026A0 La fase di unione è finita."
# Errore: non puoi usare il potere su te stesso
error_no_selfpower = "\U000026A0 Non puoi usare il potere su te stesso."
# Errore: parametro della configurazione non valido
error_invalid_config = "\U000026A0 Configurazione non valida."
# Errore: il giocatore non ha mai scritto un messaggio in chat privata al bot
error_chat_unavailable = "\U000026A0 Non hai mai scritto un messaggio in chat privata a @mifiabot!\n" \
"Scrivigli nella chat privata `/start` e riprova."
# Erorre: nessun username
error_no_username = "\U000026A0 Non hai nessun username di Telegram!\n" \
"Vai nelle impostazioni e inseriscine uno!"
# Errore: non si può votare nella prima giornata
error_no_votes_on_first_day = "\U000026A0 I Royal non votano nella prima giornata, dato che non si sono ancora verificati omicidii."
# Errore: mancano dei parametri nel comando
error_missing_parameters = "\U000026A0 Mancano uno o più parametri.\n" \
"Controlla la sintassi del comando e riprova."
# Critico: Server di telegram Timed Out
fatal_bot_timed_out = "\U0001F6D1 **Errore critico:** I server di Telegram non hanno risposto in tempo al messaggio.\n" \
"Se una partita era in corso, potrebbero essersi creati dei bug.\n" \
"E' consigliato cancellarla e ricaricare l'ultimo salvataggio disponibile."
# Critico: Rate limited
fatal_bot_rate_limited = "\U0001F6D1 **Errore critico:** Il bot ha inviato troppe richieste a Telegram ed è stato bloccato.\n" \
"Se una partita era in corso, potrebbero essersi creati dei bug.\n" \
"E' consigliato attendere 5 minuti, cancellarla e ricaricare l'ultimo salvataggio disponibile."
# Lista dei possibili nomi di una partita
if __debug__:
names_list = ["Dev"]
else:
names_list = ["Tredici"]
# Scegli il preset
preset_choose = "*Seleziona un preset per la partita:*"
# Preset semplice
preset_simple = "Semplice"
# Preset semplice selezionato
preset_simple_selected = "Selezionato il preset *Semplice*.\n" \
"In partita saranno presenti:\n" \
"*{mifioso}* Mifiosi,\n" \
"*{investigatore}* Investigatori\n" \
"e *{royal}* Royal."
# Preset classico
preset_classic = "Classico"
# Preset classico selezionato
preset_classic_selected = "Selezionato il preset *Classico*.\n" \
"In questa partita saranno presenti:\n" \
"*{mifioso}* Mifiosi,\n" \
"*{investigatore}* Investigatori,\n" \
"*{angelo}* Angeli,\n" \
"*forse* un Terrorista \n" \
"e *{royalmenouno}* o *{royal}* Royal.\n" \
# Preset avanzato
preset_advanced = "Avanzato"
# Preset avanzato selezionato
preset_advanced_selected = "Selezionato il preset *Avanzato*.\n" \
"I ruoli in questa partita sono casuali!\n" \
"Inoltre, ogni mifioso può uccidere una persona diversa ogni giorno...\n"
# Partita in cui i Mifiosi hanno un grande vantaggio (<-30)
balance_mifia_big = "_La mifia ha un grande vantaggio in questa partita.\n" \
"Buona fortuna, Royal Games, ne avrete bisogno!_"
# Partita in cui i Royal hanno un grande vantaggio (>+30)
balance_royal_big = "_La Royal Games ha un grande vantaggio in questa partita.\n" \
"State attenti, Mifiosi!_"
# Partita in cui i Mifiosi hanno un leggero vantaggio (>-30)
balance_mifia_small = "_La mifia è leggermente avvantaggiata in questa partita._"
# Partita in cui i Royal hanno un leggero vantaggio (<+30)
balance_royal_small = "_La Royal Games è leggermente avvantaggiata in questa partita._"
# Partita bilanciata (-5<x<5)
balance_perfect = "_La partita sembra bilanciata per entrambe le squadre, nessuno sembra avere un grosso vantaggio.\n" \
"Buona fortuna a tutti!_"
# Preset con uno di tutti
preset_oneofall = "Round Robin"
# Preset con uno di tutti selezionato
preset_oneofall_selected = "Selezionato il preset *Round Robin*.\n" \
"In questa partita saranno presenti lo stesso numero di tutti i ruoli.\n" \
"Se sono presenti giocatori in eccesso, verrà assegnato loro un ruolo casuale."
# Preset selezionato
preset_selected = "Preset selezionato: {selected}"
# Nome gruppo
group_name = "{phase} - Mifia {name}"
# Giorno
day = "Day {day}"
|
number = int(input())
dp = []
dp.append([0, 1])
for n in range(1, number):
dp.append([])
dp[n].append(sum(dp[n-1])) # 0
dp[n].append(dp[n-1][0]) # 1
print(sum(dp[number-1]))
|
#!/usr/bin/env python3
with open('challenge67_data.txt', 'r') as f:
triangle = [[int(i) for i in l.split(' ')] for l in f.readlines()]
longest_paths = [[0] * (i+1) for i in range(len(triangle))]
# edges between x and x + 1
# Algorithm:
# Start at top
# Go to each branch, make note of the longest path to get to that point
# find the longest path in the bottom row
longest_paths[0][0] = triangle[0][0]
# now, each location has up to 2 sources (x and/or x-1, y-1)
# we can set the cost to arrive at each location the greater of the source + that locations cost
for y, row in enumerate(triangle):
if y == 0:
continue
for x, n in enumerate(row):
total_cost1 = 0
total_cost2 = 0
total_cost1 = n + longest_paths[y-1][x-1]
try:
total_cost2 = n + longest_paths[y-1][x]
except IndexError:
pass
longest_paths[y][x] = max(total_cost1, total_cost2)
# print('\n'.join([str(l) for l in longest_paths]))
print(max(longest_paths[-1]))
|
media_filter_parameter_schema = [
{
'name': 'media_id',
'in': 'query',
'required': False,
'description': 'List of integers identifying media.',
'explode': False,
'schema': {
'type': 'array',
'items': {
'type': 'integer',
'minimum': 1,
},
},
},
{
'name': 'type',
'in': 'query',
'required': False,
'description': 'Unique integer identifying media type.',
'schema': {'type': 'integer'},
},
{
'name': 'name',
'in': 'query',
'required': False,
'description': 'Name of the media to filter on.',
'schema': {'type': 'string'},
},
{
'name': 'section',
'in': 'query',
'required': False,
'description': 'Unique integer identifying a media section.',
'schema': {'type': 'integer'},
},
{
'name': 'dtype',
'in': 'query',
'required': False,
'description': 'Data type of the files, either image or video.',
'schema': {'type': 'string', 'enum': ['image', 'video', 'multi']},
},
{
'name': 'md5',
'in': 'query',
'required': False,
'description': 'MD5 sum of the media file.',
'schema': {'type': 'string'},
},
{
'name': 'gid',
'in': 'query',
'required': False,
'description': 'Upload group ID of the media file.',
'schema': {'type': 'string'},
},
{
'name': 'uid',
'in': 'query',
'required': False,
'description': 'Upload unique ID of the media file.',
'schema': {'type': 'string'},
},
{
'name': 'after',
'in': 'query',
'required': False,
'description': 'If given, all results returned will be after the '
'file with this filename. The `start` and `stop` '
'parameters are relative to this modified range.',
'schema': {'type': 'string'},
},
{
"name": "archive_lifecycle",
"in": "query",
"required": False,
"description": ("Archive lifecycle of the files, one of live (live only), archived "
"(to_archive, archived, or to_live), or all. Defaults to 'live'"),
"schema": {"type": "string", "enum": ["live", "archived", "all"]},
},
{
'name': 'annotation_search',
'in': 'query',
'required': False,
'description': 'Lucene query syntax string for use with Elasticsearch. '
'See <a href=https://www.elastic.co/guide/en/elasticsearch/'
'reference/7.10/query-dsl-query-string-query.html#query-string-syntax>reference</a>. '
'This search is applied to child annotations of media only.',
'schema': {'type': 'string'},
},
]
|
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
nLen = len(nums) - 1
nums.sort()
fidx = nLen // 2
sidx = nLen // 2 + 1
swapIdx = 0
while swapIdx < nLen - 1:
nums[swapIdx], nums[fidx] = nums[fidx], nums[swapIdx]
swapIdx += 1
fidx += 1
nums[swapIdx], nums[sidx] = nums[sidx], nums[swapIdx]
swapIdx += 1
sidx += 1
|
class Request:
def __init__(self,number, time):
self.number = number
self.time = time
|
# abrir y leer archivo
f = open ('input.txt','r')
mensaje = f.read()
f.close()
# divido por linea y guardo en una lista
list_sits = mensaje.split('\n')
def extractRow(row,ini,end):
ini = ini
end = end
distance = end - ini
current = list(row)
for i in current:
distance = int(distance/2)
if(i=="F"):
end = ini + distance
elif(i=="B"):
ini = end - distance
return ini
def extractColumn(column,ini,end):
ini = ini
end = end
distance = end - ini
current = list(column)
for i in current:
distance = int(distance/2)
if(i=="L"):
end = ini + distance
elif(i=="R"):
ini = end - distance
return ini
higher_seat_id = 0
for i in list_sits:
row = extractRow(i[:-3],0,127)
column = extractColumn(i[-3:],0,7)
seat_id = row * 8 + column
if(higher_seat_id<=seat_id):
higher_seat_id = seat_id
print(higher_seat_id) |
"""
[2015-12-09] Challenge #244 [Intermediate] Higher order functions Array language (part 2)
https://www.reddit.com/r/dailyprogrammer/comments/3w324a/20151209_challenge_244_intermediate_higher_order/
Monday's challenge is a prerequisite. Sorry.
# J theory
Adverbs and Conjunctions in J (modifiers as a shorter group name) are primarily used to implement higher order
functions.
An adverb takes 1 parameter (that may be a function ) and may return a function (for today, assume it can only return a
function). Adverb parameter name is u.
A conjunction takes 2 parameters and may (does today) return a function. Conjunction parameter names are u and v.
From Monday, the function parameters in our array language all have 2 parameters x and y.
In J, adverbs appear to the right of their u function parameter, and x ( if not missing) and y appear to the left and
right of the group (called verb phase). More adverbs and conjunctions can appear to the right of the verb phrase, and
the evaluation order inside a verb phrase is left to right. ie. function returned by first adverb, is an input the to
next adverb on its right.
In J, Conjunctions have their u parameter (can be a verb phrase without parentheses) on the left, and their v parameter
on the right. If v is not parenthesized, then only one token (function or array or variable) is the v conjunction
parameter. More adverbs and conjunctions can be added to the right of the verb phrase.
You can use your language's natural parsing rules instead.
# 1. an insert adverb
This is actually easy and already implemented as `reduce` and `foldright` in most languages. It is `/` in J
+/ 1 2 3 4 NB. +/ is the whole verb phrase
10
1 + 2 + 3 + 4
10
an adverb in general takes one parameter (that may be a verb/function), and may return a function. The insert adverb
does take a function as parameter (add in above example), and the result is a monad function (a function that ignores
its 2nd x parameter). It may be easier, to model the insert function as the complete chain:
Insert(u, y):
where u is the function parameter, and y is an array where u is applied between items of y. But an ideal model is:
Insert(u): NB. find a function to return without needing to look at y parameters.
The result of Insert ignores any x parameter.
The definition of item in J:
A list (1d array) is a list of "scalar items"
A table (2d array) is a list of "list items"
A brick (3d array) is a list of "table items"
so,
iota 2 3
0 1 2
3 4 5
+/ iota 2 3 NB. or: (add insert) (iota 2 3)
3 5 7
0 1 2 + 3 4 5
3 5 7
+/ iota 10 5 NB. or: insert(add) iota ([2, 3])
225 235 245 255 265
iota 3 2 4 NB. result has 3 items
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19
20 21 22 23
+/ iota 3 2 4 NB. remember insert applies between items.
24 27 30 33
36 39 42 45
+/ +/ iota 3 2 4
60 66 72 78
Implement an insert adverb in your favorite language.
J definition of insert (variation from builtin to ignore x parameter) : `insert =: 1 : 'u/@:]'`
# 2. a swap adverb
swap is an adverb that reverses the x and y parameters to its function parameter such that y is passed x, and x is
passed y. If there is no x, parameter, then the function is passed (y,y)
a perhaps easy model is: the signature `swap(u, x, y=x):` but a better signature would be `swap(u):` and return a
composition of u and the swapping mechanics needed.
swap is ~ in J. iota is from Monday's challenge.
2 3 iota~ 1 NB. 1 + iota 2 3
1 2 3
4 5 6
iota~ 4 NB. 4 + iota 4
4 5 6 7
iota~/ 2 2 4 NB. insert swap iota between items of 2 2 4
4 6
iota~/ 2 4
4 5
iota insert~ 2 2 3 NB. swap (insert iota) between items of 3 2 3.
2 3 4 5
6 7 8 9
10 11 12 13
14 15 16 17
18 19 20 21
22 23 24 25
last result is same as if swap is ommitted, because insert has been defined to ignore x parameter, and swap duplicates
y as x. swap applies to the function after insert (result of insert)
swap(add) ([1, 2, 3]) NB. y is copied into x parameter
2 4 6
implement a swap adverb.
# 3. Compose conjunction.
Composition of functions u and v should be familiar. An easy model is:
`compose(u,v,y,x):` creating equivalent result to `u(v(y, x))`
note that the u function ignores its x parameter (x default value will be passed to it)
An ideal signature for compose, is compose(u,v): (In J, compose is `@:`)
2 3 iota@:+ 1 2 NB. compose(iota, add)([2,3],[1,2])
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
# 4. append itemize, and joincells functions
In Monday's bonus and iota function, the request was to make a recursive function that would then `joincells` of its
recursive calls to make one large array.
if you `append` 2 lists together, you get 1 larger list. A scalar appended with a list or scalar is also a list.
The `itemize` function takes an array and increases its dimensions by 1, creating a single item in a higher dimension.
itemize on a scalar creates a list of 1 item. itemize on a list creates a table with 1 record (that contains the
original list). itemize on a table creates a 3d array with 1 item that is a table.
If you `append` 2 items of the same dimensions, the result is 2 items. 1 record appended to 3 records is 4 items of
records (a table with 4 items). (the difference between a record and a list is that a record is a table with 1 row
(item). A list is a collection of scalar (items))
If you `append` a smaller-dimensioned item (list) with a larger-dimensioned item (record), the smaller-dimensioned item
is `itemize`d until it is the same dimension as the larger item. `append` of an item with empty item (empty can still
be high dimensioned) results in 1 item of the largest-dimensioned-parameter.
3 4 5 , iota 0 0 0 NB. append list with empty 3d array.
3 4 5
above result looks like a list, but is a brick (3d) with 1 table item, that has 1 record item.
the `joincells` function is something that was used by iota (whether you realized it or not) on the bonus applications
of Monday's challenge.
`cells` are an internal list of arrays. The algorithm is:
Find the largest dimensioned cell (array in the list).
With iota, create an empty cell that is 1 dimension higher than that maximum dimension. (for example: if all the cells
are lists, then `iota 0 0` creates an empty 0 record table.
With that new cell added on the right of the list of cells, insert(append) all the cells. (foldright append to all of
the cells). As an alternative to the iota call, you may also repeatedly itemize each of the cell arrays until they are
one dimension higher than the max-dimension-cell.
itemize(y , x=ignored): Rank _ _ NB. adds 1 dimension to y
append(y , x): Rank _ _ NB. joins x (first) to y (last). see itemize preprocessing rules
above.
joincells(listofarrays): internal function NB. see above algorithm. Though an internal function, can also be
implemented with boxes.
(itemize 4) append 1 2 3 NB. scalar 4 made into list append to other list = list
4 1 2 3
(itemize 4) append (itemize 1 2 3) NB. list append to table = table. Fills are applied to shorter list.
4 0 0
1 2 3
1 2 3 joincells 7 NB. though internal, if there are only 2 arrays to join, it works as a f(y,x)
function.
1 2 3
7 0 0
1 2 3 joincells iota 2 4
1 2 3 0
0 0 0 0
0 1 2 3
4 5 6 7
1 2 3 4 joincells iota 2 3 NB. fills are applied on the append stage.
1 2 3 4
0 0 0 0
0 1 2 0
3 4 5 0
try to implement joincells as `compose(insert(append), pretransform_arrays_function):`
# 5. Rank conjunction
This is the main challenge of the day...
The Rank conjunction can be used to split up a function call into many function calls that each results in a cell, and
then the joincells function above turns those individual function calls into a single array result.
While each function has a built in default rank, the rank conjunction **can lower** the "operating" rank of a function.
This is easier to understand as splitting the inputs to the function. `"` is the rank in J. the v (right) argument
to rank can be:
1 number: splits y argument into cells of that dimension. x rank is infinity (or is ignored).
2 numbers: splits y into cells of first number dimension, and splits x into 2nd number dimension.
`Rank(u, _ _) ` specifies rank infinity for x and y which is the same as no rank modifier at all since the full arrays
of x and y will be passed to u.
you may use 32000 as a substitute for infinity, or the default value for both "v parameters" to Rank.
`Rank(iota, 0 0)` will split the y and x parameters into scalars and call iota for each split
pR 1 3 iota("0 0) 3 4 NB. "(0 0) is Rank(u, 0 0) (an adverb) iota("0 0) is Rank(iota, 0 0). returns a
function.
1 2 3 0
3 4 5 6
equivalent to:
(1 iota 3) joincells (3 iota 4)
1 2 3 0
3 4 5 6
1 2 + 3 4 5 NB. an error in J, because only length 1 items are expanded to match the other argument lengths.
1 2 +("0 1) 3 4 5 NB. using rank to pass compatible lengths. (the order of rank v parameters in J is reversed
because x is on the left, and y on the right.
4 5 6
5 6 7
1 2 +("1 0) 3 4 5
4 5
5 6
6 7
Note in the last 2 examples, 2 items were matched with 1 item (first), and 1 item was matched with 3 items (2nd).
When matching different length items, if the lower array count is 1 item, then it is copied the number of times needed
to be the same length as the other array.
(add insert) iota 10 5 NB. seen before puts insert between rows. end result is sum of columns.
225 235 245 255 265
(add insert)"1 iota 10 5 NB. cells are the rows. result of each cell is sum of rows (a scalar). joincells
makes a list.
10 35 60 85 110 135 160 185 210 235
the last call is equivalent to `Compose(Rank(insert(add)), 1), iota)([10,5])`
#6. simple functions
`Left(y,x): return y` `]` in J
`Right(y,x): return swap(Left)(y, x=missing)` NB. returns y if there is no x. `[` in J
`double(y,x=ignored): return swap(add) y` NB. ignores x.
double 5
10
1 2 3 double~ 5 NB. swapped so passes x as y.
2 4 6
double~ 5 2 NB. if there was an x, then double that. Since there isn't, double y.
10 4
double~/ 5 2 NB. insert(swap(double))([5,2])
10
5 double~ 2
10
"""
def main():
pass
if __name__ == "__main__":
main()
|
w, h, n = map(int, input().split())
def k_fit_dip(side):
w_k = side // w
h_k = side // h
return w_k * h_k
def size_search():
left = 0
right = 10 ** 14
while right - left > 1:
mid = (right + left) // 2
k_dip = k_fit_dip(mid)
if k_dip >= n:
right = mid
else:
left = mid
return right
print(size_search())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Guenter Bartsch
#
# 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.
def get_data(k):
k.dte.set_prefixes([u''])
def answer_howdy_en(c):
c.resp(u"Great, thanks. How do you feel today?")
c.resp(u"Very well - and you?")
c.resp(u"I am doing great, how are you doing?")
c.resp(u"Great as always!")
c.resp(u"Thanks for asking, I am doing fine. How about you?")
def answer_howdy_de(c):
c.resp(u"Sehr gut, danke. Und selber?")
c.resp(u"Gut, danke. Wie geht es Dir?")
c.resp(u"Mir geht es prima, und Dir?")
c.resp(u"Mir geht es gut, und selber?")
c.resp(u"Super, wie immer!")
c.resp(u"Gut, danke der Nachfrage. Wie geht es Dir?")
k.dte.dt('en', u"(hi|hello|) (how are you|how are you doing|howdy|how do you do|how are you feeling|how are ya|how are ya doing) (today|)?",
answer_howdy_en)
k.dte.dt('de', u"(hi|hallo|) (wie geht es dir|wie gehts|was geht|wie fühlst du dich) (heute|)?",
answer_howdy_de)
k.dte.dt('en', [u"how are you this evening",
u"how do you feel",
u"how was your day today",
u"how was your day"],
answer_howdy_en)
k.dte.dt('de', [u"wie geht es dir heute abend",
u"wie fühlst du dich",
u"wie war dein tag heute",
u"wie war dein tag"],
answer_howdy_de)
k.dte.dt('en', [u"I am (also|) (doing|feeling|) (fine|good|very good|excellent|super) (too|)",
u"good thank you",
u"i am well"],
[u"Excellent! What would you like to talk about?",
u"Glad to hear that. What would you like to talk about?"])
k.dte.dt('de', [u"mir geht es (auch|) (sehr|) (super|gut|super gut) (danke|danke der nachfrage|)",
u"danke (auch|) (gut|sehr gut|super|super gut)"],
[u"Prima! Worüber möchtest Du mit mir sprechen?",
u"Freut mich zu hören. Worüber möchtest Du mit mir sprechen?"])
k.dte.dt('en', u"many thanks", u"What else can I do for you?")
k.dte.dt('de', u"vielen dank", u"Was kann ich sonst noch für Dich tun?")
k.dte.dt('en', u"ping", u"pong")
k.dte.dt('de', u"ping", u"pong")
k.dte.ts('en', 'smalltalk00', [(u"how are you?", u"very well and you?", [])])
k.dte.ts('de', 'smalltalk01', [(u"wie geht es dir?", u"Super, wie immer!", [])])
|
"""
Copy List with Random Pointer
A linked list of length n is given such that each node contains an additional random pointer,
which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes,
where each new node has its value set to the value of its corresponding original node.
Both the next and random pointer of the new nodes should point to new nodes in the
copied list such that the pointers in the original list and copied list represent the same list state.
None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y,
then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Example 4:
Input: head = []
Output: []
Explanation: The given linked list is empty (null pointer), so return null.
Constraints:
0 <= n <= 1000
-10000 <= Node.val <= 10000
Node.random is null or is pointing to some node in the linked list.
"""
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return head
# Creating a new weaved list of original and copied nodes.
ptr = head
while ptr:
# Cloned node
new_node = Node(ptr.val, None, None)
# Inserting the cloned node just next to the original node.
# If A->B->C is the original linked list,
# Linked list after weaving cloned nodes would be A->A'->B->B'->C->C'
new_node.next = ptr.next
ptr.next = new_node
ptr = new_node.next
ptr = head
# Now link the random pointers of the new nodes created.
# Iterate the newly created list and use the original nodes random pointers,
# to assign references to random pointers for cloned nodes.
while ptr:
ptr.next.random = ptr.random.next if ptr.random else None
ptr = ptr.next.next
# Unweave the linked list to get back the original linked list and the cloned list.
# i.e. A->A'->B->B'->C->C' would be broken to A->B->C and A'->B'->C'
ptr_old_list = head # A->B->C
ptr_new_list = head.next # A'->B'->C'
head_new = head.next
while ptr_old_list:
ptr_old_list.next = ptr_old_list.next.next
ptr_new_list.next = ptr_new_list.next.next if ptr_new_list.next else None
ptr_old_list = ptr_old_list.next
ptr_new_list = ptr_new_list.next
return head_new
|
# Tuples is an immutable object in Python. It means once data is set, you cannot change those data.
# Can be used for constant data or dictionary without key (nested tuples)
# Empty Tuple initialization
tup = ()
print(tup)
# Tuple initialization with data
# I didn't like this way thought ;)
tup1 = 'python', 'aws', 'security'
print(tup1)
# Another for doing the same
tup2 = ('python', 'django', 'linux')
print(tup2)
# Concatenation
tup3 = tup1 + tup2
print(tup3)
# Nesting of tuples
tup4 = (tup1, tup2)
print(tup4)
# Length of a tuple
print(len(tup3))
print(len(tup4))
# Tuple Indexing and slicing
print(tup3[2])
print(tup2[1:])
# Deleting a tuple, removing individual element from the tuple is not possible. It deletes the whole tuple
del tup4
# Converts a list into tuple
tup5 = tuple(["Sanjeev", '2021', "Flexmind"])
print(tup5)
# try tuple() to a string
tup6 = tuple('Python')
print(tup6)
#Tuple iteration
for tup in tup5:
print(tup)
# Max and min method
max_elem = max(tup1)
print("max element: ", max_elem)
print("min element: ", min(tup5))
|
class CombinationIterator:
def __init__(self, characters, combinationLength):
self.characters = characters
self.combinationLength = combinationLength
self.every_comb = self.generate()
def generate(self):
every_comb = []
for i in range(2**len(self.characters)):
string = ""
for j in range(len(self.characters)):
if ((1<<j) & i > 0):
string += self.characters[j]
if len(string) == self.combinationLength and string not in every_comb:
every_comb.append(string)
every_comb.sort()
return every_comb
def nextStr(self):
for id in range(len(self.every_comb)):
return self.every_comb.pop(id)
def hasNext(self):
if len(self.every_comb) >= 1:
return True
return False
itr = CombinationIterator("bvwz", 2)
#print(itr.every_comb)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.