Example #1
0
def recv_hardware_info(connection, timeout = 0):
     apdu = connection.wait_apdu(0x80 + _apid, b'\x10\x02', timeout)
     print('apdu '+ str(apdu))
     ack_params = None
     if apdu is None:
        return None
     ack_code = apdu.pop_byte()
     if ack_code is None:
            return False

     if ack_code == 0x00:
        num_entries = apdu.pop_byte()
        tag_id = apdu.pop_byte()
        tag_len = apdu.pop_byte()
        tag_data = apdu.pop_array(tag_len)
        tag_ppnid = apdu.pop_byte()
        tag_ppnlen = apdu.pop_byte()
        tag_ppndata = apdu.pop_array(tag_ppnlen)
        ack_params = {
                'ack_code' : 0x00,
				'num_entries' : num_entries,
				'Tag_Id' : tag_id,
				'Tag_len'  : tag_len,
                'Tag_data': tag_data,
                'Tag_ppnId' : tag_ppnid,
                'Tag_ppnlen' : tag_ppnlen,
                'Tag_ppndata' : tag_ppndata

	          }
     return ack_params
def maquina2(path):
    text=reader(path)
    intex=text.find("\n")

    cual=text[0:intex].split()[7].split(",")[0].split(".")[0]
    print(cual)
    textoFiltrado=text[intex:len(text)].split("\n")
    buffer=[]
    for i in range(0,len(textoFiltrado)):
        if(textoFiltrado[i].split()!=[]):
            buffer.append(textoFiltrado[i].split())

    for i in buffer:
        if(cual=="660"):
            id=models.execute_kw(DB, uid, PASS,
                    'lab.result', 'search_read',
                    [[['name', '=', 'M:'+i[1]+'__E:P']]],
                    {'fields': ['id']})
        elif(cual=="420"):
            id=models.execute_kw(DB, uid, PASS,
                    'lab.result', 'search_read',
                    [[['name', '=', 'M:'+i[1]+'__E:S']]],
                    {'fields': ['id']})
        elif(cual=="430"):
            id=models.execute_kw(DB, uid, PASS,
                    'lab.result', 'search_read',
                    [[['name', '=', 'M:'+i[1]+'__E:B']]],
                    {'fields': ['id']})
        if(id!=[]):
            id=id[0]['id']
            models.execute_kw(DB, uid, PASS, 'lab.result', 'write', [[int(id)], {
                'valor': float(i[3].replace(",", "."))
            }])
Example #3
0
 def print(self,*args,add=0,**kwargs):
     stack = self.get_stack()
     #builtins.print(len(stack),self.base_depth)
     depth = len(stack)-self.base_depth+add
     args = ["\t"*depth + "%s"%arg for arg in args]
     #builtins.print(len(inspect.stack()),self.base_depth)
     builtins.print(*args,**kwargs)
Example #4
0
def print(*args, newline=True, debug_only=False):
    if not debug_only or bpy.app.debug_value > 0:
        builtins.print(
            " ".join([str(a) for a in args]).encode(sys.getdefaultencoding()).decode(sys.stdout.encoding),
            end="\n" if newline else "",
            flush=True,
        )
Example #5
0
def warn(page):
    now_string = Arrow.utcnow().strftime("%x %X")
    err = traceback.format_exception(*sys.exc_info())
    with open("errlog", "a") as fh:
        builtins.print(now_string, repr(page.title), ":", file=fh)
        for line in err:
            builtins.print("\t" + line.rstrip(), file=fh)
    def execute(self):
        self.out.log("Starting analysis", logging.INFO)

        load = self.inp.get_query_sets('load',wrap_for_merge=True)
        oat = self.inp.get_query_sets('oat',wrap_for_merge=True)

        data = self.inp.merge_fill_in_data(load,oat)

        for row in data:
            ts = row['time']

            tz = timezone('America/Los_Angeles')
            print(tz)
#            ts = ts.astimezone(timezone('US/Pacific'))
            oats = row['oat']

            timestring = ts.strftime("%Y-%m-%d %H:%M")

            row_to_write = {"time": timestring, "load": row['load'][0]}

            count = 0
            for oat in oats:
                name = 'oat'+str(count)
                row_to_write[name] = oats[count]
                count += 1

#            for count, oat in oats:
#                name = 'oat'+str(count)
#                row_to_write[name] = oats[count]
            self.out.insert_row("Time_Table", row_to_write)
Example #7
0
def MostrarTabla(num):
    inicio=num
    fin=num*10
    while inicio<=fin:
        print(inicio)
        print('-')
        inicio=inicio+num
def run_analysis_old(file_to_analyze):
    print("...Started 'run_analysis' for file: " + file_to_analyze)

    end_of_file = False
    sentence = []
    # gold_sentence, pred_sentence = [], []
    sentence_counter = 0
    _total_names = 0
    _total_phrases = 0
    data = open(file_to_analyze, 'r', encoding="utf-8")
    # data = open(res_file, 'r')
    while not end_of_file:
        line = data.readline()
        if not line:
            end_of_file = True
            break

        line = line.strip("\n").strip("\t").strip(" ")
        if len(line):
            print("found regular line. starting with: " + line.split("\t")[0]) # TODO - Just a print
            print("line-length: " + str(len(line)))
            print("FULL LINE:" + line)
            sentence.append(line)
        # if we've reached the end of the sentence - en empty line.
        else:
            print("empty line")  # TODO - Just a print
            sentence_counter += 1
            gold_sentence = create_tag_list_by(sentence, GOLD_STANDARD_TAG)
            pred_sentence = create_tag_list_by(sentence, OUR_CRF_TAG)
            # send each sentence to:
            total_f_measure_res = calculate_F_measure_sentence(gold_sentence, pred_sentence)
            f_measure_res_by_name = calculte_F_measure_by_tag(gold_sentence, pred_sentence)

            # _total_phrases += total_f_measure_res[0]
            # _total_names += total_f_measure_res[1]

            # TODO: ADD ALL THE REST THAT IS MISSING !!!!!!!

    if not end_of_file:
        exit("ERROR!! DID NOT REACH END OF FILE!")
    # make_statistics(file_to_analyze, _total_phrases, _total_names)

    # Write to file
    # current_time = str(datetime.now())
    current_time = datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
    file_name_short = file_to_analyze.split("/")[1]
    res_file_name = "output/" + file_name_short + "_analysis_" + current_time + ".txt"
    res = open(res_file_name, 'w', encoding="utf-8")
    res.write(">>> TOTAL : <<< \n")
    res.write("    ------      \n")
    res.write("F_measure , Recall , Presicion \n")
    res.write(str(_total_F_measure) + " , " + str(_total_recall) + " , " + str(_total_precision) + "\n\n")
    res.write(">>> By Type : <<< \n")
    res.write("    ---------      \n")
    res.write("F_measure , Recall , Precision \n")
    for type in TAG_TYPES.keys():
        res.write(type + ") " + str(_F_by_type[TAG_TYPES[type]]) + " , " + str(_recall_by_type[TAG_TYPES[type]])
            + " , " + str(_precision__by_type[TAG_TYPES[type]]) + "\n")
    res.close()
    return res_file_name
Example #9
0
  def actualizar_medicamento(self,nombre_comercial, nombre_generico,estado,id_med):
    """
       Insertar un nuevo medicamento
    """
    print(nombre_comercial, nombre_generico,estado,id_med)
    log4py.info('##  update_medicamento dao ##')
    dao_response = None
    cursor = None

    try:
      self.open()
      cursor = self.get_cursor()
      cursor.execute('''
        UPDATE  MEDICAMENTO SET MED_NOMBRE_COMERCIAL=?, MED_NOMBRE_GENERICO=?, MED_ESTADO=?
        WHERE MED_ID=?;
      ''', (nombre_comercial, nombre_generico,estado,id_med))
      self.commit()

    except Exception as err:
      log4py.error('Error-> {0}'.format(err))
      self.rollback()
      raise err

    finally:
      self.close(cursor)
Example #10
0
  def update_detalle_medicamento(self,dem_id, id_med, presentacion,descripcion,
                                   cantidad_maxima, cantidad_minima, existencia,indicasiones,
                                   via_aministracion,fecha_alta,fecha_caducidad, condicion_venta,
                                   precio, iva, farmaceutica, elaborado_en,imagen):
    """
       Update un detalle medicamento
    """
    print(dem_id, id_med, presentacion,descripcion, cantidad_maxima, cantidad_minima, existencia,
          indicasiones,via_aministracion,fecha_alta,fecha_caducidad, condicion_venta, precio,
          iva, farmaceutica, elaborado_en,imagen)
    log4py.info('##  update_detalle_medicamento  ##')
    dao_response = None
    cursor = None
    try:
      self.open()
      cursor = self.get_cursor()
      # Se actualiza el detalle medicamento en db
      cursor.execute('''
        UPDATE  DETALLE_MEDICAMENTO SET DEM_ID=?, MED_FK=?, DEM_PRESENTACION=?, DEM_DESCRIPCION=?, DEM_CANTIDAD_MAXIMA=?, DEM_CANTIDAD_MINIMA=?,
        DEM_EN_EXISTENCIA=?, DEM_INDICACIONES=?, DEM_VIA_ADMIN_DOSIS=?, DEM_FECHA_ALTA=?, DEM_FECHA_CADUCIDAD=?,
        DEM_CONDICION_VENTA=?, DEM_PRECIO=?, DEM_IVA=?, DEM_FARMACEUTICA=?, DEM_ELABORADO_EN=?, DEM_IMAGEN=?
        WHERE DEM_ID=?
      ''', (dem_id, id_med, presentacion,descripcion, cantidad_maxima, cantidad_minima, existencia,indicasiones,
            via_aministracion,fecha_alta,fecha_caducidad, condicion_venta, precio, iva, farmaceutica, elaborado_en,imagen, dem_id ))
      self.commit()

    except Exception as err:
      log4py.error('Error-> {0}'.format(err))
      self.rollback()
      raise err

    finally:
      self.close(cursor)
 def minimize_fraction(self, ):
     if self.numerator.get_number() < self.denominator.get_number():
         while True:
             log = self.numerator.get_number()
             print(
                 "working... Current fraction:", self.numerator.get_number(), "/", self.denominator.get_number())
             numList = self.numerator.primary_factors()
             for i in range(len(numList)):
                 if numList[i] != 0:
                     if self.denominator.get_number() % numList[i] == 0:
                         self.numerator.set_number(int(self.numerator.get_number() / numList[i]))
                         self.denominator.set_number(int(self.denominator.get_number() / numList[i]))
             if log == self.numerator.get_number():
                 break
     else:
         while True:
             log = self.numerator.get_number()
             print(
                 "working... Current fraction:", self.numerator.get_number(), "/", self.denominator.get_number())
             denList = self.denominator.primary_factors()
             for i in range(len(denList)):
                 if denList[i] != 0:
                     if self.numerator.get_number() % denList[i] == 0:
                         self.numerator.set_number(int(self.numerator.get_number() / denList[i]))
                         self.denominator.set_number(int(self.denominator.get_number() / denList[i]))
             if log == self.numerator.get_number():
                 break
     minFraction = "minimum fraction is: {0}/{1}".format(self.numerator.get_number(), self.denominator.get_number())
     return minFraction
Example #12
0
 def dateVerification(value):
     rule = re.compile(r'(^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])$)')
     if rule.search(value):
         return True
     else:
         print("invalid date format")
         return False
Example #13
0
  def buscar_detalles(self,id_med):
    log4py.info('## buscar_detalles  ##')
    dao_response = None
    cursor = None
    aux = 0
    print('el id_med para buscar detalles')
    print(id_med)
    try:
      self.open()
      self.set_row_factory(consulta_detalles_row)
      cursor = self.get_cursor()
      cursor.execute('''
        SELECT DEM_ID, GRU_FK, MED_FK, CODIGO_BARRAS, DEM_PRESENTACION, DEM_DESCRIPCION, DEM_CANTIDAD_MAXIMA,
        DEM_CANTIDAD_MINIMA, DEM_EN_EXISTENCIA, DEM_INDICACIONES, DEM_VIA_ADMIN_DOSIS,DEM_FECHA_ALTA,
        DEM_FECHA_CADUCIDAD, DEM_CONDICION_VENTA,DEM_PRECIO, DEM_IVA, DEM_FARMACEUTICA, DEM_ELABORADO_EN, DEM_IMAGEN
        FROM DETALLE_MEDICAMENTO
        WHERE MED_FK=? AND DEM_ID>?
      ''', (id_med,aux))

      dao_response = cursor.fetchall()
      self.commit()

    except Exception as err:
      log4py.error('Error-> {0}'.format(err))
      self.rollback()
      raise err

    finally:
      self.close(cursor)
    return dao_response
Example #14
0
 def phoneVerification(value):
     rule = re.compile(r'(^[+0-9]{1,3})*([0-9]{10,11}$)')
     if rule.search(value):
         return True
     else:
         print("Invalid phone number. Insert phone in correct format.")
         return False
Example #15
0
    def get_calificaciones_by_materia_ajax(request):
        if request.is_ajax():

            alumnos = Alumnos.objects.all()
            flag = False
            retorno = []
            idcalificacion=0
            user = request.user

            for a in alumnos:#alumnos
                if a.is_active:
                    if a.plan:
                        if a.plan.materias.filter(clave=request.GET[
                            'id']).exists():  #pregunto si la clave de la materia del estudiante es igual a la materia escogida

                            if a.calificaciones_set.exists():
                                print(">>>>" + a.calificaciones_set.get(
                                    materia__clave=request.GET['id']).matricula.matricula)
                                idcalificacion = a.calificaciones_set.get(materia__clave=request.GET['id']).id
                                flag = True

                            retorno.append({'nombre': a.nom_alumno, 'apellido_paterno': a.apellido_paterno,
                                        'apellido_materno': a.apellido_materno, 'matricula': a.matricula, 'id': a.id,
                                        'flag': flag,'calificacion_id':idcalificacion})

            return HttpResponse(json.dumps(retorno))
        else:
            redirect('academica/calificacion/profesor_calificaciones.html')
Example #16
0
 def get_context_data(self, **kwargs):
     context = super(CalificacionList, self).get_context_data(**kwargs)
     context['form_calificacion'] = CalificacionForm
     context['list_calificacion'] = Calificaciones.objects.all()
     print(Calificaciones.objects.all())
     context['list_alumno'] = Alumnos.objects.filter(is_active=True)
     return context
Example #17
0
    def add_collection(self, path, update=False):

        for file in self.mp3_files(path):
            try:
                id3 = EasyID3(file)
                #print(id3['performer'][0],id3['artist'][0], id3['album'][0], id3['title'][0])
                #print(id3['albumartist'][0])


                artist_id = self.__db_commit_artist({
                    'name': id3['performer'][0]
                })

                album_id = self.__db_commit_album(update, {
                    'name': id3['album'][0],
                    'artist': artist_id,
                })

                song_id = self.__db_commit_song(update, {
                        'title': id3['title'][0],
                        'artist': artist_id,
                        'album': album_id,
                        'tracknumber': id3['tracknumber'][0],

                    })
                #print('ok')
            except:
                print("This was not loaded: " + file)
Example #18
0
def print(*objects, **kwargs):
    """
    Overload the print function to adapt for the encoding bug in Windows
    console.

    It will try to convert text to the console encoding before printing to
    prevent crashes.
    """
    try:
        stream = kwargs.get('file', None)
        if stream is None:
            stream = sys.stdout
        enc = stream.encoding
        if enc is None:
            enc = sys.getdefaultencoding()
    except AttributeError:
        return builtins.print(*objects, **kwargs)

    texts = []
    for object in objects:
        try:
            if type(object) is bytes:
                if sys.version_info < (3, 0):
                    # in python 2 bytes must be converted to str before decode
                    object = str(object)
                original_text = object.decode(enc, errors='replace')
            else:
                if sys.version_info < (3, 0):
                    object = unicode(object)
                original_text = object.encode(enc, errors='replace').decode(enc, errors='replace')
        except UnicodeEncodeError:
            original_text = unicode(object).encode(enc, errors='replace').decode(enc, errors='replace')
        texts.append(original_text)
    return builtins.print(*texts, **kwargs)
Example #19
0
def get_single_item_data(item_url):
    source_code = requests.get(item_url);
    plain_text = source_code.text;
    soup = BeautifulSoup(plain_text, 'lxml');

    for link in soup.findAll('span', {'class': 'notranslate',"itemprop":"price"}):
        price = link.string;
        print("price :",price);
Example #20
0
def print(*args, end='\n'):
    try:
        builtins.print(*args, end=end)
        sys.stdout.flush()
    except:   
        for arg in args: 
            bstdout.write(str(arg).encode('utf-8'))
        if end: bstdout.write(end.encode('utf-8'))
        bstdout.flush()
def identificador(path):
    text=reader(path)
    text=text.split()
    if(text[0]=="Analista"):
        maquina1(path)
    elif(text[0]=="No."):
        maquina2(path)
    elif(True):
        print("Archivo no identificado favor contactar a [email protected]")
def calculate_tweet_sentiment_of_actors(actor_tweet_map, sentiment_map):
    actor_averagetweet_map = {}
    for items in actor_tweet_map:
        total_tweet_Sentimentscore = 0
        for each_tweet in actor_tweet_map[items]:
            total_tweet_Sentimentscore += calculate_individual_tweetsentiment(each_tweet, sentiment_map)
        actor_averagetweet_map[items] = float(total_tweet_Sentimentscore/len(actor_tweet_map[items]))
    sorted_actor_averagetweet_map = sorted(actor_averagetweet_map.items(), key=operator.itemgetter(1), reverse=True)
    print(sorted_actor_averagetweet_map)
Example #23
0
def print(*objects, sep=' ', end='\n', file=None, flush=False):
    if file == None:
        file = context.buffer
    if context.first:
        context.first = False
        text = sep.join(objects)
    else:
        text = context.indent + sep.join(objects)
    builtins.print(text, end=end, file=file)
Example #24
0
 def _debug(self, msg):
     """Prints a debug message, indented to show how far down in the nested structure we are"""
     if self.debug:
         stack = inspect.stack()
         calling_frame = [x[3] for x in stack][1]
         relative_depth = len(self._state_stack)
         # print("%s[%s(%r)] %s" % (". " * relative_depth, calling_frame, self._state_stack, msg))
         state = "/".join(self._state_stack)
         builtins.print("%s/%s(): %s" % (state, calling_frame, msg))
Example #25
0
def call_110() -> None:
    """

    :rtype: None
    """
    global a, b

    h = q(10)
    v = h(100)
    print("a={}; b={}; q({})({}) => {}".format(a, 10, 100, v))
Example #26
0
    def get_my_horarios(request):
        user = request.user
        no_expediente = user.no_expediente

        alumnoNombre = Alumnos.objects.get(matricula=no_expediente)
        if (Grupos.objects.filter(id=alumnoNombre.grupo.id).exists()):
            group = Grupos.objects.filter(id=alumnoNombre.grupo.id).get()
            horarios = group.horarios
            print(horarios)
        return render_to_response('academica/horario/mis_horarios.html')
 def __init__(self, string):
     try:
         self.numerator = PrimeCalculator(int(string.split("/")[0]))
         self.denominator = PrimeCalculator(int(string.split("/")[1]))
     except (ValueError , IndexError) as e:
         if e == ValueError:
             print("Only integers!")
             sys.exit("Invalid input!")
         else:
             print("Didn't obey template!(a/b)")
             sys.exit("Invalid input!")
Example #28
0
File: card_api.py Project: veikn/S3
def print(card, end='\n'):
    """
    print the card
    
    :param:   * \ **card**\(card): the card
              * \ **end**\(string): [optional] separator (default is '\n')
    
    :UC: none
    
    """
    builtins.print(__to_string(card),end)
Example #29
0
    def get_context_data(self, **kwargs):
        context = super(CicloSemestralList, self).get_context_data(**kwargs)
        context['search_form'] = ConsultaCicloSemestralListForm
        context['form_ciclo'] = CicloSemestralForm
        ciclo_activo = False
        for i in CicloSemestral.objects.all():
            if i.vigente:
                ciclo_activo = i
                print("semestre" + ciclo_activo.clave)

        context['semestre'] = ciclo_activo
        return context
Example #30
0
 def checkAlarm(self):
     if(len(self.alarm1) != 4 and len(self.alarm1) != 5):
         self.alarm1 = ""
         self.alarmTime.configure(text=self.alarm1)
         print("Invalid time listed")
     else:
         # self.alarm1Time = int(self.alarm1.split()[0])
         self.alarm1Time = datetime.strptime(self.alarm1, '%H%M')
         self.alarm1Time = '{:%H:%M}'.format(self.alarm1Time)
         self.nextAlarm = "Next Alarm: " +str(self.alarm1Time)
         self.nextAlarmLabel.configure(text=self.nextAlarm)
         self.timePack()
Example #31
0
    def __init__(self):
        super().__init__()

        print("test")
def print_flush(*objects, sep='', end='\n', flush=False):
    return builtins.print(objects, sep, end, flush=True)
Example #33
0
 def print(x, print_statements=print_statements):
     import builtins as __builtin__
     if print_statements == True:
         __builtin__.print(x)
Example #34
0
# matrix X in a similar way to the c2h() function used in registration.

trainX = train_data[:, 0].reshape(-1, 1)
trainXsquared = np.square(train_data[:, 0]).reshape(-1, 1)
trainX = np.hstack((trainX, trainXsquared))
trainXones = util.addones(trainX)
trainY = train_data[:, 1].reshape(-1, 1)

validationX = validation_data[:, 0].reshape(-1, 1)
validationXsquared = np.square(validation_data[:, 0]).reshape(-1, 1)
validationX = np.hstack((validationX, validationXsquared))
validationones = util.addones(validationX)
validationY = validation_data[:, 1].reshape(-1, 1)

Theta, _ = reg.ls_solve(trainXones, trainY)
print(Theta)
#---------------------------------------------------------------------#

fig1 = plt.figure(figsize=(10, 10))
ax1 = fig1.add_subplot(111)
util.plot_regression(trainX, trainY, Theta, ax1)
ax1.grid()
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.legend(('Original data', 'Regression curve', 'Predicted Data', 'Error'))
ax1.set_title('Training set')

testX = test_data[:, 0].reshape(-1, 1)
testXsquared = np.square(testX[:, 0]).reshape(-1, 1)
testX = np.hstack((testX, testXsquared))
Example #35
0
import json, pika
from builtins import print
from Utils.DbUtils import process_message
from InvoiceReceiver.CreteGraphSender import notify_success

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='invoice_info', durable=True)
print('Queue invoice_info is up and waiting for messages...')


def callback(ch, method, properties, body):
    print(" message Received %r" % body)
    result = process_message(json.loads(body))
    if result:
        notify_success()
    else:
        print("process message failed")


def run():
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume('invoice_info', callback, auto_ack=True)
    channel.start_consuming()
Example #36
0
def client_2(site: Site) -> None:
    plan = site.customer.billing_plan
    print(plan)
 def on_error(self, status_code):
     print("Encountered streaming error (", status_code, ")")
     return True
Example #38
0
def log_testing():
    print('-' * 5 + 'log_testing' + '-' * 5)
    log('Logging')
    time.sleep(2)
    log('Logging')
Example #39
0
def client_3(site: Site) -> None:
    weeks = site.customer.payment_history['weeks']
    print(weeks)
Example #40
0
def log_right(msg, when=None):
    if when is None:
        when = datetime.datetime.now()
    print('%s %s' % (when, msg))
Example #41
0
def log(msg, when=datetime.datetime.now()):
    print('%s %s' % (when, msg))
Example #42
0
from builtins import print
from datetime import date
from emoji import emojize
from time import sleep
from random import randint

texto = ' \033[1;37m Desafio 088 \033[m '
print('{:*^50}'. format(texto))

limpa = '\033[m'
cores = {'vermelho':'\033[31m', 'verde':'\033[32m', 'amarelo':'\033[33m',
         'azul':'\033[34m', 'roxo':'\033[35m', 'ciano':'\033[36m', 'cinza':'\033[37m'}

texto2 =' \033[36m Palpite Mega Sena\033[m '
print(f'{texto2:*^50}')

lista = list()
jogos = list()
qtde = 0
while True:
    try:
        qtde = int(input('Quantos jogos você deseja que eu sorteie? : '))
    except:
        print('Valor inválido, digite um valor inteiro!')
    else:
        break
print('\033[31m*-\033[m' * 30)
while qtde != 0:
    for c in range(1, 7):
        num = randint(1, 60)
        if num not in lista:
Example #43
0
def cnn_model_fn(features, labels, mode):
    print(features)
    assert False
    """Model function for CNN."""
    # Input Layer
    # Reshape X to 4-D tensor: [batch_size, width, height, channels]
    # MNIST images are 28x28 pixels, and have one color channel
    input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])
    # Convolutional Layer #1
    # Computes 32 features using a 5x5 filter with ReLU activation.
    # Padding is added to preserve width and height.
    # Input Tensor Shape: [batch_size, 28, 28, 1]
    # Output Tensor Shape: [batch_size, 28, 28, 32]
    conv1 = tf.layers.conv2d(inputs=input_layer,
                             filters=32,
                             kernel_size=[5, 5],
                             padding="same",
                             activation=tf.nn.relu)
    # Pooling Layer #1
    # First max pooling layer with a 2x2 filter and stride of 2
    # Input Tensor Shape: [batch_size, 28, 28, 32]
    # Output Tensor Shape: [batch_size, 14, 14, 32]
    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

    # Convolutional Layer #2
    # Computes 64 features using a 5x5 filter.
    # Padding is added to preserve width and height.
    # Input Tensor Shape: [batch_size, 14, 14, 32]
    # Output Tensor Shape: [batch_size, 14, 14, 64]
    conv2 = tf.layers.conv2d(inputs=pool1,
                             filters=64,
                             kernel_size=[5, 5],
                             padding="same",
                             activation=tf.nn.relu)

    # Pooling Layer #2
    # Second max pooling layer with a 2x2 filter and stride of 2
    # Input Tensor Shape: [batch_size, 14, 14, 64]
    # Output Tensor Shape: [batch_size, 7, 7, 64]
    pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

    # Flatten tensor into a batch of vectors
    # Input Tensor Shape: [batch_size, 7, 7, 64]
    # Output Tensor Shape: [batch_size, 7 * 7 * 64]
    pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])

    # Dense Layer
    # Densely connected layer with 1024 neurons
    # Input Tensor Shape: [batch_size, 7 * 7 * 64]
    # Output Tensor Shape: [batch_size, 1024]
    dense = tf.layers.dense(inputs=pool2_flat,
                            units=1024,
                            activation=tf.nn.relu)

    # Add dropout operation; 0.6 probability that element will be kept
    dropout = tf.layers.dropout(inputs=dense,
                                rate=0.4,
                                training=mode == tf.estimator.ModeKeys.TRAIN)

    # Logits layer
    # Input Tensor Shape: [batch_size, 1024]
    # Output Tensor Shape: [batch_size, 10]
    logits = tf.layers.dense(inputs=dropout, units=10)

    predictions = {
        # Generate predictions (for PREDICT and EVAL mode)
        "classes": tf.argmax(input=logits, axis=1),
        # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
        # `logging_hook`.
        "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    # Calculate Loss (for both TRAIN and EVAL modes)
    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

    # Configure the Training Op (for TRAIN mode)
    if mode == tf.estimator.ModeKeys.TRAIN:
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
        train_op = optimizer.minimize(loss=loss,
                                      global_step=tf.train.get_global_step())
        return tf.estimator.EstimatorSpec(mode=mode,
                                          loss=loss,
                                          train_op=train_op)

    # Add evaluation metrics (for EVAL mode)
    eval_metric_ops = {
        "accuracy":
        tf.metrics.accuracy(labels=labels, predictions=predictions["classes"])
    }
    return tf.estimator.EstimatorSpec(mode=mode,
                                      loss=loss,
                                      eval_metric_ops=eval_metric_ops)
Example #44
0
def client_1(site: Site) -> None:
    name = site.customer.name
    print(name)
Example #45
0
from builtins import print
from util import pretty_name_8_colors, colour_mapping
from mastermind import Mastermind
from argparser import parser
import sys


class InvalidStateException(Exception):
    pass


args = parser.parse_args()
game_solver = Mastermind(args.k, args.n)

print("Welcome to Mastermind interactive solver.")
print(
    "Please think of a code combination containing {} pegs from {} colors ({})."
    .format(args.n, args.k, ", ".join(list(colour_mapping.values())[:args.k])))
print("\n")

# number of red and white pegs from the opponent's response
w, r = 0, 0
all_combinations = game_solver.all_possible_combinations
possible_combinations = game_solver.all_possible_combinations
attempt = game_solver.initial_attempt
num_attempts = 0

try:
    while r != args.n:
        num_attempts += 1
        print("Attempt {} is {}.".format(num_attempts,
Example #46
0
def is_customer_unknown(aCustomer):
    if type(aCustomer) not in [Customer, UnknownCustomer]:
        raise ValueError("Value '{}' unsupported".format(aCustomer))

    return aCustomer.is_unknown


def client_1(site: Site) -> None:
    name = site.customer.name
    print(name)


def client_2(site: Site) -> None:
    plan = site.customer.billing_plan
    print(plan)


def client_3(site: Site) -> None:
    weeks = site.customer.payment_history['weeks']
    print(weeks)


if __name__ == '__main__':
    site = Site(customer='unknown')
    client_1(site=site)
    client_2(site=site)
    client_3(site=site)

    print(is_customer_unknown(Customer('John smith')))
    print(is_customer_unknown(UnknownCustomer()))
            print(msg['text'].encode('utf-8'))
            self.socket.send(msg['text'].encode('utf-8'))
            return True
        except BaseException as e:
            print("Encountered error in on_data: %s" % str(e))
        return True

    def on_error(self, status_code):
        print("Encountered streaming error (", status_code, ")")
        return True


def readData(socket):
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, StreamListener(socket))
    tags = ["layoffs", "covid", "corona", "wfh"]
    stream.filter(track=tags)


if __name__ == "__main__":
    s = socket.socket()
    host = "localhost"
    port = 6000
    s.bind((host, port))
    print("Listening on the port: %s" % str(port))
    s.listen(5)
    socket, addr = s.accept()
    print("Received the request from: " + str(addr))
    time.sleep(5)
    readData(socket)
Example #48
0
def contador(inicio, fim, passo):
    if passo < 0:
        passo *= -1
    if passo == 0:
        passo = 1

    print('-=' * 30)
    print(f'A contagem de {inicio} até {fim} de {passo} em {passo}: ')

    if inicio < fim:
        cont = inicio
        while cont <= fim:
            print(f'{cont} ', end='')
            sleep(0.4)
            cont += passo
        print(' FIM!')
        print('-=' * 30)
    else:
        cont = inicio
        while cont >= fim:
            print(f'{cont} ', end='')
            sleep(0.4)
            cont -= passo
        print(' FIM!')
        print('-=' * 30)
Example #49
0
 def print(*args, **kwargs):
     __builtin__.print(
         *[a.strip() if type(a) == str else a for a in args])
Example #50
0
from builtins import print
from datetime import date
from emoji import emojize
from time import sleep
from random import randint
from operator import itemgetter

texto = ' \033[1;34m Desafio 098 \033[m '
print('{:*^50}'.format(texto))

limpa = '\033[m'
cores = {
    'vermelho': '\033[31m',
    'verde': '\033[32m',
    'amarelo': '\033[33m',
    'azul': '\033[34m',
    'roxo': '\033[35m',
    'ciano': '\033[36m',
    'cinza': '\033[37m'
}

texto2 = ' \033[33m Função Contador \033[m '
print(f'{texto2:*^50}')


def contador(inicio, fim, passo):
    if passo < 0:
        passo *= -1
    if passo == 0:
        passo = 1
Example #51
0
def printEpisodes(episodes):
    for episode in episodes:
        print(episode['date'] + ':', episode['title'])
Example #52
0
def print(*args, **kwargs):
    builtins.print(*args, **kwargs)
Example #53
0
"""
Variables
Listas
Tuplas
Funciones basicas de listas
"""

# Mensaje por consola
from builtins import print

print("Hellow World this is the start of a best program in inteligence artificial")

# Variables
CONSTANTE = 1  # En py no existen constantes, por lo cual para identificarlas se pueden usar en Mayus
number1 = 1
number2 = 5
suma = number1 + number2
print(suma)

# None es el tipo de dato como null o falso
variable_None = None
print('variable_None', variable_None)

# Declaracion de variables en una misma linea, con su inicialiacion en el mismo orden de posicion
valor1, valor2, valor3 = 1, 5, 15
print(valor1, valor2, valor3)

# Operadores
print(valor1 == valor2 or valor3 > valor1)
print(True and True and True)
Example #54
0
def print(*args, **kwargs):
    if "sep" not in kwargs and args[0] == "Grade: ":
        builtins.print(*args, **kwargs, sep="")
    else:
        builtins.print(*args, **kwargs)
Example #55
0
def print(*args):
    __builtin__.print(*args, flush=True)
Example #56
0
 def check(self):
     cursor = self.textCursor()
     b = cursor.block()
     if len(b.text()) >= 79:
         print("pep 8 violation on line: " + str(b.blockNumber() + 1))
Example #57
0
loc = input ("Enter the location":)
location = weather.lookup_by_location('halifax')
condition = location.condition()
print ("The current weayher is "+ (condition['text'])

a =[]
i=0

for forecasts in location.forecast():
    if i<5:
    b = []
    b.append(forecast['text']
    b.append(forecast['date'])
    b.append(forecast['high'])
    b.append(forecast['low'])
    i+=1
    a.append(b)
print (a)
max = 0

for lists in a
    if int(lists[2] > max:
	max = int(lists[2])
	s = lists[1]
print(s)




Example #58
0
    def keyPressEvent(self, e):
        textCursor = self.textCursor()
        key = e.key()

        if key == Qt.Key_H:
            # self.parent.completer.wordList
            # TODO: implement dynamic completion
            pass

        textCursorPos = textCursor.position()
        isSearch = (e.modifiers() == Qt.ControlModifier
                    and e.key() == Qt.Key_F)

        if isSearch:
            try:
                currentWidget = self.parent
                currentFile = currentWidget.fileName
                currentEditor = currentWidget.editor

                textCursor = currentEditor.textCursor()
                textCursorPos = textCursor.position()

            except (AttributeError, UnboundLocalError) as E:
                print(E)

            if currentWidget is not None:
                text, okPressed = QInputDialog.getText(self, 'Find',
                                                       'Find what: ')
                if okPressed:
                    if text == "":
                        text = " "
                        self.dialog.noMatch(text)
                    self.searchtext = text
                    try:
                        with open(currentFile, 'r') as file:
                            contents = file.read()
                            self.indexes = list(find_all(contents, text))
                            if len(self.indexes) == 0:
                                self.dialog.noMatch(text)

                    except FileNotFoundError as E:
                        print(E)

        if key == Qt.Key_QuoteDbl:
            self.insertPlainText('"')
            self.moveCursorPosBack()

        if e.modifiers() == Qt.ControlModifier and e.key(
        ) == 61:  # Press Ctrl+Equal key to make font bigger

            self.font.setPointSize(self.size + 1)
            self.font.setFamily(editor["editorFont"])
            self.setFont(self.font)
            self.size += 1
        if e.modifiers() == Qt.ControlModifier and e.key() == 16777217:
            return

        if e.modifiers() == Qt.ControlModifier and e.key(
        ) == 45:  # Press Ctrl+Minus key to make font smaller

            self.font.setPointSize(self.size - 1)

            self.font.setFamily(editor["editorFont"])
            self.setFont(self.font)
            self.size -= 1

        if key == Qt.Key_F3:
            try:
                index = self.indexes[0 + self.l]
                currentWidget = self.parent
                currentFile = currentWidget.fileName
                currentEditor = currentWidget.editor
                textCursor.setPosition(index)
                textCursor.movePosition(textCursor.Right,
                                        textCursor.KeepAnchor,
                                        len(self.searchtext))
                currentEditor.setTextCursor(textCursor)
                self.l += 1
            except IndexError:
                self.l = 0

        if key == 39:
            self.insertPlainText("'")
            self.moveCursorPosBack()

        if key == Qt.Key_BraceLeft:
            self.insertPlainText("}")
            self.moveCursorPosBack()

        if key == Qt.Key_BracketLeft:
            self.insertPlainText("]")
            self.moveCursorPosBack()

        if key == Qt.Key_ParenLeft:
            self.insertPlainText(")")
            self.moveCursorPosBack()

        if key == Qt.Key_ParenRight:
            textCursor = self.textCursor()
            textCursor.select(QTextCursor.WordUnderCursor)
            if textCursor.selectedText(
            ) == "()" or "()" in textCursor.selectedText():
                return

        if key == Qt.Key_BraceRight:
            textCursor = self.textCursor()
            textCursor.select(QTextCursor.WordUnderCursor)
            if textCursor.selectedText == "":
                return

        if key not in [16777217, 16777219, 16777220]:
            super().keyPressEvent(e)
            return

        e.accept()
        cursor = self.textCursor()
        if key == 16777217:  # and self.replace_tabs:
            amount = 4 - self.textCursor().positionInBlock() % 4
            self.insertPlainText(' ' * amount)

        elif key == 16777219 and cursor.selectionStart() == cursor.selectionEnd() and self.replace_tabs and \
                cursor.positionInBlock():
            position = cursor.positionInBlock()
            end = cursor.position()
            start = end - (position % 4)

            if start == end and position >= 4:
                start -= 4

            string = self.toPlainText()[start:end]
            if not len(string.strip()
                       ):  # if length is 0 which is binary for false
                for i in range(end - start):
                    cursor.deletePreviousChar()
            else:
                super().keyPressEvent(e)

        elif key == 16777220:
            end = cursor.position()
            start = end - cursor.positionInBlock()
            line = self.toPlainText()[start:end]
            indentation = len(line) - len(line.lstrip())

            chars = '\t'
            if self.replace_tabs:
                chars = '    '
                indentation /= self.replace_tabs

            if line.endswith(':'):
                if self.replace_tabs:
                    indentation += 1

            super().keyPressEvent(e)
            self.insertPlainText(chars * int(indentation))

        else:
            super().keyPressEvent(e)
Example #59
0
from builtins import print

score = int(input("please input a score:"))
degree = "SABCDE"
num =0
if score > 100 or score < 0:
    print("error, please input correct score")
else:
    num = score//10
    if num < 6:
        num = 5
    print(degree[10-num])
    print("score is {0},degree is {1}".format(score,degree[10-num]))
    print()
    
import pandas as pd
Example #60
0
def print(*args):
    builtins.print(*args)