예제 #1
0
def MultispectralRGeocode(lat,lng):
    ticket = "76333D50-F9F4-4088-A9D7-DE5B09F9C27C"
    url  = "http://www.geoportal.com.br/xgeocoder/cxinfo.aspx?x="+lng+"&y="+lat+"&Ticket="+str(ticket)
    page = urllib2.urlopen(url)
    conteudo = page.read()
    page.close()
    geocodexml = ElementTree.fromstring(conteudo)
    address = geocodexml.findall("INFO")
     #self.stdout.write(address[0].text+","+address[0].get("NroIni")+"-"+address[0].get("NroFim")+","+address[0].get("Bairro")+","+address[1].text+"-"+address[2].text+","+address[0].get("CEP"))
    if (address != []):
        c = CachedGeocode(
            lat = float(lat),
            lng = float(lng),
            full_address = "",
            number = address[0].get("NroIni")+"-"+address[0].get("NroFim"),
            street = title(lower(address[0].text)),
            city = title(lower(address[1].text)),
            state = address[2].text,
            country = "Brasil",
            postal_code = address[0].get("CEP"),
            administrative_area = title(lower(address[0].get("Bairro")))
        )
        c.full_address = c.street+" "+c.number+", "+c.administrative_area+" - "+c.city+", "+c.state
        c.save()
        
        return [c.full_address,c.street+" "+c.number+", "+c.administrative_area,c.city,c.state,c.postal_code]
    else: 
        raise NotImplementedError
예제 #2
0
    def post(self, request):
        if User.objects.filter(email=request.data['email']).exists():
            errors = {'errors': {'email': 'Email already exists.'}}
            return Response(errors, status=status.HTTP_400_BAD_REQUEST)

        username = lower(request.data['first_name']) + lower(
            request.data['last_name'])
        user = User.objects.create(
            username=username,
            first_name=request.data['first_name'],
            # add lastname for the user only if it is a string, otherwise add empty string
            last_name=request.data['last_name']
            if not request.data['last_name'] == "1" else "",
            email=request.data['email'],
        )
        # save hashed password value
        user.set_password(request.data['password'])
        user.save()

        settings = UserSettings.objects.create()
        settings.save()

        profile = Profile.objects.create(
            user=user,
            settings=settings,
        )
        profile.save()

        serialized = ProfileSerializer(profile)
        if serialized:
            return Response(serialized.data, status=status.HTTP_201_CREATED)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)
예제 #3
0
def answer(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if lower(question.answer_text) == lower(request.POST['answer']):
        team = Team.objects.get(username=request.user.id)
        team.current_question += 1
        team.score += 2
        team.save()
        return HttpResponseRedirect(reverse('success'))
    else:
        return render(request, 'questions/question.html', {
            'question': question,
            'error_message': "Your answer is incorrect",
        })
예제 #4
0
 def form_valid(self, form):
     funcionario = form.save(commit=False)
     username = funcionario.nome.split(' ')[0] + funcionario.sobrenome.split(' ')[0]
     funcionario.empresa = self.request.user.funcionario.empresa
     funcionario.user = User.objects.create(username=lower(username))
     funcionario.save()
     return super(FuncionarioNovo, self).form_valid(form)
예제 #5
0
파일: tests.py 프로젝트: AgentK1729/django
 def test_non_string_input(self):
     # Filters shouldn't break if passed non-strings
     self.assertEqual(addslashes(123), '123')
     self.assertEqual(linenumbers(123), '1. 123')
     self.assertEqual(lower(123), '123')
     self.assertEqual(make_list(123), ['1', '2', '3'])
     self.assertEqual(slugify(123), '123')
     self.assertEqual(title(123), '123')
     self.assertEqual(truncatewords(123, 2), '123')
     self.assertEqual(upper(123), '123')
     self.assertEqual(urlencode(123), '123')
     self.assertEqual(urlize(123), '123')
     self.assertEqual(urlizetrunc(123, 1), '123')
     self.assertEqual(wordcount(123), 1)
     self.assertEqual(wordwrap(123, 2), '123')
     self.assertEqual(ljust('123', 4), '123 ')
     self.assertEqual(rjust('123', 4), ' 123')
     self.assertEqual(center('123', 5), ' 123 ')
     self.assertEqual(center('123', 6), ' 123  ')
     self.assertEqual(cut(123, '2'), '13')
     self.assertEqual(escape(123), '123')
     self.assertEqual(linebreaks_filter(123), '<p>123</p>')
     self.assertEqual(linebreaksbr(123), '123')
     self.assertEqual(removetags(123, 'a'), '123')
     self.assertEqual(striptags(123), '123')
예제 #6
0
def get_model_core(model):
    """
    Return core view of given model or None
    """
    model_label = lower('%s.%s' %
                        (model._meta.app_label, model._meta.object_name))
    return registered_model_cores.get(model_label)
예제 #7
0
 def test_non_string_input(self):
     # Filters shouldn't break if passed non-strings
     self.assertEqual(addslashes(123), '123')
     self.assertEqual(linenumbers(123), '1. 123')
     self.assertEqual(lower(123), '123')
     self.assertEqual(make_list(123), ['1', '2', '3'])
     self.assertEqual(slugify(123), '123')
     self.assertEqual(title(123), '123')
     self.assertEqual(truncatewords(123, 2), '123')
     self.assertEqual(upper(123), '123')
     self.assertEqual(urlencode(123), '123')
     self.assertEqual(urlize(123), '123')
     self.assertEqual(urlizetrunc(123, 1), '123')
     self.assertEqual(wordcount(123), 1)
     self.assertEqual(wordwrap(123, 2), '123')
     self.assertEqual(ljust('123', 4), '123 ')
     self.assertEqual(rjust('123', 4), ' 123')
     self.assertEqual(center('123', 5), ' 123 ')
     self.assertEqual(center('123', 6), ' 123  ')
     self.assertEqual(cut(123, '2'), '13')
     self.assertEqual(escape(123), '123')
     self.assertEqual(linebreaks_filter(123), '<p>123</p>')
     self.assertEqual(linebreaksbr(123), '123')
     self.assertEqual(removetags(123, 'a'), '123')
     self.assertEqual(striptags(123), '123')
예제 #8
0
def parse():
    tag_descr = DescriptionTag.objects.filter(description='')
    print('Check needed parse?')
    if tag_descr:
        print('PARSE DESCRIPTION TAG...')
        for descr in tag_descr:
            tag = descr.tag
            page_url = 'https://stackoverflow.com/tags/' + lower(
                tag.name) + '/info'
            try:
                response = urllib.request.urlopen(page_url).read()
                page = fromstring(response)
                try:
                    description_tag = page.xpath(
                        '//div[@class="post-text"]/div[@class="welovestackoverflow"]/p'
                    )
                    description_tag = description_tag[0].text.strip()
                except IndexError:
                    description_tag = page.xpath(
                        '//div[@class="question"]/div[@class="welovestackoverflow"]/div/p[1]'
                    )
                    description_tag = description_tag[0].text.strip()
            except OSError:
                description_tag = 'Unknown tag'
            descr.description = description_tag
            descr.save()
            print(tag)
            print('description_tag saved')
예제 #9
0
def parse_tags(tagstring):
    """
    Parses tag input, with multiple word input being activated and
    delineated by commas and double quotes. Quotes take precedence, so
    they may contain commas.

    Returns a sorted list of unique tag names.

    Ported from Jonathan Buchanan's `django-tagging
    <http://django-tagging.googlecode.com/>`_
    """
    if not tagstring:
        return []

    # Should all tags be handled as lowercase?
    try:
        settings.TAGGIT_FORCE_LOWERCASE
        tagstring = lower(force_unicode(tagstring))
    except:
        tagstring = force_unicode(tagstring)

    tagstring = tagstring.replace(u',', ', ')
    words = split_strip(tagstring)

    return words
예제 #10
0
def app_label(obj):
    """
    Returns an objects app label.
    """
    try:
        return lower(obj._meta.object_name)
    except AttributeError:
        return ''
예제 #11
0
def app_label(obj):
    """
    Returns an objects app label.
    """
    try:
        return lower(obj._meta.object_name)
    except AttributeError:
        return ''
예제 #12
0
def cep_view(request, cep):
    url = 'https://viacep.com.br/ws/' + cep + '/json/'
    response = requests.get(url)
    data_cep = response.json()
    city_name = data_cep['localidade']
    City.objects.get_or_create(city_name=lower(city_name))

    return HttpResponse("Created city!")
예제 #13
0
 def register(self, generic_core):
     if (hasattr(generic_core, 'model')):
         model_label = lower('%s.%s' %
                             (generic_core.model._meta.app_label,
                              generic_core.model._meta.object_name))
         registered_model_cores[model_label] = generic_core
     registered_cores.append(generic_core)
     return generic_core
예제 #14
0
def model_resources_to_dict():
    from resource import resource_tracker

    model_resources = {}
    for resource in resource_tracker:
        if hasattr(resource, 'model') and issubclass(resource.model, models.Model):
            model = resource.model
            model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
            model_resources[model_label] = resource
    return model_resources
예제 #15
0
def model_resources_to_dict():
    from pyston.resource import resource_tracker

    model_resources = {}
    for resource in resource_tracker:
        if hasattr(resource, 'model') and issubclass(resource.model, models.Model):
            model = resource.model
            model_label = lower('{}.{}'.format(model._meta.app_label, model._meta.object_name))
            model_resources[model_label] = resource
    return model_resources
예제 #16
0
def model_handlers_to_dict():
    from handler import handler_tracker

    model_handlers = {}
    for handler in handler_tracker:
        if hasattr(handler, 'model'):
            model = handler.model
            model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
            model_handlers[model_label] = handler
    return model_handlers
예제 #17
0
    def register(self, universal_view_class):
        universal_view = universal_view_class(self.name)
        if not universal_view.menu_group in self._registry.keys():
            raise NoMenuGroup('MENU_GROUPS must contains %s for site %s' % (universal_view.menu_group, self.name))

        self._registry[universal_view.menu_group].views[universal_view.menu_subgroup] = universal_view
        if (hasattr(universal_view, 'model')):
            model_label = lower('%s.%s' % (universal_view.model._meta.app_label, universal_view.model._meta.object_name))
            registered_model_views[model_label] = universal_view
        registered_views.append(universal_view)
예제 #18
0
파일: views.py 프로젝트: Hi-Light/my_blog
def create_user(BaseMixin, request):
    if request.method == 'POST':
        url = request.POST['url']
        name = request.POST['name']
        email = lower(request.POST['email'])
        password = request.POST['password1']
        MyUser.objects.create_user(name=name, email=email, password=password)
        user = auth.authenticate(username=email, password=password)
        auth.login(request, user)
        return HttpResponseRedirect(url)
    else:
        return render(request, 'register.html')
예제 #19
0
def buscarLicor(request):
    form = SearchForm()
    categorias = Categoria.objects.all().order_by('nombre')
    if request.method == 'POST':
        form = SearchForm(request.POST, request.FILES)
        if form.is_valid():
            busqueda = form.cleaned_data["busqueda"]
            graduacionMinima = form.cleaned_data["graduacionMinima"]
            graduacionMaxima = form.cleaned_data["graduacionMaxima"]
            precioMinimo = form.cleaned_data["precioMinimo"]
            precioMaximo = form.cleaned_data["precioMaximo"]
            elem = request.POST["elem"]
            page = request.POST["page"]
            groupDic = {}
            if precioMinimo and precioMaximo:
                groupDic["precio"] = (precioMinimo, precioMaximo)
            if graduacionMinima and graduacionMaxima:
                groupDic["graduacion"] = (graduacionMinima, graduacionMaxima)
            orden = request.POST["order"]
            categoriaP = request.POST.getlist("categoria")
            categoria = []
            for cat in categoriaP:
                categoria.append(
                    (Categoria.objects.get(id=cat)).nombre.lower())
            busqueda = lower(busqueda)
            licoresId = listarPorAtributo(busqueda=busqueda,
                                          categoria=categoria,
                                          order=orden,
                                          groupDic=groupDic,
                                          nElementosPagina=int(elem),
                                          pagina=int(page))
            licores = getLicores(licoresId)
            return render(
                request, 'search_licor.html', {
                    'licores': licores,
                    'form': form,
                    'categorias': categorias,
                    'elem': elem,
                    'page': page
                })
    licoresId = listarPorAtributo()
    licores = getLicores(licoresId)
    return render(
        request, 'search_licor.html', {
            'form': form,
            'licores': licores,
            'categorias': categorias,
            'elem': 20,
            'page': 1
        })
예제 #20
0
    def register(self, universal_view_class):
        universal_view = universal_view_class(self.name)
        if not universal_view.menu_group in self._registry.keys():
            raise NoMenuGroup('MENU_GROUPS must contains %s for site %s' %
                              (universal_view.menu_group, self.name))

        self._registry[universal_view.menu_group].views[
            universal_view.menu_subgroup] = universal_view
        if (hasattr(universal_view, 'model')):
            model_label = lower('%s.%s' %
                                (universal_view.model._meta.app_label,
                                 universal_view.model._meta.object_name))
            registered_model_views[model_label] = universal_view
        registered_views.append(universal_view)
예제 #21
0
def subject_autocomplete(request, entity_type):
    search_text = lower(request.GET["term"] or "")
    database_name = get_database_name(request.user)
    dbm = get_database_manager(request.user)
    form_model = get_form_model_by_entity_type(dbm, [entity_type.lower()])
    subject_name_field = get_field_by_attribute_value(form_model, 'name', 'name')
    es_field_name_for_subject_name = es_questionnaire_field_name(subject_name_field.code, form_model.id)
    subject_short_code_field = get_field_by_attribute_value(form_model, 'name', 'short_code')
    es_field_name_for_short_code = es_questionnaire_field_name(subject_short_code_field.code, form_model.id)
    query = elasticutils.S().es(urls=ELASTIC_SEARCH_URL, timeout=ELASTIC_SEARCH_TIMEOUT).indexes(database_name).doctypes(lower(entity_type)) \
        .query(or_={es_field_name_for_subject_name + '__match': search_text,
                    es_field_name_for_subject_name + '_value': search_text,
                    es_field_name_for_short_code + '__match': search_text,
                    es_field_name_for_short_code + '_value': search_text}) \
        .values_dict()
    resp = [{"id": r[es_field_name_for_short_code], "label": r[es_field_name_for_subject_name]} for r in
            query[:min(query.count(), 50)]]
    return HttpResponse(json.dumps(resp))
예제 #22
0
def get_city_view(request, city_name):
    url = 'https://api.hgbrasil.com/weather?array_limit=2&fields=only_results,temp,city_name,results,tem,date,time&key=6698769b&city_name=' + city_name

    response = requests.get(url)
    if response:
        context = response.json()
        new_city, created = City.objects.get_or_create(
            city_name=lower(city_name))
        datetime_weather = context['date'] + " " + context['time']
        datetime_weather_formatted = datetime.strptime(
            datetime_weather, '%d/%m/%Y %H:%M').strftime("%Y-%m-%d %H:%M:%S")

        Temperatures.objects.create(city=new_city,
                                    date=datetime_weather_formatted,
                                    temperature=context['temp'])

        return HttpResponse("Add!")
    else:
        return HttpResponse("Chave API Bloqueada!")
예제 #23
0
    def drawText(self, p, x, y, contato):

        fs = int(self.impresso.fontsize)

        textobject = p.beginText()

        if contato.pronome_tratamento:
            textobject.setTextOrigin(x, y - fs * 0.8)
            textobject.setFont("Helvetica", fs * 0.8)
            textobject.textOut(
                getattr(contato.pronome_tratamento,
                        'enderecamento_singular_%s' % lower(contato.sexo)))
            textobject.moveCursor(0, fs)
        else:
            textobject.setTextOrigin(x, y - fs)

        textobject.setFont("Helvetica-Bold", fs)
        textobject.textOut(contato.nome)

        p.drawText(textobject)
예제 #24
0
파일: reports.py 프로젝트: cmjatai/cmj
    def drawText(self, p, x, y, contato):

        fs = int(self.impresso.fontsize)

        textobject = p.beginText()

        if contato.pronome_tratamento:
            textobject.setTextOrigin(x, y - fs * 0.8)
            textobject.setFont("Helvetica", fs * 0.8)
            textobject.textOut(
                getattr(contato.pronome_tratamento,
                        'enderecamento_singular_%s' % lower(contato.sexo)))
            textobject.moveCursor(0, fs)
        else:
            textobject.setTextOrigin(x, y - fs)

        textobject.setFont("Helvetica-Bold", fs)
        textobject.textOut(contato.nome)

        p.drawText(textobject)
예제 #25
0
파일: main.py 프로젝트: basetwode/cypetulip
    def form_valid(self, form):
        order_details = OrderDetail.objects.get(uuid=self.kwargs['uuid'])
        order_details.contact = order_details.shipment_address.contact
        order_details.save()

        payment_details = PaymentDetail.objects.filter(order_detail=order_details)
        payment_details.delete()

        if not 'method' in self.request.POST:
            return self.form_invalid(form)
        choosen_payment_method = PaymentMethod.objects.get(id=self.request.POST['method'])
        form = PaymentFormFactory(choosen_payment_method.name, self.request.POST)
        legal_form = LegalForm(self.request.POST)
        if form.is_valid() and legal_form.is_valid():
            payment_instance = form.save(commit=False)
            payment_instance.user = order_details.contact
            payment_instance.order_detail = order_details
            payment_instance.method = PaymentMethod.objects.get(id=self.request.POST['method'])
            payment_instance.save()
            return redirect(
                reverse('payment:%s' % lower(payment_instance.method.name), kwargs={'uuid': self.kwargs['uuid']}))
        else:
            return self.form_invalid(form)
예제 #26
0
def initialize(domain_local, lang_local, res_local, code_local):
    global options
    global browser

    global domain
    global lang
    global res
    global code

    options = webdriver.ChromeOptions()
    options.add_argument('--no-sandbox')
    options.add_argument('--ignore-certificate-errors')
    options.add_argument('--headless')
    options.add_argument("--test-type")
    options.add_argument('--disable-dev-shm-usage')
    browser = webdriver.Chrome(options=options)

    if not domain_local:
        domain = 'https://player.tvmucho.com'

    if not lang_local:
        lang = "English"

    if not code_local:
        code = "000000"
        browser.execute_script(
            ("localStorage.setItem('activationcode', '{0}')").format(code))

    if res_local:
        res = lower(res_local)
        window_width = re.search(r"\d*(?=x)", res).group()
        window_height = re.search(r"(?<=x)\d*", res).group()
    else:
        window_width = "1920"
        window_height = "1080"

    browser.set_window_size(window_width, window_height)
예제 #27
0
from helper.from_file import format_from_file
from django.template.defaultfilters import lower


def main(lenght=40, justify=False):
    #Lê todo o arquivo e processa (cuidado com o tamanho do arquivo)
    #Processa uma string
    formater = Formatter(lenght, justify)
    text = formater.text_format(
        "In the beginning God created the heavens and the earth. Now the earth was formless and empty, darkness was over the surface of the deep, and the Spirit of God was hovering over the waters.\n\nAnd God said, \"Let there be light,\" and there was light. God saw that the light was good, and he separated the light from the darkness. God called the light \"day,\" and the darkness he called \"night.\" And there was evening, and there was morning - the first day."
    )
    print(text)

    #Processa a partir de um arquivo
    text = format_from_file("helper/text.txt", lenght, justify)
    print(text)


if __name__ == "__main__":
    lenght = 40
    if len(sys.argv) > 1:
        try:
            lenght = int(sys.argv[1])
        except:
            lenght = 40

    justify = False
    if len(sys.argv) > 2:
        justify = True if lower(sys.argv[2]) == 'true' else False

    main(lenght, justify)
예제 #28
0
 def test_unicode(self):
     # uppercase E umlaut
     self.assertEqual(lower('\xcb'), '\xeb')
예제 #29
0
파일: tests.py 프로젝트: AgentK1729/django
    def test_lower(self):
        self.assertEqual(lower('TEST'), 'test')

        # uppercase E umlaut
        self.assertEqual(lower('\xcb'), '\xeb')
예제 #30
0
from django.template.defaultfilters import upper, lower

# str len

str = "hello"
print(len(str))

#upper
print(upper(str))
print(lower(str))

str1 = "world : str1"

str2 = str.format("test")
print(str2)

x = "x:hello".format(str1)
print(x + str2)

#Tuples and List

tuple = (1, 2, 3, 4, 5)
print(tuple)
print(tuple[0:2])

list = [1, 2, 3, 4, 5]
print(list)
print(list[0:2])
list.append(6)
print(list)
sublist = [7, 8, 9]
예제 #31
0
def is_content_type(obj, arg):
    try:
        ct = lower(obj._meta.object_name)
        return ct == arg
    except AttributeError:
        return ''
예제 #32
0
from django.template.defaultfilters import upper, lower

name = "hussein alrubaye"
# find number of character in string
Strlen = len(name)
print(Strlen)
# upper case to string
print(upper(name))
#lower case to string
print(lower(name))
title = "your grade is {}".format(79)
print(title)
# concat to string
str = "San Fransisco{}".format(" is nice place")
print(str)
예제 #33
0
def MaplinkRGeocode(lat,lng):
    
    ticket = "awFhbDzHd0vJaWVAzwkLyC9gf0LhbM9CyxSLyCH8aTphbIOidIZHdWOLyCtq"

    url = "http://webservices.apontador.com.br"
    
    xml = '''<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><getAddress xmlns="http://webservices.maplink2.com.br"><point><x>'''+str(lng)+'''</x><y>'''+str(lat)+'''</y></point><token>'''+str(ticket)+'''</token><tolerance>'''+str(10)+'''</tolerance></getAddress></soap:Body></soap:Envelope>'''
    
    try:
        conn = httplib2.Http(timeout=3)
        headers = {"Content-type":"text/xml; charset=\"UTF-8\"","SOAPAction":"http://webservices.maplink2.com.br/getAddress","Host":"teste.webservices.apontador.com.br"}
        resp, content = conn.request(url+ "/webservices/v3/AddressFinder/AddressFinder.asmx", "POST", body=xml,headers=headers)
        response = content
        conteudo = content
    #try:
    #    conn.request("POST", "/webservices/v3/AddressFinder/AddressFinder.asmx", xml, headers)
    #    response = conn.getresponse()
     #   conteudo = response.read()
     #   conn.close()
       
    except Exception as err:
      print(err)
      raise NotImplementedError

    if resp.status == 200:
        try:
            #print conteudo
            gxml = ElementTree.fromstring(conteudo)
            
            street = gxml.find(".//{http://webservices.maplink2.com.br}street")
            if street.text is None: street.text = ""
            city = gxml.find(".//{http://webservices.maplink2.com.br}name")
            if city.text is None: city.text = ""
            state = gxml.find(".//{http://webservices.maplink2.com.br}state")
            if state.text is None: state.text = ""
            number = gxml.find(".//{http://webservices.maplink2.com.br}houseNumber")
            if number.text is None: number.text = ""
            postal = gxml.find(".//{http://webservices.maplink2.com.br}zip")
            if postal.text is None: postal.text = ""
            
            c = CachedGeocode(
                lat = float(lat),
                lng = float(lng),
                full_address = "",
                number = number.text,
                street = title(lower(street.text)),
                city = title(city.text),
                state = state.text,
                country = "Brasil",
                postal_code = postal.text,
                #administrative_area = title(lower(address[0].get("Bairro")))
            )
        
            c.full_address = c.street+" "+ c.number+", "+c.city+", "+c.state
            #try:
            #    c.save()
            #except:
            #    pass
        except Exception as err:
            print(err)
            pass
        try:
            return [c.full_address,c.street+" "+c.number,c.city,c.state,c.postal_code]
        except TypeError as err:
            print (err)
            print c.full_address, "str>", c.street,"num>", c.number,"cty>",c.city,"sta>" , c.state,"pos>",c.postal_code,c.lat,c.lng
        return [c.full_address,]
    else:
        pass
예제 #34
0
 def testNoSummary(self):
     """Testing review requests with no summary"""
     from django.template.defaultfilters import lower
     review_request = ReviewRequest()
     lower(unicode(review_request))
예제 #35
0
 def test_lower(self):
     self.assertEqual(lower("TEST"), "test")
예제 #36
0
def get_handler_of_model(model):
    model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
    return model_handlers_to_dict().get(model_label)
예제 #37
0
 def full_name(self):
     full_name = self.user.first_name + ' ' + self.user.last_name
     if len(full_name) > 15:
         return lower(full_name)
     return full_name
예제 #38
0
def get_model_view(model):
    model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
    return registered_model_views.get(model_label)
예제 #39
0
 def test_non_string_input(self):
     self.assertEqual(lower(123), "123")
예제 #40
0
 def test_unicode(self):
     # uppercase E umlaut
     self.assertEqual(lower("\xcb"), "\xeb")
예제 #41
0
    def createParagraphs(self, contato, stylesheet):

        cleaned_data = self.filterset.form.cleaned_data

        imprimir_cargo = (cleaned_data['imprimir_cargo'] == 'True')\
            if 'imprimir_cargo' in cleaned_data and\
            cleaned_data['imprimir_cargo'] else False

        local_cargo = cleaned_data['local_cargo']\
            if 'local_cargo' in cleaned_data and\
            cleaned_data['local_cargo'] else ''

        story = []

        linha_pronome = ''
        prefixo_nome = ''

        if contato.pronome_tratamento:
            if 'imprimir_pronome' in cleaned_data and\
                    cleaned_data['imprimir_pronome'] == 'True':
                linha_pronome = getattr(
                    contato.pronome_tratamento,
                    'enderecamento_singular_%s' % lower(contato.sexo))
            prefixo_nome = getattr(
                contato.pronome_tratamento,
                'prefixo_nome_singular_%s' % lower(contato.sexo))

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_PRONOME\
                and imprimir_cargo and (linha_pronome or contato.cargo):
            linha_pronome = '%s - %s' % (linha_pronome, contato.cargo)

        if linha_pronome:
            story.append(Paragraph(linha_pronome, stylesheet['pronome_style']))

        linha_nome = '%s %s' % (prefixo_nome, contato.nome)\
            if prefixo_nome else contato.nome

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.LINHA_NOME\
                and imprimir_cargo:

            linha_nome = '%s %s' % (contato.cargo, linha_nome)
            linha_nome = linha_nome.strip()

        linha_nome = linha_nome.upper()\
            if 'nome_maiusculo' in cleaned_data and\
            cleaned_data['nome_maiusculo'] == 'True' else linha_nome

        story.append(Paragraph(linha_nome, stylesheet['nome_style']))

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_NOME\
                and imprimir_cargo and contato.cargo:
            story.append(Paragraph(contato.cargo,
                                   stylesheet['endereco_style']))

        endpref = contato.endereco_set.filter(preferencial=True).first()
        if endpref:
            endereco = endpref.endereco +\
                (' - ' + endpref.numero if endpref.numero else '') +\
                (' - ' + endpref.complemento if endpref.complemento else '')

            story.append(Paragraph(endereco, stylesheet['endereco_style']))

            b_m_uf = '%s - %s - %s' % (endpref.bairro if endpref.bairro else
                                       '', endpref.municipio.nome if
                                       endpref.municipio else '', endpref.uf)

            story.append(Paragraph(b_m_uf, stylesheet['endereco_style']))
            story.append(Paragraph(endpref.cep, stylesheet['endereco_style']))

        return story
예제 #42
0
def parse_tags(tagstring):
    """
    Parses tag input, with multiple word input being activated and
    delineated by commas and double quotes. Quotes take precedence, so
    they may contain commas.

    Returns a sorted list of unique tag names.

    Ported from Jonathan Buchanan's `django-tagging
    <http://django-tagging.googlecode.com/>`_
    """
    if not tagstring:
        return []

    if not settings.TAGGIT_ENABLE_SPACE_SPLIT_IF_NOT_QUOTES:
        tagstring = "".join([tagstring.strip().rstrip(","), ","])

    # Should all tags be handled as lowercase?
    if settings.TAGGIT_FORCE_LOWERCASE:
        tagstring = lower(force_unicode(tagstring))
    else:
        tagstring = force_unicode(tagstring)

    # Special case - if there are no commas or double quotes in the
    # input, we don't *do* a recall... I mean, we know we only need to
    # split on spaces.
    if u',' not in tagstring and u'"' not in tagstring:
        words = list(set(split_strip(tagstring, u' ')))
        words.sort()

        # shacker fork - remove any defined stopwords
        words = stopwords(words)

        return words

    words = []
    buffer = []
    # Defer splitting of non-quoted sections until we know if there are
    # any unquoted commas.
    to_be_split = []
    saw_loose_comma = False
    open_quote = False
    i = iter(tagstring)
    try:
        while True:
            c = i.next()
            if c == u'"':
                if buffer:
                    to_be_split.append(u''.join(buffer))
                    buffer = []
                # Find the matching quote
                open_quote = True
                c = i.next()
                while c != u'"':
                    buffer.append(c)
                    c = i.next()
                if buffer:
                    word = u''.join(buffer).strip()
                    if word:
                        words.append(word)
                    buffer = []
                open_quote = False
            else:
                if not saw_loose_comma and c == u',':
                    saw_loose_comma = True
                buffer.append(c)
    except StopIteration:
        # If we were parsing an open quote which was never closed treat
        # the buffer as unquoted.
        if buffer:
            if open_quote and u',' in buffer:
                saw_loose_comma = True
            to_be_split.append(u''.join(buffer))
    if to_be_split:
        if saw_loose_comma:
            delimiter = u','
        else:
            delimiter = u' '
        for chunk in to_be_split:
            words.extend(split_strip(chunk, delimiter))
    words = list(set(words))
    words.sort()

    # shacker fork - remove any defined stopwords
    words = stopwords(words)

    return words
예제 #43
0
 def test_lower(self):
     self.assertEqual(lower("TEST"), "test")
예제 #44
0
def get_model_core(model):
    """
    Return core view of given model or None
    """
    model_label = lower('%s.%s' % (model._meta.app_label, model._meta.object_name))
    return registered_model_cores.get(model_label)
예제 #45
0
파일: reports.py 프로젝트: cmjatai/cmj
    def createParagraphs(self, contato, stylesheet):

        cleaned_data = self.filterset.form.cleaned_data

        imprimir_cargo = (cleaned_data['imprimir_cargo'] == 'True')\
            if 'imprimir_cargo' in cleaned_data and\
            cleaned_data['imprimir_cargo'] else False

        local_cargo = cleaned_data['local_cargo']\
            if 'local_cargo' in cleaned_data and\
            cleaned_data['local_cargo'] else ''

        story = []

        linha_pronome = ''
        prefixo_nome = ''

        if contato.pronome_tratamento:
            if 'imprimir_pronome' in cleaned_data and\
                    cleaned_data['imprimir_pronome'] == 'True':
                linha_pronome = getattr(
                    contato.pronome_tratamento,
                    'enderecamento_singular_%s' % lower(
                        contato.sexo))
            prefixo_nome = getattr(
                contato.pronome_tratamento,
                'prefixo_nome_singular_%s' % lower(
                    contato.sexo))

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_PRONOME\
                and imprimir_cargo and (linha_pronome or contato.cargo):
            linha_pronome = '%s - %s' % (linha_pronome, contato.cargo)

        if linha_pronome:
            story.append(Paragraph(
                linha_pronome, stylesheet['pronome_style']))

        linha_nome = '%s %s' % (prefixo_nome, contato.nome)\
            if prefixo_nome else contato.nome

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.LINHA_NOME\
                and imprimir_cargo:

            linha_nome = '%s %s' % (contato.cargo, linha_nome)
            linha_nome = linha_nome.strip()

        linha_nome = linha_nome.upper()\
            if 'nome_maiusculo' in cleaned_data and\
            cleaned_data['nome_maiusculo'] == 'True' else linha_nome

        story.append(Paragraph(linha_nome, stylesheet['nome_style']))

        if local_cargo == ImpressoEnderecamentoContatoFilterSet.DEPOIS_NOME\
                and imprimir_cargo and contato.cargo:
            story.append(
                Paragraph(contato.cargo, stylesheet['endereco_style']))

        endpref = contato.endereco_set.filter(
            preferencial=True).first()
        if endpref:
            endereco = endpref.endereco +\
                (' - ' + endpref.numero if endpref.numero else '') +\
                (' - ' + endpref.complemento if endpref.complemento else '')

            story.append(Paragraph(endereco, stylesheet['endereco_style']))

            b_m_uf = '%s - %s - %s' % (
                endpref.bairro if endpref.bairro else '',
                endpref.municipio.nome if endpref.municipio else '',
                endpref.uf)

            story.append(Paragraph(b_m_uf, stylesheet['endereco_style']))
            story.append(Paragraph(endpref.cep, stylesheet['endereco_style']))

        return story
예제 #46
0
 def register(self, generic_core):
     if (hasattr(generic_core, 'model')):
         model_label = lower('%s.%s' % (generic_core.model._meta.app_label, generic_core.model._meta.object_name))
         registered_model_cores[model_label] = generic_core
     registered_cores.append(generic_core)
     return generic_core
예제 #47
0
파일: utils.py 프로젝트: 1010/django-taggit
def parse_tags(tagstring):
    """
    Parses tag input, with multiple word input being activated and
    delineated by commas and double quotes. Quotes take precedence, so
    they may contain commas.

    Returns a sorted list of unique tag names.

    Ported from Jonathan Buchanan's `django-tagging
    <http://django-tagging.googlecode.com/>`_
    """
    if not tagstring:
        return []

    # Should all tags be handled as lowercase?
    try:
        settings.TAGGIT_FORCE_LOWERCASE
        tagstring = lower(force_unicode(tagstring))
    except:
        tagstring = force_unicode(tagstring)

    # Special case - if there are no commas or double quotes in the
    # input, we don't *do* a recall... I mean, we know we only need to
    # split on spaces.
    if u',' not in tagstring and u'"' not in tagstring:
        words = list(set(split_strip(tagstring, u' ')))
        words.sort()

        # shacker fork - remove any defined stopwords
        words = stopwords(words)

        return words

    words = []
    buffer = []
    # Defer splitting of non-quoted sections until we know if there are
    # any unquoted commas.
    to_be_split = []
    saw_loose_comma = False
    open_quote = False
    i = iter(tagstring)
    try:
        while True:
            c = i.next()
            if c == u'"':
                if buffer:
                    to_be_split.append(u''.join(buffer))
                    buffer = []
                # Find the matching quote
                open_quote = True
                c = i.next()
                while c != u'"':
                    buffer.append(c)
                    c = i.next()
                if buffer:
                    word = u''.join(buffer).strip()
                    if word:
                        words.append(word)
                    buffer = []
                open_quote = False
            else:
                if not saw_loose_comma and c == u',':
                    saw_loose_comma = True
                buffer.append(c)
    except StopIteration:
        # If we were parsing an open quote which was never closed treat
        # the buffer as unquoted.
        if buffer:
            if open_quote and u',' in buffer:
                saw_loose_comma = True
            to_be_split.append(u''.join(buffer))
    if to_be_split:
        if saw_loose_comma:
            delimiter = u','
        else:
            delimiter = u' '
        for chunk in to_be_split:
            words.extend(split_strip(chunk, delimiter))
    words = list(set(words))
    words.sort()

    # shacker fork - remove any defined stopwords
    words = stopwords(words)

    return words
예제 #48
0
def is_content_type(obj, arg):
    try:
        ct = lower(obj._meta.object_name)
        return ct == arg
    except AttributeError:
        return ""
예제 #49
0
    def test_lower(self):
        self.assertEqual(lower('TEST'), 'test')

        # uppercase E umlaut
        self.assertEqual(lower('\xcb'), '\xeb')
예제 #50
0
 def test_non_string_input(self):
     self.assertEqual(lower(123), "123")
예제 #51
0
 def test_unicode(self):
     # uppercase E umlaut
     self.assertEqual(lower("\xcb"), "\xeb")
예제 #52
0
def delete_city(request, city_name):
    City.objects.filter(city_name=lower(city_name)).delete()
    return HttpResponse("Deleted!")
예제 #53
0
 def test_lower(self):
     self.assertEqual(lower('TEST'), 'test')
예제 #54
0
def path_city(request, city_name):
    Temperatures.objects.filter(city__city_name=lower(city_name)).delete()
    return HttpResponse("Deleted!")
예제 #55
0
def is_content_type(obj, arg):
    ct = lower(obj._meta.object_name)
    return ct == arg
예제 #56
0
def Geocode(array):    

    ticket = "awFhbDzHd0vJaWVAzwkLyC9gf0LhbM9CyxSLyCH8aTphbIOidIZHdWOLyCtq"
    
    url = "webservices.apontador.com.br"
    
    results = []
        
    for a in array:
        city = array[a]['city']
        state = array[a]['state']
        number = array [a]['number']
        street = array[a]['address']
        
        xml = '<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><getXY xmlns="http://webservices.maplink2.com.br"><address><street>'+street+'</street><houseNumber>'+str(number)+'</houseNumber><zip></zip><district></district><city><name>'+city+'</name><state>'+state+'</state></city></address><token>'+ticket+'</token></getXY></soap12:Body></soap12:Envelope>'
        print xml
        conn = httplib.HTTPConnection(url,timeout=3)
        headers = {"Content-type":"text/xml; charset=\"UTF-8\""}
        conn.request("POST", "/webservices/v3/AddressFinder/AddressFinder.asmx", xml, headers)
        response = conn.getresponse()
        conteudo = response.read()
        conn.close()
        
        
        
        #<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getMapResponse xmlns="http://webservices.maplink2.com.br"><getMapResult><url>http://teste.webservices.maplink2.com.br/output/</url><extent><XMin>-49.2962339</XMin><YMin>-26.94037873</YMin><XMax>-43.2075</XMax><YMax>-21.356430578</YMax></extent></getMapResult></getMapResponse></soap:Body></soap:Envelope>
    
        if response.status == 200:
            gxml = ElementTree.fromstring(conteudo)
            
            lng = gxml.find(".//{http://webservices.maplink2.com.br}x")
            lat = gxml.find(".//{http://webservices.maplink2.com.br}y")
            
            try:
                c = CachedGeocode.objects.get(Q(lng=lng.text) & Q(lat=lat.text))
            
            except ObjectDoesNotExist:    
                c = CachedGeocode(
                    lat = float(lat.text),
                    lng = float(lng.text),
                    full_address = "",
                    number = number,
                    street = title(lower(smart_str(street, encoding='utf-8', strings_only=False, errors='strict'))),
                    city = title(smart_str(city, encoding='utf-8', strings_only=False, errors='strict')),
                    state = state,
                    country = "Brasil",
                    #postal_code = postal.text,
                    #administrative_area = title(lower(address[0].get("Bairro")))
                )
        
                c.full_address = smart_str(c.street, encoding='utf-8', strings_only=False, errors='strict')+" "+str(c.number)+", "+smart_str(c.city, encoding='utf-8', strings_only=False, errors='strict')+", "+str(c.state)
                try:
                    c.save()
                except:
                    pass
            except MultipleObjectsReturned:
                c = CachedGeocode.objects.filter(Q(lng=lng.text) & Q(lat=lat.text))[0]
    
            result = {}
            result['lng'] = lng.text
            result['lat'] = lat.text
            results.append(result)
            
    json = simplejson.dumps(results)
    return HttpResponse(json, mimetype='application/json')