Esempio n. 1
0
class Hololive(ServiceBase):
    @rpc(String, Unicode, _returns=Iterable(String))
    def algoritmo(self, nombre, data):   
        _buckets = { 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], 11:[], 12:[]}
        base64_decoded = 0
        base64_decoded = base64.decodebytes(bytes(data, 'utf-8'))
        strng = base64_decoded.decode('utf-8')
        #data = a.Decode(data)
        a.ParseData(_buckets, _grupos, strng)
        a.EscribirExcel(_buckets, _carreras, nombre)
        yield a.EncodeFile(nombre).decode('utf-8')
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        """Docstring for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """
        for i in range(times):
            yield u'Hello, %s' % name
Esempio n. 3
0
    class ReaderService(ReaderService):
        @rpc(M(UnsignedInteger32),
             _returns=T,
             _in_message_name='get_%s' % T_name,
             _in_variable_names={'obj_id': "%s_id" % T_name})
        def get(ctx, obj_id):
            return ctx.udc.session.query(T).filter_by(id=obj_id).one()

        @rpc(_returns=Iterable(T), _in_message_name='get_all_%s' % T_name)
        def get_all(ctx):
            return ctx.udc.session.query(T).order_by(T.id)
Esempio n. 4
0
class SearchTeacher(ServiceBase):
    @rpc(Unicode, _returns=Iterable(AnyDict))
    def search_teacher(ctx, name):
        if soap_authenticate_api_key(ctx):
            if name:
                data = TeacherDetails.objects.filter(
                    teacher_name=name).values()
                if data:
                    return [{i: j} for i, j in data[0].items()]
                return [{"status": 'No Data Found'}]
        return [{'key': "invalid"}]
Esempio n. 5
0
class DeleteParent(ServiceBase):
    @rpc(Unicode, _returns=Iterable(AnyDict))
    def delete_parent(ctx, name):
        if soap_authenticate(ctx):
            if name:
                delete_value = ParentsDetails.objects.filter(
                    parent_name=name).delete()
                if delete_value[0]:
                    return [{'deleted': True}]
            return [{"status": 'No Data Found'}]
        return [{'credentials': "invalid"}]
Esempio n. 6
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, _returns=Iterable(Unicode), _body_style='bare')
    def say_hello(ctx, name):
        """
        Docstrings for service methods appear as documentation in the wsdl
        <b>what fun</b>
        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        """

        return u'Hello, %s' % name
Esempio n. 7
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name: the name to say hello to
        @param times: the number of times to say hello
        @return  When returning an iterable, you can use any type of python iterable. Here, we chose to use generators.
        """

        for i in range(times):
            yield u'Hello, %s' % name
Esempio n. 8
0
class CampaignCrudService(ServiceBase):

    # create campaign if it's possible and return id
    @rpc(Campaign, _returns=UnsignedInteger32)
    def create_campaign(ctx, campaign):
        campaign_id = -1
        if campaign.id is None:
            scoped_session = start_engine()
            session = scoped_session()
            campaign_facade = CampaignFacade(session)
            campaign_facade.create_campaign(campaign=campaign)
            campaign_id = campaign_facade.get_campaign_by_name(
                name=campaign.name).id
            session.close()
        return campaign_id

    # delete campaign in cascade
    @rpc(Campaign)
    def delete_campaign(ctx, campaign):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        facade.delete_module(campaign=campaign)
        session.close()

    # update campaign
    @rpc(Campaign)
    def update_campaign(ctx, campaign):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        facade.update_module(module=campaign)
        session.close()

    # return campaign by id
    @rpc(Integer, _returns=Campaign)
    def get_campaign_by_id(ctx, campaign_id):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        campaign = facade.get_campaign_by_id(campaign_id=campaign_id)
        session.close()
        return campaign

    # return campaigns by module_id
    @rpc(Integer, _returns=Iterable(Campaign))
    def get_module_campaigns(ctx, module_id):
        scoped_session = start_engine()
        session = scoped_session()
        facade = CampaignFacade(session)
        campaigns = facade.get_campaigns_from_module_id(module_id=module_id)
        session.close()
        return campaigns
Esempio n. 9
0
class CourseWebService(ServiceBase):

	# 获得课程统计信息
	@srpc(_returns=Iterable(CourseStatisticsInfo))
	def getCourseStatistics():
		return CourseService.getCourseStatistics()

	# 获得学生统计信息
	@srpc(_returns=Iterable(StudentStatisticsInfo))
	def getStudentStatistics():
		return StudentService.getStudentStatistics()

	# 获取课程信息
	@srpc(_returns=Iterable(CourseInfo))
	def getAllCourseInfo():
		return CourseService.getAllCourseInfo()

	# 根据ID列表获取相应课程信息
	@srpc(Unicode, _returns=Iterable(CourseInfo))
	def getCourseByIds(idStr):
		return CourseService.getCourseInfoByIds(idStr.split(','))
Esempio n. 10
0
class Groups(ServiceBase):
    @rpc(_returns=Iterable(Unicode))
    def get_groups(ctx):
        groups_list = groups_get()
        for groups in groups_list:
            yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, _returns=Iterable(Unicode))
    def get_by_id_groups(ctx, id):
        groups = groups_get_id(id)
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, _returns=Iterable(Unicode))
    def create_groups(ctx, name):
        groups = groups_create({'name': name})
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, Unicode, _returns=Iterable(Unicode))
    def update_groups(ctx, id, name=None):
        groups = groups_update(id, {'name': name})
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, _returns=Iterable(Unicode))
    def delete_groups(ctx, id):
        groups = groups_delete(id)
        yield u'groups: %s' % groups.serialize_normal()

    @rpc(Unicode, Unicode, _returns=Iterable(Unicode))
    def add_member(ctx, id_group, id_user):
        groups = add_member(id_group, id_user)
        yield u'groups: %s' % groups.serialize_normal()
Esempio n. 11
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode,Unicode,_returns=Iterable(Unicode))
    def say_hello(ctx, name, times):
        a = times.split(",")
        lat = a[0]
        lon = a[1]
        dynamodb = boto3.resource('dynamodb',
                        aws_access_key_id='AKIAJH7QCO7VUC43PFYQ',
                        aws_secret_access_key='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'
                        , region_name='us-east-2')
        dynamodb_client = boto3.client('dynamodb', aws_access_key_id = 'AKIAJH7QCO7VUC43PFYQ',
                        aws_secret_access_key = '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',
                        region_name = 'us-east-2')
        
        
        existing_tables = dynamodb_client.list_tables()['TableNames']

        if 'ItemTracker_tbl' not in existing_tables:

        # Create the DynamoDB table.

            table = dynamodb.create_table(TableName='ItemTracker_tbl',
                                          KeySchema=[{'AttributeName': 'itemtrackerId'
                                          , 'KeyType': 'HASH'}],
                                          AttributeDefinitions=[{'AttributeName': 'itemtrackerId'
                                          , 'AttributeType': 'S'}],
                                          ProvisionedThroughput={'ReadCapacityUnits': 5,
                                          'WriteCapacityUnits': 5})

            # Wait until the table exists.

            table.meta.client.get_waiter('table_exists').wait(TableName='ItemTracker_tbl')

        table = dynamodb.Table(name=u'ItemTracker_tbl')
        response  = table.query(KeyConditionExpression=Key('itemtrackerId').eq(name))

        if response['Count'] >0:
            table.update_item(Key={'itemtrackerId': name},
                              UpdateExpression='SET lat = list_append(lat, :i)'
                              , ExpressionAttributeValues={':i': [lat]},
                              ReturnValues='UPDATED_NEW')
            table.update_item(Key={'itemtrackerId': name},
                              UpdateExpression='SET lon = list_append(lon, :i)'
                              , ExpressionAttributeValues={':i': [lon]},
                              ReturnValues='UPDATED_NEW')
        else:
            print(name)
            table.put_item(Item={
                'itemtrackerId':name,
                'lat':[lat],
                'lon':[lon]
                })
Esempio n. 12
0
class CrimeAPIService(ServiceBase):
	@srpc(float, float, float, float, _returns=Iterable(Unicode))
	def checkcrime(lat, lon, radius, key):
		output_dict = {}
		payload={'lat':lat,'lon':lon, 'radius':radius, 'key':'.'}
       		r=requests.get('https://api.spotcrime.com/crimes.json',params=payload) 
       		crime_data=r.json()
       		#yield crime_data

       		dict_crimetype = {}
       		dictCrimeTime = dictCrimeTimeInit()
		streetList =[]
       		for crime in (crime_data["crimes"]):
			
			# get crime type
	       		if (crime["type"]) not in dict_crimetype:
				dict_crimetype[crime["type"]] = 1
	       		else:
		       		dict_crimetype[crime["type"]] += 1
			
			# get crime time
			tme = time.strptime(crime["date"], "%m/%d/%y %I:%M %p")
			t = tme.tm_hour*60 + tme.tm_min
			if t == 0:
				t = 24*60
			t = t - 1
			i = t//(3*60)
			dictCrimeTime[dictCrimeTimeHelper[i]] += 1

			# get crime street
			#yield crime["address"]
			st = re.sub(r'\d+ BLOCK OF ',"", crime["address"] ) 
			st = re.sub(r'\d+ BLOCK ',"", st)
			st = re.sub(r'^\d+ ',"", st)
			for street in re.split(r' & | AND | and | And ', st):
				streetList.append(string.rstrip(string.lstrip(street)))

		#yield dict_crimetype
		output_dict["total_crime"] = len(crime_data["crimes"])
		output_dict["crime_type_count"] = dict_crimetype
		output_dict["event_time_count"] = dictCrimeTime
		
		# set up top 3 streets
		cnt = collections.Counter(streetList).most_common(3)
		top3 = []
		for entry in cnt:
			top3.append(entry[0])

		output_dict["the_most_dangerous_streets"] = top3
		#yield cnt

		yield output_dict
Esempio n. 13
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(ctx, name, times):
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """
        for i in range(times):
            yield u'Hello, %s' % name

    @rpc(Array(Name), _returns=Iterable(Unicode))
    def say_hello_plus(self, name_plus):
        print('---', name_plus)
        if not name_plus:
            yield 'None'

        for name in name_plus:
            print(name.first_name)
            print(name.last_name)
            yield name.first_name + name.last_name
Esempio n. 14
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello(self, name, times):
        for i in range(times):
            yield 'Hello, %s' % name

    @rpc(Unicode, Integer, _returns=Unicode)
    def say_hello2(self, name, times):
        return ("yes")

    @rpc(Float, Float, _returns=Float)
    def livraison(self, poids, distance):
        return poids * (distance * (1 / 4))
Esempio n. 15
0
class HelloWorldService(ServiceBase):
    @rpc(String, UnsignedInteger, _returns=Iterable(String))
    def say_hello(ctx, name, times):
        """
        Docstrings for service methods do appear as documentation in the
        interface documents. <b>What fun!</b>
        :param name: The name to say hello to
        :param times: The number of times to say hello
        :returns: An array of 'Hello, <name>' strings, repeated <times> times.
        """

        for i in range(times):
            yield 'Hello, %s' % name
Esempio n. 16
0
class SomeService(Service):
    @rpc(Unicode, Integer, _returns=Iterable(Unicode))
    def say_hello_as_file(ctx, name, times):
        if isinstance(ctx.transport, HttpTransportContext):
            file_name = "{}.xml".format(ctx.descriptor.name)

            ctx.transport.set_mime_type("application/xml")

            # Force download
            ctx.transport.add_header('Content-Disposition', 'attachment',
                                                             filename=file_name)

        for i in range(times):
            yield u'Hello, %s' % name
Esempio n. 17
0
class HelloWorldService(ServiceBase):
    @rpc(Integer, _returns=Iterable(Integer))
    def say_fibonacci(ctx, times):
        """Docstrings for service methods appear as documentation in the wsdl.
        <b>What fun!</b>
        @param name the name to say hello to
        @param times the number of times to say hello
        @return the completed array
        """
        a, b = 0, 1
        for i in range(times):
            if (a > times): break
            yield a
            a, b = b, a + b
class GlobalTextAnalyzer(ServiceBase):

    @rpc(Unicode, Unicode, _returns=Integer)
    def count_one_word(self, text, word):
        return sum(word == text_word for text_word in re.split(r'\W', text, flags=re.UNICODE))

    @rpc(Unicode, _returns=Iterable(CharCount))
    def count_characters(self, text):
        char_counts = {}
        for c in text:
            if c not in char_counts:
                char_counts[c] = 0
            char_counts[c] += 1
        for char, count in char_counts.iteritems():
            yield CharCount(char=char, count=count)

    @rpc(Unicode, _returns=Iterable(WordCount))
    def count_words(self, text):
        word_counts = {}
        for word in re.split(r'\W', text, flags=re.UNICODE):
            if word not in word_counts:
                word_counts[word] = 0
            word_counts[word] += 1
        for word, count in word_counts.iteritems():
            yield WordCount(word=word, count=count)

    @rpc(Unicode, _returns=Unicode)
    def make_caps(self, text):
        return text.upper()

    @rpc(Unicode, _returns=Iterable(WordCount))
    def count_words_on_web_page(self, url):

        html = get_page_content(url)
        for word, count in count_words_in_html(html):
            yield WordCount(word=word, count=count)
Esempio n. 19
0
class HelloWorldService(Service):
    @rpc(Unicode(default='World'),
         UnsignedInteger(default=5),
         _returns=Iterable(Unicode))
    def say_hello(ctx, name, times):
        # workaround for Python2's lacking of nonlocal
        times = [times]

        def _cb(push):
            # This callback is called immediately after the function returns.

            if times[0] > 0:
                times[0] -= 1

                data = u'Hello, %s' % name
                print data

                # The object passed to the append() method is immediately
                # serialized to bytes and pushed to the response stream's
                # file-like object.
                push.append(data)

                # When a push-callback returns anything other than a deferred,
                # the response gets closed.
                return deferLater(reactor, 1, _cb, push)

        # This is Spyne's way of returning NOT_DONE_YET
        return Iterable.Push(_cb)

    @rpc(Unicode(default='World'), _returns=Iterable(Unicode))
    def say_hello_forever(ctx, name):
        def _cb(push):
            push.append(u'Hello, %s' % name)
            return deferLater(reactor, 0.1, _cb, push)

        return Iterable.Push(_cb)
Esempio n. 20
0
class SalesAgencyService(ServiceBase):
    def find_sales_agency(self):
        sales_agency = None
        with Pyro4.locateNS() as ns:
            uri = ns.lookup("sales_agency")
            sales_agency = Pyro4.Proxy(uri)
        if not sales_agency:
            raise ValueError("no sales agency found!")
        return sales_agency
# remote call and defines type/order of soap parameters

    @srpc(_returns=Iterable(Unicode))
    def get_properties():
        sales_agency = self.find_sales_agency()
        return sales_agency.properties
Esempio n. 21
0
class HelloWorldService(ServiceBase):
    @rpc(Integer, _returns=str)
    def getOffer(ctx, id):
        try:
            offres_stage = get_offres_stage_from_json()
            for offre in offres_stage:
                if offre['id'] == id:
                    yield offre
        except:
            pass

    @rpc(_returns=Iterable(Integer))
    def getAvailableOffersIDs(ctx):
        for i in range(len(offres_stage)):
            yield i
Esempio n. 22
0
class ObjDetectorService(ServiceBase):
    @rpc(Unicode, _returns=Iterable(Unicode))
    def img_obj(self, image_file):
        img = cv2.imread(image_file)
        bboxs = detector(img)
        for label, value in bboxs.items():
            for v in value:
                x1 = str(round(v[0]))
                y1 = str(round(v[1]))
                x2 = str(round(v[2]))
                y2 = str(round(v[3]))
                score = str(round(v[4], 2))
                label = label
                ret = x1 + ',' + y1 + ',' + x2 + ',' + y2 + ',' + score + ',' + label
                yield ret
Esempio n. 23
0
    def say_hello_with_sleep(ctx, name, times, seconds):
        """Sends multiple hello messages by waiting given number of seconds
        inbetween."""

        times = [times]  # Workaround for Python 2's lacking of nonlocal

        def _cb(response):
            if times[0] > 0:
                response.append(
                    "Hello %s, sleeping for %f seconds for %d more time(s)." %
                    (name, seconds, times[0]))
                times[0] -= 1
                return deferLater(reactor, seconds, _cb, response)

        return Iterable.Push(_cb)
Esempio n. 24
0
class digitoService(ServiceBase):
    @rpc(Unicode, Unicode, _returns = Iterable(Unicode))
    def digito_verificador(ctx, rut, times):
        n_rut = rut.split('-')
        reversed_digits = map(int, reversed(str(n_rut[0])))
        factors = cycle(range(2, 8))
        s = sum(d * f for d, f in zip(reversed_digits, factors))
        mod = (-s) % 11
        if (mod == 10):
            mod = 'k'
        if (mod == 11):
            mod = 0
        if (str(mod) == n_rut[1]):
            yield ('Para el rut ' + str(rut) + ' ' + 'el digito verificador es '+ str(mod))
        else:
            yield('dv ingresado '+ str(n_rut[1]) + ' el dv correcto es '+ str(mod))
Esempio n. 25
0
    class CrudService(ServiceBase):
        @rpc(M(UnsignedInteger32),
             _returns=T,
             _in_message_name='get_%s' % T_name,
             _in_variable_names={'obj_id': "%s_id" % T_name})
        def get(ctx, obj_id):
            return ctx.udc.session.query(T).filter_by(id=obj_id).one()

        @rpc(M(T),
             _returns=UnsignedInteger32,
             _in_message_name='put_%s' % T_name,
             _in_variable_names={'obj': T_name})
        def put(ctx, obj):
            if obj.id is None:
                ctx.udc.session.add(obj)
                ctx.udc.session.flush()  # so that we get the obj.id value

            else:
                if ctx.udc.session.query(T).get(obj.id) is None:
                    # this is to prevent the client from setting the primary key
                    # of a new object instead of the database's own primary-key
                    # generator.
                    # Instead of raising an exception, you can also choose to
                    # ignore the primary key set by the client by silently doing
                    # obj.id = None in order to have the database assign the
                    # primary key the traditional way.
                    raise ResourceNotFoundError('%s.id=%d' % (T_name, obj.id))

                else:
                    ctx.udc.session.merge(obj)

            return obj.id

        @rpc(M(UnsignedInteger32),
             _in_message_name='del_%s' % T_name,
             _in_variable_names={'obj_id': '%s_id' % T_name})
        def del_(ctx, obj_id):
            count = ctx.udc.session.query(T).filter_by(id=obj_id).count()
            if count == 0:
                raise ResourceNotFoundError(obj_id)

            ctx.udc.session.query(T).filter_by(id=obj_id).delete()

        @rpc(_returns=Iterable(T), _in_message_name='get_all_%s' % T_name)
        def get_all(ctx):
            return ctx.udc.session.query(T)
Esempio n. 26
0
class HelloWorldService(ServiceBase):
    @rpc(_returns=Iterable(GraphPlotValue))
    def testDB(ctx):
        result = engine.execute('select * from dataSST')
        # for r in result:
        #     print(r)
        v = mapArray(result)

        return v

    @rpc(_returns=String)
    def listfoodService(ctx):

        my_schema = xmlschema.XMLSchema('./data/xsd/breakfast_menu.xsd')
        if (my_schema.is_valid('./data/xml/breakfast_menu.xml')):
            with open('./data/xml/breakfast_menu.xml') as f:
                resultXML = f.read()
            result = resultXML
        else:
            result = """<Error>Error NOT Valid</Error>"""

        return result

    @rpc(_returns=String)
    def getGrapXMLdata(ctx):

        results = engine.execute('select * from dataSST')
        dictTemp = []
        for r in results:
            tempData = {}
            tempData['date_use'] = r[3]
            tempData['x_lat'] = r[1]
            tempData['y_value'] = r[2]

            dictTemp.append(tempData)

        xml = dicttoxml.dicttoxml(dictTemp)

        my_schema = xmlschema.XMLSchema('./data/xsd/graphLat.xsd')
        root = etree.XML(xml)
        if (my_schema.is_valid(root)):
            result = xml
        else:
            result = """<Error>Error NOT Valid</Error>"""

        return result
Esempio n. 27
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, Integer, _returns=Array(Unicode))
    def say_hello(self, name, times):
        results = []
        for i in range(0, times):
            results.append('Hello {0}'.format(name))
        return results

    @rpc(Project, _returns=Unicode)
    def make_project(self, pro):
        return '{0}+{1}'.format(pro.name, pro.version)

    @rpc(Array(Project), _returns=Iterable(Unicode))
    def show_project(self, pros):
        if not pros:
            yield 'None'
        for pro in pros:
            yield pro.name + pro.version
Esempio n. 28
0
class HelloWorldService(ServiceBase):
    @rpc(Integer,
         _out_variable_names=list(offres_stage[0].keys()),
         _returns=[type(v) for v in offres_stage[0].values()])
    def getOffer(ctx, id):
        try:
            offres_stage = get_offres_stage_from_json()
            for offre in offres_stage:
                if offre['id'] == id:
                    for k, v in offre.items():
                        yield v
        except:
            pass

    @rpc(_returns=Iterable(Integer))
    def getAvailableOffersIDs(ctx):
        for i in range(len(offres_stage)):
            yield i
Esempio n. 29
0
class CurrenyConverterService(ServiceBase):
    @rpc(Unicode, Unicode, _returns=Iterable(Unicode))
    def getConversionRate(ctx, fromCurrency, toCurrency):
        url = 'http://api.fixer.io/latest?base=' + fromCurrency
        response = requests.get(url)
        #print('--    ')
        #print('date ' + response.json()['date'])
        #print('fromCurrency ' + fromCurrency)
        #print('toCurrency ' + toCurrency)
        yield response.json()['date']
        yield fromCurrency
        yield toCurrency
        if fromCurrency == toCurrency:
            #print('1')
            yield '1'
        else:
            #print(response.json()['rates'][toCurrency])
            yield str(response.json()['rates'][toCurrency])
        print('--    ')
Esempio n. 30
0
class HelloWorldService(ServiceBase):
    @rpc(Unicode, _returns=Iterable(Unicode))
    def say_hello(ctx, name):

        fh = open("./imagenes/captured.pgm", "wb")
        fh.write(base64.b64decode(name))
        fh.close()

        image = RecognizeFaces()

        if image is None:
            return None
        else:
            rut = str(imageId(image))

            if rut is None:
                return 'No hay registros asociados a la persona'
            else:
                return queryPerson(str(rut))