qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
66,636,134 | i have written a python program which makes an api call to a webserver once every minute and then parse the json response and saves parsed values in to the csv files.
here is the code that is saving the values into the csv file :
```
with open('data.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])
```
how can i make it so that it saves the header only once on the top most row and not on every row ?
**UPDATE:**
here is a bit of more code to make api call and write the data to file :
```
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
import requests
import json
import csv
from datetime import datetime
def fn():
print("Starting...")
session_id = "auZsJ4F2RsQNJxSPTMDt2238324"
Outlook='http://www.myfxbook.com/api/get-community-outlook.json?session=' + session_id
Outlook_response = requests.get(Outlook)
Outlook_data = Outlook_response.json()['symbols']
now = datetime.now()
current_time = now.strftime("%H:%M")
EURUSD=Outlook_data[0]
SHORTPERC=EURUSD['shortPercentage']
LONGPERC =EURUSD['longPercentage']
SHORTvolume=EURUSD['shortVolume']
longVolume=EURUSD['longVolume']
longPositions=EURUSD['longPositions']
shortPositions=EURUSD['shortPositions']
with open('data.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])
with open('data1.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([SHORTvolume, longVolume])
with open('data2.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([SHORTPERC, LONGPERC])
```
i cant post the full code cuz it will be very ugly since its around 700 lines long , but the above mentioned code should work to create the csv file
this is how one of my csv files look :
```
07:11,31,69,555.55,1265.14,4750,2607
07:12,31,69,555.55,1265.16,4751,2607
07:13,31,69,555.55,1265.16,4751,2607
07:14,30,70,555.56,1267.36,4752,2608
07:15,30,70,555.56,1267.36,4752,2608
07:16,30,70,555.56,1267.36,4752,2608
07:17,30,70,555.46,1267.36,4752,2607
07:18,31,69,558.61,1267.36,4752,2610
07:19,31,69,558.61,1267.37,4753,2610
07:20,31,69,561.58,1267.37,4753,2611
07:21,31,69,561.61,1267.37,4753,2613
07:22,31,69,561.65,1267.37,4753,2614
07:23,31,69,561.65,1267.36,4752,2614
```
this is just part of the csv file , more rows keep adding as time passes
**EDIT 2:**
answer suggested by Sparkofska seems to work but somehow it ends up giving an empty row in between every line like this:
>
> Time,ShortPer,LongPer,ShortVolume,LongVolume,ShortPosition,LongPosition
>
>
> 05:47,44,56,19528.8,24789.27,65223,48630
>
>
> 05:48,44,56,19529.04,24789.27,65223,48633
>
>
>
code :
```
EURUSD=Outlook_data[0]
SHORTPERC=EURUSD['shortPercentage']
LONGPERC =EURUSD['longPercentage']
SHORTvolume=EURUSD['shortVolume']
longVolume=EURUSD['longVolume']
longPositions=EURUSD['longPositions']
shortPositions=EURUSD['shortPositions']
filename='EURUSD.csv';
def write_row_header_aware(filename, row):
if not os.path.exists(filename) or os.stat(filename).st_size == 0:
with open(filename, 'a') as file:
writer = csv.writer(file)
writer.writerow(['Time', 'ShortPer', 'LongPer','ShortVolume','LongVolume','ShortPosition','LongPosition'])
with open(filename, 'a') as file:
writer = csv.writer(file)
writer.writerow([current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])
write_row_header_aware(filename, [current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])
print("done...")
``` | 2021/03/15 | [
"https://Stackoverflow.com/questions/66636134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15392786/"
] | The properties you've put on `<v-col>` don't exist (i.e. align-end and justify-end). They are properties on the `<v-row>` component (which is a flex container). You need to use classes instead.
Make sure to consult the API->props section on the Vuetify component page when choosing component properties.
Try
```html
<v-col class="d-flex justify-end">
<v-btn>Button</v-btn>
</v-col>
```
Note that the alignment is dependent upon the width of v-col. If v-col is only as wide as the button, you'll need to set the width by using the cols="x" property. | Add `direction: rtl` to your `v-btn`, Here is [codepen](https://codepen.io/MNSY22/pen/qBqWZEv):
```html
<template>
<v-btn class="btn rtl">
...
</v-btn>
</template>
<style>
.rtl { direction: rtl; }
</style>
``` |
29,711,646 | I'm trying to create examples on how to manipulate massive databases composed of CSV tables using only Python.
I'd like to find out a way to emulate efficient indexed queries in tables spread through some `list()`
The example below takes 24 seconds in a 3.2Ghz Core i5
```
#!/usr/bin/env python
import csv
MAINDIR = "../"
pf = open (MAINDIR+"atp_players.csv")
players = [p for p in csv.reader(pf)]
rf = open (MAINDIR+"atp_rankings_current.csv")
rankings = [r for r in csv.reader(rf)]
for i in rankings[:10]:
player = filter(lambda x: x[0]==i[2],players)[0]
print "%s(%s),(%s) Points: %s"%(player[2],player[5],player[3],i[3])
```
For [this dataset](https://github.com/JeffSackmann/tennis_atp).
A more efficient, or more *pythonic* way would be greatly appreciated. | 2015/04/18 | [
"https://Stackoverflow.com/questions/29711646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417415/"
] | You can `itertools.islice` instead of reading all rows and use `itertools.ifilter`:
```
import csv
from itertools import islice,ifilter
MAINDIR = "../"
with open(MAINDIR + "atp_players.csv") as pf, open(MAINDIR + "atp_rankings_current.csv") as rf:
players = list(csv.reader(pf))
rankings = csv.reader(rf)
# only get first ten rows using islice
for i in islice(rankings, None, 10):
# ifilter won't create a list, gives values in the fly
player = next(ifilter(lambda x: x[0] == i[2], players),"")
```
Not quite sure what `filter(lambda x: x[0]==i[2],players)[0]` is doing, you seem to be searching the whole players list each time and just keeping the first element. It might pay to sort the list once with the first element as the key and use bisection search or build a dict with the first element as the key and the row as the value then simply do lookups.
```
import csv
from itertools import islice,ifilter
from collections import OrderedDict
MAINDIR = "../"
with open(MAINDIR + "atp_players.csv") as pf, open(MAINDIR + "atp_rankings_current.csv") as rf:
players = OrderedDict((row[0],row) for row in csv.reader(pf))
rankings = csv.reader(rf)
for i in islice(rankings, None, 10):
# now constant work getting row as opposed to 0(n)
player = players.get(i[2])
```
What default value you use or indeed if any is needed you will have to decide.
If you have repeating elements at the start of each row but just want to return the first occurrence:
```
with open(MAINDIR + "atp_players.csv") as pf, open(MAINDIR + "atp_rankings_current.csv") as rf:
players = {}
for row in csv.reader(pf):
key = row[0]
if key in players:
continue
players[key] = row
rankings = csv.reader(rf)
for i in islice(rankings, None, 10):
player = players.get(i[2])
```
Output:
```
Djokovic(SRB),(R) Points: 11360
Federer(SUI),(R) Points: 9625
Nadal(ESP),(L) Points: 6585
Wawrinka(SUI),(R) Points: 5120
Nishikori(JPN),(R) Points: 5025
Murray(GBR),(R) Points: 4675
Berdych(CZE),(R) Points: 4600
Raonic(CAN),(R) Points: 4440
Cilic(CRO),(R) Points: 4150
Ferrer(ESP),(R) Points: 4045
```
Timing for the code on ten players shows ifilter to be the fastest but we will see the dict winning when we increase rankings and just how badly your code scales:
```
In [33]: %%timeit
MAINDIR = "tennis_atp-master/"
pf = open ("/tennis_atp-master/atp_players.csv") players = [p for p in csv.reader(pf)]
rf =open( "/tennis_atp-master/atp_rankings_current.csv")
rankings = [r for r in csv.reader(rf)]
for i in rankings[:10]:
player = filter(lambda x: x[0]==i[2],players)[0]
....:
10 loops, best of 3: 123 ms per loop
In [34]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open( "/tennis_atp-master/atp_rankings_current.csv") as rf: players = list(csv.reader(pf))
rankings = csv.reader(rf) # only get first ten rows using islice
for i in islice(rankings, None, 10):
# ifilter won't create a list, gives values in the fly
player = next(ifilter(lambda x: x[0] == i[2], players),"")
....:
10 loops, best of 3: 43.6 ms per loop
In [35]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open( "/tennis_atp-master/atp_rankings_current.csv") as rf:
players = {}
for row in csv.reader(pf):
key = row[0]
if key in players:
continue
players[row[0]] = row
rankings = csv.reader(rf)
for i in islice(rankings, None, 10):
player = players.get(i[2])
pass
....:
10 loops, best of 3: 50.7 ms per loop
```
Now with 100 players you will see the dict is as fast as it was for 10. The cost of building the dict has been offset by constant time lookups:
```
In [38]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open("/tennis_atp-master/atp_rankings_current.csv") as rf:
players = list(csv.reader(pf))
rankings = csv.reader(rf)
# only get first ten rows using islice
for i in islice(rankings, None, 100):
# ifilter won't create a list, gives values in the fly
player = next(ifilter(lambda x: x[0] == i[2], players),"")
....:
10 loops, best of 3: 120 ms per loop
In [39]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open( "/tennis_atp-master/atp_rankings_current.csv") as rf:
players = {}
for row in csv.reader(pf):
key = row[0]
if key in players:
continue
players[row[0]] = row
rankings = csv.reader(rf)
for i in islice(rankings, None, 100):
player = players.get(i[2])
pass
....:
10 loops, best of 3: 50.7 ms per loop
In [40]: %%timeit
MAINDIR = "tennis_atp-master/"
pf = open ("/tennis_atp-master/atp_players.csv")
players = [p for p in csv.reader(pf)]
rf =open( "/tennis_atp-master/atp_rankings_current.csv")
rankings = [r for r in csv.reader(rf)]
for i in rankings[:100]:
player = filter(lambda x: x[0]==i[2],players)[0]
....:
1 loops, best of 3: 806 ms per loop
```
For 250 players:
```
# your code
1 loops, best of 3: 1.86 s per loop
# dict
10 loops, best of 3: 50.7 ms per loop
# ifilter
10 loops, best of 3: 483 ms per loop
```
The final test looping over the whole rankings:
```
# your code
1 loops, best of 3: 2min 40s per loop
# dict
10 loops, best of 3: 67 ms per loop
# ifilter
1 loops, best of 3: 1min 3s per loop
```
So you can see as we loop over more rankings the **dict** option is by far the most efficient as far as runtime goes and will scale extremely well. | This code doesn't take that much time to run. So I'm going to assume that you were really running through more of the rankings that just 10. When I run through them all it takes a long time. If that is what you are interested in doing, then a dictionary would shorten the search time. For a bit of overhead to setup the dictionary, you can search it very fast. Here's how I've modified your for loop:
```
play_dict = {}
for index, player in enumerate(players):
play_dict[player[0]] = index
for i in rankings[:10]:
player = players[play_dict[i[2]]]
```
With this code you can process all the rankings instantaneously. |
29,711,646 | I'm trying to create examples on how to manipulate massive databases composed of CSV tables using only Python.
I'd like to find out a way to emulate efficient indexed queries in tables spread through some `list()`
The example below takes 24 seconds in a 3.2Ghz Core i5
```
#!/usr/bin/env python
import csv
MAINDIR = "../"
pf = open (MAINDIR+"atp_players.csv")
players = [p for p in csv.reader(pf)]
rf = open (MAINDIR+"atp_rankings_current.csv")
rankings = [r for r in csv.reader(rf)]
for i in rankings[:10]:
player = filter(lambda x: x[0]==i[2],players)[0]
print "%s(%s),(%s) Points: %s"%(player[2],player[5],player[3],i[3])
```
For [this dataset](https://github.com/JeffSackmann/tennis_atp).
A more efficient, or more *pythonic* way would be greatly appreciated. | 2015/04/18 | [
"https://Stackoverflow.com/questions/29711646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417415/"
] | You can `itertools.islice` instead of reading all rows and use `itertools.ifilter`:
```
import csv
from itertools import islice,ifilter
MAINDIR = "../"
with open(MAINDIR + "atp_players.csv") as pf, open(MAINDIR + "atp_rankings_current.csv") as rf:
players = list(csv.reader(pf))
rankings = csv.reader(rf)
# only get first ten rows using islice
for i in islice(rankings, None, 10):
# ifilter won't create a list, gives values in the fly
player = next(ifilter(lambda x: x[0] == i[2], players),"")
```
Not quite sure what `filter(lambda x: x[0]==i[2],players)[0]` is doing, you seem to be searching the whole players list each time and just keeping the first element. It might pay to sort the list once with the first element as the key and use bisection search or build a dict with the first element as the key and the row as the value then simply do lookups.
```
import csv
from itertools import islice,ifilter
from collections import OrderedDict
MAINDIR = "../"
with open(MAINDIR + "atp_players.csv") as pf, open(MAINDIR + "atp_rankings_current.csv") as rf:
players = OrderedDict((row[0],row) for row in csv.reader(pf))
rankings = csv.reader(rf)
for i in islice(rankings, None, 10):
# now constant work getting row as opposed to 0(n)
player = players.get(i[2])
```
What default value you use or indeed if any is needed you will have to decide.
If you have repeating elements at the start of each row but just want to return the first occurrence:
```
with open(MAINDIR + "atp_players.csv") as pf, open(MAINDIR + "atp_rankings_current.csv") as rf:
players = {}
for row in csv.reader(pf):
key = row[0]
if key in players:
continue
players[key] = row
rankings = csv.reader(rf)
for i in islice(rankings, None, 10):
player = players.get(i[2])
```
Output:
```
Djokovic(SRB),(R) Points: 11360
Federer(SUI),(R) Points: 9625
Nadal(ESP),(L) Points: 6585
Wawrinka(SUI),(R) Points: 5120
Nishikori(JPN),(R) Points: 5025
Murray(GBR),(R) Points: 4675
Berdych(CZE),(R) Points: 4600
Raonic(CAN),(R) Points: 4440
Cilic(CRO),(R) Points: 4150
Ferrer(ESP),(R) Points: 4045
```
Timing for the code on ten players shows ifilter to be the fastest but we will see the dict winning when we increase rankings and just how badly your code scales:
```
In [33]: %%timeit
MAINDIR = "tennis_atp-master/"
pf = open ("/tennis_atp-master/atp_players.csv") players = [p for p in csv.reader(pf)]
rf =open( "/tennis_atp-master/atp_rankings_current.csv")
rankings = [r for r in csv.reader(rf)]
for i in rankings[:10]:
player = filter(lambda x: x[0]==i[2],players)[0]
....:
10 loops, best of 3: 123 ms per loop
In [34]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open( "/tennis_atp-master/atp_rankings_current.csv") as rf: players = list(csv.reader(pf))
rankings = csv.reader(rf) # only get first ten rows using islice
for i in islice(rankings, None, 10):
# ifilter won't create a list, gives values in the fly
player = next(ifilter(lambda x: x[0] == i[2], players),"")
....:
10 loops, best of 3: 43.6 ms per loop
In [35]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open( "/tennis_atp-master/atp_rankings_current.csv") as rf:
players = {}
for row in csv.reader(pf):
key = row[0]
if key in players:
continue
players[row[0]] = row
rankings = csv.reader(rf)
for i in islice(rankings, None, 10):
player = players.get(i[2])
pass
....:
10 loops, best of 3: 50.7 ms per loop
```
Now with 100 players you will see the dict is as fast as it was for 10. The cost of building the dict has been offset by constant time lookups:
```
In [38]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open("/tennis_atp-master/atp_rankings_current.csv") as rf:
players = list(csv.reader(pf))
rankings = csv.reader(rf)
# only get first ten rows using islice
for i in islice(rankings, None, 100):
# ifilter won't create a list, gives values in the fly
player = next(ifilter(lambda x: x[0] == i[2], players),"")
....:
10 loops, best of 3: 120 ms per loop
In [39]: %%timeit
with open("/tennis_atp-master/atp_players.csv") as pf, open( "/tennis_atp-master/atp_rankings_current.csv") as rf:
players = {}
for row in csv.reader(pf):
key = row[0]
if key in players:
continue
players[row[0]] = row
rankings = csv.reader(rf)
for i in islice(rankings, None, 100):
player = players.get(i[2])
pass
....:
10 loops, best of 3: 50.7 ms per loop
In [40]: %%timeit
MAINDIR = "tennis_atp-master/"
pf = open ("/tennis_atp-master/atp_players.csv")
players = [p for p in csv.reader(pf)]
rf =open( "/tennis_atp-master/atp_rankings_current.csv")
rankings = [r for r in csv.reader(rf)]
for i in rankings[:100]:
player = filter(lambda x: x[0]==i[2],players)[0]
....:
1 loops, best of 3: 806 ms per loop
```
For 250 players:
```
# your code
1 loops, best of 3: 1.86 s per loop
# dict
10 loops, best of 3: 50.7 ms per loop
# ifilter
10 loops, best of 3: 483 ms per loop
```
The final test looping over the whole rankings:
```
# your code
1 loops, best of 3: 2min 40s per loop
# dict
10 loops, best of 3: 67 ms per loop
# ifilter
1 loops, best of 3: 1min 3s per loop
```
So you can see as we loop over more rankings the **dict** option is by far the most efficient as far as runtime goes and will scale extremely well. | Consider putting your data in an [SQLite database](https://docs.python.org/3/library/sqlite3.html). This meets your requirement of using only Python, since it is built into the standard Python library and supported in (almost) all Python interpreters. SQLite is a database library that allows you to do processing on data using the SQL syntax. It gives you features like indexing and foreign key relationships.
If you need to do multiple queries on the data, doing some pre-computation (i.e. indexes and data normalization) is the most sensible route. |
29,711,646 | I'm trying to create examples on how to manipulate massive databases composed of CSV tables using only Python.
I'd like to find out a way to emulate efficient indexed queries in tables spread through some `list()`
The example below takes 24 seconds in a 3.2Ghz Core i5
```
#!/usr/bin/env python
import csv
MAINDIR = "../"
pf = open (MAINDIR+"atp_players.csv")
players = [p for p in csv.reader(pf)]
rf = open (MAINDIR+"atp_rankings_current.csv")
rankings = [r for r in csv.reader(rf)]
for i in rankings[:10]:
player = filter(lambda x: x[0]==i[2],players)[0]
print "%s(%s),(%s) Points: %s"%(player[2],player[5],player[3],i[3])
```
For [this dataset](https://github.com/JeffSackmann/tennis_atp).
A more efficient, or more *pythonic* way would be greatly appreciated. | 2015/04/18 | [
"https://Stackoverflow.com/questions/29711646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417415/"
] | Consider putting your data in an [SQLite database](https://docs.python.org/3/library/sqlite3.html). This meets your requirement of using only Python, since it is built into the standard Python library and supported in (almost) all Python interpreters. SQLite is a database library that allows you to do processing on data using the SQL syntax. It gives you features like indexing and foreign key relationships.
If you need to do multiple queries on the data, doing some pre-computation (i.e. indexes and data normalization) is the most sensible route. | This code doesn't take that much time to run. So I'm going to assume that you were really running through more of the rankings that just 10. When I run through them all it takes a long time. If that is what you are interested in doing, then a dictionary would shorten the search time. For a bit of overhead to setup the dictionary, you can search it very fast. Here's how I've modified your for loop:
```
play_dict = {}
for index, player in enumerate(players):
play_dict[player[0]] = index
for i in rankings[:10]:
player = players[play_dict[i[2]]]
```
With this code you can process all the rankings instantaneously. |
68,705,417 | I am getting the below error while running a pyspark program on PYCHARM,
Error:
>
> java.io.IOException: Cannot run program "python3": CreateProcess error=2, The system cannot find the file specified ......
>
>
>
The interpreter is recognizing the python.exe file and I have added the Content root in project structure.
I got a similar issue while running the same program before in on windows command prompt and solved it using [What is the right way to edit spark-env.sh before running spark-shell?](https://stackoverflow.com/questions/38300099/what-is-the-right-way-to-edit-spark-env-sh-before-running-spark-shell) | 2021/08/08 | [
"https://Stackoverflow.com/questions/68705417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11609306/"
] | create an environment variable PYSPARK\_PYTHON with value 'python'.
it worked for me! | 1. Go to Environmental variable and within System variable set a new variable as `PYSPARK_PYTHON` and value as `python`
>
> PYSPARK\_PYTHON=python
>
>
>
2. Add below codebits to your pyspark code
```
import os
import sys
from pyspark import SparkContext
os.environ['PYSPARK_PYTHON'] = sys.executable
os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable
``` |
68,705,417 | I am getting the below error while running a pyspark program on PYCHARM,
Error:
>
> java.io.IOException: Cannot run program "python3": CreateProcess error=2, The system cannot find the file specified ......
>
>
>
The interpreter is recognizing the python.exe file and I have added the Content root in project structure.
I got a similar issue while running the same program before in on windows command prompt and solved it using [What is the right way to edit spark-env.sh before running spark-shell?](https://stackoverflow.com/questions/38300099/what-is-the-right-way-to-edit-spark-env-sh-before-running-spark-shell) | 2021/08/08 | [
"https://Stackoverflow.com/questions/68705417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11609306/"
] | Before creating your spark session, set the following environment variables in your code:
```py
import os
import sys
from pyspark.sql import SparkSession
os.environ['PYSPARK_PYTHON'] = sys.executable
os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable
spark = SparkSession.builder.getOrCreate()
``` | 1. Go to Environmental variable and within System variable set a new variable as `PYSPARK_PYTHON` and value as `python`
>
> PYSPARK\_PYTHON=python
>
>
>
2. Add below codebits to your pyspark code
```
import os
import sys
from pyspark import SparkContext
os.environ['PYSPARK_PYTHON'] = sys.executable
os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable
``` |
60,553,140 | I have the following insert statement that let me parse sql query into a python file and then returning a dataframe of that data that is collected from the query
```
params = 'DRIVER={ODBC Driver 13 for SQL Server};' \
'SERVER=localhost;' \
'PORT=XXX;' \
'DATABASE=database_name;' \
'UID=XXX;' \
'PWD=XXX;'
params = urllib.parse.quote_plus(params)
db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
sql = '''
select * from table_name
where column_name= variable_in_python
'''
dataframe = pd.read_sql_query(sql, db)
```
Now, after the 'where' statement, I want to have a variable that I declare in Python, for example an id-number (let's say 1123581321). This variable needs to come in that 'variable\_python'-place.
I tried:
```
import pyodbc as py
import urllib
from sqlalchemy import create_engine
import pandas as pd
x = 1123581321
params = 'DRIVER={ODBC Driver 13 for SQL Server};' \
'SERVER=localhost;' \
'PORT=XXX;' \
'DATABASE=database_name;' \
'UID=XXX;' \
'PWD=XXX;'
params = urllib.parse.quote_plus(params)
db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
sql = '''
select * from table_name
where column_name= 'x'
'''
dataframe = pd.read_sql_query(sql, db)
```
This obviously doesn't work. But I have not a single idea how I can do this (if it can be done).
Any suggestions are more than welcome! | 2020/03/05 | [
"https://Stackoverflow.com/questions/60553140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292254/"
] | You can use `?` as a [placeholder](https://learn.microsoft.com/en-us/sql/connect/php/how-to-perform-parameterized-queries?view=sql-server-ver15) in the query and pass the value as a parameter to the `read_sql_query` function:
```
sql = '''
select * from table_name
where column_name= ?
'''
dataframe = pd.read_sql_query(sql, db, params=(variable_in_python,))
``` | You can do something like:
```
sql = '''
select * from table_name
where column_name= {}
'''.format(variable_in_python)
```
For more information, have a look at <https://docs.python.org/3/tutorial/inputoutput.html> |
60,553,140 | I have the following insert statement that let me parse sql query into a python file and then returning a dataframe of that data that is collected from the query
```
params = 'DRIVER={ODBC Driver 13 for SQL Server};' \
'SERVER=localhost;' \
'PORT=XXX;' \
'DATABASE=database_name;' \
'UID=XXX;' \
'PWD=XXX;'
params = urllib.parse.quote_plus(params)
db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
sql = '''
select * from table_name
where column_name= variable_in_python
'''
dataframe = pd.read_sql_query(sql, db)
```
Now, after the 'where' statement, I want to have a variable that I declare in Python, for example an id-number (let's say 1123581321). This variable needs to come in that 'variable\_python'-place.
I tried:
```
import pyodbc as py
import urllib
from sqlalchemy import create_engine
import pandas as pd
x = 1123581321
params = 'DRIVER={ODBC Driver 13 for SQL Server};' \
'SERVER=localhost;' \
'PORT=XXX;' \
'DATABASE=database_name;' \
'UID=XXX;' \
'PWD=XXX;'
params = urllib.parse.quote_plus(params)
db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
sql = '''
select * from table_name
where column_name= 'x'
'''
dataframe = pd.read_sql_query(sql, db)
```
This obviously doesn't work. But I have not a single idea how I can do this (if it can be done).
Any suggestions are more than welcome! | 2020/03/05 | [
"https://Stackoverflow.com/questions/60553140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292254/"
] | I like the answer by @blhsing.
Another way is f-strings. I particularly like them because they make things very readable.
For example:
```
# Query Parameters
column_name = 'x'
```
and then:
```
sql = f'''
select * from table_name
where column_name= {column_name}
'''
```
You could go further with this and use a dictionary of parameters and call each one by key within the f-string itself. The advantage of this method is that if you have a lot of parameters for longer and more complex queries, you always have a dictionary to refer to. Another is that when you do a `print(sql)` in this case, you can see exactly what parameters you are passing (this helps in the case of longer queries with more parameters). | You can do something like:
```
sql = '''
select * from table_name
where column_name= {}
'''.format(variable_in_python)
```
For more information, have a look at <https://docs.python.org/3/tutorial/inputoutput.html> |
60,553,140 | I have the following insert statement that let me parse sql query into a python file and then returning a dataframe of that data that is collected from the query
```
params = 'DRIVER={ODBC Driver 13 for SQL Server};' \
'SERVER=localhost;' \
'PORT=XXX;' \
'DATABASE=database_name;' \
'UID=XXX;' \
'PWD=XXX;'
params = urllib.parse.quote_plus(params)
db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
sql = '''
select * from table_name
where column_name= variable_in_python
'''
dataframe = pd.read_sql_query(sql, db)
```
Now, after the 'where' statement, I want to have a variable that I declare in Python, for example an id-number (let's say 1123581321). This variable needs to come in that 'variable\_python'-place.
I tried:
```
import pyodbc as py
import urllib
from sqlalchemy import create_engine
import pandas as pd
x = 1123581321
params = 'DRIVER={ODBC Driver 13 for SQL Server};' \
'SERVER=localhost;' \
'PORT=XXX;' \
'DATABASE=database_name;' \
'UID=XXX;' \
'PWD=XXX;'
params = urllib.parse.quote_plus(params)
db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
sql = '''
select * from table_name
where column_name= 'x'
'''
dataframe = pd.read_sql_query(sql, db)
```
This obviously doesn't work. But I have not a single idea how I can do this (if it can be done).
Any suggestions are more than welcome! | 2020/03/05 | [
"https://Stackoverflow.com/questions/60553140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12292254/"
] | You can use `?` as a [placeholder](https://learn.microsoft.com/en-us/sql/connect/php/how-to-perform-parameterized-queries?view=sql-server-ver15) in the query and pass the value as a parameter to the `read_sql_query` function:
```
sql = '''
select * from table_name
where column_name= ?
'''
dataframe = pd.read_sql_query(sql, db, params=(variable_in_python,))
``` | I like the answer by @blhsing.
Another way is f-strings. I particularly like them because they make things very readable.
For example:
```
# Query Parameters
column_name = 'x'
```
and then:
```
sql = f'''
select * from table_name
where column_name= {column_name}
'''
```
You could go further with this and use a dictionary of parameters and call each one by key within the f-string itself. The advantage of this method is that if you have a lot of parameters for longer and more complex queries, you always have a dictionary to refer to. Another is that when you do a `print(sql)` in this case, you can see exactly what parameters you are passing (this helps in the case of longer queries with more parameters). |
51,759,688 | Why only ***if*** statement is executed & not ***else*** statement if we write an ***if-else*** with ***if*** having constant value. For example this code in python
```
x=5
if 5:
print("hello 5")
else:
print("bye")
```
Also the point to be noted is that in second line even if I replace 5 with 500 or any number, if statement will be only executed.Can anyone please explain. | 2018/08/09 | [
"https://Stackoverflow.com/questions/51759688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6659144/"
] | Threading is your only possibility. Also it always requires the ENTER when you are using std::cin. This could work:
```
#include <future>
#include <iostream>
#include <thread>
int main(int argc, char** argv) {
int i = 1;
std::atomic_int ch{1};
std::atomic_bool readKeyboard{true};
std::thread t([&ch, &readKeyboard]() {
while (readKeyboard) {
int input;
if (std::cin >> input) {
ch = input;
if (ch == '0') {
break;
}
}
}
});
while (ch != '0') {
std::cout << "Hi" << i << std::endl;
++i;
}
readKeyboard = false;
t.join();
return 1;
}
``` | You can do this but you will have to use threads. Here is the minimal example how to achive this behaviour. Please note that you will need C++11 at least.
```
#include <iostream>
#include <thread>
#include <atomic>
int main()
{
std::atomic<bool> stopLoop;
std::thread t([&]()
{
while (!stopLoop)
{
std::cout << "Hi";
}
});
while (std::cin.get() != '0') //you will need to press enter after pressing '0'
{
; //empty loop, just wait until there is 0 on input
}
stopLoop = true; //this stops the other loop
}
```
Other options will be to dive into OS specific libraries. You must now that C++ doesn't have any kind of non-blocking I/O in standard library and for most time you will have to press `<ENTER>` to have any input in input stream (std::cin) |
16,066,838 | OK so I have this book
Violent Python - A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers.
I have gotten to page 10 and I'm a complete noob at this but it really fascinates me.
But this piece of code has me stumped:
```
import socket
socket.setdefaulttimeout(2)
s = socket.socket()
s.connect(("192.168.95.148",21))
ans = s.recv(1024)
print ans
```
This is what I get in the console as a result:
```
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.timeout: timed out
```
From what I can see the book says I should get this:
```
220 FreeFloat Ftp Server (Version 1.00).
```
Im using pydev and eclipse
Any help would be much appreciated. | 2013/04/17 | [
"https://Stackoverflow.com/questions/16066838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282257/"
] | `s.connect(("192.168.95.148",21))` seems to try to connect to an FTP server on IP address 192.168.95.148. If you don't have an FTP server running on that IP, you will get a connection timeout error instead of a response from the FTP server. Do you have a FreeFloat FTP Server running on 192.168.95.148? | Well, you could try connecting to a known public FTP server? If the lack of a server is stopping you.
For example, ftp.mozilla.org |
73,625,732 | I have an table of people where each person can have a associate partner like this:
| id\_person | Name | id\_partner |
| --- | --- | --- |
| 1 | Javi | 5 |
| 2 | John | 4 |
| 3 | Mike | 6 |
| 4 | Lucy | 2 |
| 5 | Jenny | 1 |
| 6 | Cindy | 3 |
So I would like to have a query where I can get all the couples without repetance like
| Name 1 | Name 2 |
| --- | --- |
| Javi | Jenny |
| John | Lucy |
| Mike | Cindy |
I now how I would do it in python but in sql I have no clue
Thank you in advance!!! | 2022/09/06 | [
"https://Stackoverflow.com/questions/73625732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17563150/"
] | Assuming you want daily value counts, use `asfreq` and `fillna`:
```
july_log_mel.index = pd.to_datetime(july_log_mel.index)
july_log_mel.asfreq('D').fillna(0)
``` | You can `reindex` your Series with `date_range`:
```
s = df['date'].value_counts()
s = s.reindex(pd.date_range(s.index.min(), s.index.max(), freq='D')
.strftime('%Y-%m-%d'),
fill_value=0)
```
output:
```
2022-07-04 2
2022-07-05 0
2022-07-06 1
2022-07-07 0
2022-07-08 1
Name: date, dtype: int64
```
used input:
```
date
0 2022-07-04
1 2022-07-04
2 2022-07-06
3 2022-07-08
``` |
50,717,721 | HI I am following an install from a book "Python Crash Course" chapter 15 which directed me to install matplotlib via downloading from pypi and using the format
```
python -m pip install --user matplotlib-2.2.2-cp36-cp36m-win32.whl
```
This seems to go ok but reports at the end.
File "C:\Program Files (x86)\Python Community\Python 3.6.1\lib\decimal.py", line 3 in , from decimal import \*
AttributeError: module 'numbers' has no attribute 'Number'
and when I enter an interactive shell:
>
> import matplotlib
>
>
>
I get a ModuleNotFoundError
I have tried a matplotlib-2.2.2-cp36-cp36m-win32.whl and matplotlib-2.2.2-cp36-cp36m-win\_amd64.whl both give the same error.
Could someone please let me know how to fix this? | 2018/06/06 | [
"https://Stackoverflow.com/questions/50717721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9902618/"
] | I am answering my own question.
The issue was to do with a file called numbers.py residing in a folder that I have all my python files, wheel files etc.
I found the answer in stack overflow. I will link to this [matplotlib - AttributeError: module 'numbers' has no attribute 'Integral'](https://stackoverflow.com/questions/49535107/matplotlib-attributeerror-module-numbers-has-no-attribute-integral).
The file was stopping the install so I renamed it and reinstalled matplotlib and it now works.
Sorry but this was not obvious to me ! | Try running cmd as **administrator** inside the python directory. Then execute:
```
pip3 install matplotlib-2.2.2-cp36-cp36m-win32.whl
```
Also make sure that you have all dependencies installed. |
50,717,721 | HI I am following an install from a book "Python Crash Course" chapter 15 which directed me to install matplotlib via downloading from pypi and using the format
```
python -m pip install --user matplotlib-2.2.2-cp36-cp36m-win32.whl
```
This seems to go ok but reports at the end.
File "C:\Program Files (x86)\Python Community\Python 3.6.1\lib\decimal.py", line 3 in , from decimal import \*
AttributeError: module 'numbers' has no attribute 'Number'
and when I enter an interactive shell:
>
> import matplotlib
>
>
>
I get a ModuleNotFoundError
I have tried a matplotlib-2.2.2-cp36-cp36m-win32.whl and matplotlib-2.2.2-cp36-cp36m-win\_amd64.whl both give the same error.
Could someone please let me know how to fix this? | 2018/06/06 | [
"https://Stackoverflow.com/questions/50717721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9902618/"
] | I am answering my own question.
The issue was to do with a file called numbers.py residing in a folder that I have all my python files, wheel files etc.
I found the answer in stack overflow. I will link to this [matplotlib - AttributeError: module 'numbers' has no attribute 'Integral'](https://stackoverflow.com/questions/49535107/matplotlib-attributeerror-module-numbers-has-no-attribute-integral).
The file was stopping the install so I renamed it and reinstalled matplotlib and it now works.
Sorry but this was not obvious to me ! | The code seems very specific and something may not be supported any more.
You could first uninstall the current version using:
```
pip uninstall matplotlib
```
and then try installing matplotlib as follows:
```
pip install matplotlib
```
providing that you have admin rights to do so.
Then you can import as: `import matplotlib.pyplot as plt` |
50,717,721 | HI I am following an install from a book "Python Crash Course" chapter 15 which directed me to install matplotlib via downloading from pypi and using the format
```
python -m pip install --user matplotlib-2.2.2-cp36-cp36m-win32.whl
```
This seems to go ok but reports at the end.
File "C:\Program Files (x86)\Python Community\Python 3.6.1\lib\decimal.py", line 3 in , from decimal import \*
AttributeError: module 'numbers' has no attribute 'Number'
and when I enter an interactive shell:
>
> import matplotlib
>
>
>
I get a ModuleNotFoundError
I have tried a matplotlib-2.2.2-cp36-cp36m-win32.whl and matplotlib-2.2.2-cp36-cp36m-win\_amd64.whl both give the same error.
Could someone please let me know how to fix this? | 2018/06/06 | [
"https://Stackoverflow.com/questions/50717721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9902618/"
] | I am answering my own question.
The issue was to do with a file called numbers.py residing in a folder that I have all my python files, wheel files etc.
I found the answer in stack overflow. I will link to this [matplotlib - AttributeError: module 'numbers' has no attribute 'Integral'](https://stackoverflow.com/questions/49535107/matplotlib-attributeerror-module-numbers-has-no-attribute-integral).
The file was stopping the install so I renamed it and reinstalled matplotlib and it now works.
Sorry but this was not obvious to me ! | It seems like you are installing the package on Python 2.
Try installing the library using:
```
py -3 -m pip install --user matplotlib
```
Assuming you are using Windows. |
50,717,721 | HI I am following an install from a book "Python Crash Course" chapter 15 which directed me to install matplotlib via downloading from pypi and using the format
```
python -m pip install --user matplotlib-2.2.2-cp36-cp36m-win32.whl
```
This seems to go ok but reports at the end.
File "C:\Program Files (x86)\Python Community\Python 3.6.1\lib\decimal.py", line 3 in , from decimal import \*
AttributeError: module 'numbers' has no attribute 'Number'
and when I enter an interactive shell:
>
> import matplotlib
>
>
>
I get a ModuleNotFoundError
I have tried a matplotlib-2.2.2-cp36-cp36m-win32.whl and matplotlib-2.2.2-cp36-cp36m-win\_amd64.whl both give the same error.
Could someone please let me know how to fix this? | 2018/06/06 | [
"https://Stackoverflow.com/questions/50717721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9902618/"
] | I am answering my own question.
The issue was to do with a file called numbers.py residing in a folder that I have all my python files, wheel files etc.
I found the answer in stack overflow. I will link to this [matplotlib - AttributeError: module 'numbers' has no attribute 'Integral'](https://stackoverflow.com/questions/49535107/matplotlib-attributeerror-module-numbers-has-no-attribute-integral).
The file was stopping the install so I renamed it and reinstalled matplotlib and it now works.
Sorry but this was not obvious to me ! | Try doing as below:
python -m pip install --user matplotlib |
46,630,311 | Actually I'm calculating throughput given certain window size.
However, I don't know how to accumulate the values by window. For instance:
```
time = [0.9, 1.1, 1.2, 2.1, 2.3, 2.6]
value = [1, 2, 3, 4, 5, 6]
```
After window size with 1 is applied, I should get
```
new_value = [1, 5, 15]
```
I've thought of using indexes of data frame but not sure how I can realize it since I'm new to python. | 2017/10/08 | [
"https://Stackoverflow.com/questions/46630311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5785396/"
] | You could use `itertools.groupby` with a custom grouping function
```
from itertools import groupby
def f(time, values, dt=1):
vit = iter(values)
return [sum(v for _, v in zip(g, vit)) for _, g in groupby(time, lambda x: x // dt)]
```
```
In [14]: f([0.9, 1.1, 1.2, 2.1, 2.3, 2.6], [1, 2, 3, 4, 5, 6])
Out[14]: [1, 5, 15]
In [15]: f([0.9, 1.1, 1.2, 2.1, 2.3, 2.6], [1, 2, 3, 4, 5, 6], dt=2)
Out[15]: [6, 15]
```
Note that for the window of size 1 you could simply use `groupby(time, int)`. | You could use a [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter):
```
time = [0.9, 1.1, 1.2, 2.1, 2.3, 2.6]
value = [1, 2, 3, 4, 5, 6]
from collections import Counter
counter = Counter()
for t,v in zip(time, value):
counter[int(t)] += v
print(sorted(counter.items()))
# [(0, 1), (1, 5), (2, 15)]
``` |
48,982,187 | I am using `telegraf` as a measuring/monitoring tool in my tests. I need to edit `telegraf` configurations automatically; since all tests are being executed automatically.
Currently I am using `re` for configuring it; this is the process:
1. Read the whole file content.
2. Use regex to find and edit the required plugin/property.
3. Write the whole changed content to the file.
But I'm searching for a library, if exists, like [`ConfigParser`](https://docs.python.org/3/library/configparser.html) or [`reconfigure`](https://pypi.python.org/pypi/reconfigure/0.1.39) to handle the configurations as an object not content.
I tried `ConfigParser.ConfigParser`, `ConfigParser.RawConfigParser` and `ConfigParser.SafeConfigParser`; all return:
```
ConfigParser.ParsingError: File contains parsing errors: /etc/telegraf/telegraf.conf
```
`reconfigure` library has specific configuration classes, each belongs to a special type of linux configs (e.g. `FSTabConfig`, `ResolvConfig` and some other types), but it doesn't contain a class for `telegraf` configs.
Does anyone have an option in mind?
**EDIT 1:**
I tried `configobj` library (as @KevinC suggested), but it loads nothing:
```
>>> import configobj
>>> c = configobj.ConfigObj('/home/zeinab/Desktop/config-modification/telegraf.conf', list_values=False)
>>> c
ConfigObj({})
```
Using `list_values=True` returns the same results. | 2018/02/26 | [
"https://Stackoverflow.com/questions/48982187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1626977/"
] | You can use [toml](https://pypi.org/project/toml/)
Configuration file
```
[[inputs.ping]]
## Hosts to send ping packets to.
urls = ["example.org"]
method = "exec"
```
Usage
```
import toml
conf = (toml.load("/etc/telegraf/telegraf.conf"))
conf.get("inputs")
```
Output
```
{'ping': [{'urls': ['example.org'], 'method': 'exec'}]}
``` | You can use [configobj](http://configobj.readthedocs.io/en/latest/), but you have to specify "list\_values"=False
```
c = configobj.ConfigObj('/etc/telegraf/telegraf.conf', list_values=False)
``` |
56,109,815 | If there is any bug in my code (code within a model that is used within a view which uses LoginRequiredMixin ) e.g. A bug like:
```
if (True: # <-- example bug to show how bugs like this are hidden
```
Then I get the following error:
```
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django.core.exceptions.ImproperlyConfigured:
AUTH_USER_MODEL refers to model 'auth.User' that has not been installed
```
This makes it really hard to debug the code. I have figured out if I remove this line from my views.py:
```
from django.contrib.auth.mixins import LoginRequiredMixin
```
Even if I remove all instances where LoginRequiredMixin is used, just by importing it, it hides the true bug and generates the above auth error.
I have read: [AUTH\_USER\_MODEL refers to model '%s' that has not been installed" % settings.AUTH\_USER\_MODEL](https://stackoverflow.com/questions/37028655/auth-user-model-refers-to-model-s-that-has-not-been-installed-settings-aut?rq=1)
My research shows most of the time this is due to "django.contrib.auth'" missing from INSTALLED\_APPS, which you can see I have (settings.py snippet, Django 2.2):
```
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth', # <-- Important for this topic!
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.CommonConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
```
I tried adding this to above the mixim import but neither helped:
```
from django.contrib import auth
from django.contrib.auth.models import User
```
This part of the full traceback agrees with the above:
```
Traceback (most recent call last):
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\registry.py", line 155, in get_app_config
return self.app_configs[app_label]
KeyError: 'auth'
```
Here is the traceback if I call makemigrations (This is what I expect):
```
C:\code\myproject\src>pipenv run python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\code\myproject\src\myapp\models.py", line 14, in <module>
from .sql import myapp_entry_clean, myapp_entry_grouping
File "C:\code\myproject\src\myapp\sql.py", line 68
if (True:
^
SyntaxError: invalid syntax
C:\code\myproject\src>
```
Here is the traceback with runserver:
```
C:\code\myproject\src>pipenv run python manage.py runserver
Watching for file changes with StatReloader
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\User\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception
raise _exception[0](_exception[1]).with_traceback(_exception[2])
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\code\myproject\src\myapp\models.py", line 14, in <module>
from .sql import myapp_entry_clean, myapp_entry_grouping
File "<string>", line None
SyntaxError: invalid syntax (sql.py, line 68)
Traceback (most recent call last):
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\registry.py", line 155, in get_app_config
return self.app_configs[app_label]
KeyError: 'auth'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\contrib\auth\__init__.py", line 165, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\registry.py", line 205, in get_model
app_config = self.get_app_config(app_label)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\apps\registry.py", line 162, in get_app_config
raise LookupError(message)
LookupError: No installed app with label 'auth'.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute
super().execute(*args, **options)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle
self.run(**options)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run
autoreload.run_with_reloader(self.inner_run, **options)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\utils\autoreload.py", line 579, in run_with_reloader
start_django(reloader, main_func, *args, **kwargs)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\utils\autoreload.py", line 564, in start_django
reloader.run(django_main_thread)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\utils\autoreload.py", line 272, in run
get_resolver().urlconf_module
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\urls\resolvers.py", line 564, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\code\myproject\src\linkcube\urls.py", line 20, in <module>
path('', include('common.urls')),
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\code\myproject\src\common\urls.py", line 5, in <module>
from . import views
File "C:\code\myproject\src\common\views.py", line 9, in <module>
from django.contrib.auth.mixins import LoginRequiredMixin
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\contrib\auth\mixins.py", line 3, in <module>
from django.contrib.auth.views import redirect_to_login
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\contrib\auth\views.py", line 10, in <module>
from django.contrib.auth.forms import (
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\contrib\auth\forms.py", line 20, in <module>
UserModel = get_user_model()
File "C:\Users\User\.virtualenvs\myproject-wc-xNQPL\lib\site-packages\django\contrib\auth\__init__.py", line 170, in get_user_model
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed
C:\code\myproject\src>
```
How do I make it so that the auth error is not falsely raised? | 2019/05/13 | [
"https://Stackoverflow.com/questions/56109815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5506400/"
] | You need to do:
```
$typ = $reqarr['message']['entities'][0]['type'];
```
Output:-<https://3v4l.org/KQc2s> | Try this:
```
if(!isset($reqarr['message']['entities'][0])){
$reqarr['message']['entities']=array($reqarr['message']['entities']);
}
foreach($reqarr['message']['entities'] as $entity){
var_dump($entities);
die();
}
``` |
45,247,778 | Writing a script in python to get data from table, when I use xpath I get the data according to it's row and column wise format. However, when I use css selector with the same I get an error 'list' object has no attribute 'text'. How to get around that? Thanks in advance?
Using xpath which is working errorlessly:
```
import requests
from lxml import html
url="https://fantasy.premierleague.com/player-list/"
response = requests.get(url).text
tree = html.fromstring(response)
for titles in tree.xpath("//table[@class='ism-table']")[0]:
for row in titles.xpath('.//tr'):
tab_d = row.xpath('.//td/text()')
print(tab_d)
```
Using css selector with the same I get aforesaid error:
```
import requests
from lxml import html
url="https://fantasy.premierleague.com/player-list/"
response = requests.get(url).text
tree = html.fromstring(response)
for titles in tree.cssselect("table.ism-table")[0]:
for row in titles.cssselect('tr'):
tab_d = row.cssselect('td')
print(tab_d.text)
```
[](https://i.stack.imgur.com/wFLkk.jpg) | 2017/07/21 | [
"https://Stackoverflow.com/questions/45247778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | You can do it with CSS only if you use checkbox.
Use the `:checked` selector to display the content.
```
// You css
input[type=checkbox] + label {
color: #ccc;
font-style: italic;
}
// Set the content to be displayed when the radio/checkbox is checked.
// using the css3 selector :checked
input[type=checkbox]:checked + label {
color: #f00;
font-style: normal;
}
```
```
<input type="checkbox" id="ossm" name="ossm">
<label for="ossm">CSS is Awesome</label>
``` | You could give the same class name to everyone of your `<fieldset>` and then loop over all elements having this class name. This loop would be executed once the page is load and on every checkbox event. |
45,247,778 | Writing a script in python to get data from table, when I use xpath I get the data according to it's row and column wise format. However, when I use css selector with the same I get an error 'list' object has no attribute 'text'. How to get around that? Thanks in advance?
Using xpath which is working errorlessly:
```
import requests
from lxml import html
url="https://fantasy.premierleague.com/player-list/"
response = requests.get(url).text
tree = html.fromstring(response)
for titles in tree.xpath("//table[@class='ism-table']")[0]:
for row in titles.xpath('.//tr'):
tab_d = row.xpath('.//td/text()')
print(tab_d)
```
Using css selector with the same I get aforesaid error:
```
import requests
from lxml import html
url="https://fantasy.premierleague.com/player-list/"
response = requests.get(url).text
tree = html.fromstring(response)
for titles in tree.cssselect("table.ism-table")[0]:
for row in titles.cssselect('tr'):
tab_d = row.cssselect('td')
print(tab_d.text)
```
[](https://i.stack.imgur.com/wFLkk.jpg) | 2017/07/21 | [
"https://Stackoverflow.com/questions/45247778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | Use this javascript snippet
```js
function show(elem, show){
var elements =
elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden");
var i;
for(i=0; i<elements.length; i++){
if(show){
elements[i].style.display = "initial";
}
else{
elements[i].style.display = "none";
}
}
}
var yes_radio_button=document.getElementById("yes_radio");
if(yes_radio_button.checked){
show(yes_radio_button,true);
}
else{
show(yes_radio_button,false);
}
```
```css
.hidden {
display: none;
width: 100%;
padding: 0px;
margin: 2px;
overflow: hidden;
}
```
```html
<fieldset>
<legend>Something</legend>
<ul>
<li>
<input type="radio" name="X" value="No" id="no_radio" onchange="show(this, true)" checked>
<label>No</label>
</li>
<li>
<input type="radio" name="X" value="Yes" id="yes_radio" onchange="show(this, true)" >
<label>Yes</label>
</li>
</ul>
<p class="hidden">
Elements
</p>
<fieldset class="hidden">
Elements
</fieldset>
</fieldset>
```
Try the fiddle [here](https://jsfiddle.net/9zgfjrub/) | You can do it with CSS only if you use checkbox.
Use the `:checked` selector to display the content.
```
// You css
input[type=checkbox] + label {
color: #ccc;
font-style: italic;
}
// Set the content to be displayed when the radio/checkbox is checked.
// using the css3 selector :checked
input[type=checkbox]:checked + label {
color: #f00;
font-style: normal;
}
```
```
<input type="checkbox" id="ossm" name="ossm">
<label for="ossm">CSS is Awesome</label>
``` |
45,247,778 | Writing a script in python to get data from table, when I use xpath I get the data according to it's row and column wise format. However, when I use css selector with the same I get an error 'list' object has no attribute 'text'. How to get around that? Thanks in advance?
Using xpath which is working errorlessly:
```
import requests
from lxml import html
url="https://fantasy.premierleague.com/player-list/"
response = requests.get(url).text
tree = html.fromstring(response)
for titles in tree.xpath("//table[@class='ism-table']")[0]:
for row in titles.xpath('.//tr'):
tab_d = row.xpath('.//td/text()')
print(tab_d)
```
Using css selector with the same I get aforesaid error:
```
import requests
from lxml import html
url="https://fantasy.premierleague.com/player-list/"
response = requests.get(url).text
tree = html.fromstring(response)
for titles in tree.cssselect("table.ism-table")[0]:
for row in titles.cssselect('tr'):
tab_d = row.cssselect('td')
print(tab_d.text)
```
[](https://i.stack.imgur.com/wFLkk.jpg) | 2017/07/21 | [
"https://Stackoverflow.com/questions/45247778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | Use this javascript snippet
```js
function show(elem, show){
var elements =
elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden");
var i;
for(i=0; i<elements.length; i++){
if(show){
elements[i].style.display = "initial";
}
else{
elements[i].style.display = "none";
}
}
}
var yes_radio_button=document.getElementById("yes_radio");
if(yes_radio_button.checked){
show(yes_radio_button,true);
}
else{
show(yes_radio_button,false);
}
```
```css
.hidden {
display: none;
width: 100%;
padding: 0px;
margin: 2px;
overflow: hidden;
}
```
```html
<fieldset>
<legend>Something</legend>
<ul>
<li>
<input type="radio" name="X" value="No" id="no_radio" onchange="show(this, true)" checked>
<label>No</label>
</li>
<li>
<input type="radio" name="X" value="Yes" id="yes_radio" onchange="show(this, true)" >
<label>Yes</label>
</li>
</ul>
<p class="hidden">
Elements
</p>
<fieldset class="hidden">
Elements
</fieldset>
</fieldset>
```
Try the fiddle [here](https://jsfiddle.net/9zgfjrub/) | You could give the same class name to everyone of your `<fieldset>` and then loop over all elements having this class name. This loop would be executed once the page is load and on every checkbox event. |
6,949,915 | I have several scripts written in perl, python, and java (wrapped under java GUI with system calls to perl & python). And I have many not-tech-savy users that need to use this in their windows machines (xp & 7).
To avoid users from installing perl,python,and java and to avoid potential incompatibility between various versions of these interpreters, I'd like to make a local copy of these interpreters in a folder and then calling them. I'd zip the whole folder (which would also contain my code) and send it away.
I'd have to worry about environment variables and make calls to the correct interpreter (especially when other versions of python,java,perl may exists in their current system), but not sure what other problems I may face. Any better ideas?
I never used jython and do not know the overhead of moving to it. I also suspect a complex python system, with many files and 3rd party modules will have problems. Same with perl scripts and I don't know a robust perl interpreter callable from java.
Thank you, in advance. | 2011/08/04 | [
"https://Stackoverflow.com/questions/6949915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/737088/"
] | Try [Portable Python](http://www.portablepython.com/) and [Portable Perl](http://portableapps.com/node/12595). You can unzip them into your application tree and they should work. | Why don't you try migrating your perl/python code into java and then packagin everything into a nice webstart application? What do perl/python offer that java doesn't support?
For perl you can use something like perl2exe and for python py2exe so you can have 2 exes (which would include all the necessary interpreter bits) and invoke them as resources from within java? Or unzip them inside user's home directory and call them again as normal external programs (ProcessBuilder ?) ? |
6,937,505 | I have python application that shoud be launched as windows executable. I'm using py2exe and pymssql 1.9.908.
I used next build script to generate application:
```
from distutils.core import setup
import MySQLdb
import fnmatch
import os
import pymssql
import shutil
import py2exe
import glob
##############
name = 'BGAgent'
old_version = '0.1'
ver = '0.1'
distDir = 'Dist' + name + ver
shutil.rmtree(distDir, True)
shutil.rmtree('Dist' + name + old_version, True)
os.mkdir(distDir)
##############
class Target(object):
""" A simple class that holds information on our executable file. """
def __init__(self, **kw):
""" Default class constructor. Update as you need. """
self.__dict__.update(kw)
# MySQLdb
#dst = os.path.join(distDir, "MySQLdb")
#copy_tree(MySQLdb.__path__[0], dst )
# pymssql
site_packages_dir = os.path.dirname(pymssql.__file__)
pymssql_files = []#'pymssql.py', 'pymssql.pyc', 'pymssql.pyo', '_mssql.pyd']
for eggInfo in glob.glob(os.path.join(site_packages_dir, '*mssql*')) :
pymssql_files.append(os.path.basename(eggInfo))
for fname in pymssql_files :
src = os.path.join(site_packages_dir, fname)
dst = os.path.join(distDir, fname)
if(os.path.isfile(src)) :
shutil.copy(src, dst)
else :
shutil.copytree(src, dst)
includes = ['MySQLdb', 'pymssql', 'OpenSSL']
excludes = ['run_w.exe'] #['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl', 'Tkconstants', 'Tkinter']
packages = ['MySQLdb', 'pymssql', 'OpenSSL']
dll_excludes = []#['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll']
data_files = ['server.pem',
'config.ini',
'run.bat',
#os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'),
]
icon_resources = []
bitmap_resources = []
other_resources = []
MyApp_Target = Target(
# what to build
script = "run.py",
icon_resources = icon_resources,
bitmap_resources = bitmap_resources,
other_resources = other_resources,
dest_base = name,
version = ver,
company_name = "",
copyright = "",
name = name,
)
setup(
data_files = data_files,
options = {"py2exe": {"compressed": 0,
"optimize": 1,
"includes": includes,
"excludes": excludes,
"packages": packages,
"dll_excludes": dll_excludes,
"bundle_files": 3,
"dist_dir": distDir,
"xref": False,
"skip_archive": False,
"ascii": False,
"custom_boot_script": '',
}
},
zipfile = r'library.zip',
console = [],
windows = [MyApp_Target],
service = [],
com_server = [],
ctypes_com_server = []
)
```
Build works, but I have error when I tried to launch application:
```
File "pymssql.pyo", line 12, in <module>
File "pymssql.pyo", line 10, in __load
File "_mssql.pxd", line 10, in init pymssql (pymssql.c:7370)
ImportError: No module named _mssql
```
\_mssql.pyd and pymssql.pyd files are in executable directory.
OS version Windows 7 Enterprice SP 1. | 2011/08/04 | [
"https://Stackoverflow.com/questions/6937505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/412793/"
] | In the program you are trying to import (eg. in the A.py for A.exe ), specify import statement for \_mssql as well. You might also need to import a couple of other modules (decimal & uuid )to get the exe working | ```
from distutils.core import setup
import py2exe, os, pymssql
import decimal
data_files = []
data_files.append(os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'))
py2exe_options = {"py2exe":{"includes": ['decimal'],
"dll_excludes":["mswsock.dll",
"powrprof.dll",
"user32.dll",
"shell32.dll",
"wsock32.dll",
"advapi32.dll",
"kernel32.dll",
"ntwdblib.dll",
"ws2_32.dll",
"oleaut32.dll",
"ole32.dll",
],
}}
setup(console=["jobs_pcc_main.py"], options= py2exe_options, data_files=data_files)
``` |
6,937,505 | I have python application that shoud be launched as windows executable. I'm using py2exe and pymssql 1.9.908.
I used next build script to generate application:
```
from distutils.core import setup
import MySQLdb
import fnmatch
import os
import pymssql
import shutil
import py2exe
import glob
##############
name = 'BGAgent'
old_version = '0.1'
ver = '0.1'
distDir = 'Dist' + name + ver
shutil.rmtree(distDir, True)
shutil.rmtree('Dist' + name + old_version, True)
os.mkdir(distDir)
##############
class Target(object):
""" A simple class that holds information on our executable file. """
def __init__(self, **kw):
""" Default class constructor. Update as you need. """
self.__dict__.update(kw)
# MySQLdb
#dst = os.path.join(distDir, "MySQLdb")
#copy_tree(MySQLdb.__path__[0], dst )
# pymssql
site_packages_dir = os.path.dirname(pymssql.__file__)
pymssql_files = []#'pymssql.py', 'pymssql.pyc', 'pymssql.pyo', '_mssql.pyd']
for eggInfo in glob.glob(os.path.join(site_packages_dir, '*mssql*')) :
pymssql_files.append(os.path.basename(eggInfo))
for fname in pymssql_files :
src = os.path.join(site_packages_dir, fname)
dst = os.path.join(distDir, fname)
if(os.path.isfile(src)) :
shutil.copy(src, dst)
else :
shutil.copytree(src, dst)
includes = ['MySQLdb', 'pymssql', 'OpenSSL']
excludes = ['run_w.exe'] #['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl', 'Tkconstants', 'Tkinter']
packages = ['MySQLdb', 'pymssql', 'OpenSSL']
dll_excludes = []#['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll']
data_files = ['server.pem',
'config.ini',
'run.bat',
#os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'),
]
icon_resources = []
bitmap_resources = []
other_resources = []
MyApp_Target = Target(
# what to build
script = "run.py",
icon_resources = icon_resources,
bitmap_resources = bitmap_resources,
other_resources = other_resources,
dest_base = name,
version = ver,
company_name = "",
copyright = "",
name = name,
)
setup(
data_files = data_files,
options = {"py2exe": {"compressed": 0,
"optimize": 1,
"includes": includes,
"excludes": excludes,
"packages": packages,
"dll_excludes": dll_excludes,
"bundle_files": 3,
"dist_dir": distDir,
"xref": False,
"skip_archive": False,
"ascii": False,
"custom_boot_script": '',
}
},
zipfile = r'library.zip',
console = [],
windows = [MyApp_Target],
service = [],
com_server = [],
ctypes_com_server = []
)
```
Build works, but I have error when I tried to launch application:
```
File "pymssql.pyo", line 12, in <module>
File "pymssql.pyo", line 10, in __load
File "_mssql.pxd", line 10, in init pymssql (pymssql.c:7370)
ImportError: No module named _mssql
```
\_mssql.pyd and pymssql.pyd files are in executable directory.
OS version Windows 7 Enterprice SP 1. | 2011/08/04 | [
"https://Stackoverflow.com/questions/6937505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/412793/"
] | In the program you are trying to import (eg. in the A.py for A.exe ), specify import statement for \_mssql as well. You might also need to import a couple of other modules (decimal & uuid )to get the exe working | Just add the statement `import _mssql` in your file. Next, run your program. When you get the same thing, just import that module in your code. This method works well for me. |
6,937,505 | I have python application that shoud be launched as windows executable. I'm using py2exe and pymssql 1.9.908.
I used next build script to generate application:
```
from distutils.core import setup
import MySQLdb
import fnmatch
import os
import pymssql
import shutil
import py2exe
import glob
##############
name = 'BGAgent'
old_version = '0.1'
ver = '0.1'
distDir = 'Dist' + name + ver
shutil.rmtree(distDir, True)
shutil.rmtree('Dist' + name + old_version, True)
os.mkdir(distDir)
##############
class Target(object):
""" A simple class that holds information on our executable file. """
def __init__(self, **kw):
""" Default class constructor. Update as you need. """
self.__dict__.update(kw)
# MySQLdb
#dst = os.path.join(distDir, "MySQLdb")
#copy_tree(MySQLdb.__path__[0], dst )
# pymssql
site_packages_dir = os.path.dirname(pymssql.__file__)
pymssql_files = []#'pymssql.py', 'pymssql.pyc', 'pymssql.pyo', '_mssql.pyd']
for eggInfo in glob.glob(os.path.join(site_packages_dir, '*mssql*')) :
pymssql_files.append(os.path.basename(eggInfo))
for fname in pymssql_files :
src = os.path.join(site_packages_dir, fname)
dst = os.path.join(distDir, fname)
if(os.path.isfile(src)) :
shutil.copy(src, dst)
else :
shutil.copytree(src, dst)
includes = ['MySQLdb', 'pymssql', 'OpenSSL']
excludes = ['run_w.exe'] #['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl', 'Tkconstants', 'Tkinter']
packages = ['MySQLdb', 'pymssql', 'OpenSSL']
dll_excludes = []#['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll']
data_files = ['server.pem',
'config.ini',
'run.bat',
#os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'),
]
icon_resources = []
bitmap_resources = []
other_resources = []
MyApp_Target = Target(
# what to build
script = "run.py",
icon_resources = icon_resources,
bitmap_resources = bitmap_resources,
other_resources = other_resources,
dest_base = name,
version = ver,
company_name = "",
copyright = "",
name = name,
)
setup(
data_files = data_files,
options = {"py2exe": {"compressed": 0,
"optimize": 1,
"includes": includes,
"excludes": excludes,
"packages": packages,
"dll_excludes": dll_excludes,
"bundle_files": 3,
"dist_dir": distDir,
"xref": False,
"skip_archive": False,
"ascii": False,
"custom_boot_script": '',
}
},
zipfile = r'library.zip',
console = [],
windows = [MyApp_Target],
service = [],
com_server = [],
ctypes_com_server = []
)
```
Build works, but I have error when I tried to launch application:
```
File "pymssql.pyo", line 12, in <module>
File "pymssql.pyo", line 10, in __load
File "_mssql.pxd", line 10, in init pymssql (pymssql.c:7370)
ImportError: No module named _mssql
```
\_mssql.pyd and pymssql.pyd files are in executable directory.
OS version Windows 7 Enterprice SP 1. | 2011/08/04 | [
"https://Stackoverflow.com/questions/6937505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/412793/"
] | In the program you are trying to import (eg. in the A.py for A.exe ), specify import statement for \_mssql as well. You might also need to import a couple of other modules (decimal & uuid )to get the exe working | To whom might help
I got lots of issues trying to user pymssql with Pyinstaller and
I finally got it right so posting here might help someone
after you install pymssql using pip install pymssql
use this parameters in pyinstaller to get it included
```
--onefile --paths=.\venv\ --hidden-import='pymssql' --hidden-import='uuid' --collect-all='pymssql' --collect-all='uuid'
``` |
6,937,505 | I have python application that shoud be launched as windows executable. I'm using py2exe and pymssql 1.9.908.
I used next build script to generate application:
```
from distutils.core import setup
import MySQLdb
import fnmatch
import os
import pymssql
import shutil
import py2exe
import glob
##############
name = 'BGAgent'
old_version = '0.1'
ver = '0.1'
distDir = 'Dist' + name + ver
shutil.rmtree(distDir, True)
shutil.rmtree('Dist' + name + old_version, True)
os.mkdir(distDir)
##############
class Target(object):
""" A simple class that holds information on our executable file. """
def __init__(self, **kw):
""" Default class constructor. Update as you need. """
self.__dict__.update(kw)
# MySQLdb
#dst = os.path.join(distDir, "MySQLdb")
#copy_tree(MySQLdb.__path__[0], dst )
# pymssql
site_packages_dir = os.path.dirname(pymssql.__file__)
pymssql_files = []#'pymssql.py', 'pymssql.pyc', 'pymssql.pyo', '_mssql.pyd']
for eggInfo in glob.glob(os.path.join(site_packages_dir, '*mssql*')) :
pymssql_files.append(os.path.basename(eggInfo))
for fname in pymssql_files :
src = os.path.join(site_packages_dir, fname)
dst = os.path.join(distDir, fname)
if(os.path.isfile(src)) :
shutil.copy(src, dst)
else :
shutil.copytree(src, dst)
includes = ['MySQLdb', 'pymssql', 'OpenSSL']
excludes = ['run_w.exe'] #['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl', 'Tkconstants', 'Tkinter']
packages = ['MySQLdb', 'pymssql', 'OpenSSL']
dll_excludes = []#['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll']
data_files = ['server.pem',
'config.ini',
'run.bat',
#os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'),
]
icon_resources = []
bitmap_resources = []
other_resources = []
MyApp_Target = Target(
# what to build
script = "run.py",
icon_resources = icon_resources,
bitmap_resources = bitmap_resources,
other_resources = other_resources,
dest_base = name,
version = ver,
company_name = "",
copyright = "",
name = name,
)
setup(
data_files = data_files,
options = {"py2exe": {"compressed": 0,
"optimize": 1,
"includes": includes,
"excludes": excludes,
"packages": packages,
"dll_excludes": dll_excludes,
"bundle_files": 3,
"dist_dir": distDir,
"xref": False,
"skip_archive": False,
"ascii": False,
"custom_boot_script": '',
}
},
zipfile = r'library.zip',
console = [],
windows = [MyApp_Target],
service = [],
com_server = [],
ctypes_com_server = []
)
```
Build works, but I have error when I tried to launch application:
```
File "pymssql.pyo", line 12, in <module>
File "pymssql.pyo", line 10, in __load
File "_mssql.pxd", line 10, in init pymssql (pymssql.c:7370)
ImportError: No module named _mssql
```
\_mssql.pyd and pymssql.pyd files are in executable directory.
OS version Windows 7 Enterprice SP 1. | 2011/08/04 | [
"https://Stackoverflow.com/questions/6937505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/412793/"
] | ```
from distutils.core import setup
import py2exe, os, pymssql
import decimal
data_files = []
data_files.append(os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'))
py2exe_options = {"py2exe":{"includes": ['decimal'],
"dll_excludes":["mswsock.dll",
"powrprof.dll",
"user32.dll",
"shell32.dll",
"wsock32.dll",
"advapi32.dll",
"kernel32.dll",
"ntwdblib.dll",
"ws2_32.dll",
"oleaut32.dll",
"ole32.dll",
],
}}
setup(console=["jobs_pcc_main.py"], options= py2exe_options, data_files=data_files)
``` | To whom might help
I got lots of issues trying to user pymssql with Pyinstaller and
I finally got it right so posting here might help someone
after you install pymssql using pip install pymssql
use this parameters in pyinstaller to get it included
```
--onefile --paths=.\venv\ --hidden-import='pymssql' --hidden-import='uuid' --collect-all='pymssql' --collect-all='uuid'
``` |
6,937,505 | I have python application that shoud be launched as windows executable. I'm using py2exe and pymssql 1.9.908.
I used next build script to generate application:
```
from distutils.core import setup
import MySQLdb
import fnmatch
import os
import pymssql
import shutil
import py2exe
import glob
##############
name = 'BGAgent'
old_version = '0.1'
ver = '0.1'
distDir = 'Dist' + name + ver
shutil.rmtree(distDir, True)
shutil.rmtree('Dist' + name + old_version, True)
os.mkdir(distDir)
##############
class Target(object):
""" A simple class that holds information on our executable file. """
def __init__(self, **kw):
""" Default class constructor. Update as you need. """
self.__dict__.update(kw)
# MySQLdb
#dst = os.path.join(distDir, "MySQLdb")
#copy_tree(MySQLdb.__path__[0], dst )
# pymssql
site_packages_dir = os.path.dirname(pymssql.__file__)
pymssql_files = []#'pymssql.py', 'pymssql.pyc', 'pymssql.pyo', '_mssql.pyd']
for eggInfo in glob.glob(os.path.join(site_packages_dir, '*mssql*')) :
pymssql_files.append(os.path.basename(eggInfo))
for fname in pymssql_files :
src = os.path.join(site_packages_dir, fname)
dst = os.path.join(distDir, fname)
if(os.path.isfile(src)) :
shutil.copy(src, dst)
else :
shutil.copytree(src, dst)
includes = ['MySQLdb', 'pymssql', 'OpenSSL']
excludes = ['run_w.exe'] #['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl', 'Tkconstants', 'Tkinter']
packages = ['MySQLdb', 'pymssql', 'OpenSSL']
dll_excludes = []#['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll']
data_files = ['server.pem',
'config.ini',
'run.bat',
#os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'),
]
icon_resources = []
bitmap_resources = []
other_resources = []
MyApp_Target = Target(
# what to build
script = "run.py",
icon_resources = icon_resources,
bitmap_resources = bitmap_resources,
other_resources = other_resources,
dest_base = name,
version = ver,
company_name = "",
copyright = "",
name = name,
)
setup(
data_files = data_files,
options = {"py2exe": {"compressed": 0,
"optimize": 1,
"includes": includes,
"excludes": excludes,
"packages": packages,
"dll_excludes": dll_excludes,
"bundle_files": 3,
"dist_dir": distDir,
"xref": False,
"skip_archive": False,
"ascii": False,
"custom_boot_script": '',
}
},
zipfile = r'library.zip',
console = [],
windows = [MyApp_Target],
service = [],
com_server = [],
ctypes_com_server = []
)
```
Build works, but I have error when I tried to launch application:
```
File "pymssql.pyo", line 12, in <module>
File "pymssql.pyo", line 10, in __load
File "_mssql.pxd", line 10, in init pymssql (pymssql.c:7370)
ImportError: No module named _mssql
```
\_mssql.pyd and pymssql.pyd files are in executable directory.
OS version Windows 7 Enterprice SP 1. | 2011/08/04 | [
"https://Stackoverflow.com/questions/6937505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/412793/"
] | Just add the statement `import _mssql` in your file. Next, run your program. When you get the same thing, just import that module in your code. This method works well for me. | To whom might help
I got lots of issues trying to user pymssql with Pyinstaller and
I finally got it right so posting here might help someone
after you install pymssql using pip install pymssql
use this parameters in pyinstaller to get it included
```
--onefile --paths=.\venv\ --hidden-import='pymssql' --hidden-import='uuid' --collect-all='pymssql' --collect-all='uuid'
``` |
10,068,576 | Is there a way to remove all references to an object at once? I know that's unpythonic, so I'll explain what I'm trying to do and maybe someone knows a better way.
I'm writing an object-oriented wrapper around a SWIG wrapper for a C library. When a proxy for one of the C objects is deleted, it also deletes child objects (directly in C). I'd like that to also trigger deletion of their proxy objects in Python. Otherwise I run into a situation where there are Python objects carrying around invalid pointers which will segfault if they're accessed.
It looks sort of like this:
```
class Parent(object):
def __init__(self):
self.ptr = swig.createParent()
def __del__(self):
swig.deleteParent(self.ptr) # also deletes children
class Child(object):
def __init__(self, parent):
self.ptr = swig.createChild(parent)
def __del__(self):
swig.deleteChild(self.ptr)
```
And this is the situation I'm worried about:
```
p = Parent()
c = Child(parent)
del p
# accessing c.ptr now would be bad right?
``` | 2012/04/09 | [
"https://Stackoverflow.com/questions/10068576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429898/"
] | If I understand you correctly, you are wrapping some C code, and the C code has a destructor that can be called. After that, any attempt to use the pointer to the C code object causes a fatal crash.
I am not sure of your exact situation, so I am going to give you two alternate answers.
0) If the C object can be freed for some reason out of your control, and you need to make sure your Python wrapper code doesn't crash, you need to make the Python wrapper know whether the C object is available or not. Make your Python object handle the pointer no longer being valid. You could raise a Python exception, return an error code, or just have the method functions become no-op functions, depending on what you are doing. The C object going away doesn't free the Python object, so you can handle this cleanly.
1) If the C object is only freed when the Python object is freed, you don't have a problem. Python references, when they go out of scope or you call `del()` on them, do not free the Python object; they just decrement the reference count on that object. When the reference count goes to zero, *then* the object is freed and your `__del__()` method function can call into the C code to free the C object.
You can watch how it works by running this code:
```
class DelTest(object):
def __init__(self):
print "__init__() called: object %08x created" % id(self)
def __del__(self):
print "__del__() called: object %08x destroyed" % id(self)
print "begin"
print "creating object, binding to name d"
d = DelTest()
print "adding reference bound to name x"
x = d
print "adding reference bound to lst[0]"
lst = []
lst.append(d)
print "deleting lst"
del(lst)
print "deleting x"
del(x)
print "deleting d"
del(d)
print "end"
```
Output from the above:
```
begin
creating object, binding to name d
__init__() called: object 01e4db50 created
adding reference bound to name x
adding reference bound to lst[0]
deleting lst
deleting x
deleting d
__del__() called: object 01e4db50 destroyed
end
``` | A note about the [behavior of `__del__()` method](http://docs.python.org/reference/datamodel.html#object.__del__).
>
> del x doesn’t directly call `x.__del__()` — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero.
>
>
>
Therefore even if you delete `parent`, it does not necessarily mean that `__del__` is executed immediately until there are any references to it. Here is an example.
```
>>> class C(object):
... def __del__(self):
... print "deleting object of type: %s" %self.__class__
...
>>> class D(object):
... def __init__(self, parent):
... self.parent = parent
... def __del__(self):
... print "deleting object of type: %s" % self.__class__
...
>>> c = C()
>>> d = D(c)
>>> del c
>>> del d
deleting object of type: <class '__main__.D'>
deleting object of type: <class '__main__.C'>
```
Note that the `__del__` method of `C` is called *after* the `del d` call. |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | This is a bug in the font management of matplotlib, on my machine this is the file /usr/lib/pymodules/python2.6/matplotlib/font\_manager.py:1220. I've highlighted the change in the code snippet below; this is fixed in the newest version of matplotlib.
```
if best_font is None or best_score >= 10.0:
verbose.report('findfont: Could not match %s. Returning %s' %
(prop, self.defaultFont))
[+]result = self.defaultFont[fontext]
[-]result = self.defaultFont
print "defaultFont", result
else:
verbose.report('findfont: Matching %s to %s (%s) with score of %f' %
(prop, best_font.name, best_font.fname, best_score))
result = best_font.fname
print "best_font", result
```
This error occurs only if no "good" font was found and the font manager falls back to a default font. Therefore the error occured without apparent reason, probably because of changes in the installed fonts.
Hope that helps! | I experienced a similar error today, concerning code that I know for a fact was working a week ago. I also have recently uninstalled/reinstalled both Matplotlib and Numpy, while checking something else (I'm using Python 2.5).
The code went something like this:
```
self.ax.cla()
if self.logy: self.ax.set_yscale('log')
self.canvas.draw()
```
Whenever it was run with self.logy as True, it failed as above. Otherwise, it worked perfectly fine.
I ended up sidsteping the issue by uninstalling Matplotlib and Numpy and installing the latest versions of them. However, the version throwing the error had previously been used with no problems. Only after swapping the old version for the newer one and back again did this start happening.
Perhaps the uninstall/reinstall process messes up certain aspects of the configuration files.
For completeness, here is the complete traceback given:
```
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\path\to\file\being\called\by\Tkinter.py", line 1081, in refresh
self.canvas.draw()
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_tkagg.py", line 215, in draw
FigureCanvasAgg.draw(self)
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 314, in draw
self.figure.draw(self.renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line 773, in draw
for a in self.axes: a.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axes.py", line 1735, in draw
a.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 742, in draw
tick.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 196, in draw
self.label1.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 515, in draw
bbox, info = self._get_layout(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 279, in _get_layout
clean_line, self._fontproperties, ismath=ismath)
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 156, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 2797, in parse
font_output = fontset_class(prop, backend)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 658, in __init__
self._stix_fallback = StixFonts(*args, **kwargs)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 900, in __init__
fullpath = findfont(name)
File "C:\Python25\Lib\site-packages\matplotlib\font_manager.py", line 1306, in findfont
if not os.path.exists(font):
File "C:\Python25\lib\ntpath.py", line 255, in exists
st = os.stat(path)
TypeError: coercing to Unicode: need string or buffer, dict found
``` |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | I had the same problem with matplotlib 0.98.5.2. I was able to fix it by upgrading to matplotlib 1.0.1 (0.99.3 didn't work), or by blowing away my ~/.matplotlib directory. Not sure what the equivalent is for Windows. | I experienced a similar error today, concerning code that I know for a fact was working a week ago. I also have recently uninstalled/reinstalled both Matplotlib and Numpy, while checking something else (I'm using Python 2.5).
The code went something like this:
```
self.ax.cla()
if self.logy: self.ax.set_yscale('log')
self.canvas.draw()
```
Whenever it was run with self.logy as True, it failed as above. Otherwise, it worked perfectly fine.
I ended up sidsteping the issue by uninstalling Matplotlib and Numpy and installing the latest versions of them. However, the version throwing the error had previously been used with no problems. Only after swapping the old version for the newer one and back again did this start happening.
Perhaps the uninstall/reinstall process messes up certain aspects of the configuration files.
For completeness, here is the complete traceback given:
```
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\path\to\file\being\called\by\Tkinter.py", line 1081, in refresh
self.canvas.draw()
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_tkagg.py", line 215, in draw
FigureCanvasAgg.draw(self)
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 314, in draw
self.figure.draw(self.renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line 773, in draw
for a in self.axes: a.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axes.py", line 1735, in draw
a.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 742, in draw
tick.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 196, in draw
self.label1.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 515, in draw
bbox, info = self._get_layout(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 279, in _get_layout
clean_line, self._fontproperties, ismath=ismath)
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 156, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 2797, in parse
font_output = fontset_class(prop, backend)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 658, in __init__
self._stix_fallback = StixFonts(*args, **kwargs)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 900, in __init__
fullpath = findfont(name)
File "C:\Python25\Lib\site-packages\matplotlib\font_manager.py", line 1306, in findfont
if not os.path.exists(font):
File "C:\Python25\lib\ntpath.py", line 255, in exists
st = os.stat(path)
TypeError: coercing to Unicode: need string or buffer, dict found
``` |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | I had the same problem today, and I found the issue in github
<https://github.com/matplotlib/matplotlib/issues/198>
The proposed workaround is to delete the `.matplotlib/fontList.cache` file, and worked for me. | I experienced a similar error today, concerning code that I know for a fact was working a week ago. I also have recently uninstalled/reinstalled both Matplotlib and Numpy, while checking something else (I'm using Python 2.5).
The code went something like this:
```
self.ax.cla()
if self.logy: self.ax.set_yscale('log')
self.canvas.draw()
```
Whenever it was run with self.logy as True, it failed as above. Otherwise, it worked perfectly fine.
I ended up sidsteping the issue by uninstalling Matplotlib and Numpy and installing the latest versions of them. However, the version throwing the error had previously been used with no problems. Only after swapping the old version for the newer one and back again did this start happening.
Perhaps the uninstall/reinstall process messes up certain aspects of the configuration files.
For completeness, here is the complete traceback given:
```
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\path\to\file\being\called\by\Tkinter.py", line 1081, in refresh
self.canvas.draw()
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_tkagg.py", line 215, in draw
FigureCanvasAgg.draw(self)
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 314, in draw
self.figure.draw(self.renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line 773, in draw
for a in self.axes: a.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axes.py", line 1735, in draw
a.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 742, in draw
tick.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
draw(artist, renderer, *kl)
File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 196, in draw
self.label1.draw(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 515, in draw
bbox, info = self._get_layout(renderer)
File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 279, in _get_layout
clean_line, self._fontproperties, ismath=ismath)
File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 156, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 2797, in parse
font_output = fontset_class(prop, backend)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 658, in __init__
self._stix_fallback = StixFonts(*args, **kwargs)
File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 900, in __init__
fullpath = findfont(name)
File "C:\Python25\Lib\site-packages\matplotlib\font_manager.py", line 1306, in findfont
if not os.path.exists(font):
File "C:\Python25\lib\ntpath.py", line 255, in exists
st = os.stat(path)
TypeError: coercing to Unicode: need string or buffer, dict found
``` |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | This is a bug in the font management of matplotlib, on my machine this is the file /usr/lib/pymodules/python2.6/matplotlib/font\_manager.py:1220. I've highlighted the change in the code snippet below; this is fixed in the newest version of matplotlib.
```
if best_font is None or best_score >= 10.0:
verbose.report('findfont: Could not match %s. Returning %s' %
(prop, self.defaultFont))
[+]result = self.defaultFont[fontext]
[-]result = self.defaultFont
print "defaultFont", result
else:
verbose.report('findfont: Matching %s to %s (%s) with score of %f' %
(prop, best_font.name, best_font.fname, best_score))
result = best_font.fname
print "best_font", result
```
This error occurs only if no "good" font was found and the font manager falls back to a default font. Therefore the error occured without apparent reason, probably because of changes in the installed fonts.
Hope that helps! | I had the same problem today, and I found the issue in github
<https://github.com/matplotlib/matplotlib/issues/198>
The proposed workaround is to delete the `.matplotlib/fontList.cache` file, and worked for me. |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | This is a bug in the font management of matplotlib, on my machine this is the file /usr/lib/pymodules/python2.6/matplotlib/font\_manager.py:1220. I've highlighted the change in the code snippet below; this is fixed in the newest version of matplotlib.
```
if best_font is None or best_score >= 10.0:
verbose.report('findfont: Could not match %s. Returning %s' %
(prop, self.defaultFont))
[+]result = self.defaultFont[fontext]
[-]result = self.defaultFont
print "defaultFont", result
else:
verbose.report('findfont: Matching %s to %s (%s) with score of %f' %
(prop, best_font.name, best_font.fname, best_score))
result = best_font.fname
print "best_font", result
```
This error occurs only if no "good" font was found and the font manager falls back to a default font. Therefore the error occured without apparent reason, probably because of changes in the installed fonts.
Hope that helps! | Thanks for explaining the issue!
Since I'm using the Mac OS 10.6 system install of matplotlib, (and I'm stuck on Python2.5 due to other package requirements) I am not interested in upgrading matplotlib (I just can't handle all the versioning of open-source packages!)
So the fix I randomly tried, which worked, was to edit my `~/.matplotlib/matplotlibrc`
and enable LaTex, by setting `text.usetex : True`
(since it showed a long list of supported fonts, so I thought it might try harder to find a "good" font).
Not a real "fix", but got my script working with minimal tinkering/downtime. |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | I had the same problem with matplotlib 0.98.5.2. I was able to fix it by upgrading to matplotlib 1.0.1 (0.99.3 didn't work), or by blowing away my ~/.matplotlib directory. Not sure what the equivalent is for Windows. | I had the same problem today, and I found the issue in github
<https://github.com/matplotlib/matplotlib/issues/198>
The proposed workaround is to delete the `.matplotlib/fontList.cache` file, and worked for me. |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | I had the same problem with matplotlib 0.98.5.2. I was able to fix it by upgrading to matplotlib 1.0.1 (0.99.3 didn't work), or by blowing away my ~/.matplotlib directory. Not sure what the equivalent is for Windows. | Thanks for explaining the issue!
Since I'm using the Mac OS 10.6 system install of matplotlib, (and I'm stuck on Python2.5 due to other package requirements) I am not interested in upgrading matplotlib (I just can't handle all the versioning of open-source packages!)
So the fix I randomly tried, which worked, was to edit my `~/.matplotlib/matplotlibrc`
and enable LaTex, by setting `text.usetex : True`
(since it showed a long list of supported fonts, so I thought it might try harder to find a "good" font).
Not a real "fix", but got my script working with minimal tinkering/downtime. |
3,479,887 | I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:
```
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
```
I get this error (at the `plt.show()` line):
```
TypeError: coercing to Unicode: need string or buffer, dict found
```
I've tried changing the backend to many different values - nothing helps. I am using `Qt4Agg`. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance. | 2010/08/13 | [
"https://Stackoverflow.com/questions/3479887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419902/"
] | I had the same problem today, and I found the issue in github
<https://github.com/matplotlib/matplotlib/issues/198>
The proposed workaround is to delete the `.matplotlib/fontList.cache` file, and worked for me. | Thanks for explaining the issue!
Since I'm using the Mac OS 10.6 system install of matplotlib, (and I'm stuck on Python2.5 due to other package requirements) I am not interested in upgrading matplotlib (I just can't handle all the versioning of open-source packages!)
So the fix I randomly tried, which worked, was to edit my `~/.matplotlib/matplotlibrc`
and enable LaTex, by setting `text.usetex : True`
(since it showed a long list of supported fonts, so I thought it might try harder to find a "good" font).
Not a real "fix", but got my script working with minimal tinkering/downtime. |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | You can do this using [Comparator](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html) as shown below:
```
List<String> sorted = List.of("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2")
.stream()
.sorted((s1, s2) -> {
String[] s1Parts = s1.split("\\.");
String[] s2Parts = s2.split("\\.");
Integer[] s1IntParts = Arrays.stream(s1Parts).map(Integer::parseInt).toArray(Integer[]::new);
Integer[] s2IntParts = Arrays.stream(s2Parts).map(Integer::parseInt).toArray(Integer[]::new);
int comparisonResult = -1;
for (int i=0; i<3; i++) {
comparisonResult = Integer.compare(s1IntParts[i], s2IntParts[i]);
if (comparisonResult != 0) {
break;
}
}
return comparisonResult;
})
.collect(Collectors.toList());
``` | Assuming:
```
List<String> versions = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");
```
You should use a custom `Comparator` as long as the default comparator cannot be applied to this type of the String, otherwise the numbers will not be sorted numerically (ex, `12` is considered lower than `2`.
```
versions.sort(new Comparator<String>() {
@Override
public int compare(final String l, final String r) {
String[] left = l.split("\\.");
String[] right = r.split("\\.");
int iterableLength = Math.min(left.length, right.length);
for (int i=0; i<iterableLength; i++) {
if (!left[i].equals(right[i])) {
return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
}
}
return 0;
}
});
```
... using a lambda expression ...
```
versions.sort((l, r) -> {
String[] left = l.split("\\.");
String[] right = r.split("\\.");
int iterableLength = Math.min(left.length, right.length);
for (int i=0; i<iterableLength; i++) {
if (!left[i].equals(right[i])) {
return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
}
}
return 0;
});
```
This is a very straightforward solution using Regex to split the version notation into 3 separate parts. Each part not equal to another is a subject for the numeric comparison, hence `Integer.parseInt(String)` is needed. |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | ```
public static void main(String[] args) {
String[] versions_list = {"1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"};
Arrays.sort(versions_list, (o1, o2) -> {
String[] str1 = o1.split("\\.");
String[] str2 = o2.split("\\.");
if (!Integer.valueOf(str1[0]).equals(Integer.valueOf(str2[0])))
return Integer.valueOf(str1[0]) - Integer.valueOf(str2[0]);
if (!Integer.valueOf(str1[1]).equals(Integer.valueOf(str2[1])))
return Integer.valueOf(str1[1]) - Integer.valueOf(str2[1]);
return Integer.valueOf(str1[2]) - Integer.valueOf(str2[2]);
});
for (String str : versions_list) {
System.out.println(str);
}
}
```
sorry,I wirte code again
output:1.0.0 1.0.2 1.0.12 1.1.2 1.3.3, you also use cycle to do it! | Assuming:
```
List<String> versions = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");
```
You should use a custom `Comparator` as long as the default comparator cannot be applied to this type of the String, otherwise the numbers will not be sorted numerically (ex, `12` is considered lower than `2`.
```
versions.sort(new Comparator<String>() {
@Override
public int compare(final String l, final String r) {
String[] left = l.split("\\.");
String[] right = r.split("\\.");
int iterableLength = Math.min(left.length, right.length);
for (int i=0; i<iterableLength; i++) {
if (!left[i].equals(right[i])) {
return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
}
}
return 0;
}
});
```
... using a lambda expression ...
```
versions.sort((l, r) -> {
String[] left = l.split("\\.");
String[] right = r.split("\\.");
int iterableLength = Math.min(left.length, right.length);
for (int i=0; i<iterableLength; i++) {
if (!left[i].equals(right[i])) {
return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
}
}
return 0;
});
```
This is a very straightforward solution using Regex to split the version notation into 3 separate parts. Each part not equal to another is a subject for the numeric comparison, hence `Integer.parseInt(String)` is needed. |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | Here is a *modern* solution, using `Comparator.comparing` to build a version string comparator, based on the pre-existing standard library `Arrays.compare(int[])` method.
```
List<String> versionList = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");
Pattern pattern = Pattern.compile("\\.");
Comparator<String> versionComparator = Comparator.comparing(
str -> pattern.splitAsStream(str)
.mapToInt(Integer::parseInt)
.toArray(),
Arrays::compare);
versionList.sort(versionComparator);
System.out.println(versionList);
``` | Assuming:
```
List<String> versions = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");
```
You should use a custom `Comparator` as long as the default comparator cannot be applied to this type of the String, otherwise the numbers will not be sorted numerically (ex, `12` is considered lower than `2`.
```
versions.sort(new Comparator<String>() {
@Override
public int compare(final String l, final String r) {
String[] left = l.split("\\.");
String[] right = r.split("\\.");
int iterableLength = Math.min(left.length, right.length);
for (int i=0; i<iterableLength; i++) {
if (!left[i].equals(right[i])) {
return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
}
}
return 0;
}
});
```
... using a lambda expression ...
```
versions.sort((l, r) -> {
String[] left = l.split("\\.");
String[] right = r.split("\\.");
int iterableLength = Math.min(left.length, right.length);
for (int i=0; i<iterableLength; i++) {
if (!left[i].equals(right[i])) {
return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
}
}
return 0;
});
```
This is a very straightforward solution using Regex to split the version notation into 3 separate parts. Each part not equal to another is a subject for the numeric comparison, hence `Integer.parseInt(String)` is needed. |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | Here is a *modern* solution, using `Comparator.comparing` to build a version string comparator, based on the pre-existing standard library `Arrays.compare(int[])` method.
```
List<String> versionList = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");
Pattern pattern = Pattern.compile("\\.");
Comparator<String> versionComparator = Comparator.comparing(
str -> pattern.splitAsStream(str)
.mapToInt(Integer::parseInt)
.toArray(),
Arrays::compare);
versionList.sort(versionComparator);
System.out.println(versionList);
``` | You can do this using [Comparator](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html) as shown below:
```
List<String> sorted = List.of("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2")
.stream()
.sorted((s1, s2) -> {
String[] s1Parts = s1.split("\\.");
String[] s2Parts = s2.split("\\.");
Integer[] s1IntParts = Arrays.stream(s1Parts).map(Integer::parseInt).toArray(Integer[]::new);
Integer[] s2IntParts = Arrays.stream(s2Parts).map(Integer::parseInt).toArray(Integer[]::new);
int comparisonResult = -1;
for (int i=0; i<3; i++) {
comparisonResult = Integer.compare(s1IntParts[i], s2IntParts[i]);
if (comparisonResult != 0) {
break;
}
}
return comparisonResult;
})
.collect(Collectors.toList());
``` |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | You can do this using [Comparator](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html) as shown below:
```
List<String> sorted = List.of("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2")
.stream()
.sorted((s1, s2) -> {
String[] s1Parts = s1.split("\\.");
String[] s2Parts = s2.split("\\.");
Integer[] s1IntParts = Arrays.stream(s1Parts).map(Integer::parseInt).toArray(Integer[]::new);
Integer[] s2IntParts = Arrays.stream(s2Parts).map(Integer::parseInt).toArray(Integer[]::new);
int comparisonResult = -1;
for (int i=0; i<3; i++) {
comparisonResult = Integer.compare(s1IntParts[i], s2IntParts[i]);
if (comparisonResult != 0) {
break;
}
}
return comparisonResult;
})
.collect(Collectors.toList());
``` | Here is one way using a lambda of the Comparator. Takes care of varying length version ids.
```
Comparator<String> comp = (a, b) -> {
String[] aa = a.split("\\.");
String[] bb = b.split("\\.");
int r = 0;
for (int i = 0; i < Math.min(aa.length, bb.length); i++) {
r = Integer
.compare(Integer.valueOf(aa[i]),Integer.valueOf(bb[i]));
if (r != 0) {
return r;
}
}
return Integer.compare(aa.length, bb.length);
};
List<String> versions_list = Arrays.asList("1.1.2", "1.0.0",
"1.3.3", "1.0.12", "1.0.0.12", "1.1.0.2", "1.0.2", "1.2.1.2.3");
versions_list.sort(comp);
System.out.println(versions_list);
```
Prints
```
[1.0.0, 1.0.0.12, 1.0.2, 1.0.12, 1.1.0.2, 1.1.2, 1.2.1.2.3, 1.3.3]
``` |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | Here is a *modern* solution, using `Comparator.comparing` to build a version string comparator, based on the pre-existing standard library `Arrays.compare(int[])` method.
```
List<String> versionList = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");
Pattern pattern = Pattern.compile("\\.");
Comparator<String> versionComparator = Comparator.comparing(
str -> pattern.splitAsStream(str)
.mapToInt(Integer::parseInt)
.toArray(),
Arrays::compare);
versionList.sort(versionComparator);
System.out.println(versionList);
``` | ```
public static void main(String[] args) {
String[] versions_list = {"1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"};
Arrays.sort(versions_list, (o1, o2) -> {
String[] str1 = o1.split("\\.");
String[] str2 = o2.split("\\.");
if (!Integer.valueOf(str1[0]).equals(Integer.valueOf(str2[0])))
return Integer.valueOf(str1[0]) - Integer.valueOf(str2[0]);
if (!Integer.valueOf(str1[1]).equals(Integer.valueOf(str2[1])))
return Integer.valueOf(str1[1]) - Integer.valueOf(str2[1]);
return Integer.valueOf(str1[2]) - Integer.valueOf(str2[2]);
});
for (String str : versions_list) {
System.out.println(str);
}
}
```
sorry,I wirte code again
output:1.0.0 1.0.2 1.0.12 1.1.2 1.3.3, you also use cycle to do it! |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | ```
public static void main(String[] args) {
String[] versions_list = {"1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"};
Arrays.sort(versions_list, (o1, o2) -> {
String[] str1 = o1.split("\\.");
String[] str2 = o2.split("\\.");
if (!Integer.valueOf(str1[0]).equals(Integer.valueOf(str2[0])))
return Integer.valueOf(str1[0]) - Integer.valueOf(str2[0]);
if (!Integer.valueOf(str1[1]).equals(Integer.valueOf(str2[1])))
return Integer.valueOf(str1[1]) - Integer.valueOf(str2[1]);
return Integer.valueOf(str1[2]) - Integer.valueOf(str2[2]);
});
for (String str : versions_list) {
System.out.println(str);
}
}
```
sorry,I wirte code again
output:1.0.0 1.0.2 1.0.12 1.1.2 1.3.3, you also use cycle to do it! | Here is one way using a lambda of the Comparator. Takes care of varying length version ids.
```
Comparator<String> comp = (a, b) -> {
String[] aa = a.split("\\.");
String[] bb = b.split("\\.");
int r = 0;
for (int i = 0; i < Math.min(aa.length, bb.length); i++) {
r = Integer
.compare(Integer.valueOf(aa[i]),Integer.valueOf(bb[i]));
if (r != 0) {
return r;
}
}
return Integer.compare(aa.length, bb.length);
};
List<String> versions_list = Arrays.asList("1.1.2", "1.0.0",
"1.3.3", "1.0.12", "1.0.0.12", "1.1.0.2", "1.0.2", "1.2.1.2.3");
versions_list.sort(comp);
System.out.println(versions_list);
```
Prints
```
[1.0.0, 1.0.0.12, 1.0.2, 1.0.12, 1.1.0.2, 1.1.2, 1.2.1.2.3, 1.3.3]
``` |
63,206,368 | Python does not work in PowerShell anymore.
I've never had any problems, until recently. CMD still recognizes the `py` command, but powershell doesn't recognize any of the basic python commands: `py`,`py3`,`python`,`python3`.
My problem occured after I installed MinGW and added its path to the Path variable.
I have restarted my computer many times, while trying new things.
Things I've tried:
* I have tried removing MinGW from the Path variable.
* I have tried uninstalling MinGW.
* I have tried reinstalling python.
* I have tried manually adding the Python path.
* I have tried letting Python automatically add my Python path.
* I have tried adding the Python path to both the user environment variables and the system variables.
* I have tried running PowerShell as administrator.
Finally, this is what my Path variable looks like now:
**User Path Variable:**
```
C:\Users\lcdew\AppData\Local\Microsoft\WindowsApps
C:\Users\lcdew\AppData\Local\GitHubDesktop\bin
```
**System Path Variable:**
```
C:\Program Files\Python38\Scripts
C:\Program Files\Python38
C:\Program Files\Scripts
C:\Program Files
C:\Program Files (x86)\Scripts
C:\Program Files (x86)
C:\Program Files (x86)\Razer Chroma SDK\bin
C:\Program Files\Razer Chroma SDK\bin
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0
C:\Windows\System32\OpenSSH
C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps
C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common
``` | 2020/08/01 | [
"https://Stackoverflow.com/questions/63206368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583502/"
] | Here is a *modern* solution, using `Comparator.comparing` to build a version string comparator, based on the pre-existing standard library `Arrays.compare(int[])` method.
```
List<String> versionList = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");
Pattern pattern = Pattern.compile("\\.");
Comparator<String> versionComparator = Comparator.comparing(
str -> pattern.splitAsStream(str)
.mapToInt(Integer::parseInt)
.toArray(),
Arrays::compare);
versionList.sort(versionComparator);
System.out.println(versionList);
``` | Here is one way using a lambda of the Comparator. Takes care of varying length version ids.
```
Comparator<String> comp = (a, b) -> {
String[] aa = a.split("\\.");
String[] bb = b.split("\\.");
int r = 0;
for (int i = 0; i < Math.min(aa.length, bb.length); i++) {
r = Integer
.compare(Integer.valueOf(aa[i]),Integer.valueOf(bb[i]));
if (r != 0) {
return r;
}
}
return Integer.compare(aa.length, bb.length);
};
List<String> versions_list = Arrays.asList("1.1.2", "1.0.0",
"1.3.3", "1.0.12", "1.0.0.12", "1.1.0.2", "1.0.2", "1.2.1.2.3");
versions_list.sort(comp);
System.out.println(versions_list);
```
Prints
```
[1.0.0, 1.0.0.12, 1.0.2, 1.0.12, 1.1.0.2, 1.1.2, 1.2.1.2.3, 1.3.3]
``` |
62,326,253 | ```
curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" --header "Content-Type: application/json" \
--data '{"path": "<subgroup_path>", "name": "<subgroup_name>", "parent_id": <parent_group_id> } \
"https://gitlab.example.com/api/v4/groups/"
```
I was following the documentation from [gitlab](https://docs.gitlab.com/ee/api/groups.html#new-subgroup). I just wanted to to know how to represent the part after `--data` as a python request. Will it be a part of `params`, `json` or any other parameter in requests module?
Any help is appreciated. Thank you. | 2020/06/11 | [
"https://Stackoverflow.com/questions/62326253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11430726/"
] | Here's the equivalent using `requests`:
```
import requests
import json
headers = {
"PRIVATE-TOKEN": "<your_access_token>",
"Content-Type": "application/json",
}
data = {
"path": "<subgroup_path>",
"name": "<subgroup_name>",
"parent_id": "<parent_group_id>",
}
requests.post("https://gitlab.example.com/api/v4/groups/",
headers=headers, data=json.dumps(data))
``` | It can be done by python's [requests](https://2.python-requests.org/en/master/) package.
```
import requests
import json
url = "https://gitlab.example.com/api/v4/groups/"
headers = {'PRIVATE-TOKEN': '<your_access_token>', 'Content-Type':'application/json'}
data = {"path": "<subgroup_path>", "name": "<subgroup_name>", "parent_id": <parent_group_id>}
requests.post(url, data=json.dumps(data), headers=headers)
```
reference : [Python Request Post with param data](https://stackoverflow.com/questions/15900338/python-request-post-with-param-data) |
49,643,205 | I installed ansible on MAC High Sierra 10.13.3 and when I am trying to run
"ansible --version" I am receiving following error
-bash: /usr/local/bin/ansible: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory
Please let me know if you have ran into same issue or have solution. | 2018/04/04 | [
"https://Stackoverflow.com/questions/49643205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594666/"
] | `/usr/local/bin/ansible` has PATH `"/usr/local/opt/python/bin/python2.7"` on the first line. and in `/usr/local/opt/python/bin/` directory I had python3.6 instead of python2.7.
So I changed PATH on file `vi /usr/local/bin/ansible`
from `#!/usr/local/opt/python/bin/python2.7`
to `#!/usr/local/opt/python/bin/python3.6`
and that fixed the issue
Verification :
```sh
$ ansible --version
ansible 2.5.0
config file = None
configured module search path = ['/Users/<username>/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/<username>/Library/Python/3.6/lib/python/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.6.4 (default, Mar 1 2018, 18:36:50) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]
$ ansible localhost -m ping
localhost | SUCCESS => {
"changed": false,
"ping": "pong"
}
$ ansible localhost -m setup -a 'filter=ansible_distribution'
localhost | SUCCESS => {
"ansible_facts": {
"ansible_distribution": "MacOSX"
},
"changed": false
}
``` | Changing the python version might be pushing into some compatibility issues
It happens, when we have multiple python versions installed in our OS.
Simple steps for troubleshooting:
1. Check the python version
command: `which python /usr/bin/python`
2. Create a soft link to the path
command : `ln -s /usr/bin/python /usr/local/opt/python/bin/python2.7`
I hope it will fix the error. |
49,643,205 | I installed ansible on MAC High Sierra 10.13.3 and when I am trying to run
"ansible --version" I am receiving following error
-bash: /usr/local/bin/ansible: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory
Please let me know if you have ran into same issue or have solution. | 2018/04/04 | [
"https://Stackoverflow.com/questions/49643205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594666/"
] | `/usr/local/bin/ansible` has PATH `"/usr/local/opt/python/bin/python2.7"` on the first line. and in `/usr/local/opt/python/bin/` directory I had python3.6 instead of python2.7.
So I changed PATH on file `vi /usr/local/bin/ansible`
from `#!/usr/local/opt/python/bin/python2.7`
to `#!/usr/local/opt/python/bin/python3.6`
and that fixed the issue
Verification :
```sh
$ ansible --version
ansible 2.5.0
config file = None
configured module search path = ['/Users/<username>/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/<username>/Library/Python/3.6/lib/python/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.6.4 (default, Mar 1 2018, 18:36:50) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)]
$ ansible localhost -m ping
localhost | SUCCESS => {
"changed": false,
"ping": "pong"
}
$ ansible localhost -m setup -a 'filter=ansible_distribution'
localhost | SUCCESS => {
"ansible_facts": {
"ansible_distribution": "MacOSX"
},
"changed": false
}
``` | In my case I am using [pyenv](https://github.com/pyenv/pyenv) to manage my python versions and $PATH and symlinks were all correct pointing to the correct paths.
### Check your python paths
```sh
$ pyenv which python
/Users/<username>/.pyenv/versions/3.7.3/bin/python
$ which python
/Users/<username>/.pyenv/shims/python
```
### Check ansible configuration
ansible configuration at `/usr/local/bin/ansible` pointed the correct python version 3.7
```
#!/usr/local/opt/python/bin/python3.7
.
.
.
```
but `ansible --version` returned python 2.7 as its interpreter
```sh
$ ansible --version
ansible 2.9.12
configured module search path = ['/Users/<username>/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/<username>/.pyenv/versions/2.7.16/lib/python2.7/site-packages/ansible
executable location = /Users/<username>/.pyenv/versions/2.7.16/bin/ansible
python version = 2.7.16 (default, Apr 2 2020, 13:02:51) [Clang 11.0.3 (clang-1103.0.32.29)]
```
### Ansible for Python3
[Official ansible docs](https://docs.ansible.com/ansible/latest/reference_appendices/python_3_support.html) said to use pip3 to install ansible for python3 and I uninstalled ansible and reinstalled using pip3 but the interperter still pointed to python2.7.
Finally I manually added [.ansible.cfg](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#ansible-configuration-settings) file in my home path and configured python interpreted manually by adding
```
ansible_python_interpreter=/usr/bin/python
```
[Example config file](https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg) for ansible.cfg
Now ansible is configured for python3 correctly
```
ansible 2.9.12
config file = /Users/<username>/.ansible.cfg
configured module search path = ['/Users/<username>/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/<username>/.pyenv/versions/3.7.3/lib/python3.7/site-packages/ansible
executable location = /Users/<username>/.pyenv/versions/3.7.3/bin/ansible
python version = 3.7.3 (default, Apr 2 2020, 13:02:51) [Clang 11.0.3 (clang-1103.0.32.29)]
``` |
49,643,205 | I installed ansible on MAC High Sierra 10.13.3 and when I am trying to run
"ansible --version" I am receiving following error
-bash: /usr/local/bin/ansible: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory
Please let me know if you have ran into same issue or have solution. | 2018/04/04 | [
"https://Stackoverflow.com/questions/49643205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594666/"
] | In my case I am using [pyenv](https://github.com/pyenv/pyenv) to manage my python versions and $PATH and symlinks were all correct pointing to the correct paths.
### Check your python paths
```sh
$ pyenv which python
/Users/<username>/.pyenv/versions/3.7.3/bin/python
$ which python
/Users/<username>/.pyenv/shims/python
```
### Check ansible configuration
ansible configuration at `/usr/local/bin/ansible` pointed the correct python version 3.7
```
#!/usr/local/opt/python/bin/python3.7
.
.
.
```
but `ansible --version` returned python 2.7 as its interpreter
```sh
$ ansible --version
ansible 2.9.12
configured module search path = ['/Users/<username>/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/<username>/.pyenv/versions/2.7.16/lib/python2.7/site-packages/ansible
executable location = /Users/<username>/.pyenv/versions/2.7.16/bin/ansible
python version = 2.7.16 (default, Apr 2 2020, 13:02:51) [Clang 11.0.3 (clang-1103.0.32.29)]
```
### Ansible for Python3
[Official ansible docs](https://docs.ansible.com/ansible/latest/reference_appendices/python_3_support.html) said to use pip3 to install ansible for python3 and I uninstalled ansible and reinstalled using pip3 but the interperter still pointed to python2.7.
Finally I manually added [.ansible.cfg](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#ansible-configuration-settings) file in my home path and configured python interpreted manually by adding
```
ansible_python_interpreter=/usr/bin/python
```
[Example config file](https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg) for ansible.cfg
Now ansible is configured for python3 correctly
```
ansible 2.9.12
config file = /Users/<username>/.ansible.cfg
configured module search path = ['/Users/<username>/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/<username>/.pyenv/versions/3.7.3/lib/python3.7/site-packages/ansible
executable location = /Users/<username>/.pyenv/versions/3.7.3/bin/ansible
python version = 3.7.3 (default, Apr 2 2020, 13:02:51) [Clang 11.0.3 (clang-1103.0.32.29)]
``` | Changing the python version might be pushing into some compatibility issues
It happens, when we have multiple python versions installed in our OS.
Simple steps for troubleshooting:
1. Check the python version
command: `which python /usr/bin/python`
2. Create a soft link to the path
command : `ln -s /usr/bin/python /usr/local/opt/python/bin/python2.7`
I hope it will fix the error. |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | You need to store the value of either a or b in a temporary variable first;
```
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
``` | i'll do this
```
fib = 100;
for(int a = 1, b = 0;a <= fib;a += b, b = (a-b)) {
System.out.print(a + ",");
}
``` |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | The line
```
a, b = b, b+a
```
Doesn't easily translate. It's something like this. You could simplify it. This is the literal meaning.
```
t1 = b
t2 = b+a
a = t1
b = t2
``` | The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this:
```
Make a list out of 'b' and 'a + b'
Make another list out of references to 'a' and 'b'
Assign all the elements from the second list to the first one
```
(It might actually be a tuple, I'm not exactly fluent in Python.)
So the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java.
In general, a statement in Python like
```
var1, var2, ...varN = expression1, expression2, ...expressionN
```
is going to translate in Java to
```
temp1 = expression1;
temp2 = expression2;
...
tempN = expressionN;
var1 = temp1;
var2 = temp2;
...
varN = tempN;
```
This way all the expressions resolve to values **before** the assignments happen, and none of the assignments have side effects on the expressions.
If I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible. |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | Java integers can only store the first 46 Fibonacci numbers, use a lookup table. | Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid:
```
public int Fibb(int index) {
if (index < 2)
return 1;
else
return Fibb(index-1)+Fibb(index-2);
};
```
Given the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover. |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | You need to store the value of either a or b in a temporary variable first;
```
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
``` | Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid:
```
public int Fibb(int index) {
if (index < 2)
return 1;
else
return Fibb(index-1)+Fibb(index-2);
};
```
Given the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover. |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | You need to store the value of either a or b in a temporary variable first;
```
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
``` | I'll just translate your earlier code:
```
public void fibb(int max) {
int a = 0;
int b = 1;
while (a < max) {
System.out.println(a);
int temp = a + b;
a = b;
b = temp;
}
}
``` |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | I'd do it this way:
```
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
```
This keeps it as close to your original Java code as possible.
*[Editor's note: `Integers` have been replaced with `ints`. There is no reason to use `Integers` for this.]* | The line
```
a, b = b, b+a
```
Doesn't easily translate. It's something like this. You could simplify it. This is the literal meaning.
```
t1 = b
t2 = b+a
a = t1
b = t2
``` |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | There was a recursive solution posted above, but this solution is tail recursive so it grows linearly.
```
public class Fibonacci {
public long fibonacci(int number) {
return fib(0,1,number);
}
private long fib(long result, long next, int n) {
if (n == 0)
return result;
else
return fib(next, result+next, n-1);
}
}
``` | public Integer increment() {
a = b;
b = a + b;
return value;
}
Is certainly wrong. I think switching the first two lines should do the trick |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | You need to store the value of either a or b in a temporary variable first;
```
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
``` | public Integer increment() {
a = b;
b = a + b;
return value;
}
Is certainly wrong. I think switching the first two lines should do the trick |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | I'd do it this way:
```
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
```
This keeps it as close to your original Java code as possible.
*[Editor's note: `Integers` have been replaced with `ints`. There is no reason to use `Integers` for this.]* | There was a recursive solution posted above, but this solution is tail recursive so it grows linearly.
```
public class Fibonacci {
public long fibonacci(int number) {
return fib(0,1,number);
}
private long fib(long result, long next, int n) {
if (n == 0)
return result;
else
return fib(next, result+next, n-1);
}
}
``` |
1,045,151 | I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
```
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
```
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
```
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
```
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me. | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128967/"
] | Java integers can only store the first 46 Fibonacci numbers, use a lookup table. | The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this:
```
Make a list out of 'b' and 'a + b'
Make another list out of references to 'a' and 'b'
Assign all the elements from the second list to the first one
```
(It might actually be a tuple, I'm not exactly fluent in Python.)
So the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java.
In general, a statement in Python like
```
var1, var2, ...varN = expression1, expression2, ...expressionN
```
is going to translate in Java to
```
temp1 = expression1;
temp2 = expression2;
...
tempN = expressionN;
var1 = temp1;
var2 = temp2;
...
varN = tempN;
```
This way all the expressions resolve to values **before** the assignments happen, and none of the assignments have side effects on the expressions.
If I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible. |
65,347,497 | What improvements can I make to my python pandas code to make it more efficient? For my case, I have this dataframe
```
In [1]: df = pd.DataFrame({'PersonID': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'Name': ["Jan", "Jan", "Jan", "Don", "Don", "Don", "Joe", "Joe", "Joe"],
'Label': ["REL", "REL", "REL", "REL", "REL", "REL", "REL", "REL", "REL"],
'RuleID': [55, 55, 55, 3, 3, 3, 10, 10, 10],
'RuleNumber': [3, 4, 5, 1, 2, 3, 234, 567, 999]})
```
Which gives this result:
```
In [2]: df
Out[2]:
PersonID Name Label RuleID RuleNumber
0 1 Jan REL 55 3
1 1 Jan REL 55 4
2 1 Jan REL 55 5
3 2 Don REL 3 1
4 2 Don REL 3 2
5 2 Don REL 3 3
6 3 Joe REL 10 234
7 3 Joe REL 10 567
8 3 Joe REL 10 999
```
What I need to accomplished here is to update the fields under the Label column to MAIN for the lowest rule value associated with each Rule ID that is applied to a Person ID and Name. Therefore, the results need to look like this:
```
In [3]: df
Out[3]:
PersonID Name Label RuleID RuleNumber
0 1 Jan MAIN 55 3
1 1 Jan REL 55 4
2 1 Jan REL 55 5
3 2 Don MAIN 3 1
4 2 Don REL 3 2
5 2 Don REL 3 3
6 3 Joe MAIN 10 234
7 3 Joe REL 10 567
8 3 Joe REL 10 999
```
This is the code that I wrote to accomplish this:
```
In [4]:
df['Label'] = np.where(
df['RuleNumber'] ==
df.groupby(['PersonID', 'Name', 'RuleID'])['RuleNumber'].transform('min'),
"MAIN", df.Label)
```
Is there a better way to update the values under the Label column? I feel like I'm brute forcing my way through and this may not be the most efficient way to do this.
I used the following SO threads to arrive at my result:
[Replace column values within a groupby and condition](https://stackoverflow.com/questions/48142757/replace-column-values-within-a-groupby-and-condition)
[Replace values within a groupby based on multiple conditions](https://stackoverflow.com/questions/50418372/replace-values-within-a-groupby-based-on-multiple-conditions?noredirect=1&lq=1)
<https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmin.html>
<https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html>
[Using Pandas to Find Minimum Values of Grouped Rows](https://stackoverflow.com/questions/41450963/using-pandas-to-find-minimum-values-of-grouped-rows)
Any advice would be appreciated.
Thank you. | 2020/12/17 | [
"https://Stackoverflow.com/questions/65347497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14557333/"
] | It seems like you can filter by the grouped `idxmin` regardless of sorted order and update `RuleNumber` based on that. You can use `loc`, `np.where`, `mask`, or `where` as follows:
```
df.loc[df.groupby(['PersonID', 'Name', 'RuleID'])['RuleNumber'].idxmin(), 'Label'] = 'MAIN'
```
OR with `np.where` as you were trying:
```
df['Label'] = (np.where((df.index == df.groupby(['PersonID', 'Name', 'RuleID'])
['RuleNumber'].transform('idxmin')), 'MAIN', 'REL'))
df
Out[1]:
PersonID Name Label RuleID RuleNumber
0 1 Jan MAIN 55 3
1 1 Jan REL 55 4
2 1 Jan REL 55 5
3 2 Don MAIN 3 1
4 2 Don REL 3 2
5 2 Don REL 3 3
6 3 Joe MAIN 10 234
7 3 Joe REL 10 567
8 3 Joe REL 10 999
```
Using `mask` or its inverse `where` would also work:
```
df['Label'] = (df['Label'].mask((df.index == df.groupby(['PersonID', 'Name', 'RuleID'])
['RuleNumber'].transform('idxmin')), 'MAIN'))
```
OR
```
df['Label'] = (df['Label'].where((df.index != df.groupby(['PersonID', 'Name', 'RuleID'])
['RuleNumber'].transform('idxmin')), 'MAIN'))
``` | Use `duplicated` on PersonID:
```
df.loc[~df['PersonID'].duplicated(),'Label'] = 'MAIN'
print(df)
```
Output:
```
PersonID Name Label RuleID RuleNumber
0 1 Jan MAIN 55 3
1 1 Jan REL 55 4
2 1 Jan REL 55 5
3 2 Don MAIN 3 1
4 2 Don REL 3 2
5 2 Don REL 3 3
6 3 Joe MAIN 10 234
7 3 Joe REL 10 567
8 3 Joe REL 10 999
``` |
65,347,497 | What improvements can I make to my python pandas code to make it more efficient? For my case, I have this dataframe
```
In [1]: df = pd.DataFrame({'PersonID': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'Name': ["Jan", "Jan", "Jan", "Don", "Don", "Don", "Joe", "Joe", "Joe"],
'Label': ["REL", "REL", "REL", "REL", "REL", "REL", "REL", "REL", "REL"],
'RuleID': [55, 55, 55, 3, 3, 3, 10, 10, 10],
'RuleNumber': [3, 4, 5, 1, 2, 3, 234, 567, 999]})
```
Which gives this result:
```
In [2]: df
Out[2]:
PersonID Name Label RuleID RuleNumber
0 1 Jan REL 55 3
1 1 Jan REL 55 4
2 1 Jan REL 55 5
3 2 Don REL 3 1
4 2 Don REL 3 2
5 2 Don REL 3 3
6 3 Joe REL 10 234
7 3 Joe REL 10 567
8 3 Joe REL 10 999
```
What I need to accomplished here is to update the fields under the Label column to MAIN for the lowest rule value associated with each Rule ID that is applied to a Person ID and Name. Therefore, the results need to look like this:
```
In [3]: df
Out[3]:
PersonID Name Label RuleID RuleNumber
0 1 Jan MAIN 55 3
1 1 Jan REL 55 4
2 1 Jan REL 55 5
3 2 Don MAIN 3 1
4 2 Don REL 3 2
5 2 Don REL 3 3
6 3 Joe MAIN 10 234
7 3 Joe REL 10 567
8 3 Joe REL 10 999
```
This is the code that I wrote to accomplish this:
```
In [4]:
df['Label'] = np.where(
df['RuleNumber'] ==
df.groupby(['PersonID', 'Name', 'RuleID'])['RuleNumber'].transform('min'),
"MAIN", df.Label)
```
Is there a better way to update the values under the Label column? I feel like I'm brute forcing my way through and this may not be the most efficient way to do this.
I used the following SO threads to arrive at my result:
[Replace column values within a groupby and condition](https://stackoverflow.com/questions/48142757/replace-column-values-within-a-groupby-and-condition)
[Replace values within a groupby based on multiple conditions](https://stackoverflow.com/questions/50418372/replace-values-within-a-groupby-based-on-multiple-conditions?noredirect=1&lq=1)
<https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmin.html>
<https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.transform.html>
[Using Pandas to Find Minimum Values of Grouped Rows](https://stackoverflow.com/questions/41450963/using-pandas-to-find-minimum-values-of-grouped-rows)
Any advice would be appreciated.
Thank you. | 2020/12/17 | [
"https://Stackoverflow.com/questions/65347497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14557333/"
] | ```
import pandas as pd
df = pd.DataFrame({'PersonID': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'Name': ["Jan", "Jan", "Jan", "Don", "Don", "Don", "Joe", "Joe", "Joe"],
'Label': ["REL", "REL", "REL", "REL", "REL", "REL", "REL", "REL", "REL"],
'RuleID': [55, 55, 55, 3, 3, 3, 10, 10, 10],
'RuleNumber': [3, 4, 5, 1, 2, 3, 234, 567, 999]})
df.loc[df.groupby('Name')['RuleNumber'].idxmin()[:], 'Label'] = 'MAIN'
``` | Use `duplicated` on PersonID:
```
df.loc[~df['PersonID'].duplicated(),'Label'] = 'MAIN'
print(df)
```
Output:
```
PersonID Name Label RuleID RuleNumber
0 1 Jan MAIN 55 3
1 1 Jan REL 55 4
2 1 Jan REL 55 5
3 2 Don MAIN 3 1
4 2 Don REL 3 2
5 2 Don REL 3 3
6 3 Joe MAIN 10 234
7 3 Joe REL 10 567
8 3 Joe REL 10 999
``` |
73,504,727 | hi i want to make a class in python then import the class in another python file in python
we have a file called `squaretypes` that has a class called `Square` then its imported in `class2` but when i want to import the python file and then use `Square` but it gives an error
note: i am using jupyter notebook
error:
>
>
> ```
> ImportError Traceback (most recent call last)
> Input In [19], in <cell line: 1>()
> ----> 1 from squaretypes import Square
> 3 newClass = Square(5)
> 4 val = newClass.getVal()
>
> ImportError: cannot import name 'Square' from 'squaretypes' (C:\Users\DAVID\anaconda3\lib\types.py)
>
> ```
>
>
squaretypes:
```
class Square:
def __init__(self,val):
self.val=val
def getVal(self):
return self.val * self.val
```
class2:
```
from squaretypes import Square
newClass = Square(5)
val = newClass.getVal()
print(val)
```
note: `class2` is giving a error and i am using jupyter notebook | 2022/08/26 | [
"https://Stackoverflow.com/questions/73504727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19542186/"
] | "types" is the name of a standard library in python: <https://docs.python.org/3/library/types.html>
Rename your file to something different, e.g. "squaretype.py". | you should try to do following things
**- You can rename the name of classes**
* **if the above technic doesn't work just create an object without main in global and import it in the second python file . it will be imported with the values and functions, but you have to do some change in functions as well** |
38,736,721 | We have a scenario where we have to authenticate the user with LDAP server
Flow 1:
```
client --> application server --> LDAP server
```
In above flow the client enters LDAP credentials which comes to application server and then using python-ldap we can authenticate the user, straight forward. Since the user LDAP credentials comes to application server an organisation may not be willing for such flow for obvious reasons.
Flow 2:
```
client --> oauth2 --> LDAP server
```
Oauth scenario suites best here, since authentication of the user is responsibility of the oauth and application server do not need to know the user credentials.
Have anyone encountered such case, if yes, how you tackled it?
Is there are any Oauth client for LDAP free and paid ? | 2016/08/03 | [
"https://Stackoverflow.com/questions/38736721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1207003/"
] | If you don't want user credentials to reach the Application server then what you need is a perimeter authentication. You need to have an external authentication provider , say Oracle Access Manager, that will perform the authentication and set a certain token in the request. The application server can assert this token and let user access resources. This model enables SSO as well.
1. The resources that require authorized access are configured as protected URLs in OAM.
2. When a user tries to access a protected resource he is challenged for credentials.
3. OAM authenticates the user against an LDAP directory(that is configured in OAM).
4. A token corresponding to the authenticated user is set in the request. Also an SSO cookie is set.
5. Application server (Weblogic) can assert (verify) this token and let the user access the resource.
Note: Oracle Access Manager supports oAuth as well. | Ory Hydra <https://ory.sh/hydra> might be what the original poster was asking for. This question is several years old now but in the interest of helping anyone else who sees this...check out Ory Hydra. It provides the OAuth2/OpenID parts and can be linked to an LDAP server behind the scenes. |
38,736,721 | We have a scenario where we have to authenticate the user with LDAP server
Flow 1:
```
client --> application server --> LDAP server
```
In above flow the client enters LDAP credentials which comes to application server and then using python-ldap we can authenticate the user, straight forward. Since the user LDAP credentials comes to application server an organisation may not be willing for such flow for obvious reasons.
Flow 2:
```
client --> oauth2 --> LDAP server
```
Oauth scenario suites best here, since authentication of the user is responsibility of the oauth and application server do not need to know the user credentials.
Have anyone encountered such case, if yes, how you tackled it?
Is there are any Oauth client for LDAP free and paid ? | 2016/08/03 | [
"https://Stackoverflow.com/questions/38736721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1207003/"
] | If you don't want user credentials to reach the Application server then what you need is a perimeter authentication. You need to have an external authentication provider , say Oracle Access Manager, that will perform the authentication and set a certain token in the request. The application server can assert this token and let user access resources. This model enables SSO as well.
1. The resources that require authorized access are configured as protected URLs in OAM.
2. When a user tries to access a protected resource he is challenged for credentials.
3. OAM authenticates the user against an LDAP directory(that is configured in OAM).
4. A token corresponding to the authenticated user is set in the request. Also an SSO cookie is set.
5. Application server (Weblogic) can assert (verify) this token and let the user access the resource.
Note: Oracle Access Manager supports oAuth as well. | canaille is a free and light OAuth2/OpenID service over a LDAP backend, written in python. *(canaille developper here)*
<https://gitlab.com/yaal/canaille> |
10,296,483 | ```
class Item(models.Model):
name = models.CharField(max_length = 200)
image = models.ImageField(upload_to = 'read', blank=True)
creative_url = models.CharField(max_length = 200)
description = RichTextField()
def save(self, *args, **kwargs):
content = urllib2.urlopen(self.creative_url).read()
self.image.save("test.jpg", File(content))
super(Item, self).save(*args, **kwargs)
```
Gives exception:
'str' object has no attribute 'name'
I was trying to follow this answer (http://stackoverflow.com/questions/1393202/django-add-image-in-an-imagefield-from-image-url) But it did not help to get rid of the exception.
---
```
AttributeError at /admin/collection/item/1/ 'str' object has no attribute 'name' Request Method: POST Request
URL: http://127.0.0.1:8000/admin/collection/item/1/ Django
Version: 1.2.5 Exception Type: AttributeError Exception Value: 'str'
object has no attribute 'name' Exception
Location: D:\FF\django\core\files\base.py in _get_size, line 39 Python
Executable: C:\Python27\python.exe Python Version: 2.7.2 Python
Path: ['D:\\FF',
'C:\\Python27\\lib\\site-packages\\django_social_auth-0.6.7-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\python_openid-2.2.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\oauth2-1.5.211-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\httplib2-0.7.4-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\selenium-2.20.0-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\ipython-0.12-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\django_localeurl-1.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pil-1.1.7-py2.7-win32.egg',
'C:\\Python27\\lib\\site-packages\\pip-1.1-py2.7.egg',
'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs',
'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk', 'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'c:\\python27\\lib\\site-packages'] Server time: Tue, 24 Apr 2012
14:19:00 +0300
``` | 2012/04/24 | [
"https://Stackoverflow.com/questions/10296483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126545/"
] | Instead of `File`, you need to use [`django.core.files.base.ContentFile`](https://docs.djangoproject.com/en/1.4/ref/files/file/#the-contentfile-class)
```
self.image.save("test.jpg", ContentFile(content), save=False)
```
`File` accepts file object or `StringIO` object having `size` property or you need to manually set `size` property of a `File` or `ImageFile` to make it working w/ `StringIO`:
```
s = StringIO()
s.write(urllib2.urlopen(self.creative_url).read())
s.size = s.tell()
self.image.save('test.jpg', File(s), save=False)
```
Also, please note the `save=False` inside `self.image.save`: by default, `save=True`, this will cause the instance, which contains the image field, to be saved. Thus the `save` logic in your code might encounter an infinite loop and reach maximum recursion depth. | Try something like:
-------------------
(As supposed at: [Programmatically saving image to Django ImageField](https://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield))
```
from django.db import models
from django.core.files.base import ContentFile
import urllib2
from PIL import Image
from StringIO import StringIO
class Item(models.Model):
name = models.CharField(max_length=200)
image = models.ImageField(upload_to='read', blank=True)
creative_url = models.URLField(max_length=200)
class Meta:
verbose_name = "Item"
verbose_name_plural = "Items"
def download_image(self, url):
input_file = StringIO(urllib2.urlopen(url).read())
output_file = StringIO()
img = Image.open(input_file)
if img.mode != "RGB":
img = img.convert("RGB")
img.save(output_file, "JPEG")
self.image.save(self.name+".jpg", ContentFile(output_file.getvalue()), save=False)
def save(self, *args, **kwargs):
self.download_image(self.creative_url)
super(Item, self).save(*args, **kwargs)
``` |
10,296,483 | ```
class Item(models.Model):
name = models.CharField(max_length = 200)
image = models.ImageField(upload_to = 'read', blank=True)
creative_url = models.CharField(max_length = 200)
description = RichTextField()
def save(self, *args, **kwargs):
content = urllib2.urlopen(self.creative_url).read()
self.image.save("test.jpg", File(content))
super(Item, self).save(*args, **kwargs)
```
Gives exception:
'str' object has no attribute 'name'
I was trying to follow this answer (http://stackoverflow.com/questions/1393202/django-add-image-in-an-imagefield-from-image-url) But it did not help to get rid of the exception.
---
```
AttributeError at /admin/collection/item/1/ 'str' object has no attribute 'name' Request Method: POST Request
URL: http://127.0.0.1:8000/admin/collection/item/1/ Django
Version: 1.2.5 Exception Type: AttributeError Exception Value: 'str'
object has no attribute 'name' Exception
Location: D:\FF\django\core\files\base.py in _get_size, line 39 Python
Executable: C:\Python27\python.exe Python Version: 2.7.2 Python
Path: ['D:\\FF',
'C:\\Python27\\lib\\site-packages\\django_social_auth-0.6.7-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\python_openid-2.2.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\oauth2-1.5.211-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\httplib2-0.7.4-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\selenium-2.20.0-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\ipython-0.12-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\django_localeurl-1.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pil-1.1.7-py2.7-win32.egg',
'C:\\Python27\\lib\\site-packages\\pip-1.1-py2.7.egg',
'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs',
'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk', 'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'c:\\python27\\lib\\site-packages'] Server time: Tue, 24 Apr 2012
14:19:00 +0300
``` | 2012/04/24 | [
"https://Stackoverflow.com/questions/10296483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126545/"
] | Try something like:
-------------------
(As supposed at: [Programmatically saving image to Django ImageField](https://stackoverflow.com/questions/1308386/programmatically-saving-image-to-django-imagefield))
```
from django.db import models
from django.core.files.base import ContentFile
import urllib2
from PIL import Image
from StringIO import StringIO
class Item(models.Model):
name = models.CharField(max_length=200)
image = models.ImageField(upload_to='read', blank=True)
creative_url = models.URLField(max_length=200)
class Meta:
verbose_name = "Item"
verbose_name_plural = "Items"
def download_image(self, url):
input_file = StringIO(urllib2.urlopen(url).read())
output_file = StringIO()
img = Image.open(input_file)
if img.mode != "RGB":
img = img.convert("RGB")
img.save(output_file, "JPEG")
self.image.save(self.name+".jpg", ContentFile(output_file.getvalue()), save=False)
def save(self, *args, **kwargs):
self.download_image(self.creative_url)
super(Item, self).save(*args, **kwargs)
``` | solution using **requests**
```
from django.core.files.base import ContentFile
from requests import request, HTTPError
def save(self, *args, **kwargs):
try:
data = request('GET', self.creative_url,)
data.raise_for_status()
self.image.save('fname.jpg', ContentFile(data.content),save=False)
except HTTPError:
pass
super(Item, self).save(*args, **kwargs)
``` |
10,296,483 | ```
class Item(models.Model):
name = models.CharField(max_length = 200)
image = models.ImageField(upload_to = 'read', blank=True)
creative_url = models.CharField(max_length = 200)
description = RichTextField()
def save(self, *args, **kwargs):
content = urllib2.urlopen(self.creative_url).read()
self.image.save("test.jpg", File(content))
super(Item, self).save(*args, **kwargs)
```
Gives exception:
'str' object has no attribute 'name'
I was trying to follow this answer (http://stackoverflow.com/questions/1393202/django-add-image-in-an-imagefield-from-image-url) But it did not help to get rid of the exception.
---
```
AttributeError at /admin/collection/item/1/ 'str' object has no attribute 'name' Request Method: POST Request
URL: http://127.0.0.1:8000/admin/collection/item/1/ Django
Version: 1.2.5 Exception Type: AttributeError Exception Value: 'str'
object has no attribute 'name' Exception
Location: D:\FF\django\core\files\base.py in _get_size, line 39 Python
Executable: C:\Python27\python.exe Python Version: 2.7.2 Python
Path: ['D:\\FF',
'C:\\Python27\\lib\\site-packages\\django_social_auth-0.6.7-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\python_openid-2.2.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\oauth2-1.5.211-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\httplib2-0.7.4-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\selenium-2.20.0-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\ipython-0.12-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\django_localeurl-1.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pil-1.1.7-py2.7-win32.egg',
'C:\\Python27\\lib\\site-packages\\pip-1.1-py2.7.egg',
'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs',
'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk', 'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'c:\\python27\\lib\\site-packages'] Server time: Tue, 24 Apr 2012
14:19:00 +0300
``` | 2012/04/24 | [
"https://Stackoverflow.com/questions/10296483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126545/"
] | Instead of `File`, you need to use [`django.core.files.base.ContentFile`](https://docs.djangoproject.com/en/1.4/ref/files/file/#the-contentfile-class)
```
self.image.save("test.jpg", ContentFile(content), save=False)
```
`File` accepts file object or `StringIO` object having `size` property or you need to manually set `size` property of a `File` or `ImageFile` to make it working w/ `StringIO`:
```
s = StringIO()
s.write(urllib2.urlopen(self.creative_url).read())
s.size = s.tell()
self.image.save('test.jpg', File(s), save=False)
```
Also, please note the `save=False` inside `self.image.save`: by default, `save=True`, this will cause the instance, which contains the image field, to be saved. Thus the `save` logic in your code might encounter an infinite loop and reach maximum recursion depth. | solution using **requests**
```
from django.core.files.base import ContentFile
from requests import request, HTTPError
def save(self, *args, **kwargs):
try:
data = request('GET', self.creative_url,)
data.raise_for_status()
self.image.save('fname.jpg', ContentFile(data.content),save=False)
except HTTPError:
pass
super(Item, self).save(*args, **kwargs)
``` |
65,009,888 | I wrote a python script (with pandas library) to create txt files. I also use a txt file as an input. It works well but I want to make it more automated.
My code starts like;
```
girdi = input("Lütfen gir: ")
input2 = girdi+".txt"
veriCNR = pd.read_table(
input2, decimal=",",
usecols=[
"Chromosome",
"Name",
.
.
.
```
I am entering the name of the files one by one and getting outputs like this:
```
.
.
.
outputCNR = girdi+".cnr"
sonTabloCNR.to_csv(outputCNR, sep="\t", index=False)
outputCNS = girdi+".cns"
sonTabloCNS.to_csv(outputCNS, sep="\t", index=False)
outputCNG = girdi+".genemetrics.cns"
sonTabloCNG.to_csv(outputCNG, sep="\t", index=False)
```
As you see I am using input name also for outputs. They are tab seperated txt files with different file extensions.
I want to use all txt files in a folder as an input and run this script for every one of them.
I hope I explained it clearly.
ps. I am not a programmer. Please be explanatory with codes :) | 2020/11/25 | [
"https://Stackoverflow.com/questions/65009888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570497/"
] | Your question was not clear, I assume that you will have multiple rows and multiple elements. There is my solution according to what I understand.
```
payload.rows.forEach(x=> x.elements.forEach(y => console.log(y.distance.value)))
``` | ```
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);
``` |
65,009,888 | I wrote a python script (with pandas library) to create txt files. I also use a txt file as an input. It works well but I want to make it more automated.
My code starts like;
```
girdi = input("Lütfen gir: ")
input2 = girdi+".txt"
veriCNR = pd.read_table(
input2, decimal=",",
usecols=[
"Chromosome",
"Name",
.
.
.
```
I am entering the name of the files one by one and getting outputs like this:
```
.
.
.
outputCNR = girdi+".cnr"
sonTabloCNR.to_csv(outputCNR, sep="\t", index=False)
outputCNS = girdi+".cns"
sonTabloCNS.to_csv(outputCNS, sep="\t", index=False)
outputCNG = girdi+".genemetrics.cns"
sonTabloCNG.to_csv(outputCNG, sep="\t", index=False)
```
As you see I am using input name also for outputs. They are tab seperated txt files with different file extensions.
I want to use all txt files in a folder as an input and run this script for every one of them.
I hope I explained it clearly.
ps. I am not a programmer. Please be explanatory with codes :) | 2020/11/25 | [
"https://Stackoverflow.com/questions/65009888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570497/"
] | Try like below
```js
var body = {
"destination_addresses": ["XXXXXXXX 60, 13XXX Berlin, Germany"],
"origin_addresses": ["XXXXXXX Str. 67, 10XXX Berlin, Germany"],
"rows": [{
"elements": [{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}]
}],
"status": "OK"
};
var payload = JSON.parse(JSON.stringify(body));
payload.rows.forEach(row => row.elements.forEach(elem => console.log("Distance : ", elem.distance.value)))
``` | ```
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);
``` |
65,009,888 | I wrote a python script (with pandas library) to create txt files. I also use a txt file as an input. It works well but I want to make it more automated.
My code starts like;
```
girdi = input("Lütfen gir: ")
input2 = girdi+".txt"
veriCNR = pd.read_table(
input2, decimal=",",
usecols=[
"Chromosome",
"Name",
.
.
.
```
I am entering the name of the files one by one and getting outputs like this:
```
.
.
.
outputCNR = girdi+".cnr"
sonTabloCNR.to_csv(outputCNR, sep="\t", index=False)
outputCNS = girdi+".cns"
sonTabloCNS.to_csv(outputCNS, sep="\t", index=False)
outputCNG = girdi+".genemetrics.cns"
sonTabloCNG.to_csv(outputCNG, sep="\t", index=False)
```
As you see I am using input name also for outputs. They are tab seperated txt files with different file extensions.
I want to use all txt files in a folder as an input and run this script for every one of them.
I hope I explained it clearly.
ps. I am not a programmer. Please be explanatory with codes :) | 2020/11/25 | [
"https://Stackoverflow.com/questions/65009888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570497/"
] | I don't know exactly what you want, but you can get the distance object with something like that:
```js
const payload = {
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
let distance = payload.rows[0].elements.map(element => {
return {
distance: element.distance
}
});
// Map returns an array, so you can get the object using the index:
console.log(distance[0]);
// If you want only the value:
console.log(distance[0].distance.value);
```
If you want, you can also use Object.assign or something like that to avoid getting the value by the index.
Hope it helped! | ```
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);
``` |
65,009,888 | I wrote a python script (with pandas library) to create txt files. I also use a txt file as an input. It works well but I want to make it more automated.
My code starts like;
```
girdi = input("Lütfen gir: ")
input2 = girdi+".txt"
veriCNR = pd.read_table(
input2, decimal=",",
usecols=[
"Chromosome",
"Name",
.
.
.
```
I am entering the name of the files one by one and getting outputs like this:
```
.
.
.
outputCNR = girdi+".cnr"
sonTabloCNR.to_csv(outputCNR, sep="\t", index=False)
outputCNS = girdi+".cns"
sonTabloCNS.to_csv(outputCNS, sep="\t", index=False)
outputCNG = girdi+".genemetrics.cns"
sonTabloCNG.to_csv(outputCNG, sep="\t", index=False)
```
As you see I am using input name also for outputs. They are tab seperated txt files with different file extensions.
I want to use all txt files in a folder as an input and run this script for every one of them.
I hope I explained it clearly.
ps. I am not a programmer. Please be explanatory with codes :) | 2020/11/25 | [
"https://Stackoverflow.com/questions/65009888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570497/"
] | ```
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
```
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (*object\_name.property\_name*). You can access an array's element by typing the element index in square brackets next to the array's name *(array\_name[element\_number])*.
In our case we access the property "rows" which is an array of the object "payload" - *payload.rows*. Then we access the element number [0] of this array by typing [0] next to the property's name - *payload.rows[0]*. We get another object which has the property "elements" in it - *payload.rows[0].elements* . This property stores another array and we access its first element again -
*payload.rows[0].elements[0]*. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - *payload.rows[0].elements[0].distance.value*
Source <https://eloquentjavascript.net/04_data.html> | ```
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);
``` |
65,009,888 | I wrote a python script (with pandas library) to create txt files. I also use a txt file as an input. It works well but I want to make it more automated.
My code starts like;
```
girdi = input("Lütfen gir: ")
input2 = girdi+".txt"
veriCNR = pd.read_table(
input2, decimal=",",
usecols=[
"Chromosome",
"Name",
.
.
.
```
I am entering the name of the files one by one and getting outputs like this:
```
.
.
.
outputCNR = girdi+".cnr"
sonTabloCNR.to_csv(outputCNR, sep="\t", index=False)
outputCNS = girdi+".cns"
sonTabloCNS.to_csv(outputCNS, sep="\t", index=False)
outputCNG = girdi+".genemetrics.cns"
sonTabloCNG.to_csv(outputCNG, sep="\t", index=False)
```
As you see I am using input name also for outputs. They are tab seperated txt files with different file extensions.
I want to use all txt files in a folder as an input and run this script for every one of them.
I hope I explained it clearly.
ps. I am not a programmer. Please be explanatory with codes :) | 2020/11/25 | [
"https://Stackoverflow.com/questions/65009888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570497/"
] | ```
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
```
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (*object\_name.property\_name*). You can access an array's element by typing the element index in square brackets next to the array's name *(array\_name[element\_number])*.
In our case we access the property "rows" which is an array of the object "payload" - *payload.rows*. Then we access the element number [0] of this array by typing [0] next to the property's name - *payload.rows[0]*. We get another object which has the property "elements" in it - *payload.rows[0].elements* . This property stores another array and we access its first element again -
*payload.rows[0].elements[0]*. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - *payload.rows[0].elements[0].distance.value*
Source <https://eloquentjavascript.net/04_data.html> | Your question was not clear, I assume that you will have multiple rows and multiple elements. There is my solution according to what I understand.
```
payload.rows.forEach(x=> x.elements.forEach(y => console.log(y.distance.value)))
``` |
65,009,888 | I wrote a python script (with pandas library) to create txt files. I also use a txt file as an input. It works well but I want to make it more automated.
My code starts like;
```
girdi = input("Lütfen gir: ")
input2 = girdi+".txt"
veriCNR = pd.read_table(
input2, decimal=",",
usecols=[
"Chromosome",
"Name",
.
.
.
```
I am entering the name of the files one by one and getting outputs like this:
```
.
.
.
outputCNR = girdi+".cnr"
sonTabloCNR.to_csv(outputCNR, sep="\t", index=False)
outputCNS = girdi+".cns"
sonTabloCNS.to_csv(outputCNS, sep="\t", index=False)
outputCNG = girdi+".genemetrics.cns"
sonTabloCNG.to_csv(outputCNG, sep="\t", index=False)
```
As you see I am using input name also for outputs. They are tab seperated txt files with different file extensions.
I want to use all txt files in a folder as an input and run this script for every one of them.
I hope I explained it clearly.
ps. I am not a programmer. Please be explanatory with codes :) | 2020/11/25 | [
"https://Stackoverflow.com/questions/65009888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570497/"
] | ```
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
```
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (*object\_name.property\_name*). You can access an array's element by typing the element index in square brackets next to the array's name *(array\_name[element\_number])*.
In our case we access the property "rows" which is an array of the object "payload" - *payload.rows*. Then we access the element number [0] of this array by typing [0] next to the property's name - *payload.rows[0]*. We get another object which has the property "elements" in it - *payload.rows[0].elements* . This property stores another array and we access its first element again -
*payload.rows[0].elements[0]*. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - *payload.rows[0].elements[0].distance.value*
Source <https://eloquentjavascript.net/04_data.html> | Try like below
```js
var body = {
"destination_addresses": ["XXXXXXXX 60, 13XXX Berlin, Germany"],
"origin_addresses": ["XXXXXXX Str. 67, 10XXX Berlin, Germany"],
"rows": [{
"elements": [{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}]
}],
"status": "OK"
};
var payload = JSON.parse(JSON.stringify(body));
payload.rows.forEach(row => row.elements.forEach(elem => console.log("Distance : ", elem.distance.value)))
``` |
65,009,888 | I wrote a python script (with pandas library) to create txt files. I also use a txt file as an input. It works well but I want to make it more automated.
My code starts like;
```
girdi = input("Lütfen gir: ")
input2 = girdi+".txt"
veriCNR = pd.read_table(
input2, decimal=",",
usecols=[
"Chromosome",
"Name",
.
.
.
```
I am entering the name of the files one by one and getting outputs like this:
```
.
.
.
outputCNR = girdi+".cnr"
sonTabloCNR.to_csv(outputCNR, sep="\t", index=False)
outputCNS = girdi+".cns"
sonTabloCNS.to_csv(outputCNS, sep="\t", index=False)
outputCNG = girdi+".genemetrics.cns"
sonTabloCNG.to_csv(outputCNG, sep="\t", index=False)
```
As you see I am using input name also for outputs. They are tab seperated txt files with different file extensions.
I want to use all txt files in a folder as an input and run this script for every one of them.
I hope I explained it clearly.
ps. I am not a programmer. Please be explanatory with codes :) | 2020/11/25 | [
"https://Stackoverflow.com/questions/65009888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14570497/"
] | ```
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
```
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (*object\_name.property\_name*). You can access an array's element by typing the element index in square brackets next to the array's name *(array\_name[element\_number])*.
In our case we access the property "rows" which is an array of the object "payload" - *payload.rows*. Then we access the element number [0] of this array by typing [0] next to the property's name - *payload.rows[0]*. We get another object which has the property "elements" in it - *payload.rows[0].elements* . This property stores another array and we access its first element again -
*payload.rows[0].elements[0]*. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - *payload.rows[0].elements[0].distance.value*
Source <https://eloquentjavascript.net/04_data.html> | I don't know exactly what you want, but you can get the distance object with something like that:
```js
const payload = {
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
let distance = payload.rows[0].elements.map(element => {
return {
distance: element.distance
}
});
// Map returns an array, so you can get the object using the index:
console.log(distance[0]);
// If you want only the value:
console.log(distance[0].distance.value);
```
If you want, you can also use Object.assign or something like that to avoid getting the value by the index.
Hope it helped! |
14,659,118 | <http://pypi.python.org/pypi/pylinkgrammar>
I am encountering an error when attempting to install pylinkgrammar:
```
Running setup.py egg_info for package pylinkgrammar
Installing collected packages: pylinkgrammar
Running setup.py install for pylinkgrammar
...
running build_ext
building 'pylinkgrammar/_clinkgrammar' extension
swigging pylinkgrammar/link_grammar.i to pylinkgrammar/link_grammar_wrap.c
swig -python -o pylinkgrammar/link_grammar_wrap.c pylinkgrammar/link_grammar.i
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c pylinkgrammar/link_grammar_wrap.c -o build/temp.linux-x86_64-2.7/pylinkgrammar/link_grammar_wrap.o
pylinkgrammar/link_grammar_wrap.c:2973:40: fatal error: link-grammar/link-includes.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1
``` | 2013/02/02 | [
"https://Stackoverflow.com/questions/14659118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011567/"
] | Besides installing the liblink-grammar4 package also install liblink-grammar4-dev package which is available in synaptic.
I had been grappling with the same for over an hour and it worked for me | You first need to install the liblink-grammar4 library:
If you're on ubuntu system, you can run:
```
sudo apt-add-repository ppa:python-pylinkgrammar/getsome
sudo apt-get install liblink-grammar4
```
If you're on a different flavor of linux, just make sure `liblink-grammar4` is installed. |
14,659,118 | <http://pypi.python.org/pypi/pylinkgrammar>
I am encountering an error when attempting to install pylinkgrammar:
```
Running setup.py egg_info for package pylinkgrammar
Installing collected packages: pylinkgrammar
Running setup.py install for pylinkgrammar
...
running build_ext
building 'pylinkgrammar/_clinkgrammar' extension
swigging pylinkgrammar/link_grammar.i to pylinkgrammar/link_grammar_wrap.c
swig -python -o pylinkgrammar/link_grammar_wrap.c pylinkgrammar/link_grammar.i
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c pylinkgrammar/link_grammar_wrap.c -o build/temp.linux-x86_64-2.7/pylinkgrammar/link_grammar_wrap.o
pylinkgrammar/link_grammar_wrap.c:2973:40: fatal error: link-grammar/link-includes.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1
``` | 2013/02/02 | [
"https://Stackoverflow.com/questions/14659118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011567/"
] | This worked for me:
```
sudo apt-get install liblink-grammar4-dev
``` | You first need to install the liblink-grammar4 library:
If you're on ubuntu system, you can run:
```
sudo apt-add-repository ppa:python-pylinkgrammar/getsome
sudo apt-get install liblink-grammar4
```
If you're on a different flavor of linux, just make sure `liblink-grammar4` is installed. |
14,659,118 | <http://pypi.python.org/pypi/pylinkgrammar>
I am encountering an error when attempting to install pylinkgrammar:
```
Running setup.py egg_info for package pylinkgrammar
Installing collected packages: pylinkgrammar
Running setup.py install for pylinkgrammar
...
running build_ext
building 'pylinkgrammar/_clinkgrammar' extension
swigging pylinkgrammar/link_grammar.i to pylinkgrammar/link_grammar_wrap.c
swig -python -o pylinkgrammar/link_grammar_wrap.c pylinkgrammar/link_grammar.i
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c pylinkgrammar/link_grammar_wrap.c -o build/temp.linux-x86_64-2.7/pylinkgrammar/link_grammar_wrap.o
pylinkgrammar/link_grammar_wrap.c:2973:40: fatal error: link-grammar/link-includes.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1
``` | 2013/02/02 | [
"https://Stackoverflow.com/questions/14659118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011567/"
] | You first need to install the liblink-grammar4 library:
If you're on ubuntu system, you can run:
```
sudo apt-add-repository ppa:python-pylinkgrammar/getsome
sudo apt-get install liblink-grammar4
```
If you're on a different flavor of linux, just make sure `liblink-grammar4` is installed. | This might be helpful
```
sudo apt-get install liblink-grammar4-dev cmake swig
sudo pip install pylinkgrammar
``` |
14,659,118 | <http://pypi.python.org/pypi/pylinkgrammar>
I am encountering an error when attempting to install pylinkgrammar:
```
Running setup.py egg_info for package pylinkgrammar
Installing collected packages: pylinkgrammar
Running setup.py install for pylinkgrammar
...
running build_ext
building 'pylinkgrammar/_clinkgrammar' extension
swigging pylinkgrammar/link_grammar.i to pylinkgrammar/link_grammar_wrap.c
swig -python -o pylinkgrammar/link_grammar_wrap.c pylinkgrammar/link_grammar.i
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c pylinkgrammar/link_grammar_wrap.c -o build/temp.linux-x86_64-2.7/pylinkgrammar/link_grammar_wrap.o
pylinkgrammar/link_grammar_wrap.c:2973:40: fatal error: link-grammar/link-includes.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1
``` | 2013/02/02 | [
"https://Stackoverflow.com/questions/14659118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011567/"
] | Besides installing the liblink-grammar4 package also install liblink-grammar4-dev package which is available in synaptic.
I had been grappling with the same for over an hour and it worked for me | This might be helpful
```
sudo apt-get install liblink-grammar4-dev cmake swig
sudo pip install pylinkgrammar
``` |
14,659,118 | <http://pypi.python.org/pypi/pylinkgrammar>
I am encountering an error when attempting to install pylinkgrammar:
```
Running setup.py egg_info for package pylinkgrammar
Installing collected packages: pylinkgrammar
Running setup.py install for pylinkgrammar
...
running build_ext
building 'pylinkgrammar/_clinkgrammar' extension
swigging pylinkgrammar/link_grammar.i to pylinkgrammar/link_grammar_wrap.c
swig -python -o pylinkgrammar/link_grammar_wrap.c pylinkgrammar/link_grammar.i
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c pylinkgrammar/link_grammar_wrap.c -o build/temp.linux-x86_64-2.7/pylinkgrammar/link_grammar_wrap.o
pylinkgrammar/link_grammar_wrap.c:2973:40: fatal error: link-grammar/link-includes.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1
``` | 2013/02/02 | [
"https://Stackoverflow.com/questions/14659118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011567/"
] | This worked for me:
```
sudo apt-get install liblink-grammar4-dev
``` | This might be helpful
```
sudo apt-get install liblink-grammar4-dev cmake swig
sudo pip install pylinkgrammar
``` |
58,614,691 | im trying to login into my google account using python selenium with chromedriver,
the code works but not in headless mode. in hm i get the the identifierId never appears :(
EDIT: added missing --disable-gpu
```py
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920,1080')
def do_login(email, password):
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://accounts.google.com/signin/v2/identifier?flowName=GlifWebSignIn&flowEntry=ServiceLogin')
email_phone = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='identifierId']")))
email_phone.send_keys(email)
driver.find_element_by_id("identifierNext").click()
pw = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//input[@name='password']"))
)
pw.send_keys(password)
driver.find_element_by_id("passwordNext").click()
time.sleep(2)
print(driver.title)
driver.close()
```
should login like in non headless mode | 2019/10/29 | [
"https://Stackoverflow.com/questions/58614691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419986/"
] | You also have to add `--disable-gpu` to your chrome options.
```
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument('--disable-gpu')
```
That's what I had to add to get my headless code fully working. | This code works in headless mode but not with gui enabled
```py
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920,1080')
def do_login(email, password):
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://accounts.google.com/signin/v2/identifier?flowName=GlifWebSignIn&flowEntry=ServiceLogin')
email_phone = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "Email")))
email_phone.send_keys(email)
driver.find_element_by_id("next").click()
pw = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.ID, "Passwd"))
)
pw.send_keys(password)
driver.find_element_by_id("signIn").click()
driver.close()
``` |
58,614,691 | im trying to login into my google account using python selenium with chromedriver,
the code works but not in headless mode. in hm i get the the identifierId never appears :(
EDIT: added missing --disable-gpu
```py
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920,1080')
def do_login(email, password):
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://accounts.google.com/signin/v2/identifier?flowName=GlifWebSignIn&flowEntry=ServiceLogin')
email_phone = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='identifierId']")))
email_phone.send_keys(email)
driver.find_element_by_id("identifierNext").click()
pw = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//input[@name='password']"))
)
pw.send_keys(password)
driver.find_element_by_id("passwordNext").click()
time.sleep(2)
print(driver.title)
driver.close()
```
should login like in non headless mode | 2019/10/29 | [
"https://Stackoverflow.com/questions/58614691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419986/"
] | I always pass below arguments, Tested and works:
```
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--start-maximized')
chrome_options.add_argument('--disable-setuid-sandbox')
``` | This code works in headless mode but not with gui enabled
```py
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920,1080')
def do_login(email, password):
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://accounts.google.com/signin/v2/identifier?flowName=GlifWebSignIn&flowEntry=ServiceLogin')
email_phone = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "Email")))
email_phone.send_keys(email)
driver.find_element_by_id("next").click()
pw = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.ID, "Passwd"))
)
pw.send_keys(password)
driver.find_element_by_id("signIn").click()
driver.close()
``` |
21,513,899 | I am trying to store the following info in a python list but the strip function isnt working
```
u'Studio', u'5', u'550.00 SqFt', u'No', u'Agent', u'Quarterly', u'Mediterranean Buildings (38-107)', u'Central A/C & Heating\n , \n \n Balcony\n , \n \n Shared Pool\n , \n \n Built in Wardrobes\n , \n \n Security\n , \n \n View of Landmark', u'']
``` | 2014/02/02 | [
"https://Stackoverflow.com/questions/21513899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1928163/"
] | You can remove internal spaces from string by regular expression:
```
import re
text_result = re.sub('\s+',' ', text_input)
```
*EDIT:*
You can even apply this function to every item in your list:
```
list_result = [re.sub("\s+", " ",x) for x in list_input]
``` | You have a list of strings (which you have left the opening brace off of).
You have one *really* ungainly string in index 7 of that list.
You just need to clean that one up. So:
```
li = [u'Studio', u'5', u'550.00 SqFt', u'No', u'Agent', u'Quarterly', u'Mediterranean Buildings (38-107)', u'Central A/C & Heating\n , \n \n Balcony\n , \n \n Shared Pool\n , \n \n Built in Wardrobes\n , \n \n Security\n , \n \n View of Landmark', u'']
', '.join([line.strip(', ') for line in li[7].splitlines() if line.strip(' ,')])
Out[35]: 'Central A/C & Heating, Balcony, Shared Pool, Built in Wardrobes, Security, View of Landmark'
```
`strip` accepts an iterable of characters to strip off both ends of a given string; I've told it to remove spaces and commas. Then we rejoin that into a string.
If you need to do this for *every* line in `li`, just do the above in a list comp:
```
[', '.join([line.strip(', ') for line in x.splitlines() if line.strip(' ,')]) for x in li]
```
At this point I would generally go back and re-write whatever code generated this list of clunky strings, since it's cleaner to simply fix the problem before it gets this far. |
21,513,899 | I am trying to store the following info in a python list but the strip function isnt working
```
u'Studio', u'5', u'550.00 SqFt', u'No', u'Agent', u'Quarterly', u'Mediterranean Buildings (38-107)', u'Central A/C & Heating\n , \n \n Balcony\n , \n \n Shared Pool\n , \n \n Built in Wardrobes\n , \n \n Security\n , \n \n View of Landmark', u'']
``` | 2014/02/02 | [
"https://Stackoverflow.com/questions/21513899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1928163/"
] | You can remove internal spaces from string by regular expression:
```
import re
text_result = re.sub('\s+',' ', text_input)
```
*EDIT:*
You can even apply this function to every item in your list:
```
list_result = [re.sub("\s+", " ",x) for x in list_input]
``` | the strip functions helps you to do something like
```
uns=' this line has extra white spaces '
strv=uns.strip()
#str now has 'this line has extra white spaces'
```
if you want to store striped string to a list you can iterate the list like this
```
pos=0
while pos < len(thelist):
thevalue=thelist[pos]
cleanvalue=thevalue.strip()
thelist[pos]=cleanvalue
pos+=1
print thelist
```
whit this every element in the list is striped from extra spaces at the beginning and at the end.
Regards |
62,228,457 | I'm trying to increase the efficiency of a non-conformity management program. Basically, I have a database containing about a few hundred rows, each row describes a non-conformity using a text field.
Text is provided in Italian and I have no control over what the user writes.
I'm trying to write a python program using NTLK to detect how many of these rows report the same problem, written differently but with similar content.
For example, the following sentences need to be related, with a high rate of confidence
* I received 10 pieces less than what was ordered
* 10 pieces have not been shipped
I already found the following article describing how to preprocess text for analysis:
[How to Develop a Paraphrasing Tool Using NLP (Natural Language Processing) Model in Python](https://paraphrase.projecttopics.org/how-to-develop-a-paraphrasing-tool-using-nlp-natural-language-processing-model-in-python.html)
I also found other questions on SO but they all refer to word similarity, two sentences comparison, or comparison using a reference meaning.
* [This one uses a reference meaning](https://stackoverflow.com/questions/24407333/how-to-perform-semantic-similarity-in-document)
* [This one refers to two sentences comparison](https://stackoverflow.com/questions/44234909/wordnet-based-semantic-similarity-measurements)
In my case, I have no reference and I have multiple sentences that needs to be grouped if they refer to similar problems, so I wonder if this job it's even possible to do with a script.
[This answer](https://stackoverflow.com/a/2057825/10511191) says that it cannot be done but it's quite old and maybe someone knows something new.
Thanks to everyone who can help me. | 2020/06/06 | [
"https://Stackoverflow.com/questions/62228457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10511191/"
] | Thank's to Anurag Wagh advice I figured it out.
I used [this tutorial](https://www.machinelearningplus.com/nlp/gensim-tutorial/) about gensim and how to use it in many ways.
[Chapter 18](https://www.machinelearningplus.com/nlp/gensim-tutorial/#18howtocomputesimilaritymetricslikecosinesimilarityandsoftcosinesimilarity) does what I was asking for, but during my test, I found out a better way to achieve my goal.
[Chatper 11](http://%5B1%5D:%20https://www.machinelearningplus.com/nlp/gensim-tutorial/#11howtocreatetopicmodelswithlda) shows how to build an LDA model and how to extract a list of main topics among a set of documents.
Here is my code used to build the LDA model
```
# Step 0: Import packages and stopwords
from gensim.models import LdaModel, LdaMulticore
import gensim.downloader as api
from gensim.utils import simple_preprocess, lemmatize
from nltk.corpus import stopwords
from gensim import corpora
import re
import nltk
import string
import pattern
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s')
logging.root.setLevel(level=logging.INFO)
docs = [doc for doc in open('file.txt', encoding='utf-8')]
import nltk
import string
import pattern
# dictionary of Italian stop-words
it_stop_words = nltk.corpus.stopwords.words('italian')
it_stop_words = it_stop_words + [<custom stop words>]
# Snowball stemmer with rules for the Italian language
ita_stemmer = nltk.stem.snowball.ItalianStemmer()
# the following function is just to get the lemma
# out of the original input word
def lemmatize_word(input_word):
in_word = input_word
word_it = pattern.it.parse(
in_word,
tokenize=False,
tag=False,
chunk=False,
lemmata=True
)
the_lemmatized_word = word_it.split()[0][0][4]
return the_lemmatized_word
# Step 2: Prepare Data (Remove stopwords and lemmatize)
data_processed = []
for doc in docs:
word_tokenized_list = nltk.tokenize.word_tokenize(doc)
word_tokenized_no_punct = [x.lower() for x in word_tokenized_list if x not in string.punctuation]
word_tokenized_no_punct_no_sw = [x for x in word_tokenized_no_punct if x not in it_stop_words]
word_tokenized_no_punct_no_sw_no_apostrophe = [x.split("'") for x in word_tokenized_no_punct_no_sw]
word_tokenized_no_punct_no_sw_no_apostrophe = [y for x in word_tokenized_no_punct_no_sw_no_apostrophe for y in x]
data_processed.append(word_tokenized_no_punct_no_sw_no_apostrophe)
dct = corpora.Dictionary(data_processed)
corpus = [dct.doc2bow(line) for line in data_processed]
lda_model = LdaMulticore(corpus=corpus,
id2word=dct,
random_state=100,
num_topics=7,
passes=10,
chunksize=1000,
batch=False,
alpha='asymmetric',
decay=0.5,
offset=64,
eta=None,
eval_every=0,
iterations=100,
gamma_threshold=0.001,
per_word_topics=True)
# save the model
lda_model.save('lda_model.model')
# See the topics
lda_model.print_topics(-1)
```
With the model trained i can get a list of topic for each new non-conformity and detect if it's related to something already reported by others non-conformities | Perhaps converting document to vectors and the computing distance between two vectors would be helpful
[doc2vec](https://radimrehurek.com/gensim/auto_examples/tutorials/run_doc2vec_lee.html#sphx-glr-auto-examples-tutorials-run-doc2vec-lee-py) can be helpful over here |
60,621,433 | pip install has suddenly stopped working - unsure if related to recent update. I've tried it both on pip 19.0.3 and pip.20.0.2
When using:
```
python -m pip install matplotlib --user
```
I get an error like this
```
PermissionError: [Errno 13] Permission denied: 'C:\\Program Files\\Python37\\Lib\\site-packages\\accesstest_deleteme_fishfingers_custard_d1677h'
```
Any help appreciated | 2020/03/10 | [
"https://Stackoverflow.com/questions/60621433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9988108/"
] | Using:
```
python -m pip install matplotlib
```
worked | I suspect you need to run your terminal as an administrator-elevated account to access the restricted resource. |
31,714,060 | For one of my assignments, rather than reading directly from a text file, we are directly taking the input from `sys.in`. I was wondering what the best way of obtaining this input and storing it would be?
So far, I've tried using:
`sys.stdin.readlines()` -- But this will not terminate unless it recieves an EOF statement, while a zero in my input signals the end of the file.
`sys.stdin.readline()` -- It will only read the final line of the input code.
`input()` -- I can only read in the first line of the input and when I try to loop it, I end up with a syntax error.
An example of the input is below:
```
3
2 1 3
3 2 1
1 3 2
2 1 3
3 2 1
1 3 2
2
1 2
1 2
2 1
2 1
0
```
My attempt at obtaining the input:
```
input_list = []
while True:
input_str = input("")
if input_str == '0':
break
else:
input_list.append(input_str)
print(input_list)
```
Returns this error while parsing the second line through:
[](https://i.stack.imgur.com/tsuNd.png)
Any help with this would be greatly appreciated. I've probably spent longer trying to get the input to work now than the actual assignment now.
EDIT: The version of Python we are using is 3.4
FINAL EDIT: Like both the answers said, it turns out that the university labs have a older version of python running when run in cmd prompt in the labs, where the input() method started behaving differently. Once I tried the code at home, it worked as intended. | 2015/07/30 | [
"https://Stackoverflow.com/questions/31714060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5171552/"
] | Looks like a typo. You use thread1 in both calls to pthread\_create.
```
iret1 = pthread_create( &thread1, 0, print_message_function1, (void*) message1);
iret2 = pthread_create( &thread1, 0, print_message_function2, (void*) message2);
```
So `pthread_join(thread2, 0);` is pretty much doomed. | This is really just **relevant information**, not an answer as such, but unfortunately SO does not support code in comments.
The problem that you *noticed* with your code was a simple typo, but I didn't see that until I read the now [accepted answer](https://stackoverflow.com/a/31714197/464581). For, I sat down and rewrote the code to standard C++, and in that process the typo disappeared, completely unnoticed! :) The problem that I did note was that you're using output statements without synchronization in your code, and that might cause output lines to be mixed, and is, I think, formally Undefined Behavior.
To fix that you can use a **mutex**. In this rewrite of your code I do not abstract up anything. But I think you can readily see the natural abstractions that hide between the code lines here:
```
#include <chrono> // operator""ms
#include <iostream>
#include <mutex>
#include <stdlib.h>
#include <thread>
using namespace std;
mutex output_ownership;
void print_message_function1( char const* const message )
{
for( int i = 0; i < 10; ++i )
{
{
lock_guard<mutex> mux( output_ownership );
cout << "Hello #" << i << message << endl;
}
this_thread::sleep_for( 1ms );
}
lock_guard<mutex> mux( output_ownership );
cout << "Thread 0 terminates" << endl;
}
void print_message_function2( char const* const message )
{
for( int i = 0; i < 10; ++i )
{
{
lock_guard<mutex> mux( output_ownership );
cout << "Hello #" << i << message << endl;
}
this_thread::sleep_for( 1ms );
}
lock_guard<mutex> mux( output_ownership );
cout << "Thread 1 terminates" << endl;
}
auto main() -> int
{
cout << "Main: Creating threads" << endl;
cout << "Main: Waiting for threads to finish" << endl << endl;
thread thread1( print_message_function1, " from Thread 1" );
thread thread2( print_message_function2, " from Thread 2" );
thread1.join();
thread2.join();
cout << "Main: Exiting" << endl;
}
```
This compiles and runs fine with Visual C++ 2015. It does not compile with MinGW-64 g++ 5.1.0, because its `std::thread` support is very much lacking. I do not know whether it will compile with latest version of g++ in Unix-land. |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | If you want to color fill a specific cell in a table you can use the code below.
For example let's say you need to fill the first cell in the first row of your table with the RGB color 1F5C8B:
```
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
```
Now if you want to also fill the second cell in the first row with the same color, you should create a new element
otherwise if you use the same element as above the fill will move on and will disappear from the first cell...
```
shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[1]._tc.get_or_add_tcPr().append(shading_elm_2)
```
...and so on for other cells.
Source: <https://groups.google.com/forum/#!topic/python-docx/-c3OrRHA3qo> | With Nikos Tavoularis' solution, we have to create a new element for every cell.
I have created a function that achieves this. Works in Python revision 3.5.6 and python-docx revision 0.8.10
```
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def set_table_header_bg_color(table.rows[row_ix].cell):
"""
set background shading for Header Rows
"""
tblCell = cell._tc
tblCellProperties = tblCell.get_or_add_tcPr()
clShading = OxmlElement('w:shd')
clShading.set(qn('w:fill'), "00519E") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
tblCellProperties.append(clShading)
return cell
"""
End of set_table_header_bg_color Function
"""
# main function
"""
..
..
..
1. Load Document
..
2. Access the required section
..
3. Load the required Table
..
4. Traverse to the cell by accessing the rows object
..
"""
for each_row in table.rows :
for each_cell in each_row.cells:
if each_cell.value satisfies a condition:
set_table_header_bg_color(each_cell)
"""
5. Continue execution
"""
``` |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | What we found is that, if you do cell.add\_paragraph('sometext', style\_object), it will keep the existing empty paragraph and add an additional paragraph with the style, which is not ideal.
What you will want to do is something like:
```
# replace the entire content of cell with new text paragraph
cell.text = 'some text'
# assign new style to the first paragraph
cell.paragraphs[0].style = style_object
```
Note that the style is applied to the paragraph not the cell, which isn't ideal for background colors (since it won't fill the enter cell if you have some padding. I haven't found a way around that (except in the case where you want EVERY cell to have a background color, you can apply a style to table.style).
Also, make sure that your styles are defined. You can check
```
styles = documents.styles
for s in styles:
print s.name
```
to see all the styles you have. You can define new styles and also load a template document with pre-defined styles already. | Taking from Nikos Tavoularis answer I would just change the shading\_elm\_1 declaration, as if you include the cell color in a loop for instance things might get messy.
As such, my suggestion would be:
```
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w'))))
``` |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | If you want to color fill a specific cell in a table you can use the code below.
For example let's say you need to fill the first cell in the first row of your table with the RGB color 1F5C8B:
```
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
```
Now if you want to also fill the second cell in the first row with the same color, you should create a new element
otherwise if you use the same element as above the fill will move on and will disappear from the first cell...
```
shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[1]._tc.get_or_add_tcPr().append(shading_elm_2)
```
...and so on for other cells.
Source: <https://groups.google.com/forum/#!topic/python-docx/-c3OrRHA3qo> | What we found is that, if you do cell.add\_paragraph('sometext', style\_object), it will keep the existing empty paragraph and add an additional paragraph with the style, which is not ideal.
What you will want to do is something like:
```
# replace the entire content of cell with new text paragraph
cell.text = 'some text'
# assign new style to the first paragraph
cell.paragraphs[0].style = style_object
```
Note that the style is applied to the paragraph not the cell, which isn't ideal for background colors (since it won't fill the enter cell if you have some padding. I haven't found a way around that (except in the case where you want EVERY cell to have a background color, you can apply a style to table.style).
Also, make sure that your styles are defined. You can check
```
styles = documents.styles
for s in styles:
print s.name
```
to see all the styles you have. You can define new styles and also load a template document with pre-defined styles already. |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | If you want to color fill a specific cell in a table you can use the code below.
For example let's say you need to fill the first cell in the first row of your table with the RGB color 1F5C8B:
```
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
```
Now if you want to also fill the second cell in the first row with the same color, you should create a new element
otherwise if you use the same element as above the fill will move on and will disappear from the first cell...
```
shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[1]._tc.get_or_add_tcPr().append(shading_elm_2)
```
...and so on for other cells.
Source: <https://groups.google.com/forum/#!topic/python-docx/-c3OrRHA3qo> | If you want to loop through the cells in a row use:
```
def color_row(row=0):
'make row of cells background colored, defaults to column header row'
row = t.rows[row]
for cell in row.cells:
shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
cell._tc.get_or_add_tcPr().append(shading_elm_2)
```
run the function to color cells in the second row
`color_row(2)` |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | What we found is that, if you do cell.add\_paragraph('sometext', style\_object), it will keep the existing empty paragraph and add an additional paragraph with the style, which is not ideal.
What you will want to do is something like:
```
# replace the entire content of cell with new text paragraph
cell.text = 'some text'
# assign new style to the first paragraph
cell.paragraphs[0].style = style_object
```
Note that the style is applied to the paragraph not the cell, which isn't ideal for background colors (since it won't fill the enter cell if you have some padding. I haven't found a way around that (except in the case where you want EVERY cell to have a background color, you can apply a style to table.style).
Also, make sure that your styles are defined. You can check
```
styles = documents.styles
for s in styles:
print s.name
```
to see all the styles you have. You can define new styles and also load a template document with pre-defined styles already. | I made a video demonstrating a way to do it here I took inspiration from the people above but I still had issues so I made this too help others.
<https://www.youtube.com/watch?v=1Mgb95yigkk&list=PL_W7lgC2xeJfWBUllp7ALKOM5GUBMCVoP>
```
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
document = Document("youfile.docx")
Table = document.tables[0]
#GET CELLS XML ELEMENT
cell_xml_element = Table.rows[1].cells[0]._tc
#RETRIEVE THE TABLE CELL PROPERTIES
table_cell_properties = cell_xml_element.get_or_add_tcPr()
#CREATE SHADING OBJECT
shade_obj = OxmlElement('w:shd')
#SET THE SHADING OBJECT
shade_obj.set(qn('w:fill'), "ff00ff")
#APPEND THE PROPERTIES TO THE TABLE CELL PROPERTIES
table_cell_properties.append(shade_obj)
document.save("yoursavefile.docx")
```
The code above will change the first cellof the second row of the first table in the document.[Example of the output.](https://i.stack.imgur.com/dlRMf.png) |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | It looks like instead of using the `cell.text = "Something"` method you need to use the `cell.add_paragraph("SomeText", a_style)` with a defined style - probably one of:
* ColorfulGrid
* ColorfulGrid-Accent1
* ColorfulGrid-Accent2
* ColorfulGrid-Accent3
* ColorfulGrid-Accent4
* ColorfulGrid-Accent5
* ColorfulGrid-Accent6
*Full list [here](https://python-docx.readthedocs.org/en/latest/user/styles.html).*
If you use the “default” template document - otherwise you will have to create your own. | I made a video demonstrating a way to do it here I took inspiration from the people above but I still had issues so I made this too help others.
<https://www.youtube.com/watch?v=1Mgb95yigkk&list=PL_W7lgC2xeJfWBUllp7ALKOM5GUBMCVoP>
```
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
document = Document("youfile.docx")
Table = document.tables[0]
#GET CELLS XML ELEMENT
cell_xml_element = Table.rows[1].cells[0]._tc
#RETRIEVE THE TABLE CELL PROPERTIES
table_cell_properties = cell_xml_element.get_or_add_tcPr()
#CREATE SHADING OBJECT
shade_obj = OxmlElement('w:shd')
#SET THE SHADING OBJECT
shade_obj.set(qn('w:fill'), "ff00ff")
#APPEND THE PROPERTIES TO THE TABLE CELL PROPERTIES
table_cell_properties.append(shade_obj)
document.save("yoursavefile.docx")
```
The code above will change the first cellof the second row of the first table in the document.[Example of the output.](https://i.stack.imgur.com/dlRMf.png) |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | It looks like instead of using the `cell.text = "Something"` method you need to use the `cell.add_paragraph("SomeText", a_style)` with a defined style - probably one of:
* ColorfulGrid
* ColorfulGrid-Accent1
* ColorfulGrid-Accent2
* ColorfulGrid-Accent3
* ColorfulGrid-Accent4
* ColorfulGrid-Accent5
* ColorfulGrid-Accent6
*Full list [here](https://python-docx.readthedocs.org/en/latest/user/styles.html).*
If you use the “default” template document - otherwise you will have to create your own. | I have compiled the previous answers and added some features.
Feel free to test: Create new file run the "main" part at the bottom.
```
""" adder for python-docx in order to change text style in tables:
font color, italic, bold
cell background color
based on answers on
https://stackoverflow.com/questions/26752856/python-docx-set-table-cell-background-and-text-color
"""
import docx # import python-docx (in order to create .docx report file)
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
def change_table_cell(cell, background_color=None, font_color=None, font_size=None, bold=None, italic=None):
""" changes the background_color or font_color or font style (bold, italic) of this cell.
Leave the params as 'None' if you do not want to change them.
params:
cell: the cell to manipulate
background_color: name for the color, e.g. "red" or "ff0000"
font_color:
font_size: size in pt (e.g. 10)
bold: requested font style. True or False, or None if it shall remain unchanged
italic: requested font style. True or False, or None if it shall remain unchanged
background_color: the color of cells background"""
if background_color:
shading_elm = parse_xml(r'<w:shd {} w:fill="{}"/>'.format(nsdecls('w'), background_color))
cell._tc.get_or_add_tcPr().append(shading_elm)
if font_color:
for p in cell.paragraphs:
for r in p.runs:
r.font.color.rgb = docx.shared.RGBColor.from_string(font_color)
if font_size:
for p in cell.paragraphs:
for r in p.runs:
r.font.size = docx.shared.Pt(font_size)
if bold is not None:
for p in cell.paragraphs:
for r in p.runs:
r.bold = bold
if italic is not None:
for p in cell.paragraphs:
for r in p.runs:
r.italic = italic
def change_table_row(table_row, background_color=None, font_color=None, font_size=None, bold=None, italic=None):
for cell in table_row.cells:
change_table_cell(cell, background_color=background_color, font_color=font_color, font_size=font_size,
bold=bold,
italic=italic)
if __name__ == "__main__": # do the following code only if we run the file itself
#document = docx.Document('template.docx') # create an instance of a word document, use the style that we have defined in 'template.docx'
document = docx.Document()
num_rows = 4
num_cols = 3
table = document.add_table(rows=num_rows, cols=num_cols) # create empty table
#table.style = document.styles['MyTableStyleBlue'] # test overwriting the predefined style
# fill table
for row in range(num_rows):
for col in range(num_cols):
table.rows[row].cells[col].text = f'row/col=({row},{col})'
""" change color (see https://stackoverflow.com/questions/26752856/python-docx-set-table-cell-background-and-text-color) """
# Nikos Tavoularis answered Apr 18, 2017 at 8:38
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
# test new function derived from dyoung's answere of May 25 at 7:34, 2022
change_table_cell(table.rows[0].cells[0], background_color=None, font_color="ff0000", bold=False)
change_table_cell(table.rows[1].cells[2], background_color="00ff00", font_color="ff0000", font_size=20, bold=True)
change_table_row(table.rows[3], background_color="lightgreen", font_color="0000ff", italic=True) # https://www.delftstack.com/howto/python/colors-in-python/
document.save('table_shading_test.docx')
``` |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | It looks like instead of using the `cell.text = "Something"` method you need to use the `cell.add_paragraph("SomeText", a_style)` with a defined style - probably one of:
* ColorfulGrid
* ColorfulGrid-Accent1
* ColorfulGrid-Accent2
* ColorfulGrid-Accent3
* ColorfulGrid-Accent4
* ColorfulGrid-Accent5
* ColorfulGrid-Accent6
*Full list [here](https://python-docx.readthedocs.org/en/latest/user/styles.html).*
If you use the “default” template document - otherwise you will have to create your own. | Taking from Nikos Tavoularis answer I would just change the shading\_elm\_1 declaration, as if you include the cell color in a loop for instance things might get messy.
As such, my suggestion would be:
```
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w'))))
``` |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | I made a video demonstrating a way to do it here I took inspiration from the people above but I still had issues so I made this too help others.
<https://www.youtube.com/watch?v=1Mgb95yigkk&list=PL_W7lgC2xeJfWBUllp7ALKOM5GUBMCVoP>
```
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
document = Document("youfile.docx")
Table = document.tables[0]
#GET CELLS XML ELEMENT
cell_xml_element = Table.rows[1].cells[0]._tc
#RETRIEVE THE TABLE CELL PROPERTIES
table_cell_properties = cell_xml_element.get_or_add_tcPr()
#CREATE SHADING OBJECT
shade_obj = OxmlElement('w:shd')
#SET THE SHADING OBJECT
shade_obj.set(qn('w:fill'), "ff00ff")
#APPEND THE PROPERTIES TO THE TABLE CELL PROPERTIES
table_cell_properties.append(shade_obj)
document.save("yoursavefile.docx")
```
The code above will change the first cellof the second row of the first table in the document.[Example of the output.](https://i.stack.imgur.com/dlRMf.png) | If you want to loop through the cells in a row use:
```
def color_row(row=0):
'make row of cells background colored, defaults to column header row'
row = t.rows[row]
for cell in row.cells:
shading_elm_2 = parse_xml(r'<w:shd {} w:fill="1F5C8B"/>'.format(nsdecls('w')))
cell._tc.get_or_add_tcPr().append(shading_elm_2)
```
run the function to color cells in the second row
`color_row(2)` |
26,752,856 | I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.
I could not find any usefull resources about single cell formatting
Any suggestions?
Edit 1
my code
```
style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
#V headinh se piše prvo polje iz table heada
document.add_heading(rec['tableHead'][0][0], level=1)
image_path = imageFolder + "\\" + slike[a]
document.add_picture(image_path, height=Inches(3.5))
#y += 28
#worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])
for i, head in enumerate(rec['tableHead']):
table = document.add_table(rows=1, cols = len(head))
hdr_cells = table.rows[0].cells
for a in range(0,len(head)):
hdr_cells[a].text = head[a]
for a,body in enumerate(rec['tableData']):
row_cells = table.add_row().cells
for a in range(0,len(body)):
if body[a]['style'] == 'footer':
stil = style_footer
elif body[a]['style'] == 'red':
stil = style_red
elif body[a]['style'] == 'yellow':
stil = style_yellow
elif body[a]['style'] == 'green':
stil = style_green
else:
stil = style_transperent
row_cells[a].add_paragraph(body[a]['value'], stil)
document.save(wordDoc)
```
All cells are still the same. | 2014/11/05 | [
"https://Stackoverflow.com/questions/26752856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945446/"
] | With Nikos Tavoularis' solution, we have to create a new element for every cell.
I have created a function that achieves this. Works in Python revision 3.5.6 and python-docx revision 0.8.10
```
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
def set_table_header_bg_color(table.rows[row_ix].cell):
"""
set background shading for Header Rows
"""
tblCell = cell._tc
tblCellProperties = tblCell.get_or_add_tcPr()
clShading = OxmlElement('w:shd')
clShading.set(qn('w:fill'), "00519E") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
tblCellProperties.append(clShading)
return cell
"""
End of set_table_header_bg_color Function
"""
# main function
"""
..
..
..
1. Load Document
..
2. Access the required section
..
3. Load the required Table
..
4. Traverse to the cell by accessing the rows object
..
"""
for each_row in table.rows :
for each_cell in each_row.cells:
if each_cell.value satisfies a condition:
set_table_header_bg_color(each_cell)
"""
5. Continue execution
"""
``` | If you want to change the text color too, you can set it on the runs within the cell. I wrote this function to handle the cell background and text colors together (using Nikos' method for the fill):
```
def shade_cell(cell, fill=None, color=None):
if fill:
shading_elm = parse_xml(r'<w:shd {} w:fill="{}"/>'.format(nsdecls('w'), fill))
cell._tc.get_or_add_tcPr().append(shading_elm)
if color:
for p in cell.paragraphs:
for r in p.runs:
r.font.color.rgb = RGBColor.from_string(color)
```
I originally tried to expand Nikos' solution by adding `w:color="XXXXXX"` to the `w:shd` tag but that didn't work for me. However setting the font color on each run got the result I wanted. |
66,310,704 | ```
Python 3.8.3
asgiref 3.3.1
Django 2.2
django-crispy-forms 1.10.0
djangorestframework 3.11.1
Pillow 7.2.0
pip 19.2.3
psycopg2 2.8.6
pytz 2020.1
setuptools 41.2.0
sqlparse 0.3.1
```
Sorry, I'm not sure where there is an abnormality in a situation, can you mention me?
Then I posted error information in stackoverflow and presented it with my code, the link is [AttributeError: type object 'Product' has no attribute 'objects'](https://stackoverflow.com/questions/66310704/attributeerror-type-object-product-has-no-attribute-objects)
, You can click the link to enter and watch...Thank you.
Everyone, help me think about the screen. After I clicked on the product I need add to car, an error appeared, and the product could not be added to my shopping cart. May I ask if this message appears.
File "C:\Users\georgiawang\PycharmProjects\libshopapp\store\views.py", line 195, in updateItem\*\*
product = Product.objects.get(id=productId)
AttributeError: type object'Product' has no attribute'objects'\*\*
Is it because views.py is damaged?
Because **"POST /store/update\_item/ HTTP/1.1" 500 59** the information came out a bit unexpectedly, after all, I didn’t mess with the program. I don’t know which side of the program affects QWQ.
Hope to mention me a bit, thank you very much.
遇到問題是:The problems encountered are:
```
product = Product.objects.get(id=productId)
AttributeError: type object 'Product' has no attribute 'objects'
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
February 22, 2021 - 13:09:19
Django version 2.2, using settings 'libshopapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[22/Feb/2021 13:09:22] "GET /store/ HTTP/1.1" 200 32153
Action: add
Product: 135
1.
Traceback (most recent call last):
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\georgiawang\PycharmProjects\libshopapp\store\views.py", line 195, in updateItem**
product = Product.objects.get(id=productId)
AttributeError: type object 'Product' has no attribute 'objects'**
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\python\Python38\lib\site-packages\django\utils\deprecation.py", line 94, in __call__
response = response or self.get_response(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 36, in inner
response = response_for_exception(request, exc)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 90, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
2.
Traceback (most recent call last):
File "D:\python\Python38\lib\wsgiref\handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "D:\python\Python38\lib\site-packages\django\contrib\staticfiles\handlers.py", line 65, in __call__
return self.application(environ, start_response)
File "D:\python\Python38\lib\site-packages\django\core\handlers\wsgi.py", line 141, in __call__
response = self.get_response(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\base.py", line 75, in get_response
response = self._middleware_chain(request)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 36, in inner
response = response_for_exception(request, exc)
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 90, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "D:\python\Python38\lib\site-packages\django\core\handlers\exception.py", line 125, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "D:\python\Python38\lib\site-packages\django\views\debug.py", line 94, in technical_500_response
html = reporter.get_traceback_html()
File "D:\python\Python38\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html
t = DEBUG_ENGINE.from_string(fh.read())
UnicodeDecodeError: 'cp950' codec can't decode byte 0xe2 in position 9735: illegal multibyte sequence
**[22/Feb/2021 13:09:27] "POST /store/update_item/ HTTP/1.1" 500 59**
```
請幫忙看看,謝謝?
please help to see, thank you.
//////////////////////////////////////////////////////code//////////////////////////////////////////////
***/// store / models.py ///***
```
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Product(models.Model):
name = models.CharField(max_length=200)
content = models.TextField(default='')
price = models.DecimalField(max_digits=7, decimal_places=2)
digital = models.BooleanField(default=False, null=True, blank=True)
draft = models.BooleanField(default=False)
image = models.ImageField(
upload_to=imgs,
null=True,
blank=True,
width_field="width_field",
height_field="height_field",
)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
products = ProductManage()
def __unicode__(self):
return self.name
def __str__(self):
return self.name
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
def get_absolute_url(self):
return reverse('store:detail', kwargs={'id': self.id})
class Meta:
ordering = ["-timestamp", "-updated"]
```
***/// home / urls.py ///***
```
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
# path('order/', views.order, name='order'),
path('social/', views.socialview, name='social'),
path('about/', views.aboutview, name='about'),
path('contact/', views.contact, name='contact'),
path('', views.index, name='index'),
]
```
***/// store / urls.py ///***
```
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
# Leave as empty string for base url
path('', views.store, name='store'),
path('cart/', views.cart, name='cart'),
path('create/', views.productCreate, name='create'),
path('<int:id>/', views.productDetail, name='detail'),
path('<int:id>/update/', views.productUpdate, name='update'),
path('<int:id>/delete/', views.productDelete, name='delete'),
path('checkout/', views.checkout, name='checkout'),
path('update_item/', views.updateItem, name='update_item'),
# path('update_item/', views.updateItem, name='update_item'),
path('process_order/', views.processOrder, name='process_order'),
path('searchbar/', views.searchbar, name='searchbar'),
]
```
***/// store / views.py ///***
```
import datetime
import json
from django.contrib import messages
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ProductForms
from .models import Product
from .utils import cartData, guestOrder
from django.utils import timezone
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action:', action)
print('Product:', productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if orderItem.quantity <= 0:
orderItem.delete()
return JsonResponse('Item was added', safe=False)
```
***/// cart.js ///***
question: "POST /store/update\_item/ HTTP/1.1" 500 59
```
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
if (user == 'AnonymousUser'){
addCookieItem(productId, action)
}else{
updateUserOrder(productId, action)
}
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = '/store/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
function addCookieItem(productId, action){
console.log('User is not authenticated')
if (action == 'add'){
if (cart[productId] == undefined){
cart[productId] = {'quantity':1}
}else{
cart[productId]['quantity'] += 1
}
}
if (action == 'remove'){
cart[productId]['quantity'] -= 1
if (cart[productId]['quantity'] <= 0){
console.log('Item should be deleted')
delete cart[productId];
}
}
console.log('CART:', cart)
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
```
***/// froms.py ///***
```
from django import forms
from store.models import Product, RegistrationData
class ProductForms(forms.ModelForm):
class Meta:
model = Product
fields = [
'name',
'price',
'digital',
'image',
'width_field',
'height_field',
'content',
]
``` | 2021/02/22 | [
"https://Stackoverflow.com/questions/66310704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15011706/"
] | where you import your models.py in your views.py?
just import your models file in your views and then you will be able to access your models classes in your views file.
something just like this:
```
from <models_directory> import models
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
product = models.Product.objects.get(id=productId)
# and other...
``` | make sure you did not define class name or function or varible with same name |
25,709,478 | If I shuffle a small list using [python's `random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle), I'm getting also unshuffled results.
```
import random
for i in range(10):
ori = [1, 2, 3]
per = ori[:]
random.shuffle(per)
print i, per, (per == ori) or ""
```
Here is a sample output:
```
0 [1, 3, 2]
1 [1, 2, 3] True
2 [3, 1, 2]
3 [2, 3, 1]
4 [1, 2, 3] True
5 [2, 3, 1]
6 [3, 2, 1]
7 [2, 1, 3]
8 [2, 1, 3]
9 [2, 1, 3]
```
I understand that this must necessarily be the case, after looking into the algorithm details [[1]](https://stackoverflow.com/a/3062966/2932052), [[2]](https://stackoverflow.com/a/18628010/2932052). But I really want get a small unsorted list (say 3 to 6 items) programmatically.
What do you think is the best approach to do this? | 2014/09/07 | [
"https://Stackoverflow.com/questions/25709478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2932052/"
] | If you must exclude the original ordering, you could simply retry the shuffle until `per != ori`. | Since it's a short array do a quick shuffle manually:
```
import random
for i in range(len(ori) - 1):
j = random.randint(i + 1, len(ori) - 1)
ori[i], ori[j] = ori[j], ori[i]
```
This way you will ensure that you won't get the original array. This is an `O(n)` solution, you should only use it on small arrays. |
25,709,478 | If I shuffle a small list using [python's `random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle), I'm getting also unshuffled results.
```
import random
for i in range(10):
ori = [1, 2, 3]
per = ori[:]
random.shuffle(per)
print i, per, (per == ori) or ""
```
Here is a sample output:
```
0 [1, 3, 2]
1 [1, 2, 3] True
2 [3, 1, 2]
3 [2, 3, 1]
4 [1, 2, 3] True
5 [2, 3, 1]
6 [3, 2, 1]
7 [2, 1, 3]
8 [2, 1, 3]
9 [2, 1, 3]
```
I understand that this must necessarily be the case, after looking into the algorithm details [[1]](https://stackoverflow.com/a/3062966/2932052), [[2]](https://stackoverflow.com/a/18628010/2932052). But I really want get a small unsorted list (say 3 to 6 items) programmatically.
What do you think is the best approach to do this? | 2014/09/07 | [
"https://Stackoverflow.com/questions/25709478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2932052/"
] | Well one way would be generate permutations of the list and then drop the first item. After that you can use `random.choice` to pick any of the permutation:
```
>>> from random import choice
>>> from itertools import permutations
>>> data = list(permutations([1, 2, 3], 3))[1:]
>>> for _ in range(10):
... print choice(data)
...
(3, 2, 1)
(3, 2, 1)
(2, 1, 3)
(1, 3, 2)
(1, 3, 2)
(1, 3, 2)
(3, 2, 1)
(2, 3, 1)
(2, 3, 1)
(2, 1, 3)
``` | Since it's a short array do a quick shuffle manually:
```
import random
for i in range(len(ori) - 1):
j = random.randint(i + 1, len(ori) - 1)
ori[i], ori[j] = ori[j], ori[i]
```
This way you will ensure that you won't get the original array. This is an `O(n)` solution, you should only use it on small arrays. |
42,136,431 | I'm using Active directory with windows server 2008 R2. I have an application running with Django and python 2.7. Now I need to use active directory authentication to access into my application.
To do that, i'm using this packages:
```
sudo apt-get-update
sudo apt-get install python-dev libldap2-dev libsasl2-dev libssl-dev
sudo pip install django-auth-ldap
sudo pip install python-ldap
```
I used the full name to have a successful bind.
```
import ldap
from django.conf import settings
username='my full name in AD'
password= 'my password'
l = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
l.simple_bind_s(username,password)
```
[](https://i.stack.imgur.com/V5vYg.png)
My problem is when i'm trying to use my cn attribute for bind, i got this error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 207, in
simple_bind_s
return self.result(msgid,all=1,timeout=self.timeout)
File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 422, in
result res_type,res_data,res_msgid = self.result2(msgid,all,timeout)
File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 426, in
result2 res_type, res_data, res_msgid, srv_ctrls =
self.result3(msgid,all,timeout)
File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 432, in
result3 ldap_result = self._ldap_call(self._l.result3,msgid,all,timeout)
File "/usr/lib/python2.7/dist-packages/ldap/ldapobject.py", line 96, in
_ldap_call result = func(*args,**kwargs)
INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C0903A9, comment:
AcceptSecurityContext error, data 52e, v1db1', 'desc': 'Invalid
credentials'}
```
[](https://i.stack.imgur.com/V5vYg.png)
Can I use my cn (common name)attribute for authentication to my Active directory?
Thanks. | 2017/02/09 | [
"https://Stackoverflow.com/questions/42136431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4787419/"
] | You can't use the cn value in your simple\_bind(). Use the alternate user principal name `sAMAccountName@FQDN` instead, or one of the other [supported bind names](https://msdn.microsoft.com/en-us/library/cc223499.aspx). | @marabu, thanks for the reply. You're right, ican't use any editor attribute (like cn, ....) in the simple bind.
we have an access to this attribute only by search method after having a successfull bind.
In my case i have two choices:
1) simple\_bind\_s(full\_name, password)
2) simple\_bind\_s(sAMAccountName@FQDN, password) if we are using email address to our session authenticate
like this:
[](https://i.stack.imgur.com/YCmuk.png) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.