Is there a way to import a single external PHP module that uses classes from other modules but same namespace?
I'm creating a tool that imports a php module from some other project and creates phpunit tests dynamically on the fly. I'm doing that by loading a module using include, and then performing some checks and creating my test cases. The problem I'm facing is with modules that use classes not defined directly in that module (but the same namespace for example).
I've tried using autoloading with composer, and passing in the classmap the classes I'm missing but this can be really tiresome and it doesn't always work (I had some issues with Laravel framework classes used in modules).
Anyways, I'm wondering what would be the best way to solve a problem like this?
See also questions close to this topic
-
Php add contents in the page
i've one question about my page. I want that any user logged in, can add his content in the page (like on ebay you can add your product that you want to sell) but i don't know how i can do it. Could someone help me? Thanks.
-
Parse JsonArray with request to php
I'm trying to parse a JsonArray that i'm getting form my php, the php should send a Json with data from user logged in the app, but i'm getting this exception
D/ContentValues: ERROR RESPUESTA en JSON: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
.I don't have any idea how make it works, I already searched many ways but nothing works
This is my activity that show the list:
public class MainLista extends AppCompatActivity { TextView txt1; ListView listaPerfil; ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_lista); listaPerfil = findViewById(R.id.listaPerfil); txt1 = findViewById(R.id.txt1); adapter = new AdaptadorDatos(this); listaPerfil.setAdapter(adapter); } }
Adapter class :
public class AdaptadorDatos extends ArrayAdapter { private RequestQueue requestQueue; JsonObjectRequest jsArrayRequest; private static final String LINK = "https://viavel.com.mx/pruebas/PHPRicardo/ejemplomostrar.php"; List<Datos> items; TextView txtNombre; public AdaptadorDatos(Context context) { super(context, 0); requestQueue = Volley.newRequestQueue(context); jsArrayRequest = new JsonObjectRequest(Request.Method.GET, LINK, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { items = parseJson(response); notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG,"ERROR RESPUESTA en JSON: " + error.getMessage()); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new Hashtable<>(); params.put("email", Globales.USER_EMAIL); params.put("contrasena", Globales.USER_PASS); return params; } }; requestQueue.add(jsArrayRequest); } @Override public int getCount() { return items != null ? items.size() : 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { //OBTENER INSTANCIA DEL INFLATER LayoutInflater inflater = LayoutInflater.from(parent.getContext()); //GUARDAR REFERENCIA DEL VIEW View view; //COMPROBAR SI EXISTE Y SI NO CREARLO view = null == convertView ? inflater.inflate(R.layout.item_lista, parent, false) : convertView; Datos item = items.get(position); //OBTENER INSTANCIA DE ELEMENTOS txtNombre = view.findViewById(R.id.txtNombre); txtNombre.setText(item.getNombre()); return view; } public List<Datos> parseJson(JSONObject jsonObject) { List<Datos> dato = new ArrayList<>(); JSONArray jsonArray; try { jsonArray = jsonObject.getJSONArray("items"); for (int i = 0; i <jsonArray.length(); i++) { try{ JSONObject objeto = jsonArray.getJSONObject(i); Datos datos = new Datos( objeto.getString("nombre")); dato.add(datos); } catch (JSONException e) { Log.e(TAG, "ERROR DE PARSING " + e.getMessage()); } } } catch (JSONException e) { e.printStackTrace(); } return dato; } }
Datos class:
public class Datos { private String nombre; private String apellido; private String telefono; private String email; private String nacimiento; private String imagen; private String contrasena; public Datos() { } public Datos(String nombre/* String apellido, String telefono, String email, String nacimiento, String imagen, String contrasena*/) { this.nombre = nombre; /* this.apellido = apellido; this.telefono = telefono; this.email = email; this.nacimiento = nacimiento; this.imagen = imagen; this.contrasena = contrasena;*/ } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } /* public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNacimiento() { return nacimiento; } public void setNacimiento(String nacimiento) { this.nacimiento = nacimiento; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public String getContrasena() { return contrasena; } public void setContrasena(String contrasena) { this.contrasena = contrasena; }*/ }
the Json obtained from the php:
[{"nombre":"Fernando","apellido":"Villarreal","telefono1":"8672554040","email":"ricardito@gmail.com","fechanacimiento":"2021-02-11","contrasena":"12345678","imagen":"https:**********/FP-aYRsz-891.png"}]
hope can you explain
-
Plotting grain size distribution plot in excel
I have one question about plotting 4 axis grain size distribution chart. would you please let me know how can I plot one chart in excel? Thank you in advance for your help.
Kind regards, Nastaran
-
Trouble importing hdf5 file using VScode with python 3.7 from anaconda3 distribution (Windows)
I am trying to import two hdf5 files.
dataFolder
contains the file path. I am using aconda venv
virtual environment in VScode. I have installed the same software via the exact same way on another computer and it works fine. The code I am trying to use is:trainData = pd.read_hdf(dataFolder+"dftrain.h5").values trainData = np.array(trainData) validData = pd.read_hdf(dataFolder+"dfvalid.h5").values validData = np.array(validData) nTrain = trainData.shape[0] nValid = validData.shape[0]
I have tried to
conda install pytables
and it shows it is already installed. (Checked also withconda list
and its there:pytables 3.6.1 py38ha5be198_0
PS D:\###\####\MLPM> conda install pytables Collecting package metadata (current_repodata.json): done Solving environment: done # All requested packages already installed.
I get the following traceback, stating that I have to install tables at the end:
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-5-421c5198a2e1> in <module> 1 dataFolder = "D:/Master/ETH Spring2021/MLPM/" 2 #C:/Users/gfrusque/Spyder_DataExploration/ ----> 3 trainData = pd.read_hdf(dataFolder+"dftrain.h5").values 4 trainData = np.array(trainData) 5 ~\anaconda3\envs\myenv\lib\site-packages\pandas\io\pytables.py in read_hdf(path_or_buf, key, mode, errors, where, start, stop, columns, iterator, chunksize, **kwargs) 397 raise FileNotFoundError(f"File {path_or_buf} does not exist") 398 --> 399 store = HDFStore(path_or_buf, mode=mode, errors=errors, **kwargs) 400 # can't auto open/close if we are using an iterator 401 # so delegate to the iterator ~\anaconda3\envs\myenv\lib\site-packages\pandas\io\pytables.py in __init__(self, path, mode, complevel, complib, fletcher32, **kwargs) 540 raise ValueError("format is not a defined argument for HDFStore") 541 --> 542 tables = import_optional_dependency("tables") 543 544 if complib is not None and complib not in tables.filters.all_complibs: ~\anaconda3\envs\myenv\lib\site-packages\pandas\compat\_optional.py in import_optional_dependency(name, extra, raise_on_missing, on_version) 107 except ImportError: 108 if raise_on_missing: --> 109 raise ImportError(msg) from None 110 else: 111 return None ImportError: Missing optional dependency 'tables'. Use pip or conda to install tables.
I have tried these: https://anaconda.org/ska/tables Missing optional dependency 'tables'. In pandas to_hdf ImportError HDFStore requires PyTables No module named tables
conda 4.9.2
Another weird thing is this:PS D:\Master\ETH Spring2021\MLPM> python --version Python 3.8.5
while the version indicated on the bottom right is
Python 3.7.10 64-bit ('myenv':conda)
-
How to import javascript resource into thymeleaf template without Spring?
I use thymeleaf WITHOUT Spring. Configuration looks
@WebListener public class ThymeleafConfig implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { TemplateEngine engine = templateEngine(sce.getServletContext()); TemplateEngineUtil.storeTemplateEngine(sce.getServletContext(), engine); } private TemplateEngine templateEngine(ServletContext servletContext) { TemplateEngine engine = new TemplateEngine(); engine.setTemplateResolver(templateResolver(servletContext)); return engine; } private ITemplateResolver templateResolver(ServletContext servletContext) { ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContext); resolver.setPrefix("/WEB-INF/templates/"); resolver.setTemplateMode(TemplateMode.HTML); return resolver; }
where I specify path /src/main/webapp/WEB-INF/templates as prefix /WEB-INF/templates/ for my index.html template. It works. Now I am trying to add javascrpt static resource that is located at /src/main/webapp/WEB-INF/js, so that I can import it in template, like
<script src="example.js" type="text/javascript"></script>
OR
<script th:src="@{/example.js}" type="text/javascript"></script>
How can I add javascript resource? All documentation and examples I have found are for the combination Spring+thymeleaf.
-
How to import library modules to my namespace from another module?
I have written this function inside my utils module
def megaimport(library_name, skip_modules = []): skip_modules.extend(["sys", "os", "dir_path"]) exec(f"import {library_name}") for module in dir(eval(library_name)): if module.startswith("__") == False and module not in skip_modules: exec(f"from {library_name}.{module} import *", globals(), locals())
What I am trying to achieve is to import all functions to my namespace from any library with the following structure:
library: - module1 - function_1_2 - function_2_2 - module2 - function_2_1 - function_2_2
just by running in my
notebook.ipynb
:from utils import megaimport megaimport("library") function_1_2() function_2_1() ... etc
The idea is to dynamically call
from library.module1 import *
for every module in a library. When I do this the function runs without errors but I when I call the functions they have not been imported properly. However, if I define the function in my code and run it it works as expected.How can I import all the functions into my current namespace?
I am aware that importing everything like this is bad practice but for me it is convenient when working with jupyter notebooks.
My
notebook.ipynb
andutils.py
live in the same directory. -
python get module name that declared a variable
so classes in python can tell you where they were defined:
# module a.py class Something: pass
from a import SomeClass print(f"name: {SomeClass.__name__}, module: {SomeClass.__module__}") # name: SomeClass, module: a
I want to know if it is possible to get the module that declared a variable, rather than a class.
# module a.py SOME_LIST = [1,2,3]
from a import SOME_LIST # something like this: print(SOME_LIST.__module__) # Traceback (most recent call last): # File "b.py", line 3, in <module> # print(SOME_LIST.__module__) # AttributeError: 'list' object has no attribute '__module__'
The use case is that I need to crawl a complicated structure of nested classes and lists across many files and I need to generate namespaces for classes and variables found in this structure.
-
Error: ENOENT: no such file or directory, scandir './data' but directory exists
I am trying to test a node module before I publish it. However, when I
npm install <path to module>
and try requiring the module + running the main function, it throws this error:Error: ENOENT: no such file or directory, scandir './data' [90m at Object.readdirSync (node:fs:1044:3)[39m at Object.<anonymous> (C:\Users\divinelemon\Downloads\Programming\Node.js\test-main\index.js:11:22) [90m at Module._compile (node:internal/modules/cjs/loader:1108:14)[39m [90m at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)[39m [90m at Module.load (node:internal/modules/cjs/loader:973:32)[39m [90m at Function.Module._load (node:internal/modules/cjs/loader:813:14)[39m [90m at Module.require (node:internal/modules/cjs/loader:997:19)[39m [90m at require (node:internal/modules/cjs/helpers:92:18)[39m at Object.<anonymous> (C:\Users\divinelemon\Downloads\Programming\Node.js\test\index.js:1:25) [90m at Module._compile (node:internal/modules/cjs/loader:1108:14)[39m { errno: [33m-4058[39m, syscall: [32m'scandir'[39m, code: [32m'ENOENT'[39m, path: [32m'./data'[39m }
However, this data folder exists, and I verified that the module worked when I ran a test in
test-main
(the module I'm trying to export).I fixed this error by using this path instead of
./data
:./node_modules/random-usernames/data
But it seems pretty hacky, and I am unsure whether or not this is the correct way to fix this.
Help appreciated, Thanks
-
Looking for a replacement to link-module-alias npm package
As per the title, I'm looking to deprecate the usage of link-module-alias in my project due to some issues with this package. I was wondering if you guys know any other good alternative to it. I tried better-module-alias, but I couldn't make it work. Plus I don't like the idea of having to import
require('better-module-alias')(__dirname)
everywhere where I wish to use it with Node files.I'm not sure if I should use Webpack Alias instead?
Thanks in advance!
-
Namespace vs global in PHP Functions?
I've got a $db variable (and others) in my global config and I've seen some sample code recently like:
function getInfo(\My\Namespace\DB $db) {...}
and then callinggetInfo($db);
but I'm used to just doing:
function getInfo() { global $db; ... }
What's the difference and is one better/preferred/best practice compared to the other now?
Thanks.
-
Use multiple namespaces in PHP
I am new to the concept of namespaces and I am reading about them.
This guide by David B Hayes has been very insightful.
But everywhere I read it mainly focuses on creating the namespaces but not about using them.
Suppose I want to use two libraries called Dompdf and Stripe.
If I do:
use Dompdf\Dompdf;
What happens if I also want to use Stripe or whatever other library or libraries?
Won't the namespaces collide?
And what if one library is namespaced and the other or others are not?
In the case of Stripe (github.com/stripe/stripe-php/blob/master/lib/Stripe.php) it "lives" in the Stripe namespace. Which would imply that I have to write
use Stripe;
before using it.
I made this example to try to understand it better:
namespace cat; class Classy{ static function says() {echo 'meoow';} } namespace dog; class Classy{ static function says() {echo 'ruff';} } use cat; echo Classy::says(), "\n";
But it outputs the string "Ruff", which means the
use cat
is apparently doing nothing. -
run container with containerd's ctr by means of uidmap to map to non-root user on the host
To better understand how to use the
--uidmap
withctr
, I've created a test container by means of the following steps. Thecontainerd
version is1.4.3
.Build and Run Container:
- Build Dockerfile
with$ cat Dockerfile FROM alpine ENTRYPOINT ["/bin/sh"]
$ docker build -t test . Sending build context to Docker daemon 143.1MB Step 1/2 : FROM alpine ---> d6e46aa2470d Step 2/2 : ENTRYPOINT ["/bin/sh"] ---> Running in 560b09f9b287 Removing intermediate container 560b09f9b287 ---> 8506bfeab109 Successfully built 8506bfeab109 Successfully tagged test:latest
- Save the image as tar ball
$ docker save test > test.tar
- Import it with containerd's
ctr
$ sudo ctr i import test.tar unpacking docker.io/library/test:latest (sha256:9f7dabf0e4feadbca9bdc180422a3f2cdd7b545445180a3c23de8129dc95f29b)...done
- Create and run the container
The uid map should map the container internal uid of 0 (root) to 5000 corresponding to ctr's manpage:$ sudo ctr run --uidmap 0:5000:4999 docker.io/library/test:latest test
--uidmap="": run inside a user namespace with the specified UID mapping range; specified with the format container-uid:host-uid:length
Check UID in container and on host:
Within the container:
ps -eo ruser,rgroup,comm RUSER RGROUP COMMAND root root sh root root ps
On the host:
$ ps -eo uid,gid,cmd | grep /bin/sh 126 128 /bin/sh /usr/lib/lightdm/lightdm-greeter-session /usr/sbin/unity-greeter 0 0 /bin/sh
Issue
It seems to not work,
/bin/sh
runs as root (uid=0) within the container as well as on the host. - Build Dockerfile
-
Code-coverage failing with count(): Parameter must be an array
I am using PHP 7.2.33 with Xdebug 2.9.8 and PHPUnit 6.0.8. When I try to generate a code-coverage report using
phpunit -d xdebug.profiler_enable=On --coverage-html tests/_report/ --filter=NotifierTest
Thats the output:
Time: 5.18 seconds, Memory: 52.25MB OK (1 test, 1 assertion) Generating code coverage report in HTML format ...count(): Parameter must be an array or an object that implements Countable
I found that was a know error and has been fixed in 5.2.3. However, I am using already PHPUnit 6.0.8, so that cannot be the problem.
Any ideas what could cause this? How could I figure out, where this
count
comes from? -
call a class in last with phpunit
I'm testing my app and I would like phpunit call a class at the end of the process and I don't know how to do. Any idea ? This is the class I want in last :
class ExerciceTest extends WebTestCase { //user1 const USER_ID_TEST = 2; const NEW_USER_ID = 5; /** * @test */ public function it_is_not_display() { $client = static::createClient(); $userRepo = static::$container->get(UserRepository::class); $testUser = $userRepo->find(self::NEW_USER_ID); $client->loginUser($testUser); $client->request(Request::METHOD_GET,'/'.$testUser->getSlug()); $this->assertSelectorNotExists('a.add-exercice', 'error'); } }
-
Using Doctrine EntityManager inside PHPUnit test class
I can not access my Doctrine EntityManager inside my PHPUnit test class. I really don't understand, and I'm not using Symfony.
My UtilisateurService.php class :
<?php require_once './bootstrap.php'; class UtilisateurServices{ private Utilisateur $_user; /** * Constructeur de classe. * @param integer $id identifiant généré de l'utilisateur */ public function __construct($id){ $userRepo = $entityManager->getRepository("Utilisateur"); $this->_user = $userRepo->find($id); } ...
My UtilisateurServiceTest.php :
<?php class UtilisateurServicesTest extends \PHPUnit\Framework\TestCase{ /** * * @var UtilisateurServices */ private $utilisateurServices; /** * Tests UtilisateurServices->getUtilisateur() */ public function testGetUtilisateur() { $id = 1; $this->utilisateurServices = new UtilisateurServices($id); assert($this->utilisateurServices->getUtilisateur()->getId(), $id); }...
My Bootstrap.php file :
<?php // bootstrap namespace DPTrace\Bootstrap; require_once join(DIRECTORY_SEPARATOR, [__DIR__, 'vendor', 'autoload.php']); use Doctrine\ORM\tools\Setup; use Doctrine\ORM\EntityManager; $entitiesPath = [ join(DIRECTORY_SEPARATOR, [__DIR__, "src\\entities"]) ]; $dbParams = array( 'driver' => 'pdo_mysql', 'host' => 'localhost', 'user' => 'DPTrace_test', 'password' => 'test', 'dbname' => 'DPTrace', 'charset' => 'utf8' ); $isDevMode = true; $proxyDir = null; $cache = null; $useSimpleAnnotationReader = false; $config = Setup::createAnnotationMetadataConfiguration($entitiesPath, $isDevMode, $proxyDir, $cache, $useSimpleAnnotationReader); $entityManager = EntityManager::create($dbParams, $config); return $entityManager; ?>
The error message when I execute vendor\bin\phpunit tests/UtilisateurServicesTest.php -c tests/phpunit.xml
- UtilisateurServicesTest::testGetUtilisateur Undefined variable: entityManager
C:\Users\gillian\git\repo\DPTrace\src\services\UtilisateurServices.php:20 C:\Users\gillian\git\repo\DPTrace\tests\UtilisateurServicesTest.php:26
Thank you a lot for your help !