text:
Q: Oracle - Use WITH clause like a text macro I have an SQL query that reuses a complex subquery in two different places across a union
SELECT A.PROJECT_ID, B.INFO B.MORE_INFO
FROM A
INNER JOIN (
     -- Complex subquery
) B ON A.PROJECT_ID = B.PROJECT_ID
WHERE -- Filter to a disjoint subset --

UNION

SELECT C.PROJECT_ID, B.INFO B.MORE_INFO
FROM C
INNER JOIN (
     --  SAME Complex subquery
) B ON C.PROJECT_ID = B.PROJECT_ID
WHERE -- Filter to a disjoint subset --

In order to reduce repeated code, I'd like to use the WITH clause so I only have to write the complex subquery once.
WITH B AS (
    -- Complex subquery
)

SELECT A.PROJECT_ID, B.INFO B.MORE_INFO
FROM A
INNER JOIN B ON A.PROJECT_ID = B.PROJECT_ID
WHERE -- Filter to a disjoint subset --

UNION

SELECT C.PROJECT_ID, B.INFO B.MORE_INFO
FROM C
INNER JOIN B ON A.PROJECT_ID = B.PROJECT_ID
WHERE -- Filter to a disjoint subset --

This works, but now the query takes 4 times longer to execute. Looking at the explain plan for both of these queries, I think I know what's going on: The WITH clause is creating a temporary table that's not indexed, so when joining A and B, a full table scan is being executed. In the plan for the original query, a pushdown predicate is being used, reducing the work needed for the join. This corroborates with this modern SQL article I found talking about how WITH clauses can adversely impact performance.
Given all of this, is there a way where I can use the WITH clause more like a text macro a la C's preprocessor without creating a temporary table? Maybe there is a plan hint I could use? Or is there possibly some other native feature in Oracle or SQL that allows me to do the same thing?
In the end, I'd like to see Oracle do the same plan as the original query, while also taking advantage of the code modularity the WITH clause offers
Some notes:

*

*Oracle 12c

*I cannot eliminate the UNION

*The two WHERE filters are different, resulting with two disjoint sets

A: The simplest thing you can try is the inline hint.
Alas, for some reason that I personally do not understand, this hint is not documented (same as its counterpart, the materialize hint), even though they are widely used. Depending on your organization's rules, you may or may not be able to use this solution. I assume you know about hints, but didn't know about this particular one; if you need more help with it please say so. In any case, you may want to try it in a test environment to see what could be done.
EDIT (since others may read this as well):
The with clause should look like this:
with
  b as ( select /*+ inline */ ...... complex query ....... )
.......

A: This answers the original version of the question.
As you have structured the query, you can use or:
SELECT A.PROJECT_ID, B.INFO B.MORE_INFO
FROM A INNER JOIN
     (
     -- Complex subquery
     ) B
     ON A.PROJECT_ID = B.PROJECT_ID
WHERE -- Filter to a disjoint subset -- OR
      -- Filter to a disjoint subset --

If you need to remove duplicates, you can add SELECT DISTINCT.


text:
Q: Unknown column in 'on clause' after MySQL upgrade I've been updating some old code which used PHP4 and MySQL 4.1 up to MySQL 5.6 / MariaDB 10. I've had a few issues with SQL JOINs
 and precedence but this one has really stumped me and is giving me the error  -
 #1054 - Unknown column 'grouping_id' in 'on clause'

I've tried messing about with the order of the JOIN statements in the query below but I haven't had any success yet, as mentioned this query worked fine on MySQL 4.
SELECT
    team.team_id,
    team.team_name,
    competition.rel_sport_id,
    country.country_name
FROM
    team
LEFT JOIN team_grouping ON(
        rel_team_id = team_id AND team_grouping.rel_grouping_id = grouping_id
    )
LEFT JOIN grouping ON grouping_id = team_grouping.rel_grouping_id
LEFT JOIN country ON team.rel_country_id = country_id
LEFT JOIN sport ON team.rel_sport_id = sport_id
LEFT JOIN competition_country ON(
        rel_competition_id = competition_id AND competition_country.rel_country_id = country_id
    )
LEFT JOIN competition ON competition_id = '985'
WHERE
    team.rel_country_id = competition_country.rel_country_id AND team.rel_sport_id = competition.rel_sport_id AND grouping_id = '3'
ORDER BY
    team_name

Can anyone help with what could be wrong with the above query?
EDIT - Added table schemas:
CREATE TABLE `grouping` (
 `grouping_id` int(11) NOT NULL AUTO_INCREMENT,
 `grouping_name` varchar(100) DEFAULT NULL,
 PRIMARY KEY (`grouping_id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin

CREATE TABLE `team` (
 `team_id` int(11) NOT NULL AUTO_INCREMENT,
 `team_name` varchar(200) DEFAULT NULL,
 `image` varchar(100) DEFAULT NULL,
 `rel_country_id` int(11) DEFAULT NULL,
 `rel_sport_id` int(11) DEFAULT NULL,
 `modified_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`team_id`),
 KEY `IDX_team_1` (`rel_country_id`),
 KEY `IDX_team_2` (`rel_sport_id`)
) ENGINE=MyISAM AUTO_INCREMENT=11918 DEFAULT CHARSET=latin1

CREATE TABLE `country` (
 `country_id` int(11) NOT NULL AUTO_INCREMENT,
 `country_name` varchar(40) DEFAULT NULL,
 `image` varchar(40) DEFAULT NULL,
 `rel_geographic_id` int(11) DEFAULT NULL,
 PRIMARY KEY (`country_id`),
 KEY `IDX_country_2` (`rel_geographic_id`)
) ENGINE=MyISAM AUTO_INCREMENT=237 DEFAULT CHARSET=latin1

CREATE TABLE `competition` (
 `competition_id` int(11) NOT NULL AUTO_INCREMENT,
 `competition_name` varchar(200) DEFAULT NULL,
 `rel_sport_id` int(11) DEFAULT NULL,
 `rel_grouping_id` int(11) DEFAULT NULL,
 `rel_competition_tz_id` int(11) NOT NULL DEFAULT '2',
 `modified_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`competition_id`),
 KEY `IDX_competition_1` (`rel_sport_id`),
 KEY `IDX_competition_2` (`rel_grouping_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1133 DEFAULT CHARSET=latin1

CREATE TABLE `sport` (
 `sport_id` int(11) NOT NULL AUTO_INCREMENT,
 `sport_name` varchar(40) DEFAULT NULL,
 `image` varchar(40) DEFAULT NULL,
 `modified_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`sport_id`)
) ENGINE=MyISAM AUTO_INCREMENT=29 DEFAULT CHARSET=latin1

CREATE TABLE `competition_country` (
 `rel_competition_id` int(11) NOT NULL DEFAULT '0',
 `rel_country_id` int(11) NOT NULL DEFAULT '0',
 PRIMARY KEY (`rel_competition_id`,`rel_country_id`),
 KEY `IDX_competition_country_1` (`rel_competition_id`),
 KEY `IDX_competition_country_2` (`rel_country_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

A: Table names in an ON clause can only refer to tables preceding it in the query. When you're joining through a relationship table, the first ON clause just relates with the table before it, you relate to the second table in the next ON clause.
So the ON clause for team_grouping should only have rel_team_id = team_id, and the ON clause for competition_country should only have rel_country_id = country_id.
I don't think you need the WHERE clause at the end. Those relationships should be implied already by the earlier joins. And since you're doing a LEFT JOIN with grouping, you should put restrictions on that table in the ON clause; otherwise, the null values from non-matching rows will be filtered out by the WHERE clause.
SELECT
    team.team_id,
    team.team_name,
    competition.rel_sport_id,
    country.country_name
FROM team
LEFT JOIN team_grouping ON rel_team_id = team_id
LEFT JOIN grouping ON grouping_id = team_grouping.rel_grouping_id AND grouping_id = 3
LEFT JOIN country ON team.rel_country_id = country_id
LEFT JOIN sport ON team.rel_sport_id = sport_id
LEFT JOIN competition_country ON competition_country.rel_country_id = country_id
LEFT JOIN competition ON competition_id = '985' AND competition_id = competition_country.rel_competition_id
ORDER BY team_name

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why Angular 2 use Observables instead of simple arrays in routing? ActivatedRoute fields are Observables. For instance we want to get an id parameter or just nth segment of URL. Instead of simple maps or arrays we uses Observables. Is this over-usage of asynchrony or really needed for a purpose?

A: You can get the current version of a parameter using the snapshot field of the ActivatedRoute.
But by default, the router reuses the same component if you navigate from a route to the same route, only changing parameters. So you need an Observable to be able to react to the changes of the parameter values from inside that component.
Let's say for example that you have a list of exercises to display. When you click an exercise, you go to /exercises/1. Inside the template of the component displaying the exercise, you have a "Next" link to /exercises/2. Clicking on that link will make the params Observable emit a new value. But the router won't create a new instance of ActivatedRoute, and won't create a new instance of ExerciseComponent. The ExerciseComponent needs to subscribe to the params observable in order to load the details of the exercise 2 when the event is emitted.
If you don't have such a link, then the snapshot is all you need, and it does contain the parameters as a regular object.


text:
Q: ajax data filtering not working I am trying to grab the content of the div from ajax response but it is returning the same content as the other div instead of that specific div.
$.ajax({
url:'test',
type:'POST',
data:{id:id},
cache:false,
success: function(data){
  $('#resp_top').html(data).find('#top');// this one works
  $('#resp_bot').html(data).find('#bottom');// this returns the same content as the above
  //$('#resp_bot').html($(data).filter('#bottom')); I have also tried this but doesn't work
}
})

php
...
echo "
".$top_content."
";
echo "
".$bottom_content."
";

A: It looks like you're just assigning the content of the data to the divs without doing any data massaging or filtering on it.
$('#resp_top').html(data).find('#top')

Adds the data object to the HTML of the resp_top ID.
$('#resp_bot').html(data).find('#bottom');

Adds the SAME data object to the HTML of the resp_bot ID.
The find isn't doing any DOM manipulation, but rather is just finding the element and not doing anything with it.
You'd be better served by massaging the data first, then assigning it:
$('#resp_top').html($(data).find('#top'));
$('#resp_bot').html($(data).find('#bottom'));

This assumes that top/bottom are in the data object as an ID.

A: Try using returning a JSON array with the two return values:
JavaScript:
$.ajax({
url:'test',
type:'POST',
data:{id:id},
dataType:'json',
cache:false,
success: function(data){
  $('#resp_top').html(data[0]).find('#top');
  $('#resp_bot').html(data[1]).find('#bottom');
}
})

PHP:
echo "
".$top_content."
";
echo "
".$bottom_content."
";
echo json_encode(array("
".$top_content."
", "
".$bottom_content."
"));


text:
Q: Prove a Sequence is Cauchy Prove that sequence {(2n+1)/n} is Cauchy.
I understand the definition of a Cauchy sequence; however, I'm not sure how to find the necessary value of N to satisfy the prove.
I know that you can simply proof that the sequence is Cauchy by stating that it converges to 2. But, for this specific problem we are asked to use strictly the definition of a Cauchy sequence in writing the proof.
Thanks for the help in advance.

A: Hint: Without loss of generality, suppose $m>n$. Then
$$\Bigg\vert \frac{2n+1}{n}- \frac{2m+1}{m}\Bigg\vert= \Bigg\vert \frac{m-n}{mn}\Bigg\vert\le\Bigg\vert \frac{m}{mn}\Bigg\vert=\frac{1}{n}$$

A: There is a theorem"a sequence is convergent iff it is a Cauchy sequence"
so it needs to prove that the given sequence is convergent which emphasises that it is Cauchy.$$a_n=2+\frac{1}{n}\to 2$$i.e. the sequence is convergent and hence it is Cauchy sequence

A: Assuming that you're considering this sequence as a sequence in $\mathbb{R}$, then the fact that $\{ \frac{2n+1}{n}\}_{n=1}^\infty$ is a convergent sequence (it converges to $2$) and using the fact that any convergent sequence is necessarily Cauchy.


text:
Q: Django query equivalent of MySQL GREATEST function? How can i get the greater of two different Decimal fields for a model using a Django query?
For example if i have a model Month with fields called income_actual and income_projected, how do i return the greater value?
I have previously used the MySQL GREATEST() function to do it but i cant work out how to do it in Django.

A: Have you looked into using the extra method?
Month.objects.extra(select={'max_income': 'greatest(income_actual, income_projected)'})

EDIT:
You're not going to be able to use that through the ORM without writing raw SQL. Although you could use some python magic:
sum(month['max_income'] for month in Month.objects.extra(select={'max_income': 'greatest(income_actual, income_projected)'}).values('max_income'))

A: You may use Django's Database Function Greatest.
For example you may use such a query:
>>> from django.db.models.functions import Greatest

>>> months = Month.objects.annotate(greatest_income=Greatest('income_actual', 'income_projected').all()

# now you can access the greatest value using something like this:
>>> months[0].greatest_income

A: @drewman already gave you the version when you want to use strictly SQL. I would do things a bit differently, and add a property to the model which dynamically calculates the correct version.
class model(models.Model):
    ....

    @property
    def income(self):
        return max(self.income_actual, self.income_real)


text:
Q: How to get the second value in list object using thymeleaf? I'm sending a model attribute object(product) from my controller to th:each tag in view page.
If that object contains 3 values like 0,1,3, I can get by using
   th:each="var:${product}"
and then
   th:text=${var.id},
but here I want only 1. How can i get it?.
Can any one please help me to solve this problem?

A: Thymeleaf expressions use SpEL (Spring Expression Language), so you can use all the features available from SpEL. From the documentation you can see that contents of a collection/array can be accessed using square brackets.
For example, if products is a collection of objects each with an id field:

Then the contents of the div would be the value of id in the second object. Other elements can be accessed by changing the index between the square brackets.

A: Here you can do two things,

1) You can use th:if in your div or any other tag. like this.

<div th:if="${var.variable == <YourValue>}"
     th:text="${var.variable}">

2) or you can just send that single value form your controller, and then just you can use that here.


text:
Q: How to update multiple rows on table with the result of a select subquery in Mysql I have a table "product_quantity_cart" that has a "price" column in Mysql. I want to update all rows that match certain "id" with the result of a select that uses values from two different tables. In order to do so, I am executing a select subquery inside the update and as a result I am getting error 1224: "subquery returns multiple rows". I have read that a subquery like mine is not the right way to achieve what I want in Mysql, so I would like to ask which is the proper way to do it.
My query looks like so:
update product_quantity_cart set price_product =
  (
  select quantity*price from (select * from product_quantity_cart) as p_q_c  inner join product
    on product.id_product=p_q_c.id_product
        where id_shopping_cart=7
        );
'''
As you can see, I intend to update column price_product in all rows from table product_quantity_cart.

A: I don't know what your tables looks like but I'm just assuming that the product in your inner join product (given above) is your table2 with columns p.id_product and p.quantity and your product_quantity_cart has columns id_product, price_product, c.price, and c.id_shopping_cart
Then the query could be like this;
update product_quantity_cart c JOIN product p ON p.id_product = c.id_product
set c.price_product = c.price * p.quantity
WHERE c.id_shopping_cart=7


text:
Q: How to (server-side) read cookies with cgi and bash? I want to read the cookies I have set on the client with cgi and bash. However, by searching around I found that the suggestion is to use jQuery. The problem is that I want to check the cookie server-side and not client-side.
I need the cookie for implementing a login-based authentication of my users. The session should be timed-out by the server and so on.

A: use this code to display cookies
#!/bin/bash

echo 'Content-Type: text/plain'
echo
echo $HTTP_COOKIE


text:
Q: Can 'Azure Event Hub' check event schema prior to ingestion - can it 'pre-filter' data coming in? If a device or an application sends an event with an invalid JSON schema, is it possible to stop this coming into an event hub?

A: If you mean something on the Event Hubs side that will check if your schema is not the same as some schema you need, then no.


text:
Q: Is RENAME DATABASE no longer available in MySQL? If so, what is the workaround? I have a genuine need for this.
Thanks.

A: Dump the existing database and import into a new one.

A: Yes, it was removed, and also refer to Michael's answer above.
http://dev.mysql.com/doc/refman/5.1/en/rename-database.html

A: No. http://dev.mysql.com/doc/refman/5.1/en/rename-database.html


text:
Q: JavaFx Controller set Object Another Controller I'am gettin Admin object in LoginController. Its not null there is no problem. When i setting this object AdminController its not working. In my initialize syso result showing "null".  I need to use this object in my other controller. Using swing i was doing this in controller constructors and swing construtors. But i dont know how i can do that with JavaFx. Sorry for my bad english. But if u look code, u will understand me.
    public class UserLoginController extends AbstractController {

    @FXML
    private Button joinBtn;
    @FXML
    private Button exitBtn;
    @FXML
    private Label statusLabel;
    @FXML
    private TextField userNo;
    @FXML
    private PasswordField password;

    @FXML
    void buttonEvent(ActionEvent event) {

        if (joinBtn == event.getSource()) {
            String userType = userNo.getText().substring(0, 2);
            switch (userType) {
            case "10":
                Admin admin = DBContext.getInstance().admins().isUserExist(Integer.parseInt(userNo.getText()), password.getText());
                if(admin != null) {
                    final String fxml = "/educationManagement/view/AdminPanel.fxml";
                    try {
                        FXMLLoader loader = new FXMLLoader(getClass().getResource(fxml));
                        Parent root = (Parent) loader.load();
                        AdminController adminController = loader.getController();
                        adminController.setAdmin(admin);
                        Scene scene = new Scene(root);
                        Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
                        stage.setTitle(admin.getFirstName() + " " + admin.getLastName());
                        stage.setScene(scene);
                        stage.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("fuck");
                    }

                } else {
                    statusLabel.setText("Kullanıcı Adı veya Şifre Yanlış");
                    userNo.setText("");
                    password.setText("");
                }
                break;

            case "40":

                break;

            case "50":

                break;

            default:
                statusLabel.setText("Kullanıcı Adı Bulunamadı");
                break;
            }

        }
    }
}

public class AdminController implements Initializable{

    private Admin admin;

    @FXML
    private TableView<Student> studentTable;

    @FXML
    private Label firstNameLbl;

    public Admin getAdmin() {
        return admin;
    }

    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        System.out.println(admin);

    }

}

A: The initialize method is being called when loading the FXML file, you should create another init method in AdminController that will do all the initialize that you need with the admin object, and call this method after the call to the setter:
 AdminController adminController = loader.getController();
 adminController.setAdmin(admin);
 adminController.initController();


text:
Q: renaming in one command line, same file which is in multiple folders I need to rename same file which is in 4 different directories in one command line(bash)...I can't use ";" or bash script.Thanks....I was trying something like:
mv folder/{folder1,folder2,...}/file folder/{folder1,folder2,...}/new_name_file

but it doesn't work.

A: Here's one way:
$ mkdir foo bar baz
$ touch {foo,bar,baz}/quux
$ find foo bar baz -type f -name quux | while read file; do mv "$file" $(dirname "$file")/xyxxy; done
$ find foo bar baz -type f -name xyxxy
foo/xyxxy
bar/xyxxy
baz/xyxxy

A: you can define more lines at the end part:
#!/bin/bash

while read dir diir; do
    mv $dir $diir
done <<___HERE
/path/to/dir1   /path/to/diir1
/path/to/dir2   /path/to/diir2
___HERE

you can run it in one line :
$./script.sh | (Do what you want here)

A: One-liner:
find folder/folder{1,2,3} -type f -name 'file' -exec bash -c 'mv -v {} $(dirname {})/new_name_file' \;

A: For this specific case you can use:
echo folder/{folder1,folder2,...} | xargs -n1 echo |xargs -I% mv %/oldfile %/newfile

but a more portable one to rename all files in a subdirectory would be
rename(){ #usage rename from_name to_name
    find . -name $1 |xargs -l dirname |xargs -I% mv %/$1 %/$2
}


text:
Q: stop label from toggling the input checkbox I have the following html code. When clicking on the label it toggles the checkbox.
Client Launch From Web:
<input type="checkbox" id="startClientFromWebEnabled" name="startClientFromWebEnabled" data-bind="checked: StartClientFromWebEnabled, enable: IsEditable" onchange="startClientFromWebToggleRequiredAttribute()" />

How can I prevent this? If I remove the for="startClientFromWebEnabled", It stops toggling but I need this because I have some logic that takes the id from the element that fires the event ...

A: The best solution would be to let label toggle the checkbox as that is intuitive and expected behaviour.
Second best solution is to make sure your checkbox is not nested inside label and label does not have for attribute. If you have some logic that depends on it, you can put data attributes on elements and use those in your logic.

<input type="checkbox" data-myid="1" />
foo

Last resort
You could prevent the default behaviour of the click event using jQuery:
$('label[for="startClientFromWebEnabled"]').click(function(e) {
    e.preventDefault();
});

Please see this jsFiddle for an example.

A: There is CSS solution too:
label {
   pointer-events: none;
   cursor: default;
}

A: if you are using JQuery, add an id on your label then
add this in your script:
$("#lbl").click(function(){
   return false;
});

A: Just prevent default on label or any part of label, if desired.

document.querySelector('.prevent-default').addEventListener('click', (e)=>{
   e.preventDefault();
}, false);
    <input type="checkbox" id="1" />
    foo

or

document.querySelector('.prevent-default').addEventListener('click', (e)=>{
   e.preventDefault();
}, false);
    <input type="checkbox" id="1" />
    foo some part not clickable

A: "I have some logic that takes the id from the element "
You could remove the for-attribute, if you store the ID somewhere else. For example in a data-*-attribute:

On the other hand, it is sometimes difficult to point and click an a check-box based on the styling and the capabilities of the user. There is are good reasons for using the for-attribute.


text:
Q: Spring NamespaceHandler - http://cxf.apache.org/transports/http/configuration Issue Log:
Configuration problem: Unable to locate Spring Namespace Handler for XML schema
namespace [http://cxf.apache.org/transports/http/configuration]

*

*What would be clue to fix this ?

*can anyone see did i missed anything ?

Environment:

Spring 4.0
  Apache CXF : 2.7.7
  WildFly App server

bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-2.5.xsd
    http://cxf.apache.org/transports/http/configuration
    http://cxf.apache.org/schemas/configuration/http-conf.xsd
    http://cxf.apache.org/jaxws
    http://cxf.apache.org/schema/jaxws.xsd">

 <http-conf:conduit name="*.http-conduit">
         <http-conf:client ReceiveTimeout="120000" ConnectionTimeout="120000" />
    </http-conf:conduit>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>b2cApplication</artifactId>
    <name>B2C Version</name>
    <version>3.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <url>http://jboss.org/richfaces</url>

 <build>
        <finalName>b2cApplication-3.0-SNAPSHOT</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>

                    <packagingExcludes>**/ojdbc14-10.2.0.3.0.jar,
                        **/asm*.jar,
                        **/cxf-2.4.0.jar,
                        **/cxf-manifest-2.4.0.jar,
                        **/ant-optional-1.5.1.jar,
                        **/activation-1.0.2.jar,
                        **/xalan-2.7.0.jar,
                        **/mail-1.3.jar,
                        **/xercesImpl-2.2.1.jar,
                        **/extranet-hotel-deduplicate-2.0.0.jar,
                        **/javassist-3.18.1-GA.jar,
                        **/cxf-api-2.7.7.jar,
                        **/cxf-rt-bindings-soap-2.7.7.jar,
                        **/cxf-rt-core-2.7.7.jar,
                        **/cxf-rt-databinding-jaxb-2.7.7.jar,
                        **/cxf-rt-frontend-simple-2.7.7.jar,
                        **/cxf-rt-transports-http-2.7.7,
                        **/cxf-rt-ws-addr-2.7.7.jar,
                        **/cxf-rt-ws-policy-2.7.7.jar,
                        **/cxf-rt-bindings-xml-2.7.7.jar,
                        **/cxf-rt-frontend-jaxws-2.7.7.jar,
                        **/cxf-rt-transports-http-2.7.7.jar,
                        **/neethi-3.0.0.jar,
                        **/servlet-api-2.5-6.1.5.jar,
                        **/velocity-1.3.jar,
                        **/mail-1.3.jar,
                        **/xerces-1.2.3.jar,
                        **/xercesImpl-2.9.1.jar,
                        **/ota-car-rentals-v2-2.0-SNAPSHOT.jar,
                        **/otasonata-FINAL.jar,
                        **/wagon*.jar,
                        **/doxia*.jar,
                        **/maven*.jar,
                        **/javaee-api-6.0.jar
                 </packagingExcludes>

                </configuration>

              <dependencies>

     <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>

        <!-- Apache Commons -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1</version>
        </dependency>

        <!-- Apache POI -->
        <dependency>
            <groupId>org.apache.poi</groupId>
             <artifactId>poi-ooxml</artifactId>
            <version>3.10.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
             <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.10.1</version>
        </dependency>
         <dependency>
             <groupId>org.apache.poi</groupId>
             <artifactId>poi</artifactId>
            <version>3.10.1</version>
        </dependency>

        <!-- JoSQL -->
        <dependency>
            <groupId>JoSQL</groupId>
             <artifactId>JoSQL</artifactId>
                <version>1.9</version>
        </dependency>

        <dependency>
            <groupId>gently</groupId>
            <artifactId>gently</artifactId>
            <version>1.5</version>
        </dependency>

 <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-api</artifactId>
            <version>2.7.7</version>

        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>2.7.7</version>

        </dependency>

        <dependency>
            <groupId>org.apache.ws.commons.schema</groupId>
            <artifactId>XmlSchema</artifactId>
            <version>1.3.2</version>

        </dependency>

 </dependencies>

</project>

A: Add this dependency:
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>${cxf.version}</version>
    </dependency>

If you look inside of this JAR, you'll see a file META-INF/spring.handlers:
http\://cxf.apache.org/transports/http/configuration=org.apache.cxf.transport.http.spring.NamespaceHandler

This says "If someone asks for http://cxf.apache.org/transports/http/configuration, then delegate to the Java class org.apache.cxf.transport.http.spring.NamespaceHandler"


text:
Q: How do I create an array of individual objects Javascript they all point to the same object "bestGamer" I don't want them to do that, I want that each cell in the array will be an individual object with different values in their props.
I want to do it static cause later I want to pass an array, I don't to push in runtime different values
const bestGamer = {
        "name" : "",
        "points" : 0
}
arr2 = new Array(2).fill(bestGamer)
console.log("First:",arr2[0])
console.log("Second:",arr2[1]);
arr2[0].name ="Yossi"
arr2[0].points++
arr2[1].name ="Dima"
arr2[1].points++
console.log("First:",arr2[0]);
console.log("Second:",arr2[1]);
console.log("Orignal Object",bestGamer);

A: You need to create a copy while placing it into newArray, fill(bestGamer) places same bestGamer on all indices so you end up having same reference at all indices

let bestGamer = { a: 1,  b: 2 }
let newArr = new Array(2).fill(0).map(v=> ({...bestGamer}))

newArr[0].a = 10
console.log(newArr)

Instead of new Array you can use Array.from

let bestGamer = { a: 1,  b: 2 }
let newArr = Array.from({length:2}, () => ({...bestGamer}) )

newArr[0].a = 10
console.log(newArr)

A: You're filling the array with bestGamer, so it'll be filled with references to that same object. You need to create a new object for each element. An easy way to do this is combining Array.map with Object.assign:
arr2 = new Array(2).fill(0).map(() => Object.assign({}, bestGamer));

A: to create an array that has individual objects, you can do this.
Step 1: declare an array
var myArray = [];

Step 2: add an object to it
myArray.push[{0, 1, 2, 3}]

Now your array has 1 item. This item is item[0]. Item[0] is an object. It has multiple values inside of it, in this case 4. so to access the second item inside of item[0] you can have item[0][1].


text:
Q: How to get group matches of regular expressions in CMake? Let's look at the following illustrative example.
set(TEXT "ab,cc,df,gg")
string(REGEX MATCHALL "((.)\\2)" RESULT "${TEXT}")
message("Result: ${RESULT}")

# Expected:  Result: cc;gg
# Actual:    Result:

Compare the expected result on regex101.
Does anyone know how to retrieve match group 1 correctly in the above example? Is this possible at all with CMake?
I couldn't find much on the limitations of the regular expression processor used by CMake in the web. Who knows more? (There's a little something written about this in CMake FAQ)
Thanks for the support!

A: CMake's regular expressions are relatively limited. Look at the static char* regatom (int *flagp) method in RegularExpression.cxx. A \\
indicates that the next character is escaped (treated literally). It looks like there are no back-references possible in the CMake regex.
As a work around, you can invoke shell commands using execute_process.
set(TEXT "ab,cc,df,gg")
message("TEXT: ${TEXT}")

execute_process(
    COMMAND echo ${TEXT}
    COMMAND sed "s/.*\\(\\(.\\)\\2\\).*/\\1/g"
    OUTPUT_VARIABLE RESULT OUTPUT_STRIP_TRAILING_WHITESPACE
    )

message("RESULT: ${RESULT}")

This produces:
TEXT: ab,cc,df,gg
RESULT: gg

You will have to adjust your regex do produce cc;gg from the given string.


text:
Q: Reading a text file word by word I have a text file containing just lowercase letters and no punctuation except for spaces. I would like to know the best way of reading the file char by char, in a way that if the next char is a space, it signifies the end of one word and the start of a new word. i.e. as each character is read it is added to a string, if the next char is space, then the word is passed to another method and reset until the reader reaches the end of the file.
I'm trying to do this with a StringReader, something like this:
public String GetNextWord(StringReader reader)
{
    String word = "";
    char c;
    do
    {
        c = Convert.ToChar(reader.Read());
        word += c;
    } while (c != ' ');
    return word;
}

and put the GetNextWord method in a while loop till the end of the file. Does this approach make sense or are there better ways of achieving this?

A: If you're interested in good performance even on very large files, you should have a look at the new(4.0) MemoryMappedFile-Class.
For example:
using (var mappedFile1 = MemoryMappedFile.CreateFromFile(filePath))
{
    using (Stream mmStream = mappedFile1.CreateViewStream())
    {
        using (StreamReader sr = new StreamReader(mmStream, ASCIIEncoding.ASCII))
        {
            while (!sr.EndOfStream)
            {
                var line = sr.ReadLine();
                var lineWords = line.Split(' ');
            }
        }
    }
}

From MSDN:

A memory-mapped file maps the contents of a file to an application's
  logical address space. Memory-mapped files enable programmers to work
  with extremely large files because memory can be managed concurrently,
  and they allow complete, random access to a file without the need for
  seeking. Memory-mapped files can also be shared across multiple
  processes.
The CreateFromFile methods create a memory-mapped file from a
  specified path or a FileStream of an existing file on disk. Changes
  are automatically propagated to disk when the file is unmapped.
The CreateNew methods create a memory-mapped file that is not mapped
  to an existing file on disk; and are suitable for creating shared
  memory for interprocess communication (IPC).
A memory-mapped file is associated with a name.
You can create multiple views of the memory-mapped file, including
  views of parts of the file. You can map the same part of a file to
  more than one address to create concurrent memory. For two views to
  remain concurrent, they have to be created from the same memory-mapped
  file. Creating two file mappings of the same file with two views does
  not provide concurrency.

A: First of all: StringReader reads from a string which is already in memory. This means that you will have to load up the input file in its entirety before being able to read from it, which kind of defeats the purpose of reading a few characters at a time; it can also be undesirable or even impossible if the input is very large.
The class to read from a text stream (which is an abstraction over a source of data) is StreamReader, and you would might want to use that one instead. Now StreamReader and StringReader share an abstract base class TextReader, which means that if you code against TextReader then you can have the best of both worlds.
TextReader's public interface will indeed support your example code, so I 'd say it's a reasonable starting point. You just need to fix the one glaring bug: there is no check for Read returning -1 (which signifies the end of available data).

A: The String lib provides an easy way of doing this: string.Split(): if you read the entire string in, C# can automatically split it on every space:
string[] words = reader.ReadToEnd().Split(' ');

The words array now contains all of the words in the file and you can do whatever you want with them.
Additionally, you may want to investigate the File.ReadAllText method  in the System.IO namespace - it may make your life much easier for file imports to text.
Edit: I guess this assumes that your file is not abhorrently large; as long as the entire thing can be reasonably read into memory, this will work most easily. If you have gigabytes of data to read in, you'll probably want to shy away from this. I'd suggest using this approach though, if possible: it makes better use of the framework that you have at your disposal.

A: All in one line, here you go (assuming ASCII and perhaps not a 2gb file):
var file = File.ReadAllText(@"C:\myfile.txt", Encoding.ASCII).Split(new[] { ' ' });

This returns a string array, which you can iterate over and do whatever you need with.

A: I would do something like this:
IEnumerable<string> ReadWords(StreamReader reader)
{
    string line;
    while((line = reader.ReadLine())!=null)
    {
        foreach(string word in line.Split(new [1] {' '}, StringSplitOptions.RemoveEmptyEntries))
        {
            yield return word;
        }
    }
}

If to use reader.ReadAllText it loads the entire file into your memory so you can get OutOfMemoryException and a lot of other problems.

A: If you want to read it whitout spliting the string - for example lines are too long, so you might encounter OutOfMemoryException, you should do it like this (using streamreader):
while (sr.Peek() >= 0)
{
    c = (char)sr.Read();
    if (c.Equals(' ') || c.Equals('\t') || c.Equals('\n') || c.Equals('\r'))
    {
        break;
    }
    else
        word += c;
}
return word;

A: This is method that will split your words, while they are separated by space or more than 1 space (two spaces for example)/
StreamReader streamReader = new StreamReader(filePath); //get the file
string stringWithMultipleSpaces= streamReader.ReadToEnd(); //load file to string
streamReader.Close();

Regex r = new Regex(" +"); //specify delimiter (spaces)
string [] words = r.Split(stringWithMultipleSpaces); //(convert string to array of words)

foreach (String W in words)
{
   MessageBox.Show(W);
}

A: I created a simple console program on your exact requirement with the files you mentioned, It should be easy to run and check. Please find attached the code. Hope this helps
static void Main(string[] args)
    {

        string[] input = File.ReadAllLines(@"C:\Users\achikhale\Desktop\file.txt");
        string[] array1File = File.ReadAllLines(@"C:\Users\achikhale\Desktop\array1.txt");
        string[] array2File = File.ReadAllLines(@"C:\Users\achikhale\Desktop\array2.txt");

        List<string> finalResultarray1File = new List<string>();
        List<string> finalResultarray2File = new List<string>();

        foreach (string inputstring in input)
        {
            string[] wordTemps = inputstring.Split(' ');//  .Split(' ');

            foreach (string array1Filestring in array1File)
            {
                string[] word1Temps = array1Filestring.Split(' ');

                var result = word1Temps.Where(y => !string.IsNullOrEmpty(y) && wordTemps.Contains(y)).ToList();

                if (result.Count > 0)
                {
                    finalResultarray1File.AddRange(result);
                }

            }

        }

        foreach (string inputstring in input)
        {
            string[] wordTemps = inputstring.Split(' ');//  .Split(' ');

            foreach (string array2Filestring in array2File)
            {
                string[] word1Temps = array2Filestring.Split(' ');

                var result = word1Temps.Where(y => !string.IsNullOrEmpty(y) && wordTemps.Contains(y)).ToList();

                if (result.Count > 0)
                {
                    finalResultarray2File.AddRange(result);
                }

            }

        }

        if (finalResultarray1File.Count > 0)
        {
            Console.WriteLine("file array1.txt contians words: {0}", string.Join(";", finalResultarray1File));
        }

        if (finalResultarray2File.Count > 0)
        {
            Console.WriteLine("file array2.txt contians words: {0}", string.Join(";", finalResultarray2File));
        }

        Console.ReadLine();

    }
}

A: This code will extract words from a text file based on the Regex pattern. You can try playing with other patterns to see what works best for you.
    StreamReader reader =  new StreamReader(fileName);

    var pattern = new Regex(
              @"( [^\W_\d]              # starting with a letter
                                        # followed by a run of either...
                  ( [^\W_\d] |          #   more letters or
                    [-'\d](?=[^\W_\d])  #   ', -, or digit followed by a letter
                  )*
                  [^\W_\d]              # and finishing with a letter
                )",
              RegexOptions.IgnorePatternWhitespace);

    string input = reader.ReadToEnd();

    foreach (Match m in pattern.Matches(input))
        Console.WriteLine("{0}", m.Groups[1].Value);

    reader.Close();


text:
Q: What are the advantages of adding a Mac to Active Directory? I was surprised to learn (from this question:  How to add a Mac to Windows Active Directory)  that you could add a Mac to AD.
What are the advantages of doing so?

A: It helps with asset management. Most asset management pieces that plug into AD can query for a list of computer objects. As long as those are kept up-to-date, you can use that to help track systems in the organization.

A: One of the main reasons you would do it is to authenticate users against Active Directory. By authenticating against AD it also makes access to file shares and printers much easier, as you are already authenticated.

A: To name a few:

*

*same password policy as Window devices;

*mounting CIFS shares that are specified for each user in their AD user account;

*SSO to applications that support Kerberos, login scripts;

*Restricting access to network/file resources;

*audit trails, 802.1x (wired/wireless);

*AD extension for Macs that can control policies much like a Windows client;


text:
Q: Selecting color when hovering over navbar So I have this navigation bar that I want to change the color of when hovering over with the mouse. Its default is black, I want it to be lightgrey-white. What have I done wrong here?
HTML:
<!DOCTYPE html>

    <title>Frontend</title>

                        <input id="sweBtn" type="button" value="SVENSKA" />
                        <input id="engBtn" type="button" value="ENGLISH" />
                        <input id="searchTxt" type="text" />
                        <input id="searchBtn" type="button" value="SÖK" />

Title

Paragraph

 //Here is the navbar I am talking about

BEHÖVER DU AVOKAT?

ADVOKATETIK

ATT BLI ADVOKAT

UTBILDNING

ADVOKATSSAMFUNDET TYCKER

<link href="~/Content/custom.css" rel="stylesheet" />

CSS:
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

    li a {
        display: block;
        color: white;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }

        li a:hover {
            background-color: #111;
        }

#header {
    background-color: #503F31;
    color: white;
    padding: 30px;
}

#searchMenu {
    margin-left: 1450px;
}

#sweBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: grey;
}

#engBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: gold;
}

#searchTxt {
    background-color: grey;
    border-color: grey;
}

#searchBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: gold;
}

#imgText {
    font-size: 25px;
    position: absolute;
}

#imgHeader {
    width: 1904px;
}

#navBar {
    font-family: 'Times New Roman';
    color: gold;
    background-color: #503F31;
}

#footer {
    background-color: grey;
    color: white;
    padding-bottom: -250px;
}

*::selection { /*This should handle the hover color situation right?*/
  background: #cc0000;
  color: #ffffff;
}
*::-moz-selection {
  background: #cc0000;
  color: #ffffff;
}
*::-webkit-selection {
  background: #cc0000;
  color: #ffffff;
}

Also a sidenote: I want for every listitem to be seperated with a vertical line like this: "|"

A: Change the li a:hover background-color to #CCC and remove this:
*::selection { /*This should handle the hover color situation right?*/
  background: #cc0000;
  color: #ffffff;
}
*::-moz-selection {
   background: #cc0000;
   color: #ffffff;
}
*::-webkit-selection {
   background: #cc0000;
   color: #ffffff;
}

I'm assuming your #111 isn't 'black' but 'blackish' and therefore, seen as black ;).

A: Just replace this blocks:
li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    /* Separator Border */
    border-right: 1px solid #000;
}

li a:hover {
    /* Background color on hover */
    background-color: silver;
    color: #fff;
}

Final css:
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    border-right: 1px solid #000;
}

li a:hover {
    background-color: silver;
    color: #fff;
}

#header {
    background-color: #503F31;
    color: white;
    padding: 30px;
}

#searchMenu {
    margin-left: 1450px;
}

#sweBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: grey;
}

#engBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: gold;
}

#searchTxt {
    background-color: grey;
    border-color: grey;
}

#searchBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: gold;
}

#imgText {
    font-size: 25px;
    position: absolute;
}

#imgHeader {
    width: 1904px;
}

#navBar {
    font-family: 'Times New Roman';
    color: gold;
    background-color: #503F31;
}

#footer {
    background-color: grey;
    color: white;
    padding-bottom: -250px;
}

*::selection { /*This should handle the hover color situation right?*/
  background: #cc0000;
  color: #ffffff;
}
*::-moz-selection {
  background: #cc0000;
  color: #ffffff;
}
*::-webkit-selection {
  background: #cc0000;
  color: #ffffff;
}

A: Try adding braces:
li a:hover {{background-color: #111;}}


text:
Q: Remove older logs than 2 months from all tables starting with raw_% I got mysql database which contains tables with logs from other systems. Each system has its own table, I want to automatically remove logs older than 2 months. I almost got it but I get an error during PREPARING the statement.
This is what I got:
-- Set up variable to delete ALL tables starting with 'raw_'
SET GROUP_CONCAT_MAX_LEN=100000;

SET @delStmt = (SELECT GROUP_CONCAT(CONCAT('DELETE FROM `', TABLE_SCHEMA, '`.`', TABLE_NAME, '` WHERE time < DATE(NOW() - INTERVAL 2 MONTH);') SEPARATOR ' ')
       FROM information_schema.TABLES
      WHERE TABLE_SCHEMA = 'log_cmd'
        AND TABLE_NAME LIKE 'raw_%');

-- SELECT @delStmt;

PREPARE stmt FROM @delStmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

And the error I get is:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DELETE FROM `log_cmd`.`raw_10203040` WHERE time < DATE(NOW() - INTERVAL 2 MONTH)' at line 1

Not sure what I am doing wrong.
Thanks in advance.

A: How to debug
You should un comment -- SELECT @delStmt; , and comment the last three lines.
You will get back the actual generated SQL statement.
You can then copy and run the statement on the actual server to get the real error message.
Observations
I ran your statement on my own system and I get null.
However, I don't have the same tables on my system, so I removed the where condition in delStmt and am getting the following:

DELETE FROM information_schema.ALL_PLUGINS WHERE time < DATE(NOW()
  - INTERVAL 2 MONTH); DELETE FROM information_schema.APPLICABLE_ROLES WHERE time < DATE(NOW() -
  INTERVAL 2 MONTH); DELETE FROM information_schema.CHARACTER_SETS
  WHERE time < DATE(NOW() - INTERVAL 2 MONTH); DELETE FROM
  information_schema.COLLATIONS WHERE time < DATE(NOW() - INTERVAL 2
  MONTH); ...

And the list goes on ...
Update
I think the error is actually related to trying to execute two SQL statements, separated by a ;.
I was able to successfully execute the delete statements one by one.
Proof of concept:
drop table raw_1;
create table raw_1(
  time int
);

drop table raw_2;
create table raw_2(
  time int
);

SET GROUP_CONCAT_MAX_LEN=100000;

SET @delStmt = (SELECT GROUP_CONCAT(CONCAT('DELETE FROM `', TABLE_SCHEMA, '`.`', TABLE_NAME, '` WHERE time < DATE(NOW() - INTERVAL 2 MONTH);') SEPARATOR ' ')
                FROM information_schema.TABLES
                WHERE TABLE_NAME LIKE 'raw_%');

SELECT @delStmt;

PREPARE stmt FROM @delStmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Result:
DELETE FROM `test`.`raw_1` WHERE time < DATE(NOW() - INTERVAL 2 MONTH); \
DELETE FROM `test`.`raw_2` WHERE time < DATE(NOW() - INTERVAL 2 MONTH);

Final Answer
The command was failing due to being multiple statements. Splitting the execution into multiple solves the problem. Another solution is to save the commands to a file and execute (as Alek says).
#Will not work without the following command/Setting:
SET SESSION sql_mode = CONCAT(@@sql_mode, ',PIPES_AS_CONCAT');

drop table raw_1;
create table  IF NOT EXISTS  raw_1(
  time int
);

create table  IF NOT EXISTS  raw_2(
  time int
);

SET SESSION sql_mode = CONCAT(@@sql_mode, ',PIPES_AS_CONCAT');

DROP PROCEDURE IF EXISTS `deleteFromLogs`;

CREATE PROCEDURE deleteFromLogs()
  BEGIN

    DECLARE torun varchar(100);
    DECLARE v_last_row_fetched INT;
    DECLARE counter CURSOR FOR SELECT 'DELETE FROM `' || TABLE_SCHEMA || '`.`' || TABLE_NAME || '` WHERE time < DATE(NOW() - INTERVAL 2 MONTH);' as torun
                               FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'raw_%' AND TABLE_SCHEMA = 'log_cmd' ;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_last_row_fetched = 1;

    SET SESSION sql_mode = CONCAT(@@sql_mode, ',PIPES_AS_CONCAT');

    OPEN counter;
    c1_loop: LOOP
      FETCH counter
      INTO torun;

      IF v_last_row_fetched = 1
      THEN LEAVE c1_loop;
      END IF;

      SET @delStmt = torun;
      select @delStmt;

#       PREPARE stmt1 FROM @delStmt;
#       EXECUTE stmt1;
#       DEALLOCATE PREPARE stmt1;
#       COMMIT;

    END LOOP c1_loop;
    CLOSE counter;

  END;

CALL deleteFromLogs();

https://www.db-fiddle.com/f/cVJ4uDhQYQALMvSURSEq4Y/1

A: I found a solution to the problem. The easiest way is to put commands into a file and execute it.
SET GROUP_CONCAT_MAX_LEN=100000;

SET @delStmt = (SELECT GROUP_CONCAT(CONCAT('DELETE FROM `', TABLE_SCHEMA, '`.`', TABLE_NAME, '` WHERE time < DATE(NOW() - INTERVAL 2 MONTH);') SEPARATOR ' ')
   FROM information_schema.TABLES
  WHERE TABLE_SCHEMA = 'log_cmd'
    AND TABLE_NAME LIKE 'raw_%');

SELECT @delStmt INTO OUTFILE '/tmp/temp.sql';
SOURCE /tmp/temp.sql;

Thanks for help


text:
Q: Open CMD in the directory where my program is I have a piece of software written in c++, that has to call command line and execute 2 simple commands. The problem is, they need to be executed in the main directory of my program (folder where exe file is). How can I make sure, that they will execute in this directory, if it can be different on PCs (for example "Program Files" or "Program Files(x86)").

A: On windows, you can use the GetModuleFileName WinAPI, which will return you the path of the exe that you can cd to and execute your commands.


text:
Q: Replacing NULL with NA in R after Pivot Wider I have a huge dataset that I transformed using pivot_wider function. This resulted in a lot of values containing NULL. Now I want to transform those values to NA but none of my approaches seems to work:
 df %>% replace(.=="NULL", NA)
df[df==0] <- NA
Also when using the pivot_wider function the values_fill = NA argument doesn't produce any NA's too.
Thanks in advance for your help.

A: I think you have data which is something like this -
df <- data.frame(a1 = c(1, 1, 1, 1,2), a2 = 1:5, a3 = c('a', 'b', 'c', 'a', 'b'))

df
#  a1 a2 a3
#1  1  1  a
#2  1  2  b
#3  1  3  c
#4  1  4  a
#5  2  5  b

Then you are using pivot_wider which returns
df1 <- tidyr::pivot_wider(df, names_from = a3, values_from = a2)

#     a1   a         b         c
#  <dbl> <list>    <list>    <list>
#1     1 <dbl [2]> <dbl [1]> <dbl [1]>
#2     2 <NULL>    <dbl [1]> <NULL>

This also returns the warning messages -

Warning message:
Values are not uniquely identified; output will contain list-cols.

*

*Use values_fn = list to suppress this warning.

*Use values_fn = length to identify where the duplicates arise

*Use values_fn = {summary_fun} to summarise duplicates

To answer your question about replacing these NULL values with NA you can do -
df1 <- df1 %>% mutate(across(a:c, ~replace(., lengths(.) == 0, NA)))
df1

#    a1    a         b         c
#  <dbl> <list>    <list>    <list>
#1     1 <dbl [2]> <dbl [1]> <dbl [1]>
#2     2 <lgl [1]> <dbl [1]> <lgl [1]>

But you should not ignore those warnings and check pivot_wider issue "Values in `values_from` are not uniquely identified; output will contain list-cols" if this would be a better option for your data.

A: If you want to replace all NULL values in your dataframe with NA you can do -
df1 <- df1 %>% mutate_all( ~replace(., lengths(.)==0, NA))

If you want to replace all NULL values with 0s, change the NA to 0 in the code.


text:
Q: How to extract objects from json I have a scenario where I need only 1 objects out of the entire json.
{"id":"1","first_name":"Steve","last_name":"Holt","user_type":"Teacher","user_key_area":"Math"}

In above I want to extract user_type.
How will I do?

A: You can use Google GSON to parse the json response and map it to the model directly . Here is the tutorial for the same TUTORIAL

A: Use this to extract the user_type from the json, pass the your json response in place of response variable.
JsonObject object =new JsonObject(response);

String user_type = object.getString("user_type");

A: You are getting this json in response you can get 1 object like this:
String value = response.getString("Key Name");

A: Get Response and that create JsonObject
JsonObject jsonObject =new JsonObject(res);

Create String object and pass string parameter "user_type"
String userType = jsonObject.getString("user_type");


text:
Q: Stream-Static join without aggregation still results in accumulating spark state I'm using Spark Structured Streaming (PySpark) to join a Kafka Stream with a Static DataFrame using a MinHashLSH approxSimilarityJoin (which under the hood does a SortMergeJoin).
The size and volume of these messages is fairly high, which results in a state of multiple GBs after a couple hours. After a while the causes OOMerrors and crashes the process.
According to the docs, stream-static joins are stateless so I would expect no state to be accumulated over time. In this use case, we are also not interested in preserving any state other than the Kafka offset.
This image below shows the State size after a few minutes, the left side of the SortMergeJoin is the static frame, while the right side is the Kafka Stream. No watermarks or dropduplicates have been added along the way.
Does anyone have an idea on how I can reduce the size of this state or even get rid of it all together?


text:
Q: Soft video encoder for M4 Video encoding is a computationally heavy task. I like to ask, are the video specs that can be managed with a ARM M4 (STM32F4 type CPU) type CPU? Perhaps low frame rate (10fps) and only VGA quality.

A: THere seems to be a lot of info on QVGA and not so much on VGA
http://www.codeforge.com/s/0/STM32F4-VGA-320x200-256-colors-keil
But this brochure has some info
With a 48MHz PIXCLK and 8-bit parallel input data interface it is possible to receive:
 - up to 15fps uncompressed data stream in SXGA resolution(1280x1024) with 16-bit per pixel
 - up to 30fps uncompressed data stream in VGA resolution (640x480)with 16-bit per pixel


text:
Q: Random image in Google slides How could I insert a random image into Google Slides? like if I use a link, that always leads to a random image, to where I don't even know what the image will be once I present. -Thanks
(This link can be used to go to a random picture: https://source.unsplash.com/random/300x200)

A: As @Tanaike commented you cannot access a resource that needs authorization using Simple Triggers.

They cannot access services that require authorization.

onOpen(e) Simple Trigger pointing to "https://www.googleapis.com/auth/script.external_request" scope in this case
As a workaround you could change the images every day, using a Time Driven Installable Trigger.
Code.gs
function changeImage() {
  let slideP = SlidesApp.getActivePresentation()
  let slide1 = slideP.getSlides()[0]
  let img = slide1.getImages()[0]
  // Fetch a new image
  let req = UrlFetchApp.fetch('https://source.unsplash.com/random/300x200')
  let blobImage = req.getAs('image/jpeg')
  // Get the properties of the actual image
  let [left, top, width, height] = [
    img.getLeft(),
    img.getTop(),
    img.getWidth(),
    img.getHeight()
  ]
  // Remove the old one
  img.remove()
  // Add the new one with the same attributes
  slide1.insertImage(blobImage, left, top, width, height)
}

Then simply add the function to a Trigger.


text:
Q: MonacoEditor not working with Jest and React Testing Library I am writing test cases for a component and currently using MonacoEditor in my component.
During running test cases I was getting below error:
Cannot find module 'monaco-editor' from 'node_modules/@uiw/react-monacoeditor/lib/index.js'

To Fix this above error I added a moduleNameMapper property inside package.json
"moduleNameMapper": {
      "monaco-editor": "<rootDir>/node_modules/@uiw/react-monacoeditor/lib/index"
    }

and after adding the property inside package.json and ran test case again I got the following error somewhere inside monacoEditor node_modules config files.
Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'create')]

I am looking for some workaround so I can completely mock this MonacoEditor module with jest and react testing library (RTL) or any way to resolve the error I am getting currently
Tried to mock like below and tried numerous ways provided online but nothing worked.
jest.mock('@uiw/react-monacoeditor', ()=>({
    MonacoEditor: ()=>null
}));

Error I am getting now:
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Thanks in advance

A: This issue can be fixed by mocking the component returned by react-monacoeditor library
jest.mock('@uiw/react-monacoeditor', ()=>({})=>(

));

A: I had also being struggled with this issue for couple of hours.
I fixed it using following steps:
1). Create mocks directory in the projects root (at the same level with node-modules);
2). Create monaco-editor.ts that exports modules you need:
module.exports = {
  editor: {
    getModelMarkers: jest.fn().mockReturnValue([]),
    // other methods here
  },
  Position: {},
  // other modules here
};

And that's it! When Jest parser finds imported 'monaco-editor' modules it looks in mocks folder first where finds our created 'monaco-editor.ts' module. Then it takes all the required modules from here.


text:
Q: can anyone help me with my code in c# it always outputs 0 in message box thanks for your fast response guys, so this is what I have now..
my problem is, it requires me to add parameter in Form2 f2 = new Form2(); part but if i did i got this error Error  "A field initializer cannot reference the non-static field, method, or property "
for my Form1 I didnt edit this one ^
public partial class Form1 : Form
    {

        Form2 f2 = new Form2();
        int userInputValue;
        string userInputValueConverted;
        string formulaShow = "";
        public double answer = 0.0;
        public double output;

        public Form1()
        {
            InitializeComponent();
        }

            f2.DuAnswer = output;
            f2.Formula.Text = formulaShow;
            f2.Show();

for my FORM2 i only have 1 constructor
public double duAnswer;

public Form2(double output)
{
    InitializeComponent();
    duAnswer = output;
}

public double DuAnswer
{
    get
    {
        return duAnswer;
    }

    set
    {
        duAnswer = value;
    }
}

and for my result button
 private void result_Click(object sender, EventArgs e)
        {
            MessageBox.Show("" + duAnswer.ToString("F2"));
        }

A: When you show your Form2 instance, you're creating a new instance of Form2.  This isn't needed, but instead, you need to set the answer on the existing form2:
// Don't create this
// Form2 outP = new Form2(output);

f2.DuAnswer = output;
f2.Formula.Text = formulaShow;
f2.Show();

This also means you don't need the second constructor:
// public Form2(double output)
// {
//    duAnswer = output;
// }

Also note that, if you do decide to include the second alternative constructor, it's important that it also calls InitializeComponent():
public Form2(double output)
{
   InitializeComponent(); // This is critical for a form
   duAnswer = output;
}

You can alternatively use constructor chaining to accomplish this:
public Form2(double output)
   : this()
{
   duAnswer = output;
}

A: You are not passing the value of answer to the output, but instantiating Form2 with the output variable that does not have any value assigned to it.
Why do you need two of them anyway? Why not just do Form2 frm = new Form2(answer);


text:
Q: How can I define Model ViewSet for contact form that sends email in django-rest-framework? I have a APIView for a contact that takes input data from user and send it to mail:
from django.core.mail import send_mail

class ContactView(APIView):
    serializer_class = ContactSerializer

    def post(self, request, *args, **kwargs):
        serializer_class = ContactSerializer(data = request.data)
        if serializer_class.is_valid():
            data = serializer_class.validated_data
            name = data.get('name')
            email = data.get('email')
            message = data.get('message')

            send_mail('Contact Form Mail from ' + name, message, email, ['bibekjoshi34@gmail.com'],)

            return Response({"success":"sent"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST)

urls.py
urlpatterns = [
    path('contactapi', views.ContactView.as_view()),
]

Question:
How can I do it using DRF ModelViewset? This below code isn't working.
class CustomerContactViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Contact.objects.all()
    http_method_names = ['post']

    serializer_class = ContactSerializer

    def post(self, request):
        serializer_class = ContactSerializer(data=request.data)
        if serializer_class.is_valid():
            data = serializer_class.validated_data
            full_name = data.get('full_name')
            email = data.get('email')
            phone_no = data.get('phone_no')
            message = data.get('message')

            send_mail('Mail From' + full_name, phone_no, message, email, ['bibekjoshi34@gmail.com'],)

            return Response({"success":"sent"}, status=status.HTTP_200_OK)
        else:
            return Response({"error":"failed"}, status=status.HTTP_400_BAD_REQUEST)

What is the best way to make contact-form: that stores data in database as well as sends to the admin mail: --------> For Production Level?


text:
Q: Flutter Error: no such module 'GoogleMaps' I am working in a project bought by a client. The project is Fluxstore. A E-commerce built with Flutter.
I can run the project in Android (emulator and device=). But iOS doesn't run. I get this following error:
Launching lib/main.dart on iPhone 11 in debug mode...
Running pod install...
Running Xcode build...
Xcode build done.                                           138,6s
Failed to build iOS app
Could not build the application for the simulator.
Error launching application on iPhone 11.
Error output from Xcode build:
↳
** BUILD FAILED **

Xcode's output:
↳
/Users/user./projects/project/ios/Runner/AppDelegate.swift:3:8: error: no such module 'GoogleMaps'
import GoogleMaps
       ^
note: Using new build system
note: Building targets in parallel
note: Planning build
note: Constructing build description

I looked up on solutions for this issue in Internet but nothing works. Can somebody please help me?

A: delete all pod file. run flutter clean. then go to iOS folder and run pod init. It's create a pod file. Add  pod 'GoogleMaps' this line here before target 'Runner' do
I share my pod file code
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
pod 'Firebase/Analytics'
pod 'GoogleMaps'
# add pods for any other desired Firebase products
# https://firebase.google.com/docs/ios/setup#available-pods

target 'Runner' do
  # Comment the next line if you don't want to use dynamic frameworks

  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for Runner

end

A: flutter pub get
cd ios
pod install
pod update

A: Did you check in the pubspec.yaml if the project still uses google_maps? Because if not, then you should remove the two lines in the AppDelegate.swift. (The import of google_maps and the GMSServices.provideAPIKey.
This should solve the problem.

A: This problem is because you opened the project in the wrong directory in xcode. If you open it correctly and try it, the problem will be solved.
Note: Applies to Flutter projects.

A: Ensure you import google map in your appdelgate.swift
import UIKit
import Flutter
import GoogleMaps //This line

    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
        GMSServices.provideAPIKey("MAP API KEY")
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }


text:
Q: PHP Fatal error: Using $this when not in object context I've got a problem:
I'm writing a new WebApp without a Framework.
In my index.php I'm using: require_once('load.php');
And in load.php I'm using require_once('class.php'); to load my class.php.
In my class.php I've got this error:

Fatal error: Using $this when not in object context in class.php on line ... (in this example it would be 11)

An example how my class.php is written:
class foobar {

    public $foo;

    public function __construct() {
        global $foo;

        $this->foo = $foo;
    }

    public function foobarfunc() {
        return $this->foo();
    }

    public function foo() {
        return $this->foo;
    }
}

In my index.php I'm loading maybe foobarfunc() like this:
foobar::foobarfunc();

but can also be
$foobar = new foobar;
$foobar->foobarfunc();

Why is the error coming?

A: First you understand one thing, $this inside a class denotes the current object.
That is which is you are created out side of the class to call class function or variable.
So when you are calling your class function like foobar::foobarfunc(), object is not created.
But inside that function you written return $this->foo(). Now here $this is nothing. Thats why its saying Using $this when not in object context in class.php
Solutions:

*

*Create a object and call foobarfunc().

*Call foo() using class name inside the foobarfunc().

A: When you call the function in a static context, $this simply doesn't exist.
You would have to use this::xyz() instead.
To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I'm static or an object?

A: Fast method : (new foobar())->foobarfunc();
You need to load your class replace :
foobar::foobarfunc();

by :
(new foobar())->foobarfunc();

or :
$Foobar = new foobar();
$Foobar->foobarfunc();

Or make static function to use foobar::.
class foobar {
    //...

    static function foobarfunc() {
        return $this->foo();
    }
}

A: You are calling a non-static method :
public function foobarfunc() {
    return $this->foo();
}

Using a static-call :
foobar::foobarfunc();

When using a static-call, the function will be called (even if not declared as static), but, as there is no instance of an object, there is no $this.
So :

*

*You should not use static calls for non-static methods

*Your static methods (or statically-called methods) can't use $this, which normally points to the current instance of the class, as there is no class instance when you're using static-calls.

Here, the methods of your class are using the current instance of the class, as they need to access the $foo property of the class.
This means your methods need an instance of the class -- which means they cannot be static.
This means you shouldn't use static calls : you should instanciate the class, and use the object to call the methods, like you did in your last portion of code :
$foobar = new foobar();
$foobar->foobarfunc();

For more informations, don't hesitate to read, in the PHP manual :

*

*The Classes and Objects section

*And the Static Keyword page.

Also note that you probably don't need this line in your __construct method :
global $foo;

Using the global keyword will make the $foo variable, declared outside of all functions and classes, visibile from inside that method... And you probably don't have such a $foo variable.
To access the $foo class-property, you only need to use $this->foo, like you did.

A:
In my index.php I'm loading maybe
foobarfunc() like this:

 foobar::foobarfunc();  // Wrong, it is not static method

but can also be

$foobar = new foobar;  // correct
$foobar->foobarfunc();

You can not invoke the method this way because it is not a static method.
foobar::foobarfunc();

You should instead use:
$foobar->foobarfunc();

If however, you have created a static method something like:
static $foo; // your top variable set as static

public static function foobarfunc() {
    return self::$foo;
}

then you can use this:
foobar::foobarfunc();

A: It seems to me to be a bug in PHP.
The error

'Fatal error: Uncaught Error: Using $this when not in object context
in'

appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:
Class_Name
{
    function foo()
    {
        $this->do_something(); // The error appears there.
    }
    function do_something()
    {
        ///
    }
}

While the error is here:
Class_Name::foo();

A: If you are invoking foobarfunc with resolution scope operator (::), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this when not in object context. $this does not exist in class context.
If you enable E_STRICT, PHP will raise a Notice about this:
Strict Standards:
Non-static method foobar::foobarfunc() should not be called statically

Do this instead
$fb = new foobar;
echo $fb->foobarfunc();

On a sidenote, I suggest not to use global inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.

A: $foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();
Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.

A: Just use the Class method using this foobar->foobarfunc();


text:
Q: Haskell cabal include static library I have an embarrassingly simple question.
I am trying to use an archive library (call it mylib.a) with a large'ish C project (compiled with GHC's copy of MinGW).
From the top level I have:
./project.cabal
./src/...haskell..code...
./cbits/interface.c (simplifies access to `lib.a`)
./include/mylib.h
./lib/mylib.a      <<<<<<<<<<<<<<< not sure where to put this or how to reference it

The project.cabal has both
c-sources:           cbits/interface.c
include-dirs:        include

The extra-lib-dirs seems to want an absolute path (directory).
How does one solve this?

A: The answer is from here https://github.com/haskell/cabal/issues/4677
I suppose your archive is name libmylib.a, then add this in your cabal file
ghc-Options: -pgml gcc "-optl-Wl,--allow-multiple-definition" "-optl-Wl,--whole-archive" "-optl-Wl,-Bstatic" "-optl-Wl,-lmylib" "-optl-Wl,-Bdynamic" "-optl-Wl,--no-whole-archive"

you might also need to specify the gcc option -L to specify the archive path


text:
Q: Adding a value from Mongoose DB into a variable in Node.js I am still quite new to Node.js and can't seem to find anything to help me around this.
I am having an issue of getting the query from my last record and adding it to my variable.
If I do it like below: -
let lastRecord = Application.find().sort({$natural:-1}).limit(1).then((result) => { result });

Then I get the value of the variable showing in console.log as : -
Promise { <pending> }

What would I need to do to output this correctly to my full data?

A: Instead of using .then(), you'll want to await the record. For example:
let lastRecord = await Application.find().sort({$natural:-1}).limit(1);
You can learn more about awaiting promises in the MDN entry for await, but the basics are that to use a response from a promise, you either use await or you put your logic into the .then statement.

A: Here is it fixed:
Application.findOne().sort({$natural:-1}).exec().then((lastRecord) => {
  console.log(lastRecord); // "lastRecord" is the result. You must use it here.
}, (err) => {
  console.log(err); // This only runs if there was an error. "err" contains the data about the error.
});

Several things:

*

*You are only getting one record, not many records, so you just use findOne instead of find. As a result you also don't need limit(1) anymore.

*You need to call .exec() to actually run the query.

*The result is returned to you inside the callback function, it must be used here.

exec() returns a Promise. A promise in JavaScript is basically just a container that holds a task that will be completed at some point in the future. It has the method then, which allows you to bind functions for it to call when it is complete.
Any time you go out to another server to get some data using JavaScript, the code does not stop and wait for the data. It actually continues executing onward without waiting. This is called "asynchronisity". Then it comes back to run the functions given by then when the data comes back.
Asynchronous is simply a word used to describe a function that will BEGIN executing when you call it, but the code will continue running onward without waiting for it to complete. This is why we need to provide some kind of function for it to come back and execute later when the data is back. This is called a "callback function".
This is a lot to explain from here, but please go do some research on JavaScript Promises and asynchronisity and this will make a lot more sense.
Edit:
If this is inside a function you can do this:
async function someFunc() {
  let lastRecord = await Application.findOne().sort({$natural:-1}).exec();
}

Note the word async before the function. This must me there in order for await to work. However this method is a bit tricky to understand if you don't understand promises already. I'd recommend you start with my first suggestion and work your way up to the async/await syntax once you fully understand promises.


text:
Q: Session not using correct variable I have a session that is supposed to carry a variable from one page to another. The session is set, however it does not have the correct value, I need this session to dynamically change.
Here's the code for the viewing page:
  // Connect to the database
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

      $query = "SELECT username FROM kaoscraft_user WHERE user_id = '" . $_SESSION['user_id'] . "'";
        $data = mysqli_query($dbc, $query);
            $row = mysqli_fetch_array($data);
            $username1 = $row['username'];

  // Grab the pm data from the database
  $query = "SELECT `to`, `from`, rank, gender, picture, title, msg FROM kaoscraft_pm WHERE `to` = '$username1' ORDER BY msg_id DESC";
  $data = mysqli_query($dbc, $query);
  $gender = $row['gender'];

  while ($row = mysqli_fetch_array($data)) {
  session_start();
    $reply = $row['from'];
    $_SESSION['reply'] = $row['from'];
  echo '
';
  echo '
';
    if(!empty($row['picture'])) {
    echo '';
    }
  if(!empty($row['from'])) {
      echo '
From:
' . $row['from'] . '
';
      echo 'Reply';
    }
  if(!empty($row['rank'])) {
      echo '
Rank:
' . $row['rank'] . '
';
    }
  if(!empty($row['gender'])){
    echo '
Gender:
 ' . $row['gender'] . '
';
  }
  echo '
';

    if(!empty($row['title'])) {
        echo'
' .$row['title']. '
';
    }
      if(!empty($row['msg'])) {
      echo '
' . $row['msg'] . '
';
    }
        echo '
';
      if(!empty($row['bio'])) {
      echo '
' . $row['bio'] . '
';
      }
      echo '
';
    echo '

';
    }
  mysqli_close($dbc);
?>

Yes, the query had been executed, and yes row is set.
Here's the carry over script:
    if (isset($_SESSION['reply'])) {
    echo 'value=' . $_SESSION['reply'];
    }

Mind you this is a test script and not the script I will actually be using, just in-case you were wondering. and in the second script it is a SNIPPET not the whole code that is why you do not see session_start();


text:
Q: is placing Entity in the name of a Domain Class a good practice? currently i am discussing if placing entity at the end of each entity is a good practice for example
public class CustomerEntity:BaseEntity{}

instead of
public class Customer:BaseEntity{}

in my career i had seen both, but how do you do it nowadays?

A: Which is more important: the fact that it's a customer or the fact that it's an entity? I say leave it off. If you use it like an entity, it will be obvious that it's an entity, regardless of how you name it. But by leaving off "Entity", you focus on the fact that it's a customer.

A: There are two conflicting bits of advice here, in my opinion.  One is to use the simplest name possible, the other is to use a naming convention to make the purpose of your objects clearer when they are being used.
Personally, if there is not likely to be any confusion as to what a Customer is, I would leave off the Entity part.  If you find yourself in a situation where you could have multiple objects named Entity, then I would leave the one that is likely to be used most named Customer, and create some compound noun for the other (like CustomerOrder, CustomerRequest, etc)

A: The business-related classes in our shop all inherit from a class called (intentionally generically) DomainObject. None of the inherited classes contain "Object" as part of their name--that would be superfluous--we just name them appropriate to their function.


text:
Q: How do I know the limit for the calculation of normalized wave function. Let we have a eigen function  for dumbbell ball given which is $ \phi= A e^{i x}$ and I have to determine  the normalization constant A. I know in thios case I will have to write
$$\int \phi \phi^* dx  $$.  Now how do i know the limit of the integration?


text:
Q: NSURLConnection ignoring SSL Certificate? I know this question is asked often, but I have implemented the solution found in the answers and I'm not having any luck.  I am not a Swift developer, so I'm guessing I'm missing something.
Here is my NSURLConnectionDelegate methods:
func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool {
    return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
}

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
    print("Second attempt resulted in authentication challenge")

    challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
    challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    print("We got a response.....")
}

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    print("============ second attempt failed ==============")
    print("\(error)")
}

The connection goes through a VPN that doesn't allow for DNS.  We have to use the IP, which results in an invalid cert error.  The Cert is correct, just not using the IP.  I am trying to ignore the cert error but I am still getting "An SSL error has occurred and a secure connection to the server cannot be made"
My understanding is that
challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)

Should resolve this, but it doesn't seem to be working. The print line does run, so the delegate method is being called.
Thanks!

A: As Breek suggested, NSAppTransportSecurity in info.plist did the trick for iOS 9.


text:
Q: How to Debug NodeJS start-server-and-test Jest Tests in Visual Studio Code with Breakpoints Activating Has anyone using start-server-and-test managed to debug their tests with breakpoints activated from within Visual Studio Code? I am using start-server-and-test to start a docker-compose stack. Once the docker-compose stack is successfully started the Jest tests start to run.
I can run this successfully within a terminal session. However, I would like to trigger it from launch.json within VSCode if possible, with the ability to stop at breakpoints. I have tried with the following launch.json configuration item:
 {
            "name": "Debug e2e tests",
            "type": "node",
            "request": "launch",
            "cwd": "${workspaceRoot}",
            "program": "${workspaceRoot}/node_modules/.bin/start-server-and-test",
            "args": [
                "docker-compose -f ./tests/docker/docker-compose.yml up",
                "http://localhost:8080/ping",
                "${workspaceRoot}/node_modules/.bin/jest -i --config=./tests/e2e/jest.config.js"
            ],
            "runtimeArgs": [
                "--inspect-brk"
            ],
            "protocol": "inspector",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen"
}

This starts the docker-compose stack and then the tests start running within an integrated terminal session in VSCode. However, no breakpoints are being hit within VSCode.
The following command is generated when VSCode runs the debugger:
/usr/local/bin/node --inspect-brk=44745 node_modules/.bin/start-server-and-test "docker-compose -f ./tests/docker/docker-compose.yml up" http://localhost:8080/ping "/Users/simon/Development/Projects/ObjectDetection_Mqtt_Plugin/node_modules/.bin/jest -i --config=./tests/e2e/jest.config.js"

If I try to run the e2e test script from within a terminal session the tests start running, as expected, after the docker-compose stack has successfully started:
# package.json extract to include script for running e2e tests
"scripts": {
     "test:e2e": "start-server-and-test 'docker-compose -f ./tests/docker/docker-compose.yml up' http://localhost:8080/ping 'jest --config=./tests/e2e/jest.config.js'",
}

# run the e2e tests
yarn run test:e2e

Also tried this:
 {
            "name": "Debug node script",
            "type": "node",
            "request": "launch",
            "runtimeExecutable": "yarn",
            "runtimeArgs": [
                "run",
                "vscode"
            ],
            "restart": true,
            "port": 9229,
            "protocol": "inspector",
            "cwd": "${workspaceFolder}",
            "console": "integratedTerminal",
            "disableOptimisticBPs": true,
            "internalConsoleOptions": "neverOpen"
}

With this script:
"vscode": "start-server-and-test 'docker-compose -f ./tests/docker/docker-compose.yml up' http://localhost:8080/ping 'node --inspect-brk ./node_modules/.bin/jest --config=./tests/e2e/jest.config.js'"

Same result...

A: Got it working in the end with this setup:
 {
            "name": "Debug e2e tests",
            "type": "node",
            "request": "launch",
            "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/start-server-and-test",
            "runtimeArgs": [
                "docker-compose -f ./tests/docker/docker-compose.yml up",
                "http://localhost:8080/ping",
                "node --inspect-brk=9239 --title=Jest-e2e-tests ${workspaceRoot}/node_modules/.bin/jest -i --config=./tests/e2e/jest.config.js"
            ],
            "port": 9239,
            "protocol": "inspector",
            "cwd": "${workspaceFolder}",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "disableOptimisticBPs": true
}

My approach was to set the runtimeExecutable as start-server-and-test and initialise the runtimeArgs array with the arguments for start-server-and-test. The test argument for start-server-and-test spawns a node process with the --inspect-brk=9239 argument to allow the VSCode debugger to attach. Additionally this required explictly setting the port VSCode debugger option.
If child processes are spawned by end to end tests then will need to add the autoAttachChildProcesses option and ensure that the code that forks the child process detects if running in inspect mode. If it is then it will add inspect argument set with a different port to the parent so no conflict occurs.


text:
Q: what is the definition of the probability measure of an inequality Let $(\Omega,\mathcal{F},\mathbb{P})$ be a probability space. If $X$ is a random variable, what is meant by $\mathbb{P}(X\le{t})$ or $\mathbb{P}(X\ge{t})$ for some t?
The context I am confused about is in a problem using chernoff bounds. why can we do:
$$\mathbb{P}(|S_N-\mu|\ge{\delta{}\mu})=\mathbb{P}(S_N-\mu\ge{\delta{}\mu})+\mathbb{P}(S_N-\mu\le{-\delta{}\mu})$$
and what is really meant by the probability measure of these inequalities?
edit: I'm essentially looking for an explicit definition of $\mathbb{P}(X\le{t})$.

A: $\mathbb{P}(X\le{t})$ is a shorthand for $\mathbb{P}(\{\omega \in\Omega\mid X (\omega) \le{t}\})$. Thus,
$$\mathbb{P}(|S_N-\mu|\ge{\delta{}\mu})=\mathbb{P}([S_N-\mu\ge{\delta{}\mu}]\cup [S_N-\mu\le{-\delta{}\mu}])=\mathbb{P}(S_N-\mu\ge{\delta{}\mu})+ \mathbb{P}(S_N-\mu\le{-\delta{}\mu}).$$


text:
Q: jQuery animate method won't start from current value I'm having a problem with an .animate() jQuery method.
Problem is, I have a div which current width is 0, when I try to animate it from 0 to X%, it doesn't go that way but goes from 100% to X%.
I also tried forcing the width before the animation and stopping all previous animations but nope, won't work.
This is my final command with all these attempts:
$("#div_3B").css({"width":"0"}).stop(true,true).animate({"width":"79.6%"}, 700);

Any idea of what could cause the problem?
I'll note that this single command is actually the last of a series of sequential commands:
$("#div_3B").animate({"width":"0"}, 700, function() {
$("#div_3A").animate({"width":"20%"}, 700, function() {
$("#div_3B").css({"width":"0"}).stop(true,true).animate({"width":"79.6%"}, 700)
;});});

Thanks in advance!

A: Okay, the reason it's going backwards is because you're animating to 0 to start. Just put the width: 0 in the css, and then you only need the two:
$("#div_3A").animate({"width":"20%"}, 700, function()
{
   $("#div_3B").css({"width":"0"}).stop(true,true).animate({"width":"79.6%"}, 700);
});

See here:
http://jsfiddle.net/thespacebean/JmzjK/
If you DO want 3B to first go from 100% to 0, and then to 79.6 after 3A is done animating, then the code you have works:
http://jsfiddle.net/thespacebean/JmzjK/2/


text:
Q: Texturing a sphere in OpenGL with glTexGen I want to get an earth texture on sphere. My sphere is an icosphere built with many triangles (100+) and I found it confusing to set the UV coordinates for whole sphere. I tried to use glTexGen and effects are quite close but I got my texture repeated 8 times (see image) . I cannot find a way to make it just wrap the whole object once. Here is my code where the sphere and textures are created.
    glEnable(GL_TEXTURE_2D);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glBegin(GL_TRIANGLES);

for (int i = 0; i < new_sphere->NumOfTrians; i++)
{
    Triangle *draw_Trian = new_sphere->Trians+i;
    glVertex3f(draw_Trian->pnts[0].coords[0], draw_Trian->pnts[0].coords[1], draw_Trian->pnts[0].coords[2]);
    glVertex3f(draw_Trian->pnts[1].coords[0], draw_Trian->pnts[1].coords[1], draw_Trian->pnts[1].coords[2]);
    glVertex3f(draw_Trian->pnts[2].coords[0], draw_Trian->pnts[2].coords[1], draw_Trian->pnts[2].coords[2]);

}
glDisable(GL_TEXTURE_2D);
free(new_sphere->Trians);
free(new_sphere);

glEnd();

A: You need to define how your texture is supposed to map to your triangles.  This depends on the texture you're using.  There are a multitude of ways to map the surface of a sphere with a texture (since no one mapping is free of singularities).  It looks like you have a cylindrical projection texture there.  So we will emit cylindrical UV coordinates.
I've tried to give you some code here, but it's assuming that

*

*Your mesh is a unit sphere (i.e., centered at 0 and has radius 1)

*pnts.coords is an array of floats

*You want to use the second coordinate (coord[1]) as the 'up' direction (or the height in a cylindrical mapping)

Your code would look something like this.  I've defined a new function for emitting cylindrical UVs, so you can put that wherever you like.
/* Map [(-1, -1, -1), (1, 1, 1)] into [(0, 0), (1, 1)] cylindrically */
inline void uvCylinder(float* coord) {
  float angle = 0.5f * atan2(coord[2], coord[0]) / 3.14159f + 0.5f;
  float height = 0.5f * coord[1] + 0.5f;
  glTexCoord2f(angle, height);
}

glEnable(GL_TEXTURE_2D);
glBegin(GL_TRIANGLES);

for (int i = 0; i < new_sphere->NumOfTrians; i++) {
  Triangle *t = new_sphere->Trians+i;

  uvCylinder(t->pnts[0].coords);
  glVertex3f(t->pnts[0].coords[0], t->pnts[0].coords[1], t->pnts[0].coords[2]);
  uvCylinder(t->pnts[1].coords);
  glVertex3f(t->pnts[1].coords[0], t->pnts[1].coords[1], t->pnts[1].coords[2]);
  uvCylinder(t->pnts[2].coords);
  glVertex3f(t->pnts[2].coords[0], t->pnts[2].coords[1], t->pnts[2].coords[2]);

}

glEnd();
glDisable(GL_TEXTURE_2D);

free(new_sphere->Trians);
free(new_sphere);

Note on Projections
The reason it's confusing to build UV coordinates for the whole sphere is that there isn't one 'correct' way to do it.  Mathematically-speaking, there's no such thing as a perfect 2D mapping of a sphere; hence why we have so many different types of projections.  When you have a 2D image that's a texture for a spherical object, you need to know what type of projection that image was built for, so that you can emit the correct UV coordinates for that texture.


text:
Q: ElasticSearch Numeric Distance I'm looking for a way to make a query that would return a score.
This score would be the numerical distance between 2 numbers.
Is there a way to do this in elasticsearch ?
for example if my data looks like this:

{
  value: INT
}

in my query I want a default parameters (an other INT)
and as result I want my data sorted with the score ( |object.value - default.value| )

A: Using a function_score query (with script_score), you can achieve what you need:
GET /_search
{
    "query": {
        "function_score": {
            "query": {
                "match_all": { }
            },
            "script_score" : {
                "script" : {
                  "source": "Math.abs(doc['value'].value - params.default)",
                  "params": {
                    "default": 10
                  }
                }
            }
        }
    }
}

A: If i understood correctly,you want something like this? It searches in the field range and returns all hits with score value between 0 and 6.

query = {
            'query': {
                'range': {
                    'score': {
                    'lte': 6,
                    'gte': 0
                    }
                }
            }   }


text:
Q: Одно нажатие на пункт - раскрытие меню, второе нажатие переход по ссылке Есть мобильное меню. Как сделать,чтобы по клику на родительский пункт раскрывались подпункты ,а по второму клику на этот же пункт переходило бы по ссылке родительского пункта?

.sub_menu {margin:15px;}

        Наружная реклама

                Вывески

        Интерьерная реклама

                Таблички

        Защитная пленка на окна

                Защитная пленка А1

        Услуги

                Формовка пластиков

A:

$(".menu > .menu_item").click(function(e) {
  var subMenu = $(this).find(".sub_menu");
  if (!subMenu.hasClass("active")) {
    subMenu.addClass("active");
    e.preventDefault();
  }
});
.sub_menu {
  margin:15px;
  display:none;
}

.active {
  display:block;
}

        Наружная реклама

                Вывески

        Интерьерная реклама

                Таблички

        Защитная пленка на окна

                Защитная пленка А1

        Услуги

                Формовка пластиков

A: Присвоить sub_menu класс display:none и по клику на sub_link проверять - если соответствующий sub_menu закрыт открывать его и не выполнять переход, если открыт то просто ничего не делать (осуществится переход по ссылке)

A: $('.page-header__menu-item').hover(function () {

}, function () {
    $(this).find('a').removeClass('active');
});

$('.page-header__menu-item a').click(function (e) {
    if ($(this).parent().hasClass('have_submenu')) {
        let width = $(window).width();
        if (width <= 1210) {
            $('.page-header__menu-item a').not($(this)).removeClass('active');
            if (!$(this).hasClass('active')) {
                $(this).addClass('active');
                e.preventDefault();
            }
        }
    }
});