text_a
stringlengths
9
150
text_b
stringlengths
18
20.9k
labels
int64
0
2
find in files using ruby or python
pi know you said you dont feel like writing it yourself but for what its worth it would be very easy using codeoswalkcode you could do something like thisp precoderesults if regexsearch p recompilesearchtext for dir subdirs subfiles in oswalkcdocs2009 for name in fnmatchfiltersubfiles txt fn ospat...
2
python fast way to remove duplicates in this list
precodegtgtgt a hello hi hello hi how what hello hi how what gtgtgt setmaptuple a sethow what hello hi codepre
2
most pythonic way to read csv values into dict of lists
pdepending on what type of data youre storing and if youre ok with using numpy a good way to do this can be with a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpygenfromtxthtml relnofollowcodenumpygenfromtxtcodeap precodeimport numpy as np data npgenfromtxtdatacsv delimiter namestrue codepre pwhat this will do i...
2
how to reverse string with stride via python string slicing
pyou can bring several ideas to a hrefhttpstackoverflowcomquestions9475241splitpythonstringeverynthcharactersplit a string in piecesa and then reverse each piece and reassemble join the list reversed toop peg using satomacoto answer in a notsoreadable wayp precodejoina1ii21 for i in range0 lena 2 codepre por using ...
2
object does not support item assignment error
pthe error seems clear model objects do not support item assignment codemymodelobjectslatestidfoo barcode will throw this same errorp pits a little confusing that your model instance is called codeprojectformcodep pto reproduce your first block of code in a loop you need to use codesetattrcodep precodefor kv in ses...
2
how to use array in django
pyou may be interested in using a a hrefhttpdocsdjangoprojectcomendevrefmodelsfieldscommaseparatedintegerfieldcodecommaseparatedintegerfieldcodeap pif youve got a list of integers like thisp precodemyints 12345 codepre pand a model like thisp precodeclass mymodelmodelsmodel values commaseparatedintegerfieldma...
2
forgetting to return the result from a function how to prevent this bug
ppylint will sometimes catch this kind of error in particular if you assign to coderesultcode but then never use itp precodepylint zorgpy module zorg w0612 5zorg unused variable result codepre phowever it does not catch the case where you build up coderesultcode in pieces and then forget to return it because then ...
2
proper way to migrate ndb model property
pyou can change the classlevel property name while keeping the underlying ndb property name by specifying the strongnamexxstrong param in the property constructorp pso something like this could be donep precodeclass userndbmodel company ndbkeypropertynamecompany repeatedtrue property def companyself return ...
2
modify an xml file in python
puse elementtreep precodefrom xmletreeelementtree import element subelement comment tostring configure one attribute with set root elementopml rootsetversion 10 rootappendcommentgenerated by elementtreecsvtoxmlpy for pymotw codepre pa hrefhttpbroadcastoreillycom201003pymotwcreatingxmldocumentshtml relnofollowhttp...
2
why it works about python type conversion
papart from when specifying function arguments codexcode is the same as codexcode so codeint100code is equivalent to codeint100codep pthey even compile to the same bytecodep precodegtgtgt import dis gtgtgt disdislambda int100 1 0 loadglobal 0 int 3 loadconst 1 100 ...
2
write a comma in csv file using python
puse the proper a hrefhttpdocspythonorgrelease264librarycsvhtmlwriterobjects relnofollowcsv writersap precodegtgtgt import csv gtgtgt spamwriter csvwriteropeneggscsv wb gtgtgt spamwriterwriterowspam lovely spam codepre poutputsp blockquote pspamlovely spamp blockquote
2
nesting functions in python
pyour problem is that codetxtreversecode does not return the reversed list it returns codenonecodep pie codetxtreversecode reverses your list in placep
2
python finding the longest sequence with findall
pcoderedotallcode does nothing in this case so ive just taken it out for simplicitys sakep precodegtgtgt import re gtgtgt maxrefindallg fggfggggfggfg keylen gggg codepre pif you need all of them in order of lengthp precodegtgtgt sortedrefindallg fggfggggfggfg keylen reversetrue gggg gg gg g codepre
2
python builtin types subclassing
pyou need to call the list initializerp precodeclass mylistlist def initself li supermylist selfinitli codepre passigning to codeselfcode in the function just replaces the local variable with the list not assign anything to the instancep precodegtgtgt class mylistlist def initself li su...
2
how to get started with a barebones eclipse pydev
pthe leanest eclipse installation is the a hrefhttpdownloadeclipseorgeclipsedownloadsdrops4r442201502041700 relnofollowplatform runtime binarya at around 50mb look for it in the middle of the page install it and then once in eclipse go to helpinstall new software and use a hrefhttppydevorgupdates relnofollowhttppydevor...
2
replace str method on list object in python
pthis solution works without a wrapper and works if you join two lists by add any operation that modify the list itself will work as expected only functions that return a copy of the list like sorted reveresed will return the native python list which is fine sort and reverse on the other hand operate on the list itself...
2
how to create a loop from 19 and from az
prather than create a range loop over a emstringem to get individual charactersp precodeimport string for character in stringasciilowercase stringdigits1 print character codepre pthis uses the a hrefhttpsdocspythonorg2librarystringhtmlcodestringcode modulea to grab predefined strings of ascii lowercase letters ...
2
python for loop with range
pyoure missing the fact that codenumscode is getting filtered on every iteration so on the first iteration all numbers for which x 2 is not 0 which includes 4 are filtered outp pif you put an extra codeprint numscode within the loop after the filter you would see this more clearlyp
2
script slicing in python
pthis is where list comprehensions become really handyp precodegtgtgt newlist partiye oy vermeyecegimi bilerek sandiga gidecegim gtgtgt print i6 for i in newlist partiy oy vermey bilere sandig gidece codepre pif you wanted to expand itp precodes for i in newlist sappendi6 codepre pits pretty much the same ap...
2
upload file to my dropbox from python script
pthanks to smarx for the answer above i just wanted to clarify for anyone else trying to do this p ol lipmake sure you install the dropbox module first of course codepip install dropboxcode pli lipcreate an app under your own dropbox account in the app console a hrefhttpswwwdropboxcomdevelopersappshttpswwwdropboxcomd...
2
any gotchas using unicodeliterals in python 26
palso take into account that codeunicodeliteralcode will affect codeevalcode but not codereprcode an asymmetric behavior which imho is a bug ie codeevalreprbxa4code wont be equal to codebxa4code as it would with python 3p pideally the following code would be an invariant which should always work for all combinations o...
2
difference between python lambda functions inside class and def
pyour problem here is the difference between bound methods and functionsp phave a simpler examplep precodeclass someclassobject bound lambda args bound method got formatargs def initself selfunbound lambda args function got formatargs codepre precodegtgtgt c someclass codepre pif we look closel...
2
python import vs execfile
panother difference execfile gets a context dictionary the global context by default or a specified dictionary this could allow some strange thingsp pcodedontdothispycodep precode probably not a good thing to do zx1 an expression that involves an undefined field codepre pobviously p precodefrom dontdothis import...
2
finding how many different letters there are in a string in python
ptry looking at the length of the set of lettersp precodelensetyourstring in 8 setlowercase out8 seta c e l o s r w in 9 lensetlowercase out9 8 codepre pnbspp pdont forget to remove spacesp precodein 10 lensetthe quick brown fox jumps over the lazy doglowerreplace out10 26 codepre
2
can listdisplay in a django modeladmin display attributes of foreignkey fields
pyou can show whatever you want in list display by using a callable it would look like thisp pre def bookauthorobject return objectbookauthor class personadminadminmodeladmin listdisplay bookauthorpre
2
why are list dict and tuple slower than and
pthe function call requires a variable name lookup followed by a function invocation the function called then creates a list and returns it the list syntax literal gets the interpreter to just make a listp precodegtgtgt import dis gtgtgt foo lambda gtgtgt bar lambda list gtgtgt disdisfoo 1 0 buildlist...
2
formating string in c
pclosest implementation would bep precodeinclude ltstdiohgt int mainvoid char text100 int var1 10 int var2 45 int var3 76 sprintftext numbers are d d d var1 var2 var3 codepre
2
is it possible to run function in a subprocess without threading or writing a separate filescript
pi think youre looking for something more like the multiprocessing modulep pa hrefhttpdocspythonorglibrarymultiprocessinghtmltheprocessclasshttpdocspythonorglibrarymultiprocessinghtmltheprocessclassap pthe subprocess module is for spawning processes and doing things with their inputoutput not for running functionsp ...
2
chained nested dict get calls in python
phow about using a small helper functionp precodedef getnd path for p in path if p not in d return none d dp return d codepre pand thenp precodegetnm gparents parent child for m in m codepre
2
python difference between and is not
pcodeiscode tests for object identity but codecode tests for object value equalityp precodein 1 a 3424 in 2 b 3424 in 3 a is b out3 false in 4 a b out4 true codepre
2
python tuple question
pif you just put code1000code python assumes youre just evaluating the expression as math hence it gets simplified to just 1000 think of the result of code5 1000 4codep pjust as the expression above would get simplified to code1009code here is what your line looks like once things have been simplifiedp precodep mu...
2
how do i make this list function faster
precodeimport collections def countworddistancesli wordmap collectionsdefaultdictlist for i w in enumerateli 1 wordmapwappendi for k v in wordmapiteritems wordmapk sumvfloatlenv return wordmap codepre pthis makes only one pass through the list and keeps operations to a minimum i tim...
2
allow all method types in flask route
pyou can change the urlmap directly for this by adding a a hrefhttpwerkzeugpocooorgdocsroutingwerkzeugroutingrulecoderulecodea with no methodsp precodefrom flask import flask request import unittest from werkzeugrouting import rule app flaskname appurlmapaddrule endpointindex appendpointindex def index return r...
2
how to return a static html file as a response in django
pif your css and js files are static dont use django to serve them or a hrefhttpsdocsdjangoprojectcomenstablehowtostaticfiles relnofollowserve them as static filesap pfor your html you could do the same if it is just some fixed file that wont have any dynamic content you could also use a hrefhttpsdocsdjangoprojectcome...
2
cascadeforward neural network
pif i understand correctly you want to connect your input layer to both hidden layer and directly to the output layerp pwhat if you simply create an additional fullconnection from input layer to output layer p precodefrom pybrainstructure import feedforwardnetwork n feedforwardnetwork from pybrainstructure import li...
2
generic way to get primary key from declaratively defined instance in sqlalchemy
pyou can use codeinspectioncode for that purposep pa hrefhttpdocssqlalchemyorgenlatestcoreinspectionhtml relnofollowhttpdocssqlalchemyorgenlatestcoreinspectionhtmlap ppassing an instance of a mapped object to inspect returns an codeinstancestatecode describing that object this state also contains the identityp preco...
2
non numerical indexing in multidimensional matrices lists
pyou can use a hrefhttppandaspydataorgpandasdocsstablegeneratedpandasdataframelochtml relnofollowcodeloccodeap precodeimport pandas as pd mat pddataframethree a 3 b 6 two a 2 b 5 one a 1 b 4 columns onetwothree print mat one two three a 1 2 ...
2
how to disable formatting for floatfield in template for django
precode floatvarstringformatf codepre
2
webpy obtain request headers
pthe a hrefhttpwebpyorgcookbookctxcodewebctxenvcodea structure gives you access to the a hrefhttpwwwpythonorgdevpepspep0333environvariableswsgi environment variablea in wsgi apps the content type header is named codecontenttypecodep precodect webctxenvgetcontenttype codepre
2
python library to modify mp3 audio without transcoding
pi got three quality answers and i thank you all and upvoted you all for them i havent chosen any as the accepted answer because each addressed one aspect so i wanted to write a summaryp pstrongdo you need to work in mp3strongp ul liptranscoding to pcm and back to mp3 is unlikely to result in a drop in quality pli li...
2
how do you use initpy
pyou also need to have initpy in a and b directoriesp pfor your example to work first you should add your base directory to the pathp precodeimport sys syspathappend import inittestaaaa codepre
2
import statement after function definition how can i make it more pythonic
phow about putting the functions in two different modulesp pcodemodule1codep precodeimport win32file def findfilewildcard returns path of the first matched file using win32file gtgtgt findfile1dpython26exe dpython26pythonexe return filepath codepre pcodemodule2codep precodeimport glob def fin...
2
identical error codes
pit appears python is exposing the error code from the os the interpretation of the code is osdependentp p111 is codeeconnrefusedcode on many linux systems and on cygwinp p146 is codeeconnrefusedcode on solarisp p10061 is codewsaeconnrefusedcode in winerrorh its the windows socket apis version of codeeconnrefusedc...
2
python math module
pcodepowcode is built into the languagenot part of the math library the problem is that you havent imported math p ptry thisp precodeimport math mathsqrt4 codepre
2
what is wrong with my algorithmcode
pin else clause put p precodeconductivitysum0 datapoint0 tempcheck tempi conductivitysumconductivityi datapoint1 codepre pbecause when you go to else clause you miss that particular conductivity of i it doesnt get saved so before moving to next i save that conductivityp
2
do oo design principles apply to python
pthe biggest differences are that python is duck typed meaning that you wont need to plan out class hierarchies in as much detail as in java and has first class functions the strategy pattern for example becomes much simpler and more obvious when you can just pass a function in rather than having to make interfaces et...
2
using pythons sysargv to return function results to command line
pok i might as well post this as my answer instead of just a commentp pinp precodeprint dictionaryagrv codepre pcodeargvcode is misspelledp pit should be p precodeprint dictionarysysargv codepre palso use codesysargvcode codeargvcode by itself wont sufficep
2
i dont understand jinja2 call blocks
pthis is the outputp precodeltdiv classdialoggt lth2gthello worldlth2gt ltdiv classcontentsgt this is a simple dialog rendered by using a macro and a call block ltdivgt ltdivgt codepre pso when we call renderdialog we pass hello world as title when it reach codecallercode it passes the contents o...
2
encoding issue with asciisafe file with codec header depending on line count
pthis looks like a regression caused by a hrefhttpbugspythonorgissue20731 relnofollowissue 20731a it looks like the position calculation is assuming there will always be crlf line endings while your file has only got lf characters leading to an incorrect offset a hrefhttpshgpythonorgcpythonfilev352parsertokenizercl510 ...
2
fastest way to load a screenshot into memory for cv template matching
pa hrefhttpslaunchpadnetxpresser relnofollowxpressera is a project that works in ubuntu that also uses opencv in the a hrefhttpbazaarlaunchpadnetniemeyerxpressertrunkviewheadxpresserxutilspy relnofollowxutils modulea theres a function to take a screenshot which is as followsp precodedef takescreenshotx0 y0 widthnone h...
2
what is a pythonic way to alter a dict with a key and multiple values to get the desired output
pmaking extensive use of generators and list comprehension you can write it like thisp pre classlangpython prettyprintoverridecodeother other unknown strings denoting noncontries ids seti for ij in mylist all ids in the list known seti for ij in mylist if j not in other...
2
trying to catch integrity error with sqlalchemy
pthere might be no database operations until codedbsessioncommitcode therefore the codeintegrityerrorcode is raised later in the stack after the controller code that has codetryexceptcode has already returnedp
2
how do numpy and gmpy2 compare with gmp in terms of speed
pnumpy and gmpy2 have different purposesp pnumpy has fast numerical libraries but to achieve high performance numpy is effectively restricted to working with vectors or arrays of lowlevel types 16 32 or 64 bit integers or 32 or 64 bit floating point values for example numpy access highly optimized routines written in...
2
python behavior of string in loop
pyou could use a hrefhttpdocspythonorglibrarystdtypeshtmlstrtitle relnofollowcodetitlecodeap precodegtgtgt s thesethreewords gtgtgt print stitle thesethreewords codepre
2
pythonregex match in string
pto allow for multiple consecutive matches use lookaheadlookbehindp precoderltdd codepre pexamplep precodegtgtgt refindallrltdd test75678test 56 78 codepre pwe can also use lookahead to perform the split as you want itp precodeimport re def splitits pieces resplitrdd s pieces1 pieces1rsplit 1 split off ...
2
more concise comparison of two lists
puse codeanycode or codeallcode to test respectively if a condition holds for any element or all of the elements in a list coupled with codezipcode to stick together the two lists for example the code in the question can be implemented more concisely like thisp precodenot anyx gt y for x y in zipt1 t2 gt true codepre ...
2
if else in a list comprehension
pyou could move the conditional top precodev 22 13 45 50 98 69 43 44 1 x1 if x gt45 else x5 for x in v codepre pbut its starting to look a little ugly so you might be better off using a normal loop note that i used codevcode instead of codelcode for the list variable to reduce confusion with the number 1 i think ...
2
with statement backport for python 25
pwithstatement wasnt back ported but implemented in python 25 adding new keywords or syntax can break existing applications with python the way they decided to handle this is allow people to optin to those features early so you can slowly transition your code overp pfrom a hrefhttppythonorgdoc252reffuturehtml relnof...
2
implementing use of with object as f in custom class in python
pthe first google hit for me explains it simply enoughp pa hrefhttpeffbotorgzonepythonwithstatementhtm relnofollowhttpeffbotorgzonepythonwithstatementhtmap pand the pep explains it more precisely but also more verboselyp pa hrefhttpwwwpythonorgdevpepspep0343 relnofollowhttpwwwpythonorgdevpepspep0343ap
2
is it possible to colour a specific item in a listbox widget
paccording to the codeeffbotorgcode documentation regarding the a hrefhttpeffbotorgtkinterbooklistboxhtmtkinterlistbox relnofollowcodelistboxcodea widget you cannot change the color of spefic itemsp blockquote pthe listbox can only contain text items and all items must have the same font and colorp blockquote pbut ...
2
matplotlib quiver and imshow superimposed how can i set two colorbars
psimply call codecolorbarcode twice right after each plotting call pylab will create a new colorbar matching to the latest plot note that as in your example the quiver values range from 01 while the imshow takes negative values for clarity not shown in this example i would use different colormaps to distinguish the two...
2
delay a task until certain time
pyou could instead use the codepausecode package a hrefhttpspypipythonorgpypipause012 relnofollowhttpspypipythonorgpypipause012a taking an example from their documentation p precodeimport pause datetime dt datetimedatetime2013 6 2 14 36 34 383752 pauseuntildt codepre
2
convert unicode codepoint to utf8 hex in python
precodedatafromfileufd9b unicodedatafromfileunicodeescapeencodeutf8 codepre
2
how to make menuaddcommand work in tkinter on the mac
pi dont think you can do that with the native aqua tk on os x and you probably shouldnt try os x native menus dont work like that and tk tries to follow apples a hrefhttpsdeveloperapplecomlibrarymacdocumentationuserexperienceconceptualosxhiguidelinesmenuappearancebehaviorhtmlapplerefdocuid20000957ch23sw1 relnofollowhu...
2
python help reading csv file failing due to lineendings
pthe two occurrences of xd5 in line 194 and the last line have nothing to do with the problemp pthe problem appears to be a bug or a misleading error message or incorrectvague documentation in the python 26 csv modulep pin the file the lines are terminated by x0d aka r in the classic mac tradition the last line is no...
2
how to convert colors into strings with the same size
passuming you are using python 26 or newer you can use a hrefhttpdocspythonorglibrarystdtypeshtmlstrformat relnofollowcodestrformatcodeap precodeprint 002102202formatselfr selfg selfb codepre pif you want hexadecimal probably you do then add an xp precodeprint 002x102x202xformatselfr selfg selfb codepre
2
writing header with dictwriter from pythons csv module
pa few optionsp p1 laboriously make an identitymapping ie donothing dict out of your fieldnames so that csvdictwriter can convert it back to a list and pass it to a csvwriter instance p p2 the documentation mentions the underlying codewritercode instance so just use it example at the endp precodedwwriterwriterowdwf...
2
how to create objects on the fly in python
puse a hrefhttpdocspythonorglibrarycollectionshtmlcollectionsnamedtuplecodecollectionsnamedtuplecodeap
2
python fabric passing host as arguemnt
precodefabfilepy from fabricapi import run env envuser root envkeyfilename homeubuntusshidrsa def test runmkdir p homeubuntu fabric fab test h 111111111111 gtgtgt1921689920 executing task test gtgtgt1921689920 run mkdir p homeubuntu gtgtgt gtgtgtdone codepre ph opstion sets envhosts to the given commadelimite...
2
how to login users with email and log them out with django rest framework json web tokens
ol liwhen using jwt for authentication youd usually store the token in the browsers localstorage or sessionstorage to logout you just remove the token theres nothing else to invalidateli lione of the benefits of using this kind of approach for authentication is that tokens are not persisted in the database so you dont ...
2
performance searching a string in a text file python
precodecounterword for word in mytext if word in mydates codepre pi think would work quickly well on ishp
2
writing list of dict into file in python
pheres a way to write out the data using a dynamic list of headersp precodenewlist tablea columnc1 datatypeint tablea columnc2 datatypevarchar tablea columnc2 datatypenumeric header newlist0keys with openmyloglog w as log logwritejoinheader logwriten for data in newlist logwr...
2
in python assign a value based on dictionary mapping
pyou reassigned codepoz0code to a different object namely the value of codesome value str0code the assignment operator codecode does not modify codepoz0codes value but changing the binding in the codedictcodep
2
how to avoid slack command timeout error
paccording to the slack a hrefhttpsapislackcomslashcommandsrespondingtoacommandslash command documentationa you need to respond within 3000ms three seconds if your command takes longer then you get the codetimeout was reachedcode error your code obviously wont stop running but the user wont get any response to their co...
2
how to set utc offset for datetime
pthe a hrefhttpdocspythonorg2librarydatetimehtml relnofollowcodedatetimecode module documentationa contains an example codetzinfocode class that represents a fixed offsetp precodezero timedelta0 a class building tzinfo objects for fixedoffset time zones note that fixedoffset0 utc is a different way to build a utc...
2
is there a standard function to iterate over base classes
pthere is a method that can return them all in method resolution order mro codeinspectgetmrocode see herep pa hrefhttpdocspythonorglibraryinspecthtmlinspectgetmrohttpdocspythonorglibraryinspecthtmlinspectgetmroap pit returns them as a tuple which you can then iterate over in a single loop yourselfp precodeimport ins...
2
python why do some packages get installed as eggs and some as egg folders
pa single egg file is in fact a zip archive with a particular directory structure inside per the a hrefhttpdocspythonorglibraryzipimporthtml relnofollowzipimporta documentation only codepycode codepyccode and codepyocode files can be imported from zip files so if the package needs to import other kinds of module resour...
2
how to access index in a pandas hdstore pytables
pthe multiindex example from the a hrefhttppandaspydataorgpandasdocsdeviohtmlstoringmultiindexdataframes relnofollowdocsap precodein 21 index multiindexlevelsfoo bar baz qux one two three labels0 0 0 1 1 2 2 3 3 3 ...
2
is any elegant way to make a list contains some integers to become a list contains some tuples
precodea2i a2i1 for i in rangelena2 codepre pthis is of course assuming that lena is an even numberp
2
accessing a value in a tuple that is in a list
pa list comprehension is absolutely the way to do this another way that emshouldem be faster is codemapcode and codeitemgettercodep precodeimport operator newlist mapoperatoritemgetter1 oldlist codepre pin response to the comment that the op couldnt find an answer on google ill point out a super naive way to do itp...
2
python sort a list by most comment element
pif your list contains other lists you could convert nested lists to tuples first before countingp precodefrom collections import counter printcounterlistoftuplesmostcommon printcountermaptuple listoflistsmostcommon codepre
2
how do i write json data to a file in python
precodejsondumpdata opendatatxt wb codepre
2
regular expression matching all but a string
pyou can make use of negative look aheadsp pfor examplep precodegtgtgt refindallraabb string a bc def ghij codepre hr ul lipcodecode matches codecodepli lipcodeaabbcode negative lookahead checks if codecode is not followed by codeaacode or codebbcodepli lipcodecode matches ony or more character other than codecodep...
2
standard solution for decoding additive numbers
pyou want to use binary operations to decode the original the following code actually returns the correct stringsp precodegtgtgt flags user redo enqueue cache os real application clusters sql debug gtgtgt def getflagsvalue flags for i flag in enumerateflags if value amp 1 ltlt i flagsapp...
2
django edit queryset objects without affecting database
pone simple method is to convert the queryset to a list the list will contain instances of your model you can do whatever you like with those instances and nothing will be saved to the database unless you call codesavecode or one of the other methods that writes to the databasep precodedividendset stockdividendseta...
2
generator functions equivalent in java
phad the same need so wrote a little class for it here are some examplesp precodegeneratorltintegergt simplegenerator new generatorltintegergt public void run throws interruptedexception yield1 some logic here yield2 for integer element simplegenerator systemoutprintlnelement...
2
python pep8 and multiline dict formatting
pput the opening curly brace on the assignment linep precodeactivationgradclasses activationforwardstrictrelu activationbackwardstrictrelu activationforwardlog activationbackwardlog activationforwardsincos activationbackwardsincos codepre pthere emrarelyem is a need to use codecode to escape a newline ...
2
creating distinct objects in a function
pyou need to create two dictsp precodev codepre por use a loopp precodev for in range2 codepre pyou are creating a two references to the same objectp precodein 2 a 2 in 3 ida0 out3 140209195751176 in 4 ida1 out4 140209195751176 in 5 a0 is a1 out5 true in 6 a for in range2 in 7 ida1 out7 1402...
2
python convert string literal to float
pfloating point values cannot have a comma you are passing code123243123code as it is to float function which is not valid first split the string based on commap precodes 123243123 print ssplit 123 24 3123 codepre pthen convert each and and every element of that list to float and add them together to get the...
2
python memory management with list comprehensions
pi presume the issue is herep precodesmallcustdictcustid1 customerdictcustid1 smallcustdictcustid2 customerdictcustid2 a loop to round out the remaining allids object to fill in 0 values for customerid catalog in smallcustdictiteritems for id in allids if id not in catalog smallcustdictcusto...
2
how to multiply a super large number with a super small number in python
pwhen multiplying an extremely large number by an extremely small number working with floats can introduce huge inaccuracies in your case the magnitude of the numbers is causing overflow errors so you have bigger problems than just inaccuracies p pwhenever you find yourself in this situation it can be useful to first...
2
idiomatic clojure equivalent of this python code
preading that python snippet it looks like you want the eventual output to look likep precodecode load 0 load 1 add store 0 labels entry 0 codepre pits much easier to write the code once you have a firm description of the goal and indeed this is a pretty simple reduce there are a number of st...
2
remove duplicate data from an array in python
pas you dont care about the order of the items you keep you could dop precodegtgtgt intdd for d in datavalues 200012025 2002121575 2000121575 codepre hr pif you would like to keep the emlowestem item i cant think of a onelinerp phere is a basic example for anybody who would like to add a condition on the key or val...
2
python custom exception and subexceptions
pa standard technique would be to subclass codeconnectivityexceptioncode to create exception classes specific to each kind of error conditionp precodeclass connectivityexceptionexception pass class httpconnectivityexceptionconnectivityexception pass class ftpconnectivityexceptionconnectivityexception pass codepre p...
2
how to count values in a certain range in a numpy array
pyou could use codehistogramcode heres a basic usage examplep precodegtgtgt import numpy gtgtgt a numpyrandomrandomsize100 100 gtgtgt numpyhistograma bins00 73 224 555 77 79 98 100 array 8 14 34 31 0 12 1 array 0 73 224 555 77 79 98 100 codepre pin your particular case it would look someth...
2
the r2 score i get from gridsearchcv is very different from the one i get from crossvalscore why sklearn python
puse codepredictorbestestimatorcode as the estimator in codecrossvalscorecode this is the one with the best parameters the way you choose it you are probably obtaining the initial estimator with default parameters you could check by putting the latter in codecrossvalscorecode as well and comparing resultsp
2
why does return listsort return none not the list
pcodelistsortcode sorts the list in place ie it doesnt return a new list just writep precodenewlistsort return newlist codepre
2
trying to verify sha1 message signature using python what am i doing wrong
pyour code is work properly a hrefhttpsgistgithubcomkalloc5106808 relnofollowhttpsgistgithubcomkalloc5106808a i see something else wrong herep
2
splitting on last delimiter in python string
puse a hrefhttpdocspythonorg2librarystdtypeshtmlstrrsplitcodersplitcodea insteadp precodesrsplit 1 codepre pdemop precodegtgtgt s abcd gtgtgt srsplit 1 abc d gtgtgt srsplit 2 ab c d codepre pthis method starts splitting from the righthandside of the string by giving it a maximum you get to split just the righthand...
2
how to generate a fully connected subgraph from node list using pythons networkx module
pi dont know of any method which does this but you can easily mimic the completegraph method of networkx and slightly change italmost like a builtinp precodeimport networkx import itertools def completegraphfromlistl createusingnone g networkxemptygraphlenlcreateusing if lenlgt1 if gisdirected ...
2