questions
stringlengths
50
48.9k
answers
stringlengths
0
58.3k
Can python or JS hide video embedded source? I'm doing a video website right now and I would like to hide the embedded source of the video from being seen by beginner programmer. (I know they are no 100% way to hide the video embeded source).Any experience programmer knows how python or JS can help to do this? or it ca...
For Javascript, hiding code (almost) cannot be done!However, if your code is sensetive in any manner, try using obfuscators so that the code will not be readable by human eye.Here are few obfuscation services:Free Javascript Obfuscator: Javascript ObfuscatorUglify JS: Uglify JSJSObfuscate to Obfuscate JS/jQueryJScrambl...
How to concatenate database elements to a string I'm currently trying to take elements from a database to be displayed in a string by iterating through each row and adding it to an empty string. def PrintOverdueBooks(): printed_message = "" for row in db_actions.GetAllOverdue(): pr...
You can try this:def PrintOverdueBooks(): printed_message = '' for row in db_actions.GetAllOverdue(): stup = ''.join(row) printed_message += stup print(printed_message)
'DataFrame' object has no attribute 'value_counts' My dataset is a DataFrame of dimension (840,84). When I write the code:ds[ds.columns[1]].value_counts()I get a correct output:Out[82]:0 8471 5Name: o_East, dtype: int64But when I write a loop to store values, I get 'DataFrame' object has no attribute 'value_cou...
Thanks to @EdChum adviced, I checked :len(ds_wdire.columns),len(ds_wdire.columns.unique())Out[100]: (83,84)Actually, there was a missing name value in the dict that should have been modified from 'WNW' to 'o_WNW'.:o_wdire.rename(columns={'ENE': 'o_ENE','ESE': 'o_ESE', 'East': 'o_East', 'NE': 'o_NE', 'NNE': 'o_NNE', 'NN...
How to find ellipses in text string Python? Fairly new to Python (And Stack Overflow!) here. I have a data set with subject line data (text strings) that I am working on building a bag of words model with. I'm creating new variables that flags a 0 or 1 for various possible scenarios, but I'm stuck trying to identify w...
Using search() instead of match() would spot an ellipses at any point in the text. If you need 0 or 1 to be returned, convert to bool and then int.import refor test in ["hello..", "again... this", "is......a test", "...def"]: print int(bool(re.search(r'(\w+)\.{3,}', test)))This matches on the middle two tests:0110T...
google.cloud namespace import error in __init__.py I have read through at least a dozen different stackoverflow questions that all present the same basic problem and have the same basic answer: either the module isn't installed correctly or the OP is doing the import wrong.In this case, I am trying to do from google.cl...
It have to be installed via terminal: pip install google-cloud-secret-managerBecause package name is not secretmanager but google-cloud-secret-manager
Python - Multiple 'split' Error I posted here 4-5 days ago, about one problem to sort some numbers from file.Now, is the same of the other problem but, I want to sort numbers from one file (x) to another file (y). For example: In x i have: (5,6,3,11,7), and I want to sort this numbers to y (3,5,6,7,11). But I have some...
There are too many problems with your code for me to address. Try this:from sys import argvwith open(argv[1], "r") as infile: with open("nums_ordenats.txt", "w") as outfile: for line in infile: nums = [int(n) for n in line.split(',')] nums.sort() outfile.write(','.join([str(n)...
PyQT - QlistWidget with infinite scroll I have a QlistWidget and I need to implement on this an Infinite Scroll, something like this HTML example:https://scrollmagic.io/examples/advanced/infinite_scrolling.htmlBasically, when the user scrolls to the last item of the list, I need to load more items and dynamically appen...
There are likely many ways to achieve this task, but the easiest I found is to watch for changes in the scroll bar, and detect if we're at the bottom before adding more items to the list widget.import sys, randomfrom PyQt5.QtWidgets import QApplication, QListWidgetclass infinite_scroll_area(QListWidget): #https://doc.q...
How to correctly import custom widgets in kivy I have a widget(W2), made of other widgets (W1). Each has a corresponding .kv file as below. Running main.py, I expect to see a black background with two labels, vertically stacked. Instead, I get both labels on top of each other, so something has gone wrong.kivy.factory.F...
why are you using two different kv files for this?I would say the proper way would be similar to what i have with my kv file. because you are spliting up things that can be done on a single page and if you need different pages you use the ScreenManager import stuffmain.py:`import kivyfrom kivy.app import Appfrom kivy.u...
ImportError: cannot import name 'convert_kernel' When i try to use tensorflow to train model, i get this error message. File "/Users/ABC/anaconda3/lib/python3.6/site-packages/keras/utils/layer_utils.py", line 7, in from .conv_utils import convert_kernelImportError: cannot import name 'convert_kernel'i have already ...
I got the same issue. The filename of my python code was "tensorflow.py". After I changed the name to "test.py". The issue was resolved.I guess there is already a "tensorflow.py" in the tensorflow package. If anyone uses the same name, it may lead to the conflict.If your python code is also called "tensorflow.py", you ...
Python function that identifies if the numbers in a list or array are closer to 0 or 1 I have a numpy array of numbers. Below is an example:[[-2.10044520e-04 1.72314372e-04 1.77235336e-04 -1.06613465e-046.76617611e-07 2.71623057e-03 -3.32789944e-05 1.44899758e-055.79249863e-05 4.06502549e-04 -1.35823707e-05 -4.139...
A straightforward way:lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]closerTo1 = [x >= 0.5 for x in lst]Or you can use np:import numpy as nplst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]arr = np.array(lst)closerTo1 = arr >= 0.5Note that >= 0.5 can be changed to > 0.5, however you choose to treat it.
Python pandas: map and return Nan I have two data frame, the first one is:id code1 22 33 34 1and the second one is:id code name1 1 Mary2 2 Ben3 3 JohnI would like to map the data frame 1 so that it looks like:id code name1 2 Ben2 3 John3 3 John4 1 MaryI try to use this code:...
Problem is different type of values in column code so necessary converting to integers or strings by astype for same types in both:print (df1['code'].dtype)objectprint (df2['code'].dtype)int64print (type(df1.loc[0, 'code']))<class 'str'>print (type(df2.loc[0, 'code']))<class 'numpy.int64'>mapping = dict(df2...
How to select a specific range of cells in an Excel worksheet with Python library tools I would like to select a specific range of cells in a workbook worksheet. I am currently able to set a variable to a workbook worksheet with the line below. import pandas as pd sheet1 = pd.read_excel('workbookname1.xlsx', sheet_nam...
You can utilize OpenPyXl module.from openpyxl import Workbook, load_workbookwb = load_workbook("workbookname1.xlsx")ws = wb.activecell_range = ws['A1':'C2']You can also use iter_rows() or iter_columns() methods.For additional information, you can refer to OpenPyXL documentation.
Listing all class members with Python `inspect` module What is the "optimal" way to list all class methods of a given class using inspect? It works if I use the inspect.isfunction as predicate in getmembers like soclass MyClass(object): def __init(self, a=1): pass def somemethod(self, b=1): passinsp...
As described in the documentation, inspect.ismethod will show bound methods. This means you have to create an instance of the class if you want to inspect its methods. Since you are trying to inspect methods on the un-instantiated class you are getting an empty list.If you do:x = MyClass()inspect.getmembers(x, predicat...
Groupby in pandas multiplication I have a data frame called bf. The commas are mine, it was imported from a csv file.val,bena,123b,234c,123I have another larger data frame df bla,val, blablab, blablaa 1,a,123,333 2,b,333,222 3,c,12,33 1,a,123,333 .....I would like to create a new data frame which mult...
Probably you want to use a merge to bring in the column ben into your dataframe:df_merged = pd.merge(df, bf, on='val')Then you can calculate your product however you like, for example:df_prod = df_merged * df_merged.ben
Why doesn't this python function with a dictionary named parameter and a default value apply the default value each time it's called? Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument The following code illustrates the issue:def fn(param, named_param={}, another_named_param=1): nam...
The default value of named_param is evaluated once, when the function definition is executed. It is the same dictionary each time and its value is retained between calls to the function.Do not use mutable objects as default values in functions unless you do not mutate them. Instead, use None or another sentinel value, ...
Importing a class to another class in python I am trying to learn python i tried to import a class in another class but it is not workingApplication.py:class Application: def example(self): return "i am from Application class"Main.pyclass Main: def main(): application = Application() applicat...
You should instantiate your Main class first. if __name__ == '__main__': myMain = Main() myMain.main()But this will give you another error: TypeError: main() takes no arguments (1 given)There are two ways to fix this. Either make Main.main take one argument:class Main: def main(self): application = App...
Jinja2 extensions - get the value of variable passed to extension So I have a Jinja2 extension. Basically follows the parser logic, except that I need to get a value from the parsed args being passed in.For instance, if I have an extension called loadfile, and pass it a variable:{% loadfile "file.txt" %}when I grab the...
This works for medef parse(self, parser): lineno = parser.stream.next().lineno # args will contains filename args = [parser.parse_expression()] return nodes.Output([ nodes.MarkSafeIfAutoescape(self.call_method('handle', args)) ]).set_lineno(lineno)def handle(self, filename): # bla-bla-bla
Get relative links from html page I want to extract only relative urls from html page; somebody has suggest this :find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE)but it return :1/all absolute and relative urls from the page.2/the url may be quated by "" or '' randomly .
Use the tool for the job: an HTML parser, like BeautifulSoup.You can pass a function as an attribute value to find_all() and check whether href starts with http:from bs4 import BeautifulSoupdata = """<div><a href="http://google.com">test1</a><a href="test2">test2</a><a href="http://amaz...
replace information in Json string based on a condition I have a very large json file with several nested keys. From whaat I've read so far, if you do:x = json.loads(data)Python will interpret it as a dictionary (correct me if I'm wrong). The fourth level of nesting in the json file contains several elements named by a...
First of all, your JSON is invalid. I assume you want this:{"level1": {"level2": {"level3": { "ID1":{"children": [1,2,3,4,5]}, "ID2":{"children": []}, "ID3":{"children": [6,7,8,9,10]} } } }}Now, load your data as a dictionary:>>> with o...
How to get percentiles on groupby column in python? I have a dataframe as below:df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id': list(range(1, 7)) * 2, 'sales': [np.random.randint(100000, 999999) for _ in range(12)]})To get percentiles of sales,state wise,I have written...
How about this?quants = np.arange(.1,1,.1)pd.concat([df.groupby('state')['sales'].quantile(x) for x in quants],axis=1,keys=[str(x) for x in quants])
Isolating subquery from its parent I have a column_property on my model that is a count of the relationships on a secondary model.membership_total = column_property( select([func.count(MembershipModel.id)]).where( MembershipModel.account_id == id).correlate_except(None))This works fine until I try to ...
Pass MembershipModel to correlate_except() instead of None, as described here in the documentation. Your current method allows omitting everything from the subquery's FROM-clause, if it can be correlated to the enclosing query. When you join MembershipModel it becomes available in the enclosing query.Here's a simplifie...
Clustering latitude longitude points in Python with fixed number of clusters kmeans does not work properly for geospatial coordinates - even when changing the distance function to haversine as stated here.I had a look at DBSCAN which doesnt let me set a fixed number of clusters.Is there any algorithm (in python if poss...
Using just lat and longitude leads to problems when your geo data spans a large area. Especially since the distance between longitudes is less near the poles. To account for this it is good practice to first convert lon and lat to cartesian coordinates.If your geo data spans the united states for example you could de...
How to make exceptions during the iteration of a for loop in python Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an if ______ in ____: block into an existing for block.For example, how would I change this block to iterate through each instance of i, omitting odd nu...
This has nothing to do with nesting. You are comparing apples to pears, or in this case, trying to find an int in a list of str objects.So the if test never matches, because there is no 1 in the list ['1', '3', '5', '7', '9']; there is no 3 or 5 or 7 or 9 either, because an integer is a different type of object from a ...
Python 2.6.2: writing lines to file hard wrap at 192 characters I implemented a function to make a wrapper to write to files. This is the code:def writeStringToFile(thestring, thefile, mode='w'): """Write a string to filename `thefile' to the directory specified in `dir_out'.""" with open(os.path.join(dir_out, t...
My own stupidity -- I was writing strings that had the character sequence \n in them, and python was rightly interpreting them as newlines. I need to escape them in my string. I'd take this post down if it hadn't already been responded to.
list of indices in 3D array I have an array that looks like this: [[[ -1., 1., -1., 1., -1., 1., 1., 1., 1., -1., 1., 1., 1., 1.]], [[ 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0.]], [[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]]I have a list of 3 indices[2,3,...
Solution 1:The most pythonic way (my way to go).c = [a[i] for i,j in enumerate(b) if a[i][0][j] == 1]print(c)[[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]]]Solution 2:a = [[[0,1,0]], [[0,0,0]], [[1,1,1]], [[1,0,1]], [[0,0,1]], [[1,0,0]]]b = [0, 1, 2, 2, 1, 0]c=[]for i,j in enumerate(b): if a[i][0][j] == 1: c.append(a...
Close cmd while Tk object remains So I made a simple calculator in Python 3.7 and made a batch file to get it to run from the CMD. The thing is, after I run the batch file, I get a CMD window and then the Tk window, but the CMD window remains there and shuts my program down if I close it.Is there a way to hide the CMD ...
You can use the pythonw executable, or rename your script to something.pyw..pyw is a special extension for Python files on Windows which are associated with pythonw, the Python interpreter that does not pop up the console window at all.
PyQt app won't run properly unless I open the whole folder So I'm trying to share my PyQt project. When I download the zip file and extract it, it looks likeIf I run app.py from CMD, it will run the app, but without the icon file which is inside of that folder. Inside of the code I do need that file and point to it, so...
Eventually, I ended up changing how I'm using the paths.I added thisdirname = os.path.dirname(__file__)iconFile = os.path.join(dirname, 'icon/icon.png')So now I'm using iconFile as my path. Seems to fix the issue
Cannot connect VPS Server to MS SQL Server I'm trying to connect to MS SQL database using my VPS server IP, and login info. But I kept getting login failed errorpyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'root'. (18456) (SQLDriverConnect); ...
When you use IP address to connect to your server, you have to set SQL-Server port even it was default. like this:server = '66.42.92.32,1433'for more information look at this Microsoft link:https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-...
Spark Sql: TypeError("StructType can not accept object in type %s" % type(obj)) I am currently pulling data from SQL Server using PyODBC and trying to insert into a table in Hive in a Near Real Time (NRT) manner. I got a single row from source and converted into List[Strings] and creating schema programatically but whi...
here is the reason for error message:>>> rowstr['1127', '', '8196660', '', '', '0', '', '', 'None' ... ] #rowstr is a list of str>>> myrdd = sc.parallelize(rowstr)#myrdd is a rdd of str>>> schema = StructType(fields)#schema is StructType([StringType, StringType, ....])>>> schemaPeo...
Encoder for a string - Python I've been playing around with encoding random sets of strings using a dictionary. I've gotten my code to replace the letters I want, but in some cases it will replace a character more than once, when I truly only want it to replace the letter in the string once. This is what I have:def enc...
Python 3's str.translate function does what you want. Note that the translation dictionary must use Unicode ordinals for keys, so the function uses a dictionary comprehension to convert it to the right format:def encode(msg,code): code = {ord(k):v for k,v in code.items()} return msg.translate(code)print(encode("...
assigning values in a numpy array I have a numpy array of zeros. For concreteness, suppose it's 2x3x4:x = np.zeros((2,3,4))and suppose I have a 2x3 array of random integers from 0 to 3 (the index of the 3rd dimension of x).>>> y = sp.stats.distributions.randint.rvs(0, 4, size=(2,3))>>> y[[2 1 0] [3 2 ...
Use numpy.meshgrid() to make arrays of indexes that you can use to index into both your original array and the array of values for the third dimension.import numpy as npimport scipy as spimport scipy.stats.distributionsa = np.zeros((2,3,4))z = sp.stats.distributions.randint.rvs(0, 4, size=(2,3))xx, yy = np.meshgrid( np...
How can I create a new folder with Google Drive API in Python? From this example. Can I use MediafileUpload with creating folder? How can I get the parent_id from?From https://developers.google.com/drive/folderI just know that i should use mime = "application/vnd.google-apps.folder" but how do I implement this tutorial...
To create a folder on Drive, try: def createRemoteFolder(self, folderName, parentID = None): # Create a folder on Drive, returns the newely created folders ID body = { 'title': folderName, 'mimeType': "application/vnd.google-apps.folder" } if parentID: body['p...
Deadlock when creating index I try to create an index with a Cypher query using py2neo 1.6.2 and neo4j 2.0.1:graph_db = neo4j.GraphDatabaseService()query = "CREATE INDEX ON :Label(prop)"neo4j.CypherQuery(graph_db, query).run()The query works fine in the neo4j web interface but throws a deadlock error in py2neo:py2neo.n...
Judging from the deadlock graph in the details section, this looks like a bug in 2.0.1. Are you doing anything else to the database other than running this specific query, or is this just starting up a fresh database and running the code you provided?In any case, since it works in the Neo4j Browser, I'd suggest swappin...
Data comes out misaligned when printing list I have a code that reads an inventory txt file that is suppose to display a menu for the user when it is run. However, when it runs the quantity and pice columns are misaligned:Select an item ID to purchase or return: ID Item Quantity Price244 Large Cake Pan ...
Using your class Inventory's getters you can make a list and just join the output.def printMenu (all_data): print () print ('Select an item ID to purchase or return: ') print () print ('ID\tItem\t\t Quantity\t Price') for item in all_data: product_id = item.get_id() product_name = item.get...
How to save a dictionary having multiple lists of values for each key in a csv file I have a dictionary in the format:cu = {'m':[['a1','a2'],['a3','a4'],['a5','a6']], 'n':[['b1','b2'], ['b3','b4']]}#the code I used to save the dictionary in csv file was:#using numpy to make the csv fileimport numpy as np # using the s...
The error is caused by cu being a dictionary type, which is not an array type.However, simply converting to an array isn't going to work either, since what you want is fairly complicated. One way to perform this data transformation is to append the key to each subarray:([['m', a1, a2], ['m', a3, a4], ['m', a5, a6]], [[...
Binding command line arguments to the object methods calls in Python I am working on a command line utility with a few possible arguments. The argument parsing is done with argparse module. In the end, with some additional customization, I get a dictionary with one and only one element:{'add_account': ['example.com', '...
You can use getattr to fetch a method object (argparse.py uses this approach several times).You didn't give us a concrete example, but I'm guessing you have a class like this:In [387]: class MyClass(object): ...: def add_account(self,*args): ...: print(args) ...: In [388]: obj=MyClass()I...
The most efficient way to iterate over a list of elements. Python 2.7 I am trying to iterate over a list of elements, however the list can be massive and takes too long to execute. I am using newspaper api. The for loop I constructed is:for article in list_articles:Each article in the list_articles are an object in the...
The best way is to use built in functions, when possible, such as functions to split strings, join strings, group things, etc...The there is the list comprehension or map when possible. If you need to construct one list from another by manipulating each element, then this is it.The thirst best way is the for item in i...
SyntaxError: invalid syntax in URLpattern hi am getting a syntax errorurl:url(r'^reset-password/$', PasswordResetView.as_view(template_name='accounts/reset_password.html', 'post_reset_redirect': 'accounts:password_reset_done'), name='reset_password'),What is the problem?thanks
The problem is that you mix dictionary syntax with parameter syntax:url( r'^reset-password/$', PasswordResetView.as_view( template_name='accounts/reset_password.html', 'post_reset_redirect': 'accounts:password_reset_done' ), name='reset_password')This syntax with a colon, is used for dictionar...
Converting hex to binary in array I'm working on Visual Studio about python Project and The user input like that 010203 and I use this code for saparating the input:dynamic_array = [ ] hexdec = input("Enter the hex number to binary ");strArray = [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0]dynamic_...
It's a lot easier if you thnk of hex as a integer (number).There's a lot of tips on how to convert integers to different outcomes, but one useful string representation tool is .format() which can format a integer (and others) to various outputs.This is a combination of:Convert hex string to int in PythonPython int to b...
Why is my program shifting s and c by the wrong amount if I enter 5 into my program but not with any other letters or number? This program is meant to ask you for a sentence and a number then it shifts the letters down the alphabet all by the inputted number and then lets you undo it by shift it by minus what you enter...
The problem is that you define a global x variable, and also a local one. The local one shadows the global one and so the result of eval("x") is not anymore what you expected to have. Solution: use a different variable for the for loop.There is much that can be improved in your code. You can take advantage of the modul...
Receiving service messages in a group chat using Telegram Bot I am trying to create a bot in my group to help me track the group users who have invited other users into the group.I have disabled the privacy mode so the bot can receive all messages in a group chat. However, it seems to be that update.message only gets m...
I suppose you are using python-telegram-bot library.You can add a handler with a specific filter to listen to service messages:from telegram.ext import MessageHandler, Filtersdef callback_func(bot, update): # here you receive a list of new members (User Objects) in a single service message new_members = update.me...
Pandas division with 2 dfs I want to divide 2 dfs by matching their names. For example,df1 = pd.DataFrame({'Name':['xy-yz','xa-ab','yz-ijk','zb-ijk'],1:[1,2,3,4],2:[1,2,1,2],3:[2,2,2,2]} )df2 = pd.DataFrame({'Name2':['x','y','z','a'],1:[0,1,2,3],2:[1,2,3,4],3:[5,5,5,6]})df1:Name1 1 2 3xy-yz 1 1 2xa-ab ...
I do not know why you need it , but this give back what you need df2=df2.set_index('Name2')dfNew=df2.reindex(df1.Name1.str.split('-',expand=True)[0])df1=df1.set_index('Name1')pd.concat([df1.reset_index(),dfNew.reset_index().rename(columns={0:'Name1'}),pd.DataFrame(df1.values/dfNew.values,columns=df1.columns).assign(Nam...
Django logout() returns none Morning everyoneIm using django logout() to end my sessions just like django docs says :views.pyclass Logout(View): def logout_view(request): logout(request) return HttpResponseRedirect(reverse('cost_control_app:login'))and im calling it from this url :urls.pyurl(r'^logout...
I'm curious, why do you have the method named logout_view()? By default, nothing is going to call that method. You need to change the name to match the HTTP verb which will be used to call the page. For instance, if it's going to be a GET request, you would change it to:def get(self, request):If you want it to be a POS...
Def and Return Function in python I'm having some problems with the def and return function in Python.On the top of my program I've defined:from subprogram import subprogramthen I've defined the def in which I've included the values I wanted to be returned:def subprogram(ssh, x_off, y_off, data_array, i, j): if j==1...
The function doesn't return the variable, only the value on it.If you want to get the returned value on var_colonna_1, you should asign it, as Sayse said, you should do:var_colonna_1 = subprogram(ssh, x_off, y_off, data_array, i, j)
Faster alternatives to Popen for CAN bus access? I'm currently using Popen to send instructions to a utility (canutils... the cansend function in particular) via the command line.The entire function looks like this.def _CANSend(self, register, value, readWrite = 'write'): """send a CAN frame""" queue=self.CANbus....
I suspect that most of that time is due to the overhead of forking every time you run cansend. To get rid of it, you'll want an approach that doesn't have to create a new process for each send.According to this blog post, SocketCAN is supported by python 3.3. It should let your program create and use CAN sockets dire...
how to install wordcloud package in python? pip install wordcloud File "<ipython-input-130-12ee30540bab>", line 1 pip install wordcloud ^SyntaxError: invalid syntaxThis is the problem I am facing while using pip install wordcloud.
pip is a tool used for installing python packages. You should not use this command inside the python interactive shell. Instead, exit out of it and write pip install wordcloud on the main shell.
Python -- sizing frames with weights In the minimum example code below, you can change the last range(), currently at 3, to 6 and notice that the frames with buttons all get smaller than if you run it with 3. I have configured 6 columns of "lower_frame" to all be weight 1. The expected result is that there are 6 empt...
If you want all of the rows and all of the columns to have the same width/height, you can set the uniform attribute of each row and column. All columns with the same uniform value will be the same width, and all rows with the same uniform value will be the same height.Note: the actual value to the uniform attribute is ...
Can't get stored python integer back in java in habase google cloud I'm using hbase over google cloud bigtable to store my bigdata. I have 2 programs. first, store data using python into hbase and the second, read those info back from java by connecting to the same endpoint.so from python interactive shell I can read b...
I found the problemthe column stored as long value so I had to first read it as long in java and then convert it to int
Using IronPython to learn the .NET framework, is this bad? Because I'm a Python fan, I'd like to learn the .NET framework using IronPython. Would I be missing out on something? Is this in some way not recommended?EDIT:I'm pretty knowledgeable of Java ( so learning/using a new language is not a problem for me ). If need...
No, sounds like a good way to learn to me. You get to stick with a language and syntax that you are familiar with, and learn about the huge range of classes available in the framework, and how the CLR supports your code.Once you've got to grips with some of the framework and the CLR services you could always pick up C#...
Django: handle migrations for an imported database? I'm working in Django 1.8 and trying to set up an existing project. I've inherited a database dump, plus a codebase. I've imported the database dump successfully. The problem is that if I try to run migrate against the imported database I then get errors about columns...
I think your migrations problem solved by the previous Answer. Therefore I'm adding a link below...If you just started django 1.7 and above thenHere I'ld like to add a link Django Migration How works That will useful where I think.
convert python integer to its signed binary representation Given a positive integer such as 171 and a "register" size, e.g. 8.I want the integer which is represented by the binary representation of 171, i.e. '0b10101011' interpreted as twos complement.In the present case, the 171 should become -85.It is negative becaus...
You don't need binary conversion to achieve that:>>> size = 8>>> value = 171>>> unsigned = value % 2**size >>> signed = unsigned - 2**size if unsigned >= 2**(size-1) else unsigned>>> signed-85
Unable to uninstall anaconda from Ubuntu 16.04 I am trying to uninstall Ananconda from my Ubuntu 16.04 LTS machine.I ran the following commandsconda install anaconda-cleananaconda-cleanrm -rf ~/anacondaEverything is getting exceuted without any error/warning. If fact, when I run anaconda-clean it is saying so and so pa...
conda install anaconda-cleananaconda-clean --yesrm -rf ~/anaconda3 Replace anaconda3 with your version of anacondaThis will uninstall anaconda
if loop repeating first if statement I'm trying to create a continuous question loop to process all my calculations for my nmea sentences in my project. For some reason only the first if statement is executed. What am I doing wrong? I'm still fairly new to python if command_type == "$GPGGA" or "GPGGA" or "GGA": ...
if command_type == "$GPGGA" or "GPGGA" or "GGA":As you can see, here you are not trying to check if command_type is valued "$GPGGA" or "GPGGA" or "GGA". But if command_type == "$GPGGA" is true or "GPGGA" is true or "GGA" is true.And a non-empty string in python is always true : your first condition will be evaluated tr...
What is the easiest way to build Python26.zip for embedded distribution? I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of the ...
I would probably use setuptools to create an egg (basically a java jar for python). The setup.py would probably look something like this:from setuptools import setup, find_packagessetup( name='python26_stdlib', package_dir = {'' : '/path/to/python/lib/directory'}, packages = find_packages(), #any other met...
Modeling a complex relationship in Django I'm working on a Web service in Django, and I need to model a very specific, complex relationship which I just can't be able to solve.Imagine three general models, let's call them Site, Category and Item. Each Site contains one or several Categories, but it can relate to them i...
Why not just have both types of category in one model, so you just have 3 models?SiteCategory Sites = models.ManyToManyField(Site) IsCommon = models.BooleanField()Item Category = models.ForeignKey(Category)You say "Internally, those two type of Categories are completely identical". So in sounds like this is possib...
How to use subversion Ctypes Python Bindings? Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and...
You need the Subversion source distribution, Python (>= 2.5), and ctypesgen.Instructions for building the ctypes bindings are here.You will end up with a package called csvn, examples of it's use are here.
Installing Python's Cryptography on Windows I've created a script on windows to connect to Remote SSH server. I have successfully installed cryptography, pynacl and finally paramiko(Took me an entire day to figure out how to successfully install them on windows).Now that I run the script, it pops an error saying that t...
After a lot of googling, I finally stumbled upon this. As mentioned in the conversation I uninstalled my previous pynacl installation, downloaded the zipped source from https://github.com/lmctv/pynacl/archive/v1.2.a0.reorder.zip, downloaded libsodium from https://github.com/jedisct1/libsodium/releases/download/1.0.15/l...
OpenCV Python Assertion Failed I am trying to run opencv-python==3.3.0.10 on a macOS 10.12.6 to read from a file and show the video in a window. I have exactly copied the code from here http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html, section 'Playing' v...
It's not clear from your question, but it looks like you're specifically running into a situation where the video completes playing without being interrupted. I think the issue is that the VideoCapture object is already closed by the time you get to cap.release(). I'd recommend putting the call to release inside of the...
reference to invalid character number: (Python ElementTree parse) I have xml file which has following content: <word>vegetation</word> <word>cover</word> <word>(31%</word> <word>split_identifier ;</word> <word>Still</word> <word&g...
If you want to get rid of those special characters, you can by scrubbing the input XML as a string:respXML = response.content.decode("utf-16")scrubbedXML = re.sub('&.+[0-9]+;', '', respXML)respRoot = ET.fromstring(scrubbedXML)If you prefer to keep the special characters you may parse them beforehand. In your case i...
Can I save results anyway even when Keyboardinterrupt? I have a very long code which is taking forever to run. I was wondering if there is a way to save the results even if I use the keyboard to interrupt the code from running? All the examples I found were using except with Keyboardinterrupt, so I don't know if this i...
You could use a try-except with KeyboardInterrupt:def your_function(): removed = [...] try: # Code that takes long time for a, b in itertools.combinations(removed, 2): ... return removed except KeyboardInterrupt: return removedA small example:import timedef foo(): resu...
How can i replace a value in a specific row and column in a csv file I need to replace a value in correspondence of an ID in a .csv file:ChatId,Color805525230,blackSo if the ID in input is equal to the one in the file my program will replace the Color "black" with the new one. I tried this:for idx, row in enu...
Assuming you loaded the csv on a dataframe, you could you use some of its functions.For example: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.htmlAlternatively, you could use the loc function:df.loc[df['ChatId'=='SomeId'], 'Color'] = 'ValueToReplace'If you need to apply it to a different column...
What is the simplest language which support template&context mechanism? I need to find the easiest way to automatically build ebooks from downloaded articles.I want to automatically generate TOC, which will be based on HTML template.I know that python django has template & context mechanism, however django is a lit...
IMHO, if you are familiar with Django:if you want to build a command line application or a abstract library, look at Jinja2 template engine.if you are looking for a web framework simpler than Django, look at Flask (Flask uses Jinja2 as the default template engine).
python managing tasks in threads when using priority queue I'm trying to write a program which starts new tasks in new threads.Data is passed from task threads to a single worker/processing thread via a priority queue (so more important jobs are processes first). The worker/processing thread gets higher priority data f...
In your request queue entry include a response queue. When finished place a response on the response queue.The requesting thread waits on the response queue.A callback method could alternately be used.
Wrong datetimes picked up by pandas Data ScrapedSo I've scraped data from a website with a timestamp of when it was scraped. As you can see I have no date between 2017-09-14 13:56:28 and 2017-09-16 14:43:05, however when I scrape it using the following code:path ='law_scraped'files = glob.glob(path + "/*.csv")frame = p...
Assuming your timestamps have the same format as the filenames in your screenshot, this should work (after the replacement of "|" by " "):df['dtScraped'] = pd.to_datetime(df['dtScraped'], format="%Y-%m-%d %H-%M-%S")
Plot wind speed and direction from u, v components I'm trying to plot the wind speed and direction, but there is an error code that keeps telling me that "sequence too large; cannot be greater than 32." Here is the code that I am using:N = 500ws = np.array(u)wd = np.array(v)df = pd.DataFrame({'direction': [ws], 'speed'...
To plot wind U, V use barbs and quiver. Look at the code below:import matplotlib.pylab as pltimport numpy as npx = np.linspace(-5, 5, 5)X, Y = np.meshgrid(x, x)d = np.arctan(Y ** 2. - .25 * Y - X)U, V = 5 * np.cos(d), np.sin(d)# barbs plotax1 = plt.subplot(1, 2, 1)ax1.barbs(X, Y, U, V)#quiver plotax2 = plt.subplot(1, 2...
Python 2.7.3 urllib2 Error When I try to run my python script this error happens. How can I solve this problem ?['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'urllib2']Traceback (most recent call last): File "m.py", line 3, in <module> import requests File "/usr/local/lib/python2.7/dist-...
you need to upgrade requests pip install --upgrade requests
"The request's session was deleted before the request completed. The user may have logged out in a concurrent request" "The request's session was deleted before the request completed. The user may have logged out in a concurrent request" I am facing this error when trying to use 2 request.session().In my code...
Since my dataset has 8000 rows, It was not a good idea to store in session variables. I have written some rest calls and that solved my problem.
Shelves an multiple items I've been trying to make a quote input that puts multiple quotes inside a file (coupled with the authors name). I have tried with pickle, but I could not get more than 2 pickled items inside a file and finally I decided to use shelf.However, I am having some trouble with shelves as well.I dont...
You can do this with pickle. As this answer describes, you can append a pickled object to a binary file using open with append in binary mode. To read the multiple pickled objects out of the file, just call pickle.load on the file handle until you get an EOF error. so your unpickle code might look likeimport pickleobj...
"chalice deploy" call ends up with "Unknown parameter in input: "Layers"" I create the most basic chalice app from chalice import Chaliceapp = Chalice(app_name='testApp')@app.route('/')def index(): return {'hello': 'world'}with empty requirements.txt and config that looks like this:{ "version": "2.0", "app_name": ...
After troubleshooting found some issues with my local configurations. What helped was running the chalice in virtualenv (https://virtualenv.pypa.io/en/latest/)
Import and insert word in sequence in Python I want to import and insert word in sequence and NOT RANDOMLY, each registration attempt uses a single username and stop until the registration is completed. Then logout and begin a new registration with the next username in the list if the REGISTRATION is FAILED, and skip i...
I am going to assume that you are happy with what the code does, with exception that the names it picks are random. This narrows everything down to one line, and namely the one that picks names randomly:idx = random.randint(0, len(names) - 1)Simple enough, you want "the next word in sequence and NOT RANDOMLY"...
Load a text file paragraph into a string without libraries sorry if this question may look a bit dumb for some of you but i'm totally a beginner at programming in Python so i'm quite bad and got a still got a lot to learn.So basically I have this long text file separated by paragraphs, sometimes the newline can be doub...
This should do the trick. It is very short and elegant:with open('dummy text.txt') as file: data = file.read().replace('\n', '')print(data)#prints out the fileThe output is:"random questions about files with a dummy text and strings hey look a new paragraph here"
Python/Kivy Assertion Error I obtained an Assertion error while attempting to learn BoxLayout in kivy. I cannot figure out what has went wrong. from kivy.app import App from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout class BoxLayoutApp(App): def build(self): retur...
Try subclassing boxlayout instead:from kivy.app import Appfrom kivy.uix.button import Buttonfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.lang import Builderclass MyBoxLayout(BoxLayout): passBuilder.load_string('''<MyBoxLayout>: BoxLayout: Button: text: "test" Button: ...
How to get the dimensions of a tensor (in TensorFlow) at graph construction time? I am trying an Op that is not behaving as expected.graph = tf.Graph()with graph.as_default(): train_dataset = tf.placeholder(tf.int32, shape=[128, 2]) embeddings = tf.Variable( tf.random_uniform([50000, 64], -1.0, 1.0)) embed = tf.n...
I see most people confused about tf.shape(tensor) and tensor.get_shape()Let's make it clear:tf.shapetf.shape is used for dynamic shape. If your tensor's shape is changable, use it. An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:ne...
/usr/bin/python: No module named pip I am having a bit of trouble getting everything to work on my Mac running El Capitan. I am running 3.5.1. I am under the impression that Pip is included with an install of the above, however when I try to use it to install sympy using the syntax in terminal: python -m pip install So...
I believe that you can run it by calling pip in the terminal. If you have it already installed.pip install sympy
Get params validation on viewsets.ModelViewSet I am new to django and building a REST API using django-rest-framework.I have written some code to check whether the user has supplied some parameters or not.But that is very ugly with lot of if conditions, so i want to refactor it.Below is the code that i have written ple...
You can make serializers, they have a very easy way to validate your data. As in your case all the fields seem to be required it becomes even easier.Create a file on you api app like:serializers.py#Import Serializers libfrom rest_framework import serializers#Import your models here (You can put more than one serializer...
Python - Error in two-layer neural network I am trying to implement a 2-layer neural network from scratch. But there is something wrong. After some iterations, my loss becomes nan.'''We are implementing a two layer neural network.'''import numpy as npx,y = np.random.rand(64,1000),np.random.randn(64,10)w1,w2 = np.random...
Its because your loss is becoming too hightry this loss = np.square(ypred - y).mean()and if still doesn't work try reducing the learning rate to something like 1e-8.and observe if the loss is going up or down, if loss is reducing thats good, if the loss is increasing thats a bad sign, you might want to consider using a...
How to implement n times nested loops in python? I want to do nested loops with n times, this n is an variable and can be provided by function or input methods. In order to do this, I have to write lots of if..elif blocks depend on size of n, does anybody have good strategies to handle this task? The codes (for combina...
You can use itertools.product with repeat parameterimport itertoolsdef charCombination(n): return ["".join(item) for item in itertools.product("ATCG", repeat=n)]print charCombination(1)print charCombination(2)print charCombination(3)Output['A', 'T', 'C', 'G']['AA', 'AT', 'AC', 'AG', 'TA', 'TT', 'TC', 'TG', 'CA', 'CT...
Timer for variable time delay I would like a timer (Using Python 3.8 currently) that first checks the system time or Naval Observatory clock, so it can be started at any time and synch with the 00 seconds.I'm only interested in the number of seconds on the system clock or Naval Observatory. At the top of every minute, ...
This will call a function when the seconds are 0:def time_loop(job): while True: if int(time.time()) % 60 == 0: job() time.sleep( 1 )
Finding nearest timeindex for many categories I am trying to obtain the data points nearest to the query timestamp for multiple independent categories like this (example in more detail in the gist):dt = pd.to_datetime(dt)df_output = list()for category in df.category.unique(): df_temp = df[df.category == category] ...
Pandas was made for time-series data so this is it's bread and butter. Try this for performance:dt = '2017-12-23 01:49:13'df["timedelta"] = abs(df.index - pd.Timestamp(dt))df.loc[df.groupby(by="category")["timedelta"].idxmin()].drop("timedelta", axis=1)This is creating a new column called timedelta, named after pandas...
Cassandra Pagination CPU Utilization Issue I had developed a python script for pulling the data but it is using only single cpu core and when I do top cassandra is using more than 200% cpu. Going into Idle state since in between GC coming into picture Unable understand how can I convert the code to utilize multiple cor...
You wont get blazing performance out of python driver, but you can look at cqlsh's copy functions (https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py#L229) if you really want to see a fast implementation that can use multiple cores.On C* side make sure you have enough nodes with adequate hardware...
finding just full words in a python string Basically it all comes down to finding just the fullword, not matching also a substring thereof.I have phrases like: texto = "hello today is the first day of working week" and what I wanted to do is to split that phrase into words to see if any matched fullwords that I have ob...
I dont't see why split() should not work. The issue is the .__str__() (which I don't see any need for). It creates one single string in which the keywords are searched - and then it will find substrings as well. The following is working for me:texto = "hello today is the first day of working week"keywords = ["is", "day...
How to solve a Dataset problem in python? i have a dataset with different programming language in a column titled and i want to get the 10 most used programming language in my dataset pythonDataset: https://drive.google.com/file/d/1nJLDFSdIbkNxcqY7NBtJZfcgLW1wpsUZ/view?usp=sharing
On StackOverflow, you should not link to outside sources, but include relevant data in your question. You should also pare down the data - if it is long, make it as short as possible and still illustrate your question.Finally, on StackOverflow, we don't ask bare questions like "how to do x". You must first ...
Python/Django - Having trouble giving an object a foreignkey that was just created I am expanding on the basic django Poll site tutorial, and I have made a view that allows users to add their own polls. Adding a poll works, adding choices does not. Apparently this is because the poll does not "exist" yet, and the p.id ...
Nevermind, I figured it out. The choice doent need an id, rather, it needs the object. FIxed by changing:c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)toc1 = Choice(poll=p, choice_text=request.POST['c1'], votes=0)
No such file or directory: ...build/sip/setup.py I'm trying to install PyQt on Ubuntu. The list of obstacles I'm dealing with is far too long to include here. The obstacle I'm currently trying to get past is this:(myvenv)% cd ~/.virtualenvs/myvenv/build/pyqt(myvenv)% python ./configure.pyTraceback (most recent call l...
allready answer herestart all from the beginning and make sure that all dependencies are satisfied.
parallel installion of Python 2.7 and 3.3 via Homebrew - pip3 fails I would like to make the jump and get acquainted with Python 3.I followed the instructions found here with the installation working flawlessly.I'm also able to use the provided virtualenv to create enviroments for Python 2 and Python 3 (Followed the in...
I was having the same problem as you were and I had export PYTHONPATH="/usr/local/lib/python2.7/site-packages:$PYTHONPATH"in my ~/.bash_profile. Removing that line solved the problem for me. If you have that or something like it in your ~/.bashrc or ~/.bash_profile, try removing it.
graph theory - connect point in 3D space with other three nearest points (distance based) I want to connect nodes (Atoms) with the three nearest nodes(atoms).I am doingad1 = np.zeros((31,31))for i in range(31): dist_i = dist_mat[i] cut_off = sorted(dist_i)[3] ad1[i, np.where((dist_i<=cut_off) & (dist_i!...
A KDTree would be more appropriate for what you're trying to do. Once you've built the tree, you can search for the 3 nearest points to all points in the tree:from sklearn.neighbors import KDTreetree = KDTree(X, leaf_size=2)dist, ind = tree.query(X, k=3) To check the result, we can verify that the three smallest values...
How to change the field of username to user_name in to django custom user model? I have created custom user model. now I want to use user_name as username field instead of username. like shown in below code snippet.class CustomUser(AbstractBaseUser): username_validator = UnicodeUsernameValidator() user_name =...
in admin.py where you are registering your User model. you are registering it with ModelAdmin and in that ModelAdmion you have named field incorrectly. change it to user_name their too.
Video Intelligence API - Label Segment time I am following this LABEL DETECTION TUTORIAL.The code below does the following(after getting the response back) Our response will contain result within an AnnotateVideoResponse, which consists of a list of annotationResults, one for each video sent in the request. Because ...
I see that the part of the tutorial that you are following uses the simplest examples available, while the list of samples provides a more complete example where more features of the Video Intelligence API are used.In order to achieve the objective you want (have a more detailed information about the time instants when...
Is there a way to extend a PyTables EArray in the second dimension? I have a 2D array that can grow to larger sizes than I'm able to fit on memory, so I'm trying to store it in a h5 file using Pytables. The number of rows is known beforehand but the length of each row is not known and is variable between rows. After so...
Here is an example showing how to create a VLArray (Variable Length). It is similar to the EArray example above, and follows the example from the Pytables doc (link in comment above). However, although a VLArray supports variable length rows, it does not have a mechanism to add items to an existing row (AFAIK).import t...
Legend with vertical line in matplotlib I need to show a vertical line in a matplotlib legend for a specific reason. I am trying to make matplotlib understand that I want a vertical line with the lines.Line2D(x,y) but this is clearly not working.import matplotlib.pyplot as pltfrom matplotlib import linesfig, ax = plt.s...
You can use the vertical line marker when making your line2D object. A list of valid markers can be found here.import matplotlib.pyplot as pltfrom matplotlib import linesfig, ax = plt.subplots()ax.plot([0,0],[0,3])vertical_line = lines.Line2D([], [], color='#1f77b4', marker='|', linestyle='None', ...
count the occurrences of alphabet of string in python String containing both upper and lower case alphabets. We need to count the number of occurrences of each alphabet(case insensitive) and display the same.Below is the program,but does not led to desired outputoutput should be-2A 3B 2C 1Gmy output is -A 2B 3A 2...
Use Counter:from collections import CounterString = "ABaBCbGc"counts = Counter(String.lower())print(counts)OutputCounter({'b': 3, 'c': 2, 'a': 2, 'g': 1})If you prefer upper case, just change str.lower to str.upper. Or use a dictionary to keep track of the counts:string = "ABaBCbGc"counts = {}for c in string.upper(): ...
How do I insert something into multiple strings? I have 12 different strings that I want in a tuple format because I will use the strings later in a graph.How do I add the same string into the array of strings?I have these months:January, February etc. and I want to insert into each string "January LSDS", &qu...
inserted = [month.format(insert) for month in month_names]
Pandas: Reshaping Long Data to Wide with duplicated columns I need to pivot long pandas dataframe to wide. The issue is that for some id there are multiple values for the same parameter. Some parameters present only in a few ids.df = pd.DataFrame({'indx':[11,11,11,11,12,12,12,13,13,13,13],'param':['a','b','b','c','a','...
Option 1:df.astype(str).groupby(['indx', 'param'])['value'].agg(','.join).unstack()Output:param a b c dindx 11 100 54,65 65 NaN12 789 24 NaN 9813 24 27 75,35 NaNOption 2df_out = df.set_index(['indx', 'param', df.groupby(['indx','param']).cumcount...
Using Pygame and Pymunk Circle will not spawn in space So, I'm trying to make a function create_particle then make the function draw a partial with draw_circle. However, whenever I open the window, I get my grey window but no particle is shown. I'm extremely new to both pygame and pymunk so any help is appreciated.impo...
A few changes are needed:draw_circle() does not require a parameterWhen you draw the circle, you need to specify the coordinates and radiusIn the main loop, call draw_circle() and space.step(0.02)Here is the updated code:def draw_circle(): for circle in circles: pos_x = int(circle.body.position.x) pos_...
Add a new column to a dataframe based on an existing column value using pandas I am working with a dataframe created by importing a .csv file I created. I want to (1) create a new column in the dataframe and (2) use values from an existing column to assign a value to the new column. This is an example of what I'm worki...
Just use str[]. I could not see the image. If your id has more than 2 chars, you need this to get the last chardf['side'] = df.id.str[-1]Out[582]: date id height gender side0 dd/mm/yyyy 1A 6 M A1 dd/mm/yyyy 2A 4 F A2 dd/mm/yyyy 1B 1 M B3 dd/mm/yyyy 2B 7 ...
How can I load my homemade 32bit cpp DLL into my canopy 3.5 32bit python? I am trying to load my DLL (32bit) file containing CPP functions into python. It works on python 3.7 (32bit) but it gives an error when using canopy 3.5 (32bit). the code I use to load my dll:import osimport ctypesos.chdir(r"G:\DLLdirectory")mydl...
It turned out that the DLL was dependent on another DLL and this DLL was found in python automatically. However, in Canopy the second DLL needed to be loaded separately.
Django - pass a list of results when querying using filter In my FollowingPageView function, I'm trying to filter posts based on the logged in user's list of user's he/she is following.You'll see the Profile model has a "following" field that captures the names of users the Profile owner is following. What I'...
One approach is to use an __in query. Here, because you're not using user_list for anything else, you'll probably get the best results from using an inner query:posts = Post.objects.filter(created_by__in=profile.following.all())But note the performance advice in the linked docs - test it on your actual setup and see.Po...
Problem with training cifar10 data in Tensorflow-2 I got the following error in training cifar10 data in tensorflow-2. I used this tutorial. TypeError: Expected float32 passed to parameter 'y' of op 'Equal', got 'collections' of type 'str' instead. Error: Expected float32, got 'collections' of type 'str' instead.M...
set from_logits=True in the loss function.loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)It solves the error!
Problem in creating delete button in django I am trying to build delete button and currently stuck. I am new to django and need help. Thank YouThis is my models.py:- from django.db import models from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # ...
You need to make a POST request to delete the object. Furthermore the name of the object is simpleList, not part, so the form should be rewritten to:<form method="post" action="{% url 'delete_view' pk=simpleList.pk %}"> {% csrf_token %} <input class="btn btn-default btn-danger&qu...
Counter inside for loop adding duplicates in output, remove duplicate entries in output in Python I want to remove duplicate entries from my function output. I have a function which searches for relationships inside each paragraph of a text file. A sample of the metadata.csv file which searches for relationship in par...
If you prefer, you can achieve this with the help of set. But please note that order is not preserved though you can achieve uniqueness.lst = ['foo', 'bar', 'foo', 'bar']s = set(lst)print(s) # this will print foo and bar