qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
10,137,026 | So I have the directory struture like this
```
Execute_directory--> execute.py
|
Algorithm ---> algorithm.py
|
|--> data.txt
```
So I am inside execute directory and have included the following path to my python path.
```
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/.... | 2012/04/13 | [
"https://Stackoverflow.com/questions/10137026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | Are you reading `data.txt` in `algorithm.py` like this:
```
open('data.txt')
```
Because that is relative to the *working directory* and not relative to the scripts directory.
In `algorithm.py` you could try this:
```
open(os.path.join(os.path.dirname(__file__), 'data.txt'))
``` | This would usually be an issue with relative filenames not being relative to where you expect. Print the contents of `os.path.abspath(filename)` to check this. If it gives you something strange, specifying the absolute path in the first place (when you initialise `filename`) should fix it. | 15,761 |
38,060,383 | I have the following sql query:
```
SELECT
pc.patente,
cs.cpc_group_codigo_cpc_group
FROM
patente_pc pc
,
patente_cpc cpc,
cpc_subgroup cs,
cpc_group cg
WHERE
pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND
cpc.cpc = cs.codigo_cpc_subgroup AND
cs.cpc_group_codigo_c... | 2016/06/27 | [
"https://Stackoverflow.com/questions/38060383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691244/"
] | >
> Does Google allow third party access?
>
>
>
Yes. If you're going to be doing interactive programming using mainstream services, learn to use APIs. The Google API collection allows users to register their applications and sites for a *huge* variety of their services...including `Gmail`.
Look [here](https://con... | I agree with the others its fairly well documented, particularly here would be relevant for you if you intend to get started using the Java API:
[Google docs](https://developers.google.com/gmail/api/quickstart/java#step_3_set_up_the_sample)
>
> To run this quickstart, you'll need:
>
>
> Java 1.7 or greater. Gradle ... | 15,764 |
16,136,341 | I need to optimize a function call that is in a loop, for a time-critical robotics application. My script is in python, which interfaces via ctypes with a C++ library I wrote, which then calls a microcontroller library.
The bottleneck is adding position-velocity-time points to the microcontroller buffer. According to ... | 2013/04/21 | [
"https://Stackoverflow.com/questions/16136341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/901553/"
] | The round-trip between Python and C++ can be expensive, especially when using *ctypes* (which is like an interpreted version of a normal C/Python wrapper).
Your goal should be to minimize the number of trips and do the most work possible per trip.
It looks to me like your code has too fine of a granularity (i.e. doin... | You can just use `data_np.data.tobytes()`:
```
data_np = np.vstack([nodes, positions, velocities, times]).transpose().astype(np.long)
timer = time()
clibrary.addPvtAll(N, data_np.data.tobytes())
print("clibrary.addPvtAll() call: %f" % (time() - timer))
``` | 15,765 |
71,987,704 | So here is the code in question. The error I get when I run the code is
File "D:\obj\windows-release\37amd64\_Release\msi\_python\zip\_amd64\random.py", line 259, in choice
TypeError: object of type 'type' has no len()
```
import random
import tkinter as tk
from tkinter import messagebox
root=tk.Tk()
root.title("Tra... | 2022/04/24 | [
"https://Stackoverflow.com/questions/71987704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18834663/"
] | This is verging on an opinion-based question, but I think it is on-topic, since it helps to clarify the syntax and structure of ggplot calls.
In a sense you have already answered the question yourself:
>
> it does not seem to be documented anywhere in the ggplot2 help
>
>
>
This, and the near absence of examples... | ### TL;DR
I cannot see any strong reasons why not to use this pattern, but other patterns are recommended in the documentation, without elaboration.
### What does `+ aes()` do?
A ggplot has two types of aesthetics:
* the default one (typically supplied inside `ggplot()`), and
* `geom_*()` specific aesthetics
If `i... | 15,767 |
39,086,368 | I'm trying to read beyond the EOF in Python, but so far I'm failing (also tried to work with seek to position and read fixed size).
I've found a workaround which only works on Linux (and is quite slow, too) by working with debugfs and subprocess, but this is to slow and does not work on windows.
My Question: is it po... | 2016/08/22 | [
"https://Stackoverflow.com/questions/39086368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691944/"
] | You can't read more bytes than is in the file. "End of file" literally means exactly that. | You can only move to the end using:
```
file.seek(0, 2)
```
Is that you're trying to do? | 15,768 |
35,118,312 | I am trying to install a python package that needs a Windos C++ compiler
The install procedure sent me to this link:
<https://wiki.python.org/moin/WindowsCompilers>
I am using Python 2.7 x86 on Win 7 x64
The version indicated on that page is not available anymore (Microsoft Visual C++ 9.0 standalone: Visual C++ Compil... | 2016/01/31 | [
"https://Stackoverflow.com/questions/35118312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059078/"
] | Not sure what is happening with Microsoft today or these days but here is the direct link
<http://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi>
Alternatively you can search github, for "VCForPython27.msi site:github.com"
That will give you either the above link or links... | The [express versions of visual studio](https://www.visualstudio.com/products/visual-studio-express-vs) are free, I assume the command line compiler would work.
You might also need to read [Microsoft Visual C++ Compiler for Python 2.7](https://stackoverflow.com/questions/26140192/microsoft-visual-c-compiler-for-python... | 15,769 |
58,862,894 | I'm working in python using pandas and ultimately wanting to run a random forest. Python bugs out because I can't get this numeric column with spaces as nulls to be converted to a float. I tried fillna with zero and astype(float) but no success. Thanks all!
```
sm['PopHalfMile']
Out[64]:
0 2072
1 4392
2... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58862894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12374239/"
] | Unfortunately, I don't think there is any way to do regex matching on `if` conditional expressions yet.
One option is to use filtering on `push` events.
```
on:
push:
tags:
- 'v*.*.*'
```
Another option is to do the regex check in a separate step where it [creates a step output](https://help.github.com/... | As per [docs](https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet), you can do this:
```
on:
create:
tags:
- "v[0-9]+.[0-9]+"
```
I tried the above and can confirm it works. This is not full regex capability but should suffice for your needs. | 15,771 |
5,072,630 | I am trying to create a simple form/script combination that will allow someone to replace the contents of a certain div in an html file with the text they input in an html form on a separate page.
The script works fine if everything is local : the script is local, i set the working directory to where my html file is,... | 2011/02/21 | [
"https://Stackoverflow.com/questions/5072630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/627466/"
] | Yes, use:
```
range(1,7)
```
that should do it. | Use the [`range`](http://docs.python.org/library/functions.html#range) builtin.
```
range(1, 7)
``` | 15,773 |
59,141,776 | Follow the script below to convert a JSON file to parquet format. I am using the pandas library to perform the conversion.
However the following error is occurring: AttributeError: 'DataFrame' object has no attribute 'schema'
I am still new to python.
Here's the original json file I'm using:
[
{
"a": "01",
"b": "te... | 2019/12/02 | [
"https://Stackoverflow.com/questions/59141776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10515027/"
] | If your motive is to just convert json to parquet, you can probably use pyspark API:
```
>>> data = [ { "a": "01", "b": "teste01" }, { "a": "02", "b": "teste02" } ]
>>> df = spark.createDataFrame(data)
>>> df.write.parquet("data.parquet")
```
Now, this DF is a spark dataframe, which can be saved in parquet. | Welcome to Stackoverflow, the library you are using shows that in example that you need to write the column names in the data frame.
Try using column names of your data frame and it will work.
```
# Given PyArrow schema
import pyarrow as pa
schema = pa.schema([
pa.field('my_column', pa.string),
pa.field('my_in... | 15,774 |
61,619,201 | While adding groups with permission from Django Admin Panel and adding other M2M relationships too. I got this error!!
It says : **TypeError: \_bulk\_create() got an unexpected keyword argument 'ignore\_conflicts'**
I can't find the error, Probably a noob mistake.
```
class GroupSerializer(serializers.ModelSerialize... | 2020/05/05 | [
"https://Stackoverflow.com/questions/61619201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8944012/"
] | You should use:
```
@EventBusSubscriber
public static class Class {
@SubscribeEvent
public static void onEvent(EntityJoinWorldEvent event) {
if ((event.getEntity() instanceof PlayerEntity)) {
LogManager.getLogger().info("Joined!");
}
}
}
```
I thought maybe you'd need the instance of the pl... | ```java
...
@Mod(
modid = Kubecraft.MOD_ID,
name = Kubecraft.MOD_NAME,
version = Kubecraft.VERSION
)
public class Kubecraft {
...
@SubscribeEvent
public static void onEvent(EntityJoinWorldEvent event) {
Timer timer = new Timer(3000, new ActionListener() {
... | 15,781 |
48,579,232 | [enter image description here](https://i.stack.imgur.com/g89q0.jpg)i was trying to run the following command::
```
python populate_book.py
```
and stuck with this error::
```
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
```
The Whole Tra... | 2018/02/02 | [
"https://Stackoverflow.com/questions/48579232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9298418/"
] | Three things that you should make sure,
* are all the apps you have in your `INSTALLED_APPS` setting installed
on your system?
* Have you perhaps forgotten to activate the virtualenv
where everything was installed in the first place?
* If you have both of the things above on your system then maybe you
forgot to insta... | <https://www.dangtrinh.com/2014/11/how-to-avoid-models-arent-loaded-yet.html>
My advice would strongly be to perform this sort of operation within a Custom Management Command though <https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/>. | 15,782 |
927,150 | I've made a python script which should modify the profile of the phone based on the phone position. Runned under ScriptShell it works great.
The problem is that it hangs, both with the "sis" script runned upon "boot up", as well as without it.
So my question is what is wrong with the code, and also whether I need to ... | 2009/05/29 | [
"https://Stackoverflow.com/questions/927150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88054/"
] | I often use something like that at the top of my scripts:
```
import os.path, sys
PY_PATH = None
for p in ['c:\\Data\\Python', 'e:\\Data\\Python','c:\\Python','e:\\Python']:
if os.path.exists(p):
PY_PATH = p
break
if PY_PATH and PY_PATH not in sys.path: sys.path.append(PY_PATH)
``` | xprofile is not a standard library, make sure you add path to it. My guess is that when run as SIS, it doesn't find xprofile and hangs up. When releasing your SIS, either instruct that users install that separately or include inside your SIS.
Where would you have it installed, use that path. Here's python default dire... | 15,783 |
61,082,945 | So, I'm learning python in school and as a part of my current project I want to be able to make small "popups" on the screen. I've chosen to do this with wxpython but I've run into a problem. Right now I can't find a way to add a variable so I can print anything I want. I tried adding an extra variable both to the clas... | 2020/04/07 | [
"https://Stackoverflow.com/questions/61082945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13250047/"
] | You almost have it. You just need to straighten out a few details. First, if the input fails, you want an empty input:
```
try:
move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
move = []
```
Now you want to repeat the input until it is valid. You first need the syntax for a whi... | You could do this with a nested function and a recursive call if the input doesn't conform to expectations.
```py
import re
def main():
def prompt():
digits = input("Select a cell (row,col) > ")
if not re.match(r'\d+,\d+', digits):
print('Error message')
prompt()
r... | 15,784 |
2,622,866 | How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. [])
```
if request.is_ajax() and request.method == 'GET':
groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"]))
groups = groupSet.groups.all()
group_items = ... | 2010/04/12 | [
"https://Stackoverflow.com/questions/2622866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314614/"
] | Your 'groups' variable is a QuerySet object, not a dict. You will want to be more explicit with the data that you want to return.
```
import json
groups_and_items = {}
for group in groups:
group_items = []
for item in group.group_items.all():
group_items.append( {'id': item.id, 'name': item.name} )
... | You should use Python's [json](http://docs.python.org/library/json.html) module to encode your JSON.
Also, what indentation level do you have `data = serializers` at? It looks like it could be inside the for loop? | 15,786 |
46,366,139 | Hi i have a simplified example of my problem.
i would like to get an output of
```
1
a
b
2
c
3
d
e
f
4
g
5
h
```
I have tried different variations but can figure out the logic. My code is below. Thanks for your help in advance. I am trying to do it without using numpy or panda. I am using python3.4
```
num = ["1"... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46366139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7680853/"
] | Note that you are trying to print the contents of two lists. This is a linear operation in time. Two loops just won't cut it - that's quadratic in time complexity. Furthermore, your second solution doesn't flatten `y`.
---
Define a helper function using `yield` and `yield from`.
```
def foo(l1, l2):
for x, y i... | just `zip` the lists and flatten twice applying `itertools.chain`
```
num = ["1" , "2" ,"3" , "4" , "5" ]
let = [["a","b"],["c"],["d","e","f"],["g"],["h"]]
import itertools
result = list(itertools.chain.from_iterable(itertools.chain.from_iterable(zip(num,let))))
```
now `result` yields:
```
['1', 'a', 'b', '2', '... | 15,787 |
3,248,194 | Whats wrong in this code?
Here is my HTML:
```
<html><body>
<form action="iindex.py" method="POST" enctype="multipart/form-data">
<p>File: <input type="file" name="ssfilename"></p>
<p><input type="submit" value="Upload" name="submit"></p>
</form>
</body></html>
```
This is my Python script:
```
#! /usr/bin/env pyt... | 2010/07/14 | [
"https://Stackoverflow.com/questions/3248194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392373/"
] | Edit: Totally missed the part where you are `doing keep_blank_values = 1`; sorry, no idea what is wrong.
From <http://docs.python.org/library/cgi.html>:
>
> Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep\_blank\_va... | Check if you have no GET parameters in your form action URL.
If you need to pass on any data put it as form elements inside the form to be POSTed along with your upload file.
Then you find all your POSTed vars in `cgi.FieldStorage`. | 15,795 |
59,432,477 | I am working through an issue with scraping a webtable using python. I have been scraping what I would call 'standard' tables for a while and I feel like I understand that reasonably well. I define a standard table as having a structure like:
```
<table>
<tr class="row-class">
<th>Bill</th>
<td>1</td>
<td>2</td>... | 2019/12/20 | [
"https://Stackoverflow.com/questions/59432477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10862305/"
] | Here I use 3 methods how to pair the two `<tr>` tags together:
* 1st method is using `zip()` and CSS selector
* 2nd method is using BeautifulSoup's method `find_next_sibling()`
* 3rd method is using `zip()` and simple slicing with custom step
---
```
from bs4 import BeautifulSoup
t_obj = """<tr class="row-class">
... | You can use indexing:
```
from bs4 import BeautifulSoup as soup
d = soup(html, 'html.parser').find_all('tr')
result = [[d[i].text]+[c.text for c in d[i+1].find_all('td')] for i in range(0, len(d), 2)]
```
To print your result:
```
print('\n'.join(f'{a[1:]},{",".join(b)}' for a, *b in result))
```
Output:
```
Bil... | 15,797 |
10,061,124 | I once read this entry in mailing list <http://archives.postgresql.org/pgsql-hackers/2005-06/msg01481.php>
```
SELECT *
FROM foo_func(
c => current_timestamp::timestamp with time zone,
a => 2,
b => 5
);
```
Now I need this kindof solution where I can pass associative array argument to a function.
Do I ne... | 2012/04/08 | [
"https://Stackoverflow.com/questions/10061124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256007/"
] | If you have `a` as your clustering key, then that column is included in all non-clustered indices on that table.
So your index on `c` also includes `a`, so the condition
```
where c= 3 and a = 3
```
can be found in that index using an index seek. Most likely, the query optimizer decided that doing a index seek to... | >
> *This is fine, because the non clustered index doesn't have b as the key value. Hence it does an index scan from column a.*
>
>
>
This assumption is not right. index seek and scan has to deal with WHERE clause and not the select clause.
Now your question -
Where clause is optimised by sql optimizer and as th... | 15,799 |
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)
wr... | 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
<... | 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>
``` | 15,800 |
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 = "... | 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)
... | 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 ... | 15,801 |
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 struc... | 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['P... | 15,804 |
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;' \
... | 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_quer... | 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> | 15,806 |
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... | 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, ... | 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... | 15,809 |
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()
... | 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 | 15,810 |
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 re... | 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
N... | 15,811 |
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... | 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/ques... | 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. | 15,812 |
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 usin... | 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... | 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),... | 15,816 |
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 plug... | 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'... | 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)
``` | 15,817 |
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" % settin... | 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();
}
``` | 15,818 |
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:
```... | 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=check... | 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. | 15,819 |
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 ... | 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 bi... | 15,822 |
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 = 'B... | 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",
... | 15,823 |
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 objec... | 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... | 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 ... | 15,828 |
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_s... | 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(... | 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')... | 15,829 |
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 r... | 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("\\.");
... | 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`.
```... | 15,837 |
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:... | 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.exampl... | 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>",... | 15,845 |
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`... | 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 /... | 15,846 |
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... | 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 + ",");
}
``` | 15,849 |
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"],
'Lab... | 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 tryin... | 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... | 15,859 |
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:
... | 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** | 15,861 |
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 c... | 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... | 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. | 15,862 |
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).rea... | 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 s... | 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 ... | 15,864 |
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",
... | 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);
``` | 15,867 |
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/_clinkgramm... | 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. | 15,874 |
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.a... | 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_o... | 15,879 |
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 ... | 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 ... | 15,881 |
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 ... | 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)... | 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 | 15,883 |
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\\acc... | 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. | 15,884 |
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 stateme... | 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 re... | 15,885 |
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 = "LightShadin... | 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"/... | 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):
""... | 15,886 |
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... | 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... | make sure you did not define class name or function or varible with same name | 15,896 |
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 sampl... | 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... | 15,897 |
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 libs... | 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, p... | 15,899 |
51,268,745 | How can I create a permutation mapping of two lists in python?
For example I have two lists `[1,2,3]` and `['A','B','C']`
Then my code should generate a list of 6 dictionaries
```
[ {1:'A',2:'B',3:'C'},
{1:'A',2:'C',3:'B'},
{1:'B',2:'A',3:'C'},
{1:'B',2:'C',3:'A'},
{1:'C',2:'A',3:'B'},
{1:'C',2:'B',3:'A'} ... | 2018/07/10 | [
"https://Stackoverflow.com/questions/51268745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8272518/"
] | Using [`zip`](https://docs.python.org/3/library/functions.html#zip) and [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) in a list comprehension:
```
>>> from itertools import permutations
>>> L1 = [1,2,3]
>>> L2 = ['A','B','C']
>>> [dict(zip(L1, p)) for p in permutat... | You seem to permutate only the values of the dicts, so you could do something like
```
from itertools import permutations
dicts = []
keys = [1, 2, 3]
for values in permutations(['A', 'B', 'C']):
new_dict = dict(zip(keys, values))
dicts.append(new_dict)
``` | 15,900 |
1,150,765 | I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code:
```
A = "10000"
B = "10000"
C = "100" + "00"
D =... | 2009/07/19 | [
"https://Stackoverflow.com/questions/1150765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125185/"
] | Python is allowed to inline string constants; A,B,C,D are actually the same literals (if Python sees a constant expression, it treats it as a constant).
`str` is actually a class, so `str(whatever)` is calling this class' constructor, which should yield a fresh object. This explains E,F,G (note that each of these has ... | I believe short strings that can be evaluated at compile time, will be interned automatically. In the last examples, the result can't be evaluated at compile time because `str` or `join` might be redefined. | 15,901 |
20,448,734 | ```
#!/bin/sh
echo "Hello from sh"
```
---
When I run this program (hello.sh) I get a command not found error. I'm using cygwin on Windows and I looked at cy's FAQ. It said to change the permissions to 755. I already did that and still no luck. I get the same error with these other two programs.
```
#!/usr/bin/env ... | 2013/12/08 | [
"https://Stackoverflow.com/questions/20448734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As has already been said, you need to add the Cygwin binaries to your path. To do so, right click on "My Computer", click "Properties", then "Advanced", then "Environment Variables".
Create a new environment variable with name `CYGWIN_HOME` and value `C:\cygwin` (or wherever you installed cygwin. The default location ... | I was getting the "command not found" error on a Perl script. That script has the shebang line: "#!/usr/bin/env perl" as the first line and my user is the owner who has execute permissions. I was trying to run the script using the command line "ppminstall.pl ?" (the script is set up to display documentation for using t... | 15,906 |
67,698,235 | I wonder that is there anyway to speed up python3/numpy's `np.where` operation? I have a minimal working example as follows:
```
from time import time
import numpy as np
a = np.random.randint(0, 4, (768, 512, 512))
b = a.copy().astype(np.uint8)
c = b.copy()
print(a.shape)
ts = time()
a[a > 0] = 1
print(f'normalize i... | 2021/05/26 | [
"https://Stackoverflow.com/questions/67698235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15424596/"
] | The best way to accomplish your operation is to convert the matrix to the boolean datatype and then back to integer, especially if 8-bit integers are used:
```
import numpy as np
import timeit
a = np.random.randint(0, 4, (768, 512, 512))
a_short = a.astype(np.uint8)
# Time to initialize
%timeit b=a.copy()
201 ms ... | You could try with `numexpr`:
```
import numpy as np
import numexpr as ne
# for timing reference
a = np.random.randint(0, 4, (768, 512, 512))
%timeit a[a > 0] = 1
```
782 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
a = np.random.randint(0, 4, (768, 512, 512))
%timeit a = ne.evaluate("where(... | 15,908 |
66,730 | I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object. | 2008/09/15 | [
"https://Stackoverflow.com/questions/66730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8453/"
] | You can also define signals inside the class definition:
```
class MyGObjectClass(gobject.GObject):
__gsignals__ = {
"some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
}
```
The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`. | Here is how:
```
import gobject
class MyGObjectClass(gobject.GObject):
...
gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST,
None, (str, int))
```
Where the second to last argument is the return type and the last argument is a tuple of argument types. | 15,909 |
73,069,374 | I have this table
| Stars |
| --- |
| 3 stars |
| Stars 20 |
| 901stars |
| 8 |
I'm using python to filter the table but I'm not sure of the regex to reject 8. `[^0-9]` will flag `3 stars, 901stars` as errors too but I just want to flag that 8 is incorrect based on the regex.
The regex I need would only flag out the... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73069374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16125533/"
] | I'd suggest `\d+$` to match 1 or more digits at the end of the line. (or even `^\d+$` to search from beginning of line).
disclaimer: I don't have a clue wrt Python, but if has a standard rx library, this should work. | Here is a way without using regex.
```
pd.to_numeric(df['Stars'],errors = 'coerce').isna()
``` | 15,911 |
2,587,709 | I was wondering if there is a way to automatically run commands on entering the python shell as you would with the .bash\_profile or .profile scripts with bash. I would like to automatically import some modules so I don't have to type the whole shebang everytime I hop into the shell.
Thanks, | 2010/04/06 | [
"https://Stackoverflow.com/questions/2587709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278205/"
] | Yup you can use the `PYTHONSTARTUP` environment variable to do this as outlined [here](http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file) | Also consider using [ipython](http://ipython.scipy.org/) if you're doing a lot of interactive work. Your options for this kind of automation expand significantly. | 15,912 |
56,902,458 | I am trying to use this example code from the PyTorch [website](https://pytorch.org/tutorials/advanced/cpp_export.html) to convert a python model for use in the PyTorch c++ api (LibTorch).
```
Converting to Torch Script via Tracing
To convert a PyTorch model to Torch Script via tracing, you must pass an instance of yo... | 2019/07/05 | [
"https://Stackoverflow.com/questions/56902458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4402282/"
] | (from pytorch forums)
trace only supports modules that have tensor or tuple of tensor as output.
According to deeplabv3 implementation, its output is OrderedDict. That is a problem.
To solve this, make a wrapper module
```
class wrapper(torch.nn.Module):
def __init__(self, model):
super(wrapper, self).__i... | Your problem originates in the BatchNorm layer. If it requires *more than one value per channel*, then your model is in training mode. Could you invoke <https://pytorch.org/cppdocs/api/classtorch_1_1nn_1_1_module.html#_CPPv4N5torch2nn6Module4evalEv> on the model and see if there's an improvement?
Otherwise you could ... | 15,913 |
14,425,833 | What I'm trying to do seems rather simple, but I can't find a way to do it.
Imagine somebody sends you a link for a dropbox folder. You can go to that URL and see all the files in the folder.
I'm trying to write a script in either python, php, or javascript to get all the download links in that folder from that URL.
... | 2013/01/20 | [
"https://Stackoverflow.com/questions/14425833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706798/"
] | In absence of suffixes, sufficiently small numbers have `int` or `double` types
```
a = 42; /* 42 has type int */
b = 42.0; /* 42.0 has type double */
```
You can use suffixes to specify the type of the literal
```
c = 42U; /* unsigned int */
d = 42.0f; /* float */
e = 42.0L; /* long double */
f = 42ULL; /* unsigne... | >
> Will I need to cast one of the operands to (float) to make this
> condition true?
>
>
>
Yes, because integral literals are of type `int` and a division between two `int` types returns also an `int`, meaning that the fraction is omitted.
>
> Has the situation now changed, because the compiler notices one of ... | 15,914 |
58,464,713 | `H4sIAAAAAAAAAO1aT3PbSHaHrPHYkj1j73gn2doku3B2N7PJLjz4T0BVqQpFQiQ4BCCBoCjiomoADRIk/mhBUBT5AXJL5ZbkkqocUqVrDvkE+ijzFXJNJXkNSjLHpjyyx95JuWQfRHSjG6/f+/V7v/e6tylqi9qItimKYu5R96Jg4x82qPu1bJoWG9vUZoEGW9QnOPWHFPm3SW01owDvxWgwgcf/2aa2O+NpHFuzFOcPqXt6QP06CESZD8KAYVUkMUJFDhkk4goTYB7xvuf7LO/BuP08O8F5EeHJFvWwwGfFNMcTIsbGQ+r+IYqnmPp... | 2019/10/19 | [
"https://Stackoverflow.com/questions/58464713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989704/"
] | There are no quotes in your string; it's simply made up of two identical base64 encoded strings, each of which can be decoded fine after a small fix: it appears that what has happened is that the trailing `==` in the first string have become `\u003d\u003d`. Replace `\u003d\u003d` with `==` and use the first string, or ... | You can use triple quotes like so :
```
my_var = """My text with quotes ' " is stored in a variable this way"""
```
You could also use ''' instead of """ if you prefer.
```
my_var = '''My text with quotes ' " is also stored in a variable this way'''
```
See : <https://docs.python.org/3/tutorial/introduction.html#... | 15,917 |
28,654,590 | Our security team asked me to not submit `plain text` passwords in my log in page, we use HTTPS though. so I thought that I need to do client side encryption before submit, I searched for solution and decided to implement [jCryption](http://www.jcryption.org/).
However the example presented there is PHP/python, aft... | 2015/02/22 | [
"https://Stackoverflow.com/questions/28654590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735839/"
] | Your understanding about the second function is correct.
You may want to store actual nodes in the `edges` slot instead of node numbers. Then, instead of binding local variables to the node list inside of the two nodes that you want to connect, though, you can bind them to the nodes themselves, which would also look b... | Instead of:
```
(setf (slot-value (nth begin-node node-list) 'edges)
(cons end-node (slot-value (nth begin-node node-list) 'edges)))
```
You can write:
```
(push end-node (slot-value (nth begin-node node-list) 'edges))
```
Why is the following not working as expected?
```
(let ((begin-node-lst (slot-value ... | 15,918 |
40,712,568 | This python script returns a value of `90.0`:
```
import itertools
a=[12,345,1423,65,234]
b=[234,12,34,1,1,1]
c=[1,2,3,4]
def TestFunction (a, b, c):
result = a + b/c
return result
Params=itertools.product(a, b, c)
x = 2
print(TestFunction(*list(Params)[x]))
```
However, I would like to evaluate my funct... | 2016/11/21 | [
"https://Stackoverflow.com/questions/40712568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7098896/"
] | ```
for x in range (5):
print(TestFunction(*list(Params)[x]))
```
`Params` is an iterator. The first time through the loop, you consume it entirely by converting it to a list. Therefore on the second iteration there's nothing in it and converting it to a list yields `[]`, the empty list, and trying get index 1 of... | Because calling `list()` on the iterator exhausts the iterator. Thus it can be called once only:
```
>>> Params=itertools.product(a, b, c)
>>> Params
<itertools.product object at 0x7f5ed3da5870>
>>> list(Params)
[(12, 234, 1), (12, 234, 2)..., (234, 1, 4)]
>>> list(Params)
[]
```
You can see that the second call to ... | 15,919 |
68,650,493 | I have some experience starting starting up Apache Airflow but I have now an error when I try to `airflow db init` command. The error is as below. I am running Airflow on virtual env with Python 3.8. Any help would appreciated. I am not sure to understand this error as I managed to init the db without importing any `_c... | 2021/08/04 | [
"https://Stackoverflow.com/questions/68650493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8867871/"
] | Use `CROSS JOIN` to build all combinations and top up with a `LEFT JOIN`:
```
SELECT p.product_id, s.status, COUNT(t.any_not_null_column)
FROM (SELECT DISTINCT product_id FROM t) AS p
CROSS JOIN (SELECT DISTINCT status FROM t) AS s
LEFT JOIN t ON p.product_id = t.product_id AND s.status = t.status
GROUP BY p.product_i... | The following is a Postgres solution (a database I strongly recommend over MS Access). The idea is to generate all the rows and then use `left join` and `group by` to get the counts you want:
```
select p.product_id, s.status, count(d.product_id)
from (select distinct product_id from details) p cross join
(values... | 15,922 |
42,881,650 | I have a list e.g. `l1 = [1,2,3,4]` and another list: `l2 = [1,2,3,4,5,6,7,1,2,3,4]`.
I would like to check if `l1` is a subset in `l2` and if it is, then I want to delete these elements from `l2` such that `l2` would become `[5,6,7,1,2,3,4]`, where indexes 0-3 have been removed.
Is there a pythonic way of doing thi... | 2017/03/19 | [
"https://Stackoverflow.com/questions/42881650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Well, here is a brute-force way. There are probably more efficient ways. If you expect to encounter a matching sublist early, the performance shouldn't be terrible.
```
>>> l1 = [1,2,3,4]
>>> l2 = [1,2,3,4,5,6,7,1,2,3,4]
>>> for i in range(0, len(l2), len(l1)):
... if l2[i:len(l1)] == l1:
... del l2[i:len(... | I'm not proud of this, and it's not pythonic, but I thought it might be a bit of fun to write. I've annotated the code to make it a little more obvious what's happening.
```
>>> import re
>>> from ast import literal_eval
>>> l1 = [1,2,3,4]
>>> l2 = [1,2,3,4,5,6,7,1,2,3,4]
>>> literal_eval( # convert the strin... | 15,923 |
42,890,951 | I have anaconda installed in my Mac. I am trying to install python-igraph.
I tried the following commands to install it:
```
$ brew install igraph
$ pip install python-igraph
```
My python setup:
```
Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (cl... | 2017/03/19 | [
"https://Stackoverflow.com/questions/42890951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2529269/"
] | I found exactly what I was looking for, [SwipeCellKit](https://github.com/jerkoch/SwipeCellKit), by jerkoch. This library performs the same exact actions as the stock iOS Mail app does when swiping to the left. No need to deal with different `UIViews` and `UIButtons`.
To use, simply conform to the `SwipeTableViewCellD... | I would take a look at the [SWTableViewCell](https://github.com/CEWendel/SWTableViewCell) by CEWendel. It looks like it has exactly what you're looking for. | 15,924 |
49,132,008 | I have next method:
```
public void callPython() throws IOException {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("python -c \"from test import read_and_show; read_and_show()\" src/main/python");
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
... | 2018/03/06 | [
"https://Stackoverflow.com/questions/49132008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5417750/"
] | When executing other programs from java, I've found it's easier to keep it as simple as possible in java and instead execute a batch file
```
Runtime.getRuntime().exec("chrome.exe www.google.com");
```
Would instead become
```
Runtime.getRuntime().exec("openChrome.bat");
```
and openChrome.bat:
```
chrome.exe ww... | You're missing the shebang statement that states where the python interpreter is. It should be line #1
```
#!/usr/bin/python
``` | 15,927 |
33,560,877 | I would like to convert my list(items) from string to int, therefore I can calculate the numbers in it. However, the python showed up the invalid literal for int() with base 10 error, and I've no idea what's wrong with it. (list: in one line only, separate by comma and no space before and after comma.)
list:
```
51,2... | 2015/11/06 | [
"https://Stackoverflow.com/questions/33560877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532342/"
] | I modified according to your code. Please have try.
```
def main():
file = str(input("Please enter the full name of the desired file (with extension) at the prompt below: \n"))
parseCSV(file)
def parseCSV(file):
file_open = open(file)
print (file_open.read())
with open(file) as rd:
lines... | To answer your question, *'What's wrong with it?'*:
You are reading in your whole csv to a list containing one item that is the whole file as a long string. Even if your csv only contains integers the way you are parsing in all of the lines will not work. | 15,929 |
22,023,184 | I tried to subclass NSThread in order to operate a thread with some data. I want to simulate the join() in python, according to the doc:
>
> join(): Wait until the thread terminates. This blocks the calling thread until
> the thread whose join() method is called terminates
>
>
>
So I think using performSelector... | 2014/02/25 | [
"https://Stackoverflow.com/questions/22023184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014948/"
] | From Apple's documentation on `performSelector:onThread:withObject:waitUntilDone:`:
>
> This method queues the message on the run loop of the target thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the target threa... | You're basically in a deadlock condition.
```
-(void)join
{
[self performSelector:@selector(myRun) onThread:self withObject:nil waitUntilDone:YES];
}
```
`join` is waiting for `myRun` to finish (waitUntilDone flag), but `myRun` is enqueued on the same thread as `join`, so it's also waiting for `join` to finish.
... | 15,932 |
56,143,264 | i upgrade pip. But after the upgrade have some syntax error.
i try install python 3.x but not fixed.
Traceback (most recent call last):
```
File "/usr/bin/pip", line 7, in <module>
from pip._internal import main
File "/usr/lib/python2.6/site-packages/pip/_internal/__init__.py", line 19, in <module>
from pi... | 2019/05/15 | [
"https://Stackoverflow.com/questions/56143264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7571523/"
] | python2.6 is not supported anymore, try to change you SYS PATH to point for new python and pip
check this : [Python ENV](https://www.tutorialspoint.com/python/python_environment.htm)
alternatively you can use the following:
```
/path/to/pip3 install ....
/path/to/python3 <NAME_OF_THE_SCRIPT>
``` | ----------UPDATE----------------
i try to install python36u i got some errors
```
Error: Package: python36u-libs-3.6.8-1.el7.ius.x86_64 (ius)
Requires: liblzma.so.5(XZ_5.0)(64bit)
Error: Package: python36u-libs-3.6.8-1.el7.ius.x86_64 (ius)
Requires: libgdbm_compat.so.4()(64bit)
Error: Package: p... | 15,933 |
43,773,802 | Using python and pandas I can easily construct a sparse DataFrame from a list of dictionary objects. The following code snippet shows how this can be done in pandas:
```
In [1]: import pandas as pd; (pd.DataFrame([{'a':1, 'b':10},
{'d':99, 'c':1},
... | 2017/05/04 | [
"https://Stackoverflow.com/questions/43773802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862483/"
] | We can use `melt` with `xtabs` in `R`
```
library(reshape2)
xtabs(value~L1 + L2, melt(values))
# L2
#L1 a b c d
# 1 1 10 0 0
# 2 0 0 1 99
# 3 0 1 0 4
``` | Here's a solution with `plyr` package:
```
ldply(values, data.frame)
a b d c
1 1 10 NA NA
2 NA NA 99 1
3 NA 1 4 NA
# mutate each to replace NA with 0
ldply(values, data.frame) %>%
mutate_each(funs(replace(., is.na(.), 0)))
a b d c
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
``` | 15,935 |
18,942,318 | I try to upload the data into datastore use remote\_api at my dev server, but I got the following error, the SDK version is 1.8.4. Is there anyone has the same error? It looks like the new datastore version 4 cause this?
```
Traceback (most recent call last):
File "D:\python-lib\google_appengine\appcfg.py", line 1... | 2013/09/22 | [
"https://Stackoverflow.com/questions/18942318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2345755/"
] | What about this?
```
MyBase * base = dynamic_cast<MyBase *>(clicked_shape);
base->SetText("too");
```
You might want to check for `base` being null, if the Shape you get isn't actually one of yours.
`MyBase` needs at least one virtual function for this - the destructor would do. | Shape class is a base class hence it provides an interface that can be overridden. E.g. there could be `draw()` method which is called to draw a shape. That one would be a good candidate to be overridden in your new class with text box. For example:
```
class SquareWithText: public Square {
void draw() {
Square:... | 15,940 |
28,962,266 | I had drawn up an UI using the QT Designer but found out that there are no parameters for me to set QLineEdit inputs to be uppercase.
After doing some online searching, I have only seen a very few handful of results that cater to my needs, however all are coded in Qt. Example, this [link](http://www.qtforum.org/articl... | 2015/03/10 | [
"https://Stackoverflow.com/questions/28962266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212246/"
] | Try this,
I believe this serves your purpose. I won't call it much pythonic. More like PyQt override.
#minor code edit
```
from PyQt4 import QtGui
import sys
#===============================================================================
# MyEditableTextBox-
#=======================================================... | Hey i know i am kind of late, but I hope this might help some one else like me who spent some time searching for this
**Mycase:**
I was trying to convert only the first letter to capital and this is what i ended up with and it worked (just a beginner in python so if you can make this more pythonic please let me know)
... | 15,941 |
42,683,602 | I am writing a new Python application that I intend to distribute to several colleagues. Instead of my normal carefree attitude of just having everything self contained and run inside a folder in my home directory, this time I would like to broaden my horizon and actually try to utilize the Linux directory structure as... | 2017/03/08 | [
"https://Stackoverflow.com/questions/42683602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2272450/"
] | You could use the `map()` feature of the stream to convert each `User` instance in your list to a `UserWithAge` instance.
```
List<User> userList = ... // your list
List<UserWithAge> usersWithAgeList = userList.stream()
.map(user -> {
// create UserWithAge instance and copy user name
... | While you could do this, You should not do like this.
```
List<UserWithAge> userWithAgeList = new ArrayList<UserWithAge>();
userList.stream().forEach(user -> {
UserWithAge userWithAge = new UserWithAge();
userWithAge.setName(user.getName());
userWithAge.setAge(27);
... | 15,946 |
70,600,154 | How can I implement a selection based on selecting the first 3n+1 elements from a tag in it's path? For example, let's say I have the following xpath:
```
//div[@class='ResultsSectionContainer-sc-gdhf14-0 kteggz']/div[@class='Wrapper-sc-11673k2-0 gIBPSk']//div/div/a
```
Taken from this url:
```
https://www.jobsite.... | 2022/01/05 | [
"https://Stackoverflow.com/questions/70600154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15675231/"
] | The XPath filter predicate `[position() mod 3 = 1]` selects all elements whose 1-based position is 3n+1 for some integer n. | All you need here is to use a **correct** locator.
I guess you are trying to get all the job links?
If so, instead of this
`//div[@class='ResultsSectionContainer-sc-gdhf14-0 kteggz']/div[@class='Wrapper-sc-11673k2-0 gIBPSk']//div/div/a`
very long, complex and fragile XPath you can use this XPath:
```py
//a[@d... | 15,949 |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | Replace call with check\_output.
```
from subprocess import check_output
a = check_output(["lsb_release", "-si"])
``` | You can also try subprocess.check\_output.
Based on docs: "Run command with arguments and return its output as a byte string." Docs: <https://docs.python.org/2/library/subprocess.html>
Code:
```
a = subprocess.check_output(["lsb_release", "-si"])
```
In my case, output was:
```
'Ubuntu\n'
``` | 15,950 |
49,105,070 | I'm a python newbie. I created a calculator program that will accept 2 number and a type of operation from user. I already have a working code for this but I want to further simplify the code by exploring and using function.
Here's the portion of the code:
```
def addition(num1,num2):
sum = num1 + num2
print('... | 2018/03/05 | [
"https://Stackoverflow.com/questions/49105070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9404668/"
] | You should write something like that.. the ?? is so that if it can't convert the argument into Int it will add 0 to your variable myInt..
```
let myInt:Int = Int("1234") ?? 0
``` | You can do it like this by creating an extension of String:
```
extension String {
var toInt: Int {
return Int(self) ?? 0
}
}
```
and use it like this
```
let preparationTimeInt = preparationTime.toInt
``` | 15,960 |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | I have faced the similar issue in Windows Server 2012 r2. After lot of findings I found that mfplat.dll was missing which is related to Window Media Service.
Hence you have to manually install the features so that you can get dll related to window media service.
1. Turn windows features on or off
2. Skip the roles sc... | I had the same problem on Windows Server 2012 R2 x64. I was creating executable file using PyInstaller and got error in runtime:
```
ImportError: DLL load failed: The specified module could not be found.
```
After installing "Visual C++ redistributable" 2015 and enabling "Media Foundation" feature my problem was res... | 15,961 |
24,944,627 | I'm using the Canopy distribution and when I try to install pymatbridge using 'pip install pymatbridge' I get an error saying that pymatbridge does not work on win32. I've got the 64-bit version of Canopy so I don't understand what that means.
<http://arokem.github.io/python-matlab-bridge/>
```
Downloading/unpacking ... | 2014/07/24 | [
"https://Stackoverflow.com/questions/24944627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/334059/"
] | I am the developer of this software. This should work now (since version 0.4), but I don't have a Windows machine to test this one. I have had help from Windows users in developing the patches to make this Windows-functional. Though, I am not always able to solve issues, I am happy to receive suggestions/complaints/pra... | "Win32" in this context means Windows 32- or 64-bit, as distinct from Cygwin.
The developer of pymatbridge introduced this explicit restriction in May 2014:
<https://github.com/arokem/python-matlab-bridge/commit/a6fd3cc3adf5ef2b5e3d9b83a8050d783c76d48f>
I don't know why. Perhaps, like many small developers, he found ... | 15,971 |
60,119,580 | I am building HR app using python with Django framework, I am having issue to calculation retirement year of an employee, for example if an employee enters his/her date of birth let the system calculate his/her retirement year or how many years remaining to retire. staff retire at 60 years
Am getting this error:
```
... | 2020/02/07 | [
"https://Stackoverflow.com/questions/60119580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860292/"
] | Here's a full working example of what you want to achieve:
```
import pandas as pd
import matplotlib.pyplot as plt
import pandas as pd
df_1 = pd.DataFrame({'2010':[10,11,12,13],'2011':[14,18,14,15],'2012':[12,13,14,13]})
df_2 = pd.DataFrame({'2010':[10,11,12,13],'2011':[14,18,14,15],'2012':[12,13,14,13]})
df_3 = pd.Da... | I figured out the solution for this, hope it will be helpful to others. Since the input is list of dataframe, it is easier to do as follow:
```
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from itertools import cycle
df1, df2 = list_of_df[0], list_of_df[1]
colors=cm.tab10(np.linspace(0, 1,len(df1... | 15,972 |
59,207,859 | I've found related question, mine about GitLab, those about GitHub: [How to remove extra line space on GitHub markdown bullets/lists?](https://stackoverflow.com/questions/45113083/how-to-remove-extra-line-space-on-github-markdown-bullets-lists) and one answer is to use 4 spaces and another:
>
> You cannot do this ...... | 2019/12/06 | [
"https://Stackoverflow.com/questions/59207859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5499118/"
] | I found that alternating between the `+` and `-` unordered list indicators produces the desired result.
```
- Item 1
- SubItem 1
- SubItem 2
+ Item 2
+ SubItem 1
+ SubItem 2
- Item 3
- SubItem 1
- SubItem 2
``` | Small mistake: should have put `<br/>` on same level as secondary list (indent with 4 spaces) - then extra line is seen in GUI. | 15,975 |
8,673,035 | I know feature hashing (hashing-trick) is used to reduce the dimensionality and handle sparsity of bit vectors but I don't understand how it really works. Can anyone explain this to me.Is there any python library available to do feature hashing?
Thank you. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8673035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/585329/"
] | On Pandas, you could use something like this:
```
import pandas as pd
import numpy as np
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
data = pd.DataFrame(data)
def hash_col(df, col, N):
cols = [col + "_" ... | [Here](http://metaoptimize.com/qa/questions/6943/what-is-the-hashing-trick#6945) (sorry I cannot add this as a comment for some reason.) Also, the first page of [Feature Hashing for Large Scale Multitask Learning](http://arxiv.org/pdf/0902.2206) explains it nicely. | 15,976 |
11,511,080 | I am a beginner at python (one week). Here I am trying print the list of all the prime factor of 60. But for line 19, I am getting following error:
*TypeError: unsupported operand type(s) for %: 'float' and 'list'*
The code:
```
whylist = []
factor = []
boom = []
primefactor = []
n = 60
j = (list(range(1, n, 1)))
fo... | 2012/07/16 | [
"https://Stackoverflow.com/questions/11511080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526409/"
] | To apply a math operation to every element in a list you can use a list-comprehension:
```
new_list = [ x%num for x in old_list]
```
There are other ways to do it as well. Sometimes people will use `map`
```
new_list = map(lambda x: x%num, old_list)
```
but most people prefer the first form which is generally mo... | Another option is to use numpy arrays instead of lists.
```
import numpy as np
j = np.arange(1,n,1)
rem = np.mod(j,num)
```
and numpy will take care of broadcasting operations for you. It should also be faster than list comprehensions or map. | 15,979 |
55,235,230 | I get this warning most of the time when i define a model using Keras. It seems to somehow come from tensorflow though:
```
WARNING:tensorflow:From C:\Users\lenik\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\backend\tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with ... | 2019/03/19 | [
"https://Stackoverflow.com/questions/55235230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8104036/"
] | This depreciation warning is due to the Dropout layer in `tf.keras.layers.Dropout`.
To avoid this warning, you need to clearly specify `rate=` in Dropout as: `Dropout(rate=0.2)`.
Earlier it was `keep_prob` and it is now deprecated to `rate` i.e. rate = 1-keep\_prob.
For more, you can check out this tensorflow [doc... | Tensorflow is telling you that the argument `keep_prob` is deprecated and that it has been replaced by the argument `rate`.
Now, to achieve the same behavior you have now and remove the warning, you need to replace every occurrence of the `keep_prob` argument with `rate` argument, and pass the value `1-keep_prob`. | 15,980 |
4,341,206 | When trying to authenticate via OAuth in Django Piston, the following exception is thrown:
```
Environment:
Request Method: GET
Request URL: http://localhost:8000/api/oauth/request_token/?oauth_nonce=32921052&oauth_timestamp=1291331173&oauth_consumer_key=ghof7av2vu8hal2hek&oauth_signature_method=HMAC-SHA1&oauth_versi... | 2010/12/02 | [
"https://Stackoverflow.com/questions/4341206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186101/"
] | This is a piston problem that comes from an encoding problem of the key/secret of the consumer.
The solution is to force the encoding of the key/secret returned from the database to ASCII.
In the `store.py` file of Piston, modify the `lookup_consumer` so it look like this:
```
def lookup_consumer(self, key):
try:... | This problem also occurs inside Piston's "oauth.py" module's "build\_signature()" method if a unicode key value is passed in. I discovered this issue while using the clemesha/django-piston-oauth-example client code mentioned above because it kept failing after the prompt for the "PIN Code".
The underlying problem is d... | 15,981 |
62,555,213 | I am having two dicts, one in list:
```
var_a = [{'name':"John",'number':21},{'name':"Kevin",'number':23}]
var_b = {'21':"yes"},{'24':"yes"}
```
I need to compare var\_a and var\_b with the key from var\_b with the number value in var\_a.
I have tried this and got the output:
```
for key, value in var_b.iteritems(... | 2020/06/24 | [
"https://Stackoverflow.com/questions/62555213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741562/"
] | You can use `map` to create a keys set from `var_b` keys and then loop only over `var_a` to check if the number value exists in the `var_b` keys set
```
var_a = [{'name':"John",'number':21},{'name':"Kevin",'number':23}]
var_b = [{'21':"yes"},{'23':"no"}]
keys_set = set(map(lambda x: int(list(x.keys())[0]), var_b))
fo... | I think you need to use the lambda function with one for-loop:
```
for key, value in var_b.iteritems():
result = filter(lambda d: d['id'] == key, var_a)
```
The result will give you the output for sure. | 15,982 |
35,823,709 | I have read the article "Ubuntu Installation --Guide for Ubuntu 14.04 with a 64 bit processor." from Github website (<https://github.com/tiangolo/caffe/blob/ubuntu-tutorial-b/docs/install_apt2.md>).
And now, I open IPython to test that PyCaffe is working. I input "ipython" command, and enter to the ipython page.
Then,... | 2016/03/06 | [
"https://Stackoverflow.com/questions/35823709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4159177/"
] | I found this:
<https://groups.google.com/forum/#!topic/caffe-users/C_air48cISU>
Claiming that this is a non-error, cause by mis-matched versions of Boost. You can safely ignore it. They've promised to clean up the warning (at some point not yet specified) | You can edit /caffe/python/caffe/\_caffe.cpp . There are four places need to change,like this
```
bp::register_ptr_to_python<shared_ptr<Layer<Dtype> > >();
```
to
```
const boost::python::type_info cinfo = boost::python::type_id<shared_ptr<Blob<Dtype> > >();
const boost::python::converter::registration* creg = boos... | 15,983 |
49,963,862 | I have a dictionary that has tuple keys and numpy array values. I tried saving it using h5 and pickle but I get error messages. what is the best way to save this object to file?
```
import numpy as np
from collections import defaultdict
Q =defaultdict(lambda: np.zeros(2))
Q[(1,2,False)] = np.array([1,2])
Q[(1,3,True)]... | 2018/04/22 | [
"https://Stackoverflow.com/questions/49963862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7091646/"
] | How about saving it as a plain dictionary? You don't need the `defaultdict` behavior during saving.
```
In [126]: from collections import defaultdict
In [127]: Q =defaultdict(lambda: np.zeros(2))
...: Q[(1,2,False)] = np.array([1,2])
...: Q[(1,3,True)] = np.array([3,4])
...: Q[(3,4,False)]
...:
Ou... | I don't see any problems using `pickle`
```
import pickle
import numpy as np
x = {(1,2,False): np.array([1,4]), (1,3,False): np.array([4,5])}
with open('filename.pickle', 'wb') as handle:
pickle.dump(x, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open('filename.pickle', 'rb') as handle:
y = pickle.load(ha... | 15,984 |
55,647,936 | I am porting the application from python 2 to python 3 and encountered the following problem: `random.randint` returns different result according to used Python version. So
```
import random
random.seed(1)
result = random.randint(1, 100)
```
On Python 2.x result will be 14 and on Python 3.x: 18
Unfortunately, I nee... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55647936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542977/"
] | The difference is caused by two things:
1. You should use `random.seed(42, version=1)`
2. In python 3.2 there was a change to `random.randrange`, which is called by `random.randint` and probably add to above [issue](https://docs.python.org/3/library/random.html#random.randrange).
So use something like:
```
try: rand... | You can specify which version to use for the seed: `random.seed(1, version=1)`. However, as stated by Sparky05, you are probably better off using `numpy.random` instead. | 15,985 |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | It is "nil coalescing operator" (also called "default operator"). `a ?? b` is value of `a` (i.e. `a!`), unless `a` is `nil`, in which case it yields `b`. I.e. if `favouriteSnacks[person]` is missing, return assign `"Candy Bar"` in its stead. | This:
```
let snackName = favoriteSnacks[person] ?? "Candy Bar"
```
Is equals this:
```
if favoriteSnacks[person] != nil {
let snackName = favoriteSnacks[person]
} else {
let snackName = "Candy Bar"
}
```
Explaining in words, if the `let` statement fail to grab `person` from `favoriteSnacks` it will a... | 15,989 |
54,064,946 | I am working in jupyter with python in order to clean a set of data that I have retrieved from an analysis software and I would like to have an equal number of samples that pass and fail. Basically my dataframe in pandas looks like this:
```
grade section area_steel Nx Myy utilisation Accceptable
0 C16/20 STD ... | 2019/01/06 | [
"https://Stackoverflow.com/questions/54064946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10876004/"
] | Using formatting string and assuming that `optimal_system` is your dictionary:
```
with open('output.txt', 'w') as f:
for k in optimal_system.keys():
f.write("{}: {}\n".format(k, optimal_system[k]))
```
**EDIT**
As pointed by @wwii, the code above can be also written as:
```
with open('output.txt', 'w'... | You can use json.dumps() to do this with the indent parameter. For example:
```
import json
dictionary_variable = {'employee_01': {'fname': 'John', 'lname': 'Doe'},
'employee_02': {'fname': 'Jane', 'lname': 'Doe'}}
with open('output.txt', 'w') as f:
f.write(json.dumps(dictionary_variable, ... | 15,998 |
9,164,176 | >
> **Possible Duplicate:**
>
> [Good Primer for Python Slice Notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation)
>
>
>
I have a string and I'm splitting in a `;` character, I would like to associate this string with variables, but for me just the first x strings is usef... | 2012/02/06 | [
"https://Stackoverflow.com/questions/9164176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/737640/"
] | Yes! Use [slicing](https://stackoverflow.com/q/509211/21475):
```
az1, el1, az2, el2, rfsspe = data_point.split(";")[:5]
```
That "slices" the list to get the first 5 elements only. | The way, I do this is usually to add all the variables to a list(var\_list) and then when I'm processsing the list I do something like
```
for x in var_list[:5]:
print x #or do something
``` | 16,001 |
58,414,350 | Is there a way for Airflow to skip current task from the PythonOperator? For example:
```py
def execute():
if condition:
skip_current_task()
task = PythonOperator(task_id='task', python_callable=execute, dag=some_dag)
```
And also marking the task as "Skipped" in Airflow UI? | 2019/10/16 | [
"https://Stackoverflow.com/questions/58414350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7730549/"
] | Figured it out! Skipping task is as easy as:
```py
def execute():
if condition:
raise AirflowSkipException
task = PythonOperator(task_id='task', python_callable=execute, dag=some_dag)
``` | The easiest solution to skip a task:
```py
def execute():
if condition:
return
task = PythonOperator(task_id='task', python_callable=execute, dag=some_dag)
```
Unfortunately, it will mark task as `DONE` | 16,002 |
49,145,328 | I am new to using google colaboratory (colab) and pydrive along with it. I am trying to load data in 'CAS\_num\_strings' which was written in a pickle file in a specific directory on my google drive using colab as:
```
pickle.dump(CAS_num_strings,open('CAS_num_strings.p', 'wb'))
dump_meta = {'title': 'CAS.pkl', 'paren... | 2018/03/07 | [
"https://Stackoverflow.com/questions/49145328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9407842/"
] | Apply the `click` event for `<tr>` and pass the current reference `this` to the calling function like `<tr onclick="callme(this)">`. From the javascript get the current row reference and find all the `td` inside that. Now get the values using `innerHTML` and assign it to the respective input fields("id\_type" , "event\... | According to HTML spec `id` attribute should be unique in a page,
so if you have multiple elements with same `id`, your HTML is not valid.
`getElementById()` should only ever return one element. You can't make it return multiple elements.
So you can use unique `id` for each row or try using `class` | 16,003 |
62,328,382 | I'm new to python and plotly.graph\_objects. I created some maps similar to the example found here: [United States Choropleth Map](https://plotly.com/python/choropleth-maps/#united-states-choropleth-map)
I'd like to combine the maps into one figure with a common color scale. I've looked at lots of examples of people us... | 2020/06/11 | [
"https://Stackoverflow.com/questions/62328382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373313/"
] | The solution is to not use the `$_COOKIE` array, but a variable
```php
<?php
// Use a variable
$cookieValue = 1;
// Check the cookie
if ((isset($_COOKIE["i"])) && !empty($_COOKIE["i"])) {
$cookieValue = (int)$_COOKIE["i"] + 1;
}
// Push the cookie
setcookie("i", $cookieValue);
// Use the variable
echo $cookieV... | ```
else{
setcookie("i",1);
header("Refresh:0");
}
``` | 16,004 |
57,464,273 | I have a dataframe with a columns that contain GPS coordinates. I want to convert the columns that are in degree seconds to degree decimals. For example, I have a 2 columns named "lat\_sec" and "long\_sec" that are formatted with values like 186780.8954N. I tried to write a function that saves the last character in the... | 2019/08/12 | [
"https://Stackoverflow.com/questions/57464273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11771163/"
] | By doing `float(coordinate[:-1]/3600)` you are dividing `str` by `int` which is not possible, what you can do is convert the `str` into `float` than divide it by integer `3600` which gives you `float` output.
Second you are not using `apply` properly and there is no `lat_sec` column to which you are applying your func... | In your code above, inside `convertDec` method, there is also an error in :
```
decimal = float(coordinate[:-1]/3600)
```
You need to convert the `coordinate` to float first before divide it with 3600.
So, your code above should look like this :
```
import pandas as pd
# Your example dataset
dictCoordinates = {
... | 16,005 |
37,947,178 | I am using python and I have to write a program to create files of a total of 160 GB. I ran the program overnight and it was able to create files of 100 GB. However, after that it stopped running and gave an error saying "No space left on device".
QUESTION : I wanted to ask if it was possible to start running the pro... | 2016/06/21 | [
"https://Stackoverflow.com/questions/37947178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6465134/"
] | Steps to fix this error in windows 10/8/7
1.Check your javac path on Windows using Windows Explorer C:\Program Files\Java\jdk1.7.0\_02\bin and copy the address.
2.Go to Control Panel. Environment Variables and Insert the address at the beginning of var. Path followed by semicolon. i.e C:\Program Files\Java\jdk1.7.0\_... | You need to add the location of your JDK to your PATH variable, if you wish to call javac.exe without the path.
```
set PATH=%PATH%;C:\path\to\your\JDK\bin\dir
```
Then...
```
javac.exe MyFirstProgram.java
```
OR, you can simply call it via the full path to javac.exe from your JDK installation e.g.
```
C:\path\t... | 16,006 |
74,188,813 | In practicing python, I've come across the sliding window technique but don't quite understand the implementation. Given a string k and integer N, the code is to loop through, thereby moving the window from left to right. However, the capture of the windowed elements as well as how the window grows is fuzzy to me.
The... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74188813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10047888/"
] | Instead of trying to solve =b) it might be easier to look at  and just solve this iteratively, taking advantage of Python's integer type. This way you can avoid the float domain, and its associated ... | You can use decimals and play with precision and rounding instead of floats in this case
Like this:
```
from decimal import Decimal, Context, ROUND_HALF_UP, ROUND_HALF_DOWN
ctx1 = Context(prec=20, rounding=ROUND_HALF_UP)
ctx2 = Context(prec=20, rounding=ROUND_HALF_DOWN)
ctx1.divide(Decimal(243).ln( ctx1) , Decimal(3... | 16,007 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.