text:
Q: java.io.FileNotFoundException: class path resource [src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml] In my Spring Application I have configured a hibernate connection and when I try to test it by a main class but it giving me an Error.
My main class,
    public static void main(String[] args) {

        Patient sac = new Patient();
        sac.setPatient_Id("M2314");
        sac.setPatient_Age(23);
        sac.setPatient_Name("Sac");
        sac.setPatient_Address("SGTY NY");

        System.out.println("load context");
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml");

        PatientService patientService = (PatientService) context.getBean("patientService");
        patientService.persistPatient(sac);

        context.close();
}

And my servlet-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.tela.pms" />

   <beans:bean id="patientService" class="com.tela.pms.service.impl.PatientServiceImpl"/>
   <beans:bean id="patientdao" class="com.tela.pms.dao.impl.PatientDAOImpl"/>

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <beans:property name="url" value="jdbc:mysql://localhost:3306/test" />
        <beans:property name="username" value="root" />
        <beans:property name="password" value="root" />
    </beans:bean>

    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource"></beans:property>
        <beans:property name="annotatedClasses">
            <beans:list>
                <beans:value>com.tela.pms.domain.Patient</beans:value>
            </beans:list>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>

    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory">
    </beans:bean>

</beans:beans>

My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

My folder structure :

Exception :
    Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:522)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:436)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.tela.pms.Test.HibernateTester.main(HibernateTester.java:22)
Caused by: java.io.FileNotFoundException: class path resource [src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
    ... 13 more

A: Use ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml");
Notice file: in front of the path.


text:
Q: Can't see products from "Add from all products" on SAP Sales Cloud I use product lists and categories on SAP Sales Cloud but for some reason, I can't display the products contained within the categories when clicking the "Add from all products" button on the right of the opportunities.

Can someone help me, please?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Errors while running jibix binding builder I am getting error like "Errors while running jibix binding builder" while building project.I am using eclipse indigo and jdk 1.5
Please help me to resolve this issue...


text:
Q: Caliburn.Micro rebind ContentControl on navigation GoBack I'm using Caliburn.Micro within WinRT application
Here is my main VM:
public class MainViewModel : Conductor<Screen>
{
    protected override void OnActivate()
    {
        if (ActiveItem == null)
        {
           ActivateItem(
               ViewModelLocator.LocateForViewType(typeof(NewsFeedView)) as Screen);
        }

        base.OnActivate();
    }
}

here I use conductor because I want to load different controls in ContentControl, but now I have only this code. Here is my content control in main view:
<ContentControl x:Name="ActiveItem" Grid.Column="1" Grid.Row="1" />

When I running the application everything work fine, MainViewModel.Activate gets called and ActiveItem set to NewsFeedViewModel and ContentControl loads NewsFeedView.
The problem:
When I navigate in NewsFeedView control to another view using NavigationService.NavigateToViewModel method and then in that view use NavigationService.GoBack, i'm returning to MainView and in that moment when MainViewModel.Activate gets called ActiveItem is not null, but ContentControl.Content is null. I've tried use View.Model attached property for ContentControl but no luck, how to make it rebind?
EDIT:
Finally i'm setup logger in Caliburn to see what happens and I found an error - when MainView loaded after navigationg back this events occuring:
Attaching ***.Views.MainView to ***.ViewModels.MainViewModel.
ViewModel bound on ActiveItem.
Using cached view for ***.ViewModels.NewsFeedViewModel.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: Unspecified error
at Windows.UI.Xaml.Controls.ContentControl.put_Content(Object value)
... some winRT stack
at Caliburn.Micro.View.SetContentPropertyCore(...

Though it was not so informative I've used InteliTrace to get more info and got this message: "Element is already child of another element". I suppose NewsFeedView stored somewhere and when time comes to put it in ContentControl this exception thrown.
How to solve this?

A: You should adopt the view model first approach. In other words, activate an instance of a view model, and Caliburn.Micro will do the view location and binding for you.
It also looks like you want to just instantiate the view model once in the constructor for example, or OnInitialise:
public MainViewModel()
{
    this.ActivateItem(new NewsFeedViewModel());
}

A: Initialize the news feed view model only once as @devdigital said, probably in the constructor, and why not use Conductor.Collection.OneActive since you only have one active item at any given time, it is used for this situations, this could solve your issue.


text:
Q: Перенос строки в document.write Почему перенос строки \n не работает в document.write?

document.write("lalala \n lalala");

A: Потому что браузер игнорирует переносы, табы, множ. пробелы и прочие спецсимволы во время прорисовки страницы.
Решение 1
document.write ("lalala <br \/> lalala");

Решение 2
document.write ("<pre>lalala \n lalala<\/pre>");

A: Он работает. Но браузер по умолчанию группирует все пробельные символы в один пробел. Надо немого изменить css, чтобы получилось то, что ты хочешь:

document.write("lalala \n lalala");
body { white-space: pre-line; }


text:
Q: jvectormap how to Display only 1 country Hi i have spend som time with on my project getting jvectormap to show 1 particular country (Denmark). but it will only show all the world. Hope you can help me?
And this is what I try making it do but it still shows the world:
$('#map').vectorMap(
{
    map: 'dk_mill',
    series:
    { regions:
        [{ values: gdpData, scale: ['#C8EEFF', '#0071A4'], normalizeFunction: 'polynomial' }]
    }, onRegionTipShow: function(e, el, code){ el.html(el.html()+'(GDP - '+gdpData[code]+')');
    }
});

A: Please make sure that you have included the dk_mill.js file.
Denmark map file


text:
Q: Write an equation for a sphere passing through a circle and tangent to a plane I'm trying to solve this task:
'''Write an equation for a sphere passing through a circle $x^2 + y^2 = 11$ and tangent to a plane $x + y + z - 5 = 0$.'''
Center of the sphere should moves only in axis Z, so it has coordinates $(0, 0, \alpha)$. I also found that
$\alpha^2 = R^2 - 11$, where R - radius of a sphere.
I came to this system:

*

*$x_0^2 + y_0^2 + (z_0 - \sqrt(R^2 - 11))^2 = R^2$

*$x_0 + y_0 + z_0 = 5$
where $x_0, y_0, z_0$ are coordinates of a touch point of a sphere with the plane.
The correct answer is two spheres:
$x^2 + y^2 + (z + 1)^2 = 12$
$x^2 + y^2 + (z + 4)^2 = 27$
I can't figure out how to find these two values of the parameter $\alpha$. Could somebody please explain how to do it?
Thanks in advance.

A: A hint, not a solution: I would assume that you know that in a point where the plane touches the sphere, the normal vector to the plane (which is $\frac{(1,1,1)^T}{\sqrt{3}}$) is parallel to the vector from the center of the sphere to the point where the sphere touches the plane (the normal to the sphere is parallel to the normal of the plane, when the plane is tangent to the sphere).
So if $(0,0, \alpha)$ is the center of the sphere, either
$(0,0,\alpha) + R\frac{(1,1,1)}{\sqrt{3}}$ or $(0,0,\alpha) - R\frac{(1,1,1)}{\sqrt{3}}$ is a point in the plane. In other words, either
$$\alpha + \sqrt{3}\,R = 5 $$
or
$$\alpha - \sqrt{3}\,R = 5 $$
Solve this for $R$ and plug the result into $\alpha^2 = R^2 -11$.
This will allow you to find $\alpha$ (and then $R$).

A: If the center of the sphere is $(x_0, y_0, z_0)$, and its radius is $R$ then
its equation is
$ (x - x_0)^2 + (y - y_0)^2 + (z - z_0)^2 = R^2 $
Set $z = 0 $ , then you get
$ (x - x_0)^2 + (y - y_0)^2 + z_0^2 = R^2 $
Comparing this with $ x^2 + y^2 = 11 $ we deduce that $x_0 = y_0 = 0 $ and
$ 11 = R^2 - z_0^2 $
Since the sphere is tangent to $ x+ y+z = 5 $, then the distance of the center which is (0, 0, z_0) to the plane is equal to $R$ , thus
$ R = \dfrac{| 0 + 0 + z_0 - 5 |} {\sqrt{3}} $
Squaring
$ R^2 = \dfrac{(z_0 - 5)^2}{3} $
Thus
$ 11 + z_0^2 = \dfrac{(z_0 - 5)^2 }{3} $
So that,
$ 33 + 3 z_0^2 = z_0^2 - 10 z_0 + 25 $
From which,
$ 2 z_0^2 + 10 z_0 + 8 = 0 $
Dividing through by $2$,
$ z_0^2 + 5 z_0 + 4 = 0 $
Factoring,
$ (z_0 + 4)(z_0 + 1) = 0 $
Therefore, $z_0 = -4$ or $z_0 = -1$, and corresponding to that,
$R^2 =  27 $ or $ R^2 = 12 $
And the equations of the two spheres are
$ x^2 + y^2 + (z + 4)^2 = 27 $
and
$ x^2 + y^2 + (z + 1)^2 = 12 $


text:
Q: How to automate the update of dozens of mercurial repositories with ant? I have a legacy product, spread across dozens of repositories. I'm currently trying to refactor (and understand...) the given build process. First step was moving from the old version control system to mercurial, which was encouraging and easy.
The build process mainly uses ant build scripts (good news) but has to run 'on' the repository file structure (bad news...) because the ant scripts take files from all repositories and leave artifacts on .. lets say, several places... But that's not a blocker.
Before I trigger the build (now with hudson CI), I have to make sure, that all repositories are updated to the tip or a selected tag. I could write a script/batch or write a custom ant task (again) but, I don't want to ignore existing features (again):
is it possible to update a set of mercurial repositories by using existing ant tasks or mercurial features? All repositories are located in one folder (like /repo) and have a common prefix (like SYSTEMNAME_module) so it's easy to locate them/create a fileset.

A: The most simple solution today is to start the hg executable from Ant (using the exec task. Note: MacroDef is your friend). Just create a "main" build file in one of the projects, change to the parent directory  (where you can access all the local copies) and then update each one.

A: I found a different ant based solution, based on the 'apply' task:
<apply executable="hg">
  <arg value="update" />
  <arg value="--verbose" />
  <arg value="--revision" />
  <dirset dir="/repos" include="REPO_SUFFIX*" />
</apply>

Thanks to Aaron, his very helpful answer showed me the right direction.

A: I think this would be a more flexible way to update a mercurial depo. From a set of directories it chooses which ones are depots and updates those. Note that you can also do this with the foreach tag of ant contrib but the 'for' seems to consume a lot less memory.
<!-- See if the directory looks like a mercurial depo, if so update it -->
    <target name="-mercurial-update">
         <dirset dir="${dir.deps}" id="lib.dirs">
             <exclude name="build"/>
             <present targetdir="${dir.deps}">
                   <mapper type="glob" from="*" to="*/.hg" />
             </present>
           </dirset>

         <for param="file">
             <path>
                <dirset refid="lib.dirs"/>
             </path>
             <sequential>
                 <echo>Trying to update mercuriali depo @{file}</echo>
                 <exec executable="hg" dir="@{file}">
                     <arg line="pull" />
                 </exec>
                 <exec executable="hg" dir="@{file}">
                     <arg line="up" />
                 </exec>
            </sequential>
         </for>
     </target>


text:
Q: ag-grid angular is not updating row indexes after sorting or CRUD operations I am using editType as "fullRow" and cellRenderer for Edit,Delete buttons.
this is working well if we not sort the grid. after sorting or deletion of some rows it is giving wrong row indexes.
this.gridOptions.api.updateRowData({ remove: event.selectedData });

i am using above code for deleting row. but after sorting grid it is not working.
while updating rows i am getting rowNode as undefined after sorting.please see below code for updating a row.
let rowNode = this.params.api.getRowNode(rowIndex);
            rowNode.setData(previousData);

my understanding was it is giving deleted rowindex thats why we are getting rowNode as undefined .please help to fix this this.

A: This a very old question but I am posting it for people who may face this issue now.
I have recently resolved the a issue in a project.
follow the steps below

*

*<ag-grid (sortChanged)="onSortChanged($event)"></ag-grid> sortChanged will only be called when the user is trying to sort the grid.

*As we have a hook now we can modify the rowIndex parameter manually by iterating over the params
onSortChanged(params){
params.api.forEachNode((rowNode,index)=>{
rowNode.rowIndex = index;
});
}
This should update the rowindex.
You may have to refresh the grid if it is not updating the returned rowindex.One walk around for that is manually start the editing of any index and then stop it.


text:
Q: loadmodel taking plugin model I have a plugin with a model called profile. Also I have a profile model in app/model folder, which contains a function getProfileDetails. This function I am calling from the AppController, using the following code
function beforeRender(){if ($this->isAuthorized())
{
  $this->loadModel('Profile');
  $this->set('ownProfile', $this->Profile->getProfileDetails($this->Auth->user('id')));
}

}
Whenver I access the plugin through the url, Im getting getting the following error
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'getProfileDetails' at line 1
/lib/Cake/Model/Datasource/DboSource.php(436): PDOStatement->execute(Array)
/lib/Cake/Model/Datasource/DboSource.php(403): DboSource->_execute('getProfileDetai...', Array)
If I give the same function in Plugin/model/profile, everything is working. How to tell cake to take the App/model/profile model in loadmodel ?

A: Cake 2.0 and previous versions do not support duplicate Model/Controller names. The fact that such a setup was working in 1.3 and lower was an unintended side-effect unknown to the developers. Cake loads all the classes, from plugins and the actual application. So a duplicate classname anywhere in you application is bound to mess things up.
Support for duplicate classnames will likely be added in Cake 3.0 as this version willy rely on PHP 5.3 which, in turn, has support for namespaces needed to implement the ability to create duplicate classnames.
The only workaround I know of is renaming your plugin's controllers, models and views, by prefixing the plugin name to the files and classnames, for example. If the plugin uses the same database tables as the application you'll have to use the $useTable model attribute to point the renamed models to the right database tables.
Some background is covered in this bug report.


text:
Q: npm run build on my react app gives error => (Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out out of memory) I also tried
$env:NODE_OPTIONS="--max-old-space-size=8000"
and set my max memory 8000 still it gives
the same error whenever I npm run build
so I am not able to deploy
I have 8GB RAM
I don't know what else I can do
PS C:\Users\91955\Desktop\SFmovies\frontend> npm run build

> frontend@0.1.0 build
> react-scripts build

Creating an optimized production build...

<--- Last few GCs --->

[17892:000001D77EA8E2A0]    36182 ms: Scavenge 2034.0 (2082.8) -> 2032.4 (2083.0) MB, 3.1 / 0.0 ms  (average mu = 0.183, current mu = 0.156) allocation failure
[17892:000001D77EA8E2A0]    36186 ms: Scavenge 2034.5 (2083.0) -> 2032.8 (2083.3) MB, 2.5 / 0.0 ms  (average mu = 0.183, current mu = 0.156) allocation failure
[17892:000001D77EA8E2A0]    36190 ms: Scavenge 2035.0 (2083.5) -> 2033.3 (2087.8) MB, 2.5 / 0.0 ms  (average mu = 0.183, current mu = 0.156) allocation failure

<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF6526730AF v8::internal::CodeObjectRegistry::~CodeObjectRegistry+112511
 2: 00007FF652602216 DSA_meth_get_flags+65542
 3: 00007FF6526030CD node::OnFatalError+301
 4: 00007FF652F34B6E v8::Isolate::ReportExternalAllocationLimitReached+94
 5: 00007FF652F1F09D v8::SharedArrayBuffer::Externalize+781
 6: 00007FF652DC268C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1468
 7: 00007FF652DCF339 v8::internal::Heap::PublishPendingAllocations+1129
 8: 00007FF652DCC30A v8::internal::Heap::PageFlagsAreConsistent+2842
 9: 00007FF652DBEF89 v8::internal::Heap::CollectGarbage+2137
10: 00007FF652DBD140 v8::internal::Heap::AllocateExternalBackingStore+2000
11: 00007FF652DE1A76 v8::internal::Factory::NewFillerObject+214
12: 00007FF652B14CB5 v8::internal::DateCache::Weekday+1797
13: 00007FF652FC2541 v8::internal::SetupIsolateDelegate::SetupHeap+494417
14: 000001D701EE9A38

A: Solved my issue by
adding this under "scripts" in my package.json
"build": "react-scripts --max_old_space_size=4096 build"

my Package.json if you have any doubt ..
Package.json screenshot


text:
Q: ant: list folders on command line I'm new to ant. I'm looking to a way to do this
I have a folder, with a variable number of subfolders. Suppose subfolders are s1,s2,s3...,sN (N is not known)
I need to create and execute this command line
java -jar myjar.jar s1\ s2\ s3\ ... sN\
I would like to use standard  task, but I do not know how to list folders on the command line.
Any help would really be appreciated!
Alberto

A: I think the 'fileset' type is what you're looking for:
http://ant.apache.org/manual/Types/fileset.html
The 'jar' task can work with implicit filesets, or you can define custom filesets within the jar task.
http://ant.apache.org/manual/Tasks/jar.html
See the examples at the bottom of the jar page.

A: You cac create an ant custom task which get the parent dir, a dirset or a patternset and writes all the names into an ant property
See more about it here http://ant.apache.org/manual/develop.html


text:
Q: Nonsingularity of Tangent Bundle Is it true if $X$ is nonsingular affine variety of dimension $m$ inside $\mathbb{A}^n$ then $TX$, the tangent bundle of $X$ is also nonsingular variety but with dimension $2m$? I have proved it is an algebraic set of dimension $2m$ but I do not know how to prove it is irreducible and it is nonsingular. I tried to compute the rank of Jacobian but did not find the rank.
Edit : idea of my work so far is we have $TX=Z(f_1,\dots,f_r, df_1,\dots, df_r)$ where $X=Z(f_1,\dots,f_r)$. When I computed the Jacobian matrix for $TX$ at some $(p,v) \in X$, I will get lower triangular blocks of matrix,
but I was not able to find its rank. The matrix will be
$\begin{pmatrix}
A & 0\\
B & C
\end{pmatrix}$
with $A$ consists of first derivatives of $f_1,\dots,f_r$ and $B$ consists of second derivatives of same polynomials


text:
Q: Python web scraper won't save image files I started working on a small image scraping terminal program that is supposed to save images to a specified file within the program hierarchy. This comes from a basic tutorial I found online. However, whenever I enter in a search term into the terminal to start scraping bing.com (yeah, i know), the program crashes. The errors i get seem to focus on either the image file type not being recognized or the file path where the images will be saved is not being recognized:
from bs4 import BeautifulSoup
import requests
from PIL import Image
from io import BytesIO

search = input("Search for:")
params = {"q": search}
r = requests.get("http://www.bing.com/images/search", params=params)

soup = BeautifulSoup(r.text, "html.parser")
links = soup.findAll("a", {"class": "thumb"})

for item in links:
    img_obj = requests.get(item.attrs["href"])
    print("Getting", item.attrs["href"])
    title = item.attrs["href"].split("/")[-1]
    img = Image.open(BytesIO(img_obj.content))
    img.save("./scraped_images/" + title, img.format)

Error thrown: Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: './scraped_images/3849747391_4a7dc3f19e_b.jpg'
I've tried adding a file path variable (using pathlib) and concatenating that with with the other necessary variables:
from bs4 import BeautifulSoup
import requests
from PIL import Image
from io import BytesIO
from pathlib import Path

image_folder = Path("./scraped_images/")
search = input("Search for:")
params = {"q": search}
r = requests.get("http://www.bing.com/images/search", params=params)

soup = BeautifulSoup(r.text, "html.parser")
links = soup.findAll("a", {"class": "thumb"})

for item in links:
    img_obj = requests.get(item.attrs["href"])
    print("Getting", item.attrs["href"])
    title = item.attrs["href"].split("/")[-1]
    img = Image.open(BytesIO(img_obj.content))
    img.save(image_folder + title, img.format)

Error thrown: Exception has occurred: TypeError
unsupported operand type(s) for +: 'WindowsPath' and 'str'
I've checked the documentation for PIL, BeautifulSoup, etc. to see if any updates may have been screwing me up, i've checked the elements on bing to see if the classes are correct, and even tried searching by different class and nothing worked. I'm at a loss. Any thoughts or guidance is appreciated. Thanks!

A: I have changed your code a bit:
from bs4 import BeautifulSoup
import requests
from pathlib import Path
import os
image_folder = Path("./scraped_images/")
if not os.path.isdir(image_folder):
    print('Making %s'%(image_folder))
    os.mkdir(image_folder)
search = input("Search for:")
params = {"q": search}
r = requests.get("http://www.bing.com/images/search", params=params)

soup = BeautifulSoup(r.text, "html.parser")
links = soup.findAll("a", {"class": "thumb"})

for item in links:
    img_obj = requests.get(item.attrs["href"])
    print("Getting", item.attrs["href"])
    title = item.attrs["href"].split("/")[-1]
    if img_obj.ok:
        with open('%s/%s'%(image_folder, title), 'wb') as file:
            file.write(img_obj.content)

You can use PIL but in this case you do not need it.
I also improved the code with PIL to work better:
from bs4 import BeautifulSoup
import requests
from PIL import Image
from io import BytesIO
from pathlib import Path

s = requests.Session()
image_folder = Path("./scraped_images/")
search = input("Search for:")
params = {"q": search}
r = s.get("http://www.bing.com/images/search", params=params)

soup = BeautifulSoup(r.text, "html.parser")
links = soup.findAll("a", {"class": "thumb"})

for item in links:
    try:
        img_obj = s.get(item.attrs["href"], headers={'User-Agent': 'User-Agent: Mozilla/5.0'})
        if img_obj.ok:
            print("Getting", item.attrs["href"])
            title = item.attrs["href"].split("/")[-1]
            if '?' in title:
                title = title.split('?')[0]
            img = Image.open(BytesIO(img_obj.content))
            img.save(str(image_folder) + '/' + title, img.format)
        else:
            continue
    except OSError:
        print('\nError downloading %s try to visit'
              '\n%s\n'
              'manually and try to get the image manually.\n' %(title, item.attrs["href"]))

I use a requests session and added try and except if PIL can't make the image. I also only make try to make a image if the request get a 200 response from the site.


text:
Q: How can I effectively use Zangief in SF 4 Volt for iPad? I'd like to get better at using Zangief in Street Fighter 4 Volt. I'm particularly interested in strategies to counter various other players, and effective high damage combos.
To be direct: countering teleporters, and ryu/chun-li vertical jump-kicks would be great.
I'd also appreciate links to any resources you use in writing your answers, for further research.

A: I haven't played Zangief or Street Fighter IV Volt in a long time, but this is something you should be aware of in online mode. I've read about people complaining about Zangief fighting teleporters such as M. Bison and Dhalsim, and this thread has a good answer.
Basically, how you should play against teleporters online is by using green hand or body splash where the opponent is going to land. Also, another good tip mentioned there was to bait them to where you want them to go.
I did some additional research and found out that someone created a google document on all the possible combos and attack data for Zangief.

*

*The original thread can be viewed here

*The google document can be viewed here

A: Vs Teleporters
As they wake up, WALK TOWARDS SHORTER END of screen, as they start to teleport, GO TO LONG END OF SCREEN.. Get ready to SPD or Ultra them out of teleport.. You are essentially baiting them to into a teleport position for SPD..
Another popular tactic is BODY SPLASH BACKWARDS as they wake up..
During match, observe if they are single teleporters or two in a row teleporters.. Vs two-in-a-row teleports you may need to jump attack to force them to teleport, then 1 or 2 green hands to hit them when the solidify..
Vs Chun Li or NEUTRAL JUMP spammers
USE GIEF's df+P.. This attack has limited use, but is SPECIALLY designed for neutral jump spammers.. To neutral jump attacks df+P is more reliable than lariat.. Lariat NEEDS timing, and leaves you vulnerable if you miss.. df+P recovers faster and you don't get punished easy for missing..
Vs Bison neutral jump spam
When up close green-hand UNDER Bison and SPD his landing !! Works on Bison coz he floats in the air..
An alternative is to back dash and normal attack or SPD his landing !! Some ppl back dash, then EX green hand back !!
Vs FAST Characters
No throwing till you get em blocking some.. Use Gief's trusty P; it's universally useful (fast) and hits none blocking crouchers.. Use Gief's K which combos into d+K (which gives good window for SPD on counter hit).. Gief K also stops Cammy drill and Cammy air roll drill.. Gief K is a good low attack WHILE WALKING (no need crouch pause) !! Use jumping K instead of jumping fist against fast characters, quicker recovery and more active time; mix in splash too due to wide area.. No throwing until you get opponent hesitant with their speed, or you got em in hit/block stun with P or d+K or splash.. Mix short and long lariats, but mostly shor; also mix in EX green hand with normal green hand.. Save your Super meter for EX green hands !!


text:
Q: React - Uncaught TypeError: this.getDOMNode is not a function I'm trying to apply styling through jquery in react component however i'm getting error Uncaught TypeError: this.getDOMNode is not a function
topicsVisited(arr){
         $(function() {
          $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(this.getDOMNode()).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
              'background-color': 'red'
            });
          });
        });
      };

A: You need to bind your functions in order to use this properly.
topicsVisited(arr) {
    $(function() {
        $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(this.getDOMNode()).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({'background-color': 'red'});
        }.bind(this));
    }.bind(this);
}

or create a variable that references the correct this.
topicsVisited(arr) {
    var self = this;
    $(function() {
        $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(self.getDOMNode()).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({'background-color': 'red'});
        });
    };
}

A: Try this
topicsVisited(arr){
         var ReactDom = require('react-dom');
         var self = this;
         $(function() {
          $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(ReactDOM.findDOMNode(self)).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
              'background-color': 'red'
            });
          });
        });
      };


text:
Q: Extending a PrimeNg component inside Angular2 Due to some use cases, I need to extend a PrimeNG component in Angular2. For proofing purpouses, I chose using the DataTable since it is complicated enough.
After literally copy pasting the @Component annotation, I have added:
export class PPDataTable extends DataTable {}
At this point I  get the following error: No provider for DataTable. If I add DataTable to the providers array in the annotation, the content of my DataTable is empty.
Therefore I tried adding: { provide: DataTable, useValue: PPDataTable } which yields in some errors such as : TypeError: co.dt.isSorted is not a function. I tried logging this.isSorted in the new class and it does exist.
How do I extend something like this?
Also, got any better solutions to change the selector name of a PrimeNg component ( wrap it somehow ) ?
Edit
After looking some more through the debug stack I found this:
It seems that instead of providing directly the object, I am providing an array containing the object and this is (by my guess) the cause of the error. If I go in the sourcecode and change it to dt[0].isSorted() it works!
How do I provide the object directly?
Answer
Seems that if I provide { provide: DataTable, useExisting: PPDataTable } it works.

A: Try this out my good friend:
import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { PrimeNgClassToExtend } from 'path';

const DATATABLE_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => MyClassThatIsExtending),
    multi: true
};

@Component({
    selector: 'my-class-extending',
    providers: [DATATABLE_VALUE_ACCESSOR],
    template: ``
})
export class MyClassThatIsExtending extends PrimeNgClassToExtend {
}

We use NG_VALUE_ACCESSOR in order to connect your custom control to ngModel with Control Value Accessor.
Check this tutorial also, could help.


text:
Q: Datatable js in angular object destroy and data refresh not happening we are using datatablejs plugin of angular for listing data in our project https://l-lin.github.io/angular-datatables/#/getting-started ; there are certain events where the data needs to be refreshed in the datalist.
this is working with datatable js on jquery where we destroy and reload it with service.
with angular the data is not changing unless any column is clicked or page is reloaded, which is a problem for us.
how can this be resolved.
we dont wish to move to material table as there are many component where this needs to be fixed.
html:

                  <mat-tab-group>
                    <mat-tab label="Draft">

                                  <button type="button"
                                    class="btn btn-info btn-sm reject-button-alignment m-btn-body mt-1"
                                    style="margin-top:1px"
                                    (click)="open(row,$event,modal_edit_academic_calen_details)">Edit</button>
                                  <button type="submit" class="btn btn-danger reject-button-alignment mt-1"
                                    style="margin-left:5px;" (click)="openDelete(row,$event)">Delete</button>

                                  <button type="button" class="btn btn-update  reject-button-alignment mb-1"
                                    style="margin-top:4px"
                                    (click)="someClickHandler(row,$event,modal_update_event_details)">Update
                                    Events</button>

                                  <button type="button" (click)=openSendApprove(row,$event,modal_action_details)
                                    class="btn btn-success reject-button-alignment mb-1"
                                    style="margin-top:3px; margin-left:5px;">Send
                                    for
                                    Apporval</button>

                                {{ createCal.AcademicYear }}
                                 {{ createCal.CalendarCode }}

                                {{ createCal.EventCount }}
                                {{ createCal.CalandarType }}
                                {{ createCal.calendar_name }}
                                {{ createCal.created_on | date :  'yyyy-MM-dd'  }}

                    </mat-tab>
                    <mat-tab label="Send for Approval">

                                {{  sendTable.AcademicYear }}
                                {{ sendTable.CalendarCode }}

                                {{  sendTable.EventCount }}
                                {{  sendTable.CalandarType }}
                                {{  sendTable.calendar_name }}

                    </mat-tab>

                  </mat-tab-group>

ts:
// code starts here
            import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; // Data Table
            import { FormArray, FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
            import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material';
            import { AcmServiceService } from '../../Shared/acm-service.service';
            import { NgbModalConfig, NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
            import { DatePipe } from '@angular/common';
            import Swal from 'sweetalert2';
            import { trigger, state, style, animate, transition } from '@angular/animations';
            import { HttpClient, HttpResponse } from '@angular/common/http';
            import { DataTableDirective } from 'angular-datatables'; // Data Table
            import { Subject } from 'rxjs';
            import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
            import { MatTable } from '@angular/material/table';
            import { RouterLinkWithHref } from '@angular/router';
            import { Router } from '@angular/router';

            class DataTablesResponse {
            data: any[];
            draw: number;
            recordsFiltered: number;
            recordsTotal: number;
            }

            class createCal {
            AcademicYear: any;
            CalendarCode: any;
            EventCount: any;
            CalandarType: any;
            calendar_name: any;
            created_o_n: any;

            }

            class sendTable {
            AcademicYear: any;
            CalendarCode: any;
            EventCount: any;
            CalandarType: any;
            calendar_name: any;

            }
            export class AcmManageAcademicCalendarComponent implements AfterViewInit, OnDestroy, OnInit {

            @ViewChild(DataTableDirective)  // Data Table
            dtElement: DataTableDirective; // Data Table

            draftdtOptions: DataTables.Settings = {};    // First Data Table
            SendApproveldtOptions: DataTables.Settings = {}; // Second Data Table

            dtTrigger: Subject<boolean> = new Subject();     // First Data Table Trigger

            dtTrigger2: Subject<boolean> = new Subject();    // Second Data Table Trigger

            userData = { organisation_id: '1', requestStatusID: '1' };
            userData1 = { organisation_id: '1', requestStatusID: '2' };

            constructor(private Service: AcmServiceService, private http: HttpClient, private router: Router) {
            }
            ngOnInit() {
            this.dataTableAngulr();
            this.sendTabale();
            }

            //  FIrst Data Table Call
            dataTableAngulr() {
            const that = this;

            this.draftdtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
            that.http
            .post<DataTablesResponse>(
            'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData), {}
            ).subscribe(resp => {
            that.createCals = resp.data;

            callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []

            });
            });

            },
            columns: [
            { data: '', title: 'Action', name: 'ay.academic_start_year' },
            { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
            { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
            { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
            { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
            { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' },
            { data: 'created_on', title: 'Modified Date', name: 'ac.created_on' }

            ],

            };
            }
            ngAfterViewInit(): void {
            this.dtTrigger.next();
            this.dtTrigger2.next();
            }

            ngOnDestroy(): void {
            this.dtTrigger.unsubscribe();
            this.dtTrigger2.unsubscribe();
            }

            rerender(): void {
            this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {

            dtInstance.destroy();
            this.dtTrigger.next();
            this.dtTrigger2.next();  // Second Table call for rerender
            });
            }

            //  Second Data Table

            sendTabale() {
            const that = this;

            this.SendApproveldtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
            that.http
            .post<DataTablesResponse>(
            'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData1), {}
            ).subscribe(resp => {

            that.sendTables = resp.data;

            callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []

            });
            });

            },
            columns: [
            { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
            { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
            { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
            { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
            { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' }
            ]
            };
            }

            }

            Send_Approve_Adademic() {
            this.sendApproveObj = {
            RequestID: this.request_id,
            RequestStatusID: '2'
            }

            this.Service.create('AcademicCalandarStatusChange', this.sendApproveObj).subscribe(res => {
            if (res['status'] == true) {
            Swal.fire({
            type: 'success',
            title: ' Successfully Send Approvel',
            onClose: () => {
            this.GetAPI();

            this.modalRef3.close();
            }
            })
            }
            this.rerender(); // call The Rerender table
            })
            }
// code ends here

A: This seems to be a change detection issue. You might need to manually detect the changes that your API call is making.
Replace your component code with below:
import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core'; // Data Table
import { FormArray, FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material';
import { AcmServiceService } from '../../Shared/acm-service.service';
import { NgbModalConfig, NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';
import Swal from 'sweetalert2';
import { trigger, state, style, animate, transition } from '@angular/animations';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables'; // Data Table
import { Subject } from 'rxjs';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { MatTable } from '@angular/material/table';
import { RouterLinkWithHref } from '@angular/router';
import { Router } from '@angular/router';

class DataTablesResponse {
    data: any[];
    draw: number;
    recordsFiltered: number;
    recordsTotal: number;
}

class createCal {
    AcademicYear: any;
    CalendarCode: any;
    EventCount: any;
    CalandarType: any;
    calendar_name: any;
    created_o_n: any;

}

class sendTable {
    AcademicYear: any;
    CalendarCode: any;
    EventCount: any;
    CalandarType: any;
    calendar_name: any;

}
export class AcmManageAcademicCalendarComponent implements AfterViewInit, OnDestroy, OnInit {

    @ViewChild(DataTableDirective)  // Data Table
    dtElement: DataTableDirective; // Data Table

    draftdtOptions: DataTables.Settings = {};    // First Data Table
    SendApproveldtOptions: DataTables.Settings = {}; // Second Data Table

    dtTrigger: Subject<boolean> = new Subject();     // First Data Table Trigger

    dtTrigger2: Subject<boolean> = new Subject();    // Second Data Table Trigger

    userData = { organisation_id: '1', requestStatusID: '1' };
    userData1 = { organisation_id: '1', requestStatusID: '2' };

    constructor(private Service: AcmServiceService, private http: HttpClient, private router: Router,
    private cdREf: ChangeDetectorRef) {
    }
    ngOnInit() {
        this.dataTableAngulr();
        this.sendTabale();
    }

    //  FIrst Data Table Call
    dataTableAngulr() {
        const that = this;

        this.draftdtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
                that.http
                    .post<DataTablesResponse>(
                        'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData), {}
                    ).subscribe(resp => {
                        that.createCals = resp.data;

                        callback({
                            recordsTotal: resp.recordsTotal,
                            recordsFiltered: resp.recordsFiltered,
                            data: []

                        });

                        this.cdREf.markForCheck();
                    });

            },
            columns: [
                { data: '', title: 'Action', name: 'ay.academic_start_year' },
                { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
                { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
                { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
                { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
                { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' },
                { data: 'created_on', title: 'Modified Date', name: 'ac.created_on' }

            ],

        };
    }
    ngAfterViewInit(): void {
        this.dtTrigger.next();
        this.dtTrigger2.next();
    }

    ngOnDestroy(): void {
        this.dtTrigger.unsubscribe();
        this.dtTrigger2.unsubscribe();
    }

    rerender(): void {
        this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {

            dtInstance.destroy();
            this.dtTrigger.next();
            this.dtTrigger2.next();  // Second Table call for rerender
        });
    }

    //  Second Data Table

    sendTabale() {
        const that = this;

        this.SendApproveldtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
                that.http
                    .post<DataTablesResponse>(
                        'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData1), {}
                    ).subscribe(resp => {

                        that.sendTables = resp.data;

                        callback({
                            recordsTotal: resp.recordsTotal,
                            recordsFiltered: resp.recordsFiltered,
                            data: []

                        });
                        this.cdREf.markForCheck();
                    });

            },
            columns: [
                { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
                { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
                { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
                { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
                { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' }
            ]
        };
    }

}

Send_Approve_Adademic() {
    this.sendApproveObj = {
        RequestID: this.request_id,
        RequestStatusID: '2'
    }

    this.Service.create('AcademicCalandarStatusChange', this.sendApproveObj).subscribe(res => {
        if (res['status'] == true) {
            Swal.fire({
                type: 'success',
                title: ' Successfully Send Approvel',
                onClose: () => {
                    this.GetAPI();

                    this.modalRef3.close();
                }
            })
        }
        this.rerender(); // call The Rerender table
    })
}


text:
Q: Match two strings on the basis of words only neglecting some special characters I am trying to match the two strings which contains different special characters like (-,:;) but the words are same.
Eg. String 1 --> Hi, How are you?
String 2 --> Hi- How are you.
in the above example strings the words are same but only difference is in (,?-.).
So I want to know how I match these strings so that i get the answer "Strings are equal".

A: You can try something like this
    boolean res = s1.replaceAll("[\\W]", "").equals(s2.replaceAll("[\\W]", ""));


text:
Q: QProcess::execute("clear") Issue I'm writing a small console app in Qt and I want to be able to clear the terminal on a user command. I found this:
How clear screen in QT console?
which almost answers my question, but its not working.
When the function "QProcess::execute("clear");" is run, I get this output to the terminal:
TERM environment variable not set.
I'm pretty new to Linux and though I've set environment variables before, its always been in the terminal before I ran the program. Here, I'd like to take care of this programmatically if possible.
My guess is that I could use QProcess::setProcessEnvironment() but I'm not really sure how exactly.
Is it possible to set the environment variables in this way, and if so how?
Any help would be greatly appreciated!
Here's the sample code I'm working with:
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream qin(stdin);
    QTextStream qout(stdout);
    QString cmd;

    while(1)
    {
        cmd = qin.readLine();

        qout<<"command is: "<<cmd<<endl;

        if(cmd == "clear")
        {
            QProcess::execute("clear");
        }
    }
    return a.exec();
}

A: The code below works fine for me. Please make sure that the clear command works fine in your console first.
main.cpp
#include <QProcess>
#include <QDebug>

int main()
{
    QProcess::execute("clear");
    qDebug() << QProcessEnvironment::systemEnvironment().contains("TERM");
    return 0;
}

main.pro
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run
qmake && make && ./main

Note that if you are using QtCreator, you will need add the environment variable with its value explicitly in the build settings tab. Here you can find more details in the documentation:
QtCreator - Using Environment Variables


text:
Q: Change Background Color of modal view I would like to resent an viewcontroller as modal view in size .formSheet. The background color should not be grey transparent, it should be an blur effect.
How I cloud change the background color of view behind modal.
let storyboard = UIStoryboard(name: "DetailViewController", bundle: nil)
if let modalViewController = storyboard.instantiateInitialViewController() as? DetailViewController {
    self.definesPresentationContext = true
    self.providesPresentationContextTransitionStyle = true
    modalViewController.item = item
    modalViewController.modalPresentationStyle = .formSheet
    modalViewController.modalPresentationCapturesStatusBarAppearance = true

    self.present(modalViewController, animated: true, completion: nil)
}

A: From the viewWillAppear(:) method of your modalViewController, you can access the self.presentationController?.containerView property. You can either change the background color or even add a blur effect view if you want.


text:
Q: Does Elixir actually need two sets of equality operators (normal and strict)? I am learning Elixir and have just learned about the two pairs of equality operators, ==, != and ===, and !==. I think it was a mistake for Elixir to have two sets of equality operators. They created a 'strict' equality operator for the cases where ints and floats are compared. Note that this case of ints and floats being compared by value is an exception to how the operator normally works when two differing types are being compared which results in type comparison, not value comparison.
So we have made an exception to type comparison rule and added two operators to support that exception. What is the pay off? So ints and floats can be compared by value which is an operation most consider bad programming practice and is also rare.
The function of the strict equality operator should exist in the normal operator. That way when any two differing types are compared the behavior would be uniform. There would be no special case for ints and floats where the value of lesser precision gets converted into the other type and subsequently compared by value. This chart would need to be updated
number < atom < reference < function < port < pid < tuple < map < list < bitstring
to be something like this,
ints < floats < atom < reference < function < port < pid < tuple < map < list < bitstring.
Now we don't need an extra pair of operators and we have removed an exception that occurs when ints and floats are compared leaving us with a uniform rule for type comparison.
If ints and floats need to be compared they can undergo a conversion / cast before the comparison operation occurs.
What was the reason for adding two additional sets of equality operators when they could have packaged all the needed functionality into one pair of equality operators, == and !=?

A: Elixir needs to be compatible with Erlang. Erlang had this behavior and depends on it in a few places in the language.
With the updated chart you provided, both 8 > 1.5 and 8 == 8.0 would return false, which really doesn't make sense since they're both numbers and CAN be compared mathematically.
I do agree with you that it's extremely rare (if ever) that you would compare integers to floats (I don't remember I've done it before honestly in over 15 years of development), but the language uses this internally to make the most sense out of the operator and, by design, provides you with this operator for your own use.


text:
Q: How does MVC routing understands the URL? Global.asax.cs has the following code on initialization:
 routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

What I'm asking is, how does it know that what it gets for "{controller}" will be the name of the Controller class to be invoked? Are there tokens defined somewhere? if so, can I list them?
If I define additional tokens (like "{lang}") will it assume they are additional parameters?
(I'm developing a custom URL rewrite/redirect handler, and I need it to work with MVC...)
What is the most practical way to define custom patterns and "aliases" for URLs?

A: The Mvc runtime has the controller and action tokens hardcoded. In addition there is also "area" but thats about it.

A: @TDaver If I define additional tokens (like "{lang}") will it assume they are additional parameters?
yes. If you define, for instance, a parameter like lang, it wil detect it. Think about like that, it will be the querystring field called lang of the page. and you can create a route for a pretyy url. Like below;
 routes.MapRoute(
                "Default", // Route name
                "{lang}/{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

so the url will be like ; http://example.com/en/home/about
Also, the most important part of routing is to understand that the routes will be picked by order. for instance, if you have multiple routes matching your current request, the first route will be picked by MVC Framework.
I reccomend you to have a look at phil haccked's RouteDebugger
Also you can create route constraints for advanced routing options as well.


text:
Q: MongoDB TTL Collection I have a collection of Markers that have a 'createdAt' date that mongo will expire every hour for me, I also have a collection of Users where each user has a list of ObjectId to the markers they set, is there any way I can remove the Marker id from the users marker list when MongoDB expires a marker?

A: Quoting TTL Index - Delete Operations

A background thread in mongod reads the values in the index and removes expired documents from the collection.
When the TTL thread is active, you will see delete operations in the output of db.currentOp() or in the data collected by the database profiler.

There doesn't seem to be any way to hook into the process.
What you could do though is stop keeping list of Markers on the user side and instead keep a user ID in a marker itself (and add appropriate index depending on how will you store the reference and query for it). This way you'll have quick way to retrieve user's Markers and won't need to worry about stale entries in the list at a cost of an additional query.


text:
Q: JMeter- Master server failed to start and return [No route to host (Host unreachable)] I try to run a distributed test using JMeter, I have 2 EC2 instances
Master Public IP: 54.xxx.xx.xx
Slave Public IP: 204.xxx.xxx.xxx
I have opened all the necessary ports that were used in the configuration.
I can ping each EC2 from the other one and the ping is successful.
But when I try to start the test, the server failed and return [No route to host (Host unreachable)].
My plan is to use more than 1 slave.
Error Return From Master Server

A: As per NoRouteToHostException exception description:

Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the remote host cannot be reached because of an intervening firewall, or if an intermediate router is down.

So make sure that the RMI ports which JMeter slave is listening are:

*

*Not dynamic

*Open in your operating system firewall

*Open in EC2 Security Groups
More information:

*

*Remote hosts and RMI configuration

*How to Perform Distributed Testing in JMeter

*Apache JMeter Distributed Testing Step-by-step


text:
Q: org.postgresql.*; class not found error I am using Java with eclipse.
I downloaded postgresql-9.1-901.jdbc4.jar and added it. (Properties-> Java Build Path-> Libraries -> Add External JARs...
My Database connection is working just fine I can create tables, execute queries ect.
Now I want to use the CopyManager. And therefore added to my code:
import org.postgresql.copy.CopyManager;
...
CopyManager cManager = new CopyManager(XXX);

unfortunately I get an error Message saying: "The source attachment does not contain the source for the file CopyManager.class"
Exception in thread "main" java.lang.NullPointerException
at org.postgresql.copy.CopyManager.<init>(CopyManager.java:46)
at Table.insert_data_in_tb(Table.java:73)
at DB.main(DB.java:69)

I'd be very thankfull for any help...

A: This is a message you get while running your code and clicking methods in debug mode. To correct the immediate problem (being able to view the source code) do this:

*

*Download PostgreSQL 9.1 source
code

*Copy the file to some appropriate folder and untar it
tar xvf postgresql-jdbc-9.1-901.src.tar.gz

*Add the source folder to your debug configuration in Eclipse
(Run->Debug Configurations->select Java Application->Click Source
tab->Add->File System Directory->add ), where directory is
where you expanded the tarball too.
However, you really don't need to view the source code in order to determine whats going wrong in your program. The documentation for CopyManager is available in online Javadocs. The constructor for the object requires a valid connection, which I am guessing is null in your program.


text:
Q: Android application to RTL (Arabic) I have an Android application (E-commerce) in English, Now I want to change language to Arabic and RTL(Right to Left)

*

*I am new in that, where and how much efforts it take?

*What specific problems should I look out for?

A: What i have done in my app:

*

*fix layout. If you use the newest android studio the function "Analyse/Inspect-Code" provides warning if you for example use layout_alignParentRight (rtl independant) without layout_alignParentEnd (rtl dependant)

*Make shure that all text are put into string resource files (app\src\main\res\values\strings.xml for the english text). Then copy this file to app\src\main\res\values-ar\strings.xml and let somboedy translate it to arabic. Use a texteditor that can handle mixed rtl/non-rtl text if you have arabic text with english placeholders. I use notepad++ with option set "enforce rtl".


text:
Q: Really weird result with a database query from my app (sqlite database - detailed code inside) I am experiencing the weirdest problem now with my application while populating a listview with results from database.
So, I have an alertdialog in which I can choose two criterias to send to my database : a category product (restaurant, store, etc.) and a payment option (card/cash).
When the user choose something, it sets a String variable to a certain interval (categoryInterval and paymentInterval), this way :
For category (it's in a popup menu) :
case R.id.item11c:
                            filterTitle = "Bakery and Pastry Shops ";
                            categoryInterval = "('" + 86 + "','" + 87 + "')";
                            filterButton.setText("Bakery and Pastry shops");
                            return true;

For payment options (it's in a radio button) :
OnClickListener radiobutton_no_listener = new OnClickListener() {
    public void onClick(View v) {
        paymentInterval = "('" + "')";
    }
};

OnClickListener radiobutton_yes_listener = new OnClickListener() {
    public void onClick(View v) {
        paymentInterval = "('" + "visa" + "','" + "master" + "')";
    }
};

Then, when the user has made his choice, and clicks on the " OK " button of the alertdialog, there is a display method calling the query method findFilterInTable() (whose purpose is to find elements which have - in this case - one of their Category Column with the number 86 or 87 AND the Payment Column with "visa" or "master" inside) and displays the results in my listview :
public Cursor findFilterInTable(String categoryInterval,
        String paymentInterval) {
    String where = COL_CAT1 + " IN " + categoryInterval + " OR " + COL_CAT2
            + " IN " + categoryInterval + " OR " + COL_CAT3 + " IN "
            + categoryInterval + " AND " + COL_PAYMENT + " IN "
            + paymentInterval;

    Cursor c = myDatabase.query(DATABASE_TABLE, new String[] { KEY_ROWID,
            COL_NAME, COL_STREET, COL_WEBSITE, COL_PAYMENT, COL_TELEPHONE,
            COL_PRICE, COL_REMARKS, COL_DATEFRIENDLY }, where, null, null,
            null, null);
    return c;
}

But it only works partially : it works perfectly well for the category part (COL_CAT1 in categoryInterval OR COL_CAT2 in ....) but for the payment part, I have a weird result. When I click this button (payment by card), it retrieves some results from the list compare to when I don't click but it retrieves things which are not at all relevant to the research. Whatever I write in my paymentInterval ("visa" or "master" as well as "okokininjfnsoe") what it seems to do is just to retrieve some elements with specific combinations of numbers IN the category part. For example, in this case, elements where CAT_3 = 87, which doesn't make sense.
So the value of my paymentInterval, in my findFilterInTable() method affects the results but doesn't even look in the appropriate column (COL_PAYMENT) but in the COL_CAT1, COL_CAT2, COL_CAT3 and for some reason, take off some results.
I am really upset with this and have no idea how to find a solution. I actually don't know how to solve a problem I don't understand and which doesn't make sense to me ! Thanks for reading.

A: Change
String where = COL_CAT1 + " IN " + categoryInterval + " OR " + COL_CAT2
        + " IN " + categoryInterval + " OR " + COL_CAT3 + " IN "
        + categoryInterval + " AND " + COL_PAYMENT + " IN "
        + paymentInterval;

To
String where = "(" + COL_CAT1 + " IN " + categoryInterval + " OR " + COL_CAT2
        + " IN " + categoryInterval + " OR " + COL_CAT3 + " IN "
        + categoryInterval + ") AND " + COL_PAYMENT + " IN "
        + paymentInterval;


text:
Q: Extract only time in 12 hr format ( AM or PM ) from date time String android I have a string with contains date time retrieved from webservice in the form "2014-11-12 16:19:00"
I need to extract only the time in 12 hr format AM or PM .
I tried but not got desired result .
public Date validateBreakingNewsDateDate() throws Exception{
        Date date = null;
        String dtStart = "2014-11-12 16:19:00";
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
             date= format.parse(dtStart);
            Log.e("date", "kardate "+date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
}

A: Try the following code snippet
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy     hh:mm:ss a");

A: pass your date to this function it will return time
   public String setTime(String date) {
    final String OLD_FORMAT = "yyyy-MM-dd HH:mm:ss";
    final String NEW_FORMAT = "h:mm a";

    String newDate = "";
    try {
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
        Date d = sdf.parse(date);
        sdf.applyPattern(NEW_FORMAT);
        newDate = sdf.format(d);
    } catch (ParseException e) {
        // TODO: handle exception
    }
    return newDate;
}

example
 public String setTime(String date) {
    final String OLD_FORMAT = "yyyy-MM-dd HH:mm:ss";
    final String NEW_FORMAT = "h:mm a";

    String newDate = "";
    try {
        sdf = new SimpleDateFormat(OLD_FORMAT);
        Date d = sdf.parse("2014-11-12 16:19:00");
        sdf.applyPattern(NEW_FORMAT);
        newDate = sdf.format(d);
    } catch (ParseException e) {
        // TODO: handle exception
    }
    return newDate;
}

output=4:19 PM

A: try this...
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(dtStart);
String newstring = new SimpleDateFormat("hh:mm aa").format(date);

A: You can fetch 12 hour time using SimpleDateFormat as follows
Date date = null;
String dtStart = "2014-11-12 16:19:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss");
try {
    date = format.parse(dtStart);
    Log.e("date", "kardate " + date);
    // here hh means hours in 12 hr format and a stands for AM/PM
    format = new SimpleDateFormat("hh:mm:ss a");
    String desiredTime= format.format(date);
    // You will get newDate 04:19:00 pm
    Log.e("date", "newDate " + desiredTime);
} catch (Exception e) {
    e.printStackTrace();
}

Hope it helps ツ


text:
Q: Next-Auth Signin without user consent when app is already authorized I have a Next application that let's the user signup using their discord account. The signup part is working. Now I am wondering how can I let the user sign-in using the discord account without going through the authorize part again, if they had already done the signup.
In the /pages/api/auth/[...nextauth].ts file
export default (req: NextApiRequest, res: NextApiResponse<any>) => {

    if (req.query.firstName && req.query.lastName) {
        firstName = req.query.firstName;
        lastName = req.query.lastName;
    }

    return NextAuth(req, res, {

        providers: [
            DiscordProvider({
                clientId: process.env.DISCORD_CLIENT_ID,
                clientSecret: process.env.DISCORD_CLIENT_SECRET,
                authorization: { params: { scope: DISCORD_SCOPES } },
            }),
        ],

        session: { strategy: "jwt" },

        callbacks: {
            async session({ session, token, user }) {
                session.jwt = token.jwt;
                session.id = token.id;
                return session;
            },

            async jwt({ token, user, account }) {

            }

        }

    });
}

Using above logic I am saving the user data to strapi after signup.
How to let the user sign-in with discord without getting a new access token and going through authorization

A: If the user already authorized your app to log in. You can use the following in your front-end client.
import { signIn } from "next-auth/react";

signIn("discord", { callbackUrl: '', redirect: true }, { prompt: "none" });

References:
https://next-auth.js.org/getting-started/client#additional-parameters


text:
Q: Highstock/Highchart OHCL not showing? Hey guys I am having trouble loading my data into the highstock charts.
I tired to display a chart with highstock
my data.json
[{
    "date":1395651841,
    "price":11,
    "amount":12,
    "tid":33170585,
    "price_currency":"USD",
    "item":"none",
    "trade_type":"bid"
    },
    {
    "date":1395651836,
    "price":4,
    "amount":3,
    "tid":33170584,
    "price_currency":"USD",
    "item":"none",
    "trade_type":"ask"}
]

And my Html
    <script type="text/javascript">
                    $(function() {
    $.getJSON('data.json', function(data) {

        // Create the chart
        $('#container').highcharts('StockChart', {

            rangeSelector : {
                inputEnabled: $('#container').width() > 480,
                selected : 1
            },

            title : {
                text : 'Tiredddd'
            },

            series : [{
                name : '@_@',
                data : data,
                type : 'areaspline',
                threshold : null,
                tooltip : {
                    valueDecimals : 2
                },
                fillColor : {
                    linearGradient : {
                        x1: 0,
                        y1: 0,
                        x2: 0,
                        y2: 1
                    },
                    stops : [[0, Highcharts.getOptions().colors[0]], [1, 'rgba(0,0,0,0)']]
                }
            }]
        });
    });
});

        </script>

Please assist me in finding the bug

A: Make sure you have comma separated data.Please debug(alert(data)) like (1,2,3).
$.getJSON('data.json', function(data) {alert(data); // your other code......}

A: I don't see open/high/low/close properties in your data points.
See required format for Highcharts data here.


text:
Q: UIImagePickerController and application background modes I'm building an application which supports both video playback and recording (not simultaneously, it's just two separate features it provides). In order to make the videos play after the app enters background and gets back, I had to add an App plays audio item to Required background modes in the plist (I'm using MPMoviePlayerController for playback).
This, however, causes a problem with my video recording (I'm using UIImagePickerController for it). Basically, even after the picker is dismissed (either by the Cancel button or when it's finished picking media), the app still keeps the audio recording session running.
If I remove the App plays audio item from the plist, the ImagePickerController's audio session stops misbehaving, but then I can't resume the playback of MPMoviePlayerViewController on switching to app from background mode.
Is there a way I can customise the handling of the audio session so that both the MPMoviePlayerController and UIImagePickerController can work properly?

A: yes, there is a way you can customize the handling of the audio session for what you desire:  don't try to set the App plays audio setting.
instead, in your AppDelegate code (which is usually in AppDelegate.m from the simple wizard projects provided), supply code in the applicationWillResignActive: method that will stop the playback in your MPMoviePlayerController, and then use applicationDidBecomeActive: to resume the playback at the point at which you paused it if so desired.
this will not only allow the video to be resumed after a temporary pause, but it will allow you to save the state so that the video can be resumed in case the app is removed from memory or in case the user causes it to be quit.

A: You can scratch the background modes and instead use notifications to pause/resume your player. See UIApplicationDidBecomeActiveNotification and UIApplicationWillResignActiveNotification in the UIApplication class reference.
You can snag some code and see this implemented in this class. Here is some of the relevant code from that class:
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(_didBecomeActive:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(_willResignActive:)
                                             name:UIApplicationWillResignActiveNotification
                                           object:nil];

- (void) _didBecomeActive:(NSNotification*)notification {
  if (_wasPlaying) {
    [_movieController play];
  }
}

- (void) _willResignActive:(NSNotification*)notification {
  _wasPlaying = _movieController.currentPlaybackRate != 0.0;
  if (_wasPlaying) {
    [_movieController pause];
  }
}


text:
Q: Join along with sum and order by in Eloquent I'm trying to perform the following SQL query using Eloquent:
select s.username, s.link, s.followers, sum(h.count)
from users s, views h where h.username = s.username order by h.timestamp

I'm aware of the join(), sum() and select() methods, however, how can I perform the sum() and select() together?

A: To use a SUM() you will have to use DB::raw. Here is an example that should make your query work:
DB::table('users as s')
 ->select(DB::raw('s.username, s.link, s.followers, sum(h.count)'))
 ->join('views as h', 'h.username', '=', 's.username')
 ->orderBy('h.timestamp')
 ->get();


text:
Q: How to reload page whitout breaking code? i have integrated in my system an external script to allow my users to receive credits after watched a video. After they clicked a link, a popup will load the video. After the video finished there is a callback "callback_on_conversion". I need to hide the button but it's not really easy. Reading the integration guide, i found:

"This asynchronous behavior has a limitation: The javascript code that
  you can run in these callback functions may not use the document.write
  function as that will not work. Instead, we recommend that for
  creating/inserting new elements (e.g. fallback AdTags) in the page you
  use DOM and jQuery."

This is the actually script. Again, i don't know how to hide the "a" link when video finished.

Load

What should i do to prevent code breaking? Thanks!

A: jQuery has LOTS of functions to manipulate the DOM tree. For instance, this selects the attribute with ID = 'showvideo' and removes it.
$('a#showvideo').remove();

Note that if there's more than 1 such element, only the first will be taken, but you can also select using a class:
$('a.showvideo').remove();

A: If callback_on_conversion is called when the video finishes you could simply hide it with jquery. http://api.jquery.com/hide/
callback_on_conversion: function() {
    $("a#showvideo").hide();
};


text:
Q: Portable chrome on gentoo I'm currently building an module for Drupal 7, which requires the functionality of taking an screenshot of another website and delivering this to the user. For doing this i'm using an php wrapper for chrome (headless).
Aaand: It works on my machine!
But: I realizied, that the project is hosted on a managed server, so i can't install the google-chrome package from the gentoo-repository.
Now my questions is if there is any sort of portable chrome for this use case.
Thank your for helping!

A: The way i took was using an Amazon Lightsail Instance with an LAMP-Stack. There i could install the required parts. So i'm calling an endpoint on this instance from my drupal module and it's answers with the base64-encoded image data (and some stuff around it).


text:
Q: When is useEffect called in React Native for app that may run in background Suppose I have a React Native App that has useEffect as follows:
export default function App() {
    useEffect(() => {
        SOME CODE HERE
        console.log("useEffect initialization code called");
        return () => do_cleanup();
    }, [])

    function do_cleanup() {
        SOME CODE HERE
        console.log("useEffect cleanup code called");
    }

My understanding is that by using useEffect with the empty dependencies argument [], the code in useEffect runs only once after initial rendering, so console.log will only print "useEffect initialization code called" once as the app is being used.
I don't understand a couple of things though:

*

*When is the do_cleanup function called? The docs say that this is called when the component unmounts, but what exactly has to happen for the entire App to unmount?

*Suppose my app also has location services updating device location and it operates when the app is in a background state. When the app transitions from foreground to background state, does that result in do_cleanup being called. In other words, is that a condition where App would "unmount"?
And if the App is then moved back into the active state, does it "mount" again, so that the useEffect code is called again?

Is there any way in useEffect to determine that the app is just going from a background to active state, or active to background state? I have some code that needs to ONLY run when the app is first launched and some cleanup code that should only run when the app closes. In other words, it should not run when the app just changes state from foreground to background. Is there any way to do this?

A: you can use AppState Api for listening AppState changes
useEffect(() => {
    const subscription = AppState.addEventListener("change", nextAppState => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        console.log("App has come to the foreground!");
      }

      appState.current = nextAppState;
      setAppStateVisible(appState.current);
      console.log("AppState", appState.current);
    });

    return () => {
      subscription.remove();
    };
  }, []);

more ref from AppState


text:
Q: Converting String array to CGFloat array in Swift Here is my String array:
let StringArray = ["1.4", "75.3", "23.4"]

And i wan't to convert this String Array to a CGFloat Array how can i do that?

A: The easiest way is to use map to transform each element from one type to another type:
let doubleArray = StringArray.map {
    CGFloat(($0 as NSString).doubleValue)
}

The cast to NSString is needed because there's no string to double conversion in plain swift - at least I am not aware of any.


text:
Q: PHP - XMLWriter write nested array to file I'm following this example in XMLWiter functions, but I'm looking for a way to write the output to a file (sample.xml), I walked through many threads, with no luck.
I know that the solution could be easy, but I'm working on PHP only from one month. Can anyone help?
<?php

class XmlConstruct extends XMLWriter
{

/**
 * Constructor.
 * @param string $prm_rootElementName A root element's name of a current xml document
 * @param string $prm_xsltFilePath Path of a XSLT file.
 * @access public
 * @param null
 */
public function __construct($prm_rootElementName, $prm_xsltFilePath=''){
    $this->openMemory(); // change this with $this->openURI('your_file.xml');
    $this->setIndent(true);
    $this->setIndentString(' ');
    $this->startDocument('1.0', 'UTF-8');

    if($prm_xsltFilePath){
        $this->writePi('xml-stylesheet', 'type="text/xsl" href="'.$prm_xsltFilePath.'"');
    }

    $this->startElement($prm_rootElementName);
}

/**
 * Set an element with a text to a current xml document.
 * @access public
 * @param string $prm_elementName An element's name
 * @param string $prm_ElementText An element's text
 * @return null
 */
public function setElement($prm_elementName, $prm_ElementText){
    $this->startElement($prm_elementName);
    $this->text($prm_ElementText);
    $this->endElement();
}

/**
 * Construct elements and texts from an array.
 * The array should contain an attribute's name in index part
 * and a attribute's text in value part.
 * @access public
 * @param array $prm_array Contains attributes and texts
 * @return null
 */
public function fromArray($prm_array){
  if(is_array($prm_array)){
    foreach ($prm_array as $index => $element){
      if(is_array($element)){
        $this->startElement($index);
        $this->fromArray($element);
        $this->endElement();
      }
      else
        $this->setElement($index, $element);

    }
  }
}

/**
 * Return the content of a current xml document.
 * @access public
 * @param null
 * @return string Xml document
 */
public function getDocument(){     //comment this function
    $this->endElement();
    $this->endDocument();
    return $this->outputMemory();
}

/**
 * Output the content of a current xml document.
 * @access public
 * @param null
 */
public function output(){               //comment this function
    header('Content-type: text/xml');
    echo $this->getDocument();
}

}

//Example:

$contents = array(
  'page_title' => 'Generate a XHTML page from XML+XSLT files',
  'welcome_msg' => 'Simple XHTML document from XML+XSLT files!',
  'prova' => array(
    "gino" => array(
      "innergino" => "gino inner value"
     ),
   "filo" => "filodata"
),
);

$XmlConstruct = new XmlConstruct('root');
$XmlConstruct->fromArray($contents);
$XmlConstruct->output();              // comment this line

?>

A: Finally, (after reading lot of pages and tried a lot of examples), I followed my way to find a solution. First of all, as explained in this post, XMLWriter is the best choice for big xml files (as in my case), this is why, after a deep look, i didn't follow the solution based on the DOM as proposed by @Seyed Quarib, although has been very instructive to read that thread. Another problem was that all my xml content needed to be wrapped in a tag with a namespace like
. I found out i needed to use XMLWriter::startElementNS and also XMLWriter::writeAttribute. As I said, i find this way tho output nested xml tag very handy for my purpose (that was very specific). Here is the code, hope someone else can find it usefull:
<?php header('Content-Type: text/html; charset=utf-8') ?>

File saved

    <?php

    class XmlConstruct extends XMLWriter
    {

    /**
    * Constructor.
    * @param string $prm_rootElementName A root element's name of a current xml document
    * @param string $prm_xsltFilePath Path of a XSLT file.
    * @access public
    * @param null
    */
    public function __construct($prm_rootElementName, $prm_xsltFilePath=''){
      $this->openURI('save-to-file.xml'); // changed
      $this->setIndent(true);
      $this->setIndentString(' ');
      $this->startDocument('1.0', 'UTF-8');

    if($prm_xsltFilePath){
      $this->writePi('xml-stylesheet', 'type="text/xsl" href="'.$prm_xsltFilePath.'"');
    }

      //$this->startElement($prm_rootElementName); // changed
      $this->startElementNS("p", "TagName", null);
      $this->writeAttribute ("version", "1.0");
      $this->writeAttribute ("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
      $this->writeAttribute ("xmlns:p", "http://www.xxxxx.gov.it/sdi/xxxxx/v1.0");
      $this->writeAttribute ("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    }

    /**
    * Set an element with a text to a current xml document.
    * @access public
    * @param string $prm_elementName An element's name
    * @param string $prm_ElementText An element's text
    * @return null
    */
    public function setElement($prm_elementName, $prm_ElementText){
      $this->startElement($prm_elementName);
      $this->text($prm_ElementText);
      $this->endElement();
    }

    /**
    * Construct elements and texts from an array.
    * The array should contain an attribute's name in index part
    * and a attribute's text in value part.
    * @access public
    * @param array $prm_array Contains attributes and texts
    * @return null
    */
    public function fromArray($prm_array){
      if(is_array($prm_array)){
        foreach ($prm_array as $index => $element){
          if(is_array($element)){
            $this->startElement($index);
            $this->fromArray($element);
            $this->endElement();
          }
          else
            $this->setElement($index, $element);

        }
      }
    }

    /**
    * Return the content of a current xml document.
    * @access public
    * @param null
    * @return string Xml document
    */

    public function getDocument(){
      $this->endElement();
      $this->endDocument();
      return $this->outputMemory();
    }

    /**
    * Output the content of a current xml document.
    * @access public
    * @param null
    */

    public function output(){
      header('Content-type: text/xml');
      echo $this->getDocument();
    }

    }

    //Example:

    $contents = array(
      'prova' => array(
        "gino" => array(
          "innergino" => "gino inner value",
          "innergino2" => "gino inner another value"
        ),
        "filo" => "filodata",
        "arrays" => array (
          "inner-arrays" => array (
            "one-inner-array" => array (
              "inner-content-one" => "one",
              "inner-content-two" => "two"
            ),
            "two-inner-array" => array (
              "inner-content-one" => "one",
              "inner-content-two" => "two"
            ),
            "three-inner-array" => array (
              "inner-content-one" => "one",
              "inner-content-two" => "two"
            ),
          )
        )
      )
    );

    $XmlConstruct = new XmlConstruct('root');
    $XmlConstruct->fromArray($contents);
    $XmlConstruct->getDocument();           // cahnged

    ?>

And the output is:
<?xml version="1.0" encoding="UTF-8"?>

  <prova>
    <gino>
      <innergino>gino inner value</innergino>
      <innergino2>gino inner another value</innergino2>
    </gino>
    <filo>filodata</filo>
    <arrays>
       <inner-arrays>
         <one-inner-array>
           <inner-content-one>one</inner-content-one>
           <inner-content-two>two</inner-content-two>
        </one-inner-array>
        <two-inner-array>
          <inner-content-one>one</inner-content-one>
          <inner-content-two>two</inner-content-two>
        </two-inner-array>
        <three-inner-array>
          <inner-content-one>one</inner-content-one>
          <inner-content-two>two</inner-content-two>
        </three-inner-array>
      </inner-arrays>
    </arrays>
  </prova>


text:
Q: How to insert new data from a table to another table? I have 2 tables with names search and search2. When user search something on my website it's insert to first table and mySQL allocate auto increment ID to that. I want to ID from search table insert to search2 table automatically. These are my tables structure:
TABLE search(
    id INT AUTO_INCREMENT PRIMARY KEY,
    search_keyword VARCHAR(50) NOT NULL
)
TABLE search2(
    id INT FOREIGN KEY REFERENCES search (id)
)

and this is my query:
INSERT INTO search2 (id) SELECT id FROM search WHERE condition

I don't know what to write in condition that each time new record added to search table then it's ID insert to search2 table.
NOTE: my website wrote by PHP.

A: Create trigger after insert
DELIMITER $$

CREATE TRIGGER new_load_id
AFTER INSERT ON search
FOR EACH ROW
INSERT INTO search2 (id) VALUES (NEW.id);

END$$
DELIMITER ;


text:
Q: Use Elasticsearch significant-tems aggregation with SparkSQL I am writing/reading datas between Spark dataframes and Elasticsearch using the following code :
df.write.format("org.elasticsearch.spark.sql")
.option("es.nodes" , [MY_ES_IP])
.option("es.port",[MY_ES_PORT])

   ...

.option("es.index.auto.create","true")
.option("es.resouce.auto.create",[INDEX]/[DATA])
.save([INDEX]/[DATA])

and
val df = spark.read.format("org.elasticsearch.spark.sql")
     .option("es.nodes" , [MY_ES_IP])
     .option("es.port",[MY_ES_PORT])

     ...

     .load([INDEX]/[DATA])

I want to retrieve the result of a significant-terms request on my datas, but I can't find any example on how to achieve this using Spark.
The DSL request I would like to do :
{
    "query" : {
        "terms" : {[BUCKET REQUEST]}
    },
    "aggregations" : {
        "significant_elements" : {
            "significant_terms" : { "field" : [FIELD NAME] }
        }
    }
}

Is there any way to achieve that using only the org.elasticsearch.spark.sql lib?
EDIT :
I tried solving the problem with :
val myquery = "{\"query\" : {\"terms\" : [BUCKET REQUEST]},\"aggregations\" : {\"significant_elements\" : {\"significant_terms\" : { \"field\" : [FIELD NAME]}}}}"

val df = spark.read.format("org.elasticsearch.spark.sql")
                     .option("es.nodes" , [MY_ES_IP])
                     .option("es.port",[MY_ES_PORT])

                     ...

                     .option("query", myquery)
                     .option("pushdown", "true")
                     .load([INDEX]/[DATA])

But the dataframe I get in result is the result of the bucket request only.
I'm still looking for how to get the 'significant score' for each [FIELD NAME]


text:
Q: Google maps API V3 Passing Values to Javascript While implementing Google Maps in android using API V3(Javascript) How do i pass values from activity to the javascript?
ie.. i want to pass the Latitude and Longitude values to Javascript inorder to display my current location on map..

A: There are quite a few examples of this on Stack Overflow, e.g.
Android Calling JavaScript functions in WebView
Calling javascript function from android webview?
Call javascript function in Android WebView


text:
Q: How to throw warnings for two fields simultanouesly in Thymeleaf I have this code for application in Spring + Thymeleaf:

    <input type="number" step="any" class="form-control" th:field="*{originalBLG1}" th:errorclass="has-error"/> -
    <input type="number" step="any" class="form-control" th:field="*{originalBLG2}" th:errorclass="has-error"/>

Is there any way to catch error for two fields at the same time, in example:


text:
Q: Does moving a table to a separate datafile improve performance? In Oracle 11g, say that I have table A and table B both in the same datafile. Table A seldom has any updates while table B has lots of updates per second. I am having issues where the commits done by one process in Table A take some time to show up in queries done by other process. My theory is that by being in the same datafile, the activity on the datafile caused by table B will impact performance on queries and updates on Table A. Will commit performance improve on Table A if we move it to a separate datafile even if the datafile is in the same disk? I imagine that using a separate disk would be better, but I'd like to know whether a separate datafile in the same disk will still help.
I am particularly looking for answers that include good evidence (reference articles for example). Thanks!


text:
Q: Combining SQL Insert and Delete Ok here is the question
I have three tables
events
- id
- name

questions
- id
- event_id
- name

answers
- id
- question_id
- description

While generating the add form, i can simply search for all the questions belonging to particular event, and show the questions in single HTML form.
But consider the edit scenario. An event manager can in due time add or delete some questions from an event. So in such case, when the user tries to edit already posted answer, I generate the HTML form with the new questions as blank field and existing answers are prefilled input boxes. How can I handle the submission of this form?
When the user submits, should i delete all past answers and do a INSERT on the answers table for all the answer values? or is it a good practice to UPDATE existing answers first and INSERT only new values?
The former obiviously being easier with DELETE followed by INSERT. While the later is somewhat tedious. The problem with former solution is that the id of the answers table will increase every time..

A: Some people favour the delete/insert approach because, like you say, it is simpler.
Personally I think the update/insert/delete approach, while more work, is more correct.
If you do updates you can then have an audit trail of changes to a particular item. With just insert/delete it's either much harder or plain impossible to have that kind of linkage and history.
As for how to handle the submission of the form, for fields that can be updated (ie they're existing records), you need to be able to identify the field somehow. Personally I just encode something like the primary key in the field name.
If you do this you must of course ensure that you don't have a security hole by validating that the ID supplied is valid and the edit allowed ie never trust the client.
This could take the form of:
<input type="text" name="name_117" value="Some value">
<input type="text" name="name_118" value="Some other value">
<input type="text" name="name_1243" value="Yet another value">

and you have to process all the input parameters, decode the identifier and act accordingly.
Lastly, another problem with insert/delete is that you can't do it (or it just gets really hard) if the items you're deleting/inserting relate to other tables in the database. If you have a question table and store the answers people give, normally you'll reference the question as a foreign key. You lose that association if you delete/insert instead of updating.

A: First, the ID shouldn't be being used for anything anyway, so disregarding the incrementation is a good reminder.
I would prefer to deal with the primary question, however, cnnceptually, everything else being equal. Is the user in fact establishing a different set of questions with their edits? Then save them as a new set. Or is the original set intended to retain its conceptual identity? Then update/delete/insert. Which seems to be more the case.
In terms of securing the integrity of the question/answer set, I think of sessions having that responsibility. You should consider validating the question set against that associated with the session.

A: Online quiz applications usually lock down a quiz once it is live. It is a messy problem to deal with completed answer sets versus a changing definition of questions. If your application can handle it, I would favor not allowing questions to change once an event is first published.

A: Agree with Cletus post, writing seperately for an extra reason and an idea:
The delete/insert approach has a concurrency issue, when your website gets some heavy traffic.  Someone else could do an insert after your delete, and then you'll end up with multiple answer lists per user.
MySQL supports the ON DUPLICATE KEY UPDATE syntax. That might be an easy way to combine the insert and the update, if you have an appropriate primary key.