qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
26,575,303 | Hello people I hope you an help me out with this problem:
I am currently implementing an interpreter for a scripting language. The language needs a native call interface to C functions, like java has JNI. My problem is, that i want to call the original C functions without writing a wrapper function, which converts the call stack of my scripting language into the C call stack. This means, that I need a way, to generate argument lists of C functions at runtime. Example:
```
void a(int a, int b) {
printf("function a called %d", a + b);
}
void b(double a, int b, double c) {
printf("function b called %f", a * b + c);
}
interpreter.registerNativeFunction("a", a);
interpreter.registerNativeFunction("b", b);
```
The interpreter should be able to call the functions, with only knowing the function prototypes of my scripting language: `native void a(int a, int b);` and `native void b(double a, int b, double c);`
Is there any way to generate a C function call stack in C++, or do I have to use assembler for this task. Assembler is a problem, because the interpreter should run on almost any platform.
Edit:
The solution is to use libffi, a library, which handles the call stack creation for many different platforms and operating systems. libffi is also used by some prominent language implementations like cpython and openjdk.
Edit:
@MatsPetersson Somewhere in my code I have a method like:
```
void CInterpreter::CallNativeFunction(string name, vector<IValue> arguments, IReturnReference ret) {
// Call here correct native C function.
// this.nativeFunctions is a map which contains the function pointers.
}
```
**Edit:
Thanks for all your help! I will stay with libffi, and test it on all required platforms.** | 2014/10/26 | [
"https://Stackoverflow.com/questions/26575303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180673/"
] | Yes we can. No FFI library needed, no restriction to C calls, only pure C++11.
```
#include <iostream>
#include <list>
#include <iostream>
#include <boost/any.hpp>
template <typename T>
auto fetch_back(T& t) -> typename std::remove_reference<decltype(t.back())>::type
{
typename std::remove_reference<decltype(t.back())>::type ret = t.back();
t.pop_back();
return ret;
}
template <typename X>
struct any_ref_cast
{
X do_cast(boost::any y)
{
return boost::any_cast<X>(y);
}
};
template <typename X>
struct any_ref_cast<X&>
{
X& do_cast(boost::any y)
{
std::reference_wrapper<X> ref = boost::any_cast<std::reference_wrapper<X>>(y);
return ref.get();
}
};
template <typename X>
struct any_ref_cast<const X&>
{
const X& do_cast(boost::any y)
{
std::reference_wrapper<const X> ref = boost::any_cast<std::reference_wrapper<const X>>(y);
return ref.get();
}
};
template <typename Ret, typename...Arg>
Ret call (Ret (*func)(Arg...), std::list<boost::any> args)
{
if (sizeof...(Arg) != args.size())
throw "Argument number mismatch!";
return func(any_ref_cast<Arg>().do_cast(fetch_back(args))...);
}
int foo(int x, double y, const std::string& z, std::string& w)
{
std::cout << "foo called : " << x << " " << y << " " << z << " " << w << std::endl;
return 42;
}
```
Test drive:
```
int main ()
{
std::list<boost::any> args;
args.push_back(1);
args.push_back(4.56);
const std::string yyy("abc");
std::string zzz("123");
args.push_back(std::cref(yyy));
args.push_back(std::ref(zzz));
call(foo, args);
}
```
Exercise for the reader: implement `registerNativeFunction` in three easy steps.
1. Create an abstract base class with a pure `call` method that accepts a list of `boost::any`, call it `AbstractFunction`
2. Create a variadic class template that inherits `AbstractFunction` and adds a pointer to a concrete-type function (or `std::function`). Implement `call` in terms of that function.
3. Create an `map<string, AbstractFunction*>` (use smart pointers actually).
Drawback: totally cannot call variadic C-style functions (e.g. printf and friends) with this method. There is also no support for implicit argument conversions. If you pass an `int` to a function that requires a `double`, it will throw an exception (which is slightly better than a core dump you can get with a dynamic solution). It is possible to partially solve this for a finite fixed set of conversions by specializing `any_ref_cast`. | **In pure standard C++** (or C; see [n1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) or [n3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) or some newer standard specification, a document written in English), **the set of functions is fixed** -so cannot change-, and given by the union of all your [translation units](https://en.wikipedia.org/wiki/Translation_unit_(programming)) (and by those from the standard C or C++ library). And in pure standard C++ or C, a [function pointer](https://en.wikipedia.org/wiki/Function_pointer) is allowed only to point to some *pre-existing* function (otherwise it is [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior)), when you use it for indirect calls. All functions are, in standard C++ (or C), known at "compile-time", and practically *declared* in some translation unit (and often *implemented* in another one, or in some external library).
BTW, when coding an interpreter (for some scripting language), you don't need to grow the set of your (C or C++) functions. You just need to have (generic) interpreting functions coded in C or C++ dealing with some representation of the interpreted scripting code (which, from the point of view of your C++ or C program, is some data), perhaps an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) or some [bytecode](https://en.wikipedia.org/wiki/Bytecode). For example, a Unix shell, or a [Lua](http://lua.org/) or [Guile](https://www.gnu.org/software/guile/) interpreter, don't create C or C++ functions. You could embed Lua or Guile in your program.
However, you might be interested in *generating* or *creating new* (C or C++) *functions at runtime*, for example when compiling your scripting code into C (a [common](https://softwareengineering.stackexchange.com/a/257873/40065) practice) or in machine code. This is not possible in pure standard C or C++, but is practically possible on many *implementations*, with help from the [operating system](https://en.wikipedia.org/wiki/Operating_system) (at least to grow or add [code segments](https://en.wikipedia.org/wiki/Code_segment), i.e. [new machine](https://en.wikipedia.org/wiki/Machine_code) code, in your [virtual address space](https://en.wikipedia.org/wiki/Virtual_address_space)).
(notice that any mechanism able to create functions at runtime is *outside* of the C or C++ standard, and would return function pointers to new machine code)
See also [this](https://stackoverflow.com/a/48358134/841108) answer (to a very related question, for C; but you could adapt it for C++), detailing how that is practically possible (notably on Linux).
BTW, [`libffi`](https://sourceware.org/libffi/) is by itself *not* a way of *creating new* (C, C++, or machine code) *functions*, but of *calling existing functions* of an *arbitrary* signature with arbitrary arguments.
>
> This means, that I need a way, to generate argument lists of C functions at runtime.
>
>
>
The `libffi` is only doing that. It knows your [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) (and is partly coded in assembler).
Notice that if your set of functions is fixed (so finite), their signatures are also in a finite set, then you don't really need `libffi` (because you could special case all your signatures, so your signatures are *not* arbitrary), even if it could be convenient.
Once you are adding new functions at runtime of *arbitrary* signatures, `libffi` or an equivalent mechanism is absolutely needed (because even the set of called signatures could grow). |
26,575,303 | Hello people I hope you an help me out with this problem:
I am currently implementing an interpreter for a scripting language. The language needs a native call interface to C functions, like java has JNI. My problem is, that i want to call the original C functions without writing a wrapper function, which converts the call stack of my scripting language into the C call stack. This means, that I need a way, to generate argument lists of C functions at runtime. Example:
```
void a(int a, int b) {
printf("function a called %d", a + b);
}
void b(double a, int b, double c) {
printf("function b called %f", a * b + c);
}
interpreter.registerNativeFunction("a", a);
interpreter.registerNativeFunction("b", b);
```
The interpreter should be able to call the functions, with only knowing the function prototypes of my scripting language: `native void a(int a, int b);` and `native void b(double a, int b, double c);`
Is there any way to generate a C function call stack in C++, or do I have to use assembler for this task. Assembler is a problem, because the interpreter should run on almost any platform.
Edit:
The solution is to use libffi, a library, which handles the call stack creation for many different platforms and operating systems. libffi is also used by some prominent language implementations like cpython and openjdk.
Edit:
@MatsPetersson Somewhere in my code I have a method like:
```
void CInterpreter::CallNativeFunction(string name, vector<IValue> arguments, IReturnReference ret) {
// Call here correct native C function.
// this.nativeFunctions is a map which contains the function pointers.
}
```
**Edit:
Thanks for all your help! I will stay with libffi, and test it on all required platforms.** | 2014/10/26 | [
"https://Stackoverflow.com/questions/26575303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180673/"
] | Yes we can. No FFI library needed, no restriction to C calls, only pure C++11.
```
#include <iostream>
#include <list>
#include <iostream>
#include <boost/any.hpp>
template <typename T>
auto fetch_back(T& t) -> typename std::remove_reference<decltype(t.back())>::type
{
typename std::remove_reference<decltype(t.back())>::type ret = t.back();
t.pop_back();
return ret;
}
template <typename X>
struct any_ref_cast
{
X do_cast(boost::any y)
{
return boost::any_cast<X>(y);
}
};
template <typename X>
struct any_ref_cast<X&>
{
X& do_cast(boost::any y)
{
std::reference_wrapper<X> ref = boost::any_cast<std::reference_wrapper<X>>(y);
return ref.get();
}
};
template <typename X>
struct any_ref_cast<const X&>
{
const X& do_cast(boost::any y)
{
std::reference_wrapper<const X> ref = boost::any_cast<std::reference_wrapper<const X>>(y);
return ref.get();
}
};
template <typename Ret, typename...Arg>
Ret call (Ret (*func)(Arg...), std::list<boost::any> args)
{
if (sizeof...(Arg) != args.size())
throw "Argument number mismatch!";
return func(any_ref_cast<Arg>().do_cast(fetch_back(args))...);
}
int foo(int x, double y, const std::string& z, std::string& w)
{
std::cout << "foo called : " << x << " " << y << " " << z << " " << w << std::endl;
return 42;
}
```
Test drive:
```
int main ()
{
std::list<boost::any> args;
args.push_back(1);
args.push_back(4.56);
const std::string yyy("abc");
std::string zzz("123");
args.push_back(std::cref(yyy));
args.push_back(std::ref(zzz));
call(foo, args);
}
```
Exercise for the reader: implement `registerNativeFunction` in three easy steps.
1. Create an abstract base class with a pure `call` method that accepts a list of `boost::any`, call it `AbstractFunction`
2. Create a variadic class template that inherits `AbstractFunction` and adds a pointer to a concrete-type function (or `std::function`). Implement `call` in terms of that function.
3. Create an `map<string, AbstractFunction*>` (use smart pointers actually).
Drawback: totally cannot call variadic C-style functions (e.g. printf and friends) with this method. There is also no support for implicit argument conversions. If you pass an `int` to a function that requires a `double`, it will throw an exception (which is slightly better than a core dump you can get with a dynamic solution). It is possible to partially solve this for a finite fixed set of conversions by specializing `any_ref_cast`. | Many ways to do this.
1. Use boost (see first answer)
2. Use std::bind. Similar to boost but more simple
3. Use C function pointer.
example
```
#define DYNAMIC(p,arg,n) {\
if(0==n) ((void (*)())p)();\
else if(1==n) ((void (*)(int))p)(arg[0]);\
else if(2==n) ((void (*)(int, int))p)(arg[0], arg[1]);\
else if(3==n) ((void (*)(int, int, int))p)(arg[0], arg[1], arg[2]);\
}
void fun0()
{
printf("no arg \n");
}
void fun1(int a)
{
printf("arg %x\n", a);
}
void fun2(int a, const char *b)
{
printf("arg %x %s \n", a,b);
}
void fun3(int a,const char *b, int c)
{
printf("arg %x %s %x\n", a, b, c);
}
int a = 0xabcd;
const char* b = "test dynamic function";
int c = 0xcdef;
int d[] = { 1,(int)b,c) };
DYNAMIC(fun0, d, 0);
DYNAMIC(fun1, d, 1);
DYNAMIC(fun2, d, 2);
DYNAMIC(fun3, d, 3);
```
4. Even use some asm code more flexible:
```
void call(void* p, uint32_t arg[], int n)
{
for (int i = n-1; i >-1; --i)
{
uint32_t u = arg[i];
__asm push u
}
__asm call p
int n2 = n * 4;
__asm add esp,n2
}
int a = 0xabcd;
const char* b = "test dynamic function";
int c = 0xcdef;
int d[] = { 1,(int)b,c) };
call(fun3, d, 3);
``` |
36,655,197 | i have problem running Django server in Intellij / Pycharm (I tried in both).
There is that red cross:
[](https://i.stack.imgur.com/ssyv5.jpg)
And this is the error i get:
[](https://i.stack.imgur.com/q389E.jpg)
I have Python 2.7.10 and Django (via pip) installed on my computer.
I've tried reinstalling both python and Django, but it didn't help.
I've specified project sdk (Python).
**Edit:**
This is what it looks like in "Project Interpreter" page.
[](https://i.stack.imgur.com/XSaW7.png)
and Django configuration:
[](https://i.stack.imgur.com/05VCH.png) | 2016/04/15 | [
"https://Stackoverflow.com/questions/36655197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3671716/"
] | If your IntelliJ is up to date, there is another solution.
I had the exact same problem in **IntelliJ 2017.2** and it was driving me crazy until I read this [post from a IntelliJ maintainer](https://intellij-support.jetbrains.com/hc/en-us/community/posts/206936385-Intellij-Doesn-t-Recognize-Django-project).
If you use IntelliJ Idea and "Load an existing project", it will model it as a Java project with a Python modules attached. You cannot get Django loaded, no matter what you do.
I handled this by purging the `.idea` directory, and **created a new Django project**, with the pre-existing Django directory as the base directory in IntelliJ. I can now see Django in the project structure > project settings > module part of Intellij, and I can select the django settings file.
Step by step in pictures
------------------------
1. Delete `.idea` folder
2. Create new project
[](https://i.stack.imgur.com/KDONQ.png)
3. Select Python > Django
[](https://i.stack.imgur.com/Uat8o.png)
4. Hit next
[](https://i.stack.imgur.com/FKB8L.png)
5. Select existing django project path (or start from scratch with a new folder)
[](https://i.stack.imgur.com/PhYIg.png)
6. Add `DJANGO_SETTINGS_MODULE=yourprojectname.settings` to your run configuration (can be found in `yourprojectname/wsgi.py` file).
[](https://i.stack.imgur.com/JF0jT.png)
[](https://i.stack.imgur.com/hOuFT.png)
Enjoy your Django development | Try adding `DJANGO_SETTINGS_MODULE=untitled.settings` to the environment variables listed in the configuration menu by clicking the dropdown titled 'Django' in your first photo. |
36,655,197 | i have problem running Django server in Intellij / Pycharm (I tried in both).
There is that red cross:
[](https://i.stack.imgur.com/ssyv5.jpg)
And this is the error i get:
[](https://i.stack.imgur.com/q389E.jpg)
I have Python 2.7.10 and Django (via pip) installed on my computer.
I've tried reinstalling both python and Django, but it didn't help.
I've specified project sdk (Python).
**Edit:**
This is what it looks like in "Project Interpreter" page.
[](https://i.stack.imgur.com/XSaW7.png)
and Django configuration:
[](https://i.stack.imgur.com/05VCH.png) | 2016/04/15 | [
"https://Stackoverflow.com/questions/36655197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3671716/"
] | Try adding `DJANGO_SETTINGS_MODULE=untitled.settings` to the environment variables listed in the configuration menu by clicking the dropdown titled 'Django' in your first photo. | Problem Analysis in IntelliJ
----------------------------
The problem is whenever you import a python project in IntelliJ. It will load as java project and adjust itself into python language without changing the project type to python. So, IntelliJ thinks you are in java project even you are running python code in it and that's the reason you are not allowed to switch to Django or any other python framework.
Here is the fix for that:
-------------------------
find the `.iml` the file inside of `.idea` folder or just inside of `your project folder` and change module type from `JAVA_MODULE` to `PYTHON_MODULE` inside of `.iml` file
Close the project and re-open your project and it will prompt you to configure your project as a Django project or whatever python framework you are using.
You also need to configure the framework inside of `project_structure>module>(Your Framework)`
For `PyCharm` user make sure you have added the framework support to your imported project. |
36,655,197 | i have problem running Django server in Intellij / Pycharm (I tried in both).
There is that red cross:
[](https://i.stack.imgur.com/ssyv5.jpg)
And this is the error i get:
[](https://i.stack.imgur.com/q389E.jpg)
I have Python 2.7.10 and Django (via pip) installed on my computer.
I've tried reinstalling both python and Django, but it didn't help.
I've specified project sdk (Python).
**Edit:**
This is what it looks like in "Project Interpreter" page.
[](https://i.stack.imgur.com/XSaW7.png)
and Django configuration:
[](https://i.stack.imgur.com/05VCH.png) | 2016/04/15 | [
"https://Stackoverflow.com/questions/36655197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3671716/"
] | If your IntelliJ is up to date, there is another solution.
I had the exact same problem in **IntelliJ 2017.2** and it was driving me crazy until I read this [post from a IntelliJ maintainer](https://intellij-support.jetbrains.com/hc/en-us/community/posts/206936385-Intellij-Doesn-t-Recognize-Django-project).
If you use IntelliJ Idea and "Load an existing project", it will model it as a Java project with a Python modules attached. You cannot get Django loaded, no matter what you do.
I handled this by purging the `.idea` directory, and **created a new Django project**, with the pre-existing Django directory as the base directory in IntelliJ. I can now see Django in the project structure > project settings > module part of Intellij, and I can select the django settings file.
Step by step in pictures
------------------------
1. Delete `.idea` folder
2. Create new project
[](https://i.stack.imgur.com/KDONQ.png)
3. Select Python > Django
[](https://i.stack.imgur.com/Uat8o.png)
4. Hit next
[](https://i.stack.imgur.com/FKB8L.png)
5. Select existing django project path (or start from scratch with a new folder)
[](https://i.stack.imgur.com/PhYIg.png)
6. Add `DJANGO_SETTINGS_MODULE=yourprojectname.settings` to your run configuration (can be found in `yourprojectname/wsgi.py` file).
[](https://i.stack.imgur.com/JF0jT.png)
[](https://i.stack.imgur.com/hOuFT.png)
Enjoy your Django development | Problem Analysis in IntelliJ
----------------------------
The problem is whenever you import a python project in IntelliJ. It will load as java project and adjust itself into python language without changing the project type to python. So, IntelliJ thinks you are in java project even you are running python code in it and that's the reason you are not allowed to switch to Django or any other python framework.
Here is the fix for that:
-------------------------
find the `.iml` the file inside of `.idea` folder or just inside of `your project folder` and change module type from `JAVA_MODULE` to `PYTHON_MODULE` inside of `.iml` file
Close the project and re-open your project and it will prompt you to configure your project as a Django project or whatever python framework you are using.
You also need to configure the framework inside of `project_structure>module>(Your Framework)`
For `PyCharm` user make sure you have added the framework support to your imported project. |
63,412,757 | I am training a variational autoencoder, using pytorch-lightning. My pytorch-lightning code works with a Weights and Biases logger. I am trying to do a parameter sweep using a W&B parameter sweep.
The hyperparameter search procedure is based on what I followed from [this repo.](https://github.com/borisdayma/lightning-kitti)
The runs initialise correctly, but when my training script is run with the first set of hyperparameters, i get the following error:
```
2020-08-14 14:09:07,109 - wandb.wandb_agent - INFO - About to run command: /usr/bin/env python train_sweep.py --LR=0.02537477586974176
Traceback (most recent call last):
File "train_sweep.py", line 1, in <module>
import yaml
ImportError: No module named yaml
```
`yaml` is installed and is working correctly. I can train the network by setting the parameters manually, but not with the parameter sweep.
Here is my sweep script to train the VAE:
```
import yaml
import numpy as np
import ipdb
import torch
from vae_experiment import VAEXperiment
import torch.backends.cudnn as cudnn
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import EarlyStopping
from vae_network import VanillaVAE
import os
import wandb
from utils import get_config, log_to_wandb
# Sweep parameters
hyperparameter_defaults = dict(
root='data_semantics',
gpus=1,
batch_size = 2,
lr = 1e-3,
num_layers = 5,
features_start = 64,
bilinear = False,
grad_batches = 1,
epochs = 20
)
wandb.init(config=hyperparameter_defaults)
config = wandb.config
def main(hparams):
model = VanillaVAE(hparams['exp_params']['img_size'], **hparams['model_params'])
model.build_layers()
experiment = VAEXperiment(model, hparams['exp_params'], hparams['parameters'])
logger = WandbLogger(
project='vae',
name=config['logging_params']['name'],
version=config['logging_params']['version'],
save_dir=config['logging_params']['save_dir']
)
wandb_logger.watch(model.net)
early_stopping = EarlyStopping(
monitor='val_loss',
min_delta=0.00,
patience=3,
verbose=False,
mode='min'
)
runner = Trainer(weights_save_path="../../Logs/",
min_epochs=1,
logger=logger,
log_save_interval=10,
train_percent_check=1.,
val_percent_check=1.,
num_sanity_val_steps=5,
early_stop_callback = early_stopping,
**config['trainer_params']
)
runner.fit(experiment)
if __name__ == '__main__':
main(config)
```
Why am I getting this error? | 2020/08/14 | [
"https://Stackoverflow.com/questions/63412757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10290585/"
] | The problem is that the structure of my code and the way that I was running the wandb commands was not in the correct order. Looking at [this pytorch-ligthning](https://github.com/AyushExel/COVID19WB/blob/master/main.ipynb) with `wandb` is the correct structure to follow.
Here is my refactored code:
```
#!/usr/bin/env python
import wandb
from utils import get_config
#---------------------------------------------------------------------------------------------
def main():
"""
The training function used in each sweep of the model.
For every sweep, this function will be executed as if it is a script on its own.
"""
import wandb
import yaml
import numpy as np
import torch
from vae_experiment import VAEXperiment
import torch.backends.cudnn as cudnn
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import EarlyStopping
from vae_network import VanillaVAE
import os
from utils import log_to_wandb, format_config
path_to_config = 'sweep.yaml'
config = get_config(path_to_yaml)
path_to_defaults = 'defaults.yaml'
param_defaults = get_config(path_to_defaults)
wandb.init(config=param_defaults)
config = format_config(config, wandb.config)
model = VanillaVAE(config['meta']['img_size'], hidden_dims = config['hidden_dims'], latent_dim = config['latent_dim'])
model.build_layers()
experiment = VAEXperiment(model, config)
early_stopping = EarlyStopping(
monitor='val_loss',
min_delta=0.00,
patience=3,
verbose=False,
mode='max'
)
runner = Trainer(weights_save_path=config['meta']['save_dir'],
min_epochs=1,
train_percent_check=1.,
val_percent_check=1.,
num_sanity_val_steps=5,
early_stop_callback = early_stopping,
**config['trainer_params'])
runner.fit(experiment)
log_to_wandb(config, runner, experiment, path_to_config)
#---------------------------------------------------------------------------------------------
path_to_yaml = 'sweep.yaml'
sweep_config = get_config(path_to_yaml)
sweep_id = wandb.sweep(sweep_config)
wandb.agent(sweep_id, function=main)
#---------------------------------------------------------------------------------------------
``` | Do you launch python in your shell by typing `python` or `python3`?
Your script could be calling python 2 instead of python 3.
If this is the case, you can explicitly tell wandb to use python 3. See [this section of documentation](https://docs.wandb.com/sweeps/faq#sweep-with-custom-commands), in particular "Running Sweeps with Python 3". |
44,737,199 | I've written a script to select certain field from a webpage using python with selenium. There is a dropdown on that page from which I want to select "All". However, i tried many different ways with my script to make it but could not.
Here is how the dropdown look like.
[](https://i.stack.imgur.com/WeO1N.jpg)
Html elements for the dropdown selection:
```
<select name="ctl00$body$MedicineSummaryControl$cmbPageSelection" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$MedicineSummaryControl$cmbPageSelection\',\'\')', 0)" id="ctl00_body_MedicineSummaryControl_cmbPageSelection">
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="all">All</option>
</select>
```
Scripts I've tried with:
```
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pump')
time.sleep(8)
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()
time.sleep(7)
#selection for the dropdown should start from here
driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').click()
driver.find_element_by_xpath('//select//option[@value]').send_keys("All")
``` | 2017/06/24 | [
"https://Stackoverflow.com/questions/44737199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | This will work for you:
```
#option1
select_obj = Select(driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]'))
select_obj.select_by_visible_text('All')
#option2
select_obj = Select(driver.find_element_by_id('ctl00_body_MedicineSummaryControl_cmbPageSelection'))
select_obj.select_by_visible_text('All')
```
And don't forget to import `Select` with `from selenium.webdriver.support.ui import Select`
You can read full documentation to find all `Select` methods here : <https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.select.html> | I initially thought of suggesting that you try to tab from an element that is before the dropdown select, similar to the concept in this code:
```
driver.find_element_by_id('<id of element before the dropdown select>').send_keys(Keys.TAB)
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').send_keys('AL')
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').send_keys(Keys.ENTER + Keys.TAB)
```
However, errors from the stack trace may show you that the dropdown select is not being found with that id. I believe that you should verify that the id that you are using is the correct id for that element, when you record the action of clicking on the dropdown select and selecting an option, by using the Record option in the Selenium IDE. |
44,737,199 | I've written a script to select certain field from a webpage using python with selenium. There is a dropdown on that page from which I want to select "All". However, i tried many different ways with my script to make it but could not.
Here is how the dropdown look like.
[](https://i.stack.imgur.com/WeO1N.jpg)
Html elements for the dropdown selection:
```
<select name="ctl00$body$MedicineSummaryControl$cmbPageSelection" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$MedicineSummaryControl$cmbPageSelection\',\'\')', 0)" id="ctl00_body_MedicineSummaryControl_cmbPageSelection">
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="all">All</option>
</select>
```
Scripts I've tried with:
```
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pump')
time.sleep(8)
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()
time.sleep(7)
#selection for the dropdown should start from here
driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').click()
driver.find_element_by_xpath('//select//option[@value]').send_keys("All")
``` | 2017/06/24 | [
"https://Stackoverflow.com/questions/44737199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | This will work for you:
```
#option1
select_obj = Select(driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]'))
select_obj.select_by_visible_text('All')
#option2
select_obj = Select(driver.find_element_by_id('ctl00_body_MedicineSummaryControl_cmbPageSelection'))
select_obj.select_by_visible_text('All')
```
And don't forget to import `Select` with `from selenium.webdriver.support.ui import Select`
You can read full documentation to find all `Select` methods here : <https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.select.html> | Found the workaround finally. Here is what I did:
```
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pump')
time.sleep(8)
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()
time.sleep(7)
driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').click()
driver.find_element_by_xpath('.//option[@value="all"]').click()
time.sleep(10)
``` |
44,737,199 | I've written a script to select certain field from a webpage using python with selenium. There is a dropdown on that page from which I want to select "All". However, i tried many different ways with my script to make it but could not.
Here is how the dropdown look like.
[](https://i.stack.imgur.com/WeO1N.jpg)
Html elements for the dropdown selection:
```
<select name="ctl00$body$MedicineSummaryControl$cmbPageSelection" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$MedicineSummaryControl$cmbPageSelection\',\'\')', 0)" id="ctl00_body_MedicineSummaryControl_cmbPageSelection">
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="all">All</option>
</select>
```
Scripts I've tried with:
```
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pump')
time.sleep(8)
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()
time.sleep(7)
#selection for the dropdown should start from here
driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').click()
driver.find_element_by_xpath('//select//option[@value]').send_keys("All")
``` | 2017/06/24 | [
"https://Stackoverflow.com/questions/44737199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | Found the workaround finally. Here is what I did:
```
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pump')
time.sleep(8)
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()
time.sleep(7)
driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').click()
driver.find_element_by_xpath('.//option[@value="all"]').click()
time.sleep(10)
``` | I initially thought of suggesting that you try to tab from an element that is before the dropdown select, similar to the concept in this code:
```
driver.find_element_by_id('<id of element before the dropdown select>').send_keys(Keys.TAB)
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').send_keys('AL')
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').send_keys(Keys.ENTER + Keys.TAB)
```
However, errors from the stack trace may show you that the dropdown select is not being found with that id. I believe that you should verify that the id that you are using is the correct id for that element, when you record the action of clicking on the dropdown select and selecting an option, by using the Record option in the Selenium IDE. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
[](https://i.stack.imgur.com/yN8ez.gif)
(source: [kb-creative.net](http://www.kb-creative.net/screenshots/ipats-multifile.gif)) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.com/library/tkinter/introduction/) particular one is where I learned it from and it has been quite infallible in serving me. | As a step up to other GUI toolkits, sure. If you know other toolkits then you already understand TkInter and can leave it until you actually need it. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
[](https://i.stack.imgur.com/yN8ez.gif)
(source: [kb-creative.net](http://www.kb-creative.net/screenshots/ipats-multifile.gif)) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | As a step up to other GUI toolkits, sure. If you know other toolkits then you already understand TkInter and can leave it until you actually need it. | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
[](https://i.stack.imgur.com/yN8ez.gif)
(source: [kb-creative.net](http://www.kb-creative.net/screenshots/ipats-multifile.gif)) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.com/library/tkinter/introduction/) particular one is where I learned it from and it has been quite infallible in serving me. | You might want to take a look at [this(wxPython)](http://www.wxpython.org/quotes.php).
>
> wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first.
> -- Guido van Rossum
>
>
> |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
[](https://i.stack.imgur.com/yN8ez.gif)
(source: [kb-creative.net](http://www.kb-creative.net/screenshots/ipats-multifile.gif)) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.com/library/tkinter/introduction/) particular one is where I learned it from and it has been quite infallible in serving me. | Why not go for [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? You apparently are already familiar with Qt, so it should be relatively easy to learn. In my opinion it looks better than Tkinter, and it sure is better documented. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
[](https://i.stack.imgur.com/yN8ez.gif)
(source: [kb-creative.net](http://www.kb-creative.net/screenshots/ipats-multifile.gif)) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.com/library/tkinter/introduction/) particular one is where I learned it from and it has been quite infallible in serving me. | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
[](https://i.stack.imgur.com/yN8ez.gif)
(source: [kb-creative.net](http://www.kb-creative.net/screenshots/ipats-multifile.gif)) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | You might want to take a look at [this(wxPython)](http://www.wxpython.org/quotes.php).
>
> wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first.
> -- Guido van Rossum
>
>
> | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I stick with Qt?
[](https://i.stack.imgur.com/yN8ez.gif)
(source: [kb-creative.net](http://www.kb-creative.net/screenshots/ipats-multifile.gif)) | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | Why not go for [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? You apparently are already familiar with Qt, so it should be relatively easy to learn. In my opinion it looks better than Tkinter, and it sure is better documented. | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
60,144,779 | My formatting is terrible. Screenshot is here:
[](https://i.stack.imgur.com/KrTnL.png)
```py
n = int(input("enter the number of Fibonacci sequence you want. ")
n1 = 0
n2 = 1
count = 0
if n <= 0:
print("please enter a postive integer")
elif n == 1:
print("Fibonacci sequence:")
print(n1)
else:
while count < n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count = count + 1
```
I cannot figure out why do I get this error:
```
File "<ipython-input-68-9c2ad055a726>", line 3
n1 = 0
^
SyntaxError: invalid syntax
``` | 2020/02/10 | [
"https://Stackoverflow.com/questions/60144779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870387/"
] | A ')' is missing in first line i guess, that's an issue. | When such error arises, do check for the preceding line also. There are very high chances of error being in the preceding line, as in this case. There's a `)` missing in the input line. You closed 1 `)` for the input() function, but did not close for `int` constructor. |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.add_argument("profile-directory=Profile 1")
edge_options.binary_location = r"C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe"
driver = Edge(options = edge_options, executable_path = "C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe")
driver.get('https://google.com')
driver.quit()
```
but i am getting this error:
>
> PS C:\Users\PopA2> & "C:/Program Files/Python37/python.exe"
> "c:/Users/PopA2/OneDrive/Desktop/test de pe net.py" Traceback (most
> recent call last): File "c:/Users/PopA2/OneDrive
> Group/Desktop/test de pe net.py", line 13, in
> driver = Edge(options = edge\_options, executable\_path = "C:\Users\PopA2\Downloads\edgedriver\_win64 (1)\msedgedriver.exe")
> File "C:\Program
> Files\Python37\lib\site-packages\msedge\selenium\_tools\webdriver.py",
> line 108, in **init**
> desired\_capabilities=desired\_capabilities) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 157, in **init**
> self.start\_session(capabilities, browser\_profile) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 252, in start\_session
> response = self.execute(Command.NEW\_SESSION, parameters) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 321, in execute
> self.error\_handler.check\_response(response) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
> line 242, in check\_response
> raise exception\_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error:
> MSEdge failed to start: was killed. (unknown error:
> DevToolsActivePort file doesn't exist) (The process started from
> msedge location C:\Users\PopA2\Downloads\edgedriver\_win64
> (1)\msedgedriver.exe is no longer running, so MSEdgeDriver is
> assuming that MSEdge has crashed.)
>
>
> | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | there is an issue in your style code.if you remove it than works smoothly
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: false,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` | for navigation design add these style to your code
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<style>
.row{
margin-left:0px;
margin-right:0px;
}
.responsive-slider {
padding:1em 0;
}
.slick-prev{
left:0px;
}
.slick-next{
right:0px;
}
.slick-prev, .slick-next{
font-size:0;
top: 35%;
z-index: 1;
}
.slick-prev:before, .slick-next:before{
color: #104975;
font-size: 32px;
opacity: 9;
}
.slick-dots li button:before{
font-size: 15px;
opacity: 9;
color: #0d4775;
}
</style>
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.add_argument("profile-directory=Profile 1")
edge_options.binary_location = r"C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe"
driver = Edge(options = edge_options, executable_path = "C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe")
driver.get('https://google.com')
driver.quit()
```
but i am getting this error:
>
> PS C:\Users\PopA2> & "C:/Program Files/Python37/python.exe"
> "c:/Users/PopA2/OneDrive/Desktop/test de pe net.py" Traceback (most
> recent call last): File "c:/Users/PopA2/OneDrive
> Group/Desktop/test de pe net.py", line 13, in
> driver = Edge(options = edge\_options, executable\_path = "C:\Users\PopA2\Downloads\edgedriver\_win64 (1)\msedgedriver.exe")
> File "C:\Program
> Files\Python37\lib\site-packages\msedge\selenium\_tools\webdriver.py",
> line 108, in **init**
> desired\_capabilities=desired\_capabilities) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 157, in **init**
> self.start\_session(capabilities, browser\_profile) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 252, in start\_session
> response = self.execute(Command.NEW\_SESSION, parameters) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 321, in execute
> self.error\_handler.check\_response(response) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
> line 242, in check\_response
> raise exception\_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error:
> MSEdge failed to start: was killed. (unknown error:
> DevToolsActivePort file doesn't exist) (The process started from
> msedge location C:\Users\PopA2\Downloads\edgedriver\_win64
> (1)\msedgedriver.exe is no longer running, so MSEdgeDriver is
> assuming that MSEdge has crashed.)
>
>
> | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | there is an issue in your style code.if you remove it than works smoothly
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: false,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` | ```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<style>
.row{
margin-left:0px;
margin-right:0px;
}
.responsive-slider {
padding:1em 0;
}
.slick-prev{
left:42%;
}
.slick-next{
right:42%;
}
.slick-prev, .slick-next{
font-size:0;
z-index: 1;
top: auto !important;
bottom: -30px;
}
.slick-prev:before, .slick-next:before{
color: #104975;
font-size: 32px;
opacity: 9;
}
.slick-dots li button:before{
font-size: 15px;
opacity: 9;
color: #0d4775;
}
</style>
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.add_argument("profile-directory=Profile 1")
edge_options.binary_location = r"C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe"
driver = Edge(options = edge_options, executable_path = "C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe")
driver.get('https://google.com')
driver.quit()
```
but i am getting this error:
>
> PS C:\Users\PopA2> & "C:/Program Files/Python37/python.exe"
> "c:/Users/PopA2/OneDrive/Desktop/test de pe net.py" Traceback (most
> recent call last): File "c:/Users/PopA2/OneDrive
> Group/Desktop/test de pe net.py", line 13, in
> driver = Edge(options = edge\_options, executable\_path = "C:\Users\PopA2\Downloads\edgedriver\_win64 (1)\msedgedriver.exe")
> File "C:\Program
> Files\Python37\lib\site-packages\msedge\selenium\_tools\webdriver.py",
> line 108, in **init**
> desired\_capabilities=desired\_capabilities) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 157, in **init**
> self.start\_session(capabilities, browser\_profile) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 252, in start\_session
> response = self.execute(Command.NEW\_SESSION, parameters) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 321, in execute
> self.error\_handler.check\_response(response) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
> line 242, in check\_response
> raise exception\_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error:
> MSEdge failed to start: was killed. (unknown error:
> DevToolsActivePort file doesn't exist) (The process started from
> msedge location C:\Users\PopA2\Downloads\edgedriver\_win64
> (1)\msedgedriver.exe is no longer running, so MSEdgeDriver is
> assuming that MSEdge has crashed.)
>
>
> | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | there is an issue in your style code.if you remove it than works smoothly
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: false,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` | I want to answer simply to this question:
remove margin between slides and if you want to space between them use padding instead.
In most of the cases that we use card-like components in our front-end codes, do not use margin. |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.add_argument("profile-directory=Profile 1")
edge_options.binary_location = r"C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe"
driver = Edge(options = edge_options, executable_path = "C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe")
driver.get('https://google.com')
driver.quit()
```
but i am getting this error:
>
> PS C:\Users\PopA2> & "C:/Program Files/Python37/python.exe"
> "c:/Users/PopA2/OneDrive/Desktop/test de pe net.py" Traceback (most
> recent call last): File "c:/Users/PopA2/OneDrive
> Group/Desktop/test de pe net.py", line 13, in
> driver = Edge(options = edge\_options, executable\_path = "C:\Users\PopA2\Downloads\edgedriver\_win64 (1)\msedgedriver.exe")
> File "C:\Program
> Files\Python37\lib\site-packages\msedge\selenium\_tools\webdriver.py",
> line 108, in **init**
> desired\_capabilities=desired\_capabilities) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 157, in **init**
> self.start\_session(capabilities, browser\_profile) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 252, in start\_session
> response = self.execute(Command.NEW\_SESSION, parameters) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 321, in execute
> self.error\_handler.check\_response(response) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
> line 242, in check\_response
> raise exception\_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error:
> MSEdge failed to start: was killed. (unknown error:
> DevToolsActivePort file doesn't exist) (The process started from
> msedge location C:\Users\PopA2\Downloads\edgedriver\_win64
> (1)\msedgedriver.exe is no longer running, so MSEdgeDriver is
> assuming that MSEdge has crashed.)
>
>
> | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | ```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<style>
.row{
margin-left:0px;
margin-right:0px;
}
.responsive-slider {
padding:1em 0;
}
.slick-prev{
left:42%;
}
.slick-next{
right:42%;
}
.slick-prev, .slick-next{
font-size:0;
z-index: 1;
top: auto !important;
bottom: -30px;
}
.slick-prev:before, .slick-next:before{
color: #104975;
font-size: 32px;
opacity: 9;
}
.slick-dots li button:before{
font-size: 15px;
opacity: 9;
color: #0d4775;
}
</style>
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` | for navigation design add these style to your code
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<style>
.row{
margin-left:0px;
margin-right:0px;
}
.responsive-slider {
padding:1em 0;
}
.slick-prev{
left:0px;
}
.slick-next{
right:0px;
}
.slick-prev, .slick-next{
font-size:0;
top: 35%;
z-index: 1;
}
.slick-prev:before, .slick-next:before{
color: #104975;
font-size: 32px;
opacity: 9;
}
.slick-dots li button:before{
font-size: 15px;
opacity: 9;
color: #0d4775;
}
</style>
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.add_argument("profile-directory=Profile 1")
edge_options.binary_location = r"C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe"
driver = Edge(options = edge_options, executable_path = "C:\\Users\\PopA2\\Downloads\\edgedriver_win64 (1)\\msedgedriver.exe")
driver.get('https://google.com')
driver.quit()
```
but i am getting this error:
>
> PS C:\Users\PopA2> & "C:/Program Files/Python37/python.exe"
> "c:/Users/PopA2/OneDrive/Desktop/test de pe net.py" Traceback (most
> recent call last): File "c:/Users/PopA2/OneDrive
> Group/Desktop/test de pe net.py", line 13, in
> driver = Edge(options = edge\_options, executable\_path = "C:\Users\PopA2\Downloads\edgedriver\_win64 (1)\msedgedriver.exe")
> File "C:\Program
> Files\Python37\lib\site-packages\msedge\selenium\_tools\webdriver.py",
> line 108, in **init**
> desired\_capabilities=desired\_capabilities) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 157, in **init**
> self.start\_session(capabilities, browser\_profile) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 252, in start\_session
> response = self.execute(Command.NEW\_SESSION, parameters) File "C:\Program
> Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py",
> line 321, in execute
> self.error\_handler.check\_response(response) File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py",
> line 242, in check\_response
> raise exception\_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error:
> MSEdge failed to start: was killed. (unknown error:
> DevToolsActivePort file doesn't exist) (The process started from
> msedge location C:\Users\PopA2\Downloads\edgedriver\_win64
> (1)\msedgedriver.exe is no longer running, so MSEdgeDriver is
> assuming that MSEdge has crashed.)
>
>
> | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | ```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<style>
.row{
margin-left:0px;
margin-right:0px;
}
.responsive-slider {
padding:1em 0;
}
.slick-prev{
left:42%;
}
.slick-next{
right:42%;
}
.slick-prev, .slick-next{
font-size:0;
z-index: 1;
top: auto !important;
bottom: -30px;
}
.slick-prev:before, .slick-next:before{
color: #104975;
font-size: 32px;
opacity: 9;
}
.slick-dots li button:before{
font-size: 15px;
opacity: 9;
color: #0d4775;
}
</style>
</head>
<body>
<div class="carousel-equal-heights">
<!--Responsive Slider-->
<div class="row">
<div class="col-md-12">
<div class="responsive-slider">
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 1</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="2">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg" alt="#">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 2</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="h#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4" id="3">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 3</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 4</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 5</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 6</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 7</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 8</h4>
<p class="card-text">This is a txt for testing</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card mb-2 shadow-none h-100" style="border: 1px solid #ededed;">
<img class="card-img-top"
src="https://mdbootstrap.com/img/Photos/Horizontal/Nature/4-col/img%20(18).jpg"
alt="Card image cap">
<div class="card-body d-flex flex-column">
<h4 class="card-title">Test 9</h4>
<p class="card-text">This is a txt for testing
</p>
<a href="#" class="btn btn-primary mt-auto align-self-start ml-0">Details</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Of Container-->
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<script>
$(document).ready(function () {
//Responsive slider
$('.responsive-slider').slick({
dots: true,
arrows: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 3,
autoplay: true,
autoplaySpeed: 2000, //DELAY BEFORE NEXT SLIDE IN MILISECONDS
speed: 800,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
let $carouselItems = $('.carousel-equal-heights').find('.col-md-4');
updateItemsHeight();
$(window).resize(updateItemsHeight);
function updateItemsHeight() {
// remove old value
$carouselItems.height('auto');
// calculate new one
let maxHeight = 0;
$carouselItems.each(function () {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
// set new value
$carouselItems.each(function () {
$(this).outerHeight(maxHeight);
});
// debug it
console.log('new items height', maxHeight);
}
});
</script>
</body>
</html>
``` | I want to answer simply to this question:
remove margin between slides and if you want to space between them use padding instead.
In most of the cases that we use card-like components in our front-end codes, do not use margin. |
30,078,967 | I want to create new form view associated to new data model, I create a new menu item "menu1" that has a submenu "menus" and then, I want to customize the action view. This is my code:
**My xml file:**
**My data model:**
```python
from openerp.osv import fields, osv
class hr_cutomization(osv.osv):
_inherit = "hr.employee"
_columns = {
'new_field_ID': fields.char('new filed ID',size=11)
}
_default={
'new_field_ID':0
}
hr_cutomization()
class hr_newmodel(osv.osv):
_name = "hr.newmodel"
_columns = {
'field1': fields.char('new filed1',size=11),
'field2': fields.char('new filed2',size=11)
}
_default={
'field1':0
}
hr_newmodel()
```
When I update my module, I got this error:
>
> ParseError: "ValidateError
> Field(s) `arch` failed against a constraint: Invalid view definition
> Error details:
> Element '
>
>
>
what's doing wrong in my code ? | 2015/05/06 | [
"https://Stackoverflow.com/questions/30078967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018649/"
] | Manage to sort it out with the following.
```
Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Origin';value='*'}
Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Headers';value='Content-Type'}
Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Methods';value='GET, OPTIONS'}
```
Hope this helps someone in future, wasted allot of time on this. | I think your XPath expression doesn't match the node you're trying to manipulate. Try this:
```
Add-WebConfigurationProperty -PSPath $sitePath `
-Filter 'system.webServer/httpProtocol/customHeaders/add[@name="Access-Control-Allow-Origin"]' `
-Name 'value' -Value '*' -Force
``` |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ['B', 'B1', 'B2', 'B3','B4','B5'],
'C': ['C', 'C1', 'C2', 'C3','C4','C5'],
'D': ['D', 'D1', 'D2', 'D3','D4','D5'],
'E': ['E', 'E1', 'E2', 'E3','E4','E5']},
index=[0, 1, 2, 3,4,5])
df1
>> B C D E User
0 B C D E user1
1 B1 C1 D1 E1 user1
2 B2 C2 D2 E2 user2
3 B3 C3 D3 E3 user3
4 B4 C4 D4 E4 user2
5 B5 C5 D5 E5 user3
userList = list(df1.User.unique())
userList
> ['user1', 'user2', 'user3']
```
The I loop over unique users list and sample one row per user, saving them to a different dataframe
```
usersSample = pd.DataFrame() # empty dataframe, to save samples
for i in userList:
usersSample=usersSample.append(df1[df1.User == i].sample(1))
> usersSample
B C D E User
0 B C D E user1
4 B4 C4 D4 E4 user2
3 B3 C3 D3 E3 user3
```
Is there a more efficient way of achieving that? I'd really like to:
1) avoid appending to dataframe usersSample. This is gradually growing object and it seriously kills performance.
And 2) avoid looping over users one at a time. Is there a way to sample 1-per-user more efficiently? | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | This is what you want:
```
df1.groupby('User').apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/C1B60.png)
Without the extra index:
```
df1.groupby('User', group_keys=False).apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/cLAWS.png) | ```
df1_user_sample_one = df1.groupby('User').apply(lambda x:x.sample(1))
```
Using DataFrame.groupby.apply and lambda function to sample 1 |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ['B', 'B1', 'B2', 'B3','B4','B5'],
'C': ['C', 'C1', 'C2', 'C3','C4','C5'],
'D': ['D', 'D1', 'D2', 'D3','D4','D5'],
'E': ['E', 'E1', 'E2', 'E3','E4','E5']},
index=[0, 1, 2, 3,4,5])
df1
>> B C D E User
0 B C D E user1
1 B1 C1 D1 E1 user1
2 B2 C2 D2 E2 user2
3 B3 C3 D3 E3 user3
4 B4 C4 D4 E4 user2
5 B5 C5 D5 E5 user3
userList = list(df1.User.unique())
userList
> ['user1', 'user2', 'user3']
```
The I loop over unique users list and sample one row per user, saving them to a different dataframe
```
usersSample = pd.DataFrame() # empty dataframe, to save samples
for i in userList:
usersSample=usersSample.append(df1[df1.User == i].sample(1))
> usersSample
B C D E User
0 B C D E user1
4 B4 C4 D4 E4 user2
3 B3 C3 D3 E3 user3
```
Is there a more efficient way of achieving that? I'd really like to:
1) avoid appending to dataframe usersSample. This is gradually growing object and it seriously kills performance.
And 2) avoid looping over users one at a time. Is there a way to sample 1-per-user more efficiently? | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | This is what you want:
```
df1.groupby('User').apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/C1B60.png)
Without the extra index:
```
df1.groupby('User', group_keys=False).apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/cLAWS.png) | Based on number of rows per user this might be faster:
```
df.sample(frac=1).drop_duplicates(['User'])
``` |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ['B', 'B1', 'B2', 'B3','B4','B5'],
'C': ['C', 'C1', 'C2', 'C3','C4','C5'],
'D': ['D', 'D1', 'D2', 'D3','D4','D5'],
'E': ['E', 'E1', 'E2', 'E3','E4','E5']},
index=[0, 1, 2, 3,4,5])
df1
>> B C D E User
0 B C D E user1
1 B1 C1 D1 E1 user1
2 B2 C2 D2 E2 user2
3 B3 C3 D3 E3 user3
4 B4 C4 D4 E4 user2
5 B5 C5 D5 E5 user3
userList = list(df1.User.unique())
userList
> ['user1', 'user2', 'user3']
```
The I loop over unique users list and sample one row per user, saving them to a different dataframe
```
usersSample = pd.DataFrame() # empty dataframe, to save samples
for i in userList:
usersSample=usersSample.append(df1[df1.User == i].sample(1))
> usersSample
B C D E User
0 B C D E user1
4 B4 C4 D4 E4 user2
3 B3 C3 D3 E3 user3
```
Is there a more efficient way of achieving that? I'd really like to:
1) avoid appending to dataframe usersSample. This is gradually growing object and it seriously kills performance.
And 2) avoid looping over users one at a time. Is there a way to sample 1-per-user more efficiently? | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | This is what you want:
```
df1.groupby('User').apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/C1B60.png)
Without the extra index:
```
df1.groupby('User', group_keys=False).apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/cLAWS.png) | `.drop_duplicates` should work just fine:
```
df1.drop_duplicates(subset='User')
```
This will keep each first occurrence of a value in the column 'User' and return the respective row. |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ['B', 'B1', 'B2', 'B3','B4','B5'],
'C': ['C', 'C1', 'C2', 'C3','C4','C5'],
'D': ['D', 'D1', 'D2', 'D3','D4','D5'],
'E': ['E', 'E1', 'E2', 'E3','E4','E5']},
index=[0, 1, 2, 3,4,5])
df1
>> B C D E User
0 B C D E user1
1 B1 C1 D1 E1 user1
2 B2 C2 D2 E2 user2
3 B3 C3 D3 E3 user3
4 B4 C4 D4 E4 user2
5 B5 C5 D5 E5 user3
userList = list(df1.User.unique())
userList
> ['user1', 'user2', 'user3']
```
The I loop over unique users list and sample one row per user, saving them to a different dataframe
```
usersSample = pd.DataFrame() # empty dataframe, to save samples
for i in userList:
usersSample=usersSample.append(df1[df1.User == i].sample(1))
> usersSample
B C D E User
0 B C D E user1
4 B4 C4 D4 E4 user2
3 B3 C3 D3 E3 user3
```
Is there a more efficient way of achieving that? I'd really like to:
1) avoid appending to dataframe usersSample. This is gradually growing object and it seriously kills performance.
And 2) avoid looping over users one at a time. Is there a way to sample 1-per-user more efficiently? | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | Based on number of rows per user this might be faster:
```
df.sample(frac=1).drop_duplicates(['User'])
``` | ```
df1_user_sample_one = df1.groupby('User').apply(lambda x:x.sample(1))
```
Using DataFrame.groupby.apply and lambda function to sample 1 |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ['B', 'B1', 'B2', 'B3','B4','B5'],
'C': ['C', 'C1', 'C2', 'C3','C4','C5'],
'D': ['D', 'D1', 'D2', 'D3','D4','D5'],
'E': ['E', 'E1', 'E2', 'E3','E4','E5']},
index=[0, 1, 2, 3,4,5])
df1
>> B C D E User
0 B C D E user1
1 B1 C1 D1 E1 user1
2 B2 C2 D2 E2 user2
3 B3 C3 D3 E3 user3
4 B4 C4 D4 E4 user2
5 B5 C5 D5 E5 user3
userList = list(df1.User.unique())
userList
> ['user1', 'user2', 'user3']
```
The I loop over unique users list and sample one row per user, saving them to a different dataframe
```
usersSample = pd.DataFrame() # empty dataframe, to save samples
for i in userList:
usersSample=usersSample.append(df1[df1.User == i].sample(1))
> usersSample
B C D E User
0 B C D E user1
4 B4 C4 D4 E4 user2
3 B3 C3 D3 E3 user3
```
Is there a more efficient way of achieving that? I'd really like to:
1) avoid appending to dataframe usersSample. This is gradually growing object and it seriously kills performance.
And 2) avoid looping over users one at a time. Is there a way to sample 1-per-user more efficiently? | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | ```
df1_user_sample_one = df1.groupby('User').apply(lambda x:x.sample(1))
```
Using DataFrame.groupby.apply and lambda function to sample 1 | `.drop_duplicates` should work just fine:
```
df1.drop_duplicates(subset='User')
```
This will keep each first occurrence of a value in the column 'User' and return the respective row. |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ['B', 'B1', 'B2', 'B3','B4','B5'],
'C': ['C', 'C1', 'C2', 'C3','C4','C5'],
'D': ['D', 'D1', 'D2', 'D3','D4','D5'],
'E': ['E', 'E1', 'E2', 'E3','E4','E5']},
index=[0, 1, 2, 3,4,5])
df1
>> B C D E User
0 B C D E user1
1 B1 C1 D1 E1 user1
2 B2 C2 D2 E2 user2
3 B3 C3 D3 E3 user3
4 B4 C4 D4 E4 user2
5 B5 C5 D5 E5 user3
userList = list(df1.User.unique())
userList
> ['user1', 'user2', 'user3']
```
The I loop over unique users list and sample one row per user, saving them to a different dataframe
```
usersSample = pd.DataFrame() # empty dataframe, to save samples
for i in userList:
usersSample=usersSample.append(df1[df1.User == i].sample(1))
> usersSample
B C D E User
0 B C D E user1
4 B4 C4 D4 E4 user2
3 B3 C3 D3 E3 user3
```
Is there a more efficient way of achieving that? I'd really like to:
1) avoid appending to dataframe usersSample. This is gradually growing object and it seriously kills performance.
And 2) avoid looping over users one at a time. Is there a way to sample 1-per-user more efficiently? | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | Based on number of rows per user this might be faster:
```
df.sample(frac=1).drop_duplicates(['User'])
``` | `.drop_duplicates` should work just fine:
```
df1.drop_duplicates(subset='User')
```
This will keep each first occurrence of a value in the column 'User' and return the respective row. |
54,727,804 | I have a generator function which reads lines from a file and parses them to objects. The files are far too large to consider processing the entire file into a list which is why I've used the generator and not a list.
I'm concerned because when calling the generator, my code will sometimes break. if it finds what it is looking for it can chose to stop before reading every object from the file. I don't really understand what happens to the abandoned generator, or more importantly I don't know what happens to the open file handle.
I want to avoid resource leaks here.
---
Example code:
```
def read_massive_file(file_path)
with open(file=file_path, mode='r', encoding='utf-8') as source_file:
for line in source_file:
yield parse_entry(line)
for entry in read_massive_file(my_file):
if is_the_entry_i_need(entry):
break
else:
# not found
pass
```
---
My question is: will the above code leave my source file open, or will python find a way to close it?
Does the fact I consume from a `for` loop change anything? If I manually obtained an iterator for `read_massive_file()` and called `next()` a few times before abandoning the iterator, would I see the same result? | 2019/02/16 | [
"https://Stackoverflow.com/questions/54727804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453851/"
] | This only releases resources promptly on CPython. To really be careful about resource release in this situation, you'd have to do something like
```
with contextlib.closing(read_massive_file(my_file)) as gen:
for entry in gen:
...
```
but I've never seen anyone do it.
---
When a generator is discarded without fully exhausting it, the generator's `__del__` method will throw a `GeneratorExit` exception into the generator, to trigger `__exit__` methods and `finally` blocks. On CPython, this happens as soon as the loop breaks and the only reference to the generator is discarded, but on other implementations, like PyPy, it may only happen when a GC cycle runs, or not at all if the GC doesn't run before the end of the program.
The `GeneratorExit` will trigger file closure in your case. It's possible to accidentally catch the `GeneratorExit` and keep going, in which case proper cleanup may not trigger, but your code doesn't do that. | You never save the return value of `read_massive_file`; the only reference is held internally by the code generated by the `for` loop. As soon as that loop completes, the generator should be garbage collected.
It would be different if you had written
```
foo = read_massive_file(my_file):
for entry in foo:
...
else:
...
```
Now you would have to wait until `foo` went out of scope (or called `del foo` explicitly) before the generator could be collected. |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/php5apache2_2.dll" in the file.
Search for LoadModule php, and make sure that there is no comment
(;) in front of it.
3. Make sure that the http.conf file has the PHP MIME type in it. This should be something like AddType application/x-httpd-php
.php. This tells Apache to run .php files as PHP. Search for
AddType, and then make sure there is an entry for PHP, and that
it is uncommented.
4. Make sure your file has the .php extension on it, otherwise it will not be executed as PHP.
5. Make sure you are not using short tags in the PHP file (<?), these are deprecated, and usually disabled. Use <?php instead.
Actually run your file over said webserver using an URL like http://localhost/file.php not via local access
file://localhost/www/file.php
```
Or check <http://php.net/install>
thanks | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl restart apache2
```
and finally it worked. The module PHP for apache2 was not available. |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl restart apache2
```
and finally it worked. The module PHP for apache2 was not available. |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | In my case this was due to that I installed apache2 after the fact and then proper php mods hadn't been linked and thus activated. What you need to do:
```
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/php7.2.conf
sudo ln -s ../mods-available/php7.2.load
```
Then you just do a restart of the server by executing the following command:
```
sudo systemctl restart apache2
``` |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl restart apache2
```
and finally it worked. The module PHP for apache2 was not available. | ```
sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart
```
after that
gedit /etc/apache2/apache2.conf
add the following line
**Include /etc/phpmyadmin/apache.conf**
service apache2 restart
**libapache2-mod-php server-side, HTML-embedded scripting language (Apache 2 module) so we have to add this** |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/php5apache2_2.dll" in the file.
Search for LoadModule php, and make sure that there is no comment
(;) in front of it.
3. Make sure that the http.conf file has the PHP MIME type in it. This should be something like AddType application/x-httpd-php
.php. This tells Apache to run .php files as PHP. Search for
AddType, and then make sure there is an entry for PHP, and that
it is uncommented.
4. Make sure your file has the .php extension on it, otherwise it will not be executed as PHP.
5. Make sure you are not using short tags in the PHP file (<?), these are deprecated, and usually disabled. Use <?php instead.
Actually run your file over said webserver using an URL like http://localhost/file.php not via local access
file://localhost/www/file.php
```
Or check <http://php.net/install>
thanks |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/php5apache2_2.dll" in the file.
Search for LoadModule php, and make sure that there is no comment
(;) in front of it.
3. Make sure that the http.conf file has the PHP MIME type in it. This should be something like AddType application/x-httpd-php
.php. This tells Apache to run .php files as PHP. Search for
AddType, and then make sure there is an entry for PHP, and that
it is uncommented.
4. Make sure your file has the .php extension on it, otherwise it will not be executed as PHP.
5. Make sure you are not using short tags in the PHP file (<?), these are deprecated, and usually disabled. Use <?php instead.
Actually run your file over said webserver using an URL like http://localhost/file.php not via local access
file://localhost/www/file.php
```
Or check <http://php.net/install>
thanks | If all other PHP pages are working fine, then this is probably not a PHP related issue.
Since only the phpmyadmin login page is showing php code rather than the actual login page, chances are that your **symbolic link** in your apache web root directory `/var/www/html/phpmyadmin` is referencing the phpmyadmin index file `/usr/share/phpmyadmin/index.php` instead of the phpmyadmin directory `/usr/share/phpmyadmin`.
This is an incorrect symlink:
```
$ ll /var/www/html
lrwxrwxrwx 1 root root timestamp phpmyadmin -> /usr/share/phpmyadmin/index.php
```
This is a correct symlink:
```
$ ll /var/www/html
lrwxrwxrwx 1 root root timestamp phpmyadmin -> /usr/share/phpmyadmin/
```
If the symlink is incorrect, change it:
```
$ sudo ln -sfn /usr/share/phpmyadmin /var/www/html/phpmyadmin
```
(Or instead delete it and recreate it:)
```
$ sudo unlink /var/www/html/phpmyadmin
$ sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin
``` |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | ```
sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart
```
after that
gedit /etc/apache2/apache2.conf
add the following line
**Include /etc/phpmyadmin/apache.conf**
service apache2 restart
**libapache2-mod-php server-side, HTML-embedded scripting language (Apache 2 module) so we have to add this** |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | If all other PHP pages are working fine, then this is probably not a PHP related issue.
Since only the phpmyadmin login page is showing php code rather than the actual login page, chances are that your **symbolic link** in your apache web root directory `/var/www/html/phpmyadmin` is referencing the phpmyadmin index file `/usr/share/phpmyadmin/index.php` instead of the phpmyadmin directory `/usr/share/phpmyadmin`.
This is an incorrect symlink:
```
$ ll /var/www/html
lrwxrwxrwx 1 root root timestamp phpmyadmin -> /usr/share/phpmyadmin/index.php
```
This is a correct symlink:
```
$ ll /var/www/html
lrwxrwxrwx 1 root root timestamp phpmyadmin -> /usr/share/phpmyadmin/
```
If the symlink is incorrect, change it:
```
$ sudo ln -sfn /usr/share/phpmyadmin /var/www/html/phpmyadmin
```
(Or instead delete it and recreate it:)
```
$ sudo unlink /var/www/html/phpmyadmin
$ sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin
``` |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/php5apache2_2.dll" in the file.
Search for LoadModule php, and make sure that there is no comment
(;) in front of it.
3. Make sure that the http.conf file has the PHP MIME type in it. This should be something like AddType application/x-httpd-php
.php. This tells Apache to run .php files as PHP. Search for
AddType, and then make sure there is an entry for PHP, and that
it is uncommented.
4. Make sure your file has the .php extension on it, otherwise it will not be executed as PHP.
5. Make sure you are not using short tags in the PHP file (<?), these are deprecated, and usually disabled. Use <?php instead.
Actually run your file over said webserver using an URL like http://localhost/file.php not via local access
file://localhost/www/file.php
```
Or check <http://php.net/install>
thanks | In my case this was due to that I installed apache2 after the fact and then proper php mods hadn't been linked and thus activated. What you need to do:
```
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/php7.2.conf
sudo ln -s ../mods-available/php7.2.load
```
Then you just do a restart of the server by executing the following command:
```
sudo systemctl restart apache2
``` |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotly;
use v5.10;
use utf8;
my $user = "MYID";
my $key = "MYKEY";
my $py= WebService::Plotly->new( un => $user, key => $key );
say __LINE__; # first say
my $x0 = [1,2,3,4];
my $y0 = [10,15,13,17];
my $x1 = [2,3,4,5];
my $y1 = [16,5,11,9];
my $response = $py->plot($x0, $y0, $x1, $y1);
say __LINE__ ; # second say
```
..skip...
Then, Execute example perl code
=>> But, In this step, $py->plot always returned "HTTP::Response=HASH(0x7fd1a4236918)"
and second say is not exeucted
( I used Perl version 5.16.2 and 5.19.1, OS is MacOS X)
On the hands, python example("<https://plot.ly/api/python/docs/line-scatter>") is always succeed.
Please, let me know this problem.
Thanks a lot! | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl restart apache2
```
and finally it worked. The module PHP for apache2 was not available. | If all other PHP pages are working fine, then this is probably not a PHP related issue.
Since only the phpmyadmin login page is showing php code rather than the actual login page, chances are that your **symbolic link** in your apache web root directory `/var/www/html/phpmyadmin` is referencing the phpmyadmin index file `/usr/share/phpmyadmin/index.php` instead of the phpmyadmin directory `/usr/share/phpmyadmin`.
This is an incorrect symlink:
```
$ ll /var/www/html
lrwxrwxrwx 1 root root timestamp phpmyadmin -> /usr/share/phpmyadmin/index.php
```
This is a correct symlink:
```
$ ll /var/www/html
lrwxrwxrwx 1 root root timestamp phpmyadmin -> /usr/share/phpmyadmin/
```
If the symlink is incorrect, change it:
```
$ sudo ln -sfn /usr/share/phpmyadmin /var/www/html/phpmyadmin
```
(Or instead delete it and recreate it:)
```
$ sudo unlink /var/www/html/phpmyadmin
$ sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin
``` |
55,619,345 | I am making a card game in python. I used the code for a class of a stack that I found online :
```
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.insert(0,item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
```
When I run this its all fine however when I try to call any of the behaviours my program asks me to pass in a value for self, as if it was a parameter. I feel like Im going crazy...
When this code is run :
```
Cards = []
Cards = Stack()
Cards = Stack.push(15)
Cards = Stack.peek()
Cards = Stack.pop()
```
When the 3rd line is run this error is displayed :
```
TypeError: push() missing 1 required positional argument: 'item'
```
When I pass in the value of None like this
```
Cards = Stack.push(None,15)
```
I am left with another error :
```
self.items.insert(0,item)
AttributeError: 'NoneType' object has no attribute 'items'
``` | 2019/04/10 | [
"https://Stackoverflow.com/questions/55619345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7193131/"
] | After declaring `Cards` to be an instance of `Stack`, you don't need to refer to `Stack` anymore. Just use `Cards`.
```
Cards = Stack()
Cards.push(15)
x = Cards.peek()
y = Cards.pop()
```
Also, the first line of code `Cards = []` is useless, as you immediately reassign `Cards` to be something else. | You shouldn't reassign `Cards` on each line. `Cards` is the `Stack` object, it needs to stay the same. It should be used as the variable with which you call all the other methods.
```
Cards = Stack()
Cards.push(15)
item = Cards.peek()
item2 = Cards.pop() # item == item2
``` |
37,738,498 | I'm running into a problem I've never encountered before, and it's frustrating the hell out of me. I'm using `rpy2` to interface with `R` from within a python script and normalize an array. For some reason, when I go to piece my output together and print to a file, it takes **ages** to print. It also slows down as it proceeds until it's dripping maybe a few kb of data to output per minute.
My input file is large (366 MB), but this is running on a high performance computing cluster with near *unlimited* resources. It should have no problem slamming through this.
Here's where I'm actually doing the normalization:
```
matrix = sample_list # two-dimensional array
v = robjects.FloatVector([ element for col in matrix for element in col ])
m = robjects.r['matrix'](v, ncol = len(matrix), byrow=False)
print("Performing quantile normalization.")
Rnormalized_matrix = preprocessCore.normalize_quantiles(m)
normalized_matrix = np.array(Rnormalized_matrix)
```
As you can see, I end up with a `numpy.array` object containing my now-normalized data. I have another list containing other strings I want to print to the output as well, each element corresponding to an element of the numpy array. So I iterate through, joining each row of the array into a string and print both to output.
```
for thing in pos_list: # List of strings corresponding with each row of array.
thing_index = pos_list.index(thing)
norm_data = normalized_matrix[thing_index]
out_data = "\t".join("{0:.2f}".format(piece) for piece in norm_data)
print(thing + "\t" + out_data, file=output)
```
I'm no pro, but I have no idea why things are slowing down so much. Any insight or suggestions would be very, very appreciated. I can post more/the rest of the script if anyone thinks it may be helpful.
**Update:**
Thanks to @lgautier for his profiling suggestion. Using the `line_profiler` module, I was able to pinpoint my issue to the line:
`thing_index = pos_list.index(thing)`
This makes sense since this list is very long, and it also explains the slow down as the script proceeds. Simply using a count instead fixed the issue.
Profiling of original code (notice the % for the specified line):
```
Line # Hits Time Per Hit % Time Line Contents
115 1 16445761 16445761.0 15.5 header, pos_list, normalized_matrix = Quantile_Normalize(in
117 1 54 54.0 0.0 print("Creating output file...")
120 1 1450 1450.0 0.0 output = open(output_file, "w")
122 1 8 8.0 0.0 print(header, file=output)
124 # Iterate through each position and print QN'd data
125 100000 74600 0.7 0.1 for thing in pos_list:
126 99999 85244758 852.5 80.3 thing_index = pos_list.index(thing)
129 99999 158741 1.6 0.1 norm_data = normalized_matrix[thing_index]
130 99999 3801631 38.0 3.6 out_data = "\t".join("{0:.2f}".format(piece) for pi
132 99999 384248 3.8 0.4 print(thing + "\t" + out_data, file=output)
134 1 3641 3641.0 0.0 output.close()
```
Profiling new code:
```
Line # Hits Time Per Hit % Time Line Contents
115 1 16177130 16177130.0 82.5 header, pos_list, normalized_matrix = Quantile_Normalize(input_file, data_start)
116
117 1 55 55.0 0.0 print("Creating output file...")
118
119
120 1 26157 26157.0 0.1 output = open(output_file, "w")
121
122 1 11 11.0 0.0 print(header, file=output)
123
124 # Iterate through each position and print QN'd data
125 1 1 1.0 0.0 count = 0
126 100000 62709 0.6 0.3 for thing in pos_list:
127 99999 58587 0.6 0.3 thing_index = count
128 99999 67164 0.7 0.3 count += 1
131 99999 85664 0.9 0.4 norm_data = normalized_matrix[thing_index]
132 99999 2877634 28.8 14.7 out_data = "\t".join("{0:.2f}".format(piece) for piece in norm_data)
134 99999 240654 2.4 1.2 print(thing + "\t" + out_data, file=output)
136 1 1713 1713.0 0.0 output.close()
``` | 2016/06/10 | [
"https://Stackoverflow.com/questions/37738498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4438552/"
] | If I am understanding this correctly everything is running fine and with good performance up to (and including) the line:
```
normalized_matrix = np.array(Rnormalized_matrix)
```
At that line the resulting matrix is turned into a numpy array (literally - it can be even faster when avoiding to copy the data, as in <http://rpy2.readthedocs.io/en/version_2.8.x/numpy.html?from-rpy2-to-numpy> ).
I cannot see the performance issues in the rest of the script related to rpy2.
Now what might be happening is that this is not because it says "HPC" on the label that it is high-performance in any and every situation with all code. Did you consider running that slow last loop through a code profiler ? It would tell you where the time is spent. | For one thing, I usually use a generator to avoid the temporary list of many tiny strings.
```
out_data = "\t".join("{0:.2f}".format(piece) for piece in norm_data)
```
But it's hard to tell if this part was the slow one. |
64,334,348 | **Question:**
What is the difference between `open(<name>, "w", encoding=<encoding>)` and `open(<name>, "wb") + str.encode(<encoding>)`? They seem to (sometimes) produce different outputs.
**Context:**
While using [PyFPDF](https://pypi.org/project/fpdf/) (version 1.7.2), I subclassed the `FPDF` class, and, among other things, added my own output method (taking `pathlib.Path` objects). While looking at the source of the original `FPDF.output()` method, I noticed almost all of it is argument parsing - the only relevant bits are
```py
#Finish document if necessary
if(self.state < 3):
self.close()
[...]
f=open(name,'wb')
if(not f):
self.error('Unable to create output file: '+name)
if PY3K:
# manage binary data as latin1 until PEP461 or similar is implemented
f.write(self.buffer.encode("latin1"))
else:
f.write(self.buffer)
f.close()
```
Seeing that, my own Implementation looked like this:
```py
def write_file(self, file: Path) -> None:
if self.state < 3:
# See FPDF.output()
self.close()
file.write_text(self.buffer, "latin1", "strict")
```
This seemed to work - a .pdf file was created at the specified path, and chrome opened it. But it was completely blank, even tho I added Images and Text. After hours of experimenting, I finally found a Version that worked (produced a non empty pdf file):
```py
def write_file(self, file: Path) -> None:
if self.state < 3:
# See FPDF.output()
self.close()
# using .write_text(self.buffer, "latin1", "strict") DOES NOT WORK AND I DON'T KNOW WHY
file.write_bytes(self.buffer.encode("latin1", "strict"))
```
Looking at the `pathlib.Path` source, it uses `io.open` for `Path.write_text()`. As all of this is Python 3.8, `io.open` and the buildin `open()` [are the same](https://docs.python.org/3/library/io.html#io.open).
**Note:**
`FPDF.buffer` is of type `str`, but holds binary data (a pdf file). Probably because the Library was originally written for Python 2. | 2020/10/13 | [
"https://Stackoverflow.com/questions/64334348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5278549/"
] | You can only have a single transaction in progress at a time with a producer instance.
If you have multiple threads doing separate processing and they all need exactly once semantics, you should have a producer instance per thread. | Not sure if this was resolved.
you can use apache common pool2 to create a producer instance pool.
In the create() method of the factory implementation you can generate and assign a unique transactionalID to avoid a conflict (ProducerFencedException) |
50,026,785 | I need to download a package using pip. I ran `pip install <package>` but got the following error:
```
[user@server ~]$ pip install sistr_cmd
Collecting sistr_cmd
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.
VerifiedHTTPSConnection object at 0x7f518ee0cd90>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/
Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.
VerifiedHTTPSConnection object at 0x7f518ee0c290>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/
Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.
VerifiedHTTPSConnection object at 0x7f518ee0c510>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/
Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.
VerifiedHTTPSConnection object at 0x7f518ee0cf10>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/
Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.
VerifiedHTTPSConnection object at 0x7f518ee0c190>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/sistr-cmd/
Could not find a version that satisfies the requirement sistr_cmd (from versions: )
No matching distribution found for sistr_cmd
```
I verified that the source of the problem is the network blocking most sites because I am working behind a proxy (required by the organization). To allow these downloads, I need to compile the list of urls of the source of the downloads and send it to the network admins to unblock.
According to pip documentation (cited and explained in brief in the pip Wikipedia article), “Many packages can be found in the default source for packages and their dependencies — Python Package Index (PyPI)," so I went to the PyPI page for Biopython and found the github repository and the required dependencies for the package. There are also download links on the PyPI page and I want to be sure that all sources for the download are allowed. So does pip install from the original source of a package (the github repository or wherever the original package is hosted), the packages listed in the PyPI page under downloads, or does it search through both?
Thank you in advance for the help. | 2018/04/25 | [
"https://Stackoverflow.com/questions/50026785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8967045/"
] | ```
myzipWith :: (a->b->c) -> [a] -> [b] ->[c]
myzipWith func [] [] = []
myzipWith func (headA:restA) (headB:restB) =
[func headA headB] ++ myzipWith func restA restB
```
But note the append (`++`) isn't necessary. This would be more idiomatic (and efficient):
```
func headA headB : myzipWith func restA restB
``` | ```
myzipWith func (a:as) (b:bs) = [func a b] ++ (myzipWith func as bs)
```
The syntax `function (x:xs)` splits the list passed to `function` into two parts: the first element `x` and the rest of the list `xs`. |
25,296,807 | Is it possible in python to create an un-linked copy of a function? For example, if I have
```
a = lambda(x): x
b = lambda(x): a(x)+1
```
I want `b(x)` to always `return x+1`, regardless if `a(x)` is modified not. Currently, if I do
```
a = lambda(x): x
b = lambda(x): a(x)+1
print a(1.),b(1.)
a = lambda(x): x*0
print a(1.),b(1.)
```
the output is
```
1. 2.
0. 1.
```
Instead of being
```
1. 2.
0. 2.
```
as I would like to. Any idea on how to implement this? It seems that using `deepcopy` does not help for functions. Also keep in mind that `a(x)` is created externally and I can't change its definition. I've also looked into using [this method](https://stackoverflow.com/questions/13503079/how-to-create-a-copy-of-a-python-function), but it did not help. | 2014/08/13 | [
"https://Stackoverflow.com/questions/25296807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3939154/"
] | You could define b like this:
```
b = lambda x, a=a: a(x)+1
```
This makes `a` a parameter of `b`, and therefore a local variable. You default it to the value of `a` in the current environment, so `b` will hold onto that value. You don't need to copy `a`, just keep its current value, so that if a new value is created, you have the one you wanted.
That said, this sounds like something unusual happening, and if you tell us more about what's going on, there's likely a better answer. | I might need to know a little more about your constraints before I can give a satisfactory answer. Why couldn't you do something like
```
a = lambda(x): x
c = a
b = lambda(x): c(x)+1
```
Then no matter what happens to `a`, `b` will stay the same. This works because of the somewhat unusual way that assignment works in Python. When you do `c = a`, the name `c` is linked to the object that `a` links to. You can use `id()` to look at that object's id and see that they are the same; `c` and `a` point to the same object.
```
c = a
id(a)
>>> 4410483968
id(c)
>>> 4410483968
```
Then, when you redefine `a` with `a = lambda x: x*0`, you're actually doing two things in one line. First, `lambda x: x*0` creates a new function object, then the assignment causes the name `a` to be linked to the new object. As you can see, `a` is now pointing to a different object:
```
a = lambda x: x*0
id(a)
>>>> 4717817680
```
But if you look at `id(c)`, it still points to the old object!
```
id(c)
>>>> 4410483968
```
This is because when we redefined `a`, we merely created a new object and linked `a` to it. `c` remains linked to the old one.
So if you redefine `a` as you do in the question, you get the output you want:
```
print a(1.),b(1.)
>>>> 0.0,2.0
``` |
62,707,514 | As we all know, filling out the web forms automatically is possible using JavaScript. Basically, We find the ID of related element using Inspect (Ctrl + I) in i.e Chrome and write a javascript code in the chrome console to automate what we want to do by code.
Just like that, is it possible to automate desktop apps using python? if yes how ? | 2020/07/03 | [
"https://Stackoverflow.com/questions/62707514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13177703/"
] | You can do this in python using **selenium**. Selenium is an open-source testing tool, used for functional testing and also compatible with non-functional testing.
You can refer to this [link](https://www.guru99.com/selenium-python.html) to get started. | [Pywinauto](https://pywinauto.github.io/) is a GUI automation library written in pure Python and well developed for Windows GUI. |
48,949,121 | i have a python script that read from CSV file and check if the records meet the conditions.
* if yes the system display the result
* if no the system raise Exception based on the Error.
the csv file includes a filed that has **float values** but some of these records may not have any value so will be empty.
the problem is if the cell is empty the system display this ValueError :
```
could not convert string to float:
```
and not the Exception that i wrote it.
```
raise Exception("this Record has empty value")
```
* row[0]==> Date type Date
* row[10]==> wind speed type float
* row[11]==> fog type boolean
code:
=====
```
import csv
mydelimeter = csv.excel()
mydelimeter.delimiter=";"
myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")
# read the first line in the opened file ==> Header
myfile.readline()
myreader=csv.reader(myfile,mydelimeter)
mywind,mydate=[],[]
minTemp, maxTemp = [],[]
fastwindspeed, fog=[],[]
'''
create a variable that handle values of the 3 fields ==> Date - fastest5secwindspeed - fog
and display the result where
fog ==> Yes and highest speed more than 10.
'''
for row in myreader:
try:
if row[11] =="Yes":
if float(row[10]) < 10.0:
raise Exception( 'the wind speed is below 10 mph in ' + row[0] )
if row[10] in (None, ""):
raise Exception("this Record has empty value")
print(row[0],row[10],row[11])
except Exception as e:
print("{}".format(e))
myfile.close()
``` | 2018/02/23 | [
"https://Stackoverflow.com/questions/48949121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9162690/"
] | That behaviour is often caused by an updated installation of MongoDB. There is a "feature compatibility level" switch built into MongoDB which allows for updates to a newer version that do not alter (some of) the behaviour of the old version in a non-expected (oh well) way. The [documentation](https://docs.mongodb.com/manual/reference/command/setFeatureCompatibilityVersion/#default-values) for upgrades from v3.4 to v3.6 states on that topic:
>
> For deployments upgraded from 3.4 [the default feature compatibility level is] "3.4" until you setFeatureCompatibilityVersion to "3.6".
>
>
>
You can fix this by running the following command:
```
db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } )
``` | To everyone in the same case, the solution dnickless gave works for me:
>
> In case you've upgrade from an older version try running this:
>
>
> `db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } )`
>
>
> |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of the day (24 boolean features)
* day of the week (7 boolean features)
* day of the month (up to 31 boolean features)
* month of the year (12 boolean features)
* year (as many boolean features as they are different years in your dataset)
...
That should make it possible to identify linear dependencies on periodic events on typical human life cycles.
Additionally you can also extract the date a single float: convert each date as the number of days since the min date of your training set and divide by the difference of the number of days between the max date and the number of days of the min date. That numerical feature should make it possible to identify long term trends between the output of the event date: e.g. a linear slope in a regression problem to better predict evolution on forth-coming years that cannot be encoded with the boolean categorical variable for the year feature. | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/modules/generated/sklearn.preprocessing.OneHotEncoder.html). What it does is create a new variable for each distinct date. So instead of something like column `date` with values `['2013-04-01', '2013-05-01']`, you will have two columns, `date_2013_04_01` with values `[1, 0]` and `date_2013_05_01` with values `[0, 1]`.
I would recommend using the `toordinal` approach if you have many different dates, and the one hot encoder if the number of distinct dates is small (let's say up to 10 - 100, depending on the size of your data and what sort of relation the date has with the output variable). |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/modules/generated/sklearn.preprocessing.OneHotEncoder.html). What it does is create a new variable for each distinct date. So instead of something like column `date` with values `['2013-04-01', '2013-05-01']`, you will have two columns, `date_2013_04_01` with values `[1, 0]` and `date_2013_05_01` with values `[0, 1]`.
I would recommend using the `toordinal` approach if you have many different dates, and the one hot encoder if the number of distinct dates is small (let's say up to 10 - 100, depending on the size of your data and what sort of relation the date has with the output variable). | Before doing boolean encoding using the 1-of-K encoding suggested by @ogrisel, you may try enriching your data and playing with the number of features that you can extract from the datetime-type, i.e. day of week, day of month, day of year, week of year, quarter, etc.
See for example <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.weekofyear.html> and links to other functions. |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/modules/generated/sklearn.preprocessing.OneHotEncoder.html). What it does is create a new variable for each distinct date. So instead of something like column `date` with values `['2013-04-01', '2013-05-01']`, you will have two columns, `date_2013_04_01` with values `[1, 0]` and `date_2013_05_01` with values `[0, 1]`.
I would recommend using the `toordinal` approach if you have many different dates, and the one hot encoder if the number of distinct dates is small (let's say up to 10 - 100, depending on the size of your data and what sort of relation the date has with the output variable). | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.days
```
Of cause this will not identify behaviour within one day (hour dependent). So maybe you wanna go down to the scale that identifyes changing behaviour in your data the best.
For Hours:
```
df['HOURS_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.components['hours']
```
The code above adds a new column with the delta value, to remove the old TIMESTAMP do this afterwards:
```
df = df.drop('TIMESTAMP', axis=1)
``` |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/modules/generated/sklearn.preprocessing.OneHotEncoder.html). What it does is create a new variable for each distinct date. So instead of something like column `date` with values `['2013-04-01', '2013-05-01']`, you will have two columns, `date_2013_04_01` with values `[1, 0]` and `date_2013_05_01` with values `[0, 1]`.
I would recommend using the `toordinal` approach if you have many different dates, and the one hot encoder if the number of distinct dates is small (let's say up to 10 - 100, depending on the size of your data and what sort of relation the date has with the output variable). | I usually turn the DateTime to features of interest such as Year, Month, Day, Hour, Minute.
```
df['Year'] = df['Timestamp'].apply(lambda time: time.year)
df['Month'] = df['Timestamp'].apply(lambda time: time.month)
df['Day'] = df['Timestamp'].apply(lambda time: time.day)
df['Hour'] = df['Timestamp'].apply(lambda time: time.hour)
df['Minute'] = df['Timestamp'].apply(lambda time: time.minute)
``` |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of the day (24 boolean features)
* day of the week (7 boolean features)
* day of the month (up to 31 boolean features)
* month of the year (12 boolean features)
* year (as many boolean features as they are different years in your dataset)
...
That should make it possible to identify linear dependencies on periodic events on typical human life cycles.
Additionally you can also extract the date a single float: convert each date as the number of days since the min date of your training set and divide by the difference of the number of days between the max date and the number of days of the min date. That numerical feature should make it possible to identify long term trends between the output of the event date: e.g. a linear slope in a regression problem to better predict evolution on forth-coming years that cannot be encoded with the boolean categorical variable for the year feature. | Before doing boolean encoding using the 1-of-K encoding suggested by @ogrisel, you may try enriching your data and playing with the number of features that you can extract from the datetime-type, i.e. day of week, day of month, day of year, week of year, quarter, etc.
See for example <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.weekofyear.html> and links to other functions. |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of the day (24 boolean features)
* day of the week (7 boolean features)
* day of the month (up to 31 boolean features)
* month of the year (12 boolean features)
* year (as many boolean features as they are different years in your dataset)
...
That should make it possible to identify linear dependencies on periodic events on typical human life cycles.
Additionally you can also extract the date a single float: convert each date as the number of days since the min date of your training set and divide by the difference of the number of days between the max date and the number of days of the min date. That numerical feature should make it possible to identify long term trends between the output of the event date: e.g. a linear slope in a regression problem to better predict evolution on forth-coming years that cannot be encoded with the boolean categorical variable for the year feature. | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.days
```
Of cause this will not identify behaviour within one day (hour dependent). So maybe you wanna go down to the scale that identifyes changing behaviour in your data the best.
For Hours:
```
df['HOURS_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.components['hours']
```
The code above adds a new column with the delta value, to remove the old TIMESTAMP do this afterwards:
```
df = df.drop('TIMESTAMP', axis=1)
``` |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of the day (24 boolean features)
* day of the week (7 boolean features)
* day of the month (up to 31 boolean features)
* month of the year (12 boolean features)
* year (as many boolean features as they are different years in your dataset)
...
That should make it possible to identify linear dependencies on periodic events on typical human life cycles.
Additionally you can also extract the date a single float: convert each date as the number of days since the min date of your training set and divide by the difference of the number of days between the max date and the number of days of the min date. That numerical feature should make it possible to identify long term trends between the output of the event date: e.g. a linear slope in a regression problem to better predict evolution on forth-coming years that cannot be encoded with the boolean categorical variable for the year feature. | I usually turn the DateTime to features of interest such as Year, Month, Day, Hour, Minute.
```
df['Year'] = df['Timestamp'].apply(lambda time: time.year)
df['Month'] = df['Timestamp'].apply(lambda time: time.month)
df['Day'] = df['Timestamp'].apply(lambda time: time.day)
df['Hour'] = df['Timestamp'].apply(lambda time: time.hour)
df['Minute'] = df['Timestamp'].apply(lambda time: time.minute)
``` |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | Before doing boolean encoding using the 1-of-K encoding suggested by @ogrisel, you may try enriching your data and playing with the number of features that you can extract from the datetime-type, i.e. day of week, day of month, day of year, week of year, quarter, etc.
See for example <https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.weekofyear.html> and links to other functions. | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.days
```
Of cause this will not identify behaviour within one day (hour dependent). So maybe you wanna go down to the scale that identifyes changing behaviour in your data the best.
For Hours:
```
df['HOURS_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.components['hours']
```
The code above adds a new column with the delta value, to remove the old TIMESTAMP do this afterwards:
```
df = df.drop('TIMESTAMP', axis=1)
``` |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `date` into account in the regression model?
**Code**
```
data = sql.read_frame(...)
X_train = data.drop('y', axis=1)
y_train = data.y
rf = RandomForestRegressor().fit(X_train, y_train)
```
**Error**
```
TypeError Traceback (most recent call last)
<ipython-input-35-8bf6fc450402> in <module>()
----> 2 rf = RandomForestRegressor().fit(X_train, y_train)
C:\Python27\lib\site-packages\sklearn\ensemble\forest.pyc in fit(self, X, y, sample_weight)
292 X.ndim != 2 or
293 not X.flags.fortran):
--> 294 X = array2d(X, dtype=DTYPE, order="F")
295
296 n_samples, self.n_features_ = X.shape
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in array2d(X, dtype, order, copy)
78 raise TypeError('A sparse matrix was passed, but dense data '
79 'is required. Use X.toarray() to convert to dense.')
---> 80 X_2d = np.asarray(np.atleast_2d(X), dtype=dtype, order=order)
81 _assert_all_finite(X_2d)
82 if X is X_2d and copy:
C:\Python27\lib\site-packages\numpy\core\numeric.pyc in asarray(a, dtype, order)
318
319 """
--> 320 return array(a, dtype, copy=False, order=order)
321
322 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | I usually turn the DateTime to features of interest such as Year, Month, Day, Hour, Minute.
```
df['Year'] = df['Timestamp'].apply(lambda time: time.year)
df['Month'] = df['Timestamp'].apply(lambda time: time.month)
df['Day'] = df['Timestamp'].apply(lambda time: time.day)
df['Hour'] = df['Timestamp'].apply(lambda time: time.hour)
df['Minute'] = df['Timestamp'].apply(lambda time: time.minute)
``` | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.days
```
Of cause this will not identify behaviour within one day (hour dependent). So maybe you wanna go down to the scale that identifyes changing behaviour in your data the best.
For Hours:
```
df['HOURS_DELTA'] = (df.TIMESTAMP - df.TIMESTAMP.min()).dt.components['hours']
```
The code above adds a new column with the delta value, to remove the old TIMESTAMP do this afterwards:
```
df = df.drop('TIMESTAMP', axis=1)
``` |
46,191,793 | I followed the guide here:
<https://plot.ly/python/filled-chord-diagram/>
And I produced this:
[](https://i.stack.imgur.com/wVzNc.png)
In the guide, I followed the `ribbon_info` code to add hoverinfo to the connecting ribbons but nothing shows. I can get the hoverinfo to only show for the ribbon ends. Can anyone see where I am going wrong?
```
ribbon_info=[]
for k in range(L):
sigma=idx_sort[k]
sigma_inv=invPerm(sigma)
for j in range(k, L):
if matrix[k][j]==0 and matrix[j][k]==0: continue
eta=idx_sort[j]
eta_inv=invPerm(eta)
l=ribbon_ends[k][sigma_inv[j]]
if j==k:
layout['shapes'].append(make_self_rel(l, 'rgb(175,175,175)' ,
ideo_colors[k], radius=radii_sribb[k]))
z=0.9*np.exp(1j*(l[0]+l[1])/2)
#the text below will be displayed when hovering the mouse over the ribbon
text=labels[k]+' appears on'+ '{:d}'.format(matrix[k][k])+' of the same grants as '+ '',
ribbon_info.append(Scatter(x=z.real,
y=z.imag,
mode='markers',
marker=Marker(size=5, color=ideo_colors[k]),
text=text,
hoverinfo='text'
)
)
else:
r=ribbon_ends[j][eta_inv[k]]
zi=0.9*np.exp(1j*(l[0]+l[1])/2)
zf=0.9*np.exp(1j*(r[0]+r[1])/2)
#texti and textf are the strings that will be displayed when hovering the mouse
#over the two ribbon ends
texti=labels[k]+' appears on '+ '{:d}'.format(matrix[k][j])+' of the same grants as '+\
labels[j]+ '',
textf=labels[j]+' appears on '+ '{:d}'.format(matrix[j][k])+' of the same grants as '+\
labels[k]+ '',
ribbon_info.append(Scatter(x=zi.real,
y=zi.imag,
mode='markers',
marker=Marker(size=0.5, color=ribbon_color[k][j]),
text=texti,
hoverinfo='text'
)
),
ribbon_info.append(Scatter(x=zf.real,
y=zf.imag,
mode='markers',
marker=Marker(size=0.5, color=ribbon_color[k][j]),
text=textf,
hoverinfo='text'
)
)
r=(r[1], r[0])#IMPORTANT!!! Reverse these arc ends because otherwise you get
# a twisted ribbon
#append the ribbon shape
layout['shapes'].append(make_ribbon(l, r , 'rgb(255,175,175)', ribbon_color[k][j]))
```
The outputs for the variables are as follows:
```
texti = (u'Sociology appears on 79 of the same grants as Tools, technologies & methods',)
textf = (u'Tools, technologies & methods appears on 79 of the same grants as Sociology',)
ribbon_info = [{'hoverinfo': 'text',
'marker': {'color': 'rgba(214, 248, 149, 0.65)', 'size': 0.5},
'mode': 'markers',
'text': (u'Demography appears on 51 of the same grants as Social policy',),
'type': 'scatter',
'x': 0.89904409911342476,
'y': 0.04146936036799545},
{'hoverinfo': 'text',
'marker': {'color': 'rgba(214, 248, 149, 0.65)', 'size': 0.5},
'mode': 'markers',
'text': (u'Social policy appears on 51 of the same grants as Demography',),
'type': 'scatter',
'x': -0.65713108202353809,
'y': -0.61496238993825791},..................**etc**
sigma = array([ 0, 14, 12, 10, 9, 7, 8, 5, 4, 3, 2, 1, 6, 16, 13, 11, 15], dtype=int64)
```
The code after the previous block which builds the chord diagram is as follows:
```
ideograms=[]
for k in range(len(ideo_ends)):
z= make_ideogram_arc(1.1, ideo_ends[k])
zi=make_ideogram_arc(1.0, ideo_ends[k])
m=len(z)
n=len(zi)
ideograms.append(Scatter(x=z.real,
y=z.imag,
mode='lines',
line=Line(color=ideo_colors[k], shape='spline', width=0),
text=labels[k]+'<br>'+'{:d}'.format(row_sum[k]),
hoverinfo='text'
)
)
path='M '
for s in range(m):
path+=str(z.real[s])+', '+str(z.imag[s])+' L '
Zi=np.array(zi.tolist()[::-1])
for s in range(m):
path+=str(Zi.real[s])+', '+str(Zi.imag[s])+' L '
path+=str(z.real[0])+' ,'+str(z.imag[0])
layout['shapes'].append(make_ideo_shape(path,'rgb(150,150,150)' , ideo_colors[k]))
data = Data(ideograms+ribbon_info)
fig=Figure(data=data, layout=layout)
plotly.offline.iplot(fig, filename='chord-diagram-Fb')
```
This is the only hoverinfo that shows, the outside labels, not the ones just slightly more inside:
[](https://i.stack.imgur.com/mqzcG.png)
Using the example from the link at the start of my question. They have two sets of labels. On my example, the equivalent of 'Isabelle has commented on 32 of Sophia....' is not showing.
[](https://i.stack.imgur.com/KgF8D.png) | 2017/09/13 | [
"https://Stackoverflow.com/questions/46191793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6593031/"
] | just apply `json.dumps()` to this native python dictionary composed in one-line:
```
{k.replace(" ","_"):v.strip() for k,v in (x.split(":") for x in ["Passanger status:\n passanger cfg086d96 is unknown\n\n"])}
```
the inner generator comprehension avoids to call `split` for each part of the dict key/value. The value is stripped to remove trailing/leading blank spaces. The space characters in the key are replaced by underscores.
result is (as dict):
```
{'Passanger status': 'passanger cfg086d96 is unknown'}
```
as json string using `indent` to generate newlines:
```
>>> print(json.dumps({k.replace(" ","_"):v.strip() for k,v in (x.split(":") for x in ["Passanger status:\n passanger cfg086d96 is unknown\n\n"])},indent=2))
{
"Passanger_status": "passanger cfg086d96 is unknown"
}
``` | You can try this one also
```
data_dic = dict()
data = "Passanger status:\n passanger cfg086d96 is unknown\n\n"
x1 , x2 = map(str,data.split(":"))
data_dic[x1] = x2
print data_dic
```
If you find it simple
Output :
```
{'Passanger status': '\n passanger cfg086d96 is unknown\n\n'}
```
and for space to underscore you can use replace method in keys of the dictionary. |
73,935,930 | How (in python) can I change numbers to be going up. For example, 1 (time.sleep(0.05)) then it changes to two, and so on. But there will be text already above it, so you can't use a simple `os.system('clear')`
So like this:
>
> print("how much money do you want to make?")<
> 'number going up without deleting the "how much money" part'
>
>
> | 2022/10/03 | [
"https://Stackoverflow.com/questions/73935930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20149657/"
] | Like this:
```
import sys
import time
for i in range(10):
time.sleep(0.3)
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()
```
Edit: This was taken from [Replace console output in Python](https://stackoverflow.com/questions/6169217/replace-console-output-in-python) | The question is very unclear, but maybe you mean the following:
```py
import time
for item in [0.05,2,3]:
time.sleep(item)
```
and
```py
number = 3
print("how much money do you want to make? {}".format(number))
``` |
73,935,930 | How (in python) can I change numbers to be going up. For example, 1 (time.sleep(0.05)) then it changes to two, and so on. But there will be text already above it, so you can't use a simple `os.system('clear')`
So like this:
>
> print("how much money do you want to make?")<
> 'number going up without deleting the "how much money" part'
>
>
> | 2022/10/03 | [
"https://Stackoverflow.com/questions/73935930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20149657/"
] | I am assuming that you want it to sleep for 1 second the first time, 2 seconds for the second time, and so on. You could create a function.
```
counter = 0
def my_function():
global counter
sleep(counter)
counter = counter + 1
for i in range(3):
my_function()
```
This is an example of what you can do.Change it to meet your needs. | The question is very unclear, but maybe you mean the following:
```py
import time
for item in [0.05,2,3]:
time.sleep(item)
```
and
```py
number = 3
print("how much money do you want to make? {}".format(number))
``` |
36,115,429 | I faced a compile error in my python script as following:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start, end])
```
the output is:
```
ASD 0 2 <class 'int'> <class 'int'>
Traceback (most recent call last):
File "test.py", line 5, in <module>
print(formula[start, end])
TypeError: string indices must be integers
```
But start, end is int, so strange! | 2016/03/20 | [
"https://Stackoverflow.com/questions/36115429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3001445/"
] | The syntax to slice is with `:` not with `,`
```
>>> print(formula[start:end])
AS
``` | You seem to be performing a slicing operation, in order to do this you need to use `:` and not `,`:
```
formula[start:end]
```
Demo:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start:end])
```
output:
```
ASD 0 2 <class 'int'> <class 'int'>
AS
``` |
36,115,429 | I faced a compile error in my python script as following:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start, end])
```
the output is:
```
ASD 0 2 <class 'int'> <class 'int'>
Traceback (most recent call last):
File "test.py", line 5, in <module>
print(formula[start, end])
TypeError: string indices must be integers
```
But start, end is int, so strange! | 2016/03/20 | [
"https://Stackoverflow.com/questions/36115429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3001445/"
] | As others have said, slicing is written like
```
formula[start:end]
```
The error in your original code is because
```
formula[start, end]
```
is being interpreted as
```
formula[(start, end)]
```
So the string index is a tuple, instead of an `int` or slice. | You seem to be performing a slicing operation, in order to do this you need to use `:` and not `,`:
```
formula[start:end]
```
Demo:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start:end])
```
output:
```
ASD 0 2 <class 'int'> <class 'int'>
AS
``` |
17,528,976 | I am working on an anonymizer program which sensors the given words in the list. This is what i have so far. I am new to python so not sure how can i achieve this.
```
def isAlpha(c):
if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9'):
return True
else:
return False
def main():
message = []
userInput = str(input("Enter The Sentense: "))
truncatedInput = userInput[:140]
for i in range(len(truncatedInput)):
if(truncatedInput[i] == 'DRAT'):
truncatedInput[i] = 'x'
print(truncatedInput[i])
```
this is the output i get
```
Enter The Sentense: DRAT
D
R
A
T
```
I want the word to be replaced by XXXX | 2013/07/08 | [
"https://Stackoverflow.com/questions/17528976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2559375/"
] | You have several problems with your code:
1. There already exists an `islpha` function; it is a `str` method (see example below).
2. Your `trucatedInput` is a `str`, which is an immutable type. You can't reassign parts of an immutable type; i.e. `myStr[3]='x'` would normally fail. If you really want to do this, you're better off representing your truncated input as a list and using `''.join(truncatedInput)` to turn it into a string later.
3. You are currently looking at the characters in your truncated input to check if any of them equals `'DRAT'`. This is what your first for-loop in `main` does. However, what you seem to want is to iterate over the words themselves - you will need a "chunker" for this. This is a slightly difficult problem if you want to deal with free-form English. For example, a simple word chunker would simply split your sentence on spaces. However, what happens when you have a sentence containing the word "DRAT'S"? Due to such cases, you will be forced to create a proper chunker to deal with punctuations as required. This is a fairly high-level design decision. You may want to take a look at [`NLTK`](http://nltk.org/) to see if any of its chunkers will help you out.
**Examples**:
`str.isalpha`
```
In [3]: myStr = 'abc45d'
In [4]: for char in myStr:
...: print char, char.isalpha()
...:
a True
b True
c True
4 False
5 False
d True
```
strings are immutable
```
In [5]: myStr[3] = 'x'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-bf15aed01ea1> in <module>()
----> 1 myStr[3] = 'x'
TypeError: 'str' object does not support item assignment
```
Finally, as others have recommended, you're likely much better off using `str.replace` anyways. However, be wary of replacing substrings of non-cencored words. For example, the substring "hell" in the word "hello" does not need to be censored. To accommodate for such text, you may want to use [`re.sub`](http://docs.python.org/2/library/re.html#re.sub), a regex substitution, as opposed to `str.replace`.
One additional note, python allows for transitive comparisons. So you can shorten `if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9')` into `if( 'Z' >= c >= 'A' or 'z' >= c >= 'a' or '9' >= c >= '0')`. This, by the way, can be replaced with `if c.isalpha() or c.isdigit()`
Hope this helps | You could use [string.replace()](http://docs.python.org/2/library/string.html#string.replace)
```
truncatedInput.replace('DRAT', 'xxxx')
```
This will replace the first occurence of DRAT with xxxx, even if it is part of a longer sentence. If you want different functionality let me know. |
17,528,976 | I am working on an anonymizer program which sensors the given words in the list. This is what i have so far. I am new to python so not sure how can i achieve this.
```
def isAlpha(c):
if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9'):
return True
else:
return False
def main():
message = []
userInput = str(input("Enter The Sentense: "))
truncatedInput = userInput[:140]
for i in range(len(truncatedInput)):
if(truncatedInput[i] == 'DRAT'):
truncatedInput[i] = 'x'
print(truncatedInput[i])
```
this is the output i get
```
Enter The Sentense: DRAT
D
R
A
T
```
I want the word to be replaced by XXXX | 2013/07/08 | [
"https://Stackoverflow.com/questions/17528976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2559375/"
] | You have several problems with your code:
1. There already exists an `islpha` function; it is a `str` method (see example below).
2. Your `trucatedInput` is a `str`, which is an immutable type. You can't reassign parts of an immutable type; i.e. `myStr[3]='x'` would normally fail. If you really want to do this, you're better off representing your truncated input as a list and using `''.join(truncatedInput)` to turn it into a string later.
3. You are currently looking at the characters in your truncated input to check if any of them equals `'DRAT'`. This is what your first for-loop in `main` does. However, what you seem to want is to iterate over the words themselves - you will need a "chunker" for this. This is a slightly difficult problem if you want to deal with free-form English. For example, a simple word chunker would simply split your sentence on spaces. However, what happens when you have a sentence containing the word "DRAT'S"? Due to such cases, you will be forced to create a proper chunker to deal with punctuations as required. This is a fairly high-level design decision. You may want to take a look at [`NLTK`](http://nltk.org/) to see if any of its chunkers will help you out.
**Examples**:
`str.isalpha`
```
In [3]: myStr = 'abc45d'
In [4]: for char in myStr:
...: print char, char.isalpha()
...:
a True
b True
c True
4 False
5 False
d True
```
strings are immutable
```
In [5]: myStr[3] = 'x'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-bf15aed01ea1> in <module>()
----> 1 myStr[3] = 'x'
TypeError: 'str' object does not support item assignment
```
Finally, as others have recommended, you're likely much better off using `str.replace` anyways. However, be wary of replacing substrings of non-cencored words. For example, the substring "hell" in the word "hello" does not need to be censored. To accommodate for such text, you may want to use [`re.sub`](http://docs.python.org/2/library/re.html#re.sub), a regex substitution, as opposed to `str.replace`.
One additional note, python allows for transitive comparisons. So you can shorten `if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9')` into `if( 'Z' >= c >= 'A' or 'z' >= c >= 'a' or '9' >= c >= '0')`. This, by the way, can be replaced with `if c.isalpha() or c.isdigit()`
Hope this helps | You're iterating over the characters in a string and comparing them to 'DRAT'. Since that's multiple characters, the comparison always fails. If you want to iterate over the string by word you must first break it into a list of words using str.split() and iterate over the list. |
67,756,936 | I have this:
```py
def f(message):
l = []
for c in message:
l.append(c)
l.append('*')
return "".join(l)
```
It works but how do I make it so that it doesn't add "\*" at the end. I only want it to be between the inputted word. I'm new to python and was just trying new things. | 2021/05/30 | [
"https://Stackoverflow.com/questions/67756936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16072743/"
] | May be you can try this. It uses list comprehension
```
input_str = 'dog'
def f(x):
return '*'.join(x)
print(f('dog')) #ouput d*o*g
print(f(input_str)) #ouput d*o*g
``` | Well, technically you could just slice the returned string cutting off the last astrix.
```
message="dog"
def f(message):
l = []
for c in message:
l.append(c)
l.append('*')
return "".join(l[:-1])
print(f(message))
```
this way it returns
```
d*o*g
``` |
24,736,813 | I want to extend the datetime.date class adding it an attribute called `status` that represents if the date is a work day, an administrative non-work day, courts closed day,...
I've read from [How to extend a class in python?](https://stackoverflow.com/questions/15526858/how-to-extend-a-class-in-python), [How to extend Python class init](https://stackoverflow.com/questions/12701206/how-to-extend-python-class-init) and [Chain-calling parent constructors in python](https://stackoverflow.com/questions/904036/chain-calling-parent-constructors-in-python), but I don't understand it well, so I'm noob with OOP.
```
>>> import datetime
>>> class Fecha(datetime.date):
def __init__(self, year, month, day, status):
super(Fecha, self).__init__(self, year, month, day)
self.status = status
>>> dia = Fecha(2014, 7, 14, 'laborable')
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
dia = Fecha(2014, 7, 14, 'laborable')
TypeError: function takes at most 3 arguments (4 given)
>>>
``` | 2014/07/14 | [
"https://Stackoverflow.com/questions/24736813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3160820/"
] | `datetime.date` is an immutable type, meaning you need to override the [`__new__` method](https://docs.python.org/3/reference/datamodel.html#object.__new__) instead:
```
class Fecha(datetime.date):
def __new__(cls, year, month, day, status):
instance = super(Fecha, cls).__new__(cls, year, month, day)
instance.status = status
return instance
```
Demo:
```
>>> import datetime
>>> class Fecha(datetime.date):
... def __new__(cls, year, month, day, status):
... instance = super(Fecha, cls).__new__(cls, year, month, day)
... instance.status = status
... return instance
...
>>> dia = Fecha(2014, 7, 14, 'laborable')
>>> dia.status
'laborable'
``` | problem is in super call
```
super(Fecha, self).__init__(year, month, day)
```
Try this. |
55,739,404 | I have a Python 3.6 script that calls out to a third-party tool using subprocess.
`main_script.py:`
```
#!/usr/bin/env python
import subprocess
result = subprocess.run(['third-party-tool', '-arg1'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
```
The problem is, `main_script.py` must be run from within a virtual environment, and `third-party-tool` must be run from no virtual environment whatsoever.
I don't know much about `third-party-tool`, except that it is on my path. Calling it while I have a virtual environment active causes it to jam up and throw an exception later on. I do not know if it uses the default python binary or it it spins up its own virtual env and does stuff in there. It is not a Python script, but apparently calls one somehow.
*How do I tell subprocess to drop out of my virtual environment and run the command in the default shell environment?*
I've examined a couple of similar questions:
* [Running subprocess within different virtualenv with python](https://stackoverflow.com/questions/8052926/running-subprocess-within-different-virtualenv-with-python) -- In the first case, they are specifying the environment by calling their script with a specific version of Python. `third-party-tool` is not a Python script (I believe it's bash).
* [Python subprocess/Popen with a modified environment](https://stackoverflow.com/questions/2231227/python-subprocess-popen-with-a-modified-environment) -- In the second case, they're tweaking existing environment variables, which looks promising, but I want to reset to the default environment, and I'm not sure if I necessarily know which variables I need to clear or reset. | 2019/04/18 | [
"https://Stackoverflow.com/questions/55739404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3638628/"
] | From the documentation of subprocess:
<https://docs.python.org/3/library/subprocess.html>
The accepted args are
```
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
capture_output=False, shell=False, cwd=None, timeout=None, check=False,
encoding=None, errors=None, text=None, env=None, universal_newlines=None)
```
In particular,
>
> If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. It is passed directly to Popen.
>
>
>
Thus, passing an empty dictionary `env={}` (start with empty environment) and using `bash --login` (run as login shell, which reads env defaults) should do the trick.
```
subprocess.run(['bash', '--login', '-c', '/full/path/to/third-party-tool', '-arg1'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={})
``` | Thanks for your help, nullUser; your solution is a concise and correct answer to my question.
However, when I tried it out, my third-party-tool now fails for some other (unknown) reason. There was probably some other environment variable I don't know about that's getting lost with the new shell. Fortunately, I found an alternate solution which I'll share for anyone else struggling.
My Solution
-----------
*As far as I can tell, the only difference that entering the virtual environment does to my environment is add a new path to my PATH variable, and add the variable VIRTUAL\_ENV.*
I can replicate the outside-virtual-environment behavior by creating a copy of my environment where I:
* delete that VIRTUAL\_ENV environment variable and
* remove the python prefix from PATH.
Example
-------
### my\_script.py
`my_script.py` Implements my solution:
```
#!/usr/bin/env python
import subprocess, os, sys
env = os.environ.copy()
if hasattr(sys,'real_prefix'):
# If in virtual environment, gotta forge a copy of the environment, where we:
# Delete the VIRTUAL_ENV variable.
del(env['VIRTUAL_ENV'])
# Delete the "/home/me/.python_venv/main/bin:" from the front of my PATH variable.
orig_path = env['PATH']
virtual_env_prefix = sys.prefix + '/bin:'
env['PATH'] = orig_path.replace(virtual_env_prefix, '')
# Pass the environment into the third party tool, modified if and when required.
subprocess.run(['./third-party-tool'], shell=False, env=env)
```
### third-party-tool
`third-party-tool` is mocked out as a script that tells you if it's in a virtual environment and prints out environment variables. In this example, `third-party-tool` is a Python script but in general it might not be.
```
#!/usr/bin/env python
# third-party-tool
import sys, os
in_venv = hasattr(sys, 'real_prefix')
print('This is third-party Tool and you {} in a virtual environment.'.format("ARE" if in_venv else "ARE NOT"))
os.system('env')
```
### Testing
Now I try calling third-party-tool from outside virtual environment, inside virtual environment, and from the python script in the virtual environment, capturing the output.
```
[me@host ~]$ ./third-party-tool > without_venv.txt
# Now I activate virtual environment
(main) [me@host ~]$ ./third-party-tool > within_venv.txt
(main) [me@host ~]$ ./my_script.py > within_venv_from_python.txt
```
Note: the outputs looks like this:
This is third-party Tool and you ARE NOT in a virtual environment.
(Proceeds to pring out a list of KEY=VALUE environment variables)
I use my favorite diff tool and compare the outputs. `within_venv_from_python.txt` is identical to `without_venv.txt`, which is a good sign (in both cases, `third-party-tool` runs with same environment variables, and indicates it is not living in the matrix). After implementing this solution, my actual third-party-tool appears to be working. |
13,661,723 | How can I run online python code that owns/requires a set of modules? (e.g. numpy, matplotlib) Answers/suggestions to questions [2737539](https://stackoverflow.com/questions/2737539/python-3-online-interpreter-shell) and [3356390](https://stackoverflow.com/questions/3356390/is-there-an-online-interpreter-for-python-3) about interpreters in python 3, are not useful because those compilers don't work properly in this case. | 2012/12/01 | [
"https://Stackoverflow.com/questions/13661723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I found one that supports multiple modules, i checked `numpy, scipy, psutil, matplotlib, etc` and all of them are supported. Check out pythonanyware compiler, a sample console is [here](https://www.pythonanywhere.com/try-ipython/), however you can signup for accounts [here](https://www.pythonanywhere.com/pricing/), i believe there is a free version. I remember i used that that online compiler last year and it worked quite well, but for a free account it has certain limits. It also has a bash console, which allows you to run the python files. | You may try this as sandbox, it support numpy as well: <http://ideone.com> |
46,027,022 | I need to create a script that calculates the distance between two coordinates. The issue I'm having though is when I assign the coordinate to object one, it is stored as a string and am unable to convert it to a list or integer/float. How can I convert this into either a list or integer/float? The script and error I get is below.
---
Script:
```
one=input("Enter an x,y coordinate.")
Enter an x,y coordinate. 1,7
int(1,7)
Traceback (most recent call last):
File "<ipython-input-76-67de81c91c02>", line 1, in <module>
int(1,7)
TypeError: int() can't convert non-string with explicit base
``` | 2017/09/03 | [
"https://Stackoverflow.com/questions/46027022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5874828/"
] | You have to convert the entered string to int/float by first splitting the string into the point components, then casting to the appropriate type:
```
x, y = map(float, one.split(','))
```
To keep the entered values as a single custom datatype, named `Point` for example, you can use a [`namedtuple`](https://docs.python.org/3/library/collections.html#collections.namedtuple):
```
from collections import namedtuple
Point = namedtuple('Point', 'x, y')
```
---
Demo:
```
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x, y')
>>> Point(*map(float, '1, 2'.split(',')))
Point(x=1.0, y=2.0)
>>> _.x, _.y
(1.0, 2.0)
``` | Convert the input into the specific type as int or float
Into a list:
```
_list = list(map(int, input("Enter an x,y coordinate.").split(",")))
```
or into variables:
```
a, b = map(int, input("Enter an x,y coordinate.").split(","))
``` |
46,027,022 | I need to create a script that calculates the distance between two coordinates. The issue I'm having though is when I assign the coordinate to object one, it is stored as a string and am unable to convert it to a list or integer/float. How can I convert this into either a list or integer/float? The script and error I get is below.
---
Script:
```
one=input("Enter an x,y coordinate.")
Enter an x,y coordinate. 1,7
int(1,7)
Traceback (most recent call last):
File "<ipython-input-76-67de81c91c02>", line 1, in <module>
int(1,7)
TypeError: int() can't convert non-string with explicit base
``` | 2017/09/03 | [
"https://Stackoverflow.com/questions/46027022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5874828/"
] | You have to convert the entered string to int/float by first splitting the string into the point components, then casting to the appropriate type:
```
x, y = map(float, one.split(','))
```
To keep the entered values as a single custom datatype, named `Point` for example, you can use a [`namedtuple`](https://docs.python.org/3/library/collections.html#collections.namedtuple):
```
from collections import namedtuple
Point = namedtuple('Point', 'x, y')
```
---
Demo:
```
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x, y')
>>> Point(*map(float, '1, 2'.split(',')))
Point(x=1.0, y=2.0)
>>> _.x, _.y
(1.0, 2.0)
``` | After this `one=input("Enter an x,y coordinate.")` the variable **one** contains a string that looks like this `'x, y'` which cannot be converted to `int` as is.
You need to first split the string using `str.split(',')` which will yield a list `[x,y]` then you can iterate through the list and convert each of `x` and `y` to `int` using `map` which applies the `int(..)` function to every element of the list `[x, y]`.
In code, you can do it as follows:
```
one=input("Enter an x,y coordinate.")
x, y = map(int, one.split(','))
```
As a side note, you should consider wrapping the user input with a `try .. except` clause to handle the case where a user inserts non-int input:
```
try:
one=input("Enter an x,y coordinate.")
x, y = map(int, one.split(','))
except Exception as e:
print("Please provide a valid input")
``` |
22,225,666 | Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list.
In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` method. This is because we avoid the burden of expanding the whole list if the space is not enough.
If I'm using python, probably performances are not that relevant in any case, but what is the better way of pre-allocating a list?
I know these possible candidates:
* `[None] * n` → allocating two lists
* `[None for x in range(n)]` — or `xrange` in python2 → building another object
Is one significantly better than the other?
What if we are in the case `n = len(input)`? Since `input` exists already, would `[None for x in input]` have better performances w.r.t. `[None] * len(input)`? | 2014/03/06 | [
"https://Stackoverflow.com/questions/22225666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282614/"
] | In between those two options the first one is clearly better as no Python for loop is involved.
```
>>> %timeit [None] * 100
1000000 loops, best of 3: 469 ns per loop
>>> %timeit [None for x in range(100)]
100000 loops, best of 3: 4.8 us per loop
```
**Update:**
And `list.append` has an [`O(1)` complexity](https://wiki.python.org/moin/TimeComplexity#list) too, it might be a better choice than pre-creating list if you assign the `list.append` method to a variable.
```
>>> n = 10**3
>>> %%timeit
lis = [None]*n
for _ in range(n):
lis[_] = _
...
10000 loops, best of 3: 73.2 us per loop
>>> %%timeit
lis = []
for _ in range(n):
lis.append(_)
...
10000 loops, best of 3: 92.2 us per loop
>>> %%timeit
lis = [];app = lis.append
for _ in range(n):
app(_)
...
10000 loops, best of 3: 59.4 us per loop
>>> n = 10**6
>>> %%timeit
lis = [None]*n
for _ in range(n):
lis[_] = _
...
10 loops, best of 3: 106 ms per loop
>>> %%timeit
lis = []
for _ in range(n):
lis.append(_)
...
10 loops, best of 3: 122 ms per loop
>>> %%timeit
lis = [];app = lis.append
for _ in range(n):
app(_)
...
10 loops, best of 3: 91.8 ms per loop
``` | When you append an item to a list, Python 'over-allocates', see the [source-code](http://svn.python.org/projects/python/trunk/Objects/listobject.c) of the list object. This means that for example when adding 1 item to a list of 8 items, it actually makes room for 8 new items, and uses only the first one of those. The next 7 appends are then 'for free'.
In many languages (e.g. old versions of Matlab, the newer JIT might be better) you are always told that you need to pre-allocate your vectors, since appending during a loop is very expensive. In the worst case, appending of a single item to a list of length `n` can cost `O(n)` time, since you might have to create a bigger list and copy all the existing items over. If you need to do this on every iteration, the overall cost of adding `n` items is `O(n^2)`, ouch. Python's pre-allocation scheme spreads the cost of growing the array over many single appends (see [amortized costs](http://en.wikipedia.org/wiki/Amortized_analysis)), effectively making the cost of a single append `O(1)` and the overall cost of adding `n` items `O(n)`.
Additionally, the overhead of the rest of your Python code is usually so large, that the tiny speedup that can be obtained by pre-allocating is insignificant. So in most cases, simply forget about pre-allocating, unless your profiler tells you that appending to a list is a bottleneck.
The other answers show some profiling of the list preallocation itself, but this is useless. The only thing that matters is profiling your complete code, with all your calculations inside your loop, with and without pre-allocation. If my prediction is right, the difference is so small that the computation time you win is dwarfed by the time spent thinking about, writing and maintaining the extra lines to pre-allocate your list. |
22,225,666 | Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list.
In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` method. This is because we avoid the burden of expanding the whole list if the space is not enough.
If I'm using python, probably performances are not that relevant in any case, but what is the better way of pre-allocating a list?
I know these possible candidates:
* `[None] * n` → allocating two lists
* `[None for x in range(n)]` — or `xrange` in python2 → building another object
Is one significantly better than the other?
What if we are in the case `n = len(input)`? Since `input` exists already, would `[None for x in input]` have better performances w.r.t. `[None] * len(input)`? | 2014/03/06 | [
"https://Stackoverflow.com/questions/22225666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282614/"
] | When you append an item to a list, Python 'over-allocates', see the [source-code](http://svn.python.org/projects/python/trunk/Objects/listobject.c) of the list object. This means that for example when adding 1 item to a list of 8 items, it actually makes room for 8 new items, and uses only the first one of those. The next 7 appends are then 'for free'.
In many languages (e.g. old versions of Matlab, the newer JIT might be better) you are always told that you need to pre-allocate your vectors, since appending during a loop is very expensive. In the worst case, appending of a single item to a list of length `n` can cost `O(n)` time, since you might have to create a bigger list and copy all the existing items over. If you need to do this on every iteration, the overall cost of adding `n` items is `O(n^2)`, ouch. Python's pre-allocation scheme spreads the cost of growing the array over many single appends (see [amortized costs](http://en.wikipedia.org/wiki/Amortized_analysis)), effectively making the cost of a single append `O(1)` and the overall cost of adding `n` items `O(n)`.
Additionally, the overhead of the rest of your Python code is usually so large, that the tiny speedup that can be obtained by pre-allocating is insignificant. So in most cases, simply forget about pre-allocating, unless your profiler tells you that appending to a list is a bottleneck.
The other answers show some profiling of the list preallocation itself, but this is useless. The only thing that matters is profiling your complete code, with all your calculations inside your loop, with and without pre-allocation. If my prediction is right, the difference is so small that the computation time you win is dwarfed by the time spent thinking about, writing and maintaining the extra lines to pre-allocate your list. | Obviously, the first version. Let me explain why.
1. When you do `[None] * n`, Python internally creates a list object of size `n` and it **copies the the same object** (here `None`) (*this is the reason, you should use this method only when you are dealing with immutable objects*) to all the memory locations. So memory allocation is done only once. After that a single iteration through the list to copy the object to all the elements. [`list_repeat`](http://hg.python.org/cpython/file/52256a5861fa/Objects/listobject.c#l545) is the function which corresponds to this type of list creation.
```
# Creates the list of specified size
np = (PyListObject *) PyList_New(size);
....
...
items = np->ob_item;
if (Py_SIZE(a) == 1) {
elem = a->ob_item[0];
for (i = 0; i < n; i++) {
items[i] = elem; // Copies the same item
Py_INCREF(elem);
}
return (PyObject *) np;
}
```
2. When you use a list comprehension to build a list, Python cannot know the actual size of the list being created, so it initially allocates a chunk of memory and a **fresh copy** of the object is stored in the list. When the list grows beyond the allocated length, it has to allocate the memory again and continue with the new object creation and storing that in the list. |
22,225,666 | Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list.
In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` method. This is because we avoid the burden of expanding the whole list if the space is not enough.
If I'm using python, probably performances are not that relevant in any case, but what is the better way of pre-allocating a list?
I know these possible candidates:
* `[None] * n` → allocating two lists
* `[None for x in range(n)]` — or `xrange` in python2 → building another object
Is one significantly better than the other?
What if we are in the case `n = len(input)`? Since `input` exists already, would `[None for x in input]` have better performances w.r.t. `[None] * len(input)`? | 2014/03/06 | [
"https://Stackoverflow.com/questions/22225666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282614/"
] | In between those two options the first one is clearly better as no Python for loop is involved.
```
>>> %timeit [None] * 100
1000000 loops, best of 3: 469 ns per loop
>>> %timeit [None for x in range(100)]
100000 loops, best of 3: 4.8 us per loop
```
**Update:**
And `list.append` has an [`O(1)` complexity](https://wiki.python.org/moin/TimeComplexity#list) too, it might be a better choice than pre-creating list if you assign the `list.append` method to a variable.
```
>>> n = 10**3
>>> %%timeit
lis = [None]*n
for _ in range(n):
lis[_] = _
...
10000 loops, best of 3: 73.2 us per loop
>>> %%timeit
lis = []
for _ in range(n):
lis.append(_)
...
10000 loops, best of 3: 92.2 us per loop
>>> %%timeit
lis = [];app = lis.append
for _ in range(n):
app(_)
...
10000 loops, best of 3: 59.4 us per loop
>>> n = 10**6
>>> %%timeit
lis = [None]*n
for _ in range(n):
lis[_] = _
...
10 loops, best of 3: 106 ms per loop
>>> %%timeit
lis = []
for _ in range(n):
lis.append(_)
...
10 loops, best of 3: 122 ms per loop
>>> %%timeit
lis = [];app = lis.append
for _ in range(n):
app(_)
...
10 loops, best of 3: 91.8 ms per loop
``` | Obviously, the first version. Let me explain why.
1. When you do `[None] * n`, Python internally creates a list object of size `n` and it **copies the the same object** (here `None`) (*this is the reason, you should use this method only when you are dealing with immutable objects*) to all the memory locations. So memory allocation is done only once. After that a single iteration through the list to copy the object to all the elements. [`list_repeat`](http://hg.python.org/cpython/file/52256a5861fa/Objects/listobject.c#l545) is the function which corresponds to this type of list creation.
```
# Creates the list of specified size
np = (PyListObject *) PyList_New(size);
....
...
items = np->ob_item;
if (Py_SIZE(a) == 1) {
elem = a->ob_item[0];
for (i = 0; i < n; i++) {
items[i] = elem; // Copies the same item
Py_INCREF(elem);
}
return (PyObject *) np;
}
```
2. When you use a list comprehension to build a list, Python cannot know the actual size of the list being created, so it initially allocates a chunk of memory and a **fresh copy** of the object is stored in the list. When the list grows beyond the allocated length, it has to allocate the memory again and continue with the new object creation and storing that in the list. |
37,254,610 | ipdb is triggering an import error for me when I run my Django site locally. I'm working on Python 2.7 and within a virtual environment.
`which ipdb` shows the path `(/usr/local/bin/ipdb)`, as does `which ipython`, which surprised me since I thought it should show my venv path (but shouldn't it work if it's global, anyway?). So I tried `pip install --target=/path/to/venv ipdb` and now it shows up in `pip freeze` (which it didn't before) but still gives me an import error.
`which pip` gives `/Users/myname/.virtualenvs/myenv/bin/pip/`
My path: `/Users/myname/.virtualenvs/myenv/bin:/Users/myname/.venvburrito/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/myname/bin:/usr/local/bin`
Sys.path:
`'/Users/myname/Dropbox/myenv', '/Users/myname/.venvburrito/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg', '/Users/myname/.venvburrito/lib/python2.7/site-packages', '/Users/myname/.venvburrito/lib/python2.7/site-packages/setuptools-8.2-py2.7.egg', '/Users/myname/.virtualenvs/myenv/lib/python27.zip', '/Users/myname/.virtualenvs/myenv/lib/python2.7', '/Users/myname/.virtualenvs/myenv/lib/python2.7/plat-darwin', '/Users/myname/.virtualenvs/myenv/lib/python2.7/plat-mac', '/Users/myname/.virtualenvs/myenv/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/myname/.virtualenvs/myenv/Extras/lib/python', '/Users/myname/.virtualenvs/myenv/lib/python2.7/lib-tk', '/Users/myname/.virtualenvs/myenv/lib/python2.7/lib-old', '/Users/myname/.virtualenvs/myenv/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/myname/.virtualenvs/myenv/lib/python2.7/site-packages']`
If I run ipdb from the terminal, it works fine. I've tried restarting my terminal.
Stacktrace:
```
Traceback (most recent call last):
File "/Users/myname/.virtualenvs/myenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/myname/.virtualenvs/myenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/myname/.virtualenvs/myenv/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/myname/.virtualenvs/myenv/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/Users/myname/.virtualenvs/myenv/lib/python2.7/site-packages/django/views/generic/base.py", line 157, in get
context = self.get_context_data(**kwargs)
File "/Users/myname/Dropbox/blog/views.py", line 22, in get_context_data
import ipdb; ipdb.set_trace()
ImportError: No module named ipdb
``` | 2016/05/16 | [
"https://Stackoverflow.com/questions/37254610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695507/"
] | You have Code like below. What ever you don't need just remove it.
```
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
``` | You appears to be using the Javascript version of the Google Places API. Let me know if I've guessed incorrectly!
All you need to do is add `®ion=US` when you load the Google Maps API. E.g.:
```
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places®ion=US">
```
Note that this will still show the country for Autocomplete predictions outside of the United States (which helps disambiguate "Paris, TX" from "Paris, France").
See the section on [Region localization](https://developers.google.com/maps/documentation/javascript/localization#Region) in the Google Maps APIs documentation for more details on this parameter.
If you need even more control over the appearance, you can use the [`AutocompleteService` programmatic API](https://developers.google.com/maps/documentation/javascript/places-autocomplete#place_autocomplete_service) to build your own UI, rather than using the `Autocomplete` control. |
63,012,839 | I'm looking for a fast way to fill a QTableModel with over 10000 rows of data in python.
Iterating over the items in a double for-loop takes over 40 seconds. | 2020/07/21 | [
"https://Stackoverflow.com/questions/63012839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6796677/"
] | You don't need to explicitly add items to a QTableModel, you can build your own model around an existing data structure like a list of lists or a numpy array like below.
```
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
from PyQt5.QtCore import QModelIndex, Qt
import numpy as np
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, data=[[]], parent=None):
super().__init__(parent)
self.data = data
def headerData(self, section: int, orientation: Qt.Orientation, role: int):
if role == QtCore.Qt.DisplayRole:
if orientation == Qt.Horizontal:
return "Column " + str(section)
else:
return "Row " + str(section)
def columnCount(self, parent=None):
return len(self.data[0])
def rowCount(self, parent=None):
return len(self.data)
def data(self, index: QModelIndex, role: int):
if role == QtCore.Qt.DisplayRole:
row = index.row()
col = index.column()
return str(self.data[row][col])
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
# data = [[11, 12, 13, 14, 15],
# [21, 22, 23, 24, 25],
# [31, 32, 33, 34, 35]]
data = np.random.random((10000, 100)) * 100
model = MyTableModel(data)
view = QtWidgets.QTableView()
view.setModel(model)
view.show()
sys.exit(app.exec_())
``` | I would recommend creating a numpy array of QStandardItem and filling the Model using the appendColumn function:
```
start = time.time()
data = np.empty(rows, cols, dtype=object) # generate empty data-Array
#### Fill the data array with strings here ###
items = np.vectorize(QStandardItem)(data) # generate QStandardItem-Array
print(time.time() - start, "seconds to create items")
start = time.time()
# iterate over columns (because we have segneficantly less columns than rows)
for i in range(len(cols)):
self.myQTableModel.appendColumn(items[:,i])
self.myQTableModel.setHorizontalHeaderLabels(headerarray) # set headers
print(time.time()-start, "seconds to load DB")
```
result for 16000 rows and 7 cols:
```
0.346372127532959 seconds to create items
1.1745991706848145 seconds to load DB
``` |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg1, arg2)
```
?
I search a way to make function work like an old print (in Python <3.0), where you don't need to use parentheses. If that's not so simple, is there a way to see the code for "print"? | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
>
> Complex is better than complicated.
>
> Flat is better than nested.
>
> Sparse is better than dense.
>
> Readability counts.
>
> Special cases aren't special enough to break the rules.
>
> Although practicality beats purity.
>
> Errors should never pass silently.
>
> Unless explicitly silenced.
>
> In the face of ambiguity, refuse the temptation to guess.
>
> There should be one-- and preferably only one --obvious way to do it.
>
> Although that way may not be obvious at first unless you're Dutch.
>
> Now is better than never.
>
> Although never is often better than \*right\* now.
>
> If the implementation is hard to explain, it's a bad idea.
>
> If the implementation is easy to explain, it may be a good idea.
>
> Namespaces are one honking great idea -- let's do more of those!
>
>
> | The requirement for braces lies in the Python interpreter and not in the code for the `print` method (or any other method) itself.
(And as eph points out in the comments, `print` is a statement not a method.) |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg1, arg2)
```
?
I search a way to make function work like an old print (in Python <3.0), where you don't need to use parentheses. If that's not so simple, is there a way to see the code for "print"? | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
>
> Complex is better than complicated.
>
> Flat is better than nested.
>
> Sparse is better than dense.
>
> Readability counts.
>
> Special cases aren't special enough to break the rules.
>
> Although practicality beats purity.
>
> Errors should never pass silently.
>
> Unless explicitly silenced.
>
> In the face of ambiguity, refuse the temptation to guess.
>
> There should be one-- and preferably only one --obvious way to do it.
>
> Although that way may not be obvious at first unless you're Dutch.
>
> Now is better than never.
>
> Although never is often better than \*right\* now.
>
> If the implementation is hard to explain, it's a bad idea.
>
> If the implementation is easy to explain, it may be a good idea.
>
> Namespaces are one honking great idea -- let's do more of those!
>
>
> | As you've already been told, the `print` in Python 2.x was not a function, but a statement, like `if` or `for`. It was a "1st class" citizen, with its own special syntax. You are not allowed to create any statement, and all functions must use parentheses (both in Python 2.x and in 3.x). |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg1, arg2)
```
?
I search a way to make function work like an old print (in Python <3.0), where you don't need to use parentheses. If that's not so simple, is there a way to see the code for "print"? | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
>
> Complex is better than complicated.
>
> Flat is better than nested.
>
> Sparse is better than dense.
>
> Readability counts.
>
> Special cases aren't special enough to break the rules.
>
> Although practicality beats purity.
>
> Errors should never pass silently.
>
> Unless explicitly silenced.
>
> In the face of ambiguity, refuse the temptation to guess.
>
> There should be one-- and preferably only one --obvious way to do it.
>
> Although that way may not be obvious at first unless you're Dutch.
>
> Now is better than never.
>
> Although never is often better than \*right\* now.
>
> If the implementation is hard to explain, it's a bad idea.
>
> If the implementation is easy to explain, it may be a good idea.
>
> Namespaces are one honking great idea -- let's do more of those!
>
>
> | No. Function call needs parentheses and two directly consecutive identifiers (that excludes reserved words) are a syntax error. That's set in stone in the grammar and won't change. The only way you could support this is making your own language implementation, at least the frontend of one - that's likely more trouble than it's worth, and would require some significant learning on your side (unless of course you aren't already a parsing expert). See numerous stack overflow questions on compiler construction for material if you want to try it nevertheless. |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg1, arg2)
```
?
I search a way to make function work like an old print (in Python <3.0), where you don't need to use parentheses. If that's not so simple, is there a way to see the code for "print"? | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
>
> Complex is better than complicated.
>
> Flat is better than nested.
>
> Sparse is better than dense.
>
> Readability counts.
>
> Special cases aren't special enough to break the rules.
>
> Although practicality beats purity.
>
> Errors should never pass silently.
>
> Unless explicitly silenced.
>
> In the face of ambiguity, refuse the temptation to guess.
>
> There should be one-- and preferably only one --obvious way to do it.
>
> Although that way may not be obvious at first unless you're Dutch.
>
> Now is better than never.
>
> Although never is often better than \*right\* now.
>
> If the implementation is hard to explain, it's a bad idea.
>
> If the implementation is easy to explain, it may be a good idea.
>
> Namespaces are one honking great idea -- let's do more of those!
>
>
> | What are you trying to do? If you are trying to embed this code into another program (non-python) or invoke from the interpreter somehow, can you use `sys.argv` as an alternative instead? Here is an example of how [sys.argv](http://diveintopython.net/scripts_and_streams/command_line_arguments.html) works. |
48,247,921 | I'm attempting to get the TensorFlow Object Detection API
<https://github.com/tensorflow/models/tree/master/research/object_detection>
working on Windows by following the install instructions
<https://github.com/tensorflow/models/tree/master/research/object_detection>
Which seem to be for Linux/Mac. I can only get this to work if I put a script in the directory I cloned the above repo to. If I put the script in any other directory I get this error:
```
ModuleNotFoundError: No module named 'utils'
```
I suspect that the cause is not properly doing the Windows equivalent of this command listed on the install instructions above:
```
# From tensorflow/models/research/
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
```
I'm using Windows 10, Python 3.6, and TensorFlow 1.4.0 if that matters. Of course, I've Googled on this concern and found various links, for example, this:
<https://github.com/tensorflow/models/issues/1747>
But this has not resolved the concern. Any suggestions on how to resolve this?
Here are the steps I've done so far specifically:
---
EDIT: these steps work now after updating to incorporate RecencyEffect's answer
-------------------------------------------------------------------------------
1) Install TensorFlow and related tools via pip3
2) From an administrative command prompt, run the following:
```
pip3 install pillow
pip3 install lxml
pip3 install jupyter
pip3 install matplotlib
```
3) Clone the TensorFlow "models" repository to the Documents folder, in my case
```
C:\Users\cdahms\Documents\models
```
4) Downloaded Google Protobuf <https://github.com/google/protobuf> Windows v3.4.0 release "protoc-3.4.0-win32.zip" (I tried the most current 3.5.1 and got errors on the subsequent steps, so I tried 3.4.0 per this vid <https://www.youtube.com/watch?v=COlbP62-B-U&list=PLQVvvaa0QuDcNK5GeCQnxYnSSaar2tpku&index=1> and the protobuf compile worked)
5) Extract the Protobuf download to Program Files, specifically
```
"C:\Program Files\protoc-3.4.0-win32"
```
6) CD into the models\research directory, specifically
```
cd C:\Users\cdahms\Documents\models\research
```
7) Executed the protobuf compile, specifically
```
“C:\Program Files\protoc-3.4.0-win32\bin\protoc.exe” object_detection/protos/*.proto --python_out=.
```
Navigate to:
```
C:\Users\cdahms\Documents\models\research\object_detection\protos
```
and verify the .py files were created successfully as a result of the compile (only the .proto files were there to begin with)
8) cd to the object\_detection directory, ex:
```
cd C:\Users\cdahms\Documents\models\research\object_detection
```
then enter the following at a command prompt to start the object\_detection\_tutorial.ipynb Jupyter Notebook
```
jupyter notebook
```
9) In the Jupyter Notebook, choose "object\_detection\_tutorial.ipynb" -> Cell -> Run all, the example should run within the notebook
10) In the Jupyter Notebook, choose “File” -> “Download As” -> “Python”, and save the .py version of the notebook to the same directory, i.e.
```
C:\Users\cdahms\Documents\models\research\object_detection\object_detection_tutorial.py
```
You can now open the script in your chosen Python editor (ex. PyCharm) and run it.
---
EDIT per RecencyEffect's answer below, if you follow these additional steps you will be able to run the object\_detection\_tutorial.py script from any directory
----------------------------------------------------------------------------------------------------------------------------------------------------------------
11) Move the script to any other directory, then attempt to run it and you will find you will get the error:
```
ModuleNotFoundError: No module named 'utils'
```
because we have not yet informed Python how to find the utils directory that these lines use:
```
from utils import label_map_util
from utils import visualization_utils as vis_util
```
To resolve this . . .
12) Go to System -> Advanced system settings -> Environment Variables . . . -> New, and add a variable with the name PYTHONPATH and these values:
[](https://i.stack.imgur.com/vL13P.png)
13) Also under Environment Variables, edit PATH and add %PYTHONPATH% like so:
[](https://i.stack.imgur.com/jdpY3.png)
14) Reboot to make sure these path changes take effect
15) Pull up a command prompt and run the command "set", verify PYTHONPATH is there and PYTHONPATH and PATH contained the values from the previous steps.
16) Now you can copy the "object\_detection\_tutorial.py" to any other directory and it will run | 2018/01/14 | [
"https://Stackoverflow.com/questions/48247921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835204/"
] | As mentioned in the comment, `utils` is a submodule so you actually need to add `object_detection` to `PYTHONPATH`, not `object_detection/utils`.
I'm glad it worked for you. | cd Research/Object\_Detection
cd ..
Research
1. export PATH=~/anaconda3/bin:$PATH
RESEARCH
2. git clone <https://github.com/tensorflow/models.git>
RESEARCH
3.export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
4.protoc object\_detection/protos/string\_int\_label\_map.proto --python\_out=.
CD OBJECT\_DETECTION
5. protoc protos/string\_int\_label\_map.proto --python\_out=.
6.jupyter notebook |
48,247,921 | I'm attempting to get the TensorFlow Object Detection API
<https://github.com/tensorflow/models/tree/master/research/object_detection>
working on Windows by following the install instructions
<https://github.com/tensorflow/models/tree/master/research/object_detection>
Which seem to be for Linux/Mac. I can only get this to work if I put a script in the directory I cloned the above repo to. If I put the script in any other directory I get this error:
```
ModuleNotFoundError: No module named 'utils'
```
I suspect that the cause is not properly doing the Windows equivalent of this command listed on the install instructions above:
```
# From tensorflow/models/research/
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
```
I'm using Windows 10, Python 3.6, and TensorFlow 1.4.0 if that matters. Of course, I've Googled on this concern and found various links, for example, this:
<https://github.com/tensorflow/models/issues/1747>
But this has not resolved the concern. Any suggestions on how to resolve this?
Here are the steps I've done so far specifically:
---
EDIT: these steps work now after updating to incorporate RecencyEffect's answer
-------------------------------------------------------------------------------
1) Install TensorFlow and related tools via pip3
2) From an administrative command prompt, run the following:
```
pip3 install pillow
pip3 install lxml
pip3 install jupyter
pip3 install matplotlib
```
3) Clone the TensorFlow "models" repository to the Documents folder, in my case
```
C:\Users\cdahms\Documents\models
```
4) Downloaded Google Protobuf <https://github.com/google/protobuf> Windows v3.4.0 release "protoc-3.4.0-win32.zip" (I tried the most current 3.5.1 and got errors on the subsequent steps, so I tried 3.4.0 per this vid <https://www.youtube.com/watch?v=COlbP62-B-U&list=PLQVvvaa0QuDcNK5GeCQnxYnSSaar2tpku&index=1> and the protobuf compile worked)
5) Extract the Protobuf download to Program Files, specifically
```
"C:\Program Files\protoc-3.4.0-win32"
```
6) CD into the models\research directory, specifically
```
cd C:\Users\cdahms\Documents\models\research
```
7) Executed the protobuf compile, specifically
```
“C:\Program Files\protoc-3.4.0-win32\bin\protoc.exe” object_detection/protos/*.proto --python_out=.
```
Navigate to:
```
C:\Users\cdahms\Documents\models\research\object_detection\protos
```
and verify the .py files were created successfully as a result of the compile (only the .proto files were there to begin with)
8) cd to the object\_detection directory, ex:
```
cd C:\Users\cdahms\Documents\models\research\object_detection
```
then enter the following at a command prompt to start the object\_detection\_tutorial.ipynb Jupyter Notebook
```
jupyter notebook
```
9) In the Jupyter Notebook, choose "object\_detection\_tutorial.ipynb" -> Cell -> Run all, the example should run within the notebook
10) In the Jupyter Notebook, choose “File” -> “Download As” -> “Python”, and save the .py version of the notebook to the same directory, i.e.
```
C:\Users\cdahms\Documents\models\research\object_detection\object_detection_tutorial.py
```
You can now open the script in your chosen Python editor (ex. PyCharm) and run it.
---
EDIT per RecencyEffect's answer below, if you follow these additional steps you will be able to run the object\_detection\_tutorial.py script from any directory
----------------------------------------------------------------------------------------------------------------------------------------------------------------
11) Move the script to any other directory, then attempt to run it and you will find you will get the error:
```
ModuleNotFoundError: No module named 'utils'
```
because we have not yet informed Python how to find the utils directory that these lines use:
```
from utils import label_map_util
from utils import visualization_utils as vis_util
```
To resolve this . . .
12) Go to System -> Advanced system settings -> Environment Variables . . . -> New, and add a variable with the name PYTHONPATH and these values:
[](https://i.stack.imgur.com/vL13P.png)
13) Also under Environment Variables, edit PATH and add %PYTHONPATH% like so:
[](https://i.stack.imgur.com/jdpY3.png)
14) Reboot to make sure these path changes take effect
15) Pull up a command prompt and run the command "set", verify PYTHONPATH is there and PYTHONPATH and PATH contained the values from the previous steps.
16) Now you can copy the "object\_detection\_tutorial.py" to any other directory and it will run | 2018/01/14 | [
"https://Stackoverflow.com/questions/48247921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835204/"
] | As mentioned in the comment, `utils` is a submodule so you actually need to add `object_detection` to `PYTHONPATH`, not `object_detection/utils`.
I'm glad it worked for you. | The following command does not work on Windows:
```
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
```
Instead, I followed the directions of this [tutorial](https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10), which recommends setting the path variables for three different directories manually. I simply added a path for the utils directory as well. So far it has worked without error. |
48,247,921 | I'm attempting to get the TensorFlow Object Detection API
<https://github.com/tensorflow/models/tree/master/research/object_detection>
working on Windows by following the install instructions
<https://github.com/tensorflow/models/tree/master/research/object_detection>
Which seem to be for Linux/Mac. I can only get this to work if I put a script in the directory I cloned the above repo to. If I put the script in any other directory I get this error:
```
ModuleNotFoundError: No module named 'utils'
```
I suspect that the cause is not properly doing the Windows equivalent of this command listed on the install instructions above:
```
# From tensorflow/models/research/
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
```
I'm using Windows 10, Python 3.6, and TensorFlow 1.4.0 if that matters. Of course, I've Googled on this concern and found various links, for example, this:
<https://github.com/tensorflow/models/issues/1747>
But this has not resolved the concern. Any suggestions on how to resolve this?
Here are the steps I've done so far specifically:
---
EDIT: these steps work now after updating to incorporate RecencyEffect's answer
-------------------------------------------------------------------------------
1) Install TensorFlow and related tools via pip3
2) From an administrative command prompt, run the following:
```
pip3 install pillow
pip3 install lxml
pip3 install jupyter
pip3 install matplotlib
```
3) Clone the TensorFlow "models" repository to the Documents folder, in my case
```
C:\Users\cdahms\Documents\models
```
4) Downloaded Google Protobuf <https://github.com/google/protobuf> Windows v3.4.0 release "protoc-3.4.0-win32.zip" (I tried the most current 3.5.1 and got errors on the subsequent steps, so I tried 3.4.0 per this vid <https://www.youtube.com/watch?v=COlbP62-B-U&list=PLQVvvaa0QuDcNK5GeCQnxYnSSaar2tpku&index=1> and the protobuf compile worked)
5) Extract the Protobuf download to Program Files, specifically
```
"C:\Program Files\protoc-3.4.0-win32"
```
6) CD into the models\research directory, specifically
```
cd C:\Users\cdahms\Documents\models\research
```
7) Executed the protobuf compile, specifically
```
“C:\Program Files\protoc-3.4.0-win32\bin\protoc.exe” object_detection/protos/*.proto --python_out=.
```
Navigate to:
```
C:\Users\cdahms\Documents\models\research\object_detection\protos
```
and verify the .py files were created successfully as a result of the compile (only the .proto files were there to begin with)
8) cd to the object\_detection directory, ex:
```
cd C:\Users\cdahms\Documents\models\research\object_detection
```
then enter the following at a command prompt to start the object\_detection\_tutorial.ipynb Jupyter Notebook
```
jupyter notebook
```
9) In the Jupyter Notebook, choose "object\_detection\_tutorial.ipynb" -> Cell -> Run all, the example should run within the notebook
10) In the Jupyter Notebook, choose “File” -> “Download As” -> “Python”, and save the .py version of the notebook to the same directory, i.e.
```
C:\Users\cdahms\Documents\models\research\object_detection\object_detection_tutorial.py
```
You can now open the script in your chosen Python editor (ex. PyCharm) and run it.
---
EDIT per RecencyEffect's answer below, if you follow these additional steps you will be able to run the object\_detection\_tutorial.py script from any directory
----------------------------------------------------------------------------------------------------------------------------------------------------------------
11) Move the script to any other directory, then attempt to run it and you will find you will get the error:
```
ModuleNotFoundError: No module named 'utils'
```
because we have not yet informed Python how to find the utils directory that these lines use:
```
from utils import label_map_util
from utils import visualization_utils as vis_util
```
To resolve this . . .
12) Go to System -> Advanced system settings -> Environment Variables . . . -> New, and add a variable with the name PYTHONPATH and these values:
[](https://i.stack.imgur.com/vL13P.png)
13) Also under Environment Variables, edit PATH and add %PYTHONPATH% like so:
[](https://i.stack.imgur.com/jdpY3.png)
14) Reboot to make sure these path changes take effect
15) Pull up a command prompt and run the command "set", verify PYTHONPATH is there and PYTHONPATH and PATH contained the values from the previous steps.
16) Now you can copy the "object\_detection\_tutorial.py" to any other directory and it will run | 2018/01/14 | [
"https://Stackoverflow.com/questions/48247921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835204/"
] | As mentioned in the comment, `utils` is a submodule so you actually need to add `object_detection` to `PYTHONPATH`, not `object_detection/utils`.
I'm glad it worked for you. | Make sure you have a `__init__.py` file in your research/object\_detection/protos folder! The `__init__.py` file is empty but needs to exist for the protos module to be created correctly. |
19,819,443 | I'm writing a code in Python. Within the code, a blackbox application written in c++ is called. Sometimes this c++ application does not converge and an error message come up. This error does not terminate the Python code, but it pause the run. After clicking ok for the error message, the python code continues running till either the end of the code or the message comes up again. Is there a way to handle this problem within Python: the code detects the message and clicks ok?
Thanks | 2013/11/06 | [
"https://Stackoverflow.com/questions/19819443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961551/"
] | I believe that in your case Python program doesn't actually continue the execution, unless the program started as a subprocess completes - this is the behaviour or [subprocess.check\_call](http://docs.python.org/2/library/subprocess.html#subprocess.check_call) which you say is used to start the subprocess.
As long as you start a subprocess with `check_call`, there is pretty much no way to find out the intermediate subprocess state, until it actually terminates and you get the exit code.
So, instead you may use [subprocess.Popen()](http://docs.python.org/2/library/subprocess.html#subprocess.Popen) constructor to create a [Popen](http://docs.python.org/2/library/subprocess.html#popen-objects) object, which starts the subprocess, but doesn't wait for subprocess to complete. This way you can verify the subprocess state implicitly by checking its other outputs, if any hopefully exist for it (for example you may as well read subprocess output if you know it writes its errors or other messages to stdout or stderr).
P.S. Better solution - fix the C++ program. | Timur is correct. Unless the C++ program explicitly provides a way for you to check the status, respond to the dialog, or make it run without showing the dialog, there is nothing built into python that can solve this problem as far as i know.
There are some workarounds that might work for you, though. Depending on your platform, you could use a window manager extension module (like pywin32 or python-xlib) to search for the dialog box and programatically click the Ok.
If you can use Jython, you can use [Sikuli](http://www.sikuli.org/), which is a very nice, easy to use visual automation package. |
15,106,713 | I've searched the databases and cookbooks but can't seem to find the right answer. I have a very simple python code which sums up self powers in a range. I need the last ten digits of this very, very large number and I've tried the getcontext().prec however I'm still hitting a limit.
Here's the code:
```
def SelfPowers(n):
total = 0
for i in range(1,n):
total += (i**i)
return(total)
print SelfPowers(n)
```
How can I see all those beautiful numbers? It prints relatively fast on my quad-core. This is just for fun for ProjectEuler, Problem #48, no spoilers please I DO NOT WANT THE SOLUTION and I don't want the work done for me, so if you could point me in the right direction please?
Thanks,
mp | 2013/02/27 | [
"https://Stackoverflow.com/questions/15106713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2082350/"
] | If you want the *last ten digits* of a number, don't compute the whole thing (it will take too much memory and time).
Instead, consider using the "three-argument" form of `pow` to compute powers mod a specific base, and you will find the problem is much easier. | Testing on Python 3.2 I was able to
```
print(SelfPowers(10000))
```
though it took some seconds. How large a number were you thinking?
**Edit:** It looks like you want to use `1000`? In such case, upgrade to Python 3 and you should be fine. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think I find a solution, but If there something better pls, let me know...
I add `this.dialogRef.closeAll()`
```
class UserEffects {
constructor(
private actions$: Actions,
private dialogRef: MatDialog,
private notificationService: NotificationService,
) {}
@Effect()
addNewUser$ = this.actions$.pipe(
ofType(actions.UserActionTypes.addNewUser),
mergeMap((user: actions.addNewUser) =>
this.userService.createUser(user.user).pipe(
map(() => {
new actions.LoadUsers(),
this.notificationService.success("User added successfully!");
this.dialogRef.closeAll(); <--- //this is the key
}),
catchError(error => of(new actions.Error(error.error)))
)
));
}
```
EDIT:
modal is closed, but I get error
>
> core.js:6014 ERROR Error: Effect "UserEffects.addNewUser$" dispatched an invalid action: undefined
>
>
> TypeError: Actions must be objects
>
>
>
Any help? Thnx | In the constructor of your `@Effect`, you need to provide the dependency:
```
private dialogRef: MatDialogRef<MyDialogComponentToClose>
```
And you need to import `MatDialogModule` inside your module where your effect is. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } | In the constructor of your `@Effect`, you need to provide the dependency:
```
private dialogRef: MatDialogRef<MyDialogComponentToClose>
```
And you need to import `MatDialogModule` inside your module where your effect is. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think the best solution to closing dialog is subscribing to the effect variable
ie
```
// close the dialog
// Inside the dialog component
this.userEffects.addNewUser$.pipe(
ofType(Actions.LoadUsers)
).subscribe(_ => this.matDialogRef.close());
``` | In the constructor of your `@Effect`, you need to provide the dependency:
```
private dialogRef: MatDialogRef<MyDialogComponentToClose>
```
And you need to import `MatDialogModule` inside your module where your effect is. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think I find a solution, but If there something better pls, let me know...
I add `this.dialogRef.closeAll()`
```
class UserEffects {
constructor(
private actions$: Actions,
private dialogRef: MatDialog,
private notificationService: NotificationService,
) {}
@Effect()
addNewUser$ = this.actions$.pipe(
ofType(actions.UserActionTypes.addNewUser),
mergeMap((user: actions.addNewUser) =>
this.userService.createUser(user.user).pipe(
map(() => {
new actions.LoadUsers(),
this.notificationService.success("User added successfully!");
this.dialogRef.closeAll(); <--- //this is the key
}),
catchError(error => of(new actions.Error(error.error)))
)
));
}
```
EDIT:
modal is closed, but I get error
>
> core.js:6014 ERROR Error: Effect "UserEffects.addNewUser$" dispatched an invalid action: undefined
>
>
> TypeError: Actions must be objects
>
>
>
Any help? Thnx | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think I find a solution, but If there something better pls, let me know...
I add `this.dialogRef.closeAll()`
```
class UserEffects {
constructor(
private actions$: Actions,
private dialogRef: MatDialog,
private notificationService: NotificationService,
) {}
@Effect()
addNewUser$ = this.actions$.pipe(
ofType(actions.UserActionTypes.addNewUser),
mergeMap((user: actions.addNewUser) =>
this.userService.createUser(user.user).pipe(
map(() => {
new actions.LoadUsers(),
this.notificationService.success("User added successfully!");
this.dialogRef.closeAll(); <--- //this is the key
}),
catchError(error => of(new actions.Error(error.error)))
)
));
}
```
EDIT:
modal is closed, but I get error
>
> core.js:6014 ERROR Error: Effect "UserEffects.addNewUser$" dispatched an invalid action: undefined
>
>
> TypeError: Actions must be objects
>
>
>
Any help? Thnx | You could listen to `actions$: Actions` in your dialog component, subscribe to it and close the dialog when the action is triggered, without recurring to NgRx effects and needing to inject all the dialogs references.
Your dialog component's constructor would include, among other things:
```js
constructor(
public dialogRef: MatDialogRef<YourDialogComponent>,
private readonly actions$: Actions) {}
```
In `ngOnInit` you'd listen to the relevant action meant to close the dialog. I generally rely on `ngOnDestroy` to unsubscribe from observables.
```js
private readonly subscription = new Subscription();
ngOnInit(): void {
this.subscription.add(
this.actions$
.pipe(ofType(actions.UserActionTypes.LoadUsers))
.subscribe(() => this.dialogRef.close())
);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
```
Pay attention to the action you're listening to; it must be one triggered by the `addNewUser$` effect, which seems to be `new actions.LoadUsers()` in your case. The common pattern is to follow an `addNewUser` action with an `addNewUserSuccess` or `addNewUserFailure`.
You may have several error dialogs popping up at the same time. This approach allows one to manage concurrent dialogs made of different components: `closeAll()` will (unsurprisingly) close all the material dialogs. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } | You could listen to `actions$: Actions` in your dialog component, subscribe to it and close the dialog when the action is triggered, without recurring to NgRx effects and needing to inject all the dialogs references.
Your dialog component's constructor would include, among other things:
```js
constructor(
public dialogRef: MatDialogRef<YourDialogComponent>,
private readonly actions$: Actions) {}
```
In `ngOnInit` you'd listen to the relevant action meant to close the dialog. I generally rely on `ngOnDestroy` to unsubscribe from observables.
```js
private readonly subscription = new Subscription();
ngOnInit(): void {
this.subscription.add(
this.actions$
.pipe(ofType(actions.UserActionTypes.LoadUsers))
.subscribe(() => this.dialogRef.close())
);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
```
Pay attention to the action you're listening to; it must be one triggered by the `addNewUser$` effect, which seems to be `new actions.LoadUsers()` in your case. The common pattern is to follow an `addNewUser` action with an `addNewUserSuccess` or `addNewUserFailure`.
You may have several error dialogs popping up at the same time. This approach allows one to manage concurrent dialogs made of different components: `closeAll()` will (unsurprisingly) close all the material dialogs. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think the best solution to closing dialog is subscribing to the effect variable
ie
```
// close the dialog
// Inside the dialog component
this.userEffects.addNewUser$.pipe(
ofType(Actions.LoadUsers)
).subscribe(_ => this.matDialogRef.close());
``` | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
TypeError: function takes exactly 1 argument (3 given)
```
Expected text file output as below
```
item1 111 2.00
item2 222 5.00
item3 444 1.00
item4 666 5.00
item5 212 7.00
```
Please advise further. Thanks
**Both solution below works one for python2.7 and python3.6 above** | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think the best solution to closing dialog is subscribing to the effect variable
ie
```
// close the dialog
// Inside the dialog component
this.userEffects.addNewUser$.pipe(
ofType(Actions.LoadUsers)
).subscribe(_ => this.matDialogRef.close());
``` | You could listen to `actions$: Actions` in your dialog component, subscribe to it and close the dialog when the action is triggered, without recurring to NgRx effects and needing to inject all the dialogs references.
Your dialog component's constructor would include, among other things:
```js
constructor(
public dialogRef: MatDialogRef<YourDialogComponent>,
private readonly actions$: Actions) {}
```
In `ngOnInit` you'd listen to the relevant action meant to close the dialog. I generally rely on `ngOnDestroy` to unsubscribe from observables.
```js
private readonly subscription = new Subscription();
ngOnInit(): void {
this.subscription.add(
this.actions$
.pipe(ofType(actions.UserActionTypes.LoadUsers))
.subscribe(() => this.dialogRef.close())
);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
```
Pay attention to the action you're listening to; it must be one triggered by the `addNewUser$` effect, which seems to be `new actions.LoadUsers()` in your case. The common pattern is to follow an `addNewUser` action with an `addNewUserSuccess` or `addNewUserFailure`.
You may have several error dialogs popping up at the same time. This approach allows one to manage concurrent dialogs made of different components: `closeAll()` will (unsurprisingly) close all the material dialogs. |
49,440,741 | I have a python code base where I have refactored a module (file) into a package (directory) as the file was getting a bit large and unmanageable. However, I cannot get my unit tests running as desired with the new structure.
I place my unit test files directly alongside the code it tests (this is a requirement and cannot change - no separate `test` directories):
```
app/
+-- app.py
+-- config.py
+-- config_test.py
+-- model/
| +-- __init__.py
| +-- base.py
| +-- base_test.py
| +-- square.py
| +-- square_test.py
+-- test.py
+-- web.py
+-- web_test.py
```
Previously, the `model` package was the `model.py` module with a `model_test.py` test suite.
There is a top-level test runner - `test.py` and that works fine. It finds the test cases inside the `model` directory and runs them successfully (it uses the `discovery` feature of `unittest` - see end of post for `test.py`):
```
$ python test.py
```
However, I also want to be able to directly run the test cases in the `model` directory:
```
$ python model/base_test.py
```
This does not work, because the test is inside the package directory. The imports in the code fail because they are either not in a module when imported directly by the test suite or the search path is wrong.
For instance, in `model/square.py`, I can import `base.py` in one of two ways:
```
from model import Base
```
or
```
from .base import Base
```
These both work fine when `model` is imported. But when inside the `model` test suites, I cannot import `square` because `square` cannot import `base`.
`square_test.py` contains imports like:
```
import unittest
from square import Square
... test cases ...
if __name__ == '__main__':
unittest.main()
```
For the first type of import in `square.py` (`from model import Base`), I get the error:
```
ModuleNotFoundError: No module named 'model'
```
Fair enough, `sys.path` has `/home/camh/app/model` and there is no `model` module in there.
For the second type of import in `square.py` (`from .base import Base`), I get the error:
```
ImportError: attempted relative import with no known parent package
```
I cannot figure out how to do my imports that allows me to have tests alongside the unit-under-test and be directly runnable. I want directly runnable test suites as often I do not want to run the entire set of tests, but just target individual tests:
```
$ python model/square_test.py SquareTest.test_equal_sides
```
I cannot do that with my test runner because it just uses discovery to run all the tests and discovery is not compatible with specifying individual test suites or test functions.
My test runner (`test.py`) is just:
```
import os, sys
sys.argv += ['discover', os.path.dirname(sys.argv[0]), '*_test.py']
unittest.main(module=None)
``` | 2018/03/23 | [
"https://Stackoverflow.com/questions/49440741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23744/"
] | You can invoke the `unittest` module from the command line with arguments:
```
python -m unittest model.square_test
```
If you are using python3 you can use file names too:
```
python3 -m unittest model/square_test.py
``` | suggestions:
add `app/__init__.py`, and treat `app` as package instead of `model`
one way is for all tests, using explicit `from app.model.square import Square`
The relative import should be fine, as long as using `nosetests -vw .` in `app/` directory.
These all under the price of removing `app/test.py`
Another common mistake after re-factoring, is the `.pyc` not all removed and re-generated. |
30,314,368 | I have a CSV file that looks something like this:
```
2014-6-06 08:03:19, 439105, 1053224, Front Entrance
2014-6-06 09:43:21, 439105, 1696241, Main Exit
2014-6-06 10:01:54, 1836139, 1593258, Back Archway
2014-6-06 11:34:26, 845646, external, Exit
2014-6-06 04:45:13, 1464748, 439105, Side Exit
```
I was wondering how to delete a line if it includes the word "external"?
I saw another [post](https://stackoverflow.com/questions/21970932/remove-line-from-file-if-containing-word-from-another-txt-file-in-python-bash) on SO that addressed a very similar issue, but I don't understand completely...
I tried to use something like this (as explained in the linked post):
```
TXT_file = 'whatYouWantRemoved.txt'
CSV_file = 'comm-data-Fri.csv'
OUT_file = 'OUTPUT.csv'
## From the TXT, create a list of domains you do not want to include in output
with open(TXT_file, 'r') as txt:
domain_to_be_removed_list = []
## for each domain in the TXT
## remove the return character at the end of line
## and add the domain to list domains-to-be-removed list
for domain in txt:
domain = domain.rstrip()
domain_to_be_removed_list.append(domain)
with open(OUT_file, 'w') as outfile:
with open(CSV_file, 'r') as csv:
## for each line in csv
## extract the csv domain
for line in csv:
csv_domain = line.split(',')[0]
## if csv domain is not in domains-to-be-removed list,
## then write that to outfile
if (csv_domain not in domain_to_be_removed_list):
outfile.write(line)
```
The text file just held the one word "external" but it didn't work.... and I don't understand why.
What happens is that the program will run, and the output.txt will be generated, but nothing will change, and no lines with "external" are taken out.
I'm using Windows and python 3.4 if it makes a difference.
Sorry if this seems like a really simple question, but I'm new to python and any help in this area would be greatly appreciated, thanks!! | 2015/05/18 | [
"https://Stackoverflow.com/questions/30314368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4573703/"
] | It looks like you are grabbing the first element after you split the line. That is going to give you the date, according to your example CSV file.
What you probably want instead (again, assuming the example is the way it will always work) is to grab the 3rd element, so something like this:
```
csv_domain = line.split(',')[2]
```
But, like one of the comments said, this isn't necessarily fool proof. You are assuming none of the individual cells will have commas. Based on your example that might be a safe assumption, but in general when working with CSV files I recommend working with the [Python csv module](https://docs.python.org/3/library/csv.html). | if you can go with something else then python, grep would work like this:
```
grep file.csv "some regex" > newfile.csv
```
would give you ONLY the lines that match the regex, while:
```
grep -v file.csv "some regex" > newfile.csv
```
gives everything BUT the lines matching the regex |
30,314,368 | I have a CSV file that looks something like this:
```
2014-6-06 08:03:19, 439105, 1053224, Front Entrance
2014-6-06 09:43:21, 439105, 1696241, Main Exit
2014-6-06 10:01:54, 1836139, 1593258, Back Archway
2014-6-06 11:34:26, 845646, external, Exit
2014-6-06 04:45:13, 1464748, 439105, Side Exit
```
I was wondering how to delete a line if it includes the word "external"?
I saw another [post](https://stackoverflow.com/questions/21970932/remove-line-from-file-if-containing-word-from-another-txt-file-in-python-bash) on SO that addressed a very similar issue, but I don't understand completely...
I tried to use something like this (as explained in the linked post):
```
TXT_file = 'whatYouWantRemoved.txt'
CSV_file = 'comm-data-Fri.csv'
OUT_file = 'OUTPUT.csv'
## From the TXT, create a list of domains you do not want to include in output
with open(TXT_file, 'r') as txt:
domain_to_be_removed_list = []
## for each domain in the TXT
## remove the return character at the end of line
## and add the domain to list domains-to-be-removed list
for domain in txt:
domain = domain.rstrip()
domain_to_be_removed_list.append(domain)
with open(OUT_file, 'w') as outfile:
with open(CSV_file, 'r') as csv:
## for each line in csv
## extract the csv domain
for line in csv:
csv_domain = line.split(',')[0]
## if csv domain is not in domains-to-be-removed list,
## then write that to outfile
if (csv_domain not in domain_to_be_removed_list):
outfile.write(line)
```
The text file just held the one word "external" but it didn't work.... and I don't understand why.
What happens is that the program will run, and the output.txt will be generated, but nothing will change, and no lines with "external" are taken out.
I'm using Windows and python 3.4 if it makes a difference.
Sorry if this seems like a really simple question, but I'm new to python and any help in this area would be greatly appreciated, thanks!! | 2015/05/18 | [
"https://Stackoverflow.com/questions/30314368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4573703/"
] | It looks like you are grabbing the first element after you split the line. That is going to give you the date, according to your example CSV file.
What you probably want instead (again, assuming the example is the way it will always work) is to grab the 3rd element, so something like this:
```
csv_domain = line.split(',')[2]
```
But, like one of the comments said, this isn't necessarily fool proof. You are assuming none of the individual cells will have commas. Based on your example that might be a safe assumption, but in general when working with CSV files I recommend working with the [Python csv module](https://docs.python.org/3/library/csv.html). | Redirect output to a new file. It will give you every line, except those that contain "external"
```
import sys
import re
f = open('sum.csv', "r")
lines = f.readlines()
p = re.compile('external')
for line in lines:
if(p.search(line)):
continue
else:
sys.stdout.write(line)
``` |
52,870,674 | When I execute the following command I get the below error from Tensorflow "missing file or folder". I've checked all online solutions for this error, but nothing is resolving my error.
`python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record`
**The error:**
>
>
> ```
> File "generate_tfrecord.py", line 110, in
> tf.app.run()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
> _sys.exit(main(argv))
> File "generate_tfrecord.py", line 101, in main
> tf_example = create_tf_example(group, path)
> File "generate_tfrecord.py", line 56, in create_tf_example
> encoded_jpg = fid.read()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 125, in read
> self._preread_check()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 85, in _preread_check
> compat.as_bytes(self.__name), 1024 * 512, status)
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 519, in exit
> c_api.TF_GetCode(self.status.status))
> tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: C:\tensorflowc\models\research\object_detection\images\train\tr1138a1a1_3_lar : The system cannot find the file specified.
> ; No such file or directory
>
> ```
>
> | 2018/10/18 | [
"https://Stackoverflow.com/questions/52870674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9933958/"
] | I resolved the problem
If you are making `.CSV file` using a `xml_to_csv file.py`,
you have to check the file extension such as .jpg, .png, .jpeg in `train_labels.csv` file.
In my case, the xtension names won't be there !
[](https://i.stack.imgur.com/JtuNs.png)
**Solution:**
add the extensions like below example and run following command:
```
python generate_tfrecord.py
--csv_input=images\train_labels.csv
--image_dir=images\train
--output_path=train.record
```
It will work ! | My csv-file contained imagenames with jpg extension and I still had this error OP posted. I tried solving it with:
```
python3 generate_tf_record.py --csv_input=data/train_labels.csv --output_path=train.record
python3 generate_tf_record.py --csv_input=data/test_labels.csv --output_path=test.record
```
All images were in one folder and flags as shown below:
```
flags.DEFINE_string('csv_input', '','data/train_labels.csv')
flags.DEFINE_string('output_path','', 'train.record')
flags.DEFINE_string('image_dir', '', 'images')
```
The problem was resolved when I copied the saved record file from the main folder to the data folder. |
52,870,674 | When I execute the following command I get the below error from Tensorflow "missing file or folder". I've checked all online solutions for this error, but nothing is resolving my error.
`python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record`
**The error:**
>
>
> ```
> File "generate_tfrecord.py", line 110, in
> tf.app.run()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
> _sys.exit(main(argv))
> File "generate_tfrecord.py", line 101, in main
> tf_example = create_tf_example(group, path)
> File "generate_tfrecord.py", line 56, in create_tf_example
> encoded_jpg = fid.read()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 125, in read
> self._preread_check()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 85, in _preread_check
> compat.as_bytes(self.__name), 1024 * 512, status)
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 519, in exit
> c_api.TF_GetCode(self.status.status))
> tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: C:\tensorflowc\models\research\object_detection\images\train\tr1138a1a1_3_lar : The system cannot find the file specified.
> ; No such file or directory
>
> ```
>
> | 2018/10/18 | [
"https://Stackoverflow.com/questions/52870674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9933958/"
] | I resolved the problem
If you are making `.CSV file` using a `xml_to_csv file.py`,
you have to check the file extension such as .jpg, .png, .jpeg in `train_labels.csv` file.
In my case, the xtension names won't be there !
[](https://i.stack.imgur.com/JtuNs.png)
**Solution:**
add the extensions like below example and run following command:
```
python generate_tfrecord.py
--csv_input=images\train_labels.csv
--image_dir=images\train
--output_path=train.record
```
It will work ! | i was running into the same issue, and no amount of checking the file path (relative or absolute) was working for me. my directory was organized to have images files and xmls in the same folder. the problem came down to the return statement of the split function inside generate\_tfrecord.py not having a file extension after the filename it is looking at:
```
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
```
**IF** your train and test folders contain images and xmls in the same folder, i would recommend making this edit to the generate\_tfrecord.py file:
```
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename + '.jpg', gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
```
only after making this edit did the script run for me successfully. |
52,870,674 | When I execute the following command I get the below error from Tensorflow "missing file or folder". I've checked all online solutions for this error, but nothing is resolving my error.
`python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record`
**The error:**
>
>
> ```
> File "generate_tfrecord.py", line 110, in
> tf.app.run()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run
> _sys.exit(main(argv))
> File "generate_tfrecord.py", line 101, in main
> tf_example = create_tf_example(group, path)
> File "generate_tfrecord.py", line 56, in create_tf_example
> encoded_jpg = fid.read()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 125, in read
> self._preread_check()
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 85, in _preread_check
> compat.as_bytes(self.__name), 1024 * 512, status)
> File "C:\anaconda3\envs\tensorflowc\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 519, in exit
> c_api.TF_GetCode(self.status.status))
> tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: C:\tensorflowc\models\research\object_detection\images\train\tr1138a1a1_3_lar : The system cannot find the file specified.
> ; No such file or directory
>
> ```
>
> | 2018/10/18 | [
"https://Stackoverflow.com/questions/52870674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9933958/"
] | My csv-file contained imagenames with jpg extension and I still had this error OP posted. I tried solving it with:
```
python3 generate_tf_record.py --csv_input=data/train_labels.csv --output_path=train.record
python3 generate_tf_record.py --csv_input=data/test_labels.csv --output_path=test.record
```
All images were in one folder and flags as shown below:
```
flags.DEFINE_string('csv_input', '','data/train_labels.csv')
flags.DEFINE_string('output_path','', 'train.record')
flags.DEFINE_string('image_dir', '', 'images')
```
The problem was resolved when I copied the saved record file from the main folder to the data folder. | i was running into the same issue, and no amount of checking the file path (relative or absolute) was working for me. my directory was organized to have images files and xmls in the same folder. the problem came down to the return statement of the split function inside generate\_tfrecord.py not having a file extension after the filename it is looking at:
```
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
```
**IF** your train and test folders contain images and xmls in the same folder, i would recommend making this edit to the generate\_tfrecord.py file:
```
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename + '.jpg', gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
```
only after making this edit did the script run for me successfully. |
51,505,249 | ```
list = [1,2,,3,4,5,6,1,2,56,78,45,90,34]
range = ["0-25","25-50","50-75","75-100"]
```
I am coding in python. I want to sort a list of integers in range of numbers and store them in differrent lists.How can i do it?
I have specified my ranges in the the range list. | 2018/07/24 | [
"https://Stackoverflow.com/questions/51505249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10033784/"
] | Create a dictionary with max-value of each *bin* as key. Iterate through your numbers and append them to the list that's the value of each *bin-key*:
```
l = [1,2,3,4,5,6,1,2,56,78,45,90,34]
# your range covers 25 a piece - and share start/endvalues.
# I presume [0-25[ ranges
def inRanges(data,maxValues):
"""Sorts elements of data into bins that have a max-value. Max-values are
given by the list maxValues which holds the exclusive upper bound of the bins."""
d = {k:[] for k in maxValues} # init all keys to empty lists
for n in data:
key = min(x for x in maxValues if x>n) # get key
d[key].append(n) # add number
return d
sortEm = inRanges(l,[25,50,75,100])
print(sortEm)
print([ x for x in sortEm.values()])
```
Output:
```
{25: [1, 2, 3, 4, 5, 6, 1, 2], 50: [25, 45, 34],
75: [56], 100: [78, 90]}
[[1, 2, 3, 4, 5, 6, 1, 2], [25, 45, 34], [56], [78, 90]]
``` | Another stable bin approach for your special case (regular intervaled bins) would be to use a calculated key - this would get rid of the key-search in each step.
Stable search means the order of numbers in the list is the same as in the input data:
```
def inRegularIntervals(data, interval):
"""Sorts elements of data into bins of regular sizes.
The size of each bin is given by 'interval'."""
# init dict so keys are ordered - collection.defaultdict(list)
# would be faster - but this works for lists of a couple of
# thousand numbers if you have a quarter up to one second ...
# if random key order is ok, shorten this to d = {}
d = {k:[] for k in range(0, max(data), interval)}
for n in data:
key = n // interval # get key
key *= interval
d.setdefault(key, [])
d[key ].append(n) # add number
return d
```
Use on random data:
```
from random import choices
data = choices(range(100), k = 50)
data.append(135) # add a bigger value to see the gapped keys
binned = inRegularIntervals(data, 25)
print(binned)
```
Output (\n and spaces added):
```
{ 0: [19, 9, 1, 0, 15, 22, 4, 9, 12, 7, 12, 9, 16, 2, 7],
25: [25, 31, 37, 45, 30, 48, 44, 44, 31, 39, 27, 36],
50: [50, 50, 58, 60, 70, 69, 53, 53, 67, 59, 52, 64],
75: [86, 93, 78, 93, 99, 98, 95, 75, 88, 82, 79],
100: [],
125: [135], }
```
---
To sort the binned lists in place, use
```
for k in binned:
binned[k].sort()
```
to get:
```
{ 0: [0, 1, 2, 4, 7, 7, 9, 9, 9, 12, 12, 15, 16, 19, 22],
25: [25, 27, 30, 31, 31, 36, 37, 39, 44, 44, 45, 48],
50: [50, 50, 52, 53, 53, 58, 59, 60, 64, 67, 69, 70],
75: [75, 78, 79, 82, 86, 88, 93, 93, 95, 98, 99],
100: [],
125: [135]}
``` |
30,513,482 | I'm trying to export two overloaded functions to Python. So I first define the pointers to these functions and then I use them to expose the functions to Python.
```
BOOST_PYTHON_MODULE(mylib){
// First define pointers to overloaded function
double (*expt_pseudopot02_v1)(double,double,double,const VECTOR&,
int,int,int,double,const VECTOR&,
int,int,int,double,const VECTOR& ) = &pseudopot02;
boost::python::list (*expt_pseudopot02_v2)(double, double, double, const VECTOR&,
int,int,int,double, const VECTOR&,
int,int,int,double, const VECTOR&, int, int ) = &pseudopot02;
// Now export
def("pseudopot02", expt_pseudopot02_v1); // this works fine!
//def("pseudopot02", expt_pseudopot02_v2); // this one gives the problem!
}
```
The first export function works fine. The second (presently commented) fails, giving the error:
```
template argument deduction/substitution failed
```
it also prints this explanation:
```
...../boost_1_50_0/boost/python/make_function.hpp:104:59: note: mismatched types ‘RT (ClassT::*)(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)const volatile’ and ‘boost::python::list (*)(double, double, double, const VECTOR&, int, int, int, double, const VECTOR&, int, int, int, double, const VECTOR&, int, int)’
f,default_call_policies(), detail::get_signature(f));
^
```
which doesn't tell me much except for the general idea that there is something with function signature. So don't have any idea on the nature of the problem and hence how to fix it. It doesn't seem there was a similar problem discussed here either.
Edit:
Here I provide requested minimal,complete, verifiable code:
In file libX.cpp
```
#include <boost/python.hpp>
#include "PP.h"
using namespace boost::python;
#ifdef CYGWIN
BOOST_PYTHON_MODULE(cygX){
#else
BOOST_PYTHON_MODULE(libX){
#endif
// This set will work!
// double (*expt_PP_v1)(const VECTOR& ) = &PP;
// boost::python::list (*expt_PP_v2)(const VECTOR&,int) = &PP;
// This one - only the first function (returning double)
// the function returning boost::python::list object causes the error
double (*expt_PP_v1)(double,double,double,const VECTOR&,int,int,int,double,const VECTOR&,int,int,int,double,const VECTOR&) = &PP;
boost::python::list (*expt_PP_v2)(double, double, double, const VECTOR&, int,int,int,double, const VECTOR&, int,int,int,double, const VECTOR&, int, int ) = &PP;
def("PP", expt_PP_v1);
def("PP", expt_PP_v2);
}
```
File PP.h
```
#ifndef PP_H
#define PP_H
#include <boost/python.hpp>
using namespace boost::python;
class VECTOR{
public:
double x,y,z;
VECTOR(){ x = y = z = 0.0; }
~VECTOR(){ }
VECTOR& operator=(const double &v){ x=y=z=v; return *this; }
};
/* This set of functions will work
double PP(const VECTOR& R, int is_derivs,VECTOR& dIdR );
boost::python::list PP(const VECTOR& R,int is_derivs);
double PP(const VECTOR& R );
*/
// The following - will not, only the one returning double
double PP(double C0, double C2, double alp, const VECTOR& R,
int nxa,int nya, int nza, double alp_a, const VECTOR& Ra,
int nxb,int nyb, int nzb, double alp_b, const VECTOR& Rb,
int is_normalize,
int is_derivs, VECTOR& dIdR, VECTOR& dIdA, VECTOR& dIdB
);
boost::python::list PP(double C0, double C2, double alp, const VECTOR& R,
int nxa,int nya, int nza, double alp_a, const VECTOR& Ra,
int nxb,int nyb, int nzb, double alp_b, const VECTOR& Rb,
int is_normalize, int is_derivs
);
double PP(double C0, double C2, double alp, const VECTOR& R,
int nxa,int nya, int nza, double alp_a, const VECTOR& Ra,
int nxb,int nyb, int nzb, double alp_b, const VECTOR& Rb
);
#endif // PP_H
```
In file PP.cpp
```
#include "PP.h"
/* This set will work
double PP(const VECTOR& R, int is_derivs,VECTOR& dIdR ){ dIdR = 0.0; return 0.0; }
boost::python::list PP(const VECTOR& R,int is_derivs){
VECTOR dIdR;
double I = PP(R, is_derivs, dIdR);
boost::python::list res;
res.append(0.0); if(is_derivs){ res.append(dIdR); }
return res;
}
double PP(const VECTOR& R ){ VECTOR dIdR; double res = PP(R, 0, dIdR); return res; }
*/
// The following functions will not always work
double PP(double C0, double C2, double alp, const VECTOR& R,
int nxa,int nya, int nza, double alp_a, const VECTOR& Ra,
int nxb,int nyb, int nzb, double alp_b, const VECTOR& Rb,
int is_normalize,
int is_derivs, VECTOR& dIdR, VECTOR& dIdA, VECTOR& dIdB
){ dIdR = 0.0; dIdA = 0.0; dIdB = 0.0; return 0.0; }
boost::python::list PP(double C0, double C2, double alp, const VECTOR& R,
int nxa,int nya, int nza, double alp_a, const VECTOR& Ra,
int nxb,int nyb, int nzb, double alp_b, const VECTOR& Rb,
int is_normalize, int is_derivs
){
VECTOR dIdA, dIdR, dIdB;
double I = PP(C0,C2,alp,R, nxa,nya,nza,alp_a,Ra, nxb,nyb,nzb,alp_b,Rb, is_normalize,is_derivs,dIdR,dIdA,dIdB);
boost::python::list res;
res.append(I);
if(is_derivs){ res.append(dIdR); res.append(dIdA); res.append(dIdB); }
return res;
}
double PP(double C0, double C2, double alp, const VECTOR& R,
int nxa,int nya, int nza, double alp_a, const VECTOR& Ra,
int nxb,int nyb, int nzb, double alp_b, const VECTOR& Rb
){
VECTOR dIdR,dIdA,dIdB;
double res = PP(C0, C2, alp, R, nxa,nya,nza,alp_a,Ra, nxb,nyb,nzb,alp_b,Rb, 1, 0, dIdR, dIdA, dIdB);
return res;
}
```
So, it look to me that the recognition of template gets screwed when the number of parameters is large. I checked several times that signatures in libX.cpp, PP.cpp and PP.h match among themselves and do not overlap with those of overloaded functions. So, I'm still have no clue what is the source of the problem. | 2015/05/28 | [
"https://Stackoverflow.com/questions/30513482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938720/"
] | In short, the functions being exposed exceed the default maximum arity of 15. As noted in the [configuration documentation](http://www.boost.org/doc/libs/1_58_0/libs/python/doc/v2/configuration.html), one can define `BOOST_PYTHON_MAX_ARITY` to control the maximum allowed arity of any function, member function, or constructor being wrapped and exposed through Boost.Python. In this particular case, one of the overloads has an arity of 16, so one could define the max arity before including `boost/python.hpp`:
```cpp
#define BOOST_PYTHON_MAX_ARITY 16
#include <boost/python.hpp>
```
As of the time of this writing, Boost.Python (1.58) does not use C++11's variadic templates. Instead, if uses preprocessor macro expansions to provide template specializations and allows users to configure maximum arity through the `BOOST_PYTHON_MAX_ARITY` macro.
---
Here is a complete minimal example [demonstrating](http://coliru.stacked-crooked.com/a/540f1b699890997f) increasing the max arity:
```cpp
#define BOOST_PYTHON_MAX_ARITY 16
#include <boost/python.hpp>
// Functions have 5 parameters per line.
/// @brief Mockup spam function with 14 parameters.
double spam(
int, int, int, int, int, // 5
int, int, int, int, int, // 10
int, int, int, int // 14
)
{
return 42;
}
/// @brief Mockup spam function with 16 parameters.
boost::python::list spam(
int, int, int, int, int, // 5
int, int, int, int, int, // 10
int, int, int, int, int, // 15
int // 16
)
{
boost::python::list list;
return list;
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
double (*spam_14)(
int, int, int, int, int, // 5
int, int, int, int, int, // 10
int, int, int, int // 14
) = &spam;
python::list (*spam_16)(
int, int, int, int, int, // 5
int, int, int, int, int, // 10
int, int, int, int, int, // 15
int // 16
) = &spam;
python::def("spam", spam_14);
python::def("spam", spam_16);
}
```
Interactive usage:
```python
>>> import example
>>> assert 42 == example.spam(*range(14))
>>> assert isinstance(example.spam(*range(16)), list)
>>> print example.spam.__doc__
spam( (int)arg1, (int)arg2, (int)arg3, (int)arg4, (int)arg5,
(int)arg6, (int)arg7, (int)arg8, (int)arg9, (int)arg10,
(int)arg11, (int)arg12, (int)arg13, (int)arg14) -> float :
C++ signature :
double spam(int,int,int,int,int,
int,int,int,int,int,
int,int,int,int)
spam( (int)arg1, (int)arg2, (int)arg3, (int)arg4, (int)arg5,
(int)arg6, (int)arg7, (int)arg8, (int)arg9, (int)arg10,
(int)arg11, (int)arg12, (int)arg13, (int)arg14, (int)arg15,
(int)arg16) -> list :
C++ signature :
boost::python::list spam(int,int,int,int,int,
int,int,int,int,int,
int,int,int,int,int,
int)
```
Without defining the max arity, the same code [fails to compile](http://coliru.stacked-crooked.com/a/00e7b12f45cee091):
```cpp
/usr/local/include/boost/python/make_function.hpp:104:36: error: no matching
function for call to 'get_signature'
f,default_call_policies(), detail::get_signature(f));
^~~~~~~~~~~~~~~~~~~~~
... failed template argument deduction
``` | As @bogdan pointed the function returning boost::python::list is having 16 parameters and max boost python arity by default is set to 15. Use `#define BOOST_PYTHON_MAX_ARITY 16` to increase the limit or (better) consider wrapping parameters into struct. |
20,997,283 | Does anyone know of some `Python` package or function that can upload a Pandas `DataFrame` (or simply a `.csv`) to a PostgreSQL table, **even if the table doesn't yet exist**?
(i.e. it runs a CREATE TABLE with the appropriate column names and columns types based on a mapping between the python data types and closest equivalents in PostgreSQL)
In `R`, I use the `ROracle` package which provides a `dbWriteTable` function that does what I've described above. (see docs [here](http://cran.r-project.org/web/packages/ROracle/ROracle.pdf)) | 2014/01/08 | [
"https://Stackoverflow.com/questions/20997283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/176995/"
] | Since pandas 0.14, the sql functions also support postgresql (via SQLAlchemy, so all database flavors supported by SQLAlchemy work). So you can simply use `to_sql` to write a pandas DataFrame to a PostgreSQL database:
```
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
df.to_sql("table_name", engine)
```
See the docs: <http://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries>
If you have an older version of pandas (< 0.14), see this question:[How to write DataFrame to postgres table?](https://stackoverflow.com/questions/23103962/how-to-write-dataframe-to-postgres-table/23104436#23104436) | They just made a package for this. <https://gist.github.com/catawbasam/3164289> Not sure how well it works. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.