text:
Q: There i a problem executing code in jupyter notebook I am learning Python. Now whenever I try to run a code it does not get implemented. It shows In [*] instead of In [1] whenever I run the cell. Is there any solution for the problem?

A: I think the cell is still running. You can press the square button at the top to exit the process if you want.
I am assuming that it is because the code takes too long to run. I would recommend you to run something simple like
print("Hello World!")

A: I think your jupter notebook  is having problem  or  the code is running  is taking more time to execute or even  if you are using any loop the program  may bi in infinit loop


text:
Q: Is it possible to mock the string module from Python? For instance, if I have a call to the split method (i.e. some_string.split(":") )
Is is possible to mock this. I wanted to assert that the split function is called using assert_called_once_with

A: I confirm you can't do that because split() is a built-in attribute of str object and you can't set attributes of built-in or extension because they are readonly.
Below some inconclusive tests after trying into a Python 2.7.10 interpreter
>>> __builtins__.str.split
<method 'split' of 'str' objects>
>>> type(__builtins__.str.split)
<type 'method_descriptor'>

Trying to override it using a function
>>> type(lambda f:f)
<type 'function'>
>>> __builtins__.str.split = lambda f: f
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'str'

Trying to override it using a callable (function or method)
>>> type(callable)
<type 'builtin_function_or_method'>
>>> __builtins__.str.split = callable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'str'

After having a look more deeply into the CPython source code here [1]. It's a limitation in Objects/typeobject.c introduce by the function list below. This function check if we try to set a readonly attribute and raise TypeError.
    type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
{
    if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
        PyErr_Format(
            PyExc_TypeError,
            "can't set attributes of built-in/extension type '%s'",
            type->tp_name);
        return -1;
    }
    if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
        return -1;
    return update_slot(type, name);
}

[1] https://hg.python.org/cpython/file/tip/Objects/typeobject.c#l3022

A: Yes it is with a couple of caviats.
In my case I have successfully mocked str in python3 so I can assert that split is being called with a specific input
There are two caviats

*

*With patch, I replaced the original str class with a new class that inherits from str

*In the code that I was testing, I had to do a redundant string casting like str(str_val).split
Here's how one can do it:
class MyStr(str):
    def split(self, sep=None, maxsplit=-1)):
        expected_str = "some_input_mutated_inside_fn_before_split_called"
        self.assertEqual(self, expected_str)
        return super().split(sep=sep, maxsplit=maxsplit)

with patch('mymodule.str', new=MyStr):
    output = mymodule.function_that_calls_string_split(
        "some_input"
    )

redpajama_set_name: RedPajamaStackExchange


text:
Q: What the data type does author mean in exercises for cpdt book? I'm reading cpdt book (great thanks to the author!). Author gives (unofficial) exercises. There is an exercise 6 below:

*Using a reflexive inductive definition, define a type nat_tree of infinitary trees, with
natural numbers at their leaves and a countable infinity of new trees branching out of
each internal node. Define a function increment that increments the number in every
leaf of a nat_tree. Define a function leapfrog over a natural i and a tree nt. leapfrog
should recurse into the i'th child of nt, the i+1st child of that node, the i+2nd child
of the next node, and so on, until reaching a leaf, in which case leapfrog should return
the number at that leaf. Prove that the result of any call to leapfrog is incremented by
one by calling increment on the tree.

The question is: what datatype does author mean?
What I was able to create is kind of
Inductive nat_tree : Set :=
| Leaf (n : nat) : nat_tree
| Node (nat -> nat_tree) : nat_tree.

Very the same definitions I was able to find in the internet. But this does not look to me like code above respects to author's requirement. Because author says function increment that increments the number in every leaf of a nat_tree. But with this definition there is only one leaf in any nat_tree. So, this is just a list, not a tree. One could add one more parameter in 'Node' constructor, like Node (nat->nat_tree) (nat-> nat_tree) : nat_tree, but this definition looks to me like it has exactly 2 children of each internal node, but author says about infinity of new trees branching out of each internal node.
So, I would like to ask for help with nat_tree definition. Or for a clarification why the definition above is good for the task. Or any else clarification which anybody is able to provide.
Notice. I think we do not break any honor code giving an answer. Author removed these exercises from the book and he says he does not support these exercises anymore. Author did not ask anywhere in book to hide sulutions (in opposite to, in example, Software Foundations book). More over, I was able to easily find several solutions to this task in the internet (but they all are like the given above). So, I think this question should be fully ok.

A: This looks like the adequate data type according to the exercise description.
You can build trees with an arbitrary number of distinct leaves, e.g.
Node (fun n => if n =? 0 then Leaf 3 else Leaf 5), Node (fun n => Leaf n)
or Node (fun n => Node (fun m => Leaf (n + m)).


text:
Q: How to tunnel mqtt sub data to pure data (pd) in bash mosquitto_sub -v -h 127.0.0.1 -p 1883 -t 'gyro' | sed 's/[^ ]* //' | pdsend 3000 localhost udp

this command doesn't output anything.
while it should output a value I receive over mqtt.
without sed 's/[^ ]* //' it would output: gyro 23
As output, I want to have a bare number (without gyro) :)

A: To print only 23 from the output of gyro 23
Option 1: using sed to print only numeric.
mosquitto_sub -v -h 127.0.0.1 -p 1883 -t 'gyro' | sed 's/[^0-9]//g'

Option 2: using awk to print the second field which is 23
mosquitto_sub -v -h 127.0.0.1 -p 1883 -t 'gyro' | awk '{print $2}'


text:
Q: Trying to clone a list of GitLab Repo's with subprocess module I'm trying to clone a big list of GitLab repositories from my GitLab Server. However, I'm having trouble getting the subprocess module to work. I've tried the answer to this question but it won't work for me. Open Git Bash shell using a python script and then run a shell script in git bash shell
Here is my code:
repo_list = [list_with_all_repository_names]

    for repo_name in repo_list:
        repo_url = f'https://url_to_my_gitlab_server/{repo_name}.git'
        p = subprocess.run(["C:/Users/my_user_name/AppData/Local/Programs/Git/git-bash.exe",
                            "C:/Users/my_user_name/Documents/Gitlab Repos/git-clone-shell.sh",
                            f"git clone {repo_name}"],
                         bufsize=-1,
                         executable=None,
                         stdin=None,
                         stdout=None,
                         stderr=None,
                         preexec_fn=None,
                         close_fds=False,
                         shell=False,
                         cwd="C:/Users/my_user_name/Documents/Gitlab Repos")
        time.sleep(20)

My shell script is simply a placeholder for the f"git clone {repo_name}" argument in the subprocess.run call, and therefore it's contents are no more than $1
Git bash opens but immediatly crashes and I don't know why. I've also tried to run the command directly in bash without a shell script, but this simply opens git bash and does nothing:
p = subprocess.run(
    [f'git clone {repo_url}'],
    bufsize=-1,
    executable='C:/Users/my_user_name/AppData/Local/Programs/Git/git-bash.exe',
    capture_output=True,
    cwd="C:/Users/my_user_name/Documents/Gitlab Repos"
)

I have the feeling that I'm close to a solution but I don't understand where it's going wrong.

A: I've solved the problem by running the script in a WSL-environment, with the following subprocess setting:
for repo_name in repo_list:
    repo_url = f'url_to_gitlab_server/{repo_name}.git'
    p = subprocess.run(["git", "clone", f"{repo_url}"],
                     bufsize=-1,
                     stdin=None,
                     stdout=None,
                     stderr=None,
                     shell=False)
    print(p)


text:
Q: Named pipe communication in C
EDIT:  I just realised I've entered a double block (I've first opened
  fifoR on both, but fifoR is the oposite on each). corrected that and
  established communication! (CODE BELOW IS FIXED).

I'm trying to create a client-server app, in which the server forks and the child uses named pipes as stdin and stdout to communicate with the client.
It's my first program utilizing named pipes, so I'm probably missing something basic, but I can't tell what (possibly a bunch of stuff)
Here are my codes (compile with no errors and a similar code but using TCP sockets instead of named pipes is running splendid).
Server Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>

#define FIFO_R "./tmp/myfifoR"
#define FIFO_W "./tmp/myfifoW"

void fatal(const char *msg);
void child_process(int fdr,int fdw);

int main()
{
    int fdr,fdw;
    char *myfifor = FIFO_R;
    char *myfifow = FIFO_W;
    int status;

    /* create the FIFO (named pipe) */
    if ( mkfifo(myfifor, 0666) < 0 )
    {
        fatal("fifoR");
    }
    if ( mkfifo(myfifow, 0666) < 0 )
    {
        fatal("fifoW");
    }
    printf("openning fifoR\n");
    if( (fdr = open(myfifor, O_RDONLY)) < 0 )
        fatal("opening fdr");
    printf("fifoR unblocked\n");
    printf("openning fifoW\n");
    if( (fdw = open(myfifow, O_WRONLY)) < 0 )
        fatal("opening fdw");
    printf("fifoW unblocked\n");
    switch(fork())
    {
        case 0:
            child_process(fdr,fdw);
        case -1:
            fatal("child creation");
        default:
            printf("parent\n");
            close(fdr);
            close(fdw);
            wait(&status);
            unlink(myfifor);
            unlink(myfifow);
            printf("all clean, exiting\n");
    }

    return EXIT_SUCCESS;
}

void fatal(const char *msg)
{
    printf("%s\n",msg);
    perror(msg);
    exit(-1);
}

#define APP "./calc/calc"
void child_process(int fdr,int fdw)
{
    printf("child\n");
    close(0);
    close(1);
    close(2);
    if( dup(fdr) != 0 || dup(fdw) != 1 || dup(fdw) != 2 )
        fatal("dup sockets");
    execl(APP,"",(char*)NULL);
    fatal("execl");
}

Client Code (FIXED):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

#define FIFO_W "./tmp/myfifoR"
#define FIFO_R "./tmp/myfifoW"
#define EXIT_CHAR 'q'
#define MAX_BUF 1024

void fatal(const char *msg)
{
    perror(msg);
    exit(-1);
}

int main()
{
    int fdr,fdw;
    char *myfifor = FIFO_R;
    char *myfifow = FIFO_W;
    char buff[MAX_BUF];
    char c;

/* the order of this opens was inversed to the order in server, so it resulted in a deadlock */
    printf("openning fifoR\n");
    if( (fdw = open(myfifow, O_WRONLY)) < 0 )
        fatal("opening fdw");
    printf("fifoR unblocked\n");
/* */

    printf("openning fifoW\n");
    if( (fdr = open(myfifor, O_RDONLY)) < 0 )
        fatal("opening fdr");
    printf("fifoW unblocked\n");
    /*  first strings   */
    memset(buff, 0, sizeof(buff));
    read(fdr,buff,sizeof(buff));
    printf("%s\n",buff);
    while( (c = getchar()) != EXIT_CHAR )
    {
        write(fdw,&c,1);
        if(c == '\n')
        {
            memset(buff, 0, sizeof(buff));
            read(fdr,buff,sizeof(buff));
            printf("%s",buff);
        }
    };
    close(fdw);
    close(fdr);
    return EXIT_SUCCESS;
}

Thanks very much!


text:
Q: Using same keys for y axis and legend for bar graph I have some data that I want to plot.
import matplotlib.pyplot as plt

data = {
    "key 1" : 3,
    "key 2" : 5,
    "key 3" : 7
}

colors = {
    "key 1" : "red",
    "key 2" : "green",
    "key 3" :"blue"
}

x = data.keys()
y = data.values()

plt.bar(x, y, color=[colors[k] for k in data])
plt.legend(y)

This is my output:

I want the legend showing: red color - key 1, green color - key2 etc. and remove the keys from the y axis.

A: You can do that pretty easily using this post:
handles = plt.bar(x, y, color=[colors[k] for k in data])
plt.legend(handles, x)


text:
Q: Are centrifugal fans subject to triboelectric effects, and if so can the increase in charge be predicted and measured? A centrifugal blower is a device that moves gas, usually under power of an electric motor. The blower housing and impeller may be metallic, but often are made of plastic materials. My question is threefold.

*

*Can a centrifugal blower, if made from plastics impart an electric charge on the outlet gas?

*If so what is the predicted increase/decrease in charge based on assumptions of materials, geometry of construction, fan speed, etc. using fundamental physical laws?

*Is there an instrument that can accurately measure the charge of a stream of gas flow?


text:
Q: Calculating length of common boundary lines of two polygon in QGIS I have a map consisting various district. How can I estimate the length of the common boundary shared by any two corresponding districts/polygons in QGIS?
For example if a polygon "A" shares a common boundary with polygons, "B", "C" and "D". Then what would be the length of the boundary between polygon "A-B", "A-C" and "A-D"?
I have calculated the neighboring polygon using the following in field calculator
aggregate(
  layer:='file_districts',
  aggregate:='concatenate',
  expression:= DIST_ID,
  concatenator:=', ',
  filter:=touches($geometry, geometry(@parent))
)

Now i want to estimate the length of each of the neighbor polygon.

A:
Preamble: this solution was being written before the moment when the author demonstrated his efforts in the field calculator.

In QGIS I can suggest using a "Virtual Layer" through Layer > Add Layer > Add/Edit Virtual Layer....
Let's assume we have a layer 'units_1' (yellow) with its corresponding attribute tables accordingly, see image below.

Case 1. With aggregation
With the following query, it is possible to estimate the length of the common boundary shared by any two corresponding districts/polygons.
SELECT
    u11.*,
    GROUP_CONCAT(u12.id || ', len:' || round(st_length(st_intersection(u11.geometry, u12.geometry)), 4), "; ") AS "neighbor_info"
FROM
    "unit_1" AS u11, "unit_1" AS u12
WHERE
    st_intersects(u11.geometry, u12.geometry)
    AND u11.id <> u12.id
GROUP BY
    u11.id
ORDER BY
    u11.id ASC

The output Virtual Layer with its Attribute table will look as following

Case 2. Without aggregation
In case if no aggregation has to be conducted then proceed with the following query
SELECT
    u11.*,
    u12.id || ', len:' || round(st_length(st_intersection(u11.geometry, u12.geometry)), 4) AS "neighbor_info"
FROM
    "unit_1" AS u11, "unit_1" AS u12
WHERE
    st_intersects(u11.geometry, u12.geometry)
    AND u11.id <> u12.id
ORDER BY
    u11.id ASC

Then the new output Virtual Layer with its Attribute table will look as following

A: Similar to @Taras's answer, you can create a virtual layer to get the actual border lines, and then compute their length (or display them, or label them, or ...)
Go to the menu Layer > Add Layer > Add/Edit Virtual Layer... and enter the following query.
select a.id as poly1_id, b.id as poly2_id,
      st_intersection(a.geometry, b.geometry) as geometry,
      st_length(st_intersection(a.geometry, b.geometry)) as border_length
from my_layer a
    join my_layer b
        ON st_intersects(a.geometry, b.geometry)
            AND a.id < b.id

Note that if your layer is in lat/longs (4326), the you should use
st_length(st_intersection(a.geometry, b.geometry),true) as border_length instead. This version of st_length will return a distance in meters instead of degrees.

A: Calculate the length of the border the current polygon shares with all bordering polygons, use this expression that creates an array:

    array_foreach (
        overlay_touches (@layer, $geometry),
        length (intersection ($geometry, @element))
    )

Convert it to a string with array_to_string(), add the $id to identify the polygons and add other modifications (see below).
A polygon layer with an expression-generated label, based on the expression from above, that generates a text-string list of length with all neighboring polygons (see below for the exact expression used here):

*

*The expression used to generate the red line in the screenshot, using Geometry generator:
if ($id = 1, intersection ( $geometry, overlay_touches (@layer, $geometry)[0]),'')

*To generate the length of the common boundary line of polygons b and c, stored in the field named name, use this expression (change layer name and value in lines 2 and 6):
if (
    name = 'b',
    length(
        intersection (
            $geometry,
            geometry (get_feature (@layer, 'name', 'c'))
        )
    ),
    ''
)

*The expression used to generate the label in the screenshot - can be used without changes on any polygon layer:
 'Length border of polygon '  ||
 $id || ' with: '  ||  '\n'  ||
 array_to_string (
     array_foreach (
         overlay_touches (@layer, $id),
         '   - polygon'  ||
         @element || ': ' ||
         round (
             length (
                 intersection (
                     $geometry,
                     geometry (
                         get_feature_by_id (
                             @layer,
                             @element
                         )
                     )
                 )
             ),
             3
         )
     )
 )


text:
Q: Is execution_guard_enabled officially supported feature? I just want to ask if execution_guard is supported feature in neo4j?
The reason I ask is the following:
It looks like it is really helpful to configure neo to terminate all queries longer than some threshold and we want to have it in our application. But I have not found any notes about this in neo4j documentation, and I do not know if it will/won't be changed without further notice in future...
We are currently using neo4j-1.8.2, but we also have plans to move to more recent version of neo4j in the nearest future.
Thanks,
Denys

A: Guards are a not supported feature in Neo4j. Since they are not part of the documentation or the public API they are potentially subject to change in any new release. However they have not changed from 1.8 -> 1.9 and will work in 2.0 as well.


text:
Q: A command to add a customized icon or symbol to Plasma's Default Panel Is there a command, that can add/remove a simple icon in KDE environment tray or anywhere in plasma's Panel (taskbar)?
I need a customized notification icon or any other persistent symbol which shows a customized condition is on or off. (for me, it will show whether a network cable traffic is limited or is free)

A: Just to archive an answer.
Thanks to Sparhawk I could add something in  Panel which shows the state of a connection.
I have scripts for limiting a connection:

each can be run by quicklaunch shortcuts located in panel.
For example 64kbits can contain something like:
#!/bin/bash

wondershaper eth0 64 64

echo 64 > /home/Walesa/mycommands/kbits/state.txt

But running each script should show a persistent easy to see sign, so that the user knows about the limitation. With STDIN widget the contents of state.txt can be displayed:

Here 32 shows the connection has speed 32 kbits. state.txt is what the scripts prepare. But the widget checks its contents every 30 seconds. Not an ideal solution.


text:
Q: how to identify and remove the position ListView I extends ArrayAdapter, painted the following picture

public class UrlArrayAdapter extends ArrayAdapter<UrlItem> {
    private LayoutInflater inflater;
    public UrlArrayAdapter(Context context, List<UrlItem> urlLists) {
        super(context, R.layout.database_table_list, R.id.editLinearLayout1,urlLists);
        inflater = LayoutInflater.from(context);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        UrlItem urlItem = (UrlItem) this.getItem(position);
        CheckBox checkBox = null;
        TextView textView = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.database_table_item, null);
            textView = (TextView) convertView.findViewById(R.id.editText1);
            checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
            convertView.setTag(urlItem);
            checkBox.setChecked(urlItem.getUse());
            textView.setText(urlItem.getUrl());
            textView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                }
            });
        } else {
        }
        return convertView;
    }
}

how to identify and remove the position  to which I press?
setOnClickListener() - does not work - account for a long time to click

A: First of all, in your getView method, your code seems incorrect: you need to set values regardless of whether you use converted view or not.  The code should be like this:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    UrlItem urlItem = (UrlItem) this.getItem(position);
    CheckBox checkBox = null;
    TextView textView = null;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.database_table_item, null);
    }

    textView = (TextView) convertView.findViewById(R.id.editText1);
    checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
    convertView.setTag(urlItem);
    checkBox.setChecked(urlItem.getUse());
    textView.setText(urlItem.getUrl());
}

Then, to detect clicks on individual items, do not use onClickListener on the items.  Instead, use setOnItemClickListener on your ListView.  You will have something like this:
final UrlArrayAdapter adapter = new UrlArrayAdapter(this, items);
ListView list = this.findViewById(R.id.my_list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //deal here with removing the item at position _position_
        //from your adapter, then notify the list view that the data has changed
        adapter.notifyDataSetChanged();
    }
});

A: I think this will help you.
list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
        // REMOVE DATA FROM YOUR LIST ACCORDING TO POSITION.
        adapter.notifyDataSetChanged();
    }
});

If you are facing any problem then you can ask.


text:
Q: If electromagnetic field is long range then why friction works only for contacting surfaces? I know that friction is cause by the electromagnetic force between electrons from 2 contacting surfaces but how come it only applies to physical contact with a solid surface?

A: As you know, atoms are made of positively charged nuclei, surrounded by an equal number of negatively charged electrons. Say the charge of a particular atom is $Z$. There is a distance between the positive and negative charges - the "radius" of the atom - and so we know that perhaps $Z/2$ electrons are "closer" to the contact surface than the positive charge of the nucleus. We can grossly model this as half of the electrons are "away" from the contact surface, and half are "toward" the contact surface, for both surfaces. Further simplifying to model each half as a point charge, and the nucleus itself as a point charge.

The electrostatic force between the two surfaces can be derived easily. Since the force is inversely proportional to square distance, the $1/D^{2}$ repulsive term dominates when the surfaces are close together. When the surfaces are far apart compared to $d$, the two electric dipoles representing each atom cancel.
Of course, this extremely simplistic line of argument can be extended to include surface charges instead of point charges, and to improve some approximation with respect to charge distribution, but the gist is there.
This is not, of course, meant to suggest that friction happens due to some shear force between perfectly parallel planar charges. This was to address the question of how the long range electromagnetic field can cause friction to happen only over short distances.

A: It is because matter is made up of approximately equal numbers of positive and negative charges so the long range effect of these charges is negligible ie the bodies concerned are electrically neutral and do not interact with one another.
Friction is to do with electrostatic forces between particle which are nanometres apart and have formed bonds with one another.
For bodies to interact to any significant degree the electron shells on the surface of each body must "touch" ie friction is a contact force.

A: Friction arises generally from the deformation, or even breaking, of the surface of one body by the other—perhaps mutually. This deformation entails the stretching (or  breaking) of intermolecular or interatomic bonds, which resists the potential or actual motion between the two bodies. This type of friction arises when the interface between the two bodies is not very flat, so that the relative movement of the bodies cannot be exactly planar.
Even when the contact between the bodies is planar, and at a set of outermost points of the bodies, there may be some friction arising from interatomic attraction between the respective neighbouring surface atoms of the two bodies. The extent to which this happens depends very much on the chemical constitution and surface preparation of the bodies, ranging from very low (compared to the general type of friction described above) to very high—the latter being the case, for example, when the presenting surfaces are certain metals that are very clean and free of termination by atoms of gases.


text:
Q: Can't seem to get this GET method to work properly in AngularJS So I am building a portfolio page which uses a json file to store the project information. For some reason, I can't get the anything to show on ng-view, any ideas would be helpful!
Link to the Plunkr
Main Page:

    <ng-view></ng-view>

Main View html:

              {{item.title}}

Application JS:
var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider){
  $routeProvider
    .when('/',{
      controller: "MainController",
      templateUlr: "main.html"
    });
})

app.controller('MainController', function($scope){
  $scope.appList = {};

  $http({
    method: "GET",
    url:"stuff.json"
  }).success(function(data){
    $scope.appList = data;
  })

})

JSON file (just an example):
[{
  "title": "Caption 1",
  "image": "http://placehold.it/450x300?text=Image + 1",
  "link": "#"
}, {
  "title": "Caption 2",
  "image": "http://placehold.it/450x300?text=Image + 2",
  "link": "#"
}, {
  "title": "Caption 3",
  "image": "http://placehold.it/450x300?text=Image + 3",
  "link": "#"
}]

I suspect there may be an issue with the json file, or how I am trying to access it. Anything will help at this point. (All dependencies are already added).

A: It is not templateUlr: instead it is : templateUrl:
You will need to inject $http and it will work.
Here is a working solution.

A: Add $http to controller
app.controller('MainController', function($scope,$http){
  $scope.appList = {};

  $http({
    method: "GET",
    url:"stuff.json"
  }).success(function(data){
    $scope.appList = data;
  })

})


text:
Q: Angular: Prevent navigating to non-existing id parameter What is a correct way to prevent manually routing to a non-existent parameter in the url, when we have the path as in the example: 'edit/:id', where id is the parameter? Of course, it works correctly if we enter an id which matches an existing url, but does not work if we input a non-existent id
I have tried using the wildcard route, but that works only for the full route, without the parameter. Even if you enter some gibberish after /user/ as a paramter, angular still considers it as a valid route.
These are the current routes:
{
        path: '',
        redirectTo: 'user',
        pathMatch: 'full'
    },
    {
        path: 'user',
        component: UserComponent
    },
    {
        path: 'user/:id',
        component: UserEditComponent,
    }
}

A: You could use a Route Resolver. This way you can first resolve the getSomethingById, and if it fails do what you want to do. Note in the example code I use 'of, Observable' from RxJS and catchError from Rxjs/operators.
@Injectable()
export class GetSingleItemResolver implements Resolve<any>{
      constructor(private apiService: APIService) {}

      resolve(route: ActivatedRouteSnapshot): Observable<any> {
        return this.apiService.getItemById(route.params['id']).pipe(
          catchError(err => {
            //Do what you want to do in the case that there is no item found with the ID

            return of(null)
          });
        );
      }
}

Do not forget to add the resolver to your module under the providers array.
In your routing module you need to add it like this:
  {
    path: 'detailPage/:id',
    component: someDetailComponent,
    resolve: {
      singleItem: GetSingleItemResolver
    }
  }

If you work lik this, you can get the singleItem from the router, so you dont have to make the getItemById request in the component itself. This will already be resolved by your resolver. You can get the item from the router like this:
this.route.data.subscribe(data => {
  this.singleItem = data['singleItem'];
});

Hope this helps!


text:
Q: Error when creating associated objects in Rails I've got a create action that is attempting to create a Rating and a Programme in one go:
  def create
    @rating = current_user.ratings.create(params[:rating])
    @rating.create_programme(params[:programme])
    redirect_to ratings_path
  end

In this code, a rating belongs to both a user and a programme and a user
  has_many :ratings
  has_many :programmes, :through => :ratings

and a programme
  has_many :users, :through => :ratings
  has_many :ratings

When I call the create action above in the RatingsController, the Programme is not being saved as being owned by the @rating for some reason. So if I call for instance:
rating.programme.channel

on a rating in a view, it tells me that the programme is a nil object. However, the programme has been saved fine - it's just the association that hasn't been saved. I'm sure it's a pretty basic thing here, but I can't figure it out. Can someone point me in the right direction?
thanks, a

A: In response to your question to help make the code cleaner:
def create
  @rating = Rating.new(params[:rating])
  @rating.user      = curent_user
  @rating.programme = Programme.find_or_create_by_title(params[:programme])
  @rating.save

  redirect_to ratings_path
end

First of all you call find_or_create for a title and then save it, but the record will aleady be created there so the save doesn't do anything at all.  Second, while the association proxies are cool for easily creating ralated objects, they can get quite hairy in a more comlex relationship like you have here and make the code harder to read.
So instead of using the association proxies to create records, direct assignment would be better.  Its easier to tell at a glance exactly what is happening and where the information is coming from, and doesn't need an ugly merge call in there.  It's a little longer, but I thinks its far more easily understood at a glance.
Lastly, you probably don't need @programme as a stand alone instance variable since you would have easy access to that object from @rating.programme in your views.  In most cases, it's best to pass as few instance variable as possible, especially when the objects have an easily accessible direct relationship.  Its especially true in this case becuase you aren't rendering a template at all.

A: Your code looks right.  Try this.  Immediately after hitting this create action go into you script/console and see whats going on.  Type:
Rating.last

It should return the rating that was just created.  Look for user_id and programme_id in the output and see if they are set.  If they are then you have a bug elsewhere.  Perhaps you are not looking at the rating you think you are or something.

A: Well you are attempting to create the parent from the child (ratings belongs to Programme, right?) . I don't think that works.
Programme.ratings.create would work.

A: I got the create action working ok with the following. Would appreciate it if anyone could et me know whether there's a more elegant way to get this to work :)
  def create
    @programme = Programme.find_or_create_by_title(params[:programme])
    @programme.save
    @rating = current_user.ratings.create!(params[:rating].merge(:programme_id => @programme.id))
    redirect_to ratings_path
  end

andy


text:
Q: Pipe with MomentJS not returning correct difference of time I built a Pipe in Ionic(Angular) that does the work of transforming the time into 'moments from now'.
This is where I'm using:
 dateOfEvent = '2018-02-05 19:45:40';

 <p>{{dateOfEvent | timeago}}</p>

expected output: 40 minutes ago
returned output: 2 hours ago

This is my Pipe
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
moment.locale('pt-br');

@Pipe({
  name: 'timeago',
})
export class TimeagoPipe implements PipeTransform {

  transform(value) {

      let timeAgo = moment(value).fromNow();
      return timeAgo;

  }
}

Can you see what I'm doing wrong?

A: Just made a fix for this. I don't know if it's the best approach but if someone has a better one just post here and I change the best answer.
All I did was to format the dateOfEvent to a moment value.
Then I get the timeAgo based on the formatted value, not the one coming from the db directly(the one from my db was being generated by moment too but someway it was not recognizing as moment when retrieving from db)
So the corrected pipe is:
transform(value) {

      let formatted = moment().format(value);
      let timeAgo = moment(formatted).fromNow();

      return timeAgo;

}

Thanks for the help!


text:
Q: image in local html couldn't be loaded into webview in windows8 I want to load local html file which in the local folder to the webview, but WebView doesn't support 'ms-aspx:///' protocal, I found a solution to read the html file to stream, and then convert it to string, using NavigateToString method to load the html, it works well. But, If there's an image in the html file, the image couldn't display, anyone can help?

A: I have solved.
Solution:
Convert the image file to base64 string
StorageFolder appFolder = ApplicationData.Current.LocalFolder;
        StorageFile file = await appFolder.GetFileAsync("SplashScreen.png");
        using (var stream = await file.OpenAsync(FileAccessMode.Read))
        {
            var reader = new DataReader(stream.GetInputStreamAt(0));
            var bytes = new byte[stream.Size];
            await reader.LoadAsync((uint)stream.Size);
            reader.ReadBytes(bytes);
            base64 = Convert.ToBase64String(bytes);
        }

Use StringBuilder to create the html string
sb.Append("<title>Image test</title>
This is a test app!
");
        TestWebView.NavigateToString(sb.ToString());

A: Try using the ms-appx-web:// scheme instead of ms-aspx:// to load html from a WebView.  If that doesn't work, you may need to use the ms-appdata:// scheme to access the image if it's in your application data folder.
Some further resources that might help:
How to load a local HTML-File into Webview
URI schemes
How to reference content


text:
Q: How does Apple Pay NFC work if the NFC SDK can't write? From what I understand, on iOS 11 the NFC SDK can't write NFC tags. How, then, does the 2-way-communication required for NFC payment systems done???
Thanks

A: Apple does not expose an API to app programmers for writing NFC data. That doesn't mean that the hardware isn't capable of two-way communication.
Apple developers have access to the hardware through APIs that are not exposed generally.


text:
Q: setup django to mysql I'm trying to connect django to mysql database on windows. I tried to install >pip install MySQL-python but i'm getting an error . I added in the file settings.py :
DATABASES = {
  'default': {
       'ENGINE': 'django.db.backends.mysql',
        'NAME': 'toto',
        'USER': 'root',
        'PASSWORD': '1234',
        'HOST': '127.0.0.1',
        'PORT': '5220',
    }
}

and when I run the server i got this error : Error loading MySQLdb module: No module named 'MySQLdb'
 I'm using python 3.5 and django 1.9

A: Installing  MySQL-python should work.
pip install MySQL-python

A: When i got this error, it went away with:
Sudo apt-get install libmysqlclient-dev

Sudo apt-get install python3.5-dev

pip install mysqlclient

Edit:
To get it to work in my Windows development environment, i had to download mysqlclient from here
http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
and then used pip to install:
pip install c:\users\myself\mysqlclient-1.3.7-cp35-cp35m-win_amd64.whl


text:
Q: How can I check for the existence of UTF-16 filenames in Perl? I have a textfile encoded in UTF-16.  Each line contains a number of columns separated by tabs.  For those who care, the file is a playlist TXT export from iTunes.  Column #27 contains a filename.
I am reading it using Perl 5.8.8 in Linux using code similar to:
binmode STDIN, ":encoding(UTF-16)";
while(<>)
{
    chomp;
    my @cols = split /\t/, $_;
    my $filename = $cols[26];   # Column #27 contains the filename
    print "File exists!" if (-e "$filename");
}

(Please note: I've shortened this code snippet.  In my actual code I do some substitutions to convert the absolute windows filename used by iTunes into a filename valid on my Linux box)
Even though the files exist, the (-e) file test does not return true.  I believe it has something to do with the string being in UTF-16 but cannot figure out what the problem is.  The actual filename uses only ASCII characters.  And the filename prints correctly if I print the $filename variable.
Can filenames in Perl be in UTF16?  Any ideas how to get this code snippet to work?

A: The UTF-16 text is processed by the :encoding layer.  By the time it gets into $_, there's no way to tell that it was ever UTF-16.  I don't think that's your issue.
My guess would be that you've either got some whitespace in your filename (that you didn't notice when you tried printing it out) or you're not in the directory you think you are.
Try
if (-e $filename) { print "File exists!" }
else { print "File <$filename> not found" }

and check the filename carefully.  You might also use Cwd; and print out the current directory.

A: I figured out the solution:
Column 27 is the last column, and the file is encoded with 0d0a (\r\n) line endings.  chomp was only removing 0a (\n).  Not sure why I didn't see this before, but it doesn't have anything to do with UTF16.
Adding:
s/\r$//;

after chomp fixes the problem.
Thanks for your help - sorry to send you down a rabbit trail.

A: If, as you say, the actual filename uses only ASCII characters, wouldn't
$filename =~ s/\0//g;

work? Anyway, xxd should help the next time you run into something like this

[sinan@archardy ~]$ xxd /mnt/c/Documents\ and\ Settings/sinan/Desktop/test.txt
0000000: fffe 2f00 6800 6f00 6d00 6500 2f00 7300  ../.h.o.m.e./.s.
0000010: 6900 6e00 6100 6e00 2f00 7400 6500 7300  i.n.a.n./.t.e.s.
0000020: 7400 6d00 6500 2e00 7400 7800 7400 0d00  t.m.e...t.x.t...
0000030: 0a00                                     ..

I see that you have solved your problem in the time it took me to create a test file and reboot into Linux. Oh well.


text:
Q: Best data combination to ensure web user uniqueness? How to ensure that the anonymous web users that voting using your poll-system are unique (each anonymous user votes for once only)?
I can think of:
 1. Client's IP Address
 2. Client's Machine Name
 3. MAC Address
 4. Storing cookie
As far as I know, you cant get (2) & (3) in web development, and (4) is not guaranteed since user can delete/not allow cookies
what do you think is better to achieve uniqueness?

A: The only safe way to achieve uniqueness is to have users to log in.
Using only IP is not good enough as IP can be messed with and there may be several users behind the same IP
Even MAC address can be easily changed (there are freeware tools for it)
Cookies are obviously not very reliable

A: I think only a log in system with external (non IT, human system) based authentication would give a very high level of certainty e.g. to support voting for government but for lessor purposes consider browser uniqueness
Web Browsers Leave 'Fingerprints' Behind as You Surf the Net
Browser Fingerprinting Can ID You Without Cookies

A: To comment on you ideas:
1) IP adress may be shared between lot of users (for example my IP adress is same for whole block of flats...), which can be an issue
2,3) yes, probably not possible without some browser extensions or other stuff like that
4) cookies can be deleted, but some sort of third party cookies (via iframe for example) may be simple kind-of-solution, because user may not look for it in cookie list... If I want to vote on example.com, I probably would not look for cookie from example2.com... I hope I made  myself clear how I mean this.
And I would add browser agent string as number 5.
But other answers are correct that registration with mailing confirmation code through post or something is likely only "safe" solution. But your question was for anonymous so...
Definitely it is NOT possible to be 100% sure that user is unique...


text:
Q: How to wait for multiple useLazyQuery in react-apollo I have a gql query MY_Q
and have a list of the data items, like data_list = [data1, data2]
how to group multiple useLazyQuery() on each data item and wait until all the query has finished before processing the data.
similar to Promise.all().
example:-
Promise.all (data_list.map((e) => useLazyQuery(MY_Q , { variables : { data :
e}}))).then ((res) {
 //process result.
})

A: I wouldn't use promises because you will want what the hooks returns in your React component won't you?
Just define the hook for each separate query and then render based on what is returned so far.  When everything is fetched render that, if not, render a loading view in the component.

function SomeComponent () {
  const [fetchInitial, {data, fetchMore}] = useLazyQuery(QUERY, {
    variables: {
      dataSets: [
        dataSet1,
        dataSet2
      ]
    }
  });

}


text:
Q: How to check if User is inside the VPN Is there a way to find out if a web user is inside the company VPN?? i need to check automatically if the user is inside the company VPN. Is there a way to do this throgh a website?
I know i can't use java-script to ping some service inside VPN, because i can't ping to a service outside of the current domain for browser security reasons.
So, how can i automatically check if the user is inside the VPN using a Web Page?
EDIT: is it possible to use an image tag to try to load an image form a server inside the VPN? If the image does not load, it means the user is not in the VPN. Is this suitable?

A: It so many Methods to be a vpn, so it is hard to tell a way to differentiate it.
I suggest you can set a independent subnet for VPN and VPN users that check the client IP, and you will sure if they came from VPN or not.
It's in common use I think. try :)


text:
Q: Parsing Facebook Fan Page's RSS Feed: How to forge headers I am attempting to pull the RSS 2.0 feed for a Facebook Fan page from within PHP.
When I access the feed from the browser, no problems. But, when I attempt to pull and use in PHP, Facebook returns code to redirect to a "Upgrade Your Browser" notice. The same happens when I attempt to validate the feed using W3C RSS validator.
So, Facebook must have some logic in place that analyzes the user agent and either delivers the feed, or the "you must update" page.
The question is: how do I get access to that RSS feed from within PHP?
Can I forge user agent headers directly when using SimpleXML or DOMdocument? I know there is an option to pull the feed using CURL (where the headers can be easily set), but I'd prefer not to do so.
Any ideas are welcome!

A: Well for those that might also be curious, ini_set() seems to be one solution.
<?php

ini_set('user_agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0');

$url = 'https://www.facebook.com/feeds/page.php?format=rss20&id={your-page-id}';
$xml = simplexml_load_file( $url );
foreach($xml->channel->item as $status){
    // Do something for each News Feed update
}

Although, when Zuckberberg feels like updating user agent requirements, who knows whether this will validate.


text:
Q: Reading Strings with Undefined Length in C first(as always) I want to apologize about my english, it may not be clear enough.
I'm not that good at C programming, and I was asked to read a "string" input with undefined length.
This is my solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *newChar();
char *addChar(char *, char);
char *readLine(void);

int main() {
  char *palabra;
  palabra = newChar();

  palabra = readLine();
  printf("palabra=%s\n", palabra);

  return 0;
}

char *newChar() {
  char *list = (char *) malloc(0 * sizeof (char));
  *list = '\0';
  return list;
}

char *addChar(char *lst, char num) {
  int largo = strlen(lst) + 1;
  realloc(&lst, largo * sizeof (char));
  *(lst + (largo - 1)) = num;
  *(lst + largo) = '\0';
  return lst;
}

char *readLine() {
  char c;
  char *palabra = newChar();

  c = getchar();
  while (c != '\n') {
    if (c != '\n') {
      palabra = addChar(palabra, c);
    }
    c = getchar();
  }
  return palabra;
}

Please, I'd appreciate that you help me by telling me if it's a good idea or giving me some other idea(and also telling me if it's a "correct" use for pointers).
Thanks in advance

EDIT: Well, thanks for you answers,they were very useful. Now I post edited(and I hope better) code, maybe could be useful for someone new to C(like me) and be feedbacked again.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reChar(char **, int *);
void readLine(char **, int *);

int main() {
    char *palabra = NULL;
    int largo = 0;

    reChar(&palabra, &largo);
    readLine(&palabra, &largo);
    printf("palabra=%s\n", palabra, largo);

    system("pause");
    return 0;
}

void reChar(char **lst, int *largo) {
    (*largo) += 4;
    char *temp = (char*) realloc(*lst, (*largo) * sizeof (char));

    if (temp != NULL) {
        *lst = temp;
    } else {
        free(*lst);
        puts("error (re)allocating memory");
        exit(1);
    }
}

void readLine(char **lst, int *largo) {
    int c;
    int pos = 0;

    c = getchar();
    while (c != '\n' && c != EOF) {
        if ((pos + 1) % 4 == 0) {
            reChar(lst, largo);
        }
        (*lst)[pos] =(char) c;
        pos++;
        c = getchar();
    }
    (*lst)[pos] = '\0';
}

PS:

*

*It seem enough to slow increase size of "palabra".

*I'm not sure if capture getchar() into a int and then cast it into a char is the correct way to hadle EOF pitfall

A: *

*You are always allocating one byte less than you are using. For example in the beginning you allocate space for zero characters and then try to set the (non-existing) first character to '\0'.

*realloc doesn't take a pointer to a pointer as first parameter. It's supposed to be used like this:
lst = realloc(lst, largo * sizeof (char));

*If you want to handle out-of-memory conditions you would have to check if malloc() or realloc() returned NULL.

*It would be more efficient to allocate a bigger buffer in the beginning and increase it in bigger steps instead of reallocating every added character separately.

A: *

*Look up the definition of POSIX getline().

*Remember that you need to capture the return value from realloc(); it is not guaranteed that the new memory block starts at the same position as the old one.

*Know that malloc(0) may return a null pointer, or it may return a non-null pointer that is unusable (because it points to zero bytes of memory).

*You may not write '*list = '\0'; when list points to zero bytes of allocated memory; you don't have permission to write there.  If you get a NULL back, you are likely to get a core dump.  In any case, you are invoking undefined behaviour, which is 'A Bad Idea™'. (Thanks)

*The palabra = newChar(); in main() leaks memory - assuming that you fix the other problems already discussed.

*The code in readLine() doesn't consider the possibility of getting EOF before getting a newline; that is bad and will result in a core dump when memory allocation (finally) fails.

*Your code will exhibit poor performance because it allocates one character at a time.  Typically, you should allocate considerably more than one extra character at a time; starting with an initial allocation of perhaps 4 bytes and doubling the allocation each time you need more space might be better.  Keep the initial allocation small so that the reallocation code is properly tested.

*The return value from getchar() is an int, not a char.  On most machines, it can return 256 different positive character values (even if char is a signed type) and a separate value, EOF, that is distinct from all the char values.  (The standard allows it to return more than 256 different characters if the machine has bytes that are bigger than 8 bits each.) (Thanks)  The C99 standard §7.19.7.1 says of fgetc():

If the end-of-file indicator for the input stream pointed to by stream is not set and a
  next character is present, the fgetc function obtains that character as an unsigned
  char converted to an int and advances the associated file position indicator for the
  stream (if defined).

(Emphasis added.)  It defines getchar() in terms of getc(), and it defines getc() in terms of fgetc().

*(Borrowed: Thanks).  The first argument to realloc() is the pointer to the start of the currently allocated memory, not a pointer to the pointer to the start of the currently allocated memory.  If you didn't get a compilation warning from it, you are not compiling with enough warnings set on your compiler.  You should turn up the warnings to the maximum.  You should heed the compiler warnings - they are normally indicative of bugs in your code, especially while you are still learning the language.

*It is often easier to keep the string without a null terminator until you know you have reached the end of the line (or end of input).  When there are no more characters to be read (for the time being), then append the null so that the string is properly terminated before it is returned.  These functions do not need the string properly terminate while they are reading, as long as you keep track of where you are in the string.  Do make sure you have enough room at all times to add the NUL '\0' to the end of the string, though.
See Kernighan & Pike 'The Practice of Programming' for a lot of relevant discussions.  I also think Maguire 'Writing Solid Code' has relevant advice to offer, for all it is somewhat dated.  However, you should be aware that there are those who excoriate the book.  Consequently, I recommend TPOP over WSC (but Amazon has WSC available from $0.01 + p&p, whereas TPOP starts at $20.00 + p&p -- this may be the market speaking).

TPOP was previously at
http://plan9.bell-labs.com/cm/cs/tpop and
http://cm.bell-labs.com/cm/cs/tpop but both are now (2015-08-10) broken.
See also Wikipedia on TPOP.

A: The first argument to the call to realloc in
realloc(&lst, largo * sizeof (char));

should be lst and not &lst
Also the pointer returned by realloc need not always be same as its first argument. If no free memory adjacent to the existing memory is found, a completely different chunk is allocated and its address is returned.
char *new_lst = realloc(lst, largo * sizeof (char));
if(new_lst != NULL) {
  lst = new_lst;
}

A: Apart from the errors in your code, I think it is better to create a variable-length string in C. Once you have that, you can write a getLine() function. This variable-length string includes the concept of capacity, so its size increases in blocks of powers of 2, instead one by one.
#include <string.h>
#include <stdio.h>

typedef struct _mystring {
    char * native;
    size_t size;
    size_t capacity;
} String;

size_t String__len(String this)
{
    return this.size;
}

String String__create(char native[], size_t capacity) {
  String this;

  this.size = strlen( native );
  if ( capacity < ( this.size + 1 ) )
        this.capacity = this.size + 1;
  else  this.capacity = capacity;

  this.native = (char *) malloc( capacity * sizeof( char ) );
  strcpy( this.native, native );

  return this;
}

String * String__set(String *this, char native[]) {
    this->size = strlen( native );

    if ( this->size >= this->capacity ) {
        do {
            this->capacity <<= 1;
        } while( this->size > this->capacity );

        this->native = realloc( this->native, this->capacity );
    }

    strcpy( this->native, native );

    return this;
}

String * String__add(String *this, char ch) {
    ++( this->size );

    if ( this->size >= this->capacity ) {
        do {
            this->capacity <<= 1;
        } while( this->size > this->capacity );

        this->native = realloc( this->native, this->capacity );
    }

    char * zeroPos = this->native + ( this->size -1 );
    *( zeroPos++ ) = ch;
    *zeroPos = 0;

    return this;
}

void String__delete(String *this)
{
    free( this->native );
}

Once you have this implementation done, which is useful for this problem and many others, you can create the getLine function:
String String__getLine()
{
    int ch;
    String this = String__create( "", 16 );

    do {
        ch = fgetc( stdin );
        String__add( &this, ch );
    } while( ch != EOF
          && ch != '\n' );

    size_t len = String__len( this );
    this.size = len -1;
    *( this.native + this.size ) = 0;

    return this;
}

Now you can just use it:
int main()
{
    printf( "Enter string: " );
    String str = String__getLine();
    printf( "You entered: '%s'\n", str.native );
    String__delete( &str );

    return EXIT_SUCCESS;
}

A: Here a working example for realloc and fgets. Its C89, no POSIX needed. You can set the parameter with your own preallocated memory or NULL. A terminating "free" is always needed.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char *getstringStdin(char *s)
{
  char buffer[9];
  s=realloc(s,1);
  *s=0;
  while( fgets(buffer,9,stdin) )
  {
    s=realloc(s,strlen(s)+1+strlen(buffer));
    strcat(s,buffer);
    if( strchr(s,'\n') )
    {
      *strchr(s,'\n')=0;
      break;
    }
  }
  return s;
}

main()
{
  char *s;
  while( *(s=getstringStdin(0)) ) /* a single Enter breaks */
  {
    puts(s);
    free(s);
  }
  free(s);
  puts("end");
  return 0;
}


text:
Q: How to print dynamic nesting data in the form of Bootstrap accordion(collapse) using php? Basically, I'm working on an E-learning project like udemy and I want to create a dynamic collapse for videos like the one udemy provides while scrolling course contents. I have linked the photos below:
so, All I have to do is, first create a section, then lecture and add video in that lecture. I want to loop over both at the same time, So I can get all the lectures of the lecture table and sections of section table and print them accordingly which tells us, which lecture is linked to which section.
What I expected:

This image has Introduction Section and within it, Welcome to the course
  lecture and video in that lecture.

https://www.picturepaste.ca/image/Hkc16
What I got:
https://www.picturepaste.ca/image/HkDmY
S.O doesn't allow me to upload pics, so I linked it anyway..
I have four tables in database:
1.Courses - For courses
2.Section - For adding Section to the Courses
3.Lecture - For adding lecture to the Section
4.Videos - For adding videos to lecture
Table Structure

Section Table

id    name              course_id
9    Getting Started     6
11   HTML                6
12   CSS                 6

Lecture Table

id  lecture_name            course_id  section_id
1   How to Learn               7           2
3   HTML TABLE                 6           11
4   Getting Started to CSS     6           12

Here's what I've tried so far:

 <?php $id = trim($_POST['id']);  ?>

       <?php
        $sctmt = $conn->prepare("SELECT id, name FROM section WHERE course_id = ? ");
        $sctmt->bind_param('s', $id);
        $sctmt->execute();
        $sctmt->store_result();
        $sctmt->bind_result( $section_id, $section);
        while ($sctmt->fetch()) {
           $section_ids[] = $section_id;
           $sections[] = $section;
       }
        $sctmt->close();

        for($i = 0; $i < count($sections); $i++) {
          ?>

               <a class="row"  href="#accordionCurriculum_<?php echo $section_ids[$i] >"

                  data-toggle="collapse"
                   aria-expanded="true">

                     <?php echo $sections[$i] ?>

                                6 Lectures
                  20:20

       <div id="accordionCurriculum_<?php echo $section_ids[$i]; ?>"

           class="collapse show"
           data-parent="#accordionCurriculum">

           <?php
              foreach($section_ids as $section_id) {
                  $lecmt = $conn->prepare("SELECT section_id, lecture_name FROM lecture
                      WHERE course_id = ? && section_id = ?");
                  $lecmt->bind_param('ii', $id, $section_id);
                  $lecmt->execute();
                  $lecmt->bind_result($lecture_section_id, $lecture_name);
                  while ($lecmt->fetch()) {
                      echo $lecture_name;
                  }
              }
              $lecmt->close();
              ?>

           Preview

           00:36

  <?php
  }
?>


text:
Q: HTML Form Text onChange event refreshes page?

"use strict";

var SEED = "";

function seedSubmit() {
    var input_box = document.getElementById("seed-form");
    SEED = input_box.elements[0].value;
}
<form id="seed-form">

Seed:

    <input type="text" onchange="seedSubmit(); return false;">
    <input type="button" onclick="seedSubmit()" value="Submit">
</form>

Here's the HTML:
<form id="seed-form">

Seed:

    <input type="text" onchange="seedSubmit(); return false;">
    <input type="button" onclick="seedSubmit()" value="Submit">
</form>

Here's the JavaScript:
"use strict";

var SEED = "";

function seedSubmit() {
    var input_box = document.getElementById("seed-form");
    SEED = input_box.elements[0].value;
}

I then use the SEED variable for some other stuff. Basically you type into the box and press submit. If the submit button is type="submit", it refreshes the page so it has to be a type="button" then it works fine. But I don't want a button at all I wanna type in the text and press enter. But doing so refreshes the page. How do I prevent this? I did some googling and searching on this site and found a few posts but none of those solutions seemed to work, what am I doing wrong? People say try return false; but that doesn't work for me.

A: You can add eventListener to "submit" and use the preventDefault method, for example:

var SEED ="";
var form = document.getElementById("seed-form");
form.addEventListener("submit", function(event){
event.preventDefault();
var input_box = document.getElementById("seed-form");
    SEED = input_box.elements[0].value;
console.log(SEED);
});
<form id="seed-form">

Seed:

    <input type="text" >
    <input type="submit" value="Submit">
</form>


text:
Q: gridview is not showing data properly while trying to get data from https://blockchain.info/ticker in my grid view, i'm finding the result in single coloumn whether i want it in different coloumn.
i'm showing you my code and please give me a soloution.

public void ticker()
{
    WebClient webClient = new WebClient();

    dynamic result =webClient.DownloadString("https://blockchain.info/ticker");

    GridView1.DataSource = result;
    GridView1.DataBind();
}

[https://i.stack.imgur.com/nPjgS.jpg]

A: It looks like your results in JSON format so you have to convert in the proper format to display well in GridView.
import Newtonsoft.Json
dynamic result =JsonConvert.DeserializeObject(
webClient.DownloadString("https://blockchain.info/ticker"));

I hope it's help you, you can search more about it
thanks


text:
Q: Lower and upper bounds for number of ideals Let $b(r,s,q)$ denote the number of
two-sided ideals in $J^2/J^s \subseteq F_q \langle x_1,...,x_r\rangle/J^s$, where $A=F_q \langle x_1,...,x_r\rangle$ is the noncommutative polynomial ring in r variables over the finite field with q elements and $J=\langle x_1,...,x_r\rangle$ is the ideal generated by $x_1, ... , x_r$. (Motivation: one obtains exactly the admissible ideals of the quiver with one point and r loops by this)
Im searching for some interesting upper $c(r,s,q)$ and lower $a(r,s,q)$ bounds for $b(r,s,q)$, for example to see what might be realistic to obtain with a computer. So the goal is to give interesting inequalities of the form $a(r,s,q) \leq b(r,s,q) \leq c(r,s,q)$. You are also allowed to choose special values that might be interesting like r=2 and q=2 or 3 it that helps.
Might be fun if each post tries to improve the bounds of the previous post.
Let me start:
$a(r,s,q)=r^2+r^3+...+r^{s-1}$,by looking at the principal ideals generated by one term polynomials and $c(r,s,q)=2^{q^{r^2+r^3+...+r^{s-1}}}$, by looking at all possible subsets of the vector space $J^2/J^s$.
If you want you can also look at asymptotics or the commutative polynomial ring first.
In Algorithm for finding quiver algebras
r-algebras the question was about precise numbers.
In this thread Im interested in the easier questions of upper and lower bounds for those numbers.


text:
Q: React apply css classes dynamically I have two divs: .div-one and .div-two. Initially .div-one is a full width div. On a button click it reduces to 50% width and .div-two opens from right to left with webkit animation to occupy other 50% width. This animation is smooth. Again on button click .div-one is made to 100% width and .div-two. is made 0% width. There is so far animation for this.
My HTML:
<div className={`div-one ${!this.state.showRegistration && !this.state.showLogin ? 'full-width' : 'half-width'}`}>

<If condition={this.state.showRegistration}>

</If>

My CSS:
.div-one {
  background: url("../../../assets/images/manhattan-min.png") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;

  position: absolute;
  width: 100%;
  min-height: 500px;
  min-height: 100vh;

}

.div-one.half-width {
  -webkit-animation: right-to-left-div1 0.3s forwards;
  animation: right-to-left-div1 0.3s forwards;
}

.div-one.full-width{
  -webkit-animation: left-to-right-div1 0.3s forwards;
  animation: left-to-right-div1 0.3s forwards;
}

.div-two {
  position: relative;
  width: 50%;
  height: 100vh;
  background-color: #EEEEEE;
  -webkit-animation: right-to-left-div2 0.3s forwards;
  animation: right-to-left-div2 0.3s forwards;
}

@keyframes right-to-left-div1{
  to {
    width: 50%;
  }
}

@keyframes left-to-right-div1{
  to{
    width:100%
  }
}

@keyframes right-to-left-div2{
  from{left:100%}
  to{left:50%}
}
@keyframes left-to-right-div2{
  from{left:0%}
  to{left:50%}
}

Example ilustration:

How can I achieve the second animation i.e. .div-two reduces from 50% to 0% to the right and div-one expands from 50% to 100% ?

A: Well, here's an example. In short, I'd use css transitions, not keyframes for something as simple as this.

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {show: false}

    this.show = this.show.bind(this)
  }

  show() {
    this.setState(prevState => ({show: !prevState.show}))
  }

  render() {
    return (

          <button onClick={this.show}>{this.state.show ? 'hide' : 'show'}</button>

one

two

    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
body {
  margin: 0;
}

.wrapper {
  overflow: hidden;
  white-space: nowrap;
}

.one, .two {
  background: #333;
  border: 2px solid #787567;
  box-sizing: border-box;
  color: #fff;
  display: inline-block;
  font-family: arial;
  overflow: hidden;
  padding: 20px;
  text-align: center;
  transition: border 0.2s, padding 0.2s, width 0.2s;
}

.one {
  width: 100%;
}
.two {
  border-width: 2px 0;
  padding: 20px 0;
  width: 0;
}

.show .one, .show .two {
  border-width: 2px;
  padding: 20px;
  width: 50%;
}


text:
Q: New Relic Application concept I have New Relic installed in a VPS. I have a "default" PHP Application and New Relic is getting data from it, but what server name is it getting from? The VPS contains some subdomains, and the server appears as "domain.com" (so I guess it is getting data from this server name). But I want to get data from "subdomain.domain.com". How can I achieve it?
Edit:
Following @Taibhse link (http://docs.newrelic.com/docs/agents/php-agent/configuration/php-directory-ini-settings#api-calls) I tried:
1. Change Apache2 configuration:
Inside <Directory ...>:
<IfModule php5_module>
    php_value newrelic.appname "myDomain.com"
</IfModule>

Also tried without <IfModule ...>, but nothing seemed to change.
2. Using API:
Then, I've tried adding:
if (extension_loaded('newrelic')) {
    newrelic_set_appname($name);
}

to the index.php file of one domain.
And also without if (extension_loaded('newrelic')), but nothing changed again.
It seems like it's getting data from all VirtualHost.

A: I work for New Relic.
If I am following you correctly, You have a reporting application from "domain.com" and wish to get data from a subdomain also?
If you are using the same PHP environment on both domain and subdomain, the PHP agent should be collect data from both. If you wish to specify different applications to split the data, I suggesting using an API call.
http://docs.newrelic.com/docs/agents/php-agent/configuration/php-directory-ini-settings#api-calls
Add this code to your subdomain:
if (extension_loaded('newrelic')) {
newrelic_set_appname($name);
}

Edit: Adding virtual host specific instructions.
We have some specifics for Virtual hosts in Apache:
http://docs.newrelic.com/docs/agents/php-agent/configuration/php-directory-ini-settings#ini-apache
Within the VirtualHost tag, add:
<IfModule php5_module>
php_value newrelic.appname "Virtual Host 1"
</IfModule>

Once updated, you will need to restart Apache.
Let me know if you have any questions or need any further assistance.


text:
Q: Error 'Cannot Convert double to int' I have what seems to me as a weird issue with my code. I have a method that performs a simple query and returns the result. I'm trying to return the value as a double but I get an error:

CS0266    Cannot implicitly convert type 'double' to 'int'. An explicit
  conversion exists (are you missing a cast?)

I'm not trying to do any conversions so I don't understand what the issue is.
Here is the calling code:
  double displacement = sqLite.GetDisplacement( transItem.Item.Name );

and here is the code that is called:
public int GetDisplacement( string item )
{
    double dDisposition = 0;
    string sSql = "SELECT [Displacement] FROM [Items] WHERE [Name] = '" + item + "';";

    using ( var dbConnection = new SQLiteConnection( sConnectionString ) )
    {
        try
        {
            dbConnection.Open();
            SQLiteCommand cmd = new SQLiteCommand( sSql, dbConnection );
            object result = cmd.ExecuteScalar();

            dDisposition = Convert.ToDouble( result );

        }
        catch ( Exception e )
        {
            MessageBox.Show( "Error retreiving displacement information: " + e.ToString() );
        }

    }

    return dDisposition; // This is where I get the error

}

I'm not trying to convert anything, everything is declared as a double. I've tried to clean and rebuild the solution several times to no avail. What am I missing?

A: The method declaration states that an int value will be returned:
public int GetDisplacement (string item)

But on the code, the return statement is returning a variable of type double:
double dDisposition = 0;

// Your code here

return dDisposition;

You have to change one or the other, so basically change the return type:
public double GetDisplacement (string item)

Or the type of the dDisposition variable and the converter method:
int dDisposition = 0;

// Your code here
dDisposition = Convert.ToInt32(result);
// More of your code here

return dDisposition;


text:
Q: How to assign an object returned by an async function to a variable I have a function that scrapes a data from a website. THe function is this:
  const getSharesInfo = async () => {
      try {
        const { data } = await axios.get(url);
        const $ = cheerio.load(data);
        const elmSelector =
          "#ctl00_ContentPlaceHolder1_LiveTrading > table > tbody > tr";
        const keys = [
          "Name",
          "LTP",
          "% Change",
          "Open",
          "High",
          "Low",
          "Qty",
          "Close Price",
        ];
        $(elmSelector).each((parentIdx, parentElm) => {
          let keyIdx = 0;
          const sharesObj = {};
          $(parentElm)
            .children()
            .each((childIdx, childElm) => {
              const tdValue = $(childElm).text();
              if (tdValue) {
                sharesObj[keys[keyIdx]] = tdValue;
                keyIdx++;
              }
            });
          console.log(sharesObj);
          return sharesObj;
        });
      } catch (err) {
        console.error(err);
      }
    };

It makes an object from the data scraped. Then when I run the function it console log the shareObj and output is like this:
{
  Name: 'USLB',
  LTP: '890.00',
  '% Change': '0.79',
  Open: '890.00',
  High: '888.10',
  Low: '888.10',
  Qty: '24'
}
{
  Name: 'VLBS',
  LTP: '849.00',
  '% Change': '0',
  Open: '850.00',
  High: '833.00',
  Low: '834.00',
  Qty: '285'
}
{
  Name: 'WNLB',
  LTP: '927.30',
  '% Change': '-4.4',
  Open: '965.00',
  High: '927.30',
  Low: '965.00',
  Qty: '270'
}

I want to catch it and pass it to the home route. I have setup router like this.
app.get("/", async (req, res) => {
  const shares = await getSharesInfo();
  res.render("home", { shares });
});

But when I console log shares I get nothing. No errors no data nothing. It just prints some empty spaces. How can I solve this ??

A: Move the const sharesObj = {} declaration outside of the call to .each (= move it up 3 lines) and move the line return sharesObj; out of the .each loop, too (e. g.: move it down two lines).
As of now you create the constant binding inside .each and then return it inside the .each callback, not in getSharesInfo.
Example:
  const getSharesInfo = async () => {
  try {
    const { data } = await axios.get(url);
    const $ = cheerio.load(data);
    const elmSelector =
      "#ctl00_ContentPlaceHolder1_LiveTrading > table > tbody > tr";
    const keys = [
      "Name",
      "LTP",
      "% Change",
      "Open",
      "High",
      "Low",
      "Qty",
      "Close Price",
    ];
    const sharesObj = {}; // <-- new position
    $(elmSelector).each((parentIdx, parentElm) => {
      let keyIdx = 0;
      //const sharesObj = {}; <-- old position
      $(parentElm)
        .children()
        .each((childIdx, childElm) => {
          const tdValue = $(childElm).text();
          if (tdValue) {
            sharesObj[keys[keyIdx]] = tdValue;
            keyIdx++;
          }
        });
      console.log(sharesObj);
      //return sharesObj; <-- old position
    });
    return sharesObj; // <-- new position
  } catch (err) {
    console.error(err);
  }
};


text:
Q: Apache .htaccess rewrite all urls to https home page with exceptions that rewrite to https current page I am trying to rewrite ALL http://www.example.com/* urls to https://www.example.com/ except some pages. I can get the catch all rewrite to work no problem:
RewriteCond %{SERVER_PORT} 80
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

However, if I try to add the exceptions before the catch all home page forward, they do not work. Also, if I just try add them by themselves, (commenting out the previous rule), they do not work.
RewriteCond %{SERVER_PORT} 80
RewriteRule ^/?products/(.*) https://%{SERVER_NAME}/products/$1 [R,L]

So, there are a few pages on the site I want to have simple http->https rewrites.
If someone goes to http://.../products they should be forwarded to https://.../products for example.
Also, I want to make sure whatever rule I have works for www.example.com/products and example.com/products.

A: Replace with
RewriteCond %{SERVER_PORT} 80
RewriteRule ^products/(.*)$ https://%{SERVER_NAME}/products/$1 [R,L]


text:
Q: Sort Data in Mysql With Condition I Write the following python code but I have a problem. I need to set a condition for MySQL 'if two var in column height is equal display more width one upper':

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="data"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM data ORDER BY Height"

mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
    print(x[0],x[1],x[2],'\n')```

A: add the second condition for order  by
SELECT * FROM data ORDER BY Height, width

or
SELECT * FROM data ORDER BY Height, width DESC

for descending order of width with same height


text:
Q: Filtering based on subquery result I have mysql query and I want to filter based on gigcount when i use where clause ie where gigcount=0 I get error unknown column
SELECT
tbl_musicvenue.id AS id,

(SELECT

    COUNT(1)AS A1
    FROM
        smliveclaims AS Extent5
    WHERE
        Extent5.tbl_MusicVenueId = tbl_musicvenue.id and (Extent5.IsDeleted =0 or Extent5.IsDeleted is null)) AS gigcount

FROM

tbl_musicvenue

Is there any way to get all items where gigcount is 0

A: You can rewrite your query as
SELECT
a.id,
COUNT(b.tbl_MusicVenueId) gigcount
FROM
tbl_musicvenue a
LEFT JOIN smliveclaims b ON a.id = b.tbl_MusicVenueId AND (b.IsDeleted =0 OR b.IsDeleted IS NULL)
GROUP BY a.id
HAVING gigcount = 0

for your question to use gigcount in where clause, Where can be used for known column(s) of table(s) involved in query. In your case gigcount is an alias not a predefined column so you cannot access this in where clause. to filter on such columns use having clause


text:
Q: Print all possible paths in a labyrinth using recursive DFS This is the task: You are given a labyrinth, which consists of N x N squares, each of it can be passable or not. Passable cells consist of lower Latin letter between "a" and "z", and the non-passable – '#'. In one of the squares is Jack. It is marked with "*".
Two squares are neighbors, if they have common wall. At one step Jack can pass from one passable square to its neighboring passable square. When Jack passes through passable squares, he writes down the letters from each square. At each exit he gets a word. Write a program, which from a given labyrinth prints the words, which Jack gets from all the possible exits.
The input data is read from a text file named Labyrinth.in. At the first line in the file there is the number N (2 < N < 10). At each of the next N lines there are N characters, each of them is either Latin letter between "a" and "z" or "#" (impassable wall) or "*" (Jack). The output must be printed in the file Labyrinth.out.
Input:
6
a##km#
z#ada#
a*m###
#d####
rifid#
#d#d#t

So far I've done that :
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

public class Maze
{
    private const string InputFileName = "Labyrinth.in";
    private const string OutputFileName = "Labyrinth.out";
    StringBuilder path = new StringBuilder();

    public class Cell
    {
        public int Row { get; set; }
        public int Column { get; set; }

        public Cell(int row, int column)
        {
            this.Row = row;
            this.Column = column;
        }
    }

    private char[,] maze;
    private int size;
    private Cell startCell = null;

    public void ReadFromFile(string fileName)
    {
        using (StreamReader reader = new StreamReader(fileName))
        {
            // Read maze size and create maze
            this.size = int.Parse(reader.ReadLine());
            this.maze = new char[this.size, this.size];

            // Read the maze cells from the file
            for (int row = 0; row < this.size; row++)
            {
                string line = reader.ReadLine();
                for (int col = 0; col < this.size; col++)
                {
                    this.maze[row, col] = line[col];
                    if (line[col] == '*')
                    {
                        this.startCell = new Cell(row, col);
                    }
                }
            }
        }
    }

    public void FindAllPathsAndPrintThem()
    {
        if (this.startCell == null)
        {
            // Start cell is missing -> no path
            SaveResult(OutputFileName, "");
            return;
        }

        VisitCell(this.startCell.Row,
            this.startCell.Column, path);

        if (path.Length == 0)
        {
            // We didn't reach any cell at the maze border -> no path
            SaveResult(OutputFileName, "");
            return;
        }
    }

    private void VisitCell(int row, int column, StringBuilder path)
    {
        if (row < 0 || row > maze.GetLength(0) - 1 ||
            column < 0 || column > maze.GetLength(1) - 1)
        {
            SaveResult(OutputFileName, path.ToString());
            return;
        }

        if (this.maze[row, column] != 'x' && this.maze[row, column] != '#')
        {
            // The cell is free --> visit it
            if (this.maze[row, column] != '*')
            {
                path.Append(this.maze[row, column]);
                this.maze[row, column] = 'x';
            }
            VisitCell(row, column + 1, path);
            VisitCell(row, column - 1, path);
            VisitCell(row + 1, column, path);
            VisitCell(row - 1, column, path);
        }
    }

    public void SaveResult(string fileName, string result)
    {
        using (StreamWriter writer = new StreamWriter(fileName))
        {
            writer.WriteLine(result);
        }
    }

    static void Main()
    {
        Maze maze = new Maze();
        maze.ReadFromFile(InputFileName);
        maze.FindAllPathsAndPrintThem();
    }
}

Sorry for long question. There need to be a small bug but I don't get it where.
The output is madifiddrdzaadamk. Thanks in advance.

A: Here's a solution I came up with.  It keeps track of what cells have been visited during one go through the maze, but not for all attempts.  This can be done by making the function return an IEnumerable<string> that will represent the paths to an exit from the current point in the maze.  First check if you have gone off the edge of the maze and return nothing.  Then check if you're at a wall and if so no path is returned.  Otherwise you check if you are at the edge and if so you return the path that is represented by the current cell only.  Then you have to mark the current cell as visited, then attempt to find all paths in each of the 4 directions and concatenate the current cell to any that you find and yield them.  Then at the end you mark the cell as not visited so it can be used for other attempts.
private static IEnumerable<string> VisitCell(int row, int column, bool[,] visited)
{
    if (row < 0 || column < 0 || row >= maze.GetLength(0) || column >= maze.GetLength(1))
        yield break;

    if (maze[row, column] == '#' || visited[row, column])
        yield break;

    if (row == 0 || row == maze.GetLength(0) - 1 ||
        column == 0 || column == maze.GetLength(1) - 1)
    {
        yield return maze[row, column].ToString();
    }

    visited[row, column] = true;

    foreach (var path in VisitCell(row, column + 1, visited))
    {
        yield return maze[row, column] + path;
    }

    foreach(var path in VisitCell(row, column - 1, visited))
    {
        yield return maze[row, column] + path;
    }

    foreach (var path in VisitCell(row + 1, column, visited))
    {
        yield return maze[row, column] + path;
    }

    foreach (var path in VisitCell(row - 1, column, visited))
    {
        yield return maze[row, column] + path;
    }

    visited[row, column] = false;
}

Then you can run this code
private static char[,] maze =
{
    { 'a', '#', '#', 'k', 'm', '#' },
    { 'z', '#', 'a', 'd', 'a', '#' },
    { 'a', '*', 'm', '#', '#', '#' },
    { '#', 'd', '#', '#', '#', '#' },
    { 'r', 'i', 'f', 'i', 'd', '#' },
    { '#', 'd', '#', 'd', '#', 't' }
};

private static void Main(string[] args)
{
    foreach(var path in VisitCell(2, 1, new bool[6, 6]))
        Console.WriteLine(path);
}

to get this result

*madam
*madamk
*madk
*madkm
*a
*az
*aza
*difid
*dir
*did

You can tweak it to remove the star from the beginning of each path.

A: Here is the correct code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

public class Maze
{
    private const string InputFileName = "Labyrinth.in";
    private const string OutputFileName = "Labyrinth.out";

    public class Cell
    {
        public int Row { get; set; }
        public int Column { get; set; }

        public Cell(int row, int column)
        {
            this.Row = row;
            this.Column = column;
        }
    }

    private char[,] maze;
    private int size;
    private Cell startCell = null;

    public void ReadFromFile(string fileName)
    {
        using (StreamReader reader = new StreamReader(fileName))
        {
            // Read maze size and create maze
            this.size = int.Parse(reader.ReadLine());
            this.maze = new char[this.size, this.size];

            // Read the maze cells from the file
            for (int row = 0; row < this.size; row++)
            {
                string line = reader.ReadLine();
                for (int col = 0; col < this.size; col++)
                {
                    this.maze[row, col] = line[col];
                    if (line[col] == '*')
                    {
                        this.startCell = new Cell(row, col);
                    }
                }
            }
        }
    }

    public void FindAllPathsAndPrintThem()
    {
        if (this.startCell == null)
        {
            // Start cell is missing -> no path
            SaveResult(OutputFileName, "");
            return;
        }

        VisitCell(this.startCell.Row,
            this.startCell.Column, "");
    }

    private void VisitCell(int row, int column, string path)
    {
        if (row < 0 || column < 0 || row >= maze.GetLength(0) || column >= maze.GetLength(1))
        {
            return;
        }
        if (row < 0 || row > maze.GetLength(0) - 1 ||
            column < 0 || column > maze.GetLength(1) - 1)
        {
            SaveResult(OutputFileName, path);
            return;
        }

        if (this.maze[row, column] != '#')
        {
            // The cell is free --> visit it
            char x = this.maze[row, column];
            this.maze[row, column] = '#';
            VisitCell(row, column + 1, path + x);
            VisitCell(row, column - 1, path + x);
            VisitCell(row + 1, column, path + x);
            VisitCell(row - 1, column, path + x);
            this.maze[row, column] = x;
        }
    }

    public void SaveResult(string fileName, string result)
    {
        using (StreamWriter writer = new StreamWriter(fileName, true))
        {
            writer.WriteLine(result);
        }
    }

    static void Main()
    {
        Maze maze = new Maze();
        maze.ReadFromFile(InputFileName);
        maze.FindAllPathsAndPrintThem();
    }
}

The comments on the question where correct I was modifying the string, so now it works, the string is not modified in process.


text:
Q: Design Pattern for different interfaces I've a question regarding the design patterns. I appreciate any kind of help.
I implemented the follwing interfaces and classes:
IType : has no methods because the implemented classes have different datatypes and different parameters.
public interface IType extends IType_1, IType_2 {}

IType_1
public interface IType_1 {
      public List<Object1> getDataType_1(List<String> list1, List<String> list2);   }

Strategy_1
public class Strategy_1 implements IType_1(List<String> list1, List<String> list2) {

@Override
public List<Object1> getDataType_1() {
    return object1;
}   }

IType_2
public interface IType_2 {
      public List<Object2> getDataType_2(List<Object2> obj);   }

Strategy_2
public class Strategy_2 implements IType_2(List<Object2> obj) {

@Override
public List<Object2> getDataType_2() {
    return object2;
}   }

I tried to create the strategies by
Strategy
public class Strategy {

public Strategy() {}

public IType createStrategy(int strategyNo) {
    IType strategy = null;
    switch(strategyNo) {
    case 1:
        strategy = (IType) new Strateg_1();
    case 2:
        strategy = (IType) new Strateg_2();
    }
    return strategy;
}    }

... but it dosn't work.
The Strategies are not created when I run the class Strategy().
I get I an exception evertime I run the program.
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
The method getDataType_1(List<String>, List<String>) is undefined for the type IType

The problem is IType extends IType_1 and IType_2. So the object Strategy doesn't really knows IType. And I don't know how to solve it to make Strategy knows IType.
What I want to achieve is to create Strategy_1 or Strategy_2 when I need it. After the Stategy is created I want to use its methods.
Thank you very much.

A: Your problem is that is Strateg_1 is NOT a IType
IType is a IType_1, but IType_1 is NOT an IType
IType is a IType_2, but IType_2 is NOT an IType
You could do instead :
public interface IType_1 extends IType {....}

public interface IType_2 extends IType {....}

A: *

*this is not working,  what error have you got?

*have a look here:
public class Strategy_1 implements IType_1(List<String> list1, List<String> list2)
this line is invalid because this (List<String> list1, List<String> list2) should not be there

*you can't cast Strateg_1 to IType as Strateg_1 does not implements it
i suggest you to get rid of IType_1 and IType_2  if possible, and have interface
public interface IType<OBJECT> {
    public List<OBJECT> getDataType(List<String> list1, List<String> list2);
 }

and implementantations
public class Strategy_1 implements IType<Object1>{
...
}

public class Strategy_2 implements IType<Object2>{
...
}


text:
Q: SQL COUNT by each date with multiple date fields I have the following table and query which is not giving the correct result.
JOB table have Open, Finished and Closed dates.
Now I need to pull the count of Open, Finished and Closed Jobs between on the selected dates group by each dates and Location.
Please help me to get the result like in below expected result
+-------+-----------+------------+-----------+----------+
| JOB_id| DateOpen  | DateFinish | DateClose | Location |
+-------+-----------+------------+-----------+----------+
|   100 | 16-Dec-18 | 18-Dec-18  | 19-Dec-18 | A        |
|   101 | 16-Dec-18 | 18-Dec-18  | 19-Dec-18 | A        |
|   102 | 17-Dec-18 | 19-Dec-18  | 20-Dec-18 | C        |
|   103 | 10-Dec-18 | 11-Dec-18  | 16-Dec-18 | D        |
|   104 | 17-Dec-18 | 19-Dec-18  | 18-Dec-18 | E        |
+-------+-----------+------------+-----------+----------+

Query:
SELECT count(DateOpen) as Opened,
       count(DateFinish) as Finised,
      count(DateClose) as Closed,
      (DateOpen) as Date
FROM JOBS
WHERE DateOpen BETWEEN '12/16/2018' AND DATEADD(DAY, 1, '12/17/2018')
group by DateOpen

Expected Result:
+-----------+------+----------+--------+----------+
|   Date    | Open | Finished | Closed | Location |
+-----------+------+----------+--------+----------+
| 16-Dec-18 |    2 |        0 |      0 | A        |
| 16-Dec-18 |    0 |        0 |      1 | D        |
| 17-Dec-18 |    1 |        0 |      0 | C        |
| 17-Dec-18 |    1 |        0 |      0 | E        |
+-----------+------+----------+--------+----------+

A: You could pull all open, finish and closed dates in a single column and left join your jobs table with it:
DECLARE @date1 AS DATE = '2018-12-16';
DECLARE @date2 AS DATE = '2018-12-17';

WITH dates(date) AS (
    SELECT DateOpen FROM jobs
    UNION
    SELECT DateFinish FROM jobs
    UNION
    SELECT DateClose FROM jobs
)
SELECT dates.date
     , Location
     , COUNT(CASE WHEN dates.date = DateOpen THEN 1 END) AS Opened
     , COUNT(CASE WHEN dates.date = DateFinish THEN 1 END) AS Finished
     , COUNT(CASE WHEN dates.date = DateClose THEN 1 END) AS Closed
FROM dates
LEFT JOIN jobs ON dates.date IN (DateOpen, DateFinish, DateClose)
WHERE dates.date BETWEEN @date1 AND @date2
GROUP BY dates.date
       , Location

Result:
| date       | Location | Opened | Finished | Closed |
|------------|----------|--------|----------|--------|
| 16/12/2018 | A        | 2      | 0        | 0      |
| 16/12/2018 | D        | 0      | 0        | 1      |
| 17/12/2018 | C        | 1      | 0        | 0      |
| 17/12/2018 | E        | 1      | 0        | 0      |

Demo on DB Fiddle

A: You can use below query for the desired result set.
select coalesce(t1.date, t2.date, t3.date) as date, t1.Opened, t2.Finished, t3.Closed,
coalesce(t1.location, t2.location, t3.location) as location
from
(SELECT Convert(date,DateOpen) as Date ,count(JobID) as Opened, location
FROM JOBS
WHERE DateOpen BETWEEN '12/16/2018' AND DATEADD(DAY, 1, '12/17/2018')
group by Convert(date,DateOpen), location
) t1
Full join
(SELECT Convert(date,DateFinish) as Date ,count(JobID) as Finished, location
FROM JOBS
WHERE DateFinish BETWEEN '12/16/2018' AND DATEADD(DAY, 1, '12/17/2018')
group by Convert(date,DateFinish), location
) t2  ON(t1.date = t2.date and t1.location = t2.location)
FULL JOIN
(SELECT Convert(date,DateClose) as Date ,count(JobID) as Closed, location
FROM JOBS
WHERE DateClose BETWEEN '12/16/2018' AND DATEADD(DAY, 1, '12/17/2018')
group by Convert(date,DateClose), location
) t3  ON(t2.date = t3.date and t2.location = t3.location)

A: First, I would recommend you to stop storing dates as text and use proper data types.
To do what you need, make a list of all dates and locations by selecting each of the dates columns and location and union them into one result (first cte - allDates). Then we need a distinct list (second cte - aggregated) to select from, and count the number of rows from your table that match the current date/location values.
Here is the whole solution:
declare @JOBS table(JOB_ID int, DateOpen varchar(10), DateFinish varchar(10), DateClose varchar(10), Location varchar(5))
insert into @JOBS values
(   100, '16-Dec-18', '18-Dec-18', '19-Dec-18', 'A'),
(   101, '16-Dec-18', '18-Dec-18', '19-Dec-18', 'A'),
(   102, '17-Dec-18', '19-Dec-18', '20-Dec-18', 'C'),
(   103, '10-Dec-18', '11-Dec-18', '16-Dec-18', 'D'),
(   104, '17-Dec-18', '19-Dec-18', '18-Dec-18', 'E')

;with allDates as (
select convert(date, DateOpen) as [Date], Location from @JOBS
union
select convert(date, DateFinish), Location from @JOBS
union
select convert(date, DateClose), Location from @JOBS
),
aggregated as (
    select [Date], Location
    from allDates
    group by [Date], Location
)
select
    a.Date
    , (select count(*) from @JOBS where a.[Date] = DateOpen and a.Location = Location) [Open]
    , (select count(*) from @JOBS where a.[Date] = DateFinish and a.Location = Location) Finished
    , (select count(*) from @JOBS where a.[Date] = DateClose and a.Location = Location) Closed
    , Location
from aggregated a
where a.Date between '20181216' and '20181217'

A: You can use a case statement with sum,
    SELECT  Convert(date,DateOpen) as Date ,
           sum(case when DateOpen =DateOpen then 1 else 0 end) as Opened,
           sum(case when DateFinish=DateOpen then 1 else 0 end) as Finised,
           sum(case when DateClose=DateOpen then 1 else 0 end) as Closed,
           Location

    FROM JOBS
    WHERE DateOpen BETWEEN '12/16/2018' AND DATEADD(DAY, 1, '12/17/2018')
    group by Convert(date,DateOpen),Location

    UNION

    SELECT  Convert(date,DateClose) as Date ,
           sum(case when DateOpen =DateClose then 1 else 0 end) as Opened,
           sum(case when DateFinish=DateClose then 1 else 0 end) as Finised,
           sum(case when DateClose=DateClose then 1 else 0 end) as Closed,
           Location

    FROM JOBS
    WHERE DateClose BETWEEN '12/16/2018' AND DATEADD(DAY, 1, '12/16/2018')
    group by Convert(date,DateClose),Location

A: You can try the following code, using SUM function that sums the state of processes on inputed dates:
SELECT Convert(date1,DateOpen) as Date,
       sum(case
            when DateOpen = Convert(date1,DateOpen) then 1
            else 0
           end) as Open,
       sum(case
            when DateFinish = Convert(date1,DateOpen) then 1
            else 0
           end) as Finished,
      sum(case
            when DateClose = Convert(date1,DateOpen) then 1
            else 0
           end) as Closed,
      Location
FROM JOBS
group by Location
UNION ALL
SELECT Convert(date2,DateOpen) as Date,
       sum(case
            when DateOpen = Convert(date2,DateOpen) then 1
            else 0
           end) as Open,
       sum(case
            when DateFinish = Convert(date2,DateOpen) then 1
            else 0
           end) as Finished,
      sum(case
            when DateClose = Convert(date2,DateOpen) then 1
            else 0
           end) as Closed,
      Location
FROM JOBS
group by Location;

EDITED: date1 and date2 are input parameters.

A: DECLARE @startDate DATETIME = '12/16/2018'
DECLARE @endDate DATETIME = '12/17/2018'

SELECT
  count(CASE when DateOpen BETWEEN @startDate AND @endDate THEN 1 end) as Opened,
  count(CASE when DateFinish BETWEEN @startDate AND @endDate THEN 1 end) as Finised,
  count(CASE when DateClose BETWEEN @startDate AND @endDate THEN 1 end) as Closed,
  DateOpen as Date,
  Location
FROM JOBS
WHERE DateOpen BETWEEN @startDate AND @endDate
group by DateOpen, Location

A: You can give it a try using unpivot to see how the performance is
with cols_to_rows
  as (
      select *
        from t
      unpivot(col for val in (dateopen,datefinish,dateclose))m
      )
select col
       ,location
       ,count(case when val='dateopen' then 1 end)   as open1
       ,count(case when val='datefinish' then 1 end) as finish
       ,count(case when val='dateclose' then 1 end)  as close1
  from cols_to_rows
where col between cast('2018-12-16' as date)
  and cast('2018-12-17' as date)
group by col,location,val
order by col,location

| 10/12/2018 00:00:00 | D | 1 | 0 | 0 |
| 11/12/2018 00:00:00 | D | 0 | 1 | 0 |
| 16/12/2018 00:00:00 | A | 2 | 0 | 0 |
| 16/12/2018 00:00:00 | D | 0 | 0 | 1 |
| 17/12/2018 00:00:00 | C | 1 | 0 | 0 |
| 17/12/2018 00:00:00 | E | 1 | 0 | 0 |
| 18/12/2018 00:00:00 | A | 0 | 2 | 0 |
| 18/12/2018 00:00:00 | E | 0 | 0 | 1 |
| 19/12/2018 00:00:00 | A | 0 | 0 | 2 |
| 19/12/2018 00:00:00 | C | 0 | 1 | 0 |
| 19/12/2018 00:00:00 | E | 0 | 1 | 0 |
| 20/12/2018 00:00:00 | C | 0 | 0 | 1 |

Here is a dbfiddle link
https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=1ca0c0180a4d31d6e112e9f3b1b99715

A: Try this:
    DECLARE @MinDate DATE = '12/16/2018',
            @MaxDate DATE = '12/17/2018'

    DECLARE @DateTable TABLE (DateOpen DATETIME)

    INSERT INTO @DateTable
    SELECT  TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
            Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
    FROM    sys.all_objects a
            CROSS JOIN sys.all_objects b;

    ;with cte
    As
    (
        SELECT DISTINCT d.DateOpen,
        SUM(CASE WHEN j.DateOpen =d.DateOpen THEN 1 ELSE 0 END) OVER(partition by d.DateOpen,Location) As [Open]
        ,SUM(CASE WHEN j.DateFinish =d.DateOpen THEN 1 ELSE 0 END) OVER(partition by d.DateOpen,Location) As [Finished]
        ,SUM(CASE WHEN j.DateClose =d.DateOpen THEN 1 ELSE 0 END) OVER(partition by d.DateOpen,Location) As [Closed]
        ,Location
        FROM @DateTable d
        CROSS JOIN JOBS j
    )

    Select * from cte where [Open]>0 or Finished>0 or Closed>0
    Order by DateOpen,Location

A: Try this one
WITH CTE AS
(
SELECT *
FROM
(
SELECT Location
FROM T
GROUP BY Location
) L CROSS APPLY
(
  SELECT DateOpen
  FROM T
  WHERE DateOpen BETWEEN '2018-12-16' AND '2018-12-18'
) D
GROUP BY Location, DateOpen
),
 F AS
(
SELECT *,
       (SELECT COUNT(1) FROM T WHERE Location = CTE.Location AND DateOpen = CTE.DateOpen) [Open],
       (SELECT COUNT(1) FROM T WHERE Location = CTE.Location AND DateFinish = CTE.DateOpen)[Finish],
       (SELECT COUNT(1) FROM T WHERE Location = CTE.Location AND DateClose = CTE.DateOpen) [Close]
FROM CTE
)
SELECT DateOpen,
       [Open],
       [Finish],
       [Close],
       Location
FROM F
WHERE [Open] > 0
      OR
      [Finish] > 0
      OR
      [Close] > 0
ORDER BY DateOpen

Returns:
+---------------------+------+--------+-------+----------+
|      DateOpen       | Open | Finish | Close | Location |
+---------------------+------+--------+-------+----------+
| 16/12/2018 00:00:00 |    2 |      0 |     0 | A        |
| 16/12/2018 00:00:00 |    0 |      0 |     1 | D        |
| 17/12/2018 00:00:00 |    1 |      0 |     0 | C        |
| 17/12/2018 00:00:00 |    1 |      0 |     0 | E        |
+---------------------+------+--------+-------+----------+

Demo