Q: My code ends at certain line I am practicing my net Java skills and I have created a server Java class that connects to the specified by the user port number:
import java.net.*;
import java.util.*;
import java.io.*;

public class WebServerMain {
    public WebServerMain(int port){
        try{
            String content = " ";
            String userChoice = " ";
            ServerSocket ss = new ServerSocket(port);
            System.out.println("Server: Initialised a socket at port " +
port);
           Socket conn = ss.accept();
            System.out.println("Server: Awating for a client");
            InputStreamReader ir = new
InputStreamReader(conn.getInputStream());
            PrintWriter out = new PrintWriter(conn.getOutputStream(),true);
            BufferedReader userIn = new BufferedReader(ir);
            userChoice = userIn.readLine();
            System.out.println("Server: The choice we got is: " +
userChoice);

            System.out.println("Server: User have chosen GET Method");
            BufferedReader in = new BufferedReader(new
FileReader("test.html"));
            String str;
            System.out.println("All good here");
            while ((str = in.readLine()) != null) {
                content += str;
            }
            in.close();
            System.out.println("Server: The content is "  + content);

            out.println(content);

        } catch(IOException e){
            e.getMessage();
        }
    }

   public static void main(String[] args){
        String path;
        int port;
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter the port number");
        port = in.nextInt();
        WebServerMain server = new WebServerMain(port);
    }
}

The output looks like this:

It seems that code exits befire the new BufferReader in reads the html file and outputs to the client.
I have chosen Safari browser and connected to the local host via the same port.
Also please NOTE, the file name for the BufferedReader in is hardcoded just to test it, I think I will need to use the regular expression to remove GET in order to read the file properly.

A: public WebServerMain(int port) {
    try {
        String content = " ";
        String userChoice = " ";
        ServerSocket ss = new ServerSocket(port);
        System.out.println("Server: Initialised a socket at port " + port);
        Socket conn = ss.accept();
        System.out.println("Server: Awating for a client");
        InputStreamReader ir = new InputStreamReader(conn.getInputStream());
        PrintWriter out = new PrintWriter(conn.getOutputStream(), true);
        BufferedReader userIn = new BufferedReader(ir);
        userChoice = userIn.readLine();
        System.out.println("Server: The choice we got is: " + userChoice);

        System.out.println("Server: User have chosen GET Method");
        BufferedReader in = new BufferedReader(new FileReader(
                //"C:/Users/jayaprakash.j/Desktop/1.html"));//
                userChoice.split(" ")[1]));
        String str;
        System.out.println("All good here");
        while ((str = in.readLine()) != null) {
            content += str;
        }
        in.close();
        System.out.println("Server: The content is " + content);

        out.println("HTTP/1.1 200 OK");
        out.println("Content-Type: text/html");
        out.println("Content-Length: " + content.length());
        out.println();
        out.println(content);
        out.close();
        conn.close();

    } catch (IOException e) {
        e.getMessage();
    }
}


Q: For-loop with string possible? I need something like this. Is it possible in Java?
    for(String i = "A"; i < "Z"; i++) {

        System.out.println(i);
    }

A: You can do it by:
for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
    System.out.println(alphabet);
}


Q: DAG, Scala/Akka I was wondering the best implementation of a DAG (Directed Acyclic Graph) using Scala/Akka where each node can be potentially on different VMs, different computers.
Think of each node as a Scala actor who would only act on its direct parents (in graph terms), how would you implement this at a high level? There are several concepts in Akka that could be applied:
•   Normal actors with discards if the sender is not a direct parent
•   Event Bus and Classifiers
•   …
I am still struggling to choose a best approach, at least in theory, knowing that for a DAG, you need to be able to handle diamond scenarios (where a node depends on two or more nodes that in turn depend on one unique node).
Any pointers to papers, articles, ideas would be welcomed.
Regards

A: This article describes one way of Distributed graph processing with Akka:
http://letitcrash.com/post/30257014291/distributed-in-memory-graph-processing-with-akka

A: Simply use Akka Remote with some DIYing


Q: Query to json firebase object or redux state I'm building my first web app with React, Redux and Firebase, it's about registering the assistance of students (alumnos) to lessons (clases). I've the following database structure (the same in Redux state, this.props).
  "clases" : {
    "-LpQkLyGXEd-Up8hExTx" : {
      "alumnos" : [ "-LpKkSh0E5jiuM0JCCpS", "-LpQi33M-0OSS4Jvup8k" ],
      "fechaClase" : "20-09-2019",
      "profesor" : "Nacho",
      "tema" : "Misión"
    },
    "-LpQmExVsWtW1uPHLK52" : {
      "alumnos" : [ "-LpJvbXb2FjgZvvBv3ei", "-LpKkSh0E5jiuM0JCCpS", "-LpQi33M-0OSS4Jvup8k", "-LpQiDGlRWITax2t6U2A" ],
      "fechaClase" : "22-09-2019",
      "profesor" : "Nacho",
      "tema" : "Bautismo"
    },
    "-LpQqZ_uWu8HxROagVjN" : {
      "alumnos" : [ "-LpKkSh0E5jiuM0JCCpS", "-LpQi33M-0OSS4Jvup8k", "-LpQiPCS2cIK7opMNqyH" ],
      "fechaClase" : "21-09-2019",
      "profesor" : "Manzo, Ignacio",
      "tema" : "Bautismo"
    }

I want to select a student (alumno), and know which lessons have made. Do I have to make a double map to the object? Can you give some help?
This is the deployed app https://metanoia-ic.herokuapp.com/
This is my github repository: https://github.com/tonicanada/metanoia
Thanks!

A: I would use Object.keys to be able to use filter and include Array.prototype methods. Asuming that clases is the object containing all the state, I would do something like this:
const studentId = this.props.studentId; // or any other value

const clasesPerStudent = Object.keys(clases).filter(clase =>
  clases[clase].alumnos.includes(studentId)
);


Q: How to create a Lock in 2 timer tasks Java reliably (So will wait when other is running) I am running 2 timer tasks. it's something like
@Autowired
private Insertion insertion;

@Autowired
private Updation updation;

*

*insert some data in DB
timer.schedule(insertion,1000,5000)

public run() {
    if(!Updationhappening) {
        //start insertion
    }
    else {
       //wait
    }
}

*update that data with something
timer.schedule(updation,1000,5000)

if(!InsertionHappening) {
    //start updation
} else {
    //wait
}

However i want to pause the update when insertion is running .
I know maybe i can do this with a volatile variable or Locks but i am not able to get any implementation about this locking system. Can anyone suggest an example implementation between 2 different nodes
Thank you in advance

A: You can order updates and inserts with PriorityBlockingQueue to process inserts with priority.

A: Thank you for your inputs Everyone
I found a solution to the issue
i used REENTRANT Locks to solve the issue . made a static Lock object in A global file and made lock.tryLock() in both the file to solve the issue


Q: GCC: "__unused__" vs just "unused" in variable attributes According to GCC's own documentation on variable attributes, the correct syntax for declaring an attribute unused is __attribute__((unused)).
However, in many examples and other code online, I frequently see __attribute__((__unused__)) instead, and they appear to both work.
Is there a reason for either specifying or omitting the __ in either case?  Does it make any difference, and is there a preferred version?  Are there any situations where using one and not the other might cause problems?
Presumably the same applies to other attribute parameters as well?

A: At the top of the very page you linked, it tells you:

You may also specify attributes with ‘__’ preceding and following
  each keyword. This allows you to use them in header files without
  being concerned about a possible macro of the same name. For example,
  you may use __aligned__ instead of aligned.

Identifiers containing double underscores (__) are reserved to the implementation. Hence no user program could legally define them as macros.


Q: JUnit 5 tests are executed in parallel inside IntelliJ and locally with Maven, but not inside Maven Docker container on Google Cloud Build I am using JUnit 5 in my Maven project.
My junit-platform.properties looks like this:
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=concurrent

When running the tests inside IntelliJ or with Maven locally, the test are executed in parallel.
However, when running them on Cloud Build inside a Maven Docker container, they seem to run sequentially.
This is how they are called:
steps:
  - name: 'maven:3-jdk-11-slim'
    args: [
      'mvn',
      # https://stackoverflow.com/a/53513809/3067148
      '-Dorg.slf4j.simpleLogger.showDateTime=true',
      '-Dorg.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss,SSS',
      '-B',
      'test'
    ]

What could be the reason why they aren't executed in parallel?

A:
Properties such as the desired parallelism and the maximum pool size can be configured using a ParallelExecutionConfigurationStrategy. The JUnit Platform provides two implementations out of the box: dynamic and fixed. Alternatively, you may implement a custom strategy.

Keep in mind that the ParallelExecutionConfigurationStrategy class is still in the "EXPERIMENTAL" state and it is not yet stable. Unintended behaviour may occur.
As you don't set a specific configuration strategy, the following section applies:

If no configuration strategy is set, JUnit Jupiter uses the dynamic configuration strategy with a factor of 1. Consequently, the desired parallelism will be equal to the number of available processors/cores.

Find more details at https://junit.org/junit5/docs/current/user-guide/#writing-tests-parallel-execution-config


Q: Scalar subquery cannot have more than one column unless using SELECT AS STRUCT to build STRUCT values I'm trying to write a query in BigQuery that select some rows based on row number and sum the columns.
In details, I have two tables: in table1 there are for each id the number of rows of table2 that I want to sum. An example of the two tables is below.
table1

table2

The desired output is:

id
points1
points2
points3

a
86
99
31

b
91
59
15

c
122
183
118

I created a UDF that tooks the 'neighbors' n1, n2 and n3 and sum the rows of table2 whose row_num is in n1, n2 and n3; then I recalled the UDF in my query below.
create temp function sum_points(neighbors array<int>)
returns array<int>
as (sum((select * from `project.dataset.table2` where row_num in unnest(neighbors))));

with cte as (
  select id, array_agg(nn) as neighbors
  from `project.dataset.table1`, unnest([n1, n2, n3]) nn
  group by id
)
select id, sum_points(neighbors) from cte

However, I got the following error:
Scalar subquery cannot have more than one column unless using SELECT AS STRUCT to build STRUCT values; failed to parse CREATE [TEMP] FUNCTION statement at [5:9]
and it is not very clear to me what that means. I tried to replace the select inside with statement with select struct<array<int>> but it did not work.

A: Better option would be to join tables and do aggregate.
You can join tables based on row_num from table2 and n1, n2, n3 from table1 as below.
SELECT
  id,
  SUM(points1) AS points1,
  SUM(points2) AS points2,
  SUM(points3) AS points3
FROM table1 JOIN table2
ON row_num in (n1, n2, n3)
GROUP BY id

Output of the query:

id
points1
points2
points3

a
86
99
31

c
122
183
118

b
91
59
15


Q: Automapper Map Property as Collection I need to map ICustomerAddresses to my own custom object Address, or List < Address >. How can I use automapper to indicate that the property Customer.ICustomerAddresses maps to my custom Address?
To, illustrate, I have a an interface that has its properties listed like this:
public interface ICustomer
{
    ICustomerAddresses Addresses;
}

In this case, ICustomerAddresses is a collection of ICustomerAddress. However, ICustomerAddress is not a simple IEnumerable, it contains properties that contain the collection, like this:
public interface ICustomerAddresses : IBusinessObjectCollection
  {
    ICustomerAddress this[int nIndex] { get; }

    ICustomerAddress CreateNew();

    ICustomerAddress AddNew();

  }

Automapper cannot figure out on its own that ICustomerAddresses is really just a collection of ICustomerAddress, so how do I tell it that's the case?
Thanks in advance!

A: A custom type converter should work fine.  Here's a quick example (thrown together -- not tested).  Also, I added a "Length" property to the ICustomerAddresses so I knew how many to loop through:
public class AddressConverter : TypeConverter<ICustomerAddresses, IList<Address>>
{
    protected override IList<Address> ConvertCore(ICustomerAddresses source)
    {
        var addresses = new List<Address>();
        for (var i = 0; i < source.Length; i++)
        {
            var addr = source[i];
            addresses.Add(new Address
                            {
                                Addr1 = addr.Addr1,
                                Zip = addr.Zip
                            });
        }

        return addresses;
    }
}

And you could probably utilize Automapper inside the loop too to convert the ICustomerAddress to an Address instead of doing it manually like I did.


Q: how to exclude image files within public folder In the public folder, I have two folder hk and sg, they have different image files.
What I want is if I build hk package, I only copy images from hk folder.
How to exclude the sg folder in ember-cli?

A: Ember uses Broccoli.js for it's build pipeline. Broccoli is build around the concept of trees. Please have a look in it's documentation for details.
You could exclude files from the tree using a plugin called broccoli-funnel. It expects an input node, which could be either a directory name as a string or an existing broccoli tree as a first argument. A configuration object should be provided as a second argument. The files or folders that should be excluded could be specified by exclude option on that object.
A broccoli tree is created as part of the build process in ember-cli-build.js. The function exported from that file should return a tree. By default it returns the tree created by app.toTree() directly. But you could customize that tree using broccoli-funnel before.
This diff shows how default ember-cli-build.js as provided by blueprint of Ember CLI 3.16.0 could be customized to exclude a specific file:
diff --git a/ember-cli-build.js b/ember-cli-build.js
index d690a25..9d072b4 100644
--- a/ember-cli-build.js
+++ b/ember-cli-build.js
@@ -1,6 +1,7 @@
 'use strict';

 const EmberApp = require('ember-cli/lib/broccoli/ember-app');
+const Funnel = require('broccoli-funnel');

 module.exports = function(defaults) {
   let app = new EmberApp(defaults, {
@@ -20,5 +21,7 @@ module.exports = function(defaults) {
   // please specify an object with the list of modules as keys
   // along with the exports of each module as its value.

-  return app.toTree();
+  return new Funnel(app.toTree(), {
+    exclude: ['file-to-exclude'],
+  });
 };

You should explicitly add broccoli-funnel to your dependencies even so it's available as a indirect dependency:
// if using npm
npm install -D broccoli-funnel

// if using yarn
yarn add -D broccoli-funnel

Broccoli-funnel does not only support exact file names but also regular expressions, glob strings or functions to define the files to exclude. Please have a look in it's documentation for details.


Q: Why multiple JADE GUI appear on refreshing JSP page I want to run JADE middleware GUI from JSP, for that I created a "Dynamic Web Project" and made right click on WebContent folder and select New .. Other ..type JsP file and gave the name e.g. runJADE.jsp. Now add the following details inside runJADE.jsp
<%@ page import="jade.core.*"%>
<% try {
    String [] _args = {"-gui"};
    jade.Boot.main(_args);
   } catch (Exception ex) {
       out.println(ex);
       ex.printStackTrace();
   }
 %>

<HTML>
<BODY>
JADE is running.
</BODY>
</HTML>

I also tried the following code in JSP page:
<%@ page import="jade.core.Profile,jade.core.ProfileImpl,jade.core.Runtime,jade.wrapper.AgentContainer %>
<% try {
        Profile profile = new ProfileImpl();
        profile.setParameter(Profile.GUI, "true");
        AgentContainer mainContainer = Runtime.instance().createMainContainer(profile);
   } catch (Exception ex) {
       out.println(ex);
       ex.printStackTrace();
   }
 %>

<HTML>
<BODY>
JADE is running.
</BODY>
</HTML>

The code gives fine result by launching the JADE but refreshing the page leads to create another GUI. Am I missing some basic step? and how to avoid this problem?

A: Your approach is deeply flawed. Every time you load your JSP, it creates another Jade container. When using Jade, you generally only want to have a single container on a single machine.
A better approach would be to start up your container when your entire application starts up. Then, when you want to trigger the Jade GUI, you should just start the RMA agent inside your Jade container, as described in this answer: https://stackoverflow.com/a/20462656/2047962

Now, let's take a step back and talk about your code. I would strongly recommend that you stop using scriptlets in your JSPs RIGHT NOW. It's a bad practice that leads to really poor designs. If you don't know the alternatives, please read "How to avoid Java code in JSP files?".
Second, why are you mixing web applications and desktop Swing UIs? Why are you opening a Swing GUI when someone accesses your web page in a browser? If you were to deploy that application, your clients would get to a page that says "JADE is running", but they wouldn't see anything. The GUI would open on the server, not the client. I can't see why you would want this functionality in a web environment.


Q: Do indexes persist on derived tables? Say I have a large table containing genomic positions from various files as follows:
CREATE TABLE chromosomal_positions (
    file_id  INT,
    chromosome_id INT,
    position INT
)

I want to compare the contents of 1 file to the contents of everything all the other files, for overlaps. So I use to derived tables.
SELECT Count(*)
FROM   (SELECT *
        FROM   chromosomal_positions
        WHERE  variant_file_id = 1) AS file_1
      JOIN (SELECT *
            FROM   chromosomal_positions
            WHERE  variant_file_id != 1) AS other_files
         ON ( file_1.chromosome_id = other_files.chromosome_id
              AND file_1.position = other_files.position )

Now if I add a compound index on file_id, chromosome_id , position in that order, will the derived tables be able to use that index?
(Using Postgres)

A: It's not so much that PostgreSQL "preserves" indexes across subqueries, as that the rewriter can often simplify and restructure your query so that it operates on the base table directly.
In this case the query is unnecessarily complicated; the subqueries can be entirely eliminated, making this a trivial self-join.
SELECT count(*)
FROM  chromosomal_positions file_1
INNER JOIN chromosomal_positions other_files
ON ( file_1.chromosome_id = other_files.chromosome_id
     AND file_1.position = other_files.position )
WHERE file1.variant_file_id = 1
AND   other_files.variant_file_id != 1;

so an index on (chromosome_id, position) would be clearly useful here.
You can experiment with index choices and usage as you go, using explain analyze to determine what the query planner is actually doing. For example, if I wanted to see if:
then I would
CREATE INDEX cp_f_c_p ON chromosomal_positions(file_id, chromosome_id , position);

-- Planner would prefer seqscan because there's not really any data;
-- force it to prefer other plans.
SET enable_seqscan = off;

EXPLAIN SELECT count(*)
FROM (
  SELECT *
  FROM   chromosomal_positions
  WHERE  file_id = 1
) AS file_1
INNER JOIN (
  SELECT *
  FROM   chromosomal_positions
  WHERE  file_id != 1
) AS other_files
ON ( file_1.chromosome_id = other_files.chromosome_id
     AND file_1.position = other_files.position )

and get the result:
                                                                                QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=78.01..78.02 rows=1 width=0)
   ->  Hash Join  (cost=29.27..78.01 rows=1 width=0)
         Hash Cond: ((chromosomal_positions_1.chromosome_id = chromosomal_positions.chromosome_id) AND (chromosomal_positions_1."position" = chromosomal_positions."position"))
         ->  Bitmap Heap Scan on chromosomal_positions chromosomal_positions_1  (cost=14.34..48.59 rows=1930 width=8)
               Filter: (file_id <> 1)
               ->  Bitmap Index Scan on cp_f_c_p  (cost=0.00..13.85 rows=1940 width=0)
         ->  Hash  (cost=14.79..14.79 rows=10 width=8)
               ->  Bitmap Heap Scan on chromosomal_positions  (cost=4.23..14.79 rows=10 width=8)
                     Recheck Cond: (file_id = 1)
                     ->  Bitmap Index Scan on cp_f_c_p  (cost=0.00..4.23 rows=10 width=0)
                           Index Cond: (file_id = 1)
(11 rows)

(view on explain.depesz.com)
showing that while it will use the index, it's actually only using it for the first column. It won't use the rest, it's just filtering on file_id. So the following index is just as good, and smaller and cheaper to maintain:
CREATE INDEX cp_file_id ON chromosomal_positions(file_id);

Sure enough, if you create this index Pg will prefer it. So no, the index you propose does not appear to be useful, unless the planner thinks it's just not worth using at this data scale, and might choose to use it in a completely different plan with more data. You really have to test on the real data to be sure.
By contrast, my proposed index:
CREATE INDEX cp_ci_p ON chromosomal_positions (chromosome_id, position);

is used to find chromosomal positions with id = 1, at least on an empty dummy data set. I suspect the planner would avoid a nested loop on a bigger data set than this, though. So again, you really just have to try it and see.
(BTW, if the planner is forced to materialize a subquery then it does not "preserve indexes on derived tables", i.e. materialized subqueries. This is particularly relevant for WITH (CTE) query terms, which are always materialized).


Q: Im trying to understand subversion / git I am trying to understand and learn how to use subversion or git. Which do you recommend?
It seem so complicated and confusing.
I do a lot of PHP web development projects. I have a habit backing up project folders like project_name_version_date
What is the best way to learn for beginner?
How do you upload updated project from local machine to live website to a different server, how that be done from subversion / git? and reupload to new version again?
Can 2 or 3 people work on the same project at the same time? do they load the code files from the server? wouldn't it conflict each other... like they had removed the class objects, functions, etc.

A:
What is the best way to learn for
  beginner?

*

*http://svnbook.red-bean.com/nightly/en/svn.intro.quickstart.html

*http://book.git-scm.com/

How do you upload updated project from
  local machine to live website to a
  different server, how that be done
  from subversion / git? and reupload to
  new version again?

With version control, you have a central repository and one or more working copies (git adds in a local repository at every working copy to allow distributed storage/management).
In your case, your live website and your development copy are both working copies - you checkout from the central repository to each of these locations. You then work on the development copy, and commit those changes to the central repository. Once you are ready to release, you simply perform an update on the live working copy which pulls all the changes from the central repository.

Can 2 or 3 people work on the same
  project at the same time? do they load
  the code files from the server?
  wouldn't it conflict each other...
  like they had removed the class
  objects, functions, etc.

Yes - each person has a working copy which they make changes to.
Conflicts are likely, and will happen from time to time - but SVN and Git can deal with a lot very easily. For example, changes to code in different places of the same file are simply merged in. Changes to code at the same place in the same file will typically require manual intervention.
Perhaps the worst conflicts that can occur are what SVN calls 'tree conflicts' - changes in the folder structure. This can be a real PITA to fix - but you have to really go out of your way to cause them.
That said, the potential for conflicts (and difficulty in resolving them) in non-version controlled environments is far, far greater.
There are some practices which help prevent major conflicts from occurring:

*

*Modular code

*Clear delineation of work - stop programmers treading on each others toes

*Update your local copy before committing

*Commit small, commit often - how small?  Hard to say, you start to get a feel for this... but think in terms of functions and functionality.

I think Git is probably better to start with if you don't use anything else already - the distributed system means that you are more able to resolve conflicts at the local level before pushing up to the central repository. All of my projects are use SVN (at the office and at home), but I'm starting to use Git through the Drupal project, and like what I've seen so far.

A: GIT is the newer paradigm for version control. SVN has been around for a while but GIT and Mercurial are gaining traction as they allow for "distributed version control." This means that there is no central server for your code. Everyone has the entire history and can send "patches" to each other to share code. However, git and mercurial do support a workflow very similar to having a central repository. Integrating git and "gerrit" is really great for working on a project with multiple people.
I suggest skipping svn because svn is an older technology that will actually hinder your understanding of git / mercurial because it is a different paradigm and uses different processes. GIT / mercurial works awesome just locally (no server and you are the only one using) and also for large teams.
GIT is more powerful but harder to use while mercurial has the basics in a more usable form factor.

A: I will suggest , go for git , you can access your repository on web also. With subversion, as far my knowledge goes, there is no such provision. But this should not be only reason. I have used both, git is very useful. Git's main advantage is that you don't have to be connected to master repository always. You can read more in this question which has been explained in nice way Why is Git better than Subversion?

A: As you are new to the whole Version/Source Control concept. I suggest you read a bit about VC in general.
The best way to learn would be to actually use a VCS for your day to day projects. Yes many people can work on the same things at once. And then 'conflicts' can happen. But the modern VCS lets you do something called merging.
I suggest you start with learning about git. As you are new to the whole thing it shouldn't be very hard for you. But IMHO learning SVN(which is a 'centralized version control system) and then moving in to git (which is a distributed version control system) tends to complicate things. A lot of people feel distributed VCS are the future. So i suggest you start learning either git or Hg, both are good VCSs.
Good Luck!

A: You should read a tutorial on Subversion and stay very far away from Git until you are reasonably experienced in SVN.
The best way to learn is follow a hands-on tutorial and then try the same things out yourself during your normal development workflow.
And certainly many people can work on the same project, that is one of the main reasons we use version control.

A: I would strongly recommend checking out http://hginit.com/  It uses Mercurial which is very similar to Git, but the important thing to gain from hginit is how distributed version control (and version control in general) work both independently and as part of a team.  Once you understand the concepts in hginit, which distributed source control tool tool you pick is not nearly as important.

A: Subversion and git are very different in the way they deal with code, but the goal is the same.
Subversion is a centralized solution to source control. Git is a distributed solution to source control. In both cases, you can use them by yourself only or an arbitrarily large team can use them.
Subversion is centralized, meaning there is only one server. All the code lives on that machine. It's a little simpler conceptually to deal with this.
Git is distributed, meaning there are a lot of servers (everyone is a server and a client). This makes it a little more complicated to understand which one is the "right" server.
Right now, you are creating a copy of the files you want to keep somewhere else on the disk and using that as a backup. When you do this, you are doing several steps at a time (at a conceptual level):

*

*Deciding which files you want to backup
Most source control needs your help to tell it which files to track. This is known as the add command in both git and subversion.

*Backing up those files so that future changes do not impact them
This is done by commiting the changes to the files your source control is tracking for you. In subversion this is done with commit. In git, add makes git aware of the changes you make to the files and commit makes the changes saved in a permanent manner.

*Labeling the copy of the files in a manner that makes sense to you
This is done in multiple manners in the different source control technologies. Both  have a history of the commits, the concept of branches/tags and different repositories (though code doesn't normally change between repositories in subversion).
In Subversion, the code is on a single server. Everyone gets it from there (originally with checkout, afterward with update). In git, you fetch remote changes from another repository.
Git has somewhat superior conflict resolution (two people changing the same thing at the same time) to subversion, but you can still get into plenty of merge headaches if you are not careful. Git rebase can be helpful, though I've only used it in an individual manner so I have not had much conflict resolution practice yet.
Git has some tools that some people swear by (bisect and grep) that I have found to be somewhat useful. Your mileage may vary :)

A: It's largely a matter of comfort, but since you are a beginner (and presumably willing to spend some time learning a new skill), I will recommend git. As someone who has used svn and git, I think your workflow looks like it would be helped by git.
Here's some questions you need to answer for yourself when thinking svn vs. git:

*

*Are you in a company where policy prevents you from using git? (If yes, use svn).

*Do you have a workflow wherein you like to create a 'topic branch' to develop a feature, and then merge it into main when you believe that feature works well? (If yes, git is better, because it actually encourages you to create branches, and merge them back very easily, whereas svn is total hell as far as creating branches and merging them into main is concerned).

*Do you prefer to commit often in small chunks so that you have a nice clean record of changes that you can selectively unroll? (I would argue that this style of development is supported better by git).

*Look at this command: http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html . I cannot tell you how many times I have had to do a custom release wherein I pull specific features and 'compose' an image / website / app for a quick demo.  If you think you will be doing this often, think how you would do it in subversion. I can predict in advance that it's not going to be a picnic :)
There are tons of other reasons, but if your workflows look like what I have described, then you should go with git.
You can learn git from this great resource: http://progit.org/book
And remember, if you are stuck with svn and would still like to use git, that is easy too!
http://progit.org/book/ch8-1.html


Q: How can I get a URL entered into WinForms OpenFileDialog? If a user enters a URL into a Windows Forms OpenFileDialog then the dialog box (on more modern versions) of Windows will download the file and open it from a temporary directory.  Is there any way to get at the entered URL?  Could the new-fangled IFileDialog help?
Please note that I am not looking for the file:// equivalent of a local file. This is for when the user enters the location of something on the Internet  into the file dialog.  e.g. http://example.com/path.
This asks essentially the same question, but didn't get a useful answer, perhaps because he asks that the result appear in the FileName property.

A: It's possible to set a windows hook to listen for text changes. This code currently picks up value changes from all fields, so you will need to figure out how to only detect the ComboBox filename field.
    public class MyForm3 : Form {

        public MyForm3() {
            Button btn = new Button { Text = "Button" };
            Controls.Add(btn);
            btn.Click += btn_Click;
        }

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
        [DllImport("user32.dll")]
        private static extern bool UnhookWinEvent(IntPtr hWinEventHook);
        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        private const int WINEVENT_OUTOFCONTEXT = 0;
        private const uint EVENT_OBJECT_VALUECHANGE = 0x800E;

        void btn_Click(object sender, EventArgs e) {
            uint pid = 0;
            uint tid = 0;
            using (var p = Process.GetCurrentProcess())
                GetWindowThreadProcessId(p.MainWindowHandle, out pid);

            var hHook = SetWinEventHook(EVENT_OBJECT_VALUECHANGE, EVENT_OBJECT_VALUECHANGE, IntPtr.Zero, CallWinEventProc, pid, tid, WINEVENT_OUTOFCONTEXT);

            OpenFileDialog d = new OpenFileDialog();
            d.ShowDialog();
            d.Dispose();
            UnhookWinEvent(hHook);

            MessageBox.Show("Original filename: " + OpenFilenameText);
        }

        private static String OpenFilenameText = "";
        private static WinEventProc CallWinEventProc = new WinEventProc(EventCallback);
        private delegate void WinEventProc(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime);
        private static void EventCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime) {
            StringBuilder sb1 = new StringBuilder(256);
            GetClassName(hWnd, sb1, sb1.Capacity);
            if (sb1.ToString() == "Edit") {
                StringBuilder sb = new StringBuilder(512);
                GetWindowText(hWnd, sb, sb.Capacity);
                OpenFilenameText = sb.ToString();
            }
        }
    }

A: If you only want to get URL (not download file), set CheckFileExists flag to false.
Example code below
        string urlName = null;
        using (var dlg = new OpenFileDialog())
        {
            dlg.CheckFileExists = false;

            dlg.ShowDialog();
            urlName = dlg.FileName;
            urlName = Path.GetFileName(urlName);

        }


Q: Angular.js Authentication with Node.js I'm unable to login with front-end might be problem with Angular-ui-Router. When I click on login button first I got an error as 'Possibly unhandled rejection' then I injected '$qProvider' in config file after adding $qProvider I don't see any error in console but the page is not changing it state whereas in the network tab i can see the Token is sent from the server. Can some one please help me.
App.config.js
angular.module('myApp', ['ui.router', 'myAppModel'])
        .config(function($qProvider, $stateProvider, $urlRouterProvider) {
            $urlRouterProvider.otherwise('/');
            $qProvider.errorOnUnhandledRejections(false);
            $stateProvider
                .state('base', {
                    abstract: true,
                    views: {
                        'nav@': {
                            template: '<navigation1></navigation1>'
                        }
                    }
                })
                .state('base.login', {
                    parent: 'base',
                    url: '/',
                    views: {
                        'main@': {
                            template: '<login></login>'
                        }
                    }
                })
                .state('base.register', {
                    parent: 'base',
                    url: '/register',
                    views: {
                        'main@': {
                            template: '<register></register>'
                        }
                    }
                })
                .state('base.dashboard', {
                    parent: 'base',
                    url: '/dashboard',
                    views: {
                        'main@': {
                            template: '<dashboard></dashboard>'
                        }
                    }
                })
        });

login.js
angular.module('myAppModel')
        .component('login', {
            templateUrl: '/components/login/login.html',
            controller: function loginCtrl(Authentication, $state) {
                var ctrl = this;

                ctrl.pageHeader = 'Login';

                ctrl.credentials = {
                    email: '',
                    password: ''
                };

                ctrl.onSubmit = function () {
                    ctrl.formError = '';
                    if(!ctrl.credentials.email || !ctrl.credentials.password) {
                        ctrl.formError = 'All fields required, please try again';
                        return false;
                    }else {
                        ctrl.doLogin();
                    }
                };

                ctrl.doLogin = function () {
                    ctrl.formError = '';
                    Authentication.login(ctrl.credentials).then(function(status) {
                        console.log(status);
                        $state.go('base.dashboard');
                    });
                };

            }
        });

Authentication-service.js
angular.module('myAppModel')
        .service('Authentication', function ($window, $http) { //Register new service with application and inject $window service
            var saveToken = function (token) {  //create a saveToken method to save a value to localStorage
                $window.localStorage['app-token'] = token;
            };

            var getToken = function () {    //Create a getToken method to read a value from localStorage
                return $window.localStorage['app-token'];
            }

            var register = function (user) {
                return $http.post('/api/users/register', user).then(function(data){
                    saveToken(data.token);
                });
            };

            var login = function (user) {
                return $http.post('/api/users/login', user).then(function (data) {
                    saveToken(data.token);
                });
            };

            var logout = function () {
                $window.localStorage.removeItem('app-token');
            };

            var isLoggedIn = function () {
                var token = getToken(); //Get token from storage

                if(token) { //If token exists get payload decode it, and parse it to JSON
                    var payload = JSON.parse($window.atob(token.split('.')[1]));
                    return payload.exp > Date.now() / 1000; //validate whether expiry date has passed
                }else {
                    return false;
                }
            };

            //Getting User Information from the JWT
            var currentUser = function () {
                if (isLoggedIn()) {
                    var token = getToken();
                    var payload = JSON.parse($window.atob(token.split('.')[1]));
                    return {
                        email: payload.email,
                        name: payload.name
                    };
                }
            };

            return {
                saveToken: saveToken,   //Expose methods to application
                getToken: getToken,
                register: register,
                login: login,
                logout: logout,
                isLoggedIn: isLoggedIn,
                currentUser: currentUser
            };

        });


Q: How to save information in multiple text boxes with save and load buttons I'm trying to create a simple Android program that has text boxes for name, address, phone number, etc. When the user puts this information in and hits save it clears the text boxes, and when they hit the load button it retrieves the info. I know how to do it with one EditText box, but I can't figure out multiple. Can I do this inside one try/catch statement, or do I need more than one? This is what I have right now:
public class MainActivity extends ActionBarActivity {
    private EditText textBoxName;
    private EditText textBoxAddress;
    private EditText textBoxCity;
    private EditText textBoxPhone;
    private EditText textBoxEmail;
    private static final int READ_BLOCK_SIZE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textBoxName = (EditText) findViewById(R.id.txtName);
        textBoxAddress = (EditText) findViewById(R.id.txtAddress);
        textBoxCity = (EditText) findViewById(R.id.txtCity);
        textBoxPhone = (EditText) findViewById(R.id.txtPhone);
        textBoxEmail = (EditText) findViewById(R.id.txtEmail);
        Button saveBtn = (Button) findViewById(R.id.btnSave);
        Button loadBtn = (Button) findViewById(R.id.btnLoad);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String strName = textBoxName.getText().toString();
                String strAddress = textBoxAddress.getText().toString();
                String strCity = textBoxCity.getText().toString();
                String strPhone = textBoxPhone.getText().toString();
                String strEmail = textBoxEmail.getText().toString();
                try {
                    FileOutputStream fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);

                    OutputStreamWriter osw = new OutputStreamWriter(fOut);

                    //write the string to the file

                    osw.write(strName);

                    osw.flush();

                    osw.close();

                    //display file saved messages
                    Toast.makeText(getBaseContext(), "File saved successfully!",
                            Toast.LENGTH_SHORT).show();

                    //clears the EditText
                    textBoxName.setText("");
                    textBoxAddress.setText("");
                    textBoxCity.setText("");
                    textBoxPhone.setText("");
                    textBoxEmail.setText("");
                }
                catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }

            }
        });

        loadBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try
                {
                    FileInputStream fIn = openFileInput("textfile.txt");
                    InputStreamReader isr = new InputStreamReader(fIn);

                    char[] inputBuffer = new char[READ_BLOCK_SIZE];
                    String s = "";

                    int charRead;
                    while ((charRead = isr.read(inputBuffer))>0)
                    {
                        //convert the chars to a String
                        String readString = String.copyValueOf(inputBuffer, 0, charRead);
                        s += readString;

                        inputBuffer = new char[READ_BLOCK_SIZE];
                    }
                    //set the EditText to the text that has been read
                    textBoxName.setText(s);
                    textBoxAddress.setText(s);
                    textBoxCity.setText(s);
                    textBoxPhone.setText(s);
                    textBoxEmail.setText(s);

                    Toast.makeText(getBaseContext(), "File loaded successfully!",
                            Toast.LENGTH_SHORT).show();
                }
                catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

A: You can use Shared Preferences to store and retrieve information in Android.

A: you can use shared preferences for this purpose . Just put the value into shared preference and load when the user need this info like username and password saved locally into any login form.


Q: How to parse the array from one activity to fragment in android? I am bulding an android application where an user select There
 favorite stuff.
The name of stuff is added in an array by clicking on Image of this
 stuff.
Now I need is that how can I parse the value of that array to any
 fragment and show in my spinner list.
For example like user select Mobile and tablet by click there image
 this value add in an array name stuffarray now I need is that this
 array value pass to my fragment on an submitted button and when I
 click on an spinner of my fragment it Should have mobile and tablet value in there
 list.
Here is my code for stuff selection :
submite = (ImageButton) findViewById(R.id.nextscreen);
    next.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Intent innext = new Intent(getApplicationContext(), MainActivitytabnew.class);

            startActivity(innext);

    });

   img1 = (ImageButton) findViewById(R.id.imageButton1);

    img1.setBackgroundResource(R.drawable.mobile);
    img1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

             isClicked1=!isClicked1;
                if (isClicked1) {
                    img1.setImageResource(R.drawable.mobile);
                    start();
                    stuff1 = "mobile";

                       myList.add(stuff1);

                }else {
                    img1.setImageResource(R.drawable.mobile);
                    myList.remove(sport1);
                    //sport1 = "";
                    txt1.setText("");
                }
        }
    });

    img2 = (ImageButton) findViewById(R.id.imageButton2);
    img2.setBackgroundResource(R.drawable.tablet);
    img2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            isClicked2=!isClicked2;
            if (isClicked2) {
                img2.setImageResource(R.drawable.tablet);
                start();
                stuff2 = "tablet";
               myList.add(stuff2);
            }else {
                img2.setImageResource(R.drawable.tablet);
               // sport2 = "";
                myList.remove(sport2);
            }
        }
    });

A: seems that your are passing List<String> to fragment.
You should use Bundle to hold your data and then pass to fragment use Fragment.setArguments.
here is a example:
    Bundle data = new Bundle();
    data.putStringArrayList("your_argument_name", dataList);
    Fragment f = ...;
    f.setArguments(data);

here is how to read value in your fragment's code, like in onCreateView :
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle data = getArguments();
        if (data != null) {
            List<String> dataList = data.getStringArrayList("yout_argument_name");
        }
        ...
    }


Q: Number of pairs that create a real number when placed in the exponent of complex number i In my intro Python class, we're exploring the use of complex numbers. I'm asked to use for loops to find the number of pairs of variables x and y that, for a given value of N, satisfy the conditions
a) 0 <= x < y <= N  and

b) i^x + i^y is a real number (not complex)

Since the value of i is sqrt(-1), this happens only when x and y are even numbers:
sqrt(-1)^0 = 1 => this is real

sqrt(-1)^1 = sqrt(-1) => this is complex

sqrt(-1)^2 = -1 => this is real

sqrt(-1)^3 = -sqrt(-1) => this is complex

and so on
So, I've written code as follows
a1 = 0
N = int(raw_input('Please select a value for N: '))
for x in range(0, N):
    for y in range(x+1, N+1):
        if x%2==0 and y%2==0:
            a1 = a1+1

This utilizes the mod operator to determine whether the values for x and y are even or odd, and, if both values are even, it advances the count variable a1 by 1. It is given to us that for N = 100, our total count, what I have as a1, should be 1900. However, at the end of my loop, my a1 is 1275. I'm having trouble analyzing the code to determine where the error is.


Q: Django creates Static Folder When uploading my statics with `collectstatic' on Google Cloud Storage, it does upload the files into the main root of the bucket, instead in a folder called "/static/", so the web on production can't read the statics. How can I create the folder  "/static/" and upload the files there on GCS?
This are my settings:
ALLOWED_HOSTS = ["*"]
DEBUG = True

INSTALLED_APPS += ["django_extensions", ]

DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"

GS_BUCKET_NAME = "static-bucket"

GS_MEDIA_BUCKET_NAME = "bucket-name"

A: Requirement for loading staticfiles GCS
Go to GCP: Cloud Storage (GCS) and click on CREATE BUCKET (fill-up as needed)
Once created, you can make it public if you want it to act like a CDN of your website (storage of your static files such as css, images, videos, etc.)
Go to your newly created bucket
Go to Permissions and then Click Add members
Add a new member "allUsers" with role "Cloud Storage - Storage Object Viewer"
Reference: https://cloud.google.com/storage/docs/quickstart-console
Main references:
https://django-storages.readthedocs.io/en/latest/backends/gcloud.html
https://medium.com/@umeshsaruk/upload-to-google-cloud-storage-using-django-storages-72ddec2f0d05
Prerequisite steps
Go to GCP: Cloud Storage (GCS) and click on CREATE BUCKET (fill-up as needed)
Once created, you can make it public if you want it to act like a CDN of your website (storage of your static files such as css, images, videos, etc.)
Go to your newly created bucket
Go to Permissions and then Click Add members
Add a new member "allUsers" with role "Cloud Storage - Storage Object Viewer"
Reference: https://cloud.google.com/storage/docs/quickstart-console
Step one 1 (easier and faster, but requires constant manual copying of files to the GCS)
Configure your Django's static file settings in your settings.py
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'templates'),
    os.path.join(BASE_DIR, "yourapp1", "templates"),
    os.path.join(BASE_DIR, "yourapp2", "static"),
    os.path.join(BASE_DIR, "watever"),
    "/home/me/Music/TaylorSwift/",
    "/home/me/Videos/notNsfw/",
]

STATIC_ROOT = "/var/www/mywebsite/"

STATIC_URL = "https://storage.googleapis.com/<your_bucket_name>/"

Step 2 If you have HTML files or CSS files that access other static files, make sure that they reference those other static files with this updated STATIC_URL setting.
In your home.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'home/css/home.css' %}">

Then in your home.css file
background-image: url("../assets/img/myHandsomeImage.jpg");

You can actually read the reference from the link i have provided.
https://django-storages.readthedocs.io/en/latest/backends/gcloud.html
https://medium.com/@umeshsaruk/upload-to-google-cloud-storage-using-django-storages-72ddec2f0d05
You home CSS link now will translate to :
https://storage.googleapis.com/[your_bucket_name]/home/css/home.css

If you wish, you could just put the absolute path (complete URL), but such configuration would always require you to update the used URLs manually, like if you switched to development mode and wanted to just access the static files locally instead of from GCS.
This would copy all files from each directory in STATICFILES_DIRS to STATIC_ROOT directory.
python3 manage.py collectstatic

# or if your STATIC_ROOT folder requires permissions to write to it then:
# sudo python3 manage.py collectstatic

Okay after searching through stackoverflow i see this problem have been solved and i don't want this to be a form of a duplicate. So here is the link to stackoverflow solution:Serve Static files from Google Cloud Storage Bucket (for Django App hosted on GCE) .


Q: C# FileInfo Name foreach I have this code:
FileInfo finfo = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "cleo", file.Key));

DialogResult modifiedcleofiles = MessageBox.Show("error", "error title", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if(modifiedcleofiles == DialogResult.OK)
{
    Message.Info(finfo.Name); //It prints filename ok
    if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "gs", "CLEO")))
        Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "gS", "CLEO"));

    foreach (FileInfo filemove in finfo) //I don't know how to make foreach
    {
        filemove.MoveTo(Path.Combine(Directory.GetCurrentDirectory(), "gS", "CLEO", filemove.Name));
    }
}

So it's my problem. This code works fine without foreach, it works with:
finfo.MoveTo(Path.Combine(Directory.GetCurrentDirectory(), "gS", "CLEO", finfo.Name));

It's ok, but if there are more than 2 files, etc.. It shows two messageboxes.. I wan't to move all finfo files. NOTE all finfo files, not all files which exists in folder ! Thanks in advance :( P.S do not give -karma or etc, I'm newbie..
P.S I'm tried this code:
foreach (FileInfo filemove in finfo.Directory.EnumerateFiles()) {
    filemove.MoveTo(Path.Combine(Directory.GetCurrentDirectory(), "gS", "CLEO", filemove.Name));
}

It move's all files from that folder, but I need only finfo..

A: Just add
.Where(i => i.Extension.Equals(".finfo", StringComparison.InvariantCultureIgnoreCase))

to the enumerable. Or better, use the other overload of EnumerateFiles:
foreach (FileInfo filemove in finfo.Directory.EnumerateFiles("*.finfo")) {

Also, note that MoveTo only works on the same logical drive. If that's not enough for you, you will need to add your own copy+delete method for moving files accross drives.


Q: How do I build a dictionary of members with children from mysql in python? I am developing a unilevel Multi Level Marketing (MLM) application which stores data with mysql columns  id, parent_id
with each item having one parent. each item can have up to 50 children. Given a particular id, how do I get all its children and children of its children etc. and its parents and parent's parents, etc. I want to get this data into a dic and display. Thanks


Q: ReactJS Firebase multiple where clause isn't working I'm developing an application which need's to fetch users based on prefered preferences but the sorting isn't functioning.
export const fetchUsers = (minAge, maxAge, prefer, gender) =>
  db.collection('profiles')
    .where('age', '>=', minAge)
    .where('age', '<=', maxAge)
    //.where('gender', '==', prefer)
    .get()
    .then(snapshot => snapshot.docs.map(doc => ({id: doc.id, ...doc.data()})))

When I use the three where clauses it should return a user but it returns zero. When I only use age or only use gender the query returns the correct data.
Why aren't the three where clauses not returning data and it only works when I use where on age or gender?
I've tried to change the .where clause to .where({...}) but this is incorrect code. Also i've tried to filter on only minAge and gender but also returns zero data, while it should return a user.

A: Firestore queries always work based on one or more indexes. In the case where you have conditions on multiple fields, it often needs a so-called composite index on those fields. Firestore automatically adds indexes for the individual fields, but you will have to explicitly tell it to create composite indexes.
When you try to execute a query for which the necessary index is missing, the SDK raises an error that contain both the fact that an index is missing and a direct link to the Firestore console to create exactly the index that the query needs. All fields are prepopulated, so you just need to click the button start creating the index.
If you don't see the error message/link in your apps logging output yet, consider wrapping the query in a try/catch and logging it explicitly.


Q: VueJs run watcher handler immediatly after triggering Example:
export default {
    data() {
        return {
            data1: 1,
            data2: 2
        }
    },
    mounted() {
        this.data1 = 2
        console.log(this.data2)
    },
    watch: {
        data1: {
            handler(newData1) {
                this.data2 = newData1 * 3
            }
        }
    }
}

Expected behavior: the browser write number 6 to the console
Current behavior: the browser write number 2 to the console
In this example I try to write the modified data2 after changed data1 value, but it write the data2 value before the watcher handler modify it. Is there a way to immediatly run watcher handler after triggering? I know I can use a computed property in this example but I need data in my project.
I tried to set the watcher immediatly property to true but isn't working.

A:
You can use computed property for data2

export default {
            data() {
                return {
                    data1: 1
                }
            },
            mounted() {
                this.data1 = 2
                console.log(this.data2)
            },
            computed: {
              data2() {
                return this.data1 * 3
              }
            }
         }

A: The watcher will not trigger in the middle of your mounted() handler, you need to wait until the handler has finished. This is how Javascript works, it is not a limitation in Vue.

A: I am not sure what the purpose of your code, but below will work
  mounted() {
    this.data1 = 2
    this.$nextTick(() => {
      console.log(this.data2)
    })
  },

A:
Current behavior: the browser write number 2 to the console

It becauses Vue performs DOM updates asynchronously first run into mounted you made change to data1 (also puts console.log(this.data2) to callback queue at this point of time this.data2 = 2 thats why you see log 2) it also triggers watch of data1 If you log data2 here you see value of 6.

In order to wait until Vue.js has finished updating the DOM after a data change, you can use Vue.nextTick(callback) immediately after the data is changed

mounted() {
  this.data1 = 2
  this.$nextTick(() => {
     console.log(this.data2); // 6
  })
}

or use Vue.$watch - Watch an expression or a computed function on the Vue instance for changes
data() {
  return {
    data1: 1,
    data2: 2
  }
},
watch: {
  data1: function(val) {
    this.data2 = val * 3
  }
},
mounted() {
  this.data1 = 2
  this.$watch('data2', (newVal) => {
    console.log(newVal) // 6
  })
}

A: As another answer explains, this is expected default behaviour and can be addressed by using nextTick, most times it's not the case because a computed is used instead, as suggested in yet another answer.
In Vue 3, this can be changed by the use of flush option:
mounted() {
    this.data1 = 2
    console.log(this.data2) // 6
},
watch: {
    data1: {
        handler(newData1) {
            this.data2 = newData1 * 3
        },
        flush: 'sync'
    }
}


Q: How can I change this WooCommerce cart icon into text Need help. How can I change this cart icon?

I want to change it to an image icon. Also, I need it to put the code in my Child-theme stylesheet.
Thank you in advance


Q: How to format columns dates in python that they are weekly based on eachother? I have a dataframe df that looks similar to this:
identity      Start        End     week
  E         6/18/2020   7/2/2020    1
  E         6/18/2020   7/2/2020    2
 2D         7/18/2020   8/1/2020    1
 2D         7/18/2020   8/1/2020    2
 A1          9/6/2020   9/20/2020   1
 A1          9/6/2020   9/20/2020   2

The problem is that when I extracted the data I only had Start date and End date for every identity it replaced, but I have the data by weeks all identitys have the same amount of weeks some times all identitys can have 5 or 6 weeks but they are always the same. I want to make Stata and end be weekly so when the first week end I add 7 days. And when the week starts again it starts where week ended. A representation would be
identity      Start        End     week
   E       6/18/2020    6/25/2020   1
   E       6/25/2020    7/2/2020    2
  2D       7/18/2020    7/25/2020   1
  2D       7/25/2020    8/1/2020    2
  A1        9/6/2020    9/13/2020   1
  A1       9/13/2020    9/20/2020   2

I tried a simple method that was creating a sevens column and making the sum to get the end of the week I get and error Addition/subtraction of integers and integer-arrays with Timestamp is no longer supported. Instead of adding/subtracting n, use n * obj.freq
Then I would concat start over minus seven but I don't know how to get around this problem. Any help would be magnificent.

A: Similar to your other question:
First convert to datetimes:
df.loc[:, ["Start", "End"]] = (df.loc[:, ["Start", "End"]]
                                 .transform(pd.to_datetime, format="%m/%d/%Y"))

df

identity    Start   End     week
0   E   2020-06-18  2020-07-02  1
1   E   2020-06-18  2020-07-02  2
2   2D  2020-07-18  2020-08-01  1
3   2D  2020-07-18  2020-08-01  2
4   A1  2020-09-06  2020-09-20  1
5   A1  2020-09-06  2020-09-20  2

Your identity is in groups of two, so I'll use that when selecting dates from the date_range:
 from itertools import chain

result = df.drop_duplicates(subset="identity")

date_range = (
    pd.date_range(start, end, freq="7D")[:2]
    for start, end in zip(result.Start, result.End)
)

date_range = chain.from_iterable(date_range)
End = lambda df: df.Start.add(pd.Timedelta("7 days"))

Create new dataframe:
df.assign(Start=list(date_range), End=End)

    identity    Start   End     week
0   E   2020-06-18  2020-06-25  1
1   E   2020-06-25  2020-07-02  2
2   2D  2020-07-18  2020-07-25  1
3   2D  2020-07-25  2020-08-01  2
4   A1  2020-09-06  2020-09-13  1
5   A1  2020-09-13  2020-09-20  2


Q: Python plot window not closing after being called from a JavaScript script I have a JavaScript script (open_hist_w_user.js) spawns a python process and passes data to a python script (create_histogram.py). The Python script creates a histogram using the Matplotlib library and displays it. The problem is that even after calling plt.close('all'), the plot window does not close.
Code:
*javascript; open_hisr_w_user.js*
/**
 * This script is used to spawn a python process that generates a histogram for the specified username.
 *
 * @param {string} username - The username for which the histogram is being generated.
 *
 * @returns {ChildProcess} - The spawned python process.
 */

const { spawn } = require('child_process');
const username = 'some_username';
const pythonProcess = spawn('python', ['./create_histogram.py', username]);

python;create_histogram.py
import matplotlib.pyplot as plt
import sys
import time

def create_histogram(username):
    """
    This function creates a histogram of data, with a specified number of bins and range, and displays it.

    Parameters
    ----------
    username : str
        The username for which the histogram is being generated.

    Returns
    -------
    None
    """
    plt.close('all')  # close any previous plot windows

    # plot the histogram
    plt.clf()  # clear the previous plot
    plt.hist([1, 2, 3, 4, 5], bins=3, range=(0, 5))
    plt.xlabel('Total')
    plt.ylabel('Frequency')
    plt.title(f'Histogram of Total Column for {username}')
    plt.show()  # show the plot
    time.sleep(5)  # wait for 5 seconds
    plt.close('all')  # close the plot window
if __name__ == "__main__":
    username = sys.argv[1]
    create_histogram(username)

I tried using plt.close('all') to close the plot window, but it did not work. I expected the plot window to close after some delay after the histogram was created. Before you ask why am I not just using a javascript script,I tried porting my code a few days ago using plotly and df3, but couldn't get it working; so here we are passing data through the console.
Expected Result:
insert image of closed window here
Actual Result:

A: Try this:
*javascript; open_hisr_w_user.js*
    /**
     * This script is used to spawn a python process that generates a histogram for the specified username.
     *
     * @param {string} username - The username for which the histogram is being generated.
     *
     * @returns {ChildProcess} - The spawned python process.
     */

    const spawn = require('child_process').spawn;
    const username = 'some_username';
    const pythonProcess = spawn('python', ['./create_histogram.py', username], {
      detached: true,
      stdio: ['ignore']
    });
    pythonProcess.unref();


Q: Returning IPv6 instead of IPv4 in VB I have this function which is querying the IP address.
Dim strHostName As String
Dim strIPAddress As String

Public Function ipconfig()
  strHostName = System.Net.Dns.GetHostName()
  strIPAddress = System.Net.Dns.GetHostEntry(strHostName).AddressList(0).ToString()

  rtb_Output.Text = rtb_Output.Text + "Computer Name: " & strHostName + Environment.NewLine + "IP Address: " &strIpAddress
End Function

It works absolutely fine on my Windows 7 desktop wired connection, and returns the IPv4 address as expected.
When I run it on my Windows 8 tablet, either wired or wirelessly, it returns the IPv6 address instead, whereas I need the IPv4 address. Do you have any ideas why, or how I can get it to return the IPv4 address instead?

A: It seems unlikely, but certainly not impossible, that your Windows 8 machine has only IPv6 addresses. However, it is not uncommon to turn off IPv6 support on network adapters for any OS as it is not commonly supported yet. Check the adapters for each computer to verify the addresses and compare to your result.
Regardless, you would be advised to assume that your query will return multiple addresses of type IPv6, IPv4 and more with multiples of any type as well. If you are looking for specific types then use the AddressFamily property to identify type.
For example, for IPv4 only:
Dim hostEntry = Dns.GetHostEntry(hostNameOrAddress)

    Dim addressList As New List(Of IPAddress)

    For Each address In hostEntry.AddressList
        If address.AddressFamily = Sockets.AddressFamily.InterNetwork Then
            addressList.Add(address)
        End If
    Next

    Return addressList

A: You can use this:
System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName).AddressList.First.ToString()

A: You can use LINQ to filter the results:
Dim ipHostEntry = Dns.GetHostEntry(Dns.GetHostName)
Dim ipAddress = ipHostEntry.AddressList.FirstOrDefault(Function(ip) ip.AddressFamily = AddressFamily.InterNetwork)
If ipAdress IsNot Nothing Then
  ' Output ipAdress.ToString()
Else
  ' No IPv4 address could be retrieved
End If

Explanation:
IPHostAddress.AddressList returns an Array(Of IPAddress) which implements the IEnumerable interface and can therefore be enumerated by LINQ expressions.
FirstOrDefault will return the first element from the AddressList array that matched the predicate lambda function that is submitted as first and only parameter of FirstOrDefault. The predicate function has to be written to return a boolean.
The array is iterated from the first to the last element, and for each element the lambda function is evaluated, where its parameter ip is the current iteration item. With ip.AddressFamily = AddressFamily.InterNetwork we determine whether the current item is an IPv4 address. If so, the expression evaluates true and the item is returned by FirstOrDefault. If it evaluates to false, the next item from the array is checked and so on. If no element matches the predicate, FirstOrDefault returns the default value, in this case Nothing (N. B.: the extension First works the same way but throws an exception if no item matches the predicate; both First and FirstOrDefault can be called without any arguments, they return the first element of the sequence then).
I prefer the extension methods based notation as above, but you can use the original From In Where Select LINQ notation as well if you prefer:
Dim ipAddress = (From ip In ipHostEntry.AddressList
                 Where ip.AddressFamily = AddressFamily.InterNetwork
                 Select ip)(0)

Note that (0) is the argument for another extension method ElementAtOrDefault(index As Integer) in this case.

A:  Public Function GetIPv4Address()
        GetIPv4Address = String.Empty
        Dim strmachine As String = System.Net.Dns.GetHostName()
        Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strmachine)

        For Each ipheal As System.Net.IPAddress In iphe.AddressList
            If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
                GetIPv4Address = ipheal
               ' MsgBox(ipheal.ToString, MsgBoxStyle.Critical, "ERROR")

           End If
        Next

    End Function


Q: Enterprise Autoscale Application Block (WASABi)  up by a variable amount I was looking at the WASABi documentation and I am confused about a particular aspect of this library.
I need to create a custom reactive rule. Say, this rule runs every minute and the "scale" action of this rule should be to scale up by "x" amount. It seems that as though I can set the "scale" action to a particular number (say 1 or 2), but not pass in a variable computed by, say my custom operand.
I understand that I can create a custom operand to check my condition, but I want the custom operand to compute how much the "scale" action should scale the target Worker Role by and then pass this value to the "scale" action.
Is there someway to define these rules outside the XML to achieve this?
Any help would be greatly appreciated!

A: Actions can increment or decrement the count by a number or by a proportion. So if you want a dynamic increment or decrement I think you will need to create a custom action. I think you could pull out the info you need from the IRuleEvaluationContext.
To change the instance count you will need to change the deployment configuration.  See https://social.msdn.microsoft.com/forums/azure/en-US/dbbf14d1-fd40-4aa3-8c65-a2424702816b/few-question-regarding-changing-instance-count-programmatically?forum=windowsazuredevelopment&prof=required for some discussion.
You should be able to do that using the Azure Management Libraries for .NET and the ComputeManagementClient.  Something like:
using (ComputeManagementClient client = new ComputeManagementClient(credentials))
{
    var response = await client.Deployments.GetBySlotAsync(serviceName, slot);

    XDocument config = XDocument.Parse(response.Configuration);

    // Change the config

    StringBuilder builder = new StringBuilder();

    using (TextWriter writer = new StringWriter(builder))
    {
        config.Save(writer);
    }

    string newConfig = builder.ToString();

    await client.Deployments.BeginChangingConfigurationBySlotAsync(serviceName, slot, new DeploymentChangeConfigurationParameters(newConfig));
}


Q: Write a title on itextPdf table border I'm using iTextPdf to create a table on an android application.
I need to have the title of the table on its upper border as shown on the image below.

How can I achieve this?
Thanks in advance

A: Please take a look at the CellTitle example. It creates a PDF in which titles are added on the cell border: cell_title.pdf

This is accomplished by using a cell event:
class Title implements PdfPCellEvent {
    protected String title;

    public Title(String title) {
        this.title = title;
    }

    public void cellLayout(PdfPCell cell, Rectangle position,
        PdfContentByte[] canvases) {
        Chunk c = new Chunk(title);
        c.setBackground(BaseColor.LIGHT_GRAY);
        PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
        ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
            new Phrase(c), position.getLeft(5), position.getTop(5), 0);
    }
}

A cell event can be added to a PdfPCell using the setCellEvent() method:
public PdfPCell getCell(String content, String title) {
    PdfPCell cell = new PdfPCell(new Phrase(content));
    cell.setCellEvent(new Title(title));
    cell.setPadding(5);
    return cell;
}

Next time, please show what you've tried before asking a question. Also take a look at the official documentation because everything you needed to answer your question yourself was available on the iText web site.


Q: How can I get the a lambda function by using its ARN in the AWS CLI? I'm using the Azure Toolkit for AWS to create my lambda, and then running some powershell scripts to act on it. After creation, I get the function's ARN as an output. I don't see anywhere in the documentation where I can access the function via the ARN, everything takes the function-name as a parameter.

A: You can use the ARN in the --function-name parameter when executing AWS CLI calls for the AWS lambda API.
Here's an example for the get-function api:

--function-name (string)

The name of the Lambda function, version, or alias.

Name formats

Function name - my-function (name-only), my-function:v1 (with alias).

Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function .

Partial ARN - 123456789012:function:my-function


Q: How can I split a column into 2 in the correct way? I am web-scraping tables from a website, and I am putting it to the Excel file.
My goal is to split a columns into 2 columns in the correct way.
The columns what i want to split: "FLIGHT"
I want this form:
First example:  KL744 --> KL    and 0744
Second example: BE1013 --> BE and 1013
So, I need to separete the FIRST 2 character (in the first column), and after that the next characters which are 1-2-3-4 characters. If 4 it's oke, i keep it, if 3, I want to put a 0 before it, if 2 : I want to put 00 before it (so my goal is to get 4 character/number in the second column.)
How Can I do this?
Here my relevant code, which is already contains a formatting code.
df2 = pd.DataFrame(datatable,columns = cols)
df2["UPLOAD_TIME"] = datetime.now()
mask = np.column_stack([df2[col].astype(str).str.contains(r"Scheduled", na=True) for col in df2])
df3 = df2.loc[~mask.any(axis=1)]

if os.path.isfile("output.csv"):
    df1 = pd.read_csv("output.csv", sep=";")
    df4 = pd.concat([df1,df3])
    df4.to_csv("output.csv", index=False, sep=";")

else:
    df3.to_csv
    df3.to_csv("output.csv", index=False, sep=";")

Here the excel prt sc from my table:

A: You can use indexing with str with zfill:
df = pd.DataFrame({'FLIGHT':['KL744','BE1013']})

df['a'] = df['FLIGHT'].str[:2]
df['b'] = df['FLIGHT'].str[2:].str.zfill(4)
print (df)
   FLIGHT   a     b
0   KL744  KL  0744
1  BE1013  BE  1013

I believe in your code need:
df2 = pd.DataFrame(datatable,columns = cols)
df2['a'] = df2['FLIGHT'].str[:2]
df2['b'] = df2['FLIGHT'].str[2:].str.zfill(4)
df2["UPLOAD_TIME"] = datetime.now()
...
...


Q: Finding the Intersection of 2 sorted lists I have an assignment for
Given two sorted lists of comparable items,
L1 and L2. You can assume that in L1 and
L2 all elements are different (no duplicates) but t
he interception between L1 and L2 may be
non-empty.
(b)
Implement  an  efficient  method  in
Java to  compute  the symmetric  difference(∆)
between  L1  and  L2,  L1 ∆L2.  Please  remember  that  in
set  theory,  the symmetric
difference of two sets A and B is the set of elements either in A or in B but not in both.
Example: Suppose A = {1,3,5,7,9} and B = {1,2,3,4,5}, A ∆ B = {2,4,7,9}.
I wrote this so far but I don't know why it stops the search at the end of the first list and doesn't continue checking the 2nd list for differences. Any help?
    public static <AnyType extends Comparable<? super AnyType>>
        void symDifference(List<AnyType> L1, List<AnyType> L2,
                List<AnyType> Difference)
{

    ListIterator<AnyType> iterL1 = L1.listIterator();
    ListIterator<AnyType> iterL2 = L2.listIterator();
    AnyType itemL1 = null;
    AnyType itemL2 = null;

    if (iterL1.hasNext() && iterL2.hasNext())
    {
        itemL1 = iterL1.next();
        itemL2 = iterL2.next();
    }

    while (itemL1 != null && itemL2 != null)
    {
        int compareResult = itemL1.compareTo(itemL2);
        if (compareResult == 0)
        {
            itemL1 = iterL1.hasNext() ? iterL1.next() : null;
            itemL2 = iterL2.hasNext() ? iterL2.next() : null;
        }
        else if (compareResult < 0)
        {
            Difference.add(itemL1);
            itemL1 = iterL1.hasNext() ? iterL1.next() : null;
        }
        else
        {
            Difference.add(itemL2);
            itemL2 = iterL2.hasNext() ? iterL2.next() : null;
        }
    }
}

public static void main(String[] args)
{
    LinkedList<Integer> list1 = new LinkedList<>();
    LinkedList<Integer> list2 = new LinkedList<>();
    LinkedList<Integer> difList = new LinkedList<>();

    list1.add(1);
    list1.add(3);
    list1.add(5);
    list1.add(7);
    list1.add(9);

    list2.add(1);
    list2.add(2);
    list2.add(3);
    list2.add(4);
    list2.add(5);

    symDifference(list1,list2,difList);
    System.out.println(difList);

}
}

A: Well, think about this.
list1 {1, 2, 3, 5}
list2 {1, 5}.
As shmosel said, what happen if your loop runs twice? It exit the loop, and the function.
Ideally, you want to go through all elements on both array.
BTW,  I don't think your solution is working as well (you can of cause, but your code will look super ugly, probably takes O(list1.length * list2.length)). Since both lists are sorted, you can compare both element, and loop the smaller element list first. For example, using list1 and list2, compare 1 and 1, both equal, then move to 2 and 5. Then compare 2 and 5, add 2 to the list, and move 2 to 3 ONLY. Which takes O(list1.length + list2.length).

A: It’s a classic pitfall. When one list runs dry, your loop stops (as it should). At this point you will still want to exhaust the other list. So after your while loop insert the logic to copy the remaining elements from the other list. Since you know one list is done and only one has elements remaining, but you don’t know which, the easy solution is just to take the remaining elements from both lists. Since both lists were sorted, you know that the remainder of the list that still has elements in it cannot contain any elements from the run-dry list, so you simply add them all to your result. All in all you will probably add two while loops after the loop you have, one for iterL1 and one for iterL2. Since each of these run in linear time, your time complexity will not get hurt.


Q: Intechanging node roles in Hyperledger Fabric Can nodes interchange roles in hyperledger fabric?
Is it possible to make an endorsing or committing peer take the role of an orderer when required?

A: *

*Every endorsing peer is also a committing peer.

*An orderer and a peer are totally different binaries, and have completely different APIs, so - you can't have one fill the role of the other.


Q: Docusign navigate to a Visualforce page upon signing Can we navigate signer who is on a Mobile device (Salesforce 1) to a visualforce page when the document is signed and the submit button is clicked?

A: Yes you can accomplish this.  You'll need to use the DocuSign API and more specifically, the Embedding functionality which will allow you to sign through a webview or an iFrame on the mobile device.
With Embedding you can control the redirects URLs based on actions the user takes.  For instance, if the user signs you can navigate to the Visual Force page in question.  Or, if the user declines to sign then you can navigate them to a different page if you'd like.  Same thing for if they hit the X to close the signing window.
To get started with learning DocuSign's APIs check out the DocuSign Developer Center:
http://www.docusign.com/developer-center
And for code samples of Embedded Signing in 6 different language stacks see the bottom 3 API Walkthroughs in the API Tools section:
http://iodocs.docusign.com/apiwalkthroughs


Q: Tickets 3.12A PHP line issue I have a TicketsCAD installation issue. I installed locally, and the install went fine, everything was well. Then, when I went to login to the admin backend, it gave me this error:

Warning: A non-numeric value encountered in C:\xampp\htdocs\tickets\incs\browser.inc.php on line 25

So, I went and checked the file, line 25:
$j=strpos($userAgent, $navigator)+$n+strlen($navigator)+1;

I don't immediately see anything wrong with this syntax. Any help would be much appreciated.
(FYI: I am not a super-programmer, as many of you are. Please go easy on me.)
PHP Version 7.2.4
Here is the entire piece of code:
$l = strlen($userAgent);
     for ($i=0; $i<count($browsers); $i++){
        $browser = $browsers[$i];
        $n = stristr($userAgent, $browser);
        if(strlen($n)>0){
     $version = "";
  $navigator = $browser;
$j = $pos+$n+strlen($navigator)+1;


Q: Executing a script takes so long on Git Bash I'm currently executing a script on Git Bash on a Windows 7 VM. The same script is executed within 15-20 seconds on my Mac machine, but it takes almost 1 hour to run on my Windows.
The script itself contains packages that extract data from XML files, and does not call upon any APIs or anything of the sort.
I have no idea what's going on, and I've tried solving it with the following answers, but to no avail:

*

*https://askubuntu.com/a/738493

*https://github.com/git-for-windows/git/wiki/Diagnosing-performance-issues
I would like to have someone help me out in diagnosing or giving a few pointers on what I could do to either understand where the issue is, or how to resolve it altogether.
EDIT:
I am not able to share the entire script, but you can see the type of commands that the script uses through previous questions I have asked on Stackoverflow. Essentially, there is a mixture of XMLStarlet commands that are used.

*

*https://stackoverflow.com/a/58694678/3480297

*https://stackoverflow.com/a/58693691/3480297

*https://stackoverflow.com/a/58080702/3480297
EDIT2:
As a high level overview, the script essentially loops over a folder for XML files, and then retrieves certain data from each one of those files, before creating an HTML page and pasting that data in tables.
A breakdown of these steps in terms of the code can be seen below:
Searching folder for XML files and looping through each one
for file in "$directory"*
do
    if [[ "$file" == *".xml"* ]]; then
        filePath+=( "$file" )
    fi
done

for ((j=0; j < ${#filePath[@]}; j++)); do

    retrieveData "${filePath[j]}"

done

Retrieving data from the XML file in question
function retrieveData() {
    filePath=$1

    # Retrieve data from the revelent xml file
    dataRow=$(xml sel -t -v "//xsd:element[@name=\"$data\"]/@type" -n "$filePath")

    outputRow "$dataRow"
}

Outputting the data to an HTML table
function outputRow() {
    rowValue=$1

    cat >> "$HTMLFILE" << EOF

$rowValue

EOF
}

As previously mentioned, the actual xml commands used to retrieve the relevant data can differ, however, the links to my previous questions have the different types of commands used.

A: Your git-bash installation is out of date.
Execute git --version to confirm this.  Are you using something from before 2.x?
Please install the latest version of git-bash, which is 2.24.0 as of 2019-11-13.
See the Release Notes for git for more information about performance improvements over time.


Q: How do I remove NLP from Tika? I just want to extract data from documents. So I do not think I need OpenNLP.
Is there a way to easily take it out so my Tika is lighter?

A: I have same need just like you.The way I deal with it is that I delete the module directly.In my program I delete the NLP and NL module and it works normally.


Q: how to search for Arabic charterers in recorders of DB2 I have a table in DB2 say premmp wherein a column say name might contain Arabic characters
Dim s As String = "SELECT EMPNO, NAME FROM lib.PRemmp where NAME like '% " & gname.text & " %'  ORDER BY RNAME "

where gname.text is a textbox. It does not work, anyone can help me?
I write this code
Adapter.SelectCommand = New OdbcCommand("SELECT EMPNO, NAME FROM lib.PRemmp where NAME like ?  ", MyODBCConnection)
Adapter.SelectCommand.Parameters.Add("@NAME", Odbc.OdbcType.NVarChar).Value = "%" & gname.Text
Adapter.SelectCommand.ExecuteNonQuery()
Adapter.Fill(ds, "MyTable")

it solve my problem
thanks


Q: Functional object basics. How to go beyond simple containers? On the upside I'm kinda bright, on the downside I'm wracked with ADD. If I have a simple example, that fits with what I already understand, I get it. I hope someone here can help me get it.
I've got a page that, on an interval, polls a server, processes the data, stores it in an object, and displays it in a div. It is using global variables, and outputing to a div defined in my html. I have to get it into an object so I can create multiple instances, pointed at different servers, and managing their data seperately.
My code is basically structured like this...
HTML...

JavaScript...
// globals
var server_url = "http://some.net/address?client=Some+Client";
var data = new Object();
var since_record_id;
var interval_id;

// window onload
window.onload(){

  getRecent();

  interval_id = setInterval(function(){
    pollForNew();
  }, 300000);
}

function getRecent(){
  var url = server_url + '&recent=20';
  // do stuff that relies on globals
  // and literal reference to "server_output" div.
}

function pollForNew(){
  var url = server_url + '&since_record_id=' + since_record_id;
  // again dealing with globals and "server_output".
}

How would I go about formatting that into an object with the globals defined as attributes, and member functions(?) Preferably one that builds its own output div on creation, and returns a reference to it. So I could do something like...
dataOne = new MyDataDiv('http://address/?client');
dataOne.style.left = "30px";

dataTwo = new MyDataDiv('http://different/?client');
dataTwo.style.left = "500px";

My code is actually much more convoluted than this, but I think if I could understand this, I could apply it to what I've already got. If there is anything I've asked for that just isn't possible please tell me. I intend to figure this out, and will. Just typing out the question has helped my ADD addled mind get a better handle on what I'm actually trying to do.
As always... Any help is help.
Thanks
Skip
UPDATE:
I've already got this...
$("body").prepend("
text
");
this.test = document.body.firstChild;
this.test.style.backgroundColor = "blue";

That's a div created in code, and a reference that can be returned. Stick it in a function, it works.
UPDATE AGAIN:
I've got draggable popups created and manipulated as objects with one prototype function. Here's the fiddle. That's my first fiddle! The popups are key to my project, and from what I've learned the data functionality will come easy.

A: This is pretty close:
// globals
var pairs = {
    { div : 'div1', url : 'http://some.net/address?client=Some+Client' } ,
    { div : 'div2', url : 'http://some.net/otheraddress?client=Some+Client' } ,
};

var since_record_id; //?? not sure what this is
var intervals = [];

// window onload
window.onload(){  // I don't think this is gonna work

    for(var i; i<pairs.length; i++) {
        getRecent(pairs[i]);
        intervals.push(setInterval(function(){
            pollForNew(map[i]);
        }, 300000));
    }
}

function getRecent(map){
    var url = map.url + '&recent=20';
    // do stuff here to retrieve the resource
    var content = loadResoucrce(url);  // must define this
    var elt = document.getElementById(map.div);
    elt.innerHTML = content;
}

function pollForNew(map){
    var url = map.url + '&since_record_id=' + since_record_id;
    var content = loadResoucrce(url); // returns an html fragment
    var elt = document.getElementById(map.div);
    elt.innerHTML = content;
}

and the html obviously needs two divs:

Your 'window.onload` - I don't think that's gonna work, but maybe you have it set up correctly and didn't want to bother putting in all the code.
About my suggested code - it defines an array in the global scope, an array of objects. Each object is a map, a dictionary if you like. These are the params for each div.  It supplies the div id, and the url stub.  If you have other params that vary according to div, put them in the map.
Then, call getRecent() once for each map object. Inside the function you can unwrap the map object and get at its parameters.
You also want to set up that interval within the loop, using the same parameterization.  I myself would prefer to use setTimeout(), but that's just me.
You need to supply the loadResource() function that accepts a URL (string) and returns the HTML available at that URL.

This solves the problem of modularity, but it is not "an object" or class-based approach to the problem. I'm not sure why you'd want one with such a simple task. Here's a crack an an object that does what you want:
(function() {

    var getRecent = function(url, div){
        url = url + '&recent=20';
        // do stuff here to retrieve the resource
        var content = loadResoucrce(url);  // must define this
        var elt = document.getElementById(div);
        elt.innerHTML = content;
    }

    var pollForNew =  function(url, div){
        url = url + '&since_record_id=' + since_record_id;
        var content = loadResoucrce(url); // returns an html fragment
        var elt = document.getElementById(div);
        elt.innerHTML = content;
    }

    UpdatingDataDiv = function(map) {
        if (! (this instanceof arguments.callee) ) {
            var error = new Error("you must use new to instantiate this class");
            error.source = "UpdatingDataDiv";
            throw error;
        }

        this.url = map.url;
        this.div = map.div;
        this.interval = map.interval || 30000; // default 30s
        var self = this;

        getRecent(this.url, this.div);

        this.intervalId = setInterval(function(){
            pollForNew(self.url, self.div);
        }, this.interval);
    };

    UpdatingDataDiv.prototype.cancel = function() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
    }

})();

var d1= new UpdatingDataDiv('div1','http://some.net/address?client=Some+Client');
var d2= new UpdatingDataDiv('div2','http://some.net/otheraddress?client=Some+Client');
   ...
 d1.cancel();

But there's not a lot you can do with d1 and d2.  You can invoke cancel() to stop the updating.  I guess you could add more functions to extend its capability.

A: OK, figured out what I needed. It's pretty straight forward.
First off disregard window.onload, the object is defined as a function and when you instantiate a new object it runs the function. Do your setup in the function.
Second, for global variables that you wish to make local to your object, simply define them as this.variable_name; within the object. Those variables are visible throughout the object, and its member functions.
Third, define your member functions as object.prototype.function = function(){};
Fourth, for my case, the object function should return this; This allows regular program flow to examine the variables of the object using dot notation.
This is the answer I was looking for. It takes my non-functional example code, and repackages it as an object...
function ServerObject(url){
  // global to the object
  this.server_url = url;
  this.data = new Object();
  this.since_record_id;
  this.interval_id;

  // do the onload functions
  this.getRecent();

  this.interval_id = setInterval(function(){
    this.pollForNew();
  }, 300000);

  // do other stuff to setup the object

  return this;
}

// define the getRecent function
ServerObject.prototype.getRecent = function(){
  // do getRecent(); stuff
  // reference object variables as this.variable;
}

// same for pollForNew();
ServerObject.prototype.pollForNew = function(){
  // do pollForNew(); stuff here.
  // reference object variables as this.variable;
}

Then in your program flow you do something like...
var server = new ServerObject("http://some.net/address");
server.variable = newValue; // access object variables

I mentioned the ADD in the first post. I'm smart enough to know how complex objects can be, and when I look for examples and explanations they expose certain layers of those complexities that cause my mind to just swim. It is difficult to drill down to the simple rules that get you started on the ground floor. What's the scope of 'this'? Sure I'll figure that out someday, but the simple truth is, you gotta reference 'this'.
Thanks
I wish I had more to offer.
Skip


Q: Using SqlCommand inside of AddSession in ASP.NET Core I was trying to execute a SqlCommand after the TimeSpan ends. When the IdleTimeout has been called, the user would go into the homepage and need to login again. But in addition. I want to call a command for my Last Login:
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddControllersWithViews();
    services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(10);
            });

    services.AddMvc();

    services.AddHsts(options =>
            {
                options.Preload = true;
                options.IncludeSubDomains = true;
                options.MaxAge = TimeSpan.FromDays(30);
            });
}

I would like to add a SqlConnection and SqlCommand inside of this part of the code:
services.AddSession(options =>
{
   options.IdleTimeout = TimeSpan.FromMinutes(10);
});

I tried many things inside of it, after debugging. When the user logged in it will start the AddSession and I thought it will only execute when the TimeSpan ends. Where can I put the end of the command after Timespan ends?
Here's my scenario:

*

*When User logs in, AddSession starts

*When the user idled for 10 mins, it will execute the SqlCommand with last login

*After executing the last login will update into new DateTime


Q: Google BigQuery exports numeric data with wrong decimal to Sheets In our workflow we often export results from a query on BigQuery to Google Sheets, e.g. for distribution to customers in .xlsx format.
I'm running into something weird: when explicitly casting the output of a query to numeric, the export in Sheets gives errors in for the decimals.
For example,

select
  cast('12.3' as numeric),
  cast('12.34' as numeric),
  cast(12.056 as numeric),
  cast('12.345786' as float64)

Yields the following query result in the WebUI

Row f0_ f1_ f2_ f3_
1   12.3    12.34   12.056  12.345786

However, the result in Google Sheets (again, using the WebUI, option Save to Sheets), is this:

f0_ f1_ f2_ f3_
12.3    1234    12056   12345786

Only pattern I can see is that the decimal sign is erroneously dropped when there are two or more decimals.
I really have no clue what is causing this, let alone how to fix it. Exporting the data to .csv and .json does yield the correct result.
Help, anyone?