Python & # 39; s .split () implemented in C

I'm a beginner in C and I just created the split () function of Python in that language.
The only missing part is to pass the delimiters as a parameter, instead of using only spaces / tabs. But it would be quite easy by modifying isDelimiter and it is not important.

For those who have not used split (), here is an example:

>>> "test test2 ?        .. stack     overflow ".split()
('test', 'test2', '?', '..', 'stack', 'overflow')

I have sufficiently documented it to not need a lot of explanations, but if something is not clear, thank you for letting me know. All comments and suggestions are welcome, also for the design itself 馃檪

#include 
#define TRUE 1
#define FALSE 0
#define DEFAULT_BUFSIZE 512


static inline int isDelimiter(char s) {
    return s == ' ' || s == 't';
}


// Splits a string with elements delimited by spaces or tabs into an array
// of strings. It works very similarly to Python's split() function.
int parser(char *source, char ***destination) {
    // The auxiliar variable `aux` will save the array contents, rather than
    // using *destination. Its elements length is initially DEFAULT_BUFSIZE
    // so that realloc() doesn't have to be called everytime a character
    // is copied. The memory used by each element will be reduced to the
    // minimum possible afterwards.
    // The most efficient solution would actually be having two buffer
    // variables: one for the element size and another for the array itself.
    // But currently this isn't neccessary.
    size_t bufsize = DEFAULT_BUFSIZE;
    char **aux = malloc(sizeof(char *));

    // The source string is iterated and its contents are copied to the aux
    // array, so we need 3 counters:
    //     * `len` is the array length
    //     * `iArr` is the array's current element index.
    //     * `iStr` is the source array's index.
    size_t len = 1;
    int iStr = 0;
    int iArr = 0;
    // If there's more than 1 delimiter in a row, a new element shouldn't be
    // created. This is why `newEl` has to be created. It acts as a boolean
    // that indicates when a new element should start.
    int newEl = TRUE;
    // The first element of the array is created. The rest will be allocated
    // inside the loop.
    aux(0) = malloc(bufsize * sizeof(char));
    while (source(iStr) != '') {
        if (isDelimiter(source(iStr)) && !newEl) {
            // The used memory is reduced to what's actually being used.
            aux(len-1) = realloc(aux(len-1), (iArr+1) * sizeof(char));
            // The current element ends.
            aux(len-1)(iArr) = '';
            iArr = 0;
            ++len;
            // Don't come back here until a character other than a delimiter
            // is found.
            newEl = TRUE;

            // The new element is allocated.
            aux = realloc(aux, len * sizeof(char *));
            aux(len-1) = malloc(bufsize * sizeof(char));
        } else if (!isDelimiter(source(iStr))) {
            // The source character is copied to the destination.
            aux(len-1)(iArr) = source(iStr);
            ++iArr;
            // From now on, a new element can be started.
            newEl = FALSE;

            // The buffer is enlargened if neccessary.
            if (iArr >= bufsize) {
                bufsize += DEFAULT_BUFSIZE;
                aux(len-1) = realloc(aux(len-1), bufsize * sizeof(char *));
            }
        }
        ++iStr;
    }

    // The last element's size has to be reduced outside of the loop, and a
    // '' is added to finish it. If newEl is true, it means the last element
    // is filled with delimiters and it shouldn't be included in the array.
    if (newEl) {
        --len;
        aux(len) = NULL;
    } else {
        aux(len-1) = realloc(aux(len-1), (iArr+1) * sizeof(char));
        aux(len-1)(iArr) = '';

        // Finally, the last element is NULL.
        aux(len) = NULL;
    }

    // Saving the destination variable and returning its length.
    *destination = aux;
    return len;
}

I've also made a small test file:

#include   // fgets()...
#include   // strlen()
#include   // size_t, atoi...
#include "parser.h"
#define MAX 1024


int main() {
    char str(MAX);
    printf("Introduce numbers delimited by spaces or tabs: ");
    fgets(str, MAX, stdin);
    // Removing the 'n' from fgets()
    str(strlen(str)-1) = '';

    char **nums;
    size_t len = parser(str, &nums);
    if (len == 0) {
        fprintf(stderr, "No input.n");
        exit(1);
    }

    int sum = 0;
    for (int i = 0; i < len; ++i)
        sum += atoi(nums(i));

    printf("Sum: %dn", sum);

    free(nums);
    return 0;
}

In addition, here is a GodBolt code snippet: https://godbolt.org/z/rGtvN9

python – How to inherit users and store them in a new table?

Odoo10 Python 2.7


I want to inherit Odoo's default users since Odoo creates the users and I'm not going to reinvent the wheel. Thus, I appear in a detachable drop-down field of all users, as in this video. After showing that they can be stored in my table person in a field with the attribute '#'Store=True& # 39 ;. The latter, I can not check because it gives me an error.


models.py

class gesti贸n_personas(models.Model):
    _name = 'gesti贸n_personas.persona'
    _inherits = {'res.partner': 'partner_id',}
    name = fields.Char(string="DNI", required=True, help="Introduce un DNI")
    partner_id = fields.Many2one('res.partner', ondelete='cascade', required=False, Store=True)
    ...

views.xml


  gesti贸n_personas.persona.tree
  gesti贸n_personas.persona
  
    
      
      
             
      
      ...
    
  

Odoo server error

    Traceback (most recent call last):
  File "/home/javier/proyectos/odoo10/odoo/http.py", line 642, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/home/javier/proyectos/odoo10/odoo/http.py", line 684, in dispatch
    result = self._call_function(**self.params)
  File "/home/javier/proyectos/odoo10/odoo/http.py", line 334, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/home/javier/proyectos/odoo10/odoo/service/model.py", line 101, in wrapper
    return f(dbname, *args, **kwargs)
  File "/home/javier/proyectos/odoo10/odoo/http.py", line 327, in checked_call
    result = self.endpoint(*a, **kw)
  File "/home/javier/proyectos/odoo10/odoo/http.py", line 942, in __call__
    return self.method(*args, **kw)
  File "/home/javier/proyectos/odoo10/odoo/http.py", line 507, in response_wrap
    response = f(*args, **kw)
  File "/home/javier/proyectos/odoo10/addons/web/controllers/main.py", line 899, in call_button
    action = self._call_kw(model, method, args, {})
  File "/home/javier/proyectos/odoo10/addons/web/controllers/main.py", line 887, in _call_kw
    return call_kw(request.env(model), method, args, kwargs)
  File "/home/javier/proyectos/odoo10/odoo/api.py", line 689, in call_kw
    return call_kw_multi(method, model, args, kwargs)
  File "/home/javier/proyectos/odoo10/odoo/api.py", line 680, in call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/home/javier/proyectos/odoo10/odoo/addons/base/module/module.py", line 412, in button_immediate_install
    return self._button_immediate_function(type(self).button_install)
  File "/home/javier/proyectos/odoo10/odoo/addons/base/module/module.py", line 486, in _button_immediate_function
    modules.registry.Registry.new(self._cr.dbname, update_module=True)
  File "/home/javier/proyectos/odoo10/odoo/modules/registry.py", line 83, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/home/javier/proyectos/odoo10/odoo/modules/loading.py", line 377, in load_modules
    loaded_modules, update_module, models_to_check)
  File "/home/javier/proyectos/odoo10/odoo/modules/loading.py", line 270, in load_marked_modules
    perform_checks=perform_checks, models_to_check=models_to_check
  File "/home/javier/proyectos/odoo10/odoo/modules/loading.py", line 182, in load_module_graph
    _load_data(cr, module_name, idref, mode, kind='data')
  File "/home/javier/proyectos/odoo10/odoo/modules/loading.py", line 96, in _load_data
    tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
  File "/home/javier/proyectos/odoo10/odoo/tools/convert.py", line 845, in convert_file
    convert_xml_import(cr, module, fp, idref, mode, noupdate, report)
  File "/home/javier/proyectos/odoo10/odoo/tools/convert.py", line 915, in convert_xml_import
    obj.parse(doc.getroot(), mode=mode)
  File "/home/javier/proyectos/odoo10/odoo/tools/convert.py", line 796, in parse
    self.parse(rec, mode)
  File "/home/javier/proyectos/odoo10/odoo/tools/convert.py", line 799, in parse
    self._tags(rec.tag)(rec, de, mode=mode)
  File "/home/javier/proyectos/odoo10/odoo/tools/convert.py", line 707, in _tag_record
    id = self.env(context=rec_context)('ir.model.data')._update(rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode)
  File "/home/javier/proyectos/odoo10/odoo/addons/base/ir/ir_model.py", line 1238, in _update
    record = record.create(values)
  File "/home/javier/proyectos/odoo10/odoo/models.py", line 3851, in create
    record = self.browse(self._create(old_vals))
  File "/home/javier/proyectos/odoo10/odoo/models.py", line 3912, in _create
    parent_id = self.env(parent_model).create(parent_vals).id
  File "/home/javier/proyectos/odoo10/odoo/addons/base/res/res_partner.py", line 534, in create
    partner = super(Partner, self).create(vals)
  File "/home/javier/proyectos/odoo10/odoo/models.py", line 3851, in create
    record = self.browse(self._create(old_vals))
  File "/home/javier/proyectos/odoo10/odoo/models.py", line 3946, in _create
    cr.execute(query, tuple(u(2) for u in updates if len(u) > 2))
  File "/home/javier/proyectos/odoo10/odoo/sql_db.py", line 154, in wrapper
    return f(self, *args, **kwargs)
  File "/home/javier/proyectos/odoo10/odoo/sql_db.py", line 231, in execute
    res = self._obj.execute(query, params)
ParseError: "new row for relation "res_partner" violates check constraint "res_partner_check_name"
DETAIL:  Failing row contains (13, null, 1, null, null, null, 2019-11-17 14:35:03.690234, 0, t, null, null, null, null, null, null, null, null, null, f, null, null, f, null, es_ES, null, null, null, f, 2019-11-17 14:35:03.690234, null, null, 1, t, 1, null, null, null, contact, f, null, null, null).
" while parsing /home/javier/proyectos/odoo10/addons/gestion_curricular/data/data.xml:19, near

            001B
            
            ...
        

Python 3.x – Unwanted Space Characters and Does not Understand Why (Python3)

beginner here. Learn Python through a book called "Breaking Ciphers with Python". As part of a simple encryption program, I wrote this (this is just the beginning):

import pyperclip

fg = lambda text, color: "33(38;5;" + str(color) + "m" + text + "33(0m"
bg = lambda text, color: "33(48;5;" + str(color) + "m" + text + "33(0m"

# Simple usage: print(fg("text", 160))

msg = input('nnEnter your secret:nn')

msg_len_int = len(msg)

msg_len_str = str(len(msg))

print('nnChoose key (has to be less than', fg((msg_len_str), 40), '): ')

key = input('nnChoose your here: ')

In output, I receive this:

enter the description of the image here

I do not understand why I have 2 space characters that I have not put, one before and the other after fg((msg_len_str).

Python 3.x – I extract features from wav format audio files using librosa but I fix the error

Traceback (last most recent call):
File "C: Users Lenovo Downloads CODE CODE FEATURE_EXTRACTION.py", line 47, in
y, sr = librosa.load (song name, mono = True, duration = 30)
File "C: Users Lenovo Anaconda3 lib site-packages librosa core audio.py", line 119, loading
with audioread.audio_open (os.path.realpath (path)) as input_file:
"C: Users Lenovo Anaconda3 lib site-packages audioread__init __. Py" file, line 116, in audio_open
raises NoBackendError ()
audioread.exceptions.NoBackendError

python – Best practice to ensure connection and response of the results of the external API

I have this code in python (using django firmware) that connects to an external API and updates some values 鈥嬧媜f this service. Each step depends on the previous step (for step 2 to work, step 1 must return True and so on including a valid connection to the API). How can I make sure all these steps take place at the same time and if one step fails, how can I go back and run them all at the same time during another try? here is the code. note that each class method does something in this external service.

# 1. add new value to account
if cls.add_balance(subscription_code, increase_amount):
# 2. set new base balance
if cls.set_topup_reset_action(
        subscription_code,
        new_base_balance,
):
    # 3. renew filters
    new_base_balance_20_percent = math.floor((Decimal(
        new_base_balance) * Decimal(20)) / Decimal(100))
    if cls.set_filter_80_percent(
            subscription_code,
            new_base_balance_20_percent,
    ) and cls.set_filter_100_percent(
        subscription_code,
    ):
        # 4. renew thresholds
        if cls.set_threshold_profile_80_percent(
                subscription_code,
        ) and cls.set_threshold_profile_100_percent(
            subscription_code,
        ):
            return True
return False

Python 3.x – Fast Performance of Selecting a Single Value in a Binary Matrix File

I've written this code to read a square matrix saved as a binary file, that it can be int, uint, float etc … to choose a value in the matrix of a given line y and column given x.
Could this code be faster to choose this value, greater than 20 seconds.
The maximum number of rows and columns in the matrix is 鈥嬧3601 for each one.

import struct

#convert x,y indexes of 2D array into index i of 1D array
#x: index for cols in the 2D
#y: index for rows in the 2D
def to1D(y,x,width):
    i = x + width*y
    return i


def readBinary_as_int(filename,x,y,file_type,width=3601):
    with open(filename,'rb') as file_data:

        #initialize, how many bytes to be read
        nbByte = 0
        #data type of the file, uint, int, float, etc...
        coding = ''
        if file_type == "signed int":
            nbByte = 2
            coding = '>h'  #2B Signed Int - BE

        if file_type == "unsigned int":
            nbByte = 2
            coding = '>H' #2B Unsigned Int - BE

        if file_type == "unsigned byte":
            nbByte = 1
            coding = '>B' #1B Unsigned Byte - BE

        if file_type == "float":
            nbByte = 4
            coding = '>f' #4B float32 - BE

        #index of my value in 1D array
        i = to1D(y,x,width)
        for each_cell in range(0,i):
            file_data.read(nbByte)

        #read and save the picked value
        my_value_pos = file_data.read(nbByte)
        val = struct.unpack(coding,my_value_pos)(0)
    return val

python – Pickle: the .py file does not open the GUI to try to import a model formed via pickle

I have created a GUI program that provides a value based on the input values.

The prediction is performed using a network of neurons trained and recorded with the help of Pickle.

When running the algorithm via Python, the GUI works properly. However, opening the .py file only displays the black screen, which disappears a few seconds later.

Is it possible to run the program by loading the model formed?

Thank you

Transparency in Label tkinter [Python]

Well, there is a form or an attribute that allows me to paste the label on a picture of the window, I am doing a project and I get it that way.

enter the description of the image here

Invalid Python syntax, what's wrong or missing?

Usually when this error occurs SyntaxError: invalid syntax In the correct syntax, you must look at the previous line to indicate that you may have forgotten to close some brackets or parentheses.

That's exactly what happened in your code note:

print('{:=^40}'.format(' SIMULADOR DE JUROS COMPOSTOS '))
print(''' ESCOLHA A OP脟脙O
(1) Para Juros
(2) Para Capital
(3) Para Taxa
(4) Para Tempo''')
opcao = int(input('Qual a sua op莽茫o? '))
if opcao == 1:
        capital = float(input('Entre com o capital '))
        taxa = float(input('Entre com a taxa '))
        tempo = float(input('Entre com o tempo ' ))
        print('O valor do Juros 茅: ',capital*(((1+(taxa/100))**tempo)-1))
elif opcao == 2:
    juros = float(input('Entre com o Juros '))
    taxa = float(input('Entre com a taxa '))
    tempo = float(input('Entre com o tempo ' ))
    print('O valor do Capital 茅: ',juros/(((1+(taxa/100)**tempo)-1)))
elif opcao == 3:
    capital= float(input('Entre com o capital '))
    juros = float(input('Entre com o Juros '))
    tempo = float(input('Entre com o tempo ' ))
    print('O valor da Taxa 茅: ',(((capital+juros)/capital)**(1/tempo))-1)
elif op莽茫o==4:
    juros = float(input('Entre com o Juros '))
    capital= float(input('Entre com o capital '))
    taxa = float(input('Entre com a taxa '))

    print('o valor o tempo 茅: ',(ln((capital+juros)/capital))/(ln(1+(taxa/100))))
else:
    print ('Op莽茫o inv谩lida. Tente novamente')

script – Decoding hexadecimal scripts in Python

Operation decodescript sure d1a076722d11ddfd0fadb96d6d960b8b2ad6c6369570cd00df70a801a6be9e44 is back:

{
"asm": "0 30440220278ee027abaf4720f580ce469139d75e330e120f91ff52b2c73955a712b96f3902204f11b7b1541dee5497cffd50291347b796e44ab1b6dac845d43a7185fdda184901 3045022100c3602c2872248e73f543fbf21ddc9fa3b73052261f619452fd5254852c9ea55102202c1323830f38a6fe149e0eccb18f92eba962165733285812deb96bcb8482de5d01 30450221008caaadf9b887828d02911ff22df335606c372f968d5c2ea0fa2f8c1a083fe5f502204c55eb85c0f06e10d488d7643a5c571bbabdeb935acc917836d44e755db6b1f601 532102939a016f9a4cfc4c73ba395c2baf16382a4de078dadf2bafaaac6846d786ed392102c7cf0bd62fb500d8f6ed39a46c7e72dc1b5185754e1a48d25a22195f113b35d8210306179c491a25d6db330a3a3e3ba0788b3ccea45aebfa2a06fc114787aadc01532103b8a79bd499afbc0f4b68e4c0e175176a013b1e2143da6ec95772add5c6728d6d2103bec7b18285d7af85b4f2c0936a106b746eaad14071f41788257fdffeb2e68e9a2103e4fda639ffcf2d996dc372db5eda18857afdd21054009d65ddd17ce96d5feed22103f5d1065abd2a8b5adc6ecda48712d2a572a24130b786f538629ff834b298379857ae",
"type": "nonstandard",
"p2sh": "32QZxW8qHSufifvr5UzXpzGG6jdcgnTCSF",
"segwit": {
"asm": "0 59d0d03149e611e8f8e879ab7c1133c99091ec09758ed29a9111341e424d9891",
"hex": "002059d0d03149e611e8f8e879ab7c1133c99091ec09758ed29a9111341e424d9891",
"reqSigs": 1,
"type": "witness_v0_scripthash",
"addresses": [
"bc1qt8gdqv2fucg7378g0x4hcyfnexgfrmqfwk8d9x53zy6pusjdnzgsdvlm7s"
],
"p2sh-segwit": "36sk1CLrrv8HXgE1d1CKkNkwnK2tWKeWSL"
}
}

The hexagon of origin:

004730440220278ee027abaf4720f580ce469139d75e330e120f91ff52b2c73955a712b96f3902204f11b7b1541dee5497cffd50291347b796e44ab1b6dac845d43a7185fdda184901483045022100c3602c2872248e73f543fbf21ddc9fa3b73052261f619452fd5254852c9ea55102202c1323830f38a6fe149e0eccb18f92eba962165733285812deb96bcb8482de5d014830450221008caaadf9b887828d02911ff22df335606c372f968d5c2ea0fa2f8c1a083fe5f502204c55eb85c0f06e10d488d7643a5c571bbabdeb935acc917836d44e755db6b1f6014cf1532102939a016f9a4cfc4c73ba395c2baf16382a4de078dadf2bafaaac6846d786ed392102c7cf0bd62fb500d8f6ed39a46c7e72dc1b5185754e1a48d25a22195f113b35d8210306179c491a25d6db330a3a3e3ba0788b3ccea45aebfa2a06fc114787aadc01532103b8a79bd499afbc0f4b68e4c0e175176a013b1e2143da6ec95772add5c6728d6d2103bec7b18285d7af85b4f2c0936a106b746eaad14071f41788257fdffeb2e68e9a2103e4fda639ffcf2d996dc372db5eda18857afdd21054009d65ddd17ce96d5feed22103f5d1065abd2a8b5adc6ecda48712d2a572a24130b786f538629ff834b298379857ae

The Blockstream explorer returns the script in the form of OP_CODE, my question is: is there a python library able to decode it in the same state?

enter the description of the image here