qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
2,686,520
|
For what I've read I need Python-Dev, how do I install it on OSX?
I think the problem I have, is, my Xcode was not properly installed, and I don't have the paths where I should.
This previous question:
[Where is gcc on OSX? I have installed Xcode already](https://stackoverflow.com/questions/2685887/where-is-gcc-on-osx-i-have-installed-xcode-already)
Was about I couldn't find gcc, now I can't find Python.h
Should I just link my /Developer directory to somewhere else in /usr/ ???
This is my output:
```
$ sudo easy_install mercurial
Password:
Searching for mercurial
Reading http://pypi.python.org/simple/mercurial/
Reading http://www.selenic.com/mercurial
Best match: mercurial 1.5.1
Downloading http://mercurial.selenic.com/release/mercurial-1.5.1.tar.gz
Processing mercurial-1.5.1.tar.gz
Running mercurial-1.5.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-_7RaTq/mercurial-1.5.1/egg-dist-tmp-l7JP3u
mercurial/base85.c:12:20: error: Python.h: No such file or directory
...
```
Thanks in advance.
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2686520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
I was struggling with this problem all day today.
I eventually discovered a [site](https://web.archive.org/web/20141221052542/http://www.jaharmi.com/2011/11/12/reinstall_xcode_if_easy_install_fails_with_missing_files_like_python_h) that claimed that all one needed to do was to reinstall Xcode, or install the latest version (4.3.2, as of this writing).
So I tried that. It did not help; not on its own. But then I went a step further: I fired up Xcode.app, and once I had done that, I opened the Xcode..Preferences menu item, and then go to the Downloads tab, and say that you want to install the "Command Line Tools"
Once I did that, and then re-ran easy\_install (in my case I was trying to "easy\_install dulwich" to satisfy a hg-git dependency), it was able to properly find Python.h for me.
|
Might depend on what version of Mac OSX you have, I have it in these spots:
```
/Developer/SDKs/MacOSX10.5.sdk/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/Python.h
/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/Python.h
```
Also I believe the version of python that comes with Xcode is a custom build that plays well with xcode but you have to jump through some hoops if you use another dev environment.
|
2,686,520
|
For what I've read I need Python-Dev, how do I install it on OSX?
I think the problem I have, is, my Xcode was not properly installed, and I don't have the paths where I should.
This previous question:
[Where is gcc on OSX? I have installed Xcode already](https://stackoverflow.com/questions/2685887/where-is-gcc-on-osx-i-have-installed-xcode-already)
Was about I couldn't find gcc, now I can't find Python.h
Should I just link my /Developer directory to somewhere else in /usr/ ???
This is my output:
```
$ sudo easy_install mercurial
Password:
Searching for mercurial
Reading http://pypi.python.org/simple/mercurial/
Reading http://www.selenic.com/mercurial
Best match: mercurial 1.5.1
Downloading http://mercurial.selenic.com/release/mercurial-1.5.1.tar.gz
Processing mercurial-1.5.1.tar.gz
Running mercurial-1.5.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-_7RaTq/mercurial-1.5.1/egg-dist-tmp-l7JP3u
mercurial/base85.c:12:20: error: Python.h: No such file or directory
...
```
Thanks in advance.
|
2010/04/21
|
[
"https://Stackoverflow.com/questions/2686520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
I was struggling with this problem all day today.
I eventually discovered a [site](https://web.archive.org/web/20141221052542/http://www.jaharmi.com/2011/11/12/reinstall_xcode_if_easy_install_fails_with_missing_files_like_python_h) that claimed that all one needed to do was to reinstall Xcode, or install the latest version (4.3.2, as of this writing).
So I tried that. It did not help; not on its own. But then I went a step further: I fired up Xcode.app, and once I had done that, I opened the Xcode..Preferences menu item, and then go to the Downloads tab, and say that you want to install the "Command Line Tools"
Once I did that, and then re-ran easy\_install (in my case I was trying to "easy\_install dulwich" to satisfy a hg-git dependency), it was able to properly find Python.h for me.
|
Are you sure you want to build Mercurial from source? There are [binary packages available](https://www.mercurial-scm.org/downloads), including the nice [MacHg](http://jasonfharris.com/machg/) which comes with a bundled Mercurial.
|
67,211,732
|
I'm trying to update my Heroku DB from a Python script I have on my computer. I set up my app on Heroku with NodeJS (because I just like Javascript for that sort of thing), and I'm not sure I can add in a Python script to manage everything. I was able to fill out the DB once, with the script, and it had no hangups. When I try to update it, I get the following statement in my console:
```
Traceback (most recent call last):
File "/home/alan/dev/python/smog_usage_stats/scripts/DBManager.py", line 17, in <module>
CONN = pg2.connect(
File "/home/alan/dev/python/smog_usage_stats/venv/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL: role "alan" does not exist
```
and this is my script:
```py
#DBManager.py
import os
import zipfile
import psycopg2 as pg2
from os.path import join, dirname
from dotenv import load_dotenv
# -------------------------------
# Connection variables
# -------------------------------
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
# -------------------------------
# Connection to database
# -------------------------------
# Server connection
CONN = pg2.connect(
database = os.environ.get('PG_DATABASE'),
user = os.environ.get('PG_USER'),
password = os.environ.get('PG_PASSWORD'),
host = os.environ.get('PG_HOST'),
port = os.environ.get('PG_PORT')
)
# Local connection
# CONN = pg2.connect(
# database = os.environ.get('LOCAL_DATABASE'),
# user = os.environ.get('LOCAL_USER'),
# password = os.environ.get('LOCAL_PASSWORD'),
# host = os.environ.get('LOCAL_HOST'),
# port = os.environ.get('LOCAL_PORT')
# )
print("Connected to POSTGRES!")
global CUR
CUR = CONN.cursor()
# -------------------------------
# Database manager class
# -------------------------------
class DB_Manager:
def __init__(self):
self.table_name = "smogon_usage_stats"
try:
self.__FILE = os.path.join(
os.getcwd(),
"data/statsmaster.csv"
)
except:
print('you haven\'t downloaded any stats')
# -------------------------------
# Create the tables for the database
# -------------------------------
def construct_tables(self):
master_file = open(self.__FILE)
columns = master_file.readline().strip().split(",")
sql_cmd = "DROP TABLE IF EXISTS " + self.table_name + ";\n"
sql_cmd += "CREATE TABLE " + self.table_name + " (\n"
sql_cmd += (
"id_ SERIAL PRIMARY KEY,\n"
+ columns[0] + " INTEGER,\n"
+ columns[1] + " VARCHAR(50),\n"
+ columns[2] + " FLOAT,\n"
+ columns[3] + " INTEGER,\n"
+ columns[4] + " FLOAT,\n"
+ columns[5] + " INTEGER,\n"
+ columns[6] + " FLOAT,\n"
+ columns[7] + " INTEGER,\n"
+ columns[8] + " VARCHAR(10),\n"
+ columns[9] + " VARCHAR(50));"
)
CUR.execute(sql_cmd)
CONN.commit()
# -------------------------------
# Copy data from CSV files created in smogon_pull.py into database
# -------------------------------.
def fill_tables(self):
master_file = open(self.__FILE, "r")
columns = tuple(master_file.readline().strip().split(","))
CUR.copy_from(
master_file,
self.table_name,
columns=columns,
sep=","
)
CONN.commit()
# -------------------------------
# Disconnect from database.
# -------------------------------
def close_db(self):
CUR.close()
print("Cursor closed.")
CONN.close()
print("Connection to server closed.")
if __name__ == "__main__":
manager = DB_Manager()
print("connected")
manager.construct_tables()
print("table made")
manager.fill_tables()
print("filled")
```
as I said, everything worked fine, but now I'm getting this unexpected error, and not sure how to trace it back. The name `"alan"` is not in any of my credentials, which is confusing me.
I'm not running it via CLI, but through my text editor (in this case VS code).
|
2021/04/22
|
[
"https://Stackoverflow.com/questions/67211732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11790979/"
] |
The "month" view provided by fullCalendar does not have this flexibility - it always starts at the beginning of the month, like a traditional paper calendar.
IMHO it would be confusing to many users if it appeared differently.
Other types of view are more flexible - they will respond to the `visibleRange` setting if you do not specify the time range in the view name, such as if you specify `timeGrid` rather than `timeGridWeek` for example.
|
Change **type: 'dayGridMonth'** to **type: 'dayGrid'**
|
66,214,454
|
Ansible version: 2.8.3 or Any
I'm using `-m <module>` Ansible's **ad-hoc** command to ensure the following package is installed **--OR--** let's say if I have a task to install few yum packages, like (i.e. How can I do the same within a task (possibly when ***I'm not using ansible's shell / command*** modules):
```
- name: Installing necessary yum dependencies
yum:
name:
- wget
- python-devel
- openssl-devel
state: latest
```
**It works,** but how can I get the output of whole `yum` operation in a nice output format (instead of getting a one line format with bunch of `\n` characters embedded in it); like what we usually get when we run the same command (`yum install <some_package>`) on Linux command prompt.
**I want to ansible to retain a command's output in original format**
The line I want to see in more linted/beautified way is: `Loaded plugins: ...`
```
[root@ansible-server test_ansible]# ansible -i hosts all -m yum -a 'name=ncdu state=present'
host1 | SUCCESS => {
"changed": true,
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirror.netsite.dk\n * elrepo: mirrors.xservers.ro\n * epel: fedora.mirrors.telekom.ro\n * extras: centos.mirrors.telekom.ro\n * remi-php70: remi.schlundtech.de\n * remi-safe: remi.schlundtech.de\n * updates: centos.mirror.iphh.net\nResolving Dependencies\n--> Running transaction check\n---> Package ncdu.x86_64 0:1.14-1.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n ncdu x86_64 1.14-1.el7 epel 51 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 51 k\nInstalled size: 87 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : ncdu-1.14-1.el7.x86_64 1/1 \n Verifying : ncdu-1.14-1.el7.x86_64 1/1 \n\nInstalled:\n ncdu.x86_64 0:1.14-1.el7 \n\nComplete!\n"
]
}
```
Example of the aligned linted/beautified format that I'm looking for, is shown below if I execute: **# yum install ncdu**, we need need the exact same output, but how it's per line and easy to read/visualize on stdout.
```
Loaded plugins: amazon-id, langpacks, product-id, search-disabled-repos, subscription-manager
This system is registered with an entitlement server, but is not receiving updates. You can use subscription-manager to assign subscriptions.
*** WARNING ***
The subscription for following product(s) has expired:
- Oracle Java (for RHEL Server)
- Red Hat Ansible Engine
- Red Hat Beta
- Red Hat CodeReady Linux Builder for x86_64
- Red Hat Container Images
- Red Hat Container Images Beta
- Red Hat Developer Tools (for RHEL Server)
- Red Hat Developer Tools Beta (for RHEL Server)
- Red Hat Developer Toolset (for RHEL Server)
- Red Hat Enterprise Linux Atomic Host
- Red Hat Enterprise Linux Atomic Host Beta
- Red Hat Enterprise Linux Server
- Red Hat Enterprise Linux for x86_64
- Red Hat Software Collections (for RHEL Server)
- Red Hat Software Collections Beta (for RHEL Server)
- dotNET on RHEL (for RHEL Server)
- dotNET on RHEL Beta (for RHEL Server)
You no longer have access to the repositories that provide these products. It is important that you apply an active subscription in order to resume access to security and other critical updates. If you don't have other active subscriptions, you can renew the expired subscription.
Resolving Dependencies
--> Running transaction check
---> Package ncdu.x86_64 0:1.15.1-1.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
==============================================================================================================================================================================================================================================================
Package Arch Version Repository Size
==============================================================================================================================================================================================================================================================
Installing:
ncdu x86_64 1.15.1-1.el7 epel 52 k
Transaction Summary
==============================================================================================================================================================================================================================================================
Install 1 Package
Total download size: 52 k
Installed size: 88 k
Is this ok [y/d/N]: y
Downloading packages:
ncdu-1.15.1-1.el7.x86_64.rpm | 52 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : ncdu-1.15.1-1.el7.x86_64 1/1
Verifying : ncdu-1.15.1-1.el7.x86_64 1/1
Installed:
ncdu.x86_64 0:1.15.1-1.el7
Complete!
```
|
2021/02/15
|
[
"https://Stackoverflow.com/questions/66214454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1499296/"
] |
You should add this line to your **MouseArea** to work:
```
anchors.fill: parent
```
|
thanks @Farshid616 for the help. The problem was that my MouseArea wasn't inside the Rectangular. So only I needed is open code and move Mouse Area into Rectangular area, so that the MouseArea would be child of the Rectangular.
|
67,484,068
|
I have a model with a unique "code" field and a form for the same model where the "code" field is hidden. I need to set the "code" value in the view after the user has copied the form, but I get an IntegrityError exception.
**model**
```
class Ticket(models.Model):
codice = models.CharField(unique=True, max_length = 13, default = '')
```
**form**
```
class NewTicketForm(forms.ModelForm):
codice = forms.CharField(widget = forms.HiddenInput(), required=False)
```
**view**
```
if request.method == 'POST':
form = NewTicketForm(request.POST)
form.codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789')
if form.is_valid():
while True:
try:
codice = 'MC-PR' + get_random_string(length=8, allowed_chars='0123456789')
form.codice = codice
form.save()
except:
break
form.save()
return redirect('ticket-homepage')
else:
form = NewTicketForm()
context = {
'form': form
}
return render(request, 'ticket/new_ticket_form.html', context)
```
I also tried to set form.code before form.is\_valid () but the exception is raised anyway. technically there shouldn't be any problems because I generate the value with get\_random\_string and try-except allows me to do it again as long as the value is not unique.
**traceback**
```
Traceback (most recent call last):
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/cursors.py", line 148, in execute
result = self._query(query)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/cursors.py", line 310, in _query
conn.query(q)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 775, in _read_query_result
result.read()
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 725, in _read_packet
packet.raise_for_error()
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
The above exception ((1062, "Duplicate entry '' for key 'ticket_ticket.ticket_ticket_codice_f619a2bb_uniq'")) was the direct cause of the following exception:
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/framework_mc/ticket/views.py", line 34, in createNewTicket
form.save()
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/forms/models.py", line 460, in save
self.instance.save()
File "/var/www/framework_mc/ticket/models.py", line 72, in save
return super(Ticket, self).save(*args, **kwargs)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
updated = self._save_table(
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert
return manager._insert(
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/cursors.py", line 148, in execute
result = self._query(query)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/cursors.py", line 310, in _query
conn.query(q)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 775, in _read_query_result
result.read()
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/connections.py", line 725, in _read_packet
packet.raise_for_error()
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "/var/www/framework_mc/framework_mc/lib/python3.8/site-packages/pymysql/err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
Exception Type: IntegrityError at /ticket/new-ticket/
Exception Value: (1062, "Duplicate entry '' for key 'ticket_ticket.ticket_ticket_codice_f619a2bb_uniq'")
```
|
2021/05/11
|
[
"https://Stackoverflow.com/questions/67484068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14293891/"
] |
To check for email and operate on it you are probably better of using Spring Integration which has out-of-the-box [email support](https://docs.spring.io/spring-integration/docs/current/reference/html/mail.html).
Regarding your question I suspect you misunderstood the [`ApplicationListener`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationListener.html). It can be used to receive events fired through the internal event API of Spring. It won't start a listener thread like the listeners for Kafka or JMS would do. Althouhg both listeners in their own sense they are quite different beast.
But as mentioned you are probably better of using the [email support](https://docs.spring.io/spring-integration/docs/current/reference/html/mail.html) of Spring Integration, saves you from writing your own.
|
I think you misunderstood the concept of spring context listeners.
Spring application context starts during the startup of spring driven application.
It has various "hooks" - points that you could listen to and be notified once they happen. So yes, context can be refreshed and when it happens, the listener "fires" and your code is executed. But that's it - it won't actually do anything useful afterwards, when the context starts. You can read about the context events [here](https://www.baeldung.com/spring-context-events) for example.
So with this in mind, basically your application context gets refreshed once, and the listener will be called also only once during the application startup.
Now I didn't understand how is RMI server related to all this :) You can remove the `@Component` annotation from the listener and restart the application, probably it will still search for the RMI server (please try that and update in the comment or something)
So first off, I think you should try to understand how is RMI related to all this, I think there is some other component in the system that gets loaded by spring boot and it searches for the RMI. Maybe You can take a thread dump or something and see which thread really works with RMI.
To get an event "when the message is added" is an entirely different thing, you will probably have to implement it by yourself or if the thirdparty that works with email has such a functionality - try to find how to achieve that with that thirdpary API, but for sure its not a ContextRefreshed event.
|
1,487,022
|
HI All,
Has anybody been able to extract the device tokens from the binary data that iPhone APNS feedback service returns using PHP? I am looking for something similar to what is been implementented using python here
[http://www.google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#m5eOMDWiKUs/APNSWrapper/**init**.py&q=feedback.push.apple.com](http://www.google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#m5eOMDWiKUs/APNSWrapper/__init__.py&q=feedback.push.apple.com)
As per the Apple documentation, I know that the first 4 bytes are timestamp, next 2 bytes is the length of the token and rest of the bytes are the actual token in binary format. (<http://developer.apple.com/IPhone/library/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3>)
I am successfully able to extract the timestamp from the data feedback service returns, but the device token that I get after i convert to hexadecimal using the PHP's built in method bin2hex() is actually different than original device token. I am doing something silly in the conversion. Can anybody help me out if they have already implemented APNS feedback service using PHP?
TIA,
-Anish
|
2009/09/28
|
[
"https://Stackoverflow.com/questions/1487022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130985/"
] |
[PHP technique to query the APNs Feedback Server](https://stackoverflow.com/questions/1278834/php-technique-to-query-the-apns-feedback-server)
|
The best place to go for this is actually the Apple developer forums in internal to the iPhone portal - the have a bunch of examples in different languages for working with these push requests.
I'm also currently at an 360iDev push session, and they noted an open source PHP server can be found at:
<http://code.google.com/p/php-apns/>
|
1,487,022
|
HI All,
Has anybody been able to extract the device tokens from the binary data that iPhone APNS feedback service returns using PHP? I am looking for something similar to what is been implementented using python here
[http://www.google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#m5eOMDWiKUs/APNSWrapper/**init**.py&q=feedback.push.apple.com](http://www.google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#m5eOMDWiKUs/APNSWrapper/__init__.py&q=feedback.push.apple.com)
As per the Apple documentation, I know that the first 4 bytes are timestamp, next 2 bytes is the length of the token and rest of the bytes are the actual token in binary format. (<http://developer.apple.com/IPhone/library/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3>)
I am successfully able to extract the timestamp from the data feedback service returns, but the device token that I get after i convert to hexadecimal using the PHP's built in method bin2hex() is actually different than original device token. I am doing something silly in the conversion. Can anybody help me out if they have already implemented APNS feedback service using PHP?
TIA,
-Anish
|
2009/09/28
|
[
"https://Stackoverflow.com/questions/1487022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130985/"
] |
[PHP technique to query the APNs Feedback Server](https://stackoverflow.com/questions/1278834/php-technique-to-query-the-apns-feedback-server)
|
Once you have your binary stream, you can process it like this:
```
while ($data = fread($stream, 38)) {
$feedback = unpack("N1timestamp/n1length/H*devtoken", $data);
// Do something
}
```
$feedback will be an associative array containing elements "timestamp", "length" and "devtoken".
|
13,336,623
|
I'm using Python 2.6.2. I have a list of tuples `pair` which I like to sort using two nested conditions.
1. The tuples are first sorted in descending count order of `fwd_count`,
2. If the value of count is the same for more than one tuple in `fwd_count`, only those tuples having equal count need to be sorted in descending order based on values in `rvs_count`.
3. The order does not matter and the positioning can be ignored, if
a) tuples have the same count in `fwd_count` and also in `rvs_count`, or
a) tuples have the same count in `fwd_count` and does not exist in `rvs_count`
I managed to write the following code:
```
pair=[((0, 12), (0, 36)), ((1, 12), (0, 36)), ((2, 12), (1, 36)), ((3, 12), (1, 36)), ((1, 36), (4, 12)), ((0, 36), (5, 12)), ((1, 36), (6, 12))]
fwd_count = {}
rvs_count = {}
for link in sorted(pair):
fwd_count[link[0]] = 0
rvs_count[link[1]] = 0
for link in sorted(pair):
fwd_count[link[0]] += 1
rvs_count[link[1]] += 1
#fwd_count {(6, 12): 1, (5, 12): 1, (4, 12): 1, (1, 36): 2, (0, 36): 2}
#rvs_count {(3, 12): 1, (1, 12): 1, (1, 36): 2, (0, 12): 1, (2, 12): 1, (0, 36): 1}
fwd_count_sort=sorted(fwd_count.items(), key=lambda x: x[1], reverse=True)
rvs_count_sort=sorted(rvs_count.items(), key=lambda x: x[1])
#fwd_count_sort [((1, 36), 2), ((0, 36), 2), ((6, 12), 1), ((5, 12), 1), ((4, 12), 1)]
#rvs_count_sort [((3, 12), 1), ((1, 12), 1), ((1, 36), 2), ((0, 12), 1), ((2, 12), 1), ((0, 36), 1)]
```
The result I am looking for is:
```
#fwd_count_sort_final [((0, 36), 2), ((1, 36), 2), ((6, 12), 1), ((5, 12), 1), ((4, 12), 1)]
```
Where the position of `(1, 36)` and `(0, 36)` have swapped position from the one in `fwd_count_sort`.
Question:
1. Is there a better way to do multi condition sorting using `fwd_count` and `rvs_count` information at the same time? (Only the tuples are important, the sort value need not be recorded.), or
2. Would I need to sort it individually for each conditions (as I did above) and try to find mean to integrate it to get the result I wanted?
I am currently working on item #2 above, but trying to learn if there are any simpler method.
This is the closest I can get to what I am looking for "Bidirectional Sorting with Numeric Values" at <http://stygianvision.net/updates/python-sort-list-object-dictionary-multiple-key/> but not sure I can use that if I create a new dictionary with {tuple: {fwd\_count : rvs\_count}} relationship.
**Update: 12 November 2012 -- SOLVED**
I have managed to solve this by using list. The below are the codes, hope it is useful for those whom are working to sort multi condition list.
```
#pair=[((0, 12), (0, 36)), ((1, 12), (1, 36)), ((2, 12), (0, 36)), ((3, 12), (1, 36)), ((1, 36), (4, 12)), ((0, 36), (5, 12)), ((1, 36), (6, 12))]
rvs_count = {}
fwd_count = {}
for link in sorted(pair):
rvs_count[link[0]] = 0
fwd_count[link[1]] = 0
for link in sorted(pair):
rvs_count[link[0]] += 1
fwd_count[link[1]] += 1
keys = []
for link in pair:
if link[0] not in keys:
keys.append(link[0])
if link[1] not in keys:
keys.append(link[1])
aggregated = []
for k in keys:
a = -1
d = -1
if k in fwd_count.keys():
a = fwd_count[k]
if k in rvs_count.keys():
d = rvs_count[k]
aggregated.append(tuple((k, tuple((a,d)) )))
def compare(x,y):
a1 = x[1][0]
d1 = x[1][1]
a2 = y[1][0]
d2 = y[1][1]
if a1 > a2:
return - a1 + a2
elif a1 == a2:
if d1 > d2:
return d1 - d2
elif d1 == d2:
return 0
else:
return d1 - d2
else:
return - a1 + a2
s = sorted(aggregated, cmp=compare)
print(s)
j = [v[0] for v in s]
print(j)
```
Thanks to Andre Fernandes, Brian and Duke for giving your comments on my work
|
2012/11/11
|
[
"https://Stackoverflow.com/questions/13336623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1611813/"
] |
If you require to swap *all* first (of pair) elements (and not just `(1, 36)` and `(0, 36)`), you can do
`fwd_count_sort=sorted(rvs_count.items(), key=lambda x: (x[0][1],-x[0][0]), reverse=True)`
|
I'm not exactly sure on the definition of your sorting criteria, but this is a method to sort the `pair` list according to the values in `fwd_count` and `rvs_count`. Hopefully you can use this to get to the result you want.
```
def keyFromPair(pair):
"""Return a tuple (f, r) to be used for sorting the pairs by frequency."""
global fwd_count
global rvs_count
first, second = pair
countFirstInv = -fwd_count[first] # use the negative to reverse the sort order
countSecond = rvs_count[second]
return (first, second)
pairs_sorted = sorted(pair, key = keyFromPair)
```
The basic idea is to use Python's in-built tuple ordering mechanism to sort on multiple keys, and to invert one of the values in the tuple so make it a reverse-order sort.
|
69,281,148
|
I have around 30000 Urls in my csv. I need to check if it has meta content is present or not, for each url. I am using request\_cache to basically cache the response to a sqlite db. It was taking about 24hrs even after using a caching sys. Therefore I moved to concurrency. I think I have done something wrong with `out = executor.map(download_site, sites, headers)`. And do not know how to fix it.
AttributeError: 'str' object has no attribute 'items'
```
import concurrent.futures
import requests
import threading
import time
import pandas as pd
import requests_cache
from PIL import Image
from io import BytesIO
thread_local = threading.local()
df = pd.read_csv("test.csv")
sites = []
for row in df['URLS']:
sites.append(row)
# print("URL is shortened")
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,}
requests_cache.install_cache('network_call', backend='sqlite', expire_after=2592000)
def getSess():
if not hasattr(thread_local, "session"):
thread_local.session = requests.Session()
return thread_local.session
def networkCall(url, headers):
print("In Download site")
session = getSess()
with session.get(url, headers=headers) as response:
print(f"Read {len(response.content)} from {url}")
return response.content
out = []
def getMeta(meta_res):
print("Get data")
for each in meta_res:
meta = each.find_all('meta')
for tag in meta:
if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['description', 'keywords']:
content = tag.attrs['content']
if content != '':
out.append("Absent")
else:
out.append("Present")
return out
def allSites(sites):
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
out = executor.map(networkCall, sites, headers)
return list(out)
if __name__ == "__main__":
sites = [
"https://www.jython.org",
"http://olympus.realpython.org/dice",
] * 15000
start_time = time.time()
list_meta = allSites(sites)
print("META ", list_meta)
duration = time.time() - start_time
print(f"Downloaded {len(sites)} in {duration} seconds")
output = getMeta(list_meta)
df["is it there"] = pd.Series(output)
df.to_csv('new.csv',index=False, header=True)
```
|
2021/09/22
|
[
"https://Stackoverflow.com/questions/69281148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16433326/"
] |
I have tried to emulate your functionality. The following code executes in under 4 minutes:-
```
from bs4 import BeautifulSoup as BS
import concurrent.futures
import time
import queue
import requests
URLs = [
"https://www.jython.org",
"http://olympus.realpython.org/dice"
] * 15_000
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers = {'User-Agent': user_agent}
class SessionCache():
def __init__(self, cachesize=20):
self.cachesize = cachesize
self.sessions = 0
self.q = queue.Queue()
def getSession(self):
try:
return self.q.get(block=False)
except queue.Empty:
pass
if self.sessions < self.cachesize:
self.q.put(requests.Session())
self.sessions += 1
return self.q.get()
def putSession(self, session):
self.q.put(session)
CACHE = SessionCache()
def doGet(url):
try:
session = CACHE.getSession()
response = session.get(url, headers=headers)
response.raise_for_status()
soup = BS(response.text, 'lxml')
for meta in soup.find_all('meta'):
if (name := meta.attrs.get('name', None)):
if name.strip().lower() in ['description', 'keywords']:
if meta.attrs.get('content', '') != '':
return url, 'Present'
return url, 'Absent'
except Exception as e:
return url, str(e)
finally:
CACHE.putSession(session)
def main():
start = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor() as executor:
for r in executor.map(doGet, URLs):
print(f'{r[0]} -> {r[1]}')
end = time.perf_counter()
print(f'Duration={end-start:.4f}s')
if __name__ == '__main__':
main()
```
|
AttributeError: 'str' object has no attribute 'items'
=====================================================
This error is happening in `requests.models.PrepareRequest.prepare_headers()`. When you call `executor.map(networkCall, sites, headers)`, it's casting `headers` to a list, so you end up with `request.headers = 'User-Agent'` instead of `request.headers = {'User-Agent': '...'}`.
Since it looks like the headers aren't actually changing, you can make that a constant and remove it as an argument from `networkCall()`:
```py
HEADERS = {'User-Agent':user_agent}
...
def networkCall(url):
session = getSess()
with session.get(url, headers=HEADERS) as response:
print(f"Read {len(response.content)} from {url}")
return response.content
...
def allSites(sites):
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
out = executor.map(networkCall, sites)
return list(out)
```
sqlite3.OperationalError: database is locked
============================================
Another thing worth noting is that `requests_cache.install_cache()` is **not** thread-safe, which causes the `sqlite3.OperationalError` you got earlier. You can remove `install_cache()` and use `requests_cache.CachedSession` instead, which **is** thread-safe:
```py
def getSess():
if not hasattr(thread_local, "session"):
thread_local.session = requests_cache.CachedSession(
'network_call',
backend='sqlite',
expire_after=2592000,
)
return thread_local.session
```
For reference, there's more info in the requests-cache user guide on the [differences between sessions and patching](https://requests-cache.readthedocs.io/en/stable/user_guide/general.html).
Performance
===========
A note on performance: Since you're doing lots of concurrent writes, SQLite isn't ideal. It's fast for concurrent reads, but for writes it internally queues operations and writes data in serial, not in parallel. If possible, try using Redis or one of the other [requests-cache backends](https://requests-cache.readthedocs.io/en/stable/user_guide/backends.html), which are better optimized for concurrent writes.
|
69,281,148
|
I have around 30000 Urls in my csv. I need to check if it has meta content is present or not, for each url. I am using request\_cache to basically cache the response to a sqlite db. It was taking about 24hrs even after using a caching sys. Therefore I moved to concurrency. I think I have done something wrong with `out = executor.map(download_site, sites, headers)`. And do not know how to fix it.
AttributeError: 'str' object has no attribute 'items'
```
import concurrent.futures
import requests
import threading
import time
import pandas as pd
import requests_cache
from PIL import Image
from io import BytesIO
thread_local = threading.local()
df = pd.read_csv("test.csv")
sites = []
for row in df['URLS']:
sites.append(row)
# print("URL is shortened")
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,}
requests_cache.install_cache('network_call', backend='sqlite', expire_after=2592000)
def getSess():
if not hasattr(thread_local, "session"):
thread_local.session = requests.Session()
return thread_local.session
def networkCall(url, headers):
print("In Download site")
session = getSess()
with session.get(url, headers=headers) as response:
print(f"Read {len(response.content)} from {url}")
return response.content
out = []
def getMeta(meta_res):
print("Get data")
for each in meta_res:
meta = each.find_all('meta')
for tag in meta:
if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['description', 'keywords']:
content = tag.attrs['content']
if content != '':
out.append("Absent")
else:
out.append("Present")
return out
def allSites(sites):
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
out = executor.map(networkCall, sites, headers)
return list(out)
if __name__ == "__main__":
sites = [
"https://www.jython.org",
"http://olympus.realpython.org/dice",
] * 15000
start_time = time.time()
list_meta = allSites(sites)
print("META ", list_meta)
duration = time.time() - start_time
print(f"Downloaded {len(sites)} in {duration} seconds")
output = getMeta(list_meta)
df["is it there"] = pd.Series(output)
df.to_csv('new.csv',index=False, header=True)
```
|
2021/09/22
|
[
"https://Stackoverflow.com/questions/69281148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16433326/"
] |
I have tried to emulate your functionality. The following code executes in under 4 minutes:-
```
from bs4 import BeautifulSoup as BS
import concurrent.futures
import time
import queue
import requests
URLs = [
"https://www.jython.org",
"http://olympus.realpython.org/dice"
] * 15_000
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers = {'User-Agent': user_agent}
class SessionCache():
def __init__(self, cachesize=20):
self.cachesize = cachesize
self.sessions = 0
self.q = queue.Queue()
def getSession(self):
try:
return self.q.get(block=False)
except queue.Empty:
pass
if self.sessions < self.cachesize:
self.q.put(requests.Session())
self.sessions += 1
return self.q.get()
def putSession(self, session):
self.q.put(session)
CACHE = SessionCache()
def doGet(url):
try:
session = CACHE.getSession()
response = session.get(url, headers=headers)
response.raise_for_status()
soup = BS(response.text, 'lxml')
for meta in soup.find_all('meta'):
if (name := meta.attrs.get('name', None)):
if name.strip().lower() in ['description', 'keywords']:
if meta.attrs.get('content', '') != '':
return url, 'Present'
return url, 'Absent'
except Exception as e:
return url, str(e)
finally:
CACHE.putSession(session)
def main():
start = time.perf_counter()
with concurrent.futures.ThreadPoolExecutor() as executor:
for r in executor.map(doGet, URLs):
print(f'{r[0]} -> {r[1]}')
end = time.perf_counter()
print(f'Duration={end-start:.4f}s')
if __name__ == '__main__':
main()
```
|
Just recently stumbled upon a library for making async requests, it is called [requests-futures](https://github.com/ross/requests-futures).
The syntax is pretty simple:
```
from concurrent.futures import as_completed
from requests_futures.sessions import FuturesSession
from bs4 import BeautifulSoup
import time
URLs = [
'https://www.jython.org',
'http://olympus.realpython.org/dice'
] * 1000
def scrape(URLs):
with FuturesSession() as session:
out = []
futures = [session.get(url) for url in URLs]
for future in as_completed(futures):
resp = future.result()
pageSoup = BeautifulSoup(resp.content, 'html.parser')
meta = pageSoup.find_all("meta")
for tag in meta:
if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['description', 'keywords']:
content = tag.attrs['content']
if content != '':
out.append("Absent")
else:
out.append("Present")
return out
```
So, it essentially took less then a minute to scrape 2,000 URLs
```
%%time
data = scrape(URLs)
```
CPU times: user 13.5 s, sys: 801 ms, total: 14.3 s
Wall time: 30.1 s
|
69,281,148
|
I have around 30000 Urls in my csv. I need to check if it has meta content is present or not, for each url. I am using request\_cache to basically cache the response to a sqlite db. It was taking about 24hrs even after using a caching sys. Therefore I moved to concurrency. I think I have done something wrong with `out = executor.map(download_site, sites, headers)`. And do not know how to fix it.
AttributeError: 'str' object has no attribute 'items'
```
import concurrent.futures
import requests
import threading
import time
import pandas as pd
import requests_cache
from PIL import Image
from io import BytesIO
thread_local = threading.local()
df = pd.read_csv("test.csv")
sites = []
for row in df['URLS']:
sites.append(row)
# print("URL is shortened")
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent,}
requests_cache.install_cache('network_call', backend='sqlite', expire_after=2592000)
def getSess():
if not hasattr(thread_local, "session"):
thread_local.session = requests.Session()
return thread_local.session
def networkCall(url, headers):
print("In Download site")
session = getSess()
with session.get(url, headers=headers) as response:
print(f"Read {len(response.content)} from {url}")
return response.content
out = []
def getMeta(meta_res):
print("Get data")
for each in meta_res:
meta = each.find_all('meta')
for tag in meta:
if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['description', 'keywords']:
content = tag.attrs['content']
if content != '':
out.append("Absent")
else:
out.append("Present")
return out
def allSites(sites):
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
out = executor.map(networkCall, sites, headers)
return list(out)
if __name__ == "__main__":
sites = [
"https://www.jython.org",
"http://olympus.realpython.org/dice",
] * 15000
start_time = time.time()
list_meta = allSites(sites)
print("META ", list_meta)
duration = time.time() - start_time
print(f"Downloaded {len(sites)} in {duration} seconds")
output = getMeta(list_meta)
df["is it there"] = pd.Series(output)
df.to_csv('new.csv',index=False, header=True)
```
|
2021/09/22
|
[
"https://Stackoverflow.com/questions/69281148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16433326/"
] |
Just recently stumbled upon a library for making async requests, it is called [requests-futures](https://github.com/ross/requests-futures).
The syntax is pretty simple:
```
from concurrent.futures import as_completed
from requests_futures.sessions import FuturesSession
from bs4 import BeautifulSoup
import time
URLs = [
'https://www.jython.org',
'http://olympus.realpython.org/dice'
] * 1000
def scrape(URLs):
with FuturesSession() as session:
out = []
futures = [session.get(url) for url in URLs]
for future in as_completed(futures):
resp = future.result()
pageSoup = BeautifulSoup(resp.content, 'html.parser')
meta = pageSoup.find_all("meta")
for tag in meta:
if 'name' in tag.attrs.keys() and tag.attrs['name'].strip().lower() in ['description', 'keywords']:
content = tag.attrs['content']
if content != '':
out.append("Absent")
else:
out.append("Present")
return out
```
So, it essentially took less then a minute to scrape 2,000 URLs
```
%%time
data = scrape(URLs)
```
CPU times: user 13.5 s, sys: 801 ms, total: 14.3 s
Wall time: 30.1 s
|
AttributeError: 'str' object has no attribute 'items'
=====================================================
This error is happening in `requests.models.PrepareRequest.prepare_headers()`. When you call `executor.map(networkCall, sites, headers)`, it's casting `headers` to a list, so you end up with `request.headers = 'User-Agent'` instead of `request.headers = {'User-Agent': '...'}`.
Since it looks like the headers aren't actually changing, you can make that a constant and remove it as an argument from `networkCall()`:
```py
HEADERS = {'User-Agent':user_agent}
...
def networkCall(url):
session = getSess()
with session.get(url, headers=HEADERS) as response:
print(f"Read {len(response.content)} from {url}")
return response.content
...
def allSites(sites):
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
out = executor.map(networkCall, sites)
return list(out)
```
sqlite3.OperationalError: database is locked
============================================
Another thing worth noting is that `requests_cache.install_cache()` is **not** thread-safe, which causes the `sqlite3.OperationalError` you got earlier. You can remove `install_cache()` and use `requests_cache.CachedSession` instead, which **is** thread-safe:
```py
def getSess():
if not hasattr(thread_local, "session"):
thread_local.session = requests_cache.CachedSession(
'network_call',
backend='sqlite',
expire_after=2592000,
)
return thread_local.session
```
For reference, there's more info in the requests-cache user guide on the [differences between sessions and patching](https://requests-cache.readthedocs.io/en/stable/user_guide/general.html).
Performance
===========
A note on performance: Since you're doing lots of concurrent writes, SQLite isn't ideal. It's fast for concurrent reads, but for writes it internally queues operations and writes data in serial, not in parallel. If possible, try using Redis or one of the other [requests-cache backends](https://requests-cache.readthedocs.io/en/stable/user_guide/backends.html), which are better optimized for concurrent writes.
|
18,937,057
|
I am searching for items that are not repeated in a list in python.
The current way I do it is,
```
python -mtimeit -s'l=[1,2,3,4,5,6,7,8,9]*99' '[x for x in l if l.count(x) == 1]'
100 loops, best of 3: 12.9 msec per loop
```
Is it possible to do it faster?
This is the output.
```
>>> l = [1,2,3,4,5,6,7,8,9]*99+[10,11]
>>> [x for x in l if l.count(x) == 1]
[10, 11]
```
|
2013/09/21
|
[
"https://Stackoverflow.com/questions/18937057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994176/"
] |
You can use [the `Counter` class](http://docs.python.org/dev/library/collections.html#collections.Counter) from `collections`:
```
from collections import Counter
...
[item for item, count in Counter(l).items() if count == 1]
```
My results:
```none
$ python -m timeit -s 'from collections import Counter; l = [1, 2, 3, 4, 5, 6, 7, 8, 9] * 99' '[item for item, count in Counter(l).items() if count == 1]'
1000 loops, best of 3: 366 usec per loop
$ python -mtimeit -s'l=[1,2,3,4,5,6,7,8,9]*99' '[x for x in l if l.count(x) == 1]'
10 loops, best of 3: 23.4 msec per loop
```
|
Basically you want to remove duplicate entries, so there are some answers here:
* [How do you remove duplicates from a list in Python whilst preserving order?](https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order)
* [Remove duplicates in a list while keeping its order (Python)](https://stackoverflow.com/a/1549550/170413)
Using `in` as opposed to `count()` should be a little quicker because the query is done once it finds the first instance.
|
66,093,541
|
Is there a way in C++ to pass arguments by name like in python?
For example I have a function:
```
void foo(int a, int b = 1, int c = 3, int d = 5);
```
Can I somehow call it like:
```
foo(5 /* a */, c = 5, d = 8);
```
Or
```
foo(5, /* a */, d = 1);
```
|
2021/02/07
|
[
"https://Stackoverflow.com/questions/66093541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15114707/"
] |
There are no named function parameters in C++, but you can achieve a similar effect with designated initializers from C++20.
Take all the function parameters and put them into a struct:
```
struct S
{
int a{}, b{}, c{}, d{};
};
```
Now modify your function to take an instance of that struct (by `const&` for efficiency)
```
void foo(S s)
{
std::cout << s.a << " " << s.b << " " << s.c << " " << s.d; // for example
}
```
and now you can call the function like this:
```
foo({.a = 2, .c = 3}); // prints 2 0 3 0
// b and d get default values of 0
```
Here's a [demo](https://godbolt.org/z/neTdeP)
|
**No**
You have to pass the arguments by order, so, to specify a value for *d*, you must also specify one for *c* since it's declared before it, for example
|
64,972,907
|
Output:
```none
pygame 2.0.0 (SDL 2.0.12, python 3.8.6)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\New User\Python Projects\Aliens Invasion Game\alien_invasion.py", line 5, in <module>
class AlienInvasion:
File "C:\Users\New User\Python Projects\Aliens Invasion Game\alien_invasion.py", line 26, in AlienInvasion
ai = AlienInvasion()
NameError: name 'AlienInvasion' is not defined
```
```py
import sys
import pygame
class AlienInvasion:
"""Overall class to manage game assets and behaviour."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
def run_game(self):
"""Start the main loop for the game."""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
#make a game instance and run the game.
ai = AlienInvasion()
ai.run_game()
```
Why am I getting `NameError` on `AlienInvasion.py`?
|
2020/11/23
|
[
"https://Stackoverflow.com/questions/64972907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14625233/"
] |
The original code you posted has an indentation issue - your `if __name__ == '__main__'` block is indented, meaning it's actually considered to be within the scope of `class AlienInvasion`:
```
import ...
class AlienInvasion:
def __init__(self):
...
def run_game(self):
...
# IMPORPERLY INDENTED:
if __name__ == '__main__':
#make a game instance and run the game.
ai = AlienInvasion()
ai.run_game()
```
Since you're trying to use `AlienInvasion` in the middle of its own definition, you'll therefore get something like this error:
```
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 16, in AlienInvasion
NameError: name 'AlienInvasion' is not defined
```
Thus, in order to fix the error, you have to fix your indentation, so that your `main` block is outside of `AlienInvasion`:
```
import sys
import pygame
class AlienInvasion:
"""Overall class to manage game assets and behaviour."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
def run_game(self):
"""Start the main loop for the game."""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
#make a game instance and run the game.
ai = AlienInvasion()
ai.run_game()
```
|
You should remove your main block from the definition of the `AlienInvasion` class.
Your `.py` file should look like this:
```
import sys
import pygame
class AlienInvasion:
"""Overall class to manage game assets and behaviour."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
def run_game(self):
"""Start the main loop for the game."""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#make the most recently drawn screen visible.
pygame.display.flip()
if __name__ == '__main__':
#make a game instance and run the game.
ai = AlienInvasion()
ai.run_game()
```
|
62,657,469
|
I want to search for the word in the file and print next value of it using any way using python
Following is the code :
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite:
remove_comment=line.split('#')[0]
for test in testList:
if re.search(test, remove_comment, re.IGNORECASE):
hashfile.writelines(remove_comment)
search_word=remove_comment.split(':component=>"', maxsplit=1)[-1].split(maxsplit=1)
print(search_word)
hashfile.close()
```
`remove_comment` has the following lines:
```
{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }
```
So now I want the output to be only the compnent value as following:
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
Please anyone help
|
2020/06/30
|
[
"https://Stackoverflow.com/questions/62657469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032819/"
] |
```
def matchTest(testsuite, testList):
hashfile = open("hash.txt", 'a')
with open ('text.txt', 'r') as suite:
lines = [line.strip() for line in suite.readlines() if line.strip()]
print(lines)
for line in lines:
f = re.search(r'component=>"(.*?)"', line) # find part you need
hashfile.write(f.group(1)+'\n')
hashfile.close()
```
**Output written to file:**
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
|
Try this:
```
import re
remove_comment = '''{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }'''
data = [x.split('"')[1] for x in re.findall(r'component=>[^,:}]*', remove_comment)]
print(data)
```
**Output:**
```
['Cloud Tier Mgmt', 'Content Store', 'Cloud-Connectivity']
```
|
62,657,469
|
I want to search for the word in the file and print next value of it using any way using python
Following is the code :
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite:
remove_comment=line.split('#')[0]
for test in testList:
if re.search(test, remove_comment, re.IGNORECASE):
hashfile.writelines(remove_comment)
search_word=remove_comment.split(':component=>"', maxsplit=1)[-1].split(maxsplit=1)
print(search_word)
hashfile.close()
```
`remove_comment` has the following lines:
```
{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }
```
So now I want the output to be only the compnent value as following:
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
Please anyone help
|
2020/06/30
|
[
"https://Stackoverflow.com/questions/62657469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032819/"
] |
Assuming the rest of the code is correct (we can't see what regular expressions you are using), you need to change only one line to:
```
search_word = remove_comment.split(':component=>"', maxsplit=1)[-1].split('"', maxsplit=1)[0]
```
|
Try this:
```
import re
remove_comment = '''{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }'''
data = [x.split('"')[1] for x in re.findall(r'component=>[^,:}]*', remove_comment)]
print(data)
```
**Output:**
```
['Cloud Tier Mgmt', 'Content Store', 'Cloud-Connectivity']
```
|
62,657,469
|
I want to search for the word in the file and print next value of it using any way using python
Following is the code :
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite:
remove_comment=line.split('#')[0]
for test in testList:
if re.search(test, remove_comment, re.IGNORECASE):
hashfile.writelines(remove_comment)
search_word=remove_comment.split(':component=>"', maxsplit=1)[-1].split(maxsplit=1)
print(search_word)
hashfile.close()
```
`remove_comment` has the following lines:
```
{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }
```
So now I want the output to be only the compnent value as following:
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
Please anyone help
|
2020/06/30
|
[
"https://Stackoverflow.com/questions/62657469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032819/"
] |
Try this function
```
def get_component(file_path):
word_list = []
file = open(file_path, 'r')
i = 0;
for line in file:
for word in line.split(','):
word = word[1:]
if word.startswith(":component=>"):
word = word[13:-1]
word_list.append(word)
print(word)
return word_list
```
You can copy-paste and give file\_path it going to work well.
here is my output:
```
['Cloud Tier Mgmt', 'Content Store', 'Cloud-Connectivity ']
```
|
Try this:
```
import re
remove_comment = '''{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }'''
data = [x.split('"')[1] for x in re.findall(r'component=>[^,:}]*', remove_comment)]
print(data)
```
**Output:**
```
['Cloud Tier Mgmt', 'Content Store', 'Cloud-Connectivity']
```
|
62,657,469
|
I want to search for the word in the file and print next value of it using any way using python
Following is the code :
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite:
remove_comment=line.split('#')[0]
for test in testList:
if re.search(test, remove_comment, re.IGNORECASE):
hashfile.writelines(remove_comment)
search_word=remove_comment.split(':component=>"', maxsplit=1)[-1].split(maxsplit=1)
print(search_word)
hashfile.close()
```
`remove_comment` has the following lines:
```
{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }
```
So now I want the output to be only the compnent value as following:
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
Please anyone help
|
2020/06/30
|
[
"https://Stackoverflow.com/questions/62657469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032819/"
] |
```
def matchTest(testsuite, testList):
hashfile = open("hash.txt", 'a')
with open ('text.txt', 'r') as suite:
lines = [line.strip() for line in suite.readlines() if line.strip()]
print(lines)
for line in lines:
f = re.search(r'component=>"(.*?)"', line) # find part you need
hashfile.write(f.group(1)+'\n')
hashfile.close()
```
**Output written to file:**
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
|
You can try
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite.split("\n"):
remove_comment=line.split('#')[0]
for i in remove_comment.split(","):
if "component=>" in i:
search_word = re.search("\"(.*)\"", i).group(1)
print(search_word)
hashfile.close()
```
Output
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
|
62,657,469
|
I want to search for the word in the file and print next value of it using any way using python
Following is the code :
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite:
remove_comment=line.split('#')[0]
for test in testList:
if re.search(test, remove_comment, re.IGNORECASE):
hashfile.writelines(remove_comment)
search_word=remove_comment.split(':component=>"', maxsplit=1)[-1].split(maxsplit=1)
print(search_word)
hashfile.close()
```
`remove_comment` has the following lines:
```
{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }
```
So now I want the output to be only the compnent value as following:
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
Please anyone help
|
2020/06/30
|
[
"https://Stackoverflow.com/questions/62657469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032819/"
] |
Assuming the rest of the code is correct (we can't see what regular expressions you are using), you need to change only one line to:
```
search_word = remove_comment.split(':component=>"', maxsplit=1)[-1].split('"', maxsplit=1)[0]
```
|
You can try
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite.split("\n"):
remove_comment=line.split('#')[0]
for i in remove_comment.split(","):
if "component=>" in i:
search_word = re.search("\"(.*)\"", i).group(1)
print(search_word)
hashfile.close()
```
Output
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
|
62,657,469
|
I want to search for the word in the file and print next value of it using any way using python
Following is the code :
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite:
remove_comment=line.split('#')[0]
for test in testList:
if re.search(test, remove_comment, re.IGNORECASE):
hashfile.writelines(remove_comment)
search_word=remove_comment.split(':component=>"', maxsplit=1)[-1].split(maxsplit=1)
print(search_word)
hashfile.close()
```
`remove_comment` has the following lines:
```
{:component=>"Cloud Tier Mgmt", :script=>"b.py", :testname=>"c", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml"}
{:skipfilesyscheck=>1, :component=>"Content Store", :script=>"b.py", --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml -s"}
{:script=>"b.py", :params=>"--ddrs=$DDRS --clients=$LOAD_CLIENT --log_level=DEBUG --config_file=a.yaml", :numddr=>1, :timeout=>10000, :component=>"Cloud-Connectivity" }
```
So now I want the output to be only the compnent value as following:
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
Please anyone help
|
2020/06/30
|
[
"https://Stackoverflow.com/questions/62657469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032819/"
] |
Try this function
```
def get_component(file_path):
word_list = []
file = open(file_path, 'r')
i = 0;
for line in file:
for word in line.split(','):
word = word[1:]
if word.startswith(":component=>"):
word = word[13:-1]
word_list.append(word)
print(word)
return word_list
```
You can copy-paste and give file\_path it going to work well.
here is my output:
```
['Cloud Tier Mgmt', 'Content Store', 'Cloud-Connectivity ']
```
|
You can try
```
def matchTest(testsuite, testList):
hashfile = open("/auto/file.txt", 'a')
with open (testsuite, 'r') as suite:
for line in suite.split("\n"):
remove_comment=line.split('#')[0]
for i in remove_comment.split(","):
if "component=>" in i:
search_word = re.search("\"(.*)\"", i).group(1)
print(search_word)
hashfile.close()
```
Output
```
Cloud Tier Mgmt
Content Store
Cloud-Connectivity
```
|
52,451,119
|
I have few text files which contain URLs. I am trying to create a SQLite database to store these URLs in a table. The URL table has two columns i.e. primary key(INTEGER) and URL(TEXT).
I try to insert 100,000 entries in one insert command and loop till I finish the URL list. Basically, read all the text files content and save in list and then I use create smaller list of 100,000 entries and insert in table.
Total URLs in the text files are 4,591,415 and total text file size is approx 97.5 MB.
**Problems**:
1. When I chose file database, it takes around **7-7.5 minutes** to insert. I feel this is not a very fast insert given that I have solid state hard-disk which has faster read/write. Along with that I have approximately 10GB RAM available as seen in task manager. Processor is i5-6300U 2.4Ghz.
2. The total text files are approx. 97.5 MB. But after I insert the URLs in the SQLite, the SQLite database is approximately 350MB i.e. almost 3.5 times the original data size. Since the database doesn't contain any other tables, indexes etc. this database size looks little odd.
For problem 1, I tried playing with parameters and came up with as best ones based on test runs with different parameters.
```css
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
text-align: left;
}
```
```html
<table style="width:100%">
<tr>
<th>Configuration</th>
<th>Time</th>
</tr>
<tr><th>50,000 - with journal = delete and no transaction </th><th>0:12:09.888404</th></tr>
<tr><th>50,000 - with journal = delete and with transaction </th><th>0:22:43.613580</th></tr>
<tr><th>50,000 - with journal = memory and transaction </th><th>0:09:01.140017</th></tr>
<tr><th>50,000 - with journal = memory </th><th>0:07:38.820148</th></tr>
<tr><th>50,000 - with journal = memory and synchronous=0 </th><th>0:07:43.587135</th></tr>
<tr><th>50,000 - with journal = memory and synchronous=1 and page_size=65535 </th><th>0:07:19.778217</th></tr>
<tr><th>50,000 - with journal = memory and synchronous=0 and page_size=65535 </th><th>0:07:28.186541</th></tr>
<tr><th>50,000 - with journal = delete and synchronous=1 and page_size=65535 </th><th>0:07:06.539198</th></tr>
<tr><th>50,000 - with journal = delete and synchronous=0 and page_size=65535 </th><th>0:07:19.810333</th></tr>
<tr><th>50,000 - with journal = wal and synchronous=0 and page_size=65535 </th><th>0:08:22.856690</th></tr>
<tr><th>50,000 - with journal = wal and synchronous=1 and page_size=65535 </th><th>0:08:22.326936</th></tr>
<tr><th>50,000 - with journal = delete and synchronous=1 and page_size=4096 </th><th>0:07:35.365883</th></tr>
<tr><th>50,000 - with journal = memory and synchronous=1 and page_size=4096 </th><th>0:07:15.183948</th></tr>
<tr><th>1,00,000 - with journal = delete and synchronous=1 and page_size=65535 </th><th>0:07:13.402985</th></tr>
</table>
```
I was checking online and saw this link <https://adamyork.com/2017/07/02/fast-database-inserts-with-python-3-6-and-sqlite/> where the system is much slower than what I but still performing very well.
Two things, that stood out from this link were:
1. The table in the link had more columns than what I have.
2. The database file didn't grow 3.5 times.
I have shared the python code and the files here: <https://github.com/ksinghgithub/python_sqlite>
Can someone guide me on optimizing this code. Thanks.
Environment:
1. Windows 10 Professional on i5-6300U and 20GB RAM and 512 SSD.
2. Python 3.7.0
***Edit 1:: New performance chart based on the feedback received on UNIQUE constraint and me playing with cache size value.***
```
self.db.execute('CREATE TABLE blacklist (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE)')
```
```css
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
text-align: left;
}
```
```html
<table>
<tr>
<th>Configuration</th>
<th>Action</th>
<th>Time</th>
<th>Notes</th>
</tr>
<tr><th>50,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = 8192</th><th>REMOVE UNIQUE FROM URL</th><th>0:00:18.011823</th><th>Size reduced to 196MB from 350MB</th><th></th></tr>
<tr><th>50,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = default</th><th>REMOVE UNIQUE FROM URL</th><th>0:00:25.692283</th><th>Size reduced to 196MB from 350MB</th><th></th></tr>
<tr><th>100,000 - with journal = delete and synchronous=1 and page_size=65535 </th><th></th><th>0:07:13.402985</th><th></th></tr>
<tr><th>100,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = 4096</th><th></th><th>0:04:47.624909</th><th></th></tr>
<tr><th>100,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = 8192</th><th></th><<th>0:03:32.473927</th><th></th></tr>
<tr><th>100,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = 8192</th><th>REMOVE UNIQUE FROM URL</th><th>0:00:17.927050</th><th>Size reduced to 196MB from 350MB</th><th></th></tr>
<tr><th>100,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = default </th><th>REMOVE UNIQUE FROM URL</th><th>0:00:21.804679</th><th>Size reduced to 196MB from 350MB</th><th></th></tr>
<tr><th>100,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = default </th><th>REMOVE UNIQUE FROM URL & ID</th><th>0:00:14.062386</th><th>Size reduced to 134MB from 350MB</th><th></th></tr>
<tr><th>100,000 - with journal = delete and synchronous=1 and page_size=65535 cache_size = default </th><th>REMOVE UNIQUE FROM URL & DELETE ID</th><th>0:00:11.961004</th><th>Size reduced to 134MB from 350MB</th><th></th></tr>
</table>
```
|
2018/09/21
|
[
"https://Stackoverflow.com/questions/52451119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139406/"
] |
SQLite uses auto-commit mode by default. This permits `begin transaction` be to omitted. But here we want all the inserts to be in a transaction and the only way to do that is to start a transaction with `begin transaction` so that all the statements that are going to be ran are all in that transaction.
The method `executemany` is only a loop over `execute` done outside Python that calls the SQLite prepare statement function only once.
The following is a really bad way to remove the last N items from a list:
```
templist = []
i = 0
while i < self.bulk_insert_entries and len(urls) > 0:
templist.append(urls.pop())
i += 1
```
It is better to do this:
```
templist = urls[-self.bulk_insert_entries:]
del urls[-self.bulk_insert_entries:]
i = len(templist)
```
The slice and del slice work even on an empty list.
Both might have the same complexity but 100K calls to append and pop costs a lot more than letting Python do it outside the interpreter.
|
The UNIQUE constraint on column "url" is creating an implicit index on the URL. That would explain the size increase.
I don't think you can populate the table and afterwards add the unique constraint.
Your bottleneck is surely the CPU. Try the following:
1. Install toolz: `pip install toolz`
2. Use this method:
```
from toolz import partition_all
def add_blacklist_url(self, urls):
# print('add_blacklist_url:: entries = {}'.format(len(urls)))
start_time = datetime.now()
for batch in partition_all(100000, urls):
try:
start_commit = datetime.now()
self.cursor.executemany('''INSERT OR IGNORE INTO blacklist(url) VALUES(:url)''', batch)
end_commit = datetime.now() - start_commit
print('add_blacklist_url:: total time for INSERT OR IGNORE INTO blacklist {} entries = {}'.format(len(templist), end_commit))
except sqlite3.Error as e:
print("add_blacklist_url:: Database error: %s" % e)
except Exception as e:
print("add_blacklist_url:: Exception in _query: %s" % e)
self.db.commit()
time_elapsed = datetime.now() - start_time
print('add_blacklist_url:: total time for {} entries = {}'.format(records, time_elapsed))
```
The code was not tested.
|
26,214,328
|
After long debugging I found why my application using python regexps is slow. Here is something I find surprising:
```
import datetime
import re
pattern = re.compile('(.*)sol(.*)')
lst = ["ciao mandi "*10000 + "sol " + "ciao mandi "*10000,
"ciao mandi "*1000 + "sal " + "ciao mandi "*1000]
for s in lst:
print "string len", len(s)
start = datetime.datetime.now()
re.findall(pattern,s)
print "time spent", datetime.datetime.now() - start
print
```
The output on my machine is:
```
string len 220004
time spent 0:00:00.002844
string len 22004
time spent 0:00:05.339580
```
The first test string is 220K long, matches, and the matching is quite fast. The second test string is 20K long, does not match and it takes 5 seconds to compute!
I knew this report <http://swtch.com/~rsc/regexp/regexp1.html> which says that regexp implementation in python, perl, ruby is somewhat non optimal... Is this the reason? I didn't thought it could happen with such a simple expression.
**added**
My original task is to split a string trying different regex in turn. Something like:
```
for regex in ['(.*)sol(.*)', '\emph{([^{}])*)}(.*)', .... ]:
lst = re.findall(regex, text)
if lst:
assert len(lst) == 1
assert len(lst[0]) == 2
return lst[0]
```
This is to explain why I cannot use `split`. I solved my issue by replacing `(.*)sol(.*)` with `(.*?)sol(.*)` as suggested by Martijn.
Probably I should use `match` instead of `findall`... but I don't think this would have solved the issue since the regexp is going to match the entire input and hence findall should stop at first match.
Anyway my question was more about how easy is to fall in this problem for a regexp newbie... I think it is not so simple to understand that `(.*?)sol(.*)` is the solution (and for example `(.*?)sol(.*?)` is not).
|
2014/10/06
|
[
"https://Stackoverflow.com/questions/26214328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221660/"
] |
The Thompson NFA approach changes regular expressions from default greedy to default non-greedy. Normal regular expression engines can do the same; simply change `.*` to `.*?`. You should not use greedy expressions when non-greedy will do.
Someone already built an NFA regular expression parser for Python: <https://github.com/xysun/regex>
It indeed outperforms the default Python regular expression parser for the pathological cases. *However*, it **under**-performs on *everything else*:
>
> This regex engine underperforms Python's re module on normal inputs (using Glenn Fowler's test suite -- see below)
>
>
>
Fixing the pathological case at the expense of the typical is probably a good reason not to use the NFA approach as a default engine, not when the pathological case can simply be avoided instead.
Another reason is that certain features (such as back references) are either very hard or impossible to implement using the NFA approach. Also see the [response on the Python Ideas mailing list](https://mail.python.org/pipermail/python-ideas/2007-April/000407.html).
As such, your test can be made to perform much better if you made at least one of the patterns non-greedy to avoid the catastrophic backtracking:
```
pattern = re.compile('(.*?)sol(.*)')
```
or don't use a regex at all; you could use `str.partition()` to get the prefix and postfix instead:
```
before, sol, after = s.partition('sol')
```
e.g. not all text problems are regular-expression shaped, so put down that hammer and look at the rest of your toolbox!
In addition, you could perhaps look at the alternative `re` module, [`regex`](https://pypi.python.org/pypi/regex). This module implements some basic checks for pathological cases and avoids them deftly, without having to resort to a Thompson NFA implementation. Quoting [an entry to a Python bug report tracking `regex`](https://bugs.python.org/issue2636#msg90954):
>
> The internal engine no longer interprets a form of bytecode but instead
> follows a linked set of nodes, and it can work breadth-wise as well as
> depth-first, which makes it perform much better when faced with one of
> those 'pathological' regexes.
>
>
>
This engine can run your pathological case more than 100 thousand times faster:
```
>>> import re, regex
>>> import timeit
>>> p_re = re.compile('(.*)sol(.*)')
>>> p_regex = regex.compile('(.*)sol(.*)')
>>> s = "ciao mandi "*1000 + "sal " + "ciao mandi "*1000
>>> timeit.timeit("p.findall(s)", 'from __main__ import s, p_re as p', number=1)
2.4578459990007104
>>> timeit.timeit("p.findall(s)", 'from __main__ import s, p_regex as p', number=100000)
1.955532732012216
```
Note the numbers; I limited the `re` test to 1 run and it took 2.46 seconds, while the `regex` test runs 100k times in under 2 seconds.
|
```
^(?=(.*?sol))\1(.*)$
```
You can try this.This reduces backtracking and fails faster.Try your string here.
<http://regex101.com/r/hQ1rP0/22>
|
26,214,328
|
After long debugging I found why my application using python regexps is slow. Here is something I find surprising:
```
import datetime
import re
pattern = re.compile('(.*)sol(.*)')
lst = ["ciao mandi "*10000 + "sol " + "ciao mandi "*10000,
"ciao mandi "*1000 + "sal " + "ciao mandi "*1000]
for s in lst:
print "string len", len(s)
start = datetime.datetime.now()
re.findall(pattern,s)
print "time spent", datetime.datetime.now() - start
print
```
The output on my machine is:
```
string len 220004
time spent 0:00:00.002844
string len 22004
time spent 0:00:05.339580
```
The first test string is 220K long, matches, and the matching is quite fast. The second test string is 20K long, does not match and it takes 5 seconds to compute!
I knew this report <http://swtch.com/~rsc/regexp/regexp1.html> which says that regexp implementation in python, perl, ruby is somewhat non optimal... Is this the reason? I didn't thought it could happen with such a simple expression.
**added**
My original task is to split a string trying different regex in turn. Something like:
```
for regex in ['(.*)sol(.*)', '\emph{([^{}])*)}(.*)', .... ]:
lst = re.findall(regex, text)
if lst:
assert len(lst) == 1
assert len(lst[0]) == 2
return lst[0]
```
This is to explain why I cannot use `split`. I solved my issue by replacing `(.*)sol(.*)` with `(.*?)sol(.*)` as suggested by Martijn.
Probably I should use `match` instead of `findall`... but I don't think this would have solved the issue since the regexp is going to match the entire input and hence findall should stop at first match.
Anyway my question was more about how easy is to fall in this problem for a regexp newbie... I think it is not so simple to understand that `(.*?)sol(.*)` is the solution (and for example `(.*?)sol(.*?)` is not).
|
2014/10/06
|
[
"https://Stackoverflow.com/questions/26214328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221660/"
] |
I think this has nothing to do with catastrophic backtracking (or at least my own understanding of it).
The problem is caused by the first `(.*)` in `(.*)sol(.*)`, and the fact that the regex is not anchored anywhere.
`re.findall()`, after failing at index 0, would retry at index 1, 2, etc. until the end of the string.
```
badbadbadbad...bad
^ Attempt to match (.*)sol(.*) from index 0. Fail
^ Attempt to match (.*)sol(.*) from index 1. Fail
^ Attempt to match (.*)sol(.*) from index 2. Fail (and so on)
```
It effectively has quadratic complexity O(n2) where n is the length of the string.
The problem can be resolved by anchoring your pattern, so it fails right away at positions that your pattern has no chance to match. `(.*)sol(.*)` will search for `sol` within a line of text (delimited by line terminator), so if it can't find a match at the start of the line, it won't find any for the rest of the line.
Therefore, you can use:
```
^(.*)sol(.*)
```
with [`re.MULTILINE`](https://docs.python.org/2/library/re.html#re.MULTILINE) option.
Running this test code (modified from yours):
```
import datetime
import re
pattern = re.compile('^(.*)sol(.*)', re.MULTILINE)
lst = ["ciao mandi "*10000 + "sol " + "ciao mandi "*10000,
"ciao mandi "*10000 + "sal " + "ciao mandi "*10000]
for s in lst:
print "string len", len(s)
start = datetime.datetime.now()
re.findall(pattern,s)
print "time spent", datetime.datetime.now() - start
print
```
(Note that both passing and failing are 220004 characters)
Gives the following result:
```
string len 220004
time spent 0:00:00.002000
string len 220004
time spent 0:00:00.005000
```
This demonstrates clearly that both cases now have the same order of magnitude.
|
```
^(?=(.*?sol))\1(.*)$
```
You can try this.This reduces backtracking and fails faster.Try your string here.
<http://regex101.com/r/hQ1rP0/22>
|
26,214,328
|
After long debugging I found why my application using python regexps is slow. Here is something I find surprising:
```
import datetime
import re
pattern = re.compile('(.*)sol(.*)')
lst = ["ciao mandi "*10000 + "sol " + "ciao mandi "*10000,
"ciao mandi "*1000 + "sal " + "ciao mandi "*1000]
for s in lst:
print "string len", len(s)
start = datetime.datetime.now()
re.findall(pattern,s)
print "time spent", datetime.datetime.now() - start
print
```
The output on my machine is:
```
string len 220004
time spent 0:00:00.002844
string len 22004
time spent 0:00:05.339580
```
The first test string is 220K long, matches, and the matching is quite fast. The second test string is 20K long, does not match and it takes 5 seconds to compute!
I knew this report <http://swtch.com/~rsc/regexp/regexp1.html> which says that regexp implementation in python, perl, ruby is somewhat non optimal... Is this the reason? I didn't thought it could happen with such a simple expression.
**added**
My original task is to split a string trying different regex in turn. Something like:
```
for regex in ['(.*)sol(.*)', '\emph{([^{}])*)}(.*)', .... ]:
lst = re.findall(regex, text)
if lst:
assert len(lst) == 1
assert len(lst[0]) == 2
return lst[0]
```
This is to explain why I cannot use `split`. I solved my issue by replacing `(.*)sol(.*)` with `(.*?)sol(.*)` as suggested by Martijn.
Probably I should use `match` instead of `findall`... but I don't think this would have solved the issue since the regexp is going to match the entire input and hence findall should stop at first match.
Anyway my question was more about how easy is to fall in this problem for a regexp newbie... I think it is not so simple to understand that `(.*?)sol(.*)` is the solution (and for example `(.*?)sol(.*?)` is not).
|
2014/10/06
|
[
"https://Stackoverflow.com/questions/26214328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221660/"
] |
The Thompson NFA approach changes regular expressions from default greedy to default non-greedy. Normal regular expression engines can do the same; simply change `.*` to `.*?`. You should not use greedy expressions when non-greedy will do.
Someone already built an NFA regular expression parser for Python: <https://github.com/xysun/regex>
It indeed outperforms the default Python regular expression parser for the pathological cases. *However*, it **under**-performs on *everything else*:
>
> This regex engine underperforms Python's re module on normal inputs (using Glenn Fowler's test suite -- see below)
>
>
>
Fixing the pathological case at the expense of the typical is probably a good reason not to use the NFA approach as a default engine, not when the pathological case can simply be avoided instead.
Another reason is that certain features (such as back references) are either very hard or impossible to implement using the NFA approach. Also see the [response on the Python Ideas mailing list](https://mail.python.org/pipermail/python-ideas/2007-April/000407.html).
As such, your test can be made to perform much better if you made at least one of the patterns non-greedy to avoid the catastrophic backtracking:
```
pattern = re.compile('(.*?)sol(.*)')
```
or don't use a regex at all; you could use `str.partition()` to get the prefix and postfix instead:
```
before, sol, after = s.partition('sol')
```
e.g. not all text problems are regular-expression shaped, so put down that hammer and look at the rest of your toolbox!
In addition, you could perhaps look at the alternative `re` module, [`regex`](https://pypi.python.org/pypi/regex). This module implements some basic checks for pathological cases and avoids them deftly, without having to resort to a Thompson NFA implementation. Quoting [an entry to a Python bug report tracking `regex`](https://bugs.python.org/issue2636#msg90954):
>
> The internal engine no longer interprets a form of bytecode but instead
> follows a linked set of nodes, and it can work breadth-wise as well as
> depth-first, which makes it perform much better when faced with one of
> those 'pathological' regexes.
>
>
>
This engine can run your pathological case more than 100 thousand times faster:
```
>>> import re, regex
>>> import timeit
>>> p_re = re.compile('(.*)sol(.*)')
>>> p_regex = regex.compile('(.*)sol(.*)')
>>> s = "ciao mandi "*1000 + "sal " + "ciao mandi "*1000
>>> timeit.timeit("p.findall(s)", 'from __main__ import s, p_re as p', number=1)
2.4578459990007104
>>> timeit.timeit("p.findall(s)", 'from __main__ import s, p_regex as p', number=100000)
1.955532732012216
```
Note the numbers; I limited the `re` test to 1 run and it took 2.46 seconds, while the `regex` test runs 100k times in under 2 seconds.
|
I think this has nothing to do with catastrophic backtracking (or at least my own understanding of it).
The problem is caused by the first `(.*)` in `(.*)sol(.*)`, and the fact that the regex is not anchored anywhere.
`re.findall()`, after failing at index 0, would retry at index 1, 2, etc. until the end of the string.
```
badbadbadbad...bad
^ Attempt to match (.*)sol(.*) from index 0. Fail
^ Attempt to match (.*)sol(.*) from index 1. Fail
^ Attempt to match (.*)sol(.*) from index 2. Fail (and so on)
```
It effectively has quadratic complexity O(n2) where n is the length of the string.
The problem can be resolved by anchoring your pattern, so it fails right away at positions that your pattern has no chance to match. `(.*)sol(.*)` will search for `sol` within a line of text (delimited by line terminator), so if it can't find a match at the start of the line, it won't find any for the rest of the line.
Therefore, you can use:
```
^(.*)sol(.*)
```
with [`re.MULTILINE`](https://docs.python.org/2/library/re.html#re.MULTILINE) option.
Running this test code (modified from yours):
```
import datetime
import re
pattern = re.compile('^(.*)sol(.*)', re.MULTILINE)
lst = ["ciao mandi "*10000 + "sol " + "ciao mandi "*10000,
"ciao mandi "*10000 + "sal " + "ciao mandi "*10000]
for s in lst:
print "string len", len(s)
start = datetime.datetime.now()
re.findall(pattern,s)
print "time spent", datetime.datetime.now() - start
print
```
(Note that both passing and failing are 220004 characters)
Gives the following result:
```
string len 220004
time spent 0:00:00.002000
string len 220004
time spent 0:00:00.005000
```
This demonstrates clearly that both cases now have the same order of magnitude.
|
48,568,283
|
Here's an example to find the greatest common divisor for positive integers `a` and `b`, and `a <= b`. I started from the smaller `a` and minus one by one to check if it's the divisor of both numbers.
```
def gcdFinder(a, b):
testerNum = a
def tester(a, b):
if b % testerNum == 0 and a % testerNum == 0:
return testerNum
else:
testerNum -= 1
tester(a, b)
return tester(a, b)
print(gcdFinder(9, 15))
```
Then, I got error message,
`UnboundLocalError: local variable 'testerNum' referenced before assignment`.
After using `global testerNum`, it successfully showed the answer `3` in Spyder console...
[](https://i.stack.imgur.com/aJAcD.png)
but in pythontutor.com, it said `NameError: name 'testerNum' is not defined` ([link](http://pythontutor.com/visualize.html#code=def%20gcdFinder%28a,%20b%29%3A%0A%0A%20%20%20%20testerNum%20%3D%20a%20%20%20%0A%0A%20%20%20%20def%20tester%28a,%20b%29%3A%0A%20%20%20%20%20%20%20%20global%20testerNum%0A%20%20%20%20%20%20%20%20if%20b%20%25%20testerNum%20%3D%3D%200%20and%20a%20%25%20testerNum%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20testerNum%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20testerNum%20-%3D%201%0A%20%20%20%20%20%20%20%20%20%20%20%20tester%28a,%20b%29%0A%0A%20%20%20%20return%20tester%28a,%20b%29%0A%0Aprint%28gcdFinder%289,%2015%29%29&cumulative=false&curInstr=8&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)).
[](https://i.stack.imgur.com/6SFHd.png)
~~**Q1:** In Spyder, I think that the `global testerNum` is a problem since `testerNum = a` is not in global scope. It's inside the scope of function `gcdFinder`. Is this description correct? If so, how did Spyder show the answer?~~
**Q2:** In pythontutor, say the last screenshot, how to solve the NameError problem in pythontutor?
~~**Q3:** Why there's difference between the results of Spyder and pythontutor, and which is correct?~~
**Q4:** Is it better not to use `global` method?
--
UPDATE: The Spyder issue was due to the value stored from previous run, so it's defined as `9` already. And this made the `global testerNum` work. I've deleted the Q1 & Q3.
|
2018/02/01
|
[
"https://Stackoverflow.com/questions/48568283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4860812/"
] |
Answers to **Q2** and **Q4**.
As I wrote in the comments, you can parse the testerNum as parameter.
Your code would then look like this:
```
def gcdFinder(a, b):
testerNum = a
def tester(a, b, testerNum):
if b % testerNum == 0 and a % testerNum == 0:
return testerNum
else:
testerNum -= 1
return tester(a, b, testerNum) # you have to return this in order for the code to work
return tester(a, b, testerNum)
print(gcdFinder(9, 15))
```
edit: (see coment)
|
TO hit only question 4, yes, it's better not to use `global` at all. `global` generally highlights poor code design.
You're going to a lot of trouble; I strongly recommend that you look up standard methods of calculating the GCD, and implement Euclid's Algorithm instead. Coding details left as an exercise for the student.
|
48,568,283
|
Here's an example to find the greatest common divisor for positive integers `a` and `b`, and `a <= b`. I started from the smaller `a` and minus one by one to check if it's the divisor of both numbers.
```
def gcdFinder(a, b):
testerNum = a
def tester(a, b):
if b % testerNum == 0 and a % testerNum == 0:
return testerNum
else:
testerNum -= 1
tester(a, b)
return tester(a, b)
print(gcdFinder(9, 15))
```
Then, I got error message,
`UnboundLocalError: local variable 'testerNum' referenced before assignment`.
After using `global testerNum`, it successfully showed the answer `3` in Spyder console...
[](https://i.stack.imgur.com/aJAcD.png)
but in pythontutor.com, it said `NameError: name 'testerNum' is not defined` ([link](http://pythontutor.com/visualize.html#code=def%20gcdFinder%28a,%20b%29%3A%0A%0A%20%20%20%20testerNum%20%3D%20a%20%20%20%0A%0A%20%20%20%20def%20tester%28a,%20b%29%3A%0A%20%20%20%20%20%20%20%20global%20testerNum%0A%20%20%20%20%20%20%20%20if%20b%20%25%20testerNum%20%3D%3D%200%20and%20a%20%25%20testerNum%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20testerNum%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20testerNum%20-%3D%201%0A%20%20%20%20%20%20%20%20%20%20%20%20tester%28a,%20b%29%0A%0A%20%20%20%20return%20tester%28a,%20b%29%0A%0Aprint%28gcdFinder%289,%2015%29%29&cumulative=false&curInstr=8&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)).
[](https://i.stack.imgur.com/6SFHd.png)
~~**Q1:** In Spyder, I think that the `global testerNum` is a problem since `testerNum = a` is not in global scope. It's inside the scope of function `gcdFinder`. Is this description correct? If so, how did Spyder show the answer?~~
**Q2:** In pythontutor, say the last screenshot, how to solve the NameError problem in pythontutor?
~~**Q3:** Why there's difference between the results of Spyder and pythontutor, and which is correct?~~
**Q4:** Is it better not to use `global` method?
--
UPDATE: The Spyder issue was due to the value stored from previous run, so it's defined as `9` already. And this made the `global testerNum` work. I've deleted the Q1 & Q3.
|
2018/02/01
|
[
"https://Stackoverflow.com/questions/48568283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4860812/"
] |
**The Problem:**
When trying to resolve a variable reference, Python first checks in the local scope and then in the local scope of any enclosing functions. For example this code:
```
def foo():
x=23
def bar():
return x +1
return bar
print(foo()())
```
Will run and print out `24` because when `x` is referenced inside of `bar`, since there is no `x` in the local scope it finds it in the scope of the enclosing function (`foo`). However, as soon as you try to assign to a variable, Python assumes it is defined in the local scope. So this:
```
def foo():
x=23
def bar():
x = x + 1
return x
return bar
print(foo()())
```
Will throw an `UnboundLocalError` because I am trying to assign to `x` which means it is going to be looked up in the local scope, but the value I'm trying to assign to it is based on the `x` from the enclosing scope. Since the assignment limits the search for `x` to the local scope, it can't be found and I get the error.
So your error is coming up because of the `testerNum -= 1` line in your else clause, it is limiting the search for `testerNum` to the local scope where it doesn't exist.
**The Fix:**
The `global` declaration isn't right since, as you noted, `testerNum` isn't defined in the global scope. I'm not familiar with Spyder and don't know why it worked there but it seems like it somehow got a `testerNum` variable in its global scope.
If you're using Python3 you can get around this by changing your `global testerNum` line to `nonlocal testerNum` which just tells Python that, despite being assigned to, testerNum isn't defined in the local scope and to keep searching outwards.
```
def foo():
x=23
def bar():
nonlocal x
x = x + 1
return x
return bar
>>> print(foo()())
24
```
Another option that would work in Python 2 or 3 is to pass around `testerNum` as Brambor outlined in their answer.
|
Answers to **Q2** and **Q4**.
As I wrote in the comments, you can parse the testerNum as parameter.
Your code would then look like this:
```
def gcdFinder(a, b):
testerNum = a
def tester(a, b, testerNum):
if b % testerNum == 0 and a % testerNum == 0:
return testerNum
else:
testerNum -= 1
return tester(a, b, testerNum) # you have to return this in order for the code to work
return tester(a, b, testerNum)
print(gcdFinder(9, 15))
```
edit: (see coment)
|
48,568,283
|
Here's an example to find the greatest common divisor for positive integers `a` and `b`, and `a <= b`. I started from the smaller `a` and minus one by one to check if it's the divisor of both numbers.
```
def gcdFinder(a, b):
testerNum = a
def tester(a, b):
if b % testerNum == 0 and a % testerNum == 0:
return testerNum
else:
testerNum -= 1
tester(a, b)
return tester(a, b)
print(gcdFinder(9, 15))
```
Then, I got error message,
`UnboundLocalError: local variable 'testerNum' referenced before assignment`.
After using `global testerNum`, it successfully showed the answer `3` in Spyder console...
[](https://i.stack.imgur.com/aJAcD.png)
but in pythontutor.com, it said `NameError: name 'testerNum' is not defined` ([link](http://pythontutor.com/visualize.html#code=def%20gcdFinder%28a,%20b%29%3A%0A%0A%20%20%20%20testerNum%20%3D%20a%20%20%20%0A%0A%20%20%20%20def%20tester%28a,%20b%29%3A%0A%20%20%20%20%20%20%20%20global%20testerNum%0A%20%20%20%20%20%20%20%20if%20b%20%25%20testerNum%20%3D%3D%200%20and%20a%20%25%20testerNum%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20testerNum%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20testerNum%20-%3D%201%0A%20%20%20%20%20%20%20%20%20%20%20%20tester%28a,%20b%29%0A%0A%20%20%20%20return%20tester%28a,%20b%29%0A%0Aprint%28gcdFinder%289,%2015%29%29&cumulative=false&curInstr=8&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)).
[](https://i.stack.imgur.com/6SFHd.png)
~~**Q1:** In Spyder, I think that the `global testerNum` is a problem since `testerNum = a` is not in global scope. It's inside the scope of function `gcdFinder`. Is this description correct? If so, how did Spyder show the answer?~~
**Q2:** In pythontutor, say the last screenshot, how to solve the NameError problem in pythontutor?
~~**Q3:** Why there's difference between the results of Spyder and pythontutor, and which is correct?~~
**Q4:** Is it better not to use `global` method?
--
UPDATE: The Spyder issue was due to the value stored from previous run, so it's defined as `9` already. And this made the `global testerNum` work. I've deleted the Q1 & Q3.
|
2018/02/01
|
[
"https://Stackoverflow.com/questions/48568283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4860812/"
] |
**The Problem:**
When trying to resolve a variable reference, Python first checks in the local scope and then in the local scope of any enclosing functions. For example this code:
```
def foo():
x=23
def bar():
return x +1
return bar
print(foo()())
```
Will run and print out `24` because when `x` is referenced inside of `bar`, since there is no `x` in the local scope it finds it in the scope of the enclosing function (`foo`). However, as soon as you try to assign to a variable, Python assumes it is defined in the local scope. So this:
```
def foo():
x=23
def bar():
x = x + 1
return x
return bar
print(foo()())
```
Will throw an `UnboundLocalError` because I am trying to assign to `x` which means it is going to be looked up in the local scope, but the value I'm trying to assign to it is based on the `x` from the enclosing scope. Since the assignment limits the search for `x` to the local scope, it can't be found and I get the error.
So your error is coming up because of the `testerNum -= 1` line in your else clause, it is limiting the search for `testerNum` to the local scope where it doesn't exist.
**The Fix:**
The `global` declaration isn't right since, as you noted, `testerNum` isn't defined in the global scope. I'm not familiar with Spyder and don't know why it worked there but it seems like it somehow got a `testerNum` variable in its global scope.
If you're using Python3 you can get around this by changing your `global testerNum` line to `nonlocal testerNum` which just tells Python that, despite being assigned to, testerNum isn't defined in the local scope and to keep searching outwards.
```
def foo():
x=23
def bar():
nonlocal x
x = x + 1
return x
return bar
>>> print(foo()())
24
```
Another option that would work in Python 2 or 3 is to pass around `testerNum` as Brambor outlined in their answer.
|
TO hit only question 4, yes, it's better not to use `global` at all. `global` generally highlights poor code design.
You're going to a lot of trouble; I strongly recommend that you look up standard methods of calculating the GCD, and implement Euclid's Algorithm instead. Coding details left as an exercise for the student.
|
70,643,142
|
Say I have this array:
```python
array = np.array([[1,2,3],[4,5,6],[7,8,9]])
```
Returns:
```none
123
456
789
```
How should I go about getting it to return something like this?
```none
111222333
111222333
111222333
444555666
444555666
444555666
777888999
777888999
777888999
```
|
2022/01/09
|
[
"https://Stackoverflow.com/questions/70643142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16809168/"
] |
You'd have to use [`np.repeat`](https://numpy.org/doc/stable/reference/generated/numpy.repeat.html#numpy-repeat) twice here.
```
np.repeat(np.repeat(array, 3, axis=1), 3, axis=0)
# [[1 1 1 2 2 2 3 3 3]
# [1 1 1 2 2 2 3 3 3]
# [1 1 1 2 2 2 3 3 3]
# [4 4 4 5 5 5 6 6 6]
# [4 4 4 5 5 5 6 6 6]
# [4 4 4 5 5 5 6 6 6]
# [7 7 7 8 8 8 9 9 9]
# [7 7 7 8 8 8 9 9 9]
# [7 7 7 8 8 8 9 9 9]]
```
|
For fun (because the nested `repeat` will be more efficient), you could use `einsum` on the input array and an array of `ones` that has extra dimensions to create a multidimensional array with the dimensions in an ideal order to `reshape` to the expected 2D shape:
```
np.einsum('ij,ikjl->ikjl', array, np.ones((3,3,3,3))).reshape(9,9)
```
The generic method being:
```
i,j = array.shape
k = 3 # extra rows
l = 3 # extra cols
np.einsum('ij,ikjl->ikjl', a, np.ones((i,k,j,l))).reshape(i*k,j*l)
```
Output:
```
array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
[1, 1, 1, 2, 2, 2, 3, 3, 3],
[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6],
[4, 4, 4, 5, 5, 5, 6, 6, 6],
[4, 4, 4, 5, 5, 5, 6, 6, 6],
[7, 7, 7, 8, 8, 8, 9, 9, 9],
[7, 7, 7, 8, 8, 8, 9, 9, 9],
[7, 7, 7, 8, 8, 8, 9, 9, 9]])
```
What is however nice with this method, is that it's quite easy to change the order to obtain other patterns or work with higher dimensions.
Example with other patterns:
```
>>> np.einsum('ij,iklj->iklj', a, np.ones((3,3,3,3))).reshape(9,9)
array([[1, 2, 3, 1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3, 1, 2, 3],
[1, 2, 3, 1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6, 4, 5, 6],
[4, 5, 6, 4, 5, 6, 4, 5, 6],
[4, 5, 6, 4, 5, 6, 4, 5, 6],
[7, 8, 9, 7, 8, 9, 7, 8, 9],
[7, 8, 9, 7, 8, 9, 7, 8, 9],
[7, 8, 9, 7, 8, 9, 7, 8, 9]])
>>> np.einsum('ij,kjil->kjil', a, np.ones((3,3,3,3))).reshape(9,9)
array([[1, 1, 1, 4, 4, 4, 7, 7, 7],
[2, 2, 2, 5, 5, 5, 8, 8, 8],
[3, 3, 3, 6, 6, 6, 9, 9, 9],
[1, 1, 1, 4, 4, 4, 7, 7, 7],
[2, 2, 2, 5, 5, 5, 8, 8, 8],
[3, 3, 3, 6, 6, 6, 9, 9, 9],
[1, 1, 1, 4, 4, 4, 7, 7, 7],
[2, 2, 2, 5, 5, 5, 8, 8, 8],
[3, 3, 3, 6, 6, 6, 9, 9, 9]])
```
|
53,080,894
|
I am trying to make a GUI where the quantity of tkinter entries is decided by the user.
My Code:
```
from tkinter import*
root = Tk()
def createEntries(quantity):
for num in range(quantity):
usrInput = Entry(root, text = num)
usrInput.pack()
createEntries(10)
root.mainloop()
```
This code is based on [this tutorial](http://usingpython.com/dynamically-creating-widgets/) i found:
```
for num in range(10):
btn = tkinter.button(window, text=num)
btn.pack(side=tkinter.LEFT)
```
The problem is that I can only access the input in the latest created widget, because they all have the same name. Is there a way of dynamically creating widgets with unique names?
Any advice would be greatly appreciated
|
2018/10/31
|
[
"https://Stackoverflow.com/questions/53080894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585009/"
] |
The solution is to store the widgets in a data structure such as a list or dictionary. For example:
```
entries = []
for num in range(quantity):
usrInput = Entry(root, text = num)
usrInput.pack()
entries.append(usrInput)
```
Later, you can iterate over this list to get the values:
```
for entry in entries:
value = entry.get()
print("value: {}".format(value))
```
And, of course, you can access specific entries by number:
```
print("first item: {}".format(entries[0].get()))
```
|
With the following Code you can adjust the number of Buttons and Entrys depending on the Var "fields". I hope it helps
```
from tkinter import *
fields = 'Last Name', 'First Name', 'Job', 'Country'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(root, fields):
entries = []
for field in fields:
row = Frame(root)
lab = Label(row, width=15, text=field, anchor='w')
ent = Entry(row)
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries.append((field, ent))
return entries
if __name__ == '__main__':
root = Tk()
ents = makeform(root, fields)
root.bind('<Return>', (lambda event, e=ents: fetch(e)))
b1 = Button(root, text='Show',
command=(lambda e=ents: fetch(e)))
b1.pack(side=LEFT, padx=5, pady=5)
b2 = Button(root, text='Quit', command=root.quit)
b2.pack(side=LEFT, padx=5, pady=5)
root.mainloop()
```
|
67,878,084
|
I'm trying to teach myself python and I am stuck in the for/while loops. Now I know the difference between the two but once nested loops get involved, i'm left feeling all over the place in terms of determining the hierarchy of the loops. Is there a way that I can get better at this? and how do I troubleshoot my loops once it gives me back an infinite loop? :(
for example: this code I was writing, to count the number of specific colored cars on each level of a garage.
```
level=1
red=0
blue=0
black=0
white=0
total=0
done=0
totalperlevel=0
sumofcars=0
currentlevel=0
cars=0
while level < 6:
cars=input(f"Enter the colour of a car on level {level}:").lower()
level+=1
while cars != done:
if cars == red:
totalperlevel=totalperlevel+1
red=red+1
elif cars == blue:
blue=blue+1
totalperlevel=totalperlevel+1
elif cars == white:
totalperlevel=totalperlevel+1
white=whitecar+1
elif cars == black:
black=black+1
totalperlevel=totalperlevel+1
else:
totalperlevel=totalperlevel
sumofcars= red+blue+white+black
cars=input(f"Enter the colour of a car on level {level}:").lower()
print(f"Total number of the 4-colours cars on Level {level} is {totalperlevel}")
print(f"Total number of red cars in the garage: {red}")
print(f"Total number of blue cars in the garage: {blue}")
print(f"Total number of black cars in the garage: {black}")
print(f"Total number of white cars in the garage: {white}")
print(f"Total number of the 4-colours cars altogether: {sumofcars}")
```
|
2021/06/07
|
[
"https://Stackoverflow.com/questions/67878084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16078295/"
] |
If you want it to be a `dm` command we can use the restriction `@commands.dm_only()`
However we then also have to check where the `answer` was given, we do that via some kind of custom `check`. I have modified your command a bit, but you can make the changes again personally.
**Take a look at the following code:**
```py
@commands.dm_only() # Make it a DM-only command
@commands.command()
async def verify(self, ctx, length=10):
def check(m):
return ctx.author == m.author and isinstance(m.channel, discord.DMChannel)
verify_characters = []
for _ in range(length):
verify_characters.append(random.choice(string.ascii_letters + string.digits + "!§$%&/()=?`-.<>"))
verify_msg = "".join(verify_characters)
print(verify_msg)
await ctx.author.send(f"Verify with the number: {verify_msg}")
try: # Try to get the answer
answer = await bot.wait_for("message", check=check)
print(answer.content)
if verify_msg == answer.content:
await ctx.author.send("Verified!")
else:
await ctx.author.send("Verify again!")
except: # Used if you for example want to set a timelimit
pass
```
|
Edited to show full answer.
Hey ho done it lol.
Basically the message object contains a lot of data, so you need to pull the content of the message using answer.conent.
<https://discordpy.readthedocs.io/en/latest/api.html?highlight=message#discord.Message.content> for reference
```
@bot.command()
async def verify(ctx):
length=10
verify_characters = []
for _ in range(length):
verify_characters.append(random.choice(string.ascii_letters + string.digits + "!§$%&/()=?`-.<>"))
verify_msg = "".join(verify_characters)
print(verify_msg)
await ctx.author.send(f"Verify with the number {verify_msg}")
answer = await bot.wait_for('message')
print(answer.content)
print("done")
if verify_msg == answer.content:
await ctx.author.send("Verified")
else:
await ctx.author.send(f"Verify again!")
```
Give that a test run and let me know what happens ;)
|
1,205,449
|
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types
i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out
if someone could provide examples in python that would be a big help
|
2009/07/30
|
[
"https://Stackoverflow.com/questions/1205449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147602/"
] |
You have to encode your input and your output to something that can be represented by the neural network units. ( for example 1 for "x has a certain property p" -1 for "x doesn't have the property p" if your units' range is in [-1, 1])
The way you encode your input and the way you decode your output depends on what you want to train the neural network for.
Moreover, there are many "neural networks" algoritms and learning rules for different tasks( Back propagation, boltzman machines, self organizing maps).
|
More complex data usually means adding more neurons in the input and output layers.
You can feed each "field" of your register, properly encoded as a real value (normalized, etc.) to each input neuron, or maybe you can even decompose even further into bit fields, assigning saturated inputs of 1 or 0 to the neurons... for the output, it depends on how you train the neural network, it will try to mimic the training set outputs.
|
1,205,449
|
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types
i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out
if someone could provide examples in python that would be a big help
|
2009/07/30
|
[
"https://Stackoverflow.com/questions/1205449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147602/"
] |
You have to encode your input and your output to something that can be represented by the neural network units. ( for example 1 for "x has a certain property p" -1 for "x doesn't have the property p" if your units' range is in [-1, 1])
The way you encode your input and the way you decode your output depends on what you want to train the neural network for.
Moreover, there are many "neural networks" algoritms and learning rules for different tasks( Back propagation, boltzman machines, self organizing maps).
|
Your features must be decomposed into parts that can be represented as real numbers. The magic of a Neural Net is it's a black box, the correct associations will be made (with internal weights) during the training
---
**Inputs**
Choose as few features as are needed to accurately describe the situation, then decompose each into a set of real valued numbers.
* Weather: [temp today, humidity today, temp yesterday, humidity yesterday...] *the association between today's temp and today's humidity is made internally*
* Team stats: [ave height, ave weight, max height, top score,...]
* Dice: *not sure I understand this one, do you mean how to encode discrete values?\**
* Complex number: [a,*ai*,b,*bi*,...]
\* Discrete valued features are tricky, but can still still be encoded as (0.0,1.0). The problem is they don't provide a gradient to learn the threshold on.
---
**Outputs**
You decide what you want the output to mean, and then encode your training examples in that format. The fewer output values, the easier to train.
* Weather: [tomorrow's chance of rain, tomorrow's temp,...] \*\*
* Team stats: [chance of winning, chance of winning by more than 20,...]
* Complex number: [x,*xi*,...]
\*\* Here your *training* vectors would be: 1.0 if it rained the next day, 0.0 if it didn't
---
Of course, whether or not the problem can actually be modeled by a neural net is a different question.
|
1,205,449
|
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types
i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out
if someone could provide examples in python that would be a big help
|
2009/07/30
|
[
"https://Stackoverflow.com/questions/1205449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147602/"
] |
You have to encode your input and your output to something that can be represented by the neural network units. ( for example 1 for "x has a certain property p" -1 for "x doesn't have the property p" if your units' range is in [-1, 1])
The way you encode your input and the way you decode your output depends on what you want to train the neural network for.
Moreover, there are many "neural networks" algoritms and learning rules for different tasks( Back propagation, boltzman machines, self organizing maps).
|
You have to add the number of units for input and output you need for the problem. If the unknown function to approximate depends on *n* parameter, you will have n input units. The number of output units depends on the nature of the funcion. For real functions with n real parameters you will have one output unit.
Some problems, for example in forecasting of time series, you will have m output units for the m succesive values of the function. The encoding is important and depends on the choosen algorithm. For example, in backpropagation for feedforward nets, is better to transform, if possible, the greater number of features in discrete inputs, as for classification tasks.
Other aspect of the encoding is that you have to evaluate the number of input and hidden units in function of the amount of data. Too many units related to data may give poor approximation due the course ff dimensionality problem. In some cases, you may to aggregate some of the input data in some way to avoid that problem or use some reduction mechanism as PCA.
|
1,205,449
|
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types
i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out
if someone could provide examples in python that would be a big help
|
2009/07/30
|
[
"https://Stackoverflow.com/questions/1205449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147602/"
] |
Your features must be decomposed into parts that can be represented as real numbers. The magic of a Neural Net is it's a black box, the correct associations will be made (with internal weights) during the training
---
**Inputs**
Choose as few features as are needed to accurately describe the situation, then decompose each into a set of real valued numbers.
* Weather: [temp today, humidity today, temp yesterday, humidity yesterday...] *the association between today's temp and today's humidity is made internally*
* Team stats: [ave height, ave weight, max height, top score,...]
* Dice: *not sure I understand this one, do you mean how to encode discrete values?\**
* Complex number: [a,*ai*,b,*bi*,...]
\* Discrete valued features are tricky, but can still still be encoded as (0.0,1.0). The problem is they don't provide a gradient to learn the threshold on.
---
**Outputs**
You decide what you want the output to mean, and then encode your training examples in that format. The fewer output values, the easier to train.
* Weather: [tomorrow's chance of rain, tomorrow's temp,...] \*\*
* Team stats: [chance of winning, chance of winning by more than 20,...]
* Complex number: [x,*xi*,...]
\*\* Here your *training* vectors would be: 1.0 if it rained the next day, 0.0 if it didn't
---
Of course, whether or not the problem can actually be modeled by a neural net is a different question.
|
More complex data usually means adding more neurons in the input and output layers.
You can feed each "field" of your register, properly encoded as a real value (normalized, etc.) to each input neuron, or maybe you can even decompose even further into bit fields, assigning saturated inputs of 1 or 0 to the neurons... for the output, it depends on how you train the neural network, it will try to mimic the training set outputs.
|
1,205,449
|
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types
i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out
if someone could provide examples in python that would be a big help
|
2009/07/30
|
[
"https://Stackoverflow.com/questions/1205449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147602/"
] |
Your features must be decomposed into parts that can be represented as real numbers. The magic of a Neural Net is it's a black box, the correct associations will be made (with internal weights) during the training
---
**Inputs**
Choose as few features as are needed to accurately describe the situation, then decompose each into a set of real valued numbers.
* Weather: [temp today, humidity today, temp yesterday, humidity yesterday...] *the association between today's temp and today's humidity is made internally*
* Team stats: [ave height, ave weight, max height, top score,...]
* Dice: *not sure I understand this one, do you mean how to encode discrete values?\**
* Complex number: [a,*ai*,b,*bi*,...]
\* Discrete valued features are tricky, but can still still be encoded as (0.0,1.0). The problem is they don't provide a gradient to learn the threshold on.
---
**Outputs**
You decide what you want the output to mean, and then encode your training examples in that format. The fewer output values, the easier to train.
* Weather: [tomorrow's chance of rain, tomorrow's temp,...] \*\*
* Team stats: [chance of winning, chance of winning by more than 20,...]
* Complex number: [x,*xi*,...]
\*\* Here your *training* vectors would be: 1.0 if it rained the next day, 0.0 if it didn't
---
Of course, whether or not the problem can actually be modeled by a neural net is a different question.
|
You have to add the number of units for input and output you need for the problem. If the unknown function to approximate depends on *n* parameter, you will have n input units. The number of output units depends on the nature of the funcion. For real functions with n real parameters you will have one output unit.
Some problems, for example in forecasting of time series, you will have m output units for the m succesive values of the function. The encoding is important and depends on the choosen algorithm. For example, in backpropagation for feedforward nets, is better to transform, if possible, the greater number of features in discrete inputs, as for classification tasks.
Other aspect of the encoding is that you have to evaluate the number of input and hidden units in function of the amount of data. Too many units related to data may give poor approximation due the course ff dimensionality problem. In some cases, you may to aggregate some of the input data in some way to avoid that problem or use some reduction mechanism as PCA.
|
2,120,332
|
I think this is more a python question than Django.
But basically I'm doing at Model A:
```
from myproject.modelb.models import ModelB
```
and at Model B:
```
from myproject.modela.models import ModelA
```
Result:
>
> cannot import name ModelA
>
>
>
Am I doing something forbidden? Thanks
|
2010/01/22
|
[
"https://Stackoverflow.com/questions/2120332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234167/"
] |
A Python module is imported by executing it top to bottom in a new namespace. When module A imports module B, the evaluation of A.py is paused until module B is loaded. When module B then imports module A, it gets the partly-initialized namespace of module A -- in your case, it lacks the `ModelA` class because the import of `myproject.modelb.models` happens before the definition of that class.
In Django you can fix this by referring to a model by name instead of by class object. So, instead of saying
```
from myproject.modela.models import ModelA
class ModelB:
a = models.ForeignKey(ModelA)
```
you would use (without the import):
```
class ModelB:
a = models.ForeignKey('ModelA')
```
|
Mutual imports usually mean you've designed your models incorrectly.
When A depends on B, you should not have B also depending on A.
Break B into two parts.
B1 - depends on A.
B2 - does not depend on A.
A depends on B1. B1 depends on B2. Circularity removed.
|
5,425,725
|
I have created an objective-C framework that I would like to import and access through a python script. I understand how to import this stuff in Python, but what do i need to do on the obj-c side to make that framework importable?
Thanks
|
2011/03/24
|
[
"https://Stackoverflow.com/questions/5425725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202431/"
] |
You can just use [PyObjC](http://pyobjc.sourceforge.net/), which is included in Mac OS X 10.5 and later.
|
I'm not sure if this particular combination works, but you might be able to use [SWIG](http://swig.org/) to create a Python module out of your Objective-C which can then be imported into Python.
|
5,425,725
|
I have created an objective-C framework that I would like to import and access through a python script. I understand how to import this stuff in Python, but what do i need to do on the obj-c side to make that framework importable?
Thanks
|
2011/03/24
|
[
"https://Stackoverflow.com/questions/5425725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202431/"
] |
You'll want to use [PyObjC](http://pyobjc.sourceforge.net/), as Chuck said. Specifically, I'd suggest getting the [source](http://svn.red-bean.com/pyobjc/trunk/), which contains a collection of scripts, pyobjc-metadata (here's the [readme](http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-metadata/ReadMe.txt)), that doesn't seem to be included in the default Apple installation, for wrapping a framework, generating the metadata the Python side needs, and so forth.
|
I'm not sure if this particular combination works, but you might be able to use [SWIG](http://swig.org/) to create a Python module out of your Objective-C which can then be imported into Python.
|
5,425,725
|
I have created an objective-C framework that I would like to import and access through a python script. I understand how to import this stuff in Python, but what do i need to do on the obj-c side to make that framework importable?
Thanks
|
2011/03/24
|
[
"https://Stackoverflow.com/questions/5425725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202431/"
] |
You'll want to use [PyObjC](http://pyobjc.sourceforge.net/), as Chuck said. Specifically, I'd suggest getting the [source](http://svn.red-bean.com/pyobjc/trunk/), which contains a collection of scripts, pyobjc-metadata (here's the [readme](http://svn.red-bean.com/pyobjc/trunk/pyobjc/pyobjc-metadata/ReadMe.txt)), that doesn't seem to be included in the default Apple installation, for wrapping a framework, generating the metadata the Python side needs, and so forth.
|
You can just use [PyObjC](http://pyobjc.sourceforge.net/), which is included in Mac OS X 10.5 and later.
|
11,842,202
|
I am trying to upgrade my plone version from 3.3.5 to 4.0. For this I went to this site: [updating plone](http://plone.org/documentation/manual/upgrade-guide/version/upgrading-plone-3-x-to-4.0/buildout-3-4). But I got stuck in the first point. In plone 3, I have python version of 2.4. But for plone 4.x I will need python 2.6. How do I upgrade my python version? In my buildout.cfg I have:
```
$extra-paths = ${instance:zope2-location}/lib/py
```
and in my versions.cfg, I have external dependencies and in that section I have `python-openid = 2.2.4`.
|
2012/08/07
|
[
"https://Stackoverflow.com/questions/11842202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596757/"
] |
To upgrade python it really depends on the underlying OS (operating system). If a OS specific upgrade fails, download python from <http://www.python.org/download/> and install it from source.
You might have to upgrade some of the paths in your buildout.cfg
|
You don't upgrade Python, you install a new version in parallell.
|
26,230,028
|
I just started using Crossbar.io to implement a live stats page. I've looked at a lot of code examples, but I can't figure out how to do this:
I have a Django service (to avoid confusion, you can assume I´m talking about a function in views.py) and I'd like it to publish messages in a specific topic, whenever it gets called. I've seen these approaches: (1) [Extending ApplicationSession](http://crossbar.io/docs/Python-Application-Components/) and (2) [using an Application instance that is "runned"](https://github.com/tavendo/AutobahnPython/blob/master/examples/twisted/wamp/app/hello/hello.py).
None of them work for me, because the Django service doesn't live inside a class, and is not executed as a stand-alone python file either, so I don't find a way to call the "publish" method (that is the only thing I want to do on the server side).
I tried to get an instance of "StatsBackend", which extends ApplicationSession, and publish something... But StatsBackend.\_instance is None always (even when I execute 'crossbar start' and StatsBackend.**init**() is called).
StatsBackend.py:
```
from twisted.internet.defer import inlineCallbacks
from autobahn import wamp
from autobahn.twisted.wamp import ApplicationSession
class StatsBackend(ApplicationSession):
_instance = None
def __init__(self, config):
ApplicationSession.__init__(self, config)
StatsBackend._instance = self
@classmethod
def update_stats(cls, amount):
if cls._instance:
cls._instance.publish('com.xxx.statsupdate', {'amount': amount})
@inlineCallbacks
def onJoin(self, details):
res = yield self.register(self)
print("CampaignStatsBackend: {} procedures registered!".format(len(res)))
```
test.py:
```
import StatsBackend
StatsBackend.update_stats(100) #Doesn't do anything, StatsBackend._instance is None
```
|
2014/10/07
|
[
"https://Stackoverflow.com/questions/26230028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445416/"
] |
Django is a blocking WSGI application, and that does not blend well with AutobahnPython, which is non-blocking (runs on top of Twisted or asyncio).
However, Crossbar.io has a built-in REST bridge, which includes a [HTTP Pusher](https://github.com/crossbario/crossbar/wiki/HTTP%20Pusher%20Service) to which you can submit events via any HTTP/POST capable client. Crossbar.io will forward those events to regular WAMP subscribers (eg via WebSocket in real-time).
Crossbar.io also comes with a complete application template to demonstrate above functionality. To try:
```
cd ~/test1
crossbar init --template pusher
crossbar start
```
Open your browser at `http://localhost:8080` (open the JS console) and in a second terminal
```
curl -H "Content-Type: application/json" \
-d '{"topic": "com.myapp.topic1", "args": ["Hello, world"]}' \
http://127.0.0.1:8080/push
```
You can then do the publish from within a blocking application like Django.
|
I found what I needed: It is possible to do a HTTP POST request to publish on a topic.
You can read the doc for more information: <https://github.com/crossbario/crossbar/wiki/Using-the-REST-to-WebSocket-Pusher>
|
21,834,702
|
Like I said in the title, my script only seems to work on the first line.
Here is my script:
```
#!/usr/bin/python
import sys
def main():
a = sys.argv[1]
f = open(a,'r')
lines = f.readlines()
w = 0
for line in lines:
spot = 0
cp = line
for char in reversed(cp):
x = -1
if char == ' ':
del line[x]
w += 0
if char != '\n' or char != ' ':
lines[spot] = line
spot += 1
break
x += 1
f.close()
f = open(a,'w')
f.writelines(lines)
print("White Space deleted: "+str(w))
if __name__ == "__main__":
main()
```
I'm not too experienced when it comes to loops.
|
2014/02/17
|
[
"https://Stackoverflow.com/questions/21834702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2353168/"
] |
The following script do the same thing as your program, more compactly:
```
import fileinput
deleted = 0
for line in fileinput.input(inplace=True):
stripped = line.rstrip()
deleted += len(line) - len(stripped) + 1 # don't count the newline
print(stripped)
print("Whitespace deleted: {}".format(deleted))
```
Here [`str.rstrip()`](http://docs.python.org/3/library/stdtypes.html#str.rstrip) removes *all* whitespace from the end of a line (newlines, spaces and tabs).
The [`fileinput` module](http://docs.python.org/3/library/fileinput.html) takes care of handling `sys.argv` for you, opening files one by one if you name more than one file.
Using `print()` will add the newline back on to the end of the stripped lines.
|
`rstrip()` is probably what you want to use to achieve this.
```
>>> 'Here is my string '.rstrip()
'Here is my string'
```
A more compact way to iterate backwards over stings is
```
>>> for c in 'Thing'[::-1]:
print(c)
g
n
i
h
T
```
`[::-1]` is slice notation. SLice notaion can be represented as `[start:stop:step]`. In my example a `-1` for the step means it will step form the back by one index. `[x:y:z]` will start at index `x` stop at `y-1` and go forward by `z` places each step.
|
21,834,702
|
Like I said in the title, my script only seems to work on the first line.
Here is my script:
```
#!/usr/bin/python
import sys
def main():
a = sys.argv[1]
f = open(a,'r')
lines = f.readlines()
w = 0
for line in lines:
spot = 0
cp = line
for char in reversed(cp):
x = -1
if char == ' ':
del line[x]
w += 0
if char != '\n' or char != ' ':
lines[spot] = line
spot += 1
break
x += 1
f.close()
f = open(a,'w')
f.writelines(lines)
print("White Space deleted: "+str(w))
if __name__ == "__main__":
main()
```
I'm not too experienced when it comes to loops.
|
2014/02/17
|
[
"https://Stackoverflow.com/questions/21834702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2353168/"
] |
The following script do the same thing as your program, more compactly:
```
import fileinput
deleted = 0
for line in fileinput.input(inplace=True):
stripped = line.rstrip()
deleted += len(line) - len(stripped) + 1 # don't count the newline
print(stripped)
print("Whitespace deleted: {}".format(deleted))
```
Here [`str.rstrip()`](http://docs.python.org/3/library/stdtypes.html#str.rstrip) removes *all* whitespace from the end of a line (newlines, spaces and tabs).
The [`fileinput` module](http://docs.python.org/3/library/fileinput.html) takes care of handling `sys.argv` for you, opening files one by one if you name more than one file.
Using `print()` will add the newline back on to the end of the stripped lines.
|
Just use `rstrip`:
```
f = open(a,'r')
lines = f.readlines()
f.close()
f = open(a,'w')
for line in lines:
f.write(line.rstrip()+'\n')
f.close()
```
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
**If you have conda installed in your system then follow these steps:**
* conda create -n py36 python=3.6
* activate py36
* conda config --add channels conda-forge
* conda install numpy
* conda install scipy
* conda install dlib
* pip install --no-dependencies face\_recognition
|
if your OS is windows7 :
1. download and install dlib.whl x64 or x86
2. download and install cmake app and add it to path
3. pip install cmake
4. pip install dlib only on python 3.6 to 3.7 with ".whl" file
5. pip install face\_recognotion
enjoy face\_recognition
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
First of all, install Cmake.
```
pip install cmake
```
After that, install the dlib.
If pip is not working, install dlib via the wheel file.
```
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
```
After that, you can install the face\_regognition module.
```
pip install face_recognition
```
|
if your OS is windows7 :
1. download and install dlib.whl x64 or x86
2. download and install cmake app and add it to path
3. pip install cmake
4. pip install dlib only on python 3.6 to 3.7 with ".whl" file
5. pip install face\_recognotion
enjoy face\_recognition
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
**If you have conda installed in your system then follow these steps:**
* conda create -n py36 python=3.6
* activate py36
* conda config --add channels conda-forge
* conda install numpy
* conda install scipy
* conda install dlib
* pip install --no-dependencies face\_recognition
|
My Env details :
>
> python 3.7 &
> ubuntu 16.04
>
>
>
---
**1)** Assign root permission and update ubuntu first
```
sudo su
apt-get update
```
**2)** Check your version & path for python & pip.
```
which python3
python3 -V
which pip3
pip3 -V
```
**3)**
```
pip3 install cmake
```
**4)**
```
apt-get install -y --fix-missing \
build-essential \
cmake \
gfortran \
git \
wget \
curl \
grapgicsmagick \
libgraphicsmagic-dev \
libatlas-dev \
libavcodec-dev \
libavformat-dev \
libgtk2.0-dev \
libjpeg-dev \
liblapack-dev \
libswscale-dev \
pkg-config \
software-properties-common \
zip
```
**6)**
```
apt-get install python3-dev
```
**5)**
```
pip3 install dlib
```
**6)**
```
pip3 install face_recognition
```
---
✅ Done
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
First of all, install Cmake.
```
pip install cmake
```
After that, install the dlib.
If pip is not working, install dlib via the wheel file.
```
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
```
After that, you can install the face\_regognition module.
```
pip install face_recognition
```
|
I have got the same problem. I have installed CMake but it shows the same problem.
This is the solution that worked for me,
```
conda install -c conda-forge dlib
```
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
First of all, install Cmake.
```
pip install cmake
```
After that, install the dlib.
If pip is not working, install dlib via the wheel file.
```
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
```
After that, you can install the face\_regognition module.
```
pip install face_recognition
```
|
Install Cmake with:
```
sudo apt install cmake
```
And for python3 don't use pip alone, use pip3 to install future python3 modules:
```
pip3 install face_recognition
```
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
**If you have conda installed in your system then follow these steps:**
* conda create -n py36 python=3.6
* activate py36
* conda config --add channels conda-forge
* conda install numpy
* conda install scipy
* conda install dlib
* pip install --no-dependencies face\_recognition
|
I just overcame the challenge. You can let VS Code do the hard work for you.
1. Download Visual Studio 2022.
2. When installing, make sure to install **Desktop Development with C++**. It automatically downloads CMake.
3. Once it is complete, clone face\_recognition. Simply navigate to a folder of your choice in Command Prompt or Bash and type
```
git clone https://github.com/ageitgey/face_recognition.git
```
4. Create a new virtual environment for easy differentiation and activate it
5. Install CMake using
```
pip install cmake
```
6. Navigate back to the folder where the face\_recognition was cloned and enter the command.
```
python setup.py install
```
Note: It is important that you are in the folder where the face\_recognition was cloned as it contains the setup.py file.
This takes some time but once complete, you will have face\_recogntion installed on your virtual machine.
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
First of all, install Cmake.
```
pip install cmake
```
After that, install the dlib.
If pip is not working, install dlib via the wheel file.
```
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
```
After that, you can install the face\_regognition module.
```
pip install face_recognition
```
|
I just overcame the challenge. You can let VS Code do the hard work for you.
1. Download Visual Studio 2022.
2. When installing, make sure to install **Desktop Development with C++**. It automatically downloads CMake.
3. Once it is complete, clone face\_recognition. Simply navigate to a folder of your choice in Command Prompt or Bash and type
```
git clone https://github.com/ageitgey/face_recognition.git
```
4. Create a new virtual environment for easy differentiation and activate it
5. Install CMake using
```
pip install cmake
```
6. Navigate back to the folder where the face\_recognition was cloned and enter the command.
```
python setup.py install
```
Note: It is important that you are in the folder where the face\_recognition was cloned as it contains the setup.py file.
This takes some time but once complete, you will have face\_recogntion installed on your virtual machine.
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
First of all, install Cmake.
```
pip install cmake
```
After that, install the dlib.
If pip is not working, install dlib via the wheel file.
```
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
```
After that, you can install the face\_regognition module.
```
pip install face_recognition
```
|
My Env details :
>
> python 3.7 &
> ubuntu 16.04
>
>
>
---
**1)** Assign root permission and update ubuntu first
```
sudo su
apt-get update
```
**2)** Check your version & path for python & pip.
```
which python3
python3 -V
which pip3
pip3 -V
```
**3)**
```
pip3 install cmake
```
**4)**
```
apt-get install -y --fix-missing \
build-essential \
cmake \
gfortran \
git \
wget \
curl \
grapgicsmagick \
libgraphicsmagic-dev \
libatlas-dev \
libavcodec-dev \
libavformat-dev \
libgtk2.0-dev \
libjpeg-dev \
liblapack-dev \
libswscale-dev \
pkg-config \
software-properties-common \
zip
```
**6)**
```
apt-get install python3-dev
```
**5)**
```
pip3 install dlib
```
**6)**
```
pip3 install face_recognition
```
---
✅ Done
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
**If you have conda installed in your system then follow these steps:**
* conda create -n py36 python=3.6
* activate py36
* conda config --add channels conda-forge
* conda install numpy
* conda install scipy
* conda install dlib
* pip install --no-dependencies face\_recognition
|
I have got the same problem. I have installed CMake but it shows the same problem.
This is the solution that worked for me,
```
conda install -c conda-forge dlib
```
|
56,696,940
|
i have installed the cmake but still dlib is not installing which is required for the installation of face\_recognition module
the below mentioned error i am getting whenever i try to install the dlib by using the pip install dlib
```
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sunil\AppData\Local\Temp\pip-wheel-2fd_0qt9' --python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\wheel\bdist_wheel.py", line 192, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib
Running setup.py install for dlib ... error
ERROR: Complete output from command 'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile:
ERROR: running install
running build
running build_py
package init file 'dlib\__init__.py' not found (or not a regular file)
running build_ext
Building extension for Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -DPYTHON_EXECUTABLE=c:\users\sunil\appdata\local\programs\python\python37\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\build\lib.win-amd64-3.7 -A x64'
-- Building for: NMake Makefiles
CMake Error in CMakeLists.txt:
Generator
NMake Makefiles
does not support platform specification, but platform
x64
was specified.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/sunil/AppData/Local/Temp/pip-install-oufh_gcl/dlib/build/temp.win-amd64-3.7/Release/CMakeFiles/CMakeOutput.log".
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 261, in <module>
'Topic :: Software Development',
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 966, in run_commands
self.run_command(cmd)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\site-packages\setuptools\command\install.py", line 61, in run
return orig.install.run(self)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\install.py", line 545, in run
self.run_command('build')
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\command\build.py", line 135, in run
self.run_command(cmd_name)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\distutils\dist.py", line 985, in run_command
cmd_obj.run()
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 135, in run
self.build_extension(ext)
File "C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\setup.py", line 172, in build_extension
subprocess.check_call(cmake_setup, cwd=build_folder)
File "c:\users\sunil\appdata\local\programs\python\python37\lib\subprocess.py", line 328, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-DPYTHON_EXECUTABLE=c:\\users\\sunil\\appdata\\local\\programs\\python\\python37\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\build\\lib.win-amd64-3.7', '-A', 'x64']' returned non-zero exit status 1.
----------------------------------------
ERROR: Command "'c:\users\sunil\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\sunil\\AppData\\Local\\Temp\\pip-install-oufh_gcl\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\sunil\AppData\Local\Temp\pip-record-89jcoq15\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\sunil\AppData\Local\Temp\pip-install-oufh_gcl\dlib\
```
can anyone tell me the easiest way to install the face\_recognition module for my windows 10
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56696940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628342/"
] |
First of all, install Cmake.
```
pip install cmake
```
After that, install the dlib.
If pip is not working, install dlib via the wheel file.
```
pip install https://pypi.python.org/packages/da/06/bd3e241c4eb0a662914b3b4875fc52dd176a9db0d4a2c915ac2ad8800e9e/dlib-19.7.0-cp36-cp36m-win_amd64.whl#md5=b7330a5b2d46420343fbed5df69e6a3f
```
After that, you can install the face\_regognition module.
```
pip install face_recognition
```
|
**Simple steps:-**
1. install python 3.8 [here](https://www.python.org/downloads/release/python-380/)
2. `pip install cmake` (or) `pip3 install cmake` (#make sure you installing cmake on python3.8 pip)
3. download cmake softwre [here](https://cmake.org/downloads)
4.install c,c++ build tools [here](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
5.once you install c++ inside the visual studio 1.9GB restart your computer
6.`pip install face_recognition`
Everything done enjoy programming
|
71,822,376
|
Is there any way I can make **Excel** add-ins/extensions using Python?
I have tried javascript but haven't found any result about making add-ins on python.
|
2022/04/11
|
[
"https://Stackoverflow.com/questions/71822376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17767517/"
] |
Try this code
```
nav .wrapper{
display: flex;
justify-content: space-between;
}
nav ul{
display: flex;
}
```
|
It should contain http
For example
href="https://classroom.udacity.com/nanodegrees/nd004-1mac-v2/dashboard/overview"
|
71,822,376
|
Is there any way I can make **Excel** add-ins/extensions using Python?
I have tried javascript but haven't found any result about making add-ins on python.
|
2022/04/11
|
[
"https://Stackoverflow.com/questions/71822376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17767517/"
] |
Try this code
```
nav .wrapper{
display: flex;
justify-content: space-between;
}
nav ul{
display: flex;
}
```
|
Maybe something like this??
```css
.wrapper {
display:flex;
flex-direction:row;
justify-content:space-evenly;
width:100%;
height:40px;
background-color:black;
padding-top:10px;
}
.wrapper > a{
color:white;
text-decoration:none;
}
a:hover {
text-decoration:underline
}
```
```html
<body>
<nav>
<div class="wrapper">
<a href="index.php"><img src="spaceship.png" alt="blogs logo"></a>
<a href="index.php">Home</a>
<a href="discover.php">About us</a>
<a href="blog.php">Find Blogs</a>
<a href="signup.php">Sign up</a>
<a href="login.php">Login</a>
</div>
</nav>
```
|
68,384,185
|
Hi I'm trying to build out a basic app django within a python/alpine image.
I am getting en error telling me that there is no matching image for the version of Django that I am looking for.
The Dockerfile in using a `python:3.9-alpine3.14` image and my requirements file is targeting `Django>=3.2.5,<3.3`.
From what i understand these should be compatible, Django >= 3 and Python 3.9.
When I run `docker-compose build` the RUN command gets so far as the `apk add` commands but fails on `pip`. I did try changing this to `pip3` but this had no effect.
Any idea what I am missing here that will fix this issue?
`requirements.txt`
```
Django>=3.2.5,<3.3
uWSGI>=2.0.19.1,<2.1
```
`Dockerfile`
```
FROM python:3.9-alpine3.14
LABEL maintainer="superapp"
ENV PYTHONUNBUFFERED 1
COPY requirements.txt /requirements.txt
RUN mkdir /app
COPY ./app /app
COPY ./scripts /scripts
WORKDIR /app
EXPOSE 8000
RUN python -m venv /py && \
/py/bin/pip install --upgrade pip && \
apk add --update --no-cache --virtual .build-deps \
build-base \
gcc \
linux-headers && \
/py/bin/pip install -r /requirements.txt && \
apk del .build-deps && \
adduser --disabled-password --no-create-home rsecuser && \
mkdir -p /vol/web/static && \
chown -R rsecuser:rsecuser /vol && \
chmod -R 755 /vol && \
chmod -R +x /scripts
ENV PATH="/scripts:/py/bin:$PATH"
USER rsecuser
CMD ["run.sh"]
```
`docker-compose.yml`
```
version: "3.9"
services:
app:
build:
context: .
command: >
sh -c "python manage.py runserver 0.0.0.0:8000"
ports:
- 8000:8000
volumes:
- ./app:/app
- ./data/web:/vol/web
environment:
- SECRET_KEY=development_key
- DEBUG=1
```
Error
```
...
...
...
(20/22) Installing build-base (0.5-r2)
(21/22) Installing linux-headers (5.10.41-r0)
(22/22) Installing .build-deps (20210714.193049)
Executing busybox-1.33.1-r2.trigger
OK: 212 MiB in 58 packages
ERROR: Could not find a version that satisfies the requirement Django<3.3,>=3.2.5 (from versions: none)
ERROR: No matching distribution found for Django<3.3,>=3.2.5
ERROR: Service 'app' failed to build : The command '/bin/sh -c python -m venv /py && /py/bin/pip install --upgrade pip && apk add --update --no-cache --virtual .build-deps build-base gcc linux-headers && /py/bin/pip install -r /requirements.txt && apk del .build-deps && adduser --disabled-password --no-create-home rsecuser && mkdir -p /vol/web/static && chown -R rsecuser:rsecuser /vol && chmod -R 755 /vol && chmod -R +x /scripts' returned a non-zero code: 1(20/22) Installing build-base (0.5-r2)
(21/22) Installing linux-headers (5.10.41-r0)
(22/22) Installing .build-deps (20210714.193049)
Executing busybox-1.33.1-r2.trigger
OK: 212 MiB in 58 packages
ERROR: Could not find a version that satisfies the requirement Django<3.3,>=3.2.5 (from versions: none)
ERROR: No matching distribution found for Django<3.3,>=3.2.5
ERROR: Service 'app' failed to build : The command '/bin/sh -c python -m venv /py && /py/bin/pip install --upgrade pip && apk add --update --no-cache --virtual .build-deps build-base gcc linux-headers && /py/bin/pip install -r /requirements.txt && apk del .build-deps && adduser --disabled-password --no-create-home rsecuser && mkdir -p /vol/web/static && chown -R rsecuser:rsecuser /vol && chmod -R 755 /vol && chmod -R +x /scripts' returned a non-zero code: 1
```
As per comments below, same command run with `/py/bin/pip -vv install -r /requirements.txt` in the Dockerfile.
```
(21/22) Installing linux-headers (5.10.41-r0)
(22/22) Installing .build-deps (20210714.195119)
Executing busybox-1.33.1-r2.trigger
OK: 212 MiB in 58 packages
Using pip 21.1.3 from /py/lib/python3.9/site-packages/pip (python 3.9)
Non-user install because user site-packages disabled
Created temporary directory: /tmp/pip-ephem-wheel-cache-gyetbpa_
Created temporary directory: /tmp/pip-req-tracker-og42yr4p
Initialized build tracking at /tmp/pip-req-tracker-og42yr4p
Created build tracker: /tmp/pip-req-tracker-og42yr4p
Entered build tracker: /tmp/pip-req-tracker-og42yr4p
Created temporary directory: /tmp/pip-install-p5b3_acb
1 location(s) to search for versions of django:
* https://pypi.org/simple/django/
Fetching project page and analyzing links: https://pypi.org/simple/django/
Getting page https://pypi.org/simple/django/
Found index url https://pypi.org/simple
Looking up "https://pypi.org/simple/django/" in the cache
Request header has "max_age" as 0, cache bypassed
Starting new HTTPS connection (1): pypi.org:443
https://pypi.org:443 "GET /simple/django/ HTTP/1.1" 200 42407
Could not fetch URL https://pypi.org/simple/django/: connection error: HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. - skipping
Skipping link: not a file: https://pypi.org/simple/django/
Given no hashes to check 0 links for project 'django': discarding no candidates
ERROR: Could not find a version that satisfies the requirement Django<3.3,>=3.2.5 (from versions: none)
ERROR: No matching distribution found for Django<3.3,>=3.2.5
Exception information:
Traceback (most recent call last):
File "/py/lib/python3.9/site-packages/pip/_vendor/resolvelib/resolvers.py", line 341, in resolve
name, crit = self._merge_into_criterion(r, parent=None)
File "/py/lib/python3.9/site-packages/pip/_vendor/resolvelib/resolvers.py", line 173, in _merge_into_criterion
raise RequirementsConflicted(criterion)
pip._vendor.resolvelib.resolvers.RequirementsConflicted: Requirements conflict: SpecifierRequirement('Django<3.3,>=3.2.5')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/py/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 127, in resolve
result = self._result = resolver.resolve(
File "/py/lib/python3.9/site-packages/pip/_vendor/resolvelib/resolvers.py", line 473, in resolve
state = resolution.resolve(requirements, max_rounds=max_rounds)
File "/py/lib/python3.9/site-packages/pip/_vendor/resolvelib/resolvers.py", line 343, in resolve
raise ResolutionImpossible(e.criterion.information)
pip._vendor.resolvelib.resolvers.ResolutionImpossible: [RequirementInformation(requirement=SpecifierRequirement('Django<3.3,>=3.2.5'), parent=None)]
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/py/lib/python3.9/site-packages/pip/_internal/cli/base_command.py", line 180, in _main
status = self.run(options, args)
File "/py/lib/python3.9/site-packages/pip/_internal/cli/req_command.py", line 205, in wrapper
return func(self, options, args)
File "/py/lib/python3.9/site-packages/pip/_internal/commands/install.py", line 318, in run
requirement_set = resolver.resolve(
File "/py/lib/python3.9/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 136, in resolve
raise error from e
pip._internal.exceptions.DistributionNotFound: No matching distribution found for Django<3.3,>=3.2.5
Removed build tracker: '/tmp/pip-req-tracker-og42yr4p'
ERROR: Service 'app' failed to build : The command '/bin/sh -c python -m venv /py && /py/bin/pip install --upgrade pip && apk add --update --no-cache --virtual .build-deps build-base gcc linux-headers && /py/bin/pip -vv install -r /requirements.txt && apk del .build-deps && adduser --disabled-password --no-create-home rsecuser && mkdir -p /vol/web/static && chown -R rsecuser:rsecuser /vol && chmod -R 755 /vol && chmod -R +x /scripts' returned a non-zero code: 1
```
|
2021/07/14
|
[
"https://Stackoverflow.com/questions/68384185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3346752/"
] |
Continuing a list over multiple section is not a standard task, I think the clean way to go is definitely with a [counter](https://docs.asciidoctor.org/asciidoc/latest/attributes/counters/).
Instead of an ordered list you could instead use a [Description list](https://docs.asciidoctor.org/asciidoc/latest/lists/description/), it does not look the same but brings some flexibility and the main idea is there:
```
== Section A
{counter:list-counter}):: item 1
{counter:list-counter}):: item 2
== Section B
{counter:list-counter}):: item 3
{counter:list-counter}):: item 4
== Section C
{counter:list-counter}):: item 5
{counter:list-counter}):: item 6
```
|
Here's another hack:
```
= Document
== Section A
. item 1
. item 2
+
[discrete]
== Section B
. item 3
. item 4
+
[discrete]
== Section C
. item 5
. item 6
```
That gets the list items to have the correct item numbers, but the "discrete" headings are indented. You could use some CSS customization (say via [docinfo files](https://docs.asciidoctor.org/asciidoctor/latest/docinfo/)) to outdent them.
|
41,204,071
|
I have implemented the [python-social-auth](https://github.com/python-social-auth) library for Google OAuth2 in my Django project, and am successfully able to log users in with it. The library stores the `access_token` received in the response for Google's OAuth2 flow.
My question is: use of the [google-api-python-client](https://github.com/google/google-api-python-client) seems to rely on creating and authorizing a `credentials` object, then using it to build an API `service` like so:
```
...
# send user to Google consent URL, get auth_code in response
credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())
from apiclient.discovery import build
service = build('gmail', 'v1', http=http_auth)
# use service for API calls...
```
Since I'm starting with an `access_token` provided by python-social-auth, how do I create & authorize the API client `service` for future API calls?
**Edit**: to clarify, the code above is from the examples provided by Google.
|
2016/12/17
|
[
"https://Stackoverflow.com/questions/41204071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306374/"
] |
Given you already have the OAuth2 access token you can use the [`AccessTokenCredentials`](https://developers.google.com/api-client-library/python/guide/aaa_oauth#AccessTokenCredentials) class.
>
> The oauth2client.client.AccessTokenCredentials class is used when you have already obtained an access token by some other means. You can create this object directly without using a Flow object.
>
>
>
Example:
```
import httplib2
from googleapiclient.discovery import build
from oauth2client.client import AccessTokenCredentials
credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)
```
|
You can check examples provided by Google Guide API, for example: sending email via gmail application, <https://developers.google.com/gmail/api/guides/sending>
|
41,204,071
|
I have implemented the [python-social-auth](https://github.com/python-social-auth) library for Google OAuth2 in my Django project, and am successfully able to log users in with it. The library stores the `access_token` received in the response for Google's OAuth2 flow.
My question is: use of the [google-api-python-client](https://github.com/google/google-api-python-client) seems to rely on creating and authorizing a `credentials` object, then using it to build an API `service` like so:
```
...
# send user to Google consent URL, get auth_code in response
credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())
from apiclient.discovery import build
service = build('gmail', 'v1', http=http_auth)
# use service for API calls...
```
Since I'm starting with an `access_token` provided by python-social-auth, how do I create & authorize the API client `service` for future API calls?
**Edit**: to clarify, the code above is from the examples provided by Google.
|
2016/12/17
|
[
"https://Stackoverflow.com/questions/41204071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306374/"
] |
Given you already have the OAuth2 access token you can use the [`AccessTokenCredentials`](https://developers.google.com/api-client-library/python/guide/aaa_oauth#AccessTokenCredentials) class.
>
> The oauth2client.client.AccessTokenCredentials class is used when you have already obtained an access token by some other means. You can create this object directly without using a Flow object.
>
>
>
Example:
```
import httplib2
from googleapiclient.discovery import build
from oauth2client.client import AccessTokenCredentials
credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)
```
|
If you have an already refreshed latest access token which is not expired, then you can get `service` variable as:
```
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
creds = Credentials("<ACCESS_TOKEN>")
service = build('gmail', 'v1', credentials=creds)
# Call the Gmail API
```
|
52,221,769
|
I have two floats `no_a` and `no_b` and a couple of ranges represented as two element lists holding the lower and upper border.
I want to check if the numbers are both in one of the following ranges: `[0, 0.33]`, `[0.33, 0.66]`, or `[0.66, 1.0]`.
How can I write that statement neatly in python code?
|
2018/09/07
|
[
"https://Stackoverflow.com/questions/52221769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682455/"
] |
If you just want to get a `True` or `False` result, consider the following.
```
>>> a = 0.4
>>> b = 0.6
>>>
>>> ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
>>>
>>> any(low <= a <= high and low <= b <= high for low, high in ranges)
True
```
If you have an arbitrary amount of numbers to check (not just `a` and `b`) you can generalize this to:
```
>>> numbers = [0.4, 0.6, 0.34]
>>> any(all(low <= x <= high for x in numbers) for low, high in ranges)
True
```
|
Have a look at [here](https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html).
Put your `no_a` and `no_b` into an array and check if all events pass your statement.
---
Second Edit:
As pointed out, the built-in `all` function outperforms the numpy version for this small dataset, so the usage of numpy has been removed:
```
ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
for i in range(len(ranges)):
if all([ranges[i][0] < no_a < ranges[i][1],
ranges[i][0] < no_b < ranges[i][1]]):
print('Both values are in the interval of %s' %ranges[i])
```
which will print out the range that both values fall into.
|
52,221,769
|
I have two floats `no_a` and `no_b` and a couple of ranges represented as two element lists holding the lower and upper border.
I want to check if the numbers are both in one of the following ranges: `[0, 0.33]`, `[0.33, 0.66]`, or `[0.66, 1.0]`.
How can I write that statement neatly in python code?
|
2018/09/07
|
[
"https://Stackoverflow.com/questions/52221769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682455/"
] |
If you just want to get a `True` or `False` result, consider the following.
```
>>> a = 0.4
>>> b = 0.6
>>>
>>> ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
>>>
>>> any(low <= a <= high and low <= b <= high for low, high in ranges)
True
```
If you have an arbitrary amount of numbers to check (not just `a` and `b`) you can generalize this to:
```
>>> numbers = [0.4, 0.6, 0.34]
>>> any(all(low <= x <= high for x in numbers) for low, high in ranges)
True
```
|
Like this:
```
RANGES = [[0,0.33], [0.33,0.66], [0.66,1.0]]
def check(no_a, no_b):
for rng in RANGES:
if rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1]:
return True
else:
return False
print(check(.1, .2))
print(check(.1, .4))
```
Output is:
```
True
False
```
Or like this:
```
no_a, no_b = .1, .2
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
no_a, no_b = .1, .4
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
```
Output is:
```
True
False
```
|
52,221,769
|
I have two floats `no_a` and `no_b` and a couple of ranges represented as two element lists holding the lower and upper border.
I want to check if the numbers are both in one of the following ranges: `[0, 0.33]`, `[0.33, 0.66]`, or `[0.66, 1.0]`.
How can I write that statement neatly in python code?
|
2018/09/07
|
[
"https://Stackoverflow.com/questions/52221769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682455/"
] |
If you just want to get a `True` or `False` result, consider the following.
```
>>> a = 0.4
>>> b = 0.6
>>>
>>> ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
>>>
>>> any(low <= a <= high and low <= b <= high for low, high in ranges)
True
```
If you have an arbitrary amount of numbers to check (not just `a` and `b`) you can generalize this to:
```
>>> numbers = [0.4, 0.6, 0.34]
>>> any(all(low <= x <= high for x in numbers) for low, high in ranges)
True
```
|
### Numpy Using Broadcasting
```
import numpy as np
check = np.array([[0.4], [0.6]])
ranges = np.array([[0,0.33], [0.33,0.66], [0.66,1.0]])
((check >= ranges[:, 0]) & (check <= ranges[:, 1])).all(0).any()
True
```
---
### Details
```
check >= ranges[:, 0]
# 0.00 0.33 0.66 <
[[ True True False] # 0.4
[ True True False]] # 0.6
```
---
```
check <= ranges[:, 1]
# 0.33 0.66 1.00 >
[[False True True] # 0.4
[False True True]] # 0.6
```
---
```
a = (check >= ranges[:, 0]) & (check <= ranges[:, 1])
a
# 0.00 0.33 0.66 <
# 0.33 0.66 1.00 >
[[False True False] # 0.4
[False True False]] # 0.6
```
In order for both values of `check` to be in one range pair, all of one column has to be `True`
```
a.all(0)
[False True False]
```
Than as long as any one of these is `True`
```
a.all(0).any()
True
```
---
### Numpy redux
However, we could have transformed the `check` and `ranges` to conduct one comparison operation.
```
b = [1, -1]
(check.T * b >= ranges * b).all(1).any()
True
```
|
52,221,769
|
I have two floats `no_a` and `no_b` and a couple of ranges represented as two element lists holding the lower and upper border.
I want to check if the numbers are both in one of the following ranges: `[0, 0.33]`, `[0.33, 0.66]`, or `[0.66, 1.0]`.
How can I write that statement neatly in python code?
|
2018/09/07
|
[
"https://Stackoverflow.com/questions/52221769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682455/"
] |
Like this:
```
RANGES = [[0,0.33], [0.33,0.66], [0.66,1.0]]
def check(no_a, no_b):
for rng in RANGES:
if rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1]:
return True
else:
return False
print(check(.1, .2))
print(check(.1, .4))
```
Output is:
```
True
False
```
Or like this:
```
no_a, no_b = .1, .2
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
no_a, no_b = .1, .4
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
```
Output is:
```
True
False
```
|
Have a look at [here](https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html).
Put your `no_a` and `no_b` into an array and check if all events pass your statement.
---
Second Edit:
As pointed out, the built-in `all` function outperforms the numpy version for this small dataset, so the usage of numpy has been removed:
```
ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
for i in range(len(ranges)):
if all([ranges[i][0] < no_a < ranges[i][1],
ranges[i][0] < no_b < ranges[i][1]]):
print('Both values are in the interval of %s' %ranges[i])
```
which will print out the range that both values fall into.
|
52,221,769
|
I have two floats `no_a` and `no_b` and a couple of ranges represented as two element lists holding the lower and upper border.
I want to check if the numbers are both in one of the following ranges: `[0, 0.33]`, `[0.33, 0.66]`, or `[0.66, 1.0]`.
How can I write that statement neatly in python code?
|
2018/09/07
|
[
"https://Stackoverflow.com/questions/52221769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5682455/"
] |
Like this:
```
RANGES = [[0,0.33], [0.33,0.66], [0.66,1.0]]
def check(no_a, no_b):
for rng in RANGES:
if rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1]:
return True
else:
return False
print(check(.1, .2))
print(check(.1, .4))
```
Output is:
```
True
False
```
Or like this:
```
no_a, no_b = .1, .2
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
no_a, no_b = .1, .4
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
```
Output is:
```
True
False
```
|
### Numpy Using Broadcasting
```
import numpy as np
check = np.array([[0.4], [0.6]])
ranges = np.array([[0,0.33], [0.33,0.66], [0.66,1.0]])
((check >= ranges[:, 0]) & (check <= ranges[:, 1])).all(0).any()
True
```
---
### Details
```
check >= ranges[:, 0]
# 0.00 0.33 0.66 <
[[ True True False] # 0.4
[ True True False]] # 0.6
```
---
```
check <= ranges[:, 1]
# 0.33 0.66 1.00 >
[[False True True] # 0.4
[False True True]] # 0.6
```
---
```
a = (check >= ranges[:, 0]) & (check <= ranges[:, 1])
a
# 0.00 0.33 0.66 <
# 0.33 0.66 1.00 >
[[False True False] # 0.4
[False True False]] # 0.6
```
In order for both values of `check` to be in one range pair, all of one column has to be `True`
```
a.all(0)
[False True False]
```
Than as long as any one of these is `True`
```
a.all(0).any()
True
```
---
### Numpy redux
However, we could have transformed the `check` and `ranges` to conduct one comparison operation.
```
b = [1, -1]
(check.T * b >= ranges * b).all(1).any()
True
```
|
17,604,130
|
I need help figuring out this code. This is my first programming class and we have a exam next week and I am trying to do the old exams.
There is one class with nested list that I am having trouble understanding. It basically says to convert `(list of [list of ints]) -> int`.
Basically given a list of list which ever has a even number in this case 0 is even return that index and if there are no even numbers we return -1.
Also we are given three examples
```
>>> first_even([[9, 1, 3], [2, 5, 7], [9, 9, 7, 2]])
1
>>> first_even([[1, 3, 5], [7, 9], [1, 0]])
2
>>> first_even([[1, 3, 5]])
-1
```
We are using python 3 in our class and I kind of have a idea in where to begin but I know its wrong. but ill give it a try
```
def first_even(L1):
count = 0
for i in range(L1):
if L1[i] % 2 = 0:
count += L1
return count
```
I thought this was it but it didn't work out.
If you guys could please help me out with hints or solution to this it would be helpful to me.
|
2013/07/11
|
[
"https://Stackoverflow.com/questions/17604130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2574430/"
] |
If I understand correctly and you want to return the index of the first list that contains at least one even number:
```
In [1]: def first_even(nl):
...: for i, l in enumerate(nl):
...: if not all(x%2 for x in l):
...: return i
...: return -1
...:
In [2]: first_even([[9, 1, 3], [2, 5, 7], [9, 9, 7, 2]])
Out[2]: 1
In [3]: first_even([[1, 3, 5], [7, 9], [1, 0]])
Out[3]: 2
In [4]: first_even([[1, 3, 5]])
Out[4]: -1
```
[`enumerate`](http://docs.python.org/3/library/functions.html#enumerate) is a convenient built-in function that gives you both the index and the item if an iterable, and so you don't need to mess with the ugly `range(len(L1))` and indexing.
[`all`](http://docs.python.org/3/library/functions.html#all) is another built-in. If all remainders are non-zero (and thus evaluate to `True`) then the list doesn't contain any even numbers.
|
There are some minor problems with your code:
* `L1[i] % 2 = 0` is using the wrong operator. `=` is for assigning variables a value, while `==` is used for equality.
* You probably meant `range(len(L1))`, as range expects an integer.
* Lastly, you're adding the whole list to the count, when you only wanted to add the index. This could be achieved with `.index()`, but this doesn't work for duplicates in the list. You can use `enumerate`, as I'm about to show below.
If you're ever working with indexes, `enumerate()` is your function:
```
def first_even(L):
for x, y in enumerate(L):
if any(z % 2 == 0 for z in y): # If any of the numbers in the subsists are even
return x # Return the index. Function breaks
return -1 # No even numbers found. Return -1
```
|
17,604,130
|
I need help figuring out this code. This is my first programming class and we have a exam next week and I am trying to do the old exams.
There is one class with nested list that I am having trouble understanding. It basically says to convert `(list of [list of ints]) -> int`.
Basically given a list of list which ever has a even number in this case 0 is even return that index and if there are no even numbers we return -1.
Also we are given three examples
```
>>> first_even([[9, 1, 3], [2, 5, 7], [9, 9, 7, 2]])
1
>>> first_even([[1, 3, 5], [7, 9], [1, 0]])
2
>>> first_even([[1, 3, 5]])
-1
```
We are using python 3 in our class and I kind of have a idea in where to begin but I know its wrong. but ill give it a try
```
def first_even(L1):
count = 0
for i in range(L1):
if L1[i] % 2 = 0:
count += L1
return count
```
I thought this was it but it didn't work out.
If you guys could please help me out with hints or solution to this it would be helpful to me.
|
2013/07/11
|
[
"https://Stackoverflow.com/questions/17604130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2574430/"
] |
If I understand correctly and you want to return the index of the first list that contains at least one even number:
```
In [1]: def first_even(nl):
...: for i, l in enumerate(nl):
...: if not all(x%2 for x in l):
...: return i
...: return -1
...:
In [2]: first_even([[9, 1, 3], [2, 5, 7], [9, 9, 7, 2]])
Out[2]: 1
In [3]: first_even([[1, 3, 5], [7, 9], [1, 0]])
Out[3]: 2
In [4]: first_even([[1, 3, 5]])
Out[4]: -1
```
[`enumerate`](http://docs.python.org/3/library/functions.html#enumerate) is a convenient built-in function that gives you both the index and the item if an iterable, and so you don't need to mess with the ugly `range(len(L1))` and indexing.
[`all`](http://docs.python.org/3/library/functions.html#all) is another built-in. If all remainders are non-zero (and thus evaluate to `True`) then the list doesn't contain any even numbers.
|
So here's what I came up with.
```
def first_even(L1):
for aList in range(len(L1)):
for anItem in range(len(L1[aList])):
if L1[aList][anItem] % 2 == 0:
return aList
return -1
```
First a fix. You need to use == for "equal to", '=' is for assigning variables.
```
L1[i] % 2 == 0
```
And for the code, here's the idea in some more pseudocodey style:
```
Iterate through the list of lists (L1):
Iterate through the list's (aList) items (anItem):
if List[current list][current item] is even:
Return the current list's index
Return -1 at this point, because if the code gets this far, an even number isn't here.
```
Hope it helps, if you need any further explanation then I'll be happy to.
|
17,604,130
|
I need help figuring out this code. This is my first programming class and we have a exam next week and I am trying to do the old exams.
There is one class with nested list that I am having trouble understanding. It basically says to convert `(list of [list of ints]) -> int`.
Basically given a list of list which ever has a even number in this case 0 is even return that index and if there are no even numbers we return -1.
Also we are given three examples
```
>>> first_even([[9, 1, 3], [2, 5, 7], [9, 9, 7, 2]])
1
>>> first_even([[1, 3, 5], [7, 9], [1, 0]])
2
>>> first_even([[1, 3, 5]])
-1
```
We are using python 3 in our class and I kind of have a idea in where to begin but I know its wrong. but ill give it a try
```
def first_even(L1):
count = 0
for i in range(L1):
if L1[i] % 2 = 0:
count += L1
return count
```
I thought this was it but it didn't work out.
If you guys could please help me out with hints or solution to this it would be helpful to me.
|
2013/07/11
|
[
"https://Stackoverflow.com/questions/17604130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2574430/"
] |
If I understand correctly and you want to return the index of the first list that contains at least one even number:
```
In [1]: def first_even(nl):
...: for i, l in enumerate(nl):
...: if not all(x%2 for x in l):
...: return i
...: return -1
...:
In [2]: first_even([[9, 1, 3], [2, 5, 7], [9, 9, 7, 2]])
Out[2]: 1
In [3]: first_even([[1, 3, 5], [7, 9], [1, 0]])
Out[3]: 2
In [4]: first_even([[1, 3, 5]])
Out[4]: -1
```
[`enumerate`](http://docs.python.org/3/library/functions.html#enumerate) is a convenient built-in function that gives you both the index and the item if an iterable, and so you don't need to mess with the ugly `range(len(L1))` and indexing.
[`all`](http://docs.python.org/3/library/functions.html#all) is another built-in. If all remainders are non-zero (and thus evaluate to `True`) then the list doesn't contain any even numbers.
|
```
def first_even(L1):
return ''.join('o' if all(n%2 for n in sl) else 'e' for sl in L1).find('e')
```
|
62,984,417
|
I am trying to format a string in python, but the values are not being replaced.
Here is my example...
```
uid = results[0][0]
query = """
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid = m.blackUid
WHERE
m.whiteUid = {uid} OR m.blackUid = {uid} OR m.id = {uid}
"""
query.format(uid=uid)
```
When I run this query the string {uid} still exists in all locations.
|
2020/07/19
|
[
"https://Stackoverflow.com/questions/62984417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3321579/"
] |
You should do this:
`query = query.format(...)`.
The format method just returns the formatted string, it doesn't change `self`.
|
String is immutable.
Use f string. It's recommended.
```
query = f"""
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid = m.blackUid
WHERE
m.whiteUid = {uid} OR m.blackUid = {uid} OR m.id = {uid}
"""
```
|
62,984,417
|
I am trying to format a string in python, but the values are not being replaced.
Here is my example...
```
uid = results[0][0]
query = """
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid = m.blackUid
WHERE
m.whiteUid = {uid} OR m.blackUid = {uid} OR m.id = {uid}
"""
query.format(uid=uid)
```
When I run this query the string {uid} still exists in all locations.
|
2020/07/19
|
[
"https://Stackoverflow.com/questions/62984417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3321579/"
] |
You should do this:
`query = query.format(...)`.
The format method just returns the formatted string, it doesn't change `self`.
|
If using python3 I would recommend f-Strings (<https://docs.python.org/3/reference/lexical_analysis.html#f-strings>):
```
uid = results[0][0]
query = f"""
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid = m.blackUid
WHERE
m.whiteUid = {uid} OR m.blackUid = {uid} OR m.id = {uid}
"""
print(query)
```
NOTE: take into account that it already tries to inject the value of any variabale defined in, so it must exists already.
|
62,984,417
|
I am trying to format a string in python, but the values are not being replaced.
Here is my example...
```
uid = results[0][0]
query = """
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid = m.blackUid
WHERE
m.whiteUid = {uid} OR m.blackUid = {uid} OR m.id = {uid}
"""
query.format(uid=uid)
```
When I run this query the string {uid} still exists in all locations.
|
2020/07/19
|
[
"https://Stackoverflow.com/questions/62984417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3321579/"
] |
String is immutable.
Use f string. It's recommended.
```
query = f"""
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid = m.blackUid
WHERE
m.whiteUid = {uid} OR m.blackUid = {uid} OR m.id = {uid}
"""
```
|
If using python3 I would recommend f-Strings (<https://docs.python.org/3/reference/lexical_analysis.html#f-strings>):
```
uid = results[0][0]
query = f"""
SELECT
m.whiteUid,
m.blackUid,
u1.displayName AS whiteDisplayName,
u2.displayName AS blackDisplayName,
m.created,
m.modified
FROM matches m
INNER JOIN users u1 ON u1.uid = m.whiteUid
INNER JOIN users u2 ON u2.uid = m.blackUid
WHERE
m.whiteUid = {uid} OR m.blackUid = {uid} OR m.id = {uid}
"""
print(query)
```
NOTE: take into account that it already tries to inject the value of any variabale defined in, so it must exists already.
|
37,724,694
|
I am just trying to pass random arguments for below python script.
Code:
```
import json,sys,os,subprocess
arg1 = 'Site1'
arg2 = "443"
arg3 = 'admin@example.com'
arg4 = 'example@123'
arg5 = '--output req.txt'
arg6 = '-h'
obj=json.load(sys.stdin)
for i in range(len(obj['data'])):
print obj['data'][i]['value']
subprocess.call(['./malopinfo.py', arg1, arg2, arg3, arg4, obj , arg5])
```
In above code variable `obj` will change randomly, But apart from that all arguments are static.
Error:
```
root@prabhu:/home/teja/MalopInfo/version1/MalopInfo# ./crver1.sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 116 0 116 0 0 5313 0 --:--:-- --:--:-- --:--:-- 5523
11.945403842773683082
Traceback (most recent call last):
File "qjson.py", line 15, in <module>
subprocess.call(['./malopinfo.py', arg1, arg2, arg3, arg4, obj])
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
```
I am trying to execute is
```
python malopinfo.py Site1 443 admin@example.com example@123 11.945403842773683082 --output req.txt
```
Please help me on this.
|
2016/06/09
|
[
"https://Stackoverflow.com/questions/37724694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5005270/"
] |
It looks to me like you're passing the entire `obj` dictionary into the command. To get the desired invocation, pass `obj['data'][i]['value']` in the arguments list to `subprocess.call`. So, the final line of your script should be
```
subprocess.call(['./malopinfo.py', arg1, arg2, arg3, arg4, obj['data'][i]['value'], arg5])
```
Or, you can make a variable to contain that on each loop iteration, whatever works.
|
You are directly passing an object. Beforehand you need to convert that into string as `subprocess.call` will expect obj to be a string. Get the string value of one of the obj properties like you already have done `obj['data'][i]['value']` and pass it into your `subprocess.call`.
|
51,492,621
|
I've recently attempted google's iot end-to-end example (<https://cloud.google.com/iot/docs/samples/end-to-end-sample>) out of pure interest. However, towards the final part of the process where I had to connect devices, I kept running into a run time error.
```
Creating JWT using RS256 from private key file rsa_private.pem
Connection Result: 5: The connection was refused.
Disconnected: 5: The connection was refused.
Connection Result: 5: The connection was refused.
Disconnected: 5: The connection was refused.
Traceback (most recent call last):
File "cloudiot_pubsub_example_mqtt_device.py", line 259, in <module>
main()
File "cloudiot_pubsub_example_mqtt_device.py", line 234, in main
device.wait_for_connection(5)
File "cloudiot_pubsub_example_mqtt_device.py", line 100, in
wait_for_connection
raise RuntimeError('Could not connect to MQTT bridge.')
RuntimeError: Could not connect to MQTT bridge.
```
Above is the error obtained after inserting the command string that was on the clipboard. Below is a more elaborated process of how i got to the error.
Regarding the device ID, i manually created on the google iot platform in the registry. For the private/public rsa key pair, I generated them following Google's instruction and pasted the public key in the device's public key and copied the private key into the same directory with the python files in them.
Thanks.
|
2018/07/24
|
[
"https://Stackoverflow.com/questions/51492621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10126223/"
] |
To solve this, just pass the correct cloud region parameter to the command --cloud\_region=asia-east1
|
You can try giving cloud region when running device script Ex : "--cloud\_region=asia-east1"
python cloudiot\_pubsub\_example\_mqtt\_device.py --project\_id=applied-grove-246108 --registry\_id=my-registry --device\_id=my-device --private\_key\_file=rsa\_private.pem --algorithm=RS256 --cloud\_region=asia-east1
|
30,103,965
|
Not by word boundaries, that is solvable.
Example:
```
#!/usr/bin/env python3
text = 'เมื่อแรกเริ่ม'
for char in text:
print(char)
```
This produces:
เ
ม
อ
แ
ร
ก
เ
ร
ม
Which obviously is not the desired output. Any ideas?
A portable representation of text is:
```
text = u'\u0e40\u0e21\u0e37\u0e48\u0e2d\u0e41\u0e23\u0e01\u0e40\u0e23\u0e34\u0e48\u0e21'
```
|
2015/05/07
|
[
"https://Stackoverflow.com/questions/30103965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2397101/"
] |
tl;dr: Use `\X` regular expression to extract user-perceived characters:
```
>>> import regex # $ pip install regex
>>> regex.findall(u'\\X', u'เมื่อแรกเริ่ม')
['เ', 'มื่', 'อ', 'แ', 'ร', 'ก', 'เ', 'ริ่', 'ม']
```
---
While I do not know Thai, I know a little French.
Consider the letter `è`. Let `s` and `s2` equal `è` in the Python shell:
```
>>> s
'è'
>>> s2
'è'
```
Same letter? To a French speaker visually, oui. To a computer, no:
```
>>> s==s2
False
```
You can create the same letter either using the actual code point for `è` or by taking the letter `e` and adding a combining code point that adds that accent character. They have different encodings:
```
>>> s.encode('utf-8')
b'\xc3\xa8'
>>> s2.encode('utf-8')
b'e\xcc\x80'
```
And differnet lengths:
```
>>> len(s)
1
>>> len(s2)
2
```
But visually both encodings result in the 'letter' `è`. This is called a [grapheme](http://en.wikipedia.org/wiki/Grapheme), or what the end user considers one character.
You can demonstrate the same looping behavior you are seeing:
```
>>> [c for c in s]
['è']
>>> [c for c in s2]
['e', '̀']
```
Your string has several combining characters in it. Hence a 9 grapheme character Thai string to your eyes becomes a 13 character string to Python.
The solution in French is to normalize the string based on Unicode [equivalence](http://en.wikipedia.org/wiki/Unicode_equivalence):
```
>>> from unicodedata import normalize
>>> normalize('NFC', s2) == s
True
```
That does not work for many non Latin languages though. An easy way to deal with unicode strings that may be multiple code points composing a [single grapheme](http://www.regular-expressions.info/unicode.html) is with a regex engine that correctly deals with this by supporting `\X`. Unfortunately Python's included `re` module [doesn't](http://bugs.python.org/issue12733) yet.
The proposed replacement, [regex](https://pypi.python.org/pypi/regex), does support `\X` though:
```
>>> import regex
>>> text = 'เมื่อแรกเริ่ม'
>>> regex.findall(r'\X', text)
['เ', 'มื่', 'อ', 'แ', 'ร', 'ก', 'เ', 'ริ่', 'ม']
>>> len(_)
9
```
|
I cannot exactly reproduce, but here is a slight modified version of you script, with the output on IDLE 3.4 on a Windows7 64 system :
```
>>> for char in text:
print(char, hex(ord(char)), unicodedata.name(char),'-',
unicodedata.category(char), '-', unicodedata.combining(char), '-',
unicodedata.east_asian_width(char))
เ 0xe40 THAI CHARACTER SARA E - Lo - 0 - N
ม 0xe21 THAI CHARACTER MO MA - Lo - 0 - N
ื 0xe37 THAI CHARACTER SARA UEE - Mn - 0 - N
่ 0xe48 THAI CHARACTER MAI EK - Mn - 107 - N
อ 0xe2d THAI CHARACTER O ANG - Lo - 0 - N
แ 0xe41 THAI CHARACTER SARA AE - Lo - 0 - N
ร 0xe23 THAI CHARACTER RO RUA - Lo - 0 - N
ก 0xe01 THAI CHARACTER KO KAI - Lo - 0 - N
เ 0xe40 THAI CHARACTER SARA E - Lo - 0 - N
ร 0xe23 THAI CHARACTER RO RUA - Lo - 0 - N
ิ 0xe34 THAI CHARACTER SARA I - Mn - 0 - N
่ 0xe48 THAI CHARACTER MAI EK - Mn - 107 - N
ม 0xe21 THAI CHARACTER MO MA - Lo - 0 - N
>>>
```
I really do not know what those characters can be - my Thai is **very** poor :-) - but it shows that :
* text is acknowledged to be Thai ...
* output is coherent with `len(text)` (`13`)
* category and combining are different when characters are combined
If it is expected output, it proves that your problem is not in Python but more on the *console* where you display it. You should try to redirect output to a file, and then open the file in an unicode editor supporting Thai characters.
If expected output is only 9 characters, that is if you do not want to decompose composed characters, and provided there are no other composing rules that should be considered, you could use something like :
```
def Thaidump(t):
old = None
for i in t:
if unicodedata.category(i) == 'Mn':
if old is not None:
old = old + i
else:
if old is not None:
print(old)
old = i
print(old)
```
That way :
```
>>> Thaidump(text)
เ
มื่
อ
แ
ร
ก
เ
ริ่
ม
>>>
```
|
30,103,965
|
Not by word boundaries, that is solvable.
Example:
```
#!/usr/bin/env python3
text = 'เมื่อแรกเริ่ม'
for char in text:
print(char)
```
This produces:
เ
ม
อ
แ
ร
ก
เ
ร
ม
Which obviously is not the desired output. Any ideas?
A portable representation of text is:
```
text = u'\u0e40\u0e21\u0e37\u0e48\u0e2d\u0e41\u0e23\u0e01\u0e40\u0e23\u0e34\u0e48\u0e21'
```
|
2015/05/07
|
[
"https://Stackoverflow.com/questions/30103965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2397101/"
] |
tl;dr: Use `\X` regular expression to extract user-perceived characters:
```
>>> import regex # $ pip install regex
>>> regex.findall(u'\\X', u'เมื่อแรกเริ่ม')
['เ', 'มื่', 'อ', 'แ', 'ร', 'ก', 'เ', 'ริ่', 'ม']
```
---
While I do not know Thai, I know a little French.
Consider the letter `è`. Let `s` and `s2` equal `è` in the Python shell:
```
>>> s
'è'
>>> s2
'è'
```
Same letter? To a French speaker visually, oui. To a computer, no:
```
>>> s==s2
False
```
You can create the same letter either using the actual code point for `è` or by taking the letter `e` and adding a combining code point that adds that accent character. They have different encodings:
```
>>> s.encode('utf-8')
b'\xc3\xa8'
>>> s2.encode('utf-8')
b'e\xcc\x80'
```
And differnet lengths:
```
>>> len(s)
1
>>> len(s2)
2
```
But visually both encodings result in the 'letter' `è`. This is called a [grapheme](http://en.wikipedia.org/wiki/Grapheme), or what the end user considers one character.
You can demonstrate the same looping behavior you are seeing:
```
>>> [c for c in s]
['è']
>>> [c for c in s2]
['e', '̀']
```
Your string has several combining characters in it. Hence a 9 grapheme character Thai string to your eyes becomes a 13 character string to Python.
The solution in French is to normalize the string based on Unicode [equivalence](http://en.wikipedia.org/wiki/Unicode_equivalence):
```
>>> from unicodedata import normalize
>>> normalize('NFC', s2) == s
True
```
That does not work for many non Latin languages though. An easy way to deal with unicode strings that may be multiple code points composing a [single grapheme](http://www.regular-expressions.info/unicode.html) is with a regex engine that correctly deals with this by supporting `\X`. Unfortunately Python's included `re` module [doesn't](http://bugs.python.org/issue12733) yet.
The proposed replacement, [regex](https://pypi.python.org/pypi/regex), does support `\X` though:
```
>>> import regex
>>> text = 'เมื่อแรกเริ่ม'
>>> regex.findall(r'\X', text)
['เ', 'มื่', 'อ', 'แ', 'ร', 'ก', 'เ', 'ริ่', 'ม']
>>> len(_)
9
```
|
For clarification of the previous answers, the issue you have is that the missing characters are "combining characters" - vowels and diacritics that must be combined with other characters in order to be displayed properly. There is no standard way to display these characters by themselves, although the most common convention is to use a dotted circle as a null consonant as shown in the answer by Serge Ballesta.
The question is then, for your application are each vowel and diacritic considered a separate character or do you wish to separate by "print cell" as shown in Serge's answer ?
By the way, in normal usage the lead vowels SARA E and SARA AE should not be displayed without a following consonant except in the process of typing a longer word.
For more information, see the WTT 2.0 standard published by the Thai API Consortium (TAPIC) which defines how characters can be combined, displayed and how to cope with errors.
|
20,294,693
|
In the following example, I want to change the `a1` key of `d` in place by calling the `set_x()` function of the class `A`. But I don't see how to access a key in a `dict`.
```
#!/usr/bin/env python
class A(object):
def __init__(self, data=''):
self.data = data
self.x = ''
def set_x(self, x):
self.x = x
def __repr__(self):
return 'A(%s:%s)' % (self.data, self.x)
def __eq__(self, another):
return hasattr(another, 'data') and self.data == another.data
def __hash__(self):
return hash(self.data)
a1 = A('foo')
d = {a1: 'foo'}
print d #{A(foo:): 'foo'}
```
I want to change `d`, so that `d` will print as `{A(foo:word): 'foo'}`. Of course, the following does not work. Also I don't want to reassign the same values. Does anybody know a way to modify a key in place by the calling the key's member function? Thanks.
```
a2 = A('foo')
a2.set_x('xxxx')
d[a2]='foo'
print d
```
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20294693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1424739/"
] |
You need to refer to the object itself, and modify it there.
Take a look at this console session:
```
>>> a = A("foo")
>>> d = {a:10}
>>> d
{A(foo:): 10}
>>> a.set_x('word')
>>> d
{A(foo:word): 10}
```
You can also get the key-value pair from `dict.items()`:
```
a, v = d.items()[0]
a.set_x("word")
```
Hope this helps!
|
You can keep the reference to the object and modify it. If you can't keep a reference to the key object, you can still iterate over the dict using `for k, v in d.items():` and then use the value to know which key you have (although this is somewhat backward in how to use a dict and highly ineficient)
```
a1 = A('foo')
d = {a1: 'foo'}
print(d) # {A(foo:): 'foo'}
a1.set_x('hello')
print(d) # {A(foo:hello): 'foo'}
```
|
59,876,292
|
I want to run gs command to copy data using python function in cloud function, is it possible to run a shell command inside the cloud function??.
|
2020/01/23
|
[
"https://Stackoverflow.com/questions/59876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12309624/"
] |
According to the official documentation [Cloud Functions Execution Environment](https://cloud.google.com/functions/docs/concepts/exec):
>
> Cloud Functions run in a fully-managed, serverless environment where
> Google handles infrastructure, operating systems, and runtime
> environments completely on your behalf. Each Cloud Function runs in
> its own isolated secure execution context, scales automatically, and
> has a lifecycle independent from other functions.
>
>
>
These are the runtimes that cloud functions supports:
```
Node.js 8, Node.js 10 (Beta), Python, Go 1.11, Go 1.13
```
Currently, it is not possible to run shell commands inside a Google Cloud Function.
However, assuming you would like to copy data to or from Cloud Storage, you can use [Cloud Storage Client Libraries for Python](https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-python)
|
Have tried using [subprocess](https://docs.python.org/3/library/subprocess.html) module to see if it helps you achieve what you need? I haven't tried this myself so I can't be sure if it will work.
```
import subprocess
subprocess.run(["ls", "-l"])
```
Alternatively you can also use CloudRun to run [Docker image with gcloud sdk](https://github.com/GoogleCloudPlatform/cloud-sdk-docker) which could help you execute shell commands directly (rather than going via python).
|
59,876,292
|
I want to run gs command to copy data using python function in cloud function, is it possible to run a shell command inside the cloud function??.
|
2020/01/23
|
[
"https://Stackoverflow.com/questions/59876292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12309624/"
] |
According to the official documentation [Cloud Functions Execution Environment](https://cloud.google.com/functions/docs/concepts/exec):
>
> Cloud Functions run in a fully-managed, serverless environment where
> Google handles infrastructure, operating systems, and runtime
> environments completely on your behalf. Each Cloud Function runs in
> its own isolated secure execution context, scales automatically, and
> has a lifecycle independent from other functions.
>
>
>
These are the runtimes that cloud functions supports:
```
Node.js 8, Node.js 10 (Beta), Python, Go 1.11, Go 1.13
```
Currently, it is not possible to run shell commands inside a Google Cloud Function.
However, assuming you would like to copy data to or from Cloud Storage, you can use [Cloud Storage Client Libraries for Python](https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-python)
|
To interact with Google APIs from a Cloud function(Python runtime), shell command is not the ideal choice.
Google Cloud Platform has [Python libraries](https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-python) to interact with its service and I suggest to you them.
Sample Python code to list the objects in a GCS Bucket
```
from google.cloud import storage
bucket_name = "gcs-bucket-name"
gcs_client = storage.Client()
gcs_objects = gcs_client.list_blobs(bucket_name)
for obj in gcs_objects:
print(obj.name)
```
|
26,292,102
|
Because of inherited html parts when using template engines such as twig (PHP) or jinja2 (python), I may need to nest rows like below:
```
<div class="container">
<div class="row">
<div class="row">
</div>
...
<div class="row">
</div>
</div>
<div class="row">
...
</div>
</div>
```
Then should I wrap inner rows in column div like below:
```
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="row">
</div>
...
<div class="row">
</div>
</div>
</div>
<div class="row">
...
</div>
</div>
```
Or should they be wrappered in container again?
|
2014/10/10
|
[
"https://Stackoverflow.com/questions/26292102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85443/"
] |
You shouldn't wrap the nested rows in `.container` elements, but you *should* nest them in columns. Bootstrap's `row` class has negative left and right margins that are negated by the `col-X` classes' positive left and right margins. If you nest two `row` classes without intermediate `col-X` classes, you get double the negative margins.
This example demonstrates the double negative margins:
```html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<!-- GOOD! Second "row" wrapped in "col" to negate negative margins. -->
<div class="container">
<div class="row">
<div class="col-xs-12" style="background: lime;">
<div class="row">
Here's my text!
</div>
</div>
</div>
</div>
<!-- BAD! Second "row" missing wrapping "col", gets double negative margins -->
<div class="container">
<div class="row">
<div class="row" style="background: tomato;">
Where's my text?
</div>
</div>
</div>
```
For further reading, [The Subtle Magic Behind Why the Bootstrap 3 Grid Works](http://www.helloerik.com/the-subtle-magic-behind-why-the-bootstrap-3-grid-works) explains the column system in great and interesting detai.
|
You shouldn't wrap them in another [container](http://getbootstrap.com/css/#grid) - containers are designed for a typical one-page layout. Unless it would look good / work well with your layout, you may want to look into `container-fluid` if you really want to do this.
**tl;dr** don't wrap in another container.
|
30,631,299
|
First i'm developing a django app, when i try to run the server with:
python manage.py runserver 0.0.0.0:8000
The terminal shows:
```
"django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb"
```
So, i need to install that package:
```
(app1)Me% pip install MySQL-python
```
Errors:
```
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: mysql-python
Running setup.py bdist_wheel for mysql-python
Complete output from command /Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/tmp1JfTpfpip-wheel-:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.5-intel-2.7
copying _mysql_exceptions.py -> build/lib.macosx-10.5-intel-2.7
creating build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
creating build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.5-intel-2.7
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Qunused-arguments -Qunused-arguments -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.6.23/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.5-intel-2.7/_mysql.o -g -fno-omit-frame-pointer -fno-strict-aliasing
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined
#define SIZEOF_SIZE_T SIZEOF_LONG
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:43:17: note: previous definition is here
# define SIZEOF_SIZE_T 8
^
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined
#define HAVE_WCSCOLL
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:911:9: note: previous definition is here
#define HAVE_WCSCOLL 1
^
_mysql.c:1589:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
if (how < 0 || how >= sizeof(row_converters)) {
~~~ ^ ~
3 warnings generated.
gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot / -Qunused-arguments -Qunused-arguments build/temp.macosx-10.5-intel-2.7/_mysql.o -L/usr/local/Cellar/mysql/5.6.23/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.5-intel-2.7/_mysql.so
ld: library not found for -lbundle1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'gcc' failed with exit status 1
----------------------------------------
Failed building wheel for mysql-python
Failed to build mysql-python
Installing collected packages: mysql-python
Running setup.py install for mysql-python
Complete output from command /Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-YOrOKA-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/GFTecla/Documents/shoutout/bin/../include/site/python2.7/mysql-python:
running install
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
running build_ext
building '_mysql' extension
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Qunused-arguments -Qunused-arguments -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.6.23/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.5-intel-2.7/_mysql.o -g -fno-omit-frame-pointer -fno-strict-aliasing
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined
#define SIZEOF_SIZE_T SIZEOF_LONG
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:43:17: note: previous definition is here
# define SIZEOF_SIZE_T 8
^
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined
#define HAVE_WCSCOLL
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:911:9: note: previous definition is here
#define HAVE_WCSCOLL 1
^
_mysql.c:1589:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
if (how < 0 || how >= sizeof(row_converters)) {
~~~ ^ ~
3 warnings generated.
gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot / -Qunused-arguments -Qunused-arguments build/temp.macosx-10.5-intel-2.7/_mysql.o -L/usr/local/Cellar/mysql/5.6.23/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.5-intel-2.7/_mysql.so
ld: library not found for -lbundle1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-YOrOKA-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/GFTecla/Documents/shoutout/bin/../include/site/python2.7/mysql-python" failed with error code 1 in /private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python
```
I have OS X 10.10.2
Django 1.8.2
Python 2.7
|
2015/06/03
|
[
"https://Stackoverflow.com/questions/30631299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2544076/"
] |
The solution was in reinstalling the developer tools:
```
xcode-select --install
```
|
What fixed it for me was:
`sudo pip install --upgrade setuptools`
Make sure you have mysql installed:
```
brew install mysql
```
|
30,631,299
|
First i'm developing a django app, when i try to run the server with:
python manage.py runserver 0.0.0.0:8000
The terminal shows:
```
"django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb"
```
So, i need to install that package:
```
(app1)Me% pip install MySQL-python
```
Errors:
```
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: mysql-python
Running setup.py bdist_wheel for mysql-python
Complete output from command /Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/tmp1JfTpfpip-wheel-:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.5-intel-2.7
copying _mysql_exceptions.py -> build/lib.macosx-10.5-intel-2.7
creating build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
creating build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.5-intel-2.7
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Qunused-arguments -Qunused-arguments -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.6.23/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.5-intel-2.7/_mysql.o -g -fno-omit-frame-pointer -fno-strict-aliasing
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined
#define SIZEOF_SIZE_T SIZEOF_LONG
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:43:17: note: previous definition is here
# define SIZEOF_SIZE_T 8
^
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined
#define HAVE_WCSCOLL
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:911:9: note: previous definition is here
#define HAVE_WCSCOLL 1
^
_mysql.c:1589:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
if (how < 0 || how >= sizeof(row_converters)) {
~~~ ^ ~
3 warnings generated.
gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot / -Qunused-arguments -Qunused-arguments build/temp.macosx-10.5-intel-2.7/_mysql.o -L/usr/local/Cellar/mysql/5.6.23/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.5-intel-2.7/_mysql.so
ld: library not found for -lbundle1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'gcc' failed with exit status 1
----------------------------------------
Failed building wheel for mysql-python
Failed to build mysql-python
Installing collected packages: mysql-python
Running setup.py install for mysql-python
Complete output from command /Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-YOrOKA-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/GFTecla/Documents/shoutout/bin/../include/site/python2.7/mysql-python:
running install
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
running build_ext
building '_mysql' extension
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Qunused-arguments -Qunused-arguments -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.6.23/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.5-intel-2.7/_mysql.o -g -fno-omit-frame-pointer -fno-strict-aliasing
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined
#define SIZEOF_SIZE_T SIZEOF_LONG
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:43:17: note: previous definition is here
# define SIZEOF_SIZE_T 8
^
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined
#define HAVE_WCSCOLL
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:911:9: note: previous definition is here
#define HAVE_WCSCOLL 1
^
_mysql.c:1589:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
if (how < 0 || how >= sizeof(row_converters)) {
~~~ ^ ~
3 warnings generated.
gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot / -Qunused-arguments -Qunused-arguments build/temp.macosx-10.5-intel-2.7/_mysql.o -L/usr/local/Cellar/mysql/5.6.23/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.5-intel-2.7/_mysql.so
ld: library not found for -lbundle1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-YOrOKA-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/GFTecla/Documents/shoutout/bin/../include/site/python2.7/mysql-python" failed with error code 1 in /private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python
```
I have OS X 10.10.2
Django 1.8.2
Python 2.7
|
2015/06/03
|
[
"https://Stackoverflow.com/questions/30631299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2544076/"
] |
The solution was in reinstalling the developer tools:
```
xcode-select --install
```
|
Based on [a solution to a seemingly unrelated problem](https://github.com/SOHU-Co/kafka-node/issues/881#issuecomment-377109841), I was able to solve the problem here by running `brew doctor` and cleaning up all the stray header files it called out.
|
30,631,299
|
First i'm developing a django app, when i try to run the server with:
python manage.py runserver 0.0.0.0:8000
The terminal shows:
```
"django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb"
```
So, i need to install that package:
```
(app1)Me% pip install MySQL-python
```
Errors:
```
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: mysql-python
Running setup.py bdist_wheel for mysql-python
Complete output from command /Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/tmp1JfTpfpip-wheel-:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.5-intel-2.7
copying _mysql_exceptions.py -> build/lib.macosx-10.5-intel-2.7
creating build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
creating build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.macosx-10.5-intel-2.7
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Qunused-arguments -Qunused-arguments -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.6.23/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.5-intel-2.7/_mysql.o -g -fno-omit-frame-pointer -fno-strict-aliasing
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined
#define SIZEOF_SIZE_T SIZEOF_LONG
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:43:17: note: previous definition is here
# define SIZEOF_SIZE_T 8
^
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined
#define HAVE_WCSCOLL
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:911:9: note: previous definition is here
#define HAVE_WCSCOLL 1
^
_mysql.c:1589:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
if (how < 0 || how >= sizeof(row_converters)) {
~~~ ^ ~
3 warnings generated.
gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot / -Qunused-arguments -Qunused-arguments build/temp.macosx-10.5-intel-2.7/_mysql.o -L/usr/local/Cellar/mysql/5.6.23/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.5-intel-2.7/_mysql.so
ld: library not found for -lbundle1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'gcc' failed with exit status 1
----------------------------------------
Failed building wheel for mysql-python
Failed to build mysql-python
Installing collected packages: mysql-python
Running setup.py install for mysql-python
Complete output from command /Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-YOrOKA-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/GFTecla/Documents/shoutout/bin/../include/site/python2.7/mysql-python:
running install
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.5-intel-2.7/MySQLdb
running build_ext
building '_mysql' extension
gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Qunused-arguments -Qunused-arguments -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.6.23/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.5-intel-2.7/_mysql.o -g -fno-omit-frame-pointer -fno-strict-aliasing
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:348:11: warning: 'SIZEOF_SIZE_T' macro redefined
#define SIZEOF_SIZE_T SIZEOF_LONG
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:43:17: note: previous definition is here
# define SIZEOF_SIZE_T 8
^
In file included from _mysql.c:44:
/usr/local/Cellar/mysql/5.6.23/include/mysql/my_config.h:442:9: warning: 'HAVE_WCSCOLL' macro redefined
#define HAVE_WCSCOLL
^
/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h:911:9: note: previous definition is here
#define HAVE_WCSCOLL 1
^
_mysql.c:1589:10: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
if (how < 0 || how >= sizeof(row_converters)) {
~~~ ^ ~
3 warnings generated.
gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot / -Qunused-arguments -Qunused-arguments build/temp.macosx-10.5-intel-2.7/_mysql.o -L/usr/local/Cellar/mysql/5.6.23/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.5-intel-2.7/_mysql.so
ld: library not found for -lbundle1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/Users/GFTecla/Documents/shoutout/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-YOrOKA-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/GFTecla/Documents/shoutout/bin/../include/site/python2.7/mysql-python" failed with error code 1 in /private/var/folders/9g/1qrws9yj3wn7lghlrpgyh9cc0000gn/T/pip-build-ZMQOQm/mysql-python
```
I have OS X 10.10.2
Django 1.8.2
Python 2.7
|
2015/06/03
|
[
"https://Stackoverflow.com/questions/30631299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2544076/"
] |
What fixed it for me was:
`sudo pip install --upgrade setuptools`
Make sure you have mysql installed:
```
brew install mysql
```
|
Based on [a solution to a seemingly unrelated problem](https://github.com/SOHU-Co/kafka-node/issues/881#issuecomment-377109841), I was able to solve the problem here by running `brew doctor` and cleaning up all the stray header files it called out.
|
69,685,355
|
I'm sorry if that didn't make any sense! I'm very new to python and I could really use some help.
I don't want the question to be solved for me, but I would appreciate some advice as a starting point.
```
listA = [("Aleah", [74, 100, 120, 67]),
("Hannah", [95, 110, 110, 67]),
("Timothy", [71, 111, 98, 106])]
```
Essentially I need to find which person has the fastest average driving speed and then print their name.
How do I calculate the average of the second element in the list (also a list) while keeping it associated with the first element in the list (their name).
I don't even know where to begin, so any advice would be much appreciated. Thank you!
|
2021/10/23
|
[
"https://Stackoverflow.com/questions/69685355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17225072/"
] |
You put your listelement inside the same container - so expanding the list would also expand everything.
You can put your listelement outside and/or give it an absolute position.
Minimal changes can be found here: [codepen](https://codepen.io/coyer/pen/KKvapbv)
Basically I wrapped the inputfield in a relative-positioned wrapper to keep that position; then I changed ul to `position:absolute`.
|
Try This
--------
---
```
ul {
max-height: 250px;
overflow-y: scroll;
}
```
|
69,685,355
|
I'm sorry if that didn't make any sense! I'm very new to python and I could really use some help.
I don't want the question to be solved for me, but I would appreciate some advice as a starting point.
```
listA = [("Aleah", [74, 100, 120, 67]),
("Hannah", [95, 110, 110, 67]),
("Timothy", [71, 111, 98, 106])]
```
Essentially I need to find which person has the fastest average driving speed and then print their name.
How do I calculate the average of the second element in the list (also a list) while keeping it associated with the first element in the list (their name).
I don't even know where to begin, so any advice would be much appreciated. Thank you!
|
2021/10/23
|
[
"https://Stackoverflow.com/questions/69685355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17225072/"
] |
Try This
--------
---
```
ul {
max-height: 250px;
overflow-y: scroll;
}
```
|
it is better use another Units for declaring height.
"vh" unit can make some problems specially in mobile devices.
```
and also use
ul{
overflow-y: scroll;
}
```
|
69,685,355
|
I'm sorry if that didn't make any sense! I'm very new to python and I could really use some help.
I don't want the question to be solved for me, but I would appreciate some advice as a starting point.
```
listA = [("Aleah", [74, 100, 120, 67]),
("Hannah", [95, 110, 110, 67]),
("Timothy", [71, 111, 98, 106])]
```
Essentially I need to find which person has the fastest average driving speed and then print their name.
How do I calculate the average of the second element in the list (also a list) while keeping it associated with the first element in the list (their name).
I don't even know where to begin, so any advice would be much appreciated. Thank you!
|
2021/10/23
|
[
"https://Stackoverflow.com/questions/69685355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17225072/"
] |
You put your listelement inside the same container - so expanding the list would also expand everything.
You can put your listelement outside and/or give it an absolute position.
Minimal changes can be found here: [codepen](https://codepen.io/coyer/pen/KKvapbv)
Basically I wrapped the inputfield in a relative-positioned wrapper to keep that position; then I changed ul to `position:absolute`.
|
This behaviour is because your body's `display:flex` and you have applied `justify-content:space-evenly`. Which automatically adjust the available space between elements. When the suggestions' list appears, it increases the size of your select element and occupies more space on the screen which eventually appears to move upwards.
Modify you `CSS` like this, this will solve your problem.
```
body {
display: flex;
flex-direction: column;
align-items: center;
position: relative; //So you can specify childrens' absolute position
min-height: 100vh;font-family: 'Urbanist', sans-serif;
text-transform: uppercase;
font-size: 1.3rem;
background-image: linear-gradient(to left top, #051937, #4d295a, #983461, #d2524d, #e98c27);
}
form {
min-height: 50vh;
transition: all 0.7s linear;
display: flex;
flex-direction: column;
justify-content: space-evenly;
border: 0 2px 0 0 solid black;
width: 20rem;
padding: 10%;
margin:auto;
flex-wrap: wrap;
background-color: #e9ac67;
}
header {
margin-top: 50px;
}
main {
position: relative;
top: 50px;
}
```
|
69,685,355
|
I'm sorry if that didn't make any sense! I'm very new to python and I could really use some help.
I don't want the question to be solved for me, but I would appreciate some advice as a starting point.
```
listA = [("Aleah", [74, 100, 120, 67]),
("Hannah", [95, 110, 110, 67]),
("Timothy", [71, 111, 98, 106])]
```
Essentially I need to find which person has the fastest average driving speed and then print their name.
How do I calculate the average of the second element in the list (also a list) while keeping it associated with the first element in the list (their name).
I don't even know where to begin, so any advice would be much appreciated. Thank you!
|
2021/10/23
|
[
"https://Stackoverflow.com/questions/69685355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17225072/"
] |
You put your listelement inside the same container - so expanding the list would also expand everything.
You can put your listelement outside and/or give it an absolute position.
Minimal changes can be found here: [codepen](https://codepen.io/coyer/pen/KKvapbv)
Basically I wrapped the inputfield in a relative-positioned wrapper to keep that position; then I changed ul to `position:absolute`.
|
it is better use another Units for declaring height.
"vh" unit can make some problems specially in mobile devices.
```
and also use
ul{
overflow-y: scroll;
}
```
|
69,685,355
|
I'm sorry if that didn't make any sense! I'm very new to python and I could really use some help.
I don't want the question to be solved for me, but I would appreciate some advice as a starting point.
```
listA = [("Aleah", [74, 100, 120, 67]),
("Hannah", [95, 110, 110, 67]),
("Timothy", [71, 111, 98, 106])]
```
Essentially I need to find which person has the fastest average driving speed and then print their name.
How do I calculate the average of the second element in the list (also a list) while keeping it associated with the first element in the list (their name).
I don't even know where to begin, so any advice would be much appreciated. Thank you!
|
2021/10/23
|
[
"https://Stackoverflow.com/questions/69685355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17225072/"
] |
This behaviour is because your body's `display:flex` and you have applied `justify-content:space-evenly`. Which automatically adjust the available space between elements. When the suggestions' list appears, it increases the size of your select element and occupies more space on the screen which eventually appears to move upwards.
Modify you `CSS` like this, this will solve your problem.
```
body {
display: flex;
flex-direction: column;
align-items: center;
position: relative; //So you can specify childrens' absolute position
min-height: 100vh;font-family: 'Urbanist', sans-serif;
text-transform: uppercase;
font-size: 1.3rem;
background-image: linear-gradient(to left top, #051937, #4d295a, #983461, #d2524d, #e98c27);
}
form {
min-height: 50vh;
transition: all 0.7s linear;
display: flex;
flex-direction: column;
justify-content: space-evenly;
border: 0 2px 0 0 solid black;
width: 20rem;
padding: 10%;
margin:auto;
flex-wrap: wrap;
background-color: #e9ac67;
}
header {
margin-top: 50px;
}
main {
position: relative;
top: 50px;
}
```
|
it is better use another Units for declaring height.
"vh" unit can make some problems specially in mobile devices.
```
and also use
ul{
overflow-y: scroll;
}
```
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
We usually use `$ python3 -m venv myvenv` to create a new virtualenv (Here `myvenv` is the name of our virtualenv).
Similar to my case, if you have both `python3.5` as well as `python3.6` on your system, then you might get some errors.
**NOTE:** On some versions of Debian/Ubuntu you may receive the following error:
```
The virtual environment was not created successfully because ensure pip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command.
apt-get installpython3-venv
You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment.
```
In this case, follow the instructions above and install the python3-venv package:
```
$ sudo apt-get install python3-venv
```
**NOTE:** On some versions of Debian/Ubuntu initiating the virtual environment like this currently gives the following error:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
To get around this, use the virtualenv command instead.
```
$ sudo apt-get install python-virtualenv
$ virtualenv --python=python3.6 myvenv
```
**NOTE:** If you get an error like
>
> E: Unable to locate package python3-venv
>
>
>
then instead run:
```
sudo apt install python3.6-venv
```
|
Installing `python3.6` and `python3.6-venv` via `ppa:deadsnakes/ppa` instead of `ppa:jonathonf/python-3.6` worked for me
```
apt-get update \
&& apt-get install -y software-properties-common curl \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y python3.6 python3.6-venv
```
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
We usually use `$ python3 -m venv myvenv` to create a new virtualenv (Here `myvenv` is the name of our virtualenv).
Similar to my case, if you have both `python3.5` as well as `python3.6` on your system, then you might get some errors.
**NOTE:** On some versions of Debian/Ubuntu you may receive the following error:
```
The virtual environment was not created successfully because ensure pip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command.
apt-get installpython3-venv
You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment.
```
In this case, follow the instructions above and install the python3-venv package:
```
$ sudo apt-get install python3-venv
```
**NOTE:** On some versions of Debian/Ubuntu initiating the virtual environment like this currently gives the following error:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
To get around this, use the virtualenv command instead.
```
$ sudo apt-get install python-virtualenv
$ virtualenv --python=python3.6 myvenv
```
**NOTE:** If you get an error like
>
> E: Unable to locate package python3-venv
>
>
>
then instead run:
```
sudo apt install python3.6-venv
```
|
I think that a problem could be related to the wrong locale.
I added to the `/etc/environment` the following lines to fix it:
```
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
```
You need to source the file from you bash with this command:
```
source /etc/environment
```
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
We usually use `$ python3 -m venv myvenv` to create a new virtualenv (Here `myvenv` is the name of our virtualenv).
Similar to my case, if you have both `python3.5` as well as `python3.6` on your system, then you might get some errors.
**NOTE:** On some versions of Debian/Ubuntu you may receive the following error:
```
The virtual environment was not created successfully because ensure pip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command.
apt-get installpython3-venv
You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment.
```
In this case, follow the instructions above and install the python3-venv package:
```
$ sudo apt-get install python3-venv
```
**NOTE:** On some versions of Debian/Ubuntu initiating the virtual environment like this currently gives the following error:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
To get around this, use the virtualenv command instead.
```
$ sudo apt-get install python-virtualenv
$ virtualenv --python=python3.6 myvenv
```
**NOTE:** If you get an error like
>
> E: Unable to locate package python3-venv
>
>
>
then instead run:
```
sudo apt install python3.6-venv
```
|
First make sure you have python3.6 installed, otherwise you can install it with command:
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install python3.6
```
Now install venv i.e
```
sudo apt-get install python3.6-venv python3.6-dev
python3.6 -m venv venv_name
```
You can install python3.7/3.8 and also respective venv with above comman, just replace 3.6 with 3.X
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
We usually use `$ python3 -m venv myvenv` to create a new virtualenv (Here `myvenv` is the name of our virtualenv).
Similar to my case, if you have both `python3.5` as well as `python3.6` on your system, then you might get some errors.
**NOTE:** On some versions of Debian/Ubuntu you may receive the following error:
```
The virtual environment was not created successfully because ensure pip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command.
apt-get installpython3-venv
You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment.
```
In this case, follow the instructions above and install the python3-venv package:
```
$ sudo apt-get install python3-venv
```
**NOTE:** On some versions of Debian/Ubuntu initiating the virtual environment like this currently gives the following error:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
To get around this, use the virtualenv command instead.
```
$ sudo apt-get install python-virtualenv
$ virtualenv --python=python3.6 myvenv
```
**NOTE:** If you get an error like
>
> E: Unable to locate package python3-venv
>
>
>
then instead run:
```
sudo apt install python3.6-venv
```
|
if you get following irritating error:
```
E: Unable to locate package python3-venv
```
try this commands:
```
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6
```
those worked for me.hope it helps !
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
Installing `python3.6` and `python3.6-venv` via `ppa:deadsnakes/ppa` instead of `ppa:jonathonf/python-3.6` worked for me
```
apt-get update \
&& apt-get install -y software-properties-common curl \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y python3.6 python3.6-venv
```
|
I think that a problem could be related to the wrong locale.
I added to the `/etc/environment` the following lines to fix it:
```
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
```
You need to source the file from you bash with this command:
```
source /etc/environment
```
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
Installing `python3.6` and `python3.6-venv` via `ppa:deadsnakes/ppa` instead of `ppa:jonathonf/python-3.6` worked for me
```
apt-get update \
&& apt-get install -y software-properties-common curl \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y python3.6 python3.6-venv
```
|
if you get following irritating error:
```
E: Unable to locate package python3-venv
```
try this commands:
```
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6
```
those worked for me.hope it helps !
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
First make sure you have python3.6 installed, otherwise you can install it with command:
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install python3.6
```
Now install venv i.e
```
sudo apt-get install python3.6-venv python3.6-dev
python3.6 -m venv venv_name
```
You can install python3.7/3.8 and also respective venv with above comman, just replace 3.6 with 3.X
|
I think that a problem could be related to the wrong locale.
I added to the `/etc/environment` the following lines to fix it:
```
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
```
You need to source the file from you bash with this command:
```
source /etc/environment
```
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
I think that a problem could be related to the wrong locale.
I added to the `/etc/environment` the following lines to fix it:
```
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
```
You need to source the file from you bash with this command:
```
source /etc/environment
```
|
if you get following irritating error:
```
E: Unable to locate package python3-venv
```
try this commands:
```
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6
```
those worked for me.hope it helps !
|
47,822,740
|
I'm using Ubuntu 16.04, which comes with Python 2.7 and Python 3.5. I've installed Python 3.6 on it and symlink python3 to python3.6 through `alias python3=python3.6`.
Then, I've installed `virtualenv` using `sudo -H pip3 install virtualenv`. When I checked, the virtualenv got installed in `"/usr/local/lib/python3.5/dist-packages"` location, so when I'm trying to create virtualenv using `python3 -m venv ./venv1` it's throwing me errors:
```
Error Command: ['/home/wgetdj/WorkPlace/Programming/Python/myvenv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']
```
What should I do?
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47822740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6609613/"
] |
First make sure you have python3.6 installed, otherwise you can install it with command:
```
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt install python3.6
```
Now install venv i.e
```
sudo apt-get install python3.6-venv python3.6-dev
python3.6 -m venv venv_name
```
You can install python3.7/3.8 and also respective venv with above comman, just replace 3.6 with 3.X
|
if you get following irritating error:
```
E: Unable to locate package python3-venv
```
try this commands:
```
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6
```
those worked for me.hope it helps !
|
14,110,709
|
Using the python library matplotlib, I've found what suggests to be a solution to this question:
[Displaying (nicely) an algebraic expression in PyQt](https://stackoverflow.com/questions/14097463/displaying-nicely-an-algebraic-expression-in-pyqt) by utilising matplotlibs [TeX markup](http://matplotlib.org/users/mathtext.html).
What I'd like to do is take TeX code from my python program which represents a mathematical expression, and save it to an image that can be displayed in my PyQt GUI, rather than displaying the equation in ugly plain text.
Something like this essentially...
```
import matplotlib.pyplot as plt
formula = '$x=3^2$'
fig = plt.figure()
fig.text(0,0,formula)
fig.savefig('formula.png')
```
However, the pyplot module is primarily for displaying graphs and plots, not the samples of text like I need. The result of that code is usually a tiny bit of text in the bottom left corner of a huge, white, blank image.
If my formula involves fractions, and thus requires downward space, it is truncated, like in the image below.
**Note that this appears a blank image; look to the left side of the display**
[Fraction at coordinate (0,0) truncated and surrounded by whitespace](https://i.stack.imgur.com/gbxek.png)
I believe I could create a very large (space wise) figure, write the formula in the middle of the blank plot, save it, and use pixel analysis to trim it to as small an image as possible, but this seems rather crude.
Are plots the only intended output of matplotlib?
Is there nothing devoted to just outputting equations, that won't require me to worry about all the extra space or position of the text?
Thanks!
|
2013/01/01
|
[
"https://Stackoverflow.com/questions/14110709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/848292/"
] |
The trick is to render the text, then get its bounding box, and finally adjust the figure size and the vertical positioning of text in the new figure. This saves the figure twice, but as is common in any text engine, the correct bounding box and other parameters can only be correctly obtained after the text has been rendered.
```
import pylab
formula = r'$x=3^2, y = \frac{1}{\frac{2}{3}}, %s$' % ('test' * 20)
fig = pylab.figure()
text = fig.text(0, 0, formula)
# Saving the figure will render the text.
dpi = 300
fig.savefig('formula.png', dpi=dpi)
# Now we can work with text's bounding box.
bbox = text.get_window_extent()
width, height = bbox.size / float(dpi) + 0.005
# Adjust the figure size so it can hold the entire text.
fig.set_size_inches((width, height))
# Adjust text's vertical position.
dy = (bbox.ymin/float(dpi))/height
text.set_position((0, -dy))
# Save the adjusted text.
fig.savefig('formula.png', dpi=dpi)
```
The `0.005` constant was added to `width` and `height` because, apparently, for certain texts Matplotlib is returning a slightly underestimated bounding box, i.e., smaller than required.
|
what about
```
import matplotlib.pyplot as plt
params = {
'figure.figsize': [2,2],
}
plt.rcParams.update(params)
formula = r'$x=\frac{3}{100}$'
fig = plt.figure()
fig.text(0.5,0.5,formula)
plt.savefig('formula.png')
```
The first two arguments of the matplotlib text() function set the position of the text (between 0 & 1, so 0.5 for both gets your text in the middle.)
You can change all kinds of things like the font and text size by setting the rc parameters. See <http://matplotlib.org/users/customizing.html>. I've editted the rc params for figure size, but you can change the defaults so you don't have to do this every time.
|
14,110,709
|
Using the python library matplotlib, I've found what suggests to be a solution to this question:
[Displaying (nicely) an algebraic expression in PyQt](https://stackoverflow.com/questions/14097463/displaying-nicely-an-algebraic-expression-in-pyqt) by utilising matplotlibs [TeX markup](http://matplotlib.org/users/mathtext.html).
What I'd like to do is take TeX code from my python program which represents a mathematical expression, and save it to an image that can be displayed in my PyQt GUI, rather than displaying the equation in ugly plain text.
Something like this essentially...
```
import matplotlib.pyplot as plt
formula = '$x=3^2$'
fig = plt.figure()
fig.text(0,0,formula)
fig.savefig('formula.png')
```
However, the pyplot module is primarily for displaying graphs and plots, not the samples of text like I need. The result of that code is usually a tiny bit of text in the bottom left corner of a huge, white, blank image.
If my formula involves fractions, and thus requires downward space, it is truncated, like in the image below.
**Note that this appears a blank image; look to the left side of the display**
[Fraction at coordinate (0,0) truncated and surrounded by whitespace](https://i.stack.imgur.com/gbxek.png)
I believe I could create a very large (space wise) figure, write the formula in the middle of the blank plot, save it, and use pixel analysis to trim it to as small an image as possible, but this seems rather crude.
Are plots the only intended output of matplotlib?
Is there nothing devoted to just outputting equations, that won't require me to worry about all the extra space or position of the text?
Thanks!
|
2013/01/01
|
[
"https://Stackoverflow.com/questions/14110709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/848292/"
] |
The text in the figure can be placed correctly using `figure.suptitle` and specifying sensible alignments, such that the text sits in the top left corner and runs down and to the right (relative to the x and y coordinates specified).
```
fig = plt.Figure()
fig.suptitle('TeX',
horizontalalignment = 'left',
verticalalignment='top',
x=0.01, y = 0.99)
```
It can be wrapped in a Qt Widget, `FigureCanvasQTAgg` to be displayed in the program.
```
canvas = FigureCanvasQTAgg(fig) #Treated as QWidget
canvas.draw()
```
However, the canvas and figure remain no knowledge of the size of the text and so can still be too large and cause white-space, or be too small and cause truncation. This is fine for the purposes of my program, but doesn't satisfy the Question as mmgp's does.
|
what about
```
import matplotlib.pyplot as plt
params = {
'figure.figsize': [2,2],
}
plt.rcParams.update(params)
formula = r'$x=\frac{3}{100}$'
fig = plt.figure()
fig.text(0.5,0.5,formula)
plt.savefig('formula.png')
```
The first two arguments of the matplotlib text() function set the position of the text (between 0 & 1, so 0.5 for both gets your text in the middle.)
You can change all kinds of things like the font and text size by setting the rc parameters. See <http://matplotlib.org/users/customizing.html>. I've editted the rc params for figure size, but you can change the defaults so you don't have to do this every time.
|
14,110,709
|
Using the python library matplotlib, I've found what suggests to be a solution to this question:
[Displaying (nicely) an algebraic expression in PyQt](https://stackoverflow.com/questions/14097463/displaying-nicely-an-algebraic-expression-in-pyqt) by utilising matplotlibs [TeX markup](http://matplotlib.org/users/mathtext.html).
What I'd like to do is take TeX code from my python program which represents a mathematical expression, and save it to an image that can be displayed in my PyQt GUI, rather than displaying the equation in ugly plain text.
Something like this essentially...
```
import matplotlib.pyplot as plt
formula = '$x=3^2$'
fig = plt.figure()
fig.text(0,0,formula)
fig.savefig('formula.png')
```
However, the pyplot module is primarily for displaying graphs and plots, not the samples of text like I need. The result of that code is usually a tiny bit of text in the bottom left corner of a huge, white, blank image.
If my formula involves fractions, and thus requires downward space, it is truncated, like in the image below.
**Note that this appears a blank image; look to the left side of the display**
[Fraction at coordinate (0,0) truncated and surrounded by whitespace](https://i.stack.imgur.com/gbxek.png)
I believe I could create a very large (space wise) figure, write the formula in the middle of the blank plot, save it, and use pixel analysis to trim it to as small an image as possible, but this seems rather crude.
Are plots the only intended output of matplotlib?
Is there nothing devoted to just outputting equations, that won't require me to worry about all the extra space or position of the text?
Thanks!
|
2013/01/01
|
[
"https://Stackoverflow.com/questions/14110709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/848292/"
] |
The trick is to render the text, then get its bounding box, and finally adjust the figure size and the vertical positioning of text in the new figure. This saves the figure twice, but as is common in any text engine, the correct bounding box and other parameters can only be correctly obtained after the text has been rendered.
```
import pylab
formula = r'$x=3^2, y = \frac{1}{\frac{2}{3}}, %s$' % ('test' * 20)
fig = pylab.figure()
text = fig.text(0, 0, formula)
# Saving the figure will render the text.
dpi = 300
fig.savefig('formula.png', dpi=dpi)
# Now we can work with text's bounding box.
bbox = text.get_window_extent()
width, height = bbox.size / float(dpi) + 0.005
# Adjust the figure size so it can hold the entire text.
fig.set_size_inches((width, height))
# Adjust text's vertical position.
dy = (bbox.ymin/float(dpi))/height
text.set_position((0, -dy))
# Save the adjusted text.
fig.savefig('formula.png', dpi=dpi)
```
The `0.005` constant was added to `width` and `height` because, apparently, for certain texts Matplotlib is returning a slightly underestimated bounding box, i.e., smaller than required.
|
The text in the figure can be placed correctly using `figure.suptitle` and specifying sensible alignments, such that the text sits in the top left corner and runs down and to the right (relative to the x and y coordinates specified).
```
fig = plt.Figure()
fig.suptitle('TeX',
horizontalalignment = 'left',
verticalalignment='top',
x=0.01, y = 0.99)
```
It can be wrapped in a Qt Widget, `FigureCanvasQTAgg` to be displayed in the program.
```
canvas = FigureCanvasQTAgg(fig) #Treated as QWidget
canvas.draw()
```
However, the canvas and figure remain no knowledge of the size of the text and so can still be too large and cause white-space, or be too small and cause truncation. This is fine for the purposes of my program, but doesn't satisfy the Question as mmgp's does.
|
23,012,931
|
How to generate something like
```
[(), (1,), (1,2), (1,2,3)..., (1,2,3,...n)]
```
and
```
[(), (4,), (4,5), (4,5,6)..., (4,5,6,...m)]
```
then take the product of them and merge into
```
[(), (1,), (1,4), (1,4,5), (1,4,5,6), (1,2), (1,2,4)....(1,2,3,...n,4,5,6,...m)]
```
?
For the first two lists I've tried the powerset recipe in <https://docs.python.org/2/library/itertools.html#recipes> , but there will be something I don't want, like `(1,3), (2,3)`
For the product I've tested with `chain` and `product`, but I just can't merge the combinations of tuples into one.
Any idea how to do this nice and clean? Thanks!
|
2014/04/11
|
[
"https://Stackoverflow.com/questions/23012931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1886382/"
] |
Please note that, single element tuples are denoted like this `(1,)`.
```
a = [(), (1,), (1, 2), (1, 2, 3)]
b = [(), (4,), (4, 5), (4, 5, 6)]
from itertools import product
for item1, item2 in product(a, b):
print item1 + item2
```
**Output**
```
()
(4,)
(4, 5)
(4, 5, 6)
(1,)
(1, 4)
(1, 4, 5)
(1, 4, 5, 6)
(1, 2)
(1, 2, 4)
(1, 2, 4, 5)
(1, 2, 4, 5, 6)
(1, 2, 3)
(1, 2, 3, 4)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5, 6)
```
If you want them in a list, you can use list comprehension like this
```
from itertools import product
print [sum(items, ()) for items in product(a, b)]
```
Or even simpler,
```
print [items[0] + items[1] for items in product(a, b)]
```
|
If you don't want to use any special imports:
```
start = 1; limit = 10
[ range(start, start + x) for x in range(limit) ]
```
With `start = 1` the output is:
`[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8, 9]]`
If you want to take the product, maybe using `itertools` might be most elegant.
|
23,012,931
|
How to generate something like
```
[(), (1,), (1,2), (1,2,3)..., (1,2,3,...n)]
```
and
```
[(), (4,), (4,5), (4,5,6)..., (4,5,6,...m)]
```
then take the product of them and merge into
```
[(), (1,), (1,4), (1,4,5), (1,4,5,6), (1,2), (1,2,4)....(1,2,3,...n,4,5,6,...m)]
```
?
For the first two lists I've tried the powerset recipe in <https://docs.python.org/2/library/itertools.html#recipes> , but there will be something I don't want, like `(1,3), (2,3)`
For the product I've tested with `chain` and `product`, but I just can't merge the combinations of tuples into one.
Any idea how to do this nice and clean? Thanks!
|
2014/04/11
|
[
"https://Stackoverflow.com/questions/23012931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1886382/"
] |
Please note that, single element tuples are denoted like this `(1,)`.
```
a = [(), (1,), (1, 2), (1, 2, 3)]
b = [(), (4,), (4, 5), (4, 5, 6)]
from itertools import product
for item1, item2 in product(a, b):
print item1 + item2
```
**Output**
```
()
(4,)
(4, 5)
(4, 5, 6)
(1,)
(1, 4)
(1, 4, 5)
(1, 4, 5, 6)
(1, 2)
(1, 2, 4)
(1, 2, 4, 5)
(1, 2, 4, 5, 6)
(1, 2, 3)
(1, 2, 3, 4)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5, 6)
```
If you want them in a list, you can use list comprehension like this
```
from itertools import product
print [sum(items, ()) for items in product(a, b)]
```
Or even simpler,
```
print [items[0] + items[1] for items in product(a, b)]
```
|
You can try like this,
```
>>> a=[(), (1,), (1,2), (1,2,3)]
>>> b=[(), (4,), (4,5), (4,5,6)]
>>> for ix in a:
... for iy in b:
... print ix + iy
...
()
(4,)
(4, 5)
(4, 5, 6)
(1,)
(1, 4)
(1, 4, 5)
(1, 4, 5, 6)
(1, 2)
(1, 2, 4)
(1, 2, 4, 5)
(1, 2, 4, 5, 6)
(1, 2, 3)
(1, 2, 3, 4)
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5, 6)
```
|
15,920,413
|
I have a large ASCII file (~100GB) which consists of roughly 1.000.000 lines of known formatted numbers which I try to process with python. The file is too large to read in completely into memory, so I decided to process the file line by line:
```
fp = open(file_name)
for count,line in enumerate(fp):
data = np.array(line.split(),dtype=np.float)
#do stuff
fp.close()
```
It turns out, that I spend most of the run time of my program in the `data =` line. Are there any ways to speed up that line? Also, the execution speed seem much slower than what I could get from an native FORTRAN program with formated read (see this [question](https://stackoverflow.com/questions/15834327/strange-accuracy-difference-between-ipython-and-ipython-notebook-then-using-fort), I've implemented a FORTRAN string processor and used it with f2py, but the run time was only comparable with the `data =` line. I guess the I/O handling and type conversions between Python/FORTRAN killed what I gained from FORTRAN)
Since I know the formatting, shouldn't there be a better and faster way as to use `split()`? Something like:
```
data = readf(line,'(1000F20.10)')
```
I tried the [fortranformat](https://pypi.python.org/pypi/fortranformat) package, which worked well, but in my case was three times slower than thee `split()` approach.
P.S. As suggested by ExP and root I tried the np.fromstring and made this quick and dirtry benchmark:
```
t1 = time.time()
for i in range(500):
data=np.array(line.split(),dtype=np.float)
t2 = time.time()
print (t2-t1)/500
print data.shape
print data[0]
0.00160977363586
(9002,)
0.0015162509
```
and:
```
t1 = time.time()
for i in range(500):
data = np.fromstring(line,sep=' ',dtype=np.float,count=9002)
t2 = time.time()
print (t2-t1)/500
print data.shape
print data[0]
0.00159792804718
(9002,)
0.0015162509
```
so `fromstring` is in fact slightly slower in my case.
|
2013/04/10
|
[
"https://Stackoverflow.com/questions/15920413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2010845/"
] |
Have you tried [`numpyp.fromstring`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html)?
```
np.fromstring(line, dtype=np.float, sep=" ")
```
|
The [*np.genfromtxt*](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html) function is a speed champion if you can get it to match you input format.
If not, then you may already be using the fastest method. Your line-by-line split-into-array approach exactly matches the [SciPy Cookbook examples](http://www.scipy.org/Cookbook/InputOutput).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.