Author: adiyatmubarak

Split Camel Case String in Python

import re

def camel_case_split(identifier):
    matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
    return [m.group(0) for m in matches]

Reference: https://stackoverflow.com/a/29920015/1936697

Advertisements

Fixing Git: refusing to merge unrelated histories

I have a new project and I add git repo later on after the project finished.
After setup remote repo to my project, I got this kind of error when pulling data from the repository.

fatal: refusing to merge unrelated histories

The problem fixed by adding this argument to git command “–allow-unrelated-histories”.

$ git pull upstream master --allow-unrelated-histories

Reference: https://stackoverflow.com/a/37938036/1936697

Comment And Uncomment Lines in Vim

I used to use IDE and I’m sure all of you familiar with command Ctrl + / or Cmd + / to add comment to your codes.

And here is how to bring that magic to VIM. Put these following lines to your .vimrc

" Commenting blocks of code.
autocmd FileType c,cpp,java,scala let b:comment_leader = '// '
autocmd FileType sh,ruby,python let b:comment_leader = '# '
autocmd FileType conf,fstab let b:comment_leader = '# '
autocmd FileType tex let b:comment_leader = '% '
autocmd FileType mail let b:comment_leader = '> '
autocmd FileType vim let b:comment_leader = '" '
noremap ,cc :silent s/^/=escape(b:comment_leader,'\/')/:nohlsearch
noremap ,cu :silent s/^\V=escape(b:comment_leader,'\/')//e:nohlsearch

Now you can select your text and type ,cc to comment and ,cu to uncomment.

Reference: https://stackoverflow.com/a/1676672/1936697

Adding Sublime Text Command in OSX Terminal

Create a symbolic link from sublime text installation.

$ ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" /usr/local/bin/subl

Then you can use this command to open text file or folder.

$ subl .  # Open current directory
$ subl path/to/file.txt

Reference: https://stackoverflow.com/a/31771252/1936697

 

Fix Django “Illegal mix of collations”

I have json file contains text non ASCII such kanji, tagalog etc.

{
    "Peru": ["S.A. - Sociedad Anónima", "S.A.A. - Sociedad Anónima Abierta"],

    "Philippines": ["Co. - Company", "Coop. - Cooperative", "Corp. - Corporation", "Ent. - Enterprise", "Inc. - Incorporated", "LLC - Limited Liability Company", "Ltd. - Limited", "Ltd. Co. - Limited Company", "Cía - Compañía", "SA - Sociedad Anónima"],

    "Poland": ["jednoosobowa działalność gospodarcza", "Przedsiębiorstwo Państwowe", "S.A. - spółka akcyjna", "s.c. - spółka cywilna", "S.K.A. - spółka komandytowo-akcyjna", "sp.j. - spółka jawna", "sp.k. - spółka komandytowa", "sp.p. - spółka partnerska", "Sp. z o.o. - spółka z ograniczoną odpowiedzialnością", "Spółdzielnia"],

    "Portugal": ["CRL - Cooperativa de Responsabilidade Limitada", "S.A. - Sociedade Anónima", "S.A. - Sociedade Aberta", "S.F. - Sociedade Fechada", "Lda. - Limitada", "Unipessoal Lda.", "SGPS - Sociedade Gestora de Participações Sociais"],

    "Romania": ["SNC - Societatea în nume colectiv", "SCS - Societatea în comandită simplă", "SCA - Societatea în comandită pe acțiuni", "SA - Societatea pe acțiuni", "SRL - Societatea cu răspundere limitată", "SRL cu proprietar unic - Societatea cu răspundere limitată cu proprietar unic", "S.A. - Societate pe Acţiuni", "S.C.A. - societate în comandită pe acţiuni", "S.C.S. - societate în comandită simplă", "S.N.C. - societate în nume colectiv", "S.R.L. - societate cu răspundere limitată", "PFA - persoana fizica autorizata", "O.N.G. - Organizație Non-Guvernamentală"],

    "Rusia": ["Nekommercheskaya organizatsiya/некоммерческая организация", "GP/ГП, GUP/ГУП - Gosudarstvennoye unitarnoye predpriyatie/Государственное унитарное предприятие", "IP/ИП - Individualny predprinimatel/Индивидуальный предприниматель", "OOO - Obshchestvo s ogranichennoy otvetstvennostyu/Общество с ограниченной ответственностью", "ПAO - Publichnoye aktsionernoye obshchestvo/Публичное акционерное общество", "kooperativ/кооператив", "AO - Aktsionernoye obshchestvo/Акционерное общество", "Prostoye Tovarishestvo - general partnership", "Kommanditnoe Tovarishestvo - limited partnership", "Hozyaystvennoe Partnerstvo - business partnership"],

    "Saudi Arabia": ["شركة ذات مسئولية محدودة - Private Limited Company", "شركة مساهمة - Joint-Stock company", "شركة تضامن - General Partnership Company", "شركة التوصية البسيطة - Limited Partnership", "شركة أجنبية - Foreign Company", "مؤسسة فردية - Individual Establishment"],
}

And I’m creating a script to read those data and insert into my database.
I’m using Django using MariaDB as my database and I found this error while inserting to the database.

django.db.utils.OperationalError: (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='")

After several minutes find a solution, the issue occurs because python using unicode string but my database doesn’t.

To fix this issue, I just need to update my database table collation in shell following below.

ALTER TABLE my_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

Reference: https://stackoverflow.com/a/7083511/1936697

Handle Base64 Encoded Binary File in DRF

I’m writing a simple class for DRF field for handling base64 string for attachment both image and file. I’m using DRF 3 at this case.

And here is how to use it following below.

class MyModelSerializer(serializers.ModelSerializer):
    company_logo = Base64CharField(required=False)

    class Meta:
        model = MyModel
        fields = '__all__'

Feel free to use and improve my code. 😀