コード例 #1
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def fetch_changed_records(self, zone_id, options=None):
        """Fetch changed records in a given custom zone."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/ChangeRecords/ChangeRecords.html#//apple_ref/doc/uid/TP40015240-CH7-SW1
        if self.database_type == 'private':
            return None

        payload = {
            'zoneID': zone_id,
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request(
            'POST',
            self.container,
            'private',
            'records/changes',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))

            more_coming = parse(result.value, 'moreComing')
            reverse = parse(result.value, 'reverse')
            sync_token = parse(result.value, 'syncToken')

            result.value = (objects, more_coming, reverse, sync_token)

        return result
コード例 #2
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.user_record_name = parse(json, 'userRecordName')
         self.first_name = parse(json, 'firstName')
         self.last_name = parse(json, 'lastName')
         self.email_address = parse(json, 'emailAddress')
         self.is_discoverable = parse(json, 'isDiscoverable')
コード例 #3
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def perform_query(self, query, options=None):
        """Fetch records using a query."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/QueryingRecords/QueryingRecords.html#//apple_ref/doc/uid/TP40015240-CH5-SW4
        payload = {
            'query': query.json(),
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request(
            'POST',
            self.container,
            self.database_type,
            'records/query',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))
            continuation_marker = parse(result.value, 'continuationMarker')

            result.value = (objects, continuation_marker)

        return result
コード例 #4
0
ファイル: datatypes.py プロジェクト: davecom/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.user_record_name = parse(json, 'userRecordName')
         self.first_name = parse(json, 'firstName')
         self.last_name = parse(json, 'lastName')
         self.email_address = parse(json, 'emailAddress')
         self.is_discoverable = parse(json, 'isDiscoverable')
コード例 #5
0
    def perform_query(self, query, continuation_marker=None, options=None):
        """Fetch records using a query."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/QueryingRecords/QueryingRecords.html#//apple_ref/doc/uid/TP40015240-CH5-SW4
        payload = {
            'query': query.json(),
        }

        if continuation_marker is not None:
            if options is None:
                options = {}
            options['continuationMarker'] = continuation_marker

        if options is not None:
            payload.update(options)

        result = Request.perform_request('POST',
                                         self.container,
                                         self.database_type,
                                         'records/query',
                                         payload,
                                         logger=self.__logger)

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))
            continuation_marker = parse(result.value, 'continuationMarker')

            result.value = (objects, continuation_marker)

        return result
コード例 #6
0
    def fetch_changed_records(self, zone_id, options=None):
        """Fetch changed records in a given custom zone."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/ChangeRecords/ChangeRecords.html#//apple_ref/doc/uid/TP40015240-CH7-SW1
        if self.database_type == 'private':
            return None

        payload = {
            'zoneID': zone_id,
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request('POST',
                                         self.container,
                                         'private',
                                         'records/changes',
                                         payload,
                                         logger=self.__logger)

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))

            more_coming = parse(result.value, 'moreComing')
            reverse = parse(result.value, 'reverse')
            sync_token = parse(result.value, 'syncToken')

            result.value = (objects, more_coming, reverse, sync_token)

        return result
コード例 #7
0
ファイル: error.py プロジェクト: yz/CloudKitPy
 def __init__(self, json, status_code, request, payload):
     if json is not None:
         self.ck_error_code = parse(json, 'ckErrorCode')
         self.is_error = self.ck_error_code is not None
         self.server_error_code = parse(json, 'serverErrorCode')
         self.is_server_error = self.server_error_code is not None
         self.reason = parse(json, 'reason')
         self.retry_after = parse(json, 'retryAfter')
         self.uuid = parse(json, 'uuid')
         self.redirect_url = parse(json, 'redirectURL')
         self.record_name = parse(json, 'recordName')
         self.subscription_id = parse(json, 'subscriptionID')
         zone_id_json = parse(json, 'zoneID')
         if zone_id_json is not None:
             zone_id = ZoneID(zone_id_json)
             self.zone_id = zone_id
     self.payload = payload
     self.status_code = status_code
     self.status_code_reason = self.__error_reason_from_satus_code(
         status_code)
     if status_code != 200 and self.server_error_code is None:
         self.server_error_code = self.__error_from_satus_code(status_code)
     if self.reason is None:
         self.reason = self.status_code_reason
     self.request = request
コード例 #8
0
ファイル: value.py プロジェクト: yz/CloudKitPy
 def update_json(self, json):
     self.value_type = parse(json, 'type')
     if self.value_type == 'TIMESTAMP':
         timestamp = parse(json, 'value')
         timestamp = float(timestamp) / 1000  # Timestamp with nanoseconds
         self.value = datetime.datetime.utcfromtimestamp(timestamp)
     elif self.value_type == 'REFERENCE_LIST':
         item_list = parse(json, 'value')
         references = []
         for item in item_list:
             reference = Reference(item)
             references.append(reference)
         self.value = references
     else:
         self.value = parse(json, 'value')
コード例 #9
0
ファイル: value.py プロジェクト: Baza207/CloudKitPy
 def update_json(self, json):
     self.value_type = parse(json, 'type')
     if self.value_type == 'TIMESTAMP':
         timestamp = parse(json, 'value')
         timestamp = float(timestamp) / 1000    # Timestamp with nanoseconds
         self.value = datetime.datetime.utcfromtimestamp(timestamp)
     elif self.value_type == 'REFERENCE_LIST':
         item_list = parse(json, 'value')
         references = []
         for item in item_list:
             reference = Reference(item)
             references.append(reference)
         self.value = references
     else:
         self.value = parse(json, 'value')
コード例 #10
0
ファイル: container.py プロジェクト: Baza207/CloudKitPy
    def discover_user_info_with_email_address(self, email_address):
        """Fetch information about a single user.

        Based on the user's email address.
        """
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/LookupUsersbyEmail/LookupUsersbyEmail.html#//apple_ref/doc/uid/TP40015240-CH14-SW1
        payload = {
            'users': [
                {'emailAddress': email_address}
            ]
        }

        result = Request.perform_request(
            'POST',
            self,
            'public',
            'users/lookup/email',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'users')
            if objects_json is not None:
                for object_json in objects_json:
                    objects.append(UserInfo(object_json))

            result.value = objects

        return result
コード例 #11
0
ファイル: container.py プロジェクト: Baza207/CloudKitPy
    def discover_user_info_with_user_record_name(self, record_name):
        """Fetch information about a single user using the record name."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/LookupUsersbyID/LookupUsersbyID.html#//apple_ref/doc/uid/TP40015240-CH15-SW1
        payload = {
            'users': [
                {'userRecordName': record_name}
            ]
        }

        result = Request.perform_request(
            'POST',
            self,
            'public',
            'users/lookup/id',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'users')
            if objects_json is not None:
                for object_json in objects_json:
                    objects.append(UserInfo(object_json))

            result.value = objects

        return result
コード例 #12
0
    def fetch_records(self,
                      records=None,
                      record_type=None,
                      record_names=None,
                      references=None,
                      options=None):
        """Fetch one or more records."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/LookupRecords/LookupRecords.html#//apple_ref/doc/uid/TP40015240-CH6-SW2
        json_records = self.__create_fetch_json_records(
            records, record_type, record_names, references)

        payload = {
            'records': json_records,
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request('POST',
                                         self.container,
                                         self.database_type,
                                         'records/lookup',
                                         payload,
                                         logger=self.__logger)

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))

            result.value = objects

        return result
コード例 #13
0
    def __modify_record_zones(self, zone_ids, operation_type):
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/ModifyZones/ModifyZones.html#//apple_ref/doc/uid/TP40015240-CH10-SW1
        operations = []
        for zone_id in zone_ids:
            operation = {
                'operationType': operation_type,
                'zone': zone_id.json()
            }
            operations.append(operation)

        payload = {
            'operations': operations,
        }

        result = Request.perform_request('POST',
                                         self.container,
                                         self.database_type,
                                         'zones/modify',
                                         payload,
                                         logger=self.__logger)

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'zones')
            for object_json in objects_json:
                objects.append(Zone(object_json))

            result.value = objects

        return result
コード例 #14
0
    def save_records(self,
                     records,
                     auto_fetch=False,
                     force=False,
                     options=None):
        """Save records to the database."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/ModifyRecords/ModifyRecords.html#//apple_ref/doc/uid/TP40015240-CH2-SW9
        operations = self.__create_modify_operations(records, auto_fetch,
                                                     force)

        payload = {
            'operations': operations,
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request('POST',
                                         self.container,
                                         self.database_type,
                                         'records/modify',
                                         payload,
                                         logger=self.__logger)

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))

            result.value = objects

        return result
コード例 #15
0
    def fetch_record_zones(self, zones):
        """Fetch one or more zones."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/GettingZonesbyIdentifier/GettingZonesbyIdentifier.html#//apple_ref/doc/uid/TP40015240-CH22-SW1
        zones_json = []
        for zone in zones:
            zones_json.append(zone.json())

        payload = {
            'zones': zones_json,
        }

        result = Request.perform_request('POST',
                                         self.container,
                                         self.database_type,
                                         'zones/lookup',
                                         payload,
                                         logger=self.__logger)

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'zones')
            for object_json in objects_json:
                objects.append(Zone(object_json))

            result.value = objects

        return result
コード例 #16
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def fetch_record_zones(self, zones):
        """Fetch one or more zones."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/GettingZonesbyIdentifier/GettingZonesbyIdentifier.html#//apple_ref/doc/uid/TP40015240-CH22-SW1
        zones_json = []
        for zone in zones:
            zones_json.append(zone.json())

        payload = {
            'zones': zones_json,
        }

        result = Request.perform_request(
            'POST',
            self.container,
            self.database_type,
            'zones/lookup',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'zones')
            for object_json in objects_json:
                objects.append(Zone(object_json))

            result.value = objects

        return result
コード例 #17
0
def main():
    R, S, U, P, M, unavaiable, servers = parse("input/example.in")
    print(R, S, U, P, M)
    for u in unavaiable:
        print(u)
    for s in servers:
        print(s)
コード例 #18
0
	def build(self, silent=False) :
		"""Build the model if it is entered manually."""

		# Model variables
		self.N_states = len(self.states)
		self.N_events = len(self.events)
		self.states_map = { i : idx for i, idx in zip(self.states, range(self.N_states)) }

		# Transition matrix
		self.transition = np.zeros((self.N_states, self.N_events), dtype=int)
		for idx, e in enumerate(self.events) :
			for i in e[1] :
				self.transition[self.states_map[i], idx] = e[1][i]

		# Cast parameters as strings
		for key, val in self.parameters.items() :
			if type(val) is not str :
				self.parameters[key] = str(val)

		# State vector
		self.X = np.zeros(self.N_states)
		for key, val in self.initconds.items() :
			self.X[self.states_map[key]] = val

		# Transition rate functions
		self.rates = []
		for e in self.events :
			self.rates.append(eval("lambda X, time : %s" % helpers.parse(e[0], self.states_map, self.parameters)))

		if not silent :
			print(self)
コード例 #19
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def __modify_record_zones(self, zone_ids, operation_type):
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/ModifyZones/ModifyZones.html#//apple_ref/doc/uid/TP40015240-CH10-SW1
        operations = []
        for zone_id in zone_ids:
            operation = {
                'operationType': operation_type,
                'zone': zone_id.json()
            }
            operations.append(operation)

        payload = {
            'operations': operations,
        }

        result = Request.perform_request(
            'POST',
            self.container,
            self.database_type,
            'zones/modify',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'zones')
            for object_json in objects_json:
                objects.append(Zone(object_json))

            result.value = objects

        return result
コード例 #20
0
async def execute(message):
    command, channel, params, mentions, author = parse(message)
    mention_strings = [m.mention for m in mentions]
    actual_params = []
    for param in params:
        if param not in mention_strings:
            actual_params.append(param)
    print("Params", params, "|", mention_strings, "=>", actual_params)
    if len(actual_params) == 0:
        await message.channel.send("Aus welchem Sub-Reddit? :O")
        return

    response = requests.get(
        f'https://www.reddit.com/r/{actual_params[0]}/randomrising.json?obey_over18=true',
        headers=reddit_headers)
    if response.status_code != 200:
        print("response.status_code != 200")
        await message.channel.send(
            f"AHHHHHHHHH, IRGENDWAS ist kaputt gegangen! o.O\n(Error Code: RED{response.status_code})"
        )
        return
    try:
        response_json = response.json()
        children = response_json["data"]["children"]
        for c in [x["data"] for x in children]:
            print(c)
            try:
                if c["over_18"] or c["url"] is None or "preview" not in c:
                    print(c["over_18"], "|", c["url"] is None, "|", "preview"
                          not in c)
                    continue
            except Exception as ex:
                print("Exception in if", ex)
                continue
            e = discord.Embed()
            e.title = c["title"]
            if c["selftext"] is not None:
                e.description = c["selftext"]
            img_url = c["preview"]["images"][0]["source"]["url"].replace(
                "&s", "&s")
            e.set_image(url=img_url)
            print(c["permalink"])
            e.url = "https://www.reddit.com/" + c["permalink"]
            e.set_footer(
                text=
                f'🔼 {c["ups"]} | 🔽 {c["downs"]} | 💬 {c["num_comments"]}'
            )
            print("=>", img_url)
            await message.channel.send(embed=e)
            return
        await message.channel.send(
            f"AHHHHHHHHH, IRGENDWAS ist kaputt gegangen! o.O\n(Error Code: RED0NC)"
        )
        return
    except Exception as ex:
        print(str(ex))
        await message.channel.send(
            "AHHHHHHHHH, IRGENDWAS ist kaputt gegangen! o.O\n(Error Code: RED123123)"
        )
        return
コード例 #21
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def fetch_records(self, records, options=None):
        """Fetch one or more records."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/LookupRecords/LookupRecords.html#//apple_ref/doc/uid/TP40015240-CH6-SW2
        json_records = []
        for record in records:
            json_records.append(record.json())

        payload = {
            'records': json_records,
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request(
            'POST',
            self.container,
            self.database_type,
            'records/lookup',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))

            result.value = objects

        return result
コード例 #22
0
    def discover_user_info_with_email_address(self, email_address):
        """Fetch information about a single user.

        Based on the user's email address.
        """
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/LookupUsersbyEmail/LookupUsersbyEmail.html#//apple_ref/doc/uid/TP40015240-CH14-SW1
        payload = {'users': [{'emailAddress': email_address}]}

        result = Request.perform_request('POST',
                                         self,
                                         'public',
                                         'users/lookup/email',
                                         payload,
                                         logger=self.__logger)

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'users')
            if objects_json is not None:
                for object_json in objects_json:
                    objects.append(UserInfo(object_json))

            result.value = objects

        return result
コード例 #23
0
async def execute(message):
    command, channel, params, mentions, author = parse(message)
    mention_strings = [m.mention for m in mentions]
    actual_params = []
    for param in params:
        if param not in mention_strings:
            actual_params.append(param)
    print("Params", params, "|", mention_strings, "=>", actual_params)

    if len(actual_params) == 0:
        await message.channel.send("Bitte gib eine URL an.")
        return
    if len(actual_params) > 1:
        await message.channel.send("Bitte gib nur eine URL an.")
        return

    if not is_url_image(actual_params[0]):
        await message.channel.send(
            "Die gewählte URL scheint nicht zu existieren oder kein Bild zu sein."
        )
        return

    shv = shelve.open("sad_config.config")
    shv[str(message.author.id)] = actual_params[0]
    shv.close()

    await message.channel.send("+sad bild auf " + actual_params[0] +
                               " gesetzt.")
コード例 #24
0
async def execute(message):
    if not await check_admin_permissions(message):
        return

    command, channel, params, mentions, author = parse(message)
    mention_strings = [m.mention for m in mentions]
    actual_params = []
    for param in params:
        if param not in mention_strings:
            actual_params.append(param)
    print("Params", params, "|", mention_strings, "=>", actual_params)

    if len(actual_params) == 0:
        await message.channel.send("Wozu denn? o.O\n(Bitte gib einen Suchterm an)")
        return
    if "@pos" in actual_params:
        lmt = 1
        pos = int(actual_params[actual_params.index("@pos")+1])
        check_last = False
        actual_params.remove(actual_params[actual_params.index("@pos")+1])
        actual_params.remove("@pos")
        print(actual_params)
    else:
        lmt = 30
        pos = 0
        check_last = True

    gif = get_gif(' '.join(actual_params), wo_anime=True, lmt=lmt, pos=pos, check_last=check_last)

    embed = discord.Embed()
    embed.description = f'Gif zu \"{" ".join(actual_params)}\"{f" @ Position {pos} "if lmt == 1 else ""}'
    embed.set_image(url=gif)
    await message.channel.send(embed=embed)
コード例 #25
0
ファイル: pruner.py プロジェクト: ptyshevs/hashcode
def magic(path='input/example.in'):
    R, S, U, P, M, unavaiable, servers = parse(path)
    for i in range(len(servers)):
        servers[i].append(i)
    servers = sorted(servers, key=lambda x: x[0], reverse=True)
    #     print(servers)

    rows = []

    for i in range(R):
        rows.append("a" * S)

    for i in range(U):
        rows[unavaiable[i]
             [0]] = rows[unavaiable[i][0]][:unavaiable[i][1]] + 'u' + rows[
                 unavaiable[i][0]][unavaiable[i][1] + 1:]

    result = []
    while len(servers) > 0:
        i = -1
        for k in range(R):
            if servers[0][0] * 'a' in rows[k] and (
                    i == -1 or rows[k].count('a') >= rows[i].count('a')):
                i = k
        if i != -1:
            slot = rows[i].find(servers[0][0] * 'a')
            rows[i] = rows[i][:slot] + servers[0][0] * 'u' + rows[i][
                slot + servers[0][0]:]
            result.append([[i, slot], servers[0]])
        del servers[0]


#     for i in range(R):
#         print(rows[i])
    return result
コード例 #26
0
def clubs():
    # the user reached the route via get get
    if request.method == "GET":
        # get the clubs from the database
        clubs = db.execute("SELECT * FROM clubs")
        # get the subscriptions for the current user
        row = db.execute("SELECT subscriptions FROM users WHERE id = :user_id",
                         user_id=session["user_id"])[0]
        subscriptions = row["subscriptions"]
        # if the user has subscriptions, create list with row values casted to int
        if subscriptions != None and subscriptions != '':
            subscriptions = [int(x) for x in parse(row["subscriptions"])]
        # if the user has no subscriptions, create an empty list
        else:
            subscriptions = []
        # calculate number of clubs to access index when iterating in html
        num = len(clubs)
        # display clubs page
        return render_template("clubs.html",
                               clubs=clubs,
                               num=num,
                               subscribed_clubs=subscriptions)
    # the user reached the route via post
    else:
        # get the user input for subscription
        subscription = request.form.get("subscribe")
        # create a blank list to store clubs in
        clubsList = []
        # select the user from the database
        row = db.execute("SELECT * FROM users WHERE id = :user_id",
                         user_id=session["user_id"])[0]
        # if the user has subscriptinos
        if row["subscriptions"] != None and row["subscriptions"] != "":
            clubsList = parse(row["subscriptions"])
            # if the user is not already subscribed to the club, add it to their subscriptions
            if subscription not in clubsList:
                clubsList.append(subscription)
        # if the user is not subscribed to any clubs, add the club to a blank list
        else:
            # update the user's subscriptions
            clubsList.append(subscription)
        db.execute(
            "UPDATE users SET subscriptions = :subscriptions WHERE id = :user_id",
            user_id=session["user_id"],
            subscriptions=rejoin(clubsList))
        # redirect to index
        return redirect("/")
コード例 #27
0
ファイル: datatypes.py プロジェクト: davecom/CloudKitPy
    def __init__(self, json=None):
        filter_by_json = None
        sort_by_json = None
        if json is not None:
            self.record_type = parse(json, 'recordType')
            filter_by_json = parse(json, 'filterBy')
            sort_by_json = parse(json, 'sortBy')

        if filter_by_json is not None and len(filter_by_json) > 0:
            self.filter_by = []
            for query_filter in filter_by_json:
                self.filter_by.append(Filter(query_filter))

        if sort_by_json is not None and len(sort_by_json) > 0:
            self.sort_by = []
            for sort_descriptor in sort_by_json:
                self.sort_by.append(SortDescriptor(sort_descriptor))
コード例 #28
0
 def to_python(self, value):
     if (value is None) or isinstance(value, datetime.timedelta):
         return value
     if isinstance(value, int):
         return datetime.timedelta(seconds=value)
     if value == "":
         return None
     return parse(value)
コード例 #29
0
 def clean(self, value):
     super(TimedeltaFormField, self).clean(value)
     if value == '' and not self.required:
         return u''
     try:
         return parse(value)
     except TypeError:
         raise forms.ValidationError(self.error_messages['invalid'])
コード例 #30
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
    def __init__(self, json=None):
        filter_by_json = None
        sort_by_json = None
        if json is not None:
            self.record_type = parse(json, 'recordType')
            filter_by_json = parse(json, 'filterBy')
            sort_by_json = parse(json, 'sortBy')

        if filter_by_json is not None and len(filter_by_json) > 0:
            self.filter_by = []
            for query_filter in filter_by_json:
                self.filter_by.append(Filter(query_filter))

        if sort_by_json is not None and len(sort_by_json) > 0:
            self.sort_by = []
            for sort_descriptor in sort_by_json:
                self.sort_by.append(SortDescriptor(sort_descriptor))
コード例 #31
0
ファイル: error.py プロジェクト: davecom/CloudKitPy
 def __init__(self, json):
     self.ck_error_code = parse(json, 'ckErrorCode')
     self.is_error = self.ck_error_code is not None
     self.server_error_code = parse(json, 'serverErrorCode')
     self.is_server_error = self.server_error_code is not None
     self.reason = parse(json, 'reason')
     self.retry_after = parse(json, 'retryAfter')
     self.uuid = parse(json, 'uuid')
     self.redirect_url = parse(json, 'redirectURL')
     self.record_name = parse(json, 'recordName')
     self.subscription_id = parse(json, 'subscriptionID')
     zone_id_json = parse(json, 'zoneID')
     if zone_id_json is not None:
         zone_id = ZoneID(zone_id_json)
         self.zone_id = zone_id
コード例 #32
0
ファイル: bot.py プロジェクト: bootuz/package_tracker
def track_message(message):
    if correct_message(message.text):
        try:
            history = PackageData(message.text).history_record
            data = parse(history)
            bot.send_message(message.chat.id, format_dict(data))
        except WrongIdError:
            bot.send_message(message.chat.id, "ID не найден")
    else:
        bot.send_message(message.chat.id, 'Неверный фортмат ID')
コード例 #33
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.zone_id = ZoneID(parse(json, 'zoneID'))
         self.subscription_id = parse(json, 'subscriptionID')
         self.subscription_type = parse(json, 'subscriptionType')
         self.query = Query(parse(json, 'query'))
         self.fires_on = parse(json, 'firesOn')
         self.fires_once = parse(json, 'firesOnce')
         self.notification_info = NotificationInfo(
             parse(json, 'notificationInfo')
         )
         self.zone_wide = parse(json, 'zoneWide')
コード例 #34
0
ファイル: datatypes.py プロジェクト: davecom/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.zone_id = ZoneID(parse(json, 'zoneID'))
         self.subscription_id = parse(json, 'subscriptionID')
         self.subscription_type = parse(json, 'subscriptionType')
         self.query = Query(parse(json, 'query'))
         self.fires_on = parse(json, 'firesOn')
         self.fires_once = parse(json, 'firesOnce')
         self.notification_info = NotificationInfo(
             parse(json, 'notificationInfo')
         )
         self.zone_wide = parse(json, 'zoneWide')
コード例 #35
0
    def _has_changed(self, initial, data):
        """
        We need to make sure the objects are of the canonical form, as a
        string comparison may needlessly fail.
        """
        if initial in ["", None] and data in ["", None]:
            return False

        if initial in ["", None] or data in ["", None]:
            return True

        if initial:
            if not isinstance(initial, datetime.timedelta):
                initial = parse(initial)

        if not isinstance(data, datetime.timedelta):
            data = parse(data)

        return initial != data
コード例 #36
0
async def execute(message):
    print(commands)
    command, channel, params, mentions, author = parse(message)
    c = 1
    for k in prefix:
        if command == k + "wackelarm":
            c = prefix[k]
            break

    await message.channel.send(c * "<a:wackelarm:721807816221786323>")
コード例 #37
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.record_name = parse(json, 'recordName')
         self.record_type = parse(json, 'recordType')
         self.record_change_tag = parse(json, 'recordChangeTag')
         self.fields = parse(json, 'fields')
         self.created = parse(json, 'created')
         self.modified = parse(json, 'modified')
         self.deleted = parse(json, 'deleted')
コード例 #38
0
ファイル: datatypes.py プロジェクト: davecom/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.record_name = parse(json, 'recordName')
         self.record_type = parse(json, 'recordType')
         self.record_change_tag = parse(json, 'recordChangeTag')
         self.fields = parse(json, 'fields')
         self.created = parse(json, 'created')
         self.modified = parse(json, 'modified')
         self.deleted = parse(json, 'deleted')
コード例 #39
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.latitude = parse(json, 'latitude')
         self.longitude = parse(json, 'longitude')
         self.horizontal_accuracy = parse(
             json,
             'horizontalAccuracy'
         )
         self.vertical_accuracy = parse(json, 'verticalAccuracy')
         self.altitude = parse(json, 'altitude')
         self.speed = parse(json, 'speed')
         self.course = parse(json, 'course')
         self.timestamp = parse(json, 'timestamp')
コード例 #40
0
ファイル: datatypes.py プロジェクト: davecom/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.latitude = parse(json, 'latitude')
         self.longitude = parse(json, 'longitude')
         self.horizontal_accuracy = parse(
             json,
             'horizontalAccuracy'
         )
         self.vertical_accuracy = parse(json, 'verticalAccuracy')
         self.altitude = parse(json, 'altitude')
         self.speed = parse(json, 'speed')
         self.course = parse(json, 'course')
         self.timestamp = parse(json, 'timestamp')
コード例 #41
0
ファイル: forms.py プロジェクト: furious-luke/cwschedule_site
    def clean(self, value):
        super(TimedeltaFormField, self).clean(value)
        if value in ('', None) and not self.required:
            return u''

        data = defaultdict(float)
        try:
            return parse(value)
        except TypeError:
            raise forms.ValidationError(self.error_messages['invalid'])

        return datetime.timedelta(**data)
コード例 #42
0
    def __init__(self, config):

        # store configuration
        self.config = config

        # finalize configuration setup
        self.config.setup()

        # parse input parameters
        self.params = helpers.parse()

        # status
        self.status = Status()

        # setup scheduler
        self.config.scheduler.setup(self.config.levels,
                                    self.config.levels_types,
                                    self.config.works, self.config.core_ratios,
                                    self.config.solver.sharedmem)

        # setup solver
        self.config.solver.setup(self.config.scheduler, self.params,
                                 self.config.root, self.config.deterministic,
                                 self.config.recycle)

        # setup samples
        self.config.samples.setup(self.config.levels, self.config.works,
                                  self.params.tolerate, self.config.recycle)

        # indicators
        self.indicators = Indicators(self.config.solver.indicator,
                                     self.config.solver.distance,
                                     self.config.levels,
                                     self.config.levels_types,
                                     self.config.pick,
                                     self.config.FINE,
                                     self.config.COARSE,
                                     self.config.works,
                                     self.config.samples.pairworks,
                                     self.config.recycle,
                                     inference=self.config.inference,
                                     enforce=self.config.enforce,
                                     ocv=self.config.ocv)

        # errors
        self.errors = Errors(self.config.levels, self.config.recycle)

        # availability
        self.available = 0

        # default file names
        self.submission_file = 'queue.dat'
        self.progress_file = 'progress.dat'
コード例 #43
0
ファイル: main.py プロジェクト: ptyshevs/hashcode
def main():
    input_fs = [
        "input/a_example.in", "input/b_small.in", "input/c_medium.in",
        "input/d_big.in"
    ]
    for input_f in input_fs:
        output_f = input_f.replace(".in", ".out").replace("input", "output")
        inp = parse(input_f)
        rows, cols, min_ing, max_area, pizza = inp
        slices = cut(inp)
        # print(slices)
        output(output_f, slices)
        print('.', end='')
コード例 #44
0
ファイル: main.py プロジェクト: ptyshevs/hashcode
def main():
    input_fs = [
        "./input/0_submission_example.in",
        "./input/1_me_at_the_zoo.in",
        "./input/2_videos_worth_spreading.in",
        "./input/3_trending_today.in",
        "./input/4_kittens.in",
    ]
    for input_f in tqdm.tqdm(input_fs):
        output_f = input_f.replace(".in", ".out").replace("input", "output")
        inp = parse(input_f)
        cs_by_vid = solve(inp)
        output(output_f, cs_by_vid)
コード例 #45
0
async def execute(message):
    command, channel, params, mentions, author = parse(message)

    if command == "animal":
        command = random.choice(commands)
    gif = get_gif(command, pos=0, lmt=10, wo_anime=True)

    if gif is None:
        await message.channel.send("Zu diesem Tier gibt es keine Gifs qwq")
    embed = discord.Embed()
    embed.description = command.replace("+", "")
    embed.set_image(url=gif)
    await message.channel.send(embed=embed)
コード例 #46
0
ファイル: datatypes.py プロジェクト: davecom/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.file_checksum = parse(json, 'fileChecksum')
         self.size = parse(json, 'size')
         self.reference_checksum = parse(json, 'referenceChecksum')
         self.wrapping_key = parse(json, 'wrappingKey')
         self.receipt = parse(json, 'receipt')
         self.download_url = parse(json, 'downloadURL')
コード例 #47
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.file_checksum = parse(json, 'fileChecksum')
         self.size = parse(json, 'size')
         self.reference_checksum = parse(json, 'referenceChecksum')
         self.wrapping_key = parse(json, 'wrappingKey')
         self.receipt = parse(json, 'receipt')
         self.download_url = parse(json, 'downloadURL')
コード例 #48
0
async def execute(message):
    if len(message.mentions) < 1 and not config.test_mode:
        await message.channel.send("Für wen den? o.O")
        return

    command, channel, params, mentions, author = parse(message)
    embed = discord.Embed()

    if message.mentions[0].name == "DrWurzeli" and message.mentions[
            0].discriminator == "2058":
        gif = "https://media.tenor.com/images/7e578d4941d0b674c5f22ea2d03f0476/tenor.gif"
        embed.description = "...wait a minute :eyes:"
        embed.set_image(url=gif)
        await message.channel.send(embed=embed)
        return

    if config.test_mode or (message.mentions[0].name == "Fera"
                            and message.mentions[0].discriminator == "7616"):
        if command == "maxitogo+" or command == "maxitogospecial":
            embed.description = "MaxiToGo Spezial wird geliefert!"
            img = get_maxi()
            file = discord.File(dir_path + "/assets/maxitogo/" + img,
                                filename=img)
            embed.set_image(url="attachment://" + img)
            await message.channel.send(file=file, embed=embed)
            return

        if random.choice([True, True, True, True, True, False]):
            embed.description = "MaxiToGo wird geliefert!"
            gif = get_gif('delivery', wo_anime=True, pos=0, lmt=10)
            gif = random.choice([
                gif, gif, gif, gif, gif, gif, gif, gif,
                "https://media.tenor.com/images/95db8481113f44469bde907db890856a/tenor.gif"
            ])
            embed.set_image(url=gif)
            await message.channel.send(embed=embed)
        else:
            embed.description = "MaxiToGo Spezial wird geliefert!"
            img = get_maxi()
            file = discord.File(dir_path + "/assets/maxitogo/" + img,
                                filename=img)
            embed.set_image(url="attachment://" + img)
            await message.channel.send(file=file, embed=embed)
    else:
        gif = get_gif('slap')
        embed.description = "Nein."
        embed.set_image(url=gif)
        await message.channel.send(embed=embed)
コード例 #49
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.alert_body = parse(json, 'alertBody')
         self.alert_localization_key = parse(
             json,
             'alertLocalizationKey'
         )
         self.alert_localization_args = parse(
             json,
             'alertLocalizationArgs'
         )
         self.alert_action_localization_key = parse(
             json,
             'alertActionLocalizationKey'
         )
         self.alert_launch_image = parse(json, 'alertLaunchImage')
         self.sound_name = parse(json, 'soundName')
         self.should_badge = parse(json, 'shouldBadge')
         self.should_send_content_available = parse(
             json,
             'shouldSendContentAvailable'
         )
コード例 #50
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def delete_records(self, records, force=False, options=None):
        """Delete one or more records."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/ModifyRecords/ModifyRecords.html#//apple_ref/doc/uid/TP40015240-CH2-SW9
        operation_type = 'delete'
        if force is True:
            operation_type = 'forceDelete'

        operations = []
        for record in records:
            operation = {
                'operationType': operation_type,
                'record': record.json()
            }
            operations.append(operation)

        payload = {
            'operations': operations,
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request(
            'POST',
            self.container,
            self.database_type,
            'records/modify',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))

            result.value = objects

        return result
コード例 #51
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def save_records(
        self,
        records,
        auto_fetch=False,
        force=False,
        options=None
    ):
        """Save records to the database."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/ModifyRecords/ModifyRecords.html#//apple_ref/doc/uid/TP40015240-CH2-SW9
        operations = self.__create_modify_operations(
            records,
            auto_fetch,
            force
        )

        payload = {
            'operations': operations,
        }
        if options is not None:
            payload.update(options)

        result = Request.perform_request(
            'POST',
            self.container,
            self.database_type,
            'records/modify',
            payload,
            logger=self.__logger
        )

        if result.is_success is True:
            objects = []
            objects_json = parse(result.value, 'records')
            for object_json in objects_json:
                objects.append(Record(object_json))

            result.value = objects

        return result
コード例 #52
0
ファイル: database.py プロジェクト: davecom/CloudKitPy
    def fetch_all_record_zones(self):
        """Fetch all zones in the database."""
        # https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/GettingAllZones/GettingAllZones.html#//apple_ref/doc/uid/TP40015240-CH21-SW3
        result = Request.perform_request(
            'GET',
            self.container,
            self.database_type,
            'zones/list',
            logger=self.__logger
        )

        if result.is_success is True:
            zones = []
            objects_json = parse(result.value, 'zones')
            for object_json in objects_json:
                zones.append(Zone(object_json))

            if len(zones) > 0:
                result.value = self.fetch_record_zones(zones)
            else:
                result.value = []

        return result
コード例 #53
0
ファイル: value.py プロジェクト: davecom/CloudKitPy
 def update_json(self, json):
     self.value = parse(json, 'value')
     self.value_type = parse(json, 'type')
コード例 #54
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.record_name = parse(json, 'recordName')
         self.zone_id = parse(json, 'zoneID')
         self.action = parse(json, 'action')
コード例 #55
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.comparator = parse(json, 'comparator')
         self.field_name = parse(json, 'fieldName')
         self.field_value = parse(json, 'fieldValue')
         self.distance = parse(json, 'distance')
コード例 #56
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.zone_name = parse(json, 'zoneName')
コード例 #57
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.zone_id = ZoneID(parse(json, 'zoneID'))
         self.sync_token = parse(json, 'syncToken')
         self.atomic = parse(json, 'atomic')
コード例 #58
0
ファイル: datatypes.py プロジェクト: Baza207/CloudKitPy
 def __init__(self, json=None):
     if json is not None:
         self.field_name = parse(json, 'fieldName')
         self.ascending = parse(json, 'ascending')
         self.relative_location = parse(json, 'relativeLocation')