问:
Tarjan algorithm, recursion mistakes
I'm trying to implement the Tarjan's algorithm (to find strongly connected components in a graph).

I'm stuck in the dfs part of the algorithm where the components counter does not update itself properly. I think it's a problem with my recursion method but I'm not able able to fix it.

Here is the code:

```<code>def dfs_scc(graph, node, components_c, nodes_c, connected_components, visited_nodes):
    nodes_c+=1
    connected_components[node]=-nodes_c
    visited_nodes.append(node)
    last=nodes_c
    for adj in graph.get_adj(node):
        if (connected_components[adj[1]]==0):
            b=dfs_scc(graph, adj[1], components_c, nodes_c, connected_components, visited_nodes)
            last=min(last, b)
        elif (connected_components[adj[1]]<0): last=min(last, -connected_components[adj[1]])
    if (last==-connected_components[node]):
        components_c+=1
        print('VISITED NODE QUEUE: ', list(visited_nodes), '; COMPONENTS COUNTER: ', components_c)
        while(visited_nodes[-1]!=node):
            w=visited_nodes.pop()
            connected_components[w]=components_c
        w=visited_nodes.pop()
        connected_components[w]=components_c
    return last
</code>```

And here the output:

```<code>VISITED NODE QUEUE: [0, 1, 6, 2, 4, 5, 7] ; COMPONENTS COUNTER: 1
VISITED NODE QUEUE: [0, 1, 6, 2, 4, 5] ; COMPONENTS COUNTER: 1
VISITED NODE QUEUE: [0, 1, 6] ; COMPONENTS COUNTER: 1
VISITED NODE QUEUE: [3] ; COMPONENTS COUNTER: 1
----------------------
CONNECTED COMPONENT: {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1}
</code>```

As you can see the queue of the visited nodes remove elements in the right order, at first recursion the node 7 is popped out course is just it's in that components; at next recursion the node 2, 4 and 5 are removed belonging to the same component and so on.

Instead in the final line of the output I've a dictionary (node : component) in which the component value is always the same.

Have any idea?

As asked here is the entire code:

```<code>class Graph(object):
    def __init__(self, graph=None):
        if graph == None: graph = {}
        self.__graph = graph

    def get_nodes(self): return list(self.__graph.keys())

    def get_edges(self): return self.__generate_edges()

    def __generate_edges(self):
        edges = []
        for node in self.__graph:
            for adj in self.__graph[node]:
                if node!=adj: edges.append((node, adj))
        return edges

    def add_node(self, node):
        if node not in self.__graph: self.__graph[node] = []

    def add_edge(self, edge):
        if edge[0] in self.__graph: self.__graph[edge[0]].append(edge[1])
        else:self.__graph[edge[0]] = [edge[1]]

    def get_adj(self, node):
        adj=[]
        for edge in self.__generate_edges():
            if node==edge[0] and edge[0]!=edge[1]: adj.append(edge)
        return adj

def scc(graph):
    #connected_components : {npde0: components, node1: components, node2: components, node3 : components, ...}
    connected_components={graph.get_nodes()[i]: 0 for i in range(len(graph.get_nodes()))}
    components_c=nodes_c=0
    visited_nodes=deque()
    for node in graph.get_nodes():
        if (connected_components[node]==0):
            dfs_scc(graph, node, components_c, nodes_c, connected_components, visited_nodes)
    return connected_components

def dfs_scc(graph, node, components_c, nodes_c, connected_components, visited_nodes):
    nodes_c+=1
    connected_components[node]=-nodes_c
    visited_nodes.append(node)
    last=nodes_c
    for adj in graph.get_adj(node):
        if (connected_components[adj[1]]==0):
            b=dfs_scc(graph, adj[1], components_c, nodes_c, connected_components, visited_nodes)
            last=min(last, b)
        elif (connected_components[adj[1]]<0):
            last=min(last, -connected_components[adj[1]])
    if (last==-connected_components[node]):
        components_c+=1
        print('VISITED NODE QUEUE: ', list(visited_nodes), '; COMPONENTS COUNTER: ', components_c)
        while(visited_nodes[-1]!=node):
            w=visited_nodes.pop()
            connected_components[w]=components_c
        w=visited_nodes.pop()
        connected_components[w]=components_c
    return last

def main():
    g={0: [1, 2], 1: [6], 2: [4], 3: [], 4: [5], 5: [2, 7], 6: [0], 7: []}
    graph=Graph(g)
    # nodes=random.randint(1, 10)
    # for i in range(nodes): graph.add_node(i)
    # for i in range(0, nodes):
    #     for j in range(0, nodes):
    #         graph.add_edge((i, j))
    cc=scc(graph)
    print("CONNECTED COMPONENTS: ", cc)
</code>```

答:
The issue is that the modification that a function execution brings to components_c, nodes_c, must carry back to the caller's variables with the same name, but that is not happening, because these variables are local to their own function execution context. The caller's variables with those names will not be modified by the recursive calls it makes, but they should.

You can solve this in different ways. One way is to make dfs_scc a function that is defined within scc, and to only define the two variables mentioned above in the scope of scc. Then dfs_scc can reference those variables via the nonlocal keyword instead of getting them as arguments, and so modify them in a way that will be seen by all execution contexts in the recursion tree.

Here is how that looks:

```<code>def scc(graph):
    components_c=nodes_c=0

    # define the recursive function with the scope where the above variables are defined
    def dfs_scc(graph, node, connected_components, visited_nodes):
        nonlocal components_c, nodes_c # reference those variables

        nodes_c+=1
        connected_components[node]=-nodes_c
        visited_nodes.append(node)
        last=nodes_c
        for adj in graph.get_adj(node):
            if (connected_components[adj[1]]==0):
                b=dfs_scc(graph, adj[1], connected_components, visited_nodes)
                last=min(last, b)
            elif (connected_components[adj[1]]<0):
                last=min(last, -connected_components[adj[1]])
        if (last==-connected_components[node]):
            components_c+=1
            print('VISITED NODE QUEUE: ', list(visited_nodes), '; COMPONENTS COUNTER: ', components_c)
            while(visited_nodes[-1]!=node):
                w=visited_nodes.pop()
                connected_components[w]=components_c
            w=visited_nodes.pop()
            connected_components[w]=components_c
        return last
    #connected_components : {npde0: components, node1: components, node2: components, node3 : components, ...}
    connected_components={graph.get_nodes()[i]: 0 for i in range(len(graph.get_nodes()))}
    visited_nodes=deque()
    for node in graph.get_nodes():
        if (connected_components[node]==0):
            dfs_scc(graph, node, connected_components, visited_nodes)
    return connected_components
</code>```

Title: Tarjan algorithm, recursion mistakes

Body:
I'm trying to implement the Tarjan's algorithm (to find strongly connected components in a graph).

I'm stuck in the dfs part of the algorithm where the components counter does not update itself properly. I think it's a problem with my recursion method but I'm not able able to fix it.

Here is the code:

def dfs_scc(graph, node, components_c, nodes_c, connected_components, visited_nodes):
    nodes_c+=1
    connected_components[node]=-nodes_c
    visited_nodes.append(node)
    last=nodes_c
    for adj in graph.get_adj(node):
        if (connected_components[adj[1]]==0):
            b=dfs_scc(graph, adj[1], components_c, nodes_c, connected_components, visited_nodes)
            last=min(last, b)
        elif (connected_components[adj[1]]<0): last=min(last, -connected_components[adj[1]])
    if (last==-connected_components[node]):
        components_c+=1
        print('VISITED NODE QUEUE: ', list(visited_nodes), '; COMPONENTS COUNTER: ', components_c)
        while(visited_nodes[-1]!=node):
            w=visited_nodes.pop()
            connected_components[w]=components_c
        w=visited_nodes.pop()
        connected_components[w]=components_c
    return last

And here the output:

VISITED NODE QUEUE: [0, 1, 6, 2, 4, 5, 7] ; COMPONENTS COUNTER: 1
VISITED NODE QUEUE: [0, 1, 6, 2, 4, 5] ; COMPONENTS COUNTER: 1
VISITED NODE QUEUE: [0, 1, 6] ; COMPONENTS COUNTER: 1
VISITED NODE QUEUE: [3] ; COMPONENTS COUNTER: 1
----------------------
CONNECTED COMPONENT: {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1}

As you can see the queue of the visited nodes remove elements in the right order, at first recursion the node 7 is popped out course is just it's in that components; at next recursion the node 2, 4 and 5 are removed belonging to the same component and so on.

Instead in the final line of the output I've a dictionary (node : component) in which the component value is always the same.

Have any idea?

As asked here is the entire code:

class Graph(object):
    def __init__(self, graph=None):
        if graph == None: graph = {}
        self.__graph = graph

    def get_nodes(self): return list(self.__graph.keys())

    def get_edges(self): return self.__generate_edges()

    def __generate_edges(self):
        edges = []
        for node in self.__graph:
            for adj in self.__graph[node]:
                if node!=adj: edges.append((node, adj))
        return edges

    def add_node(self, node):
        if node not in self.__graph: self.__graph[node] = []

    def add_edge(self, edge):
        if edge[0] in self.__graph: self.__graph[edge[0]].append(edge[1])
        else:self.__graph[edge[0]] = [edge[1]]

    def get_adj(self, node):
        adj=[]
        for edge in self.__generate_edges():
            if node==edge[0] and edge[0]!=edge[1]: adj.append(edge)
        return adj

def scc(graph):
    #connected_components : {npde0: components, node1: components, node2: components, node3 : components, ...}
    connected_components={graph.get_nodes()[i]: 0 for i in range(len(graph.get_nodes()))}
    components_c=nodes_c=0
    visited_nodes=deque()
    for node in graph.get_nodes():
        if (connected_components[node]==0):
            dfs_scc(graph, node, components_c, nodes_c, connected_components, visited_nodes)
    return connected_components

def dfs_scc(graph, node, components_c, nodes_c, connected_components, visited_nodes):
    nodes_c+=1
    connected_components[node]=-nodes_c
    visited_nodes.append(node)
    last=nodes_c
    for adj in graph.get_adj(node):
        if (connected_components[adj[1]]==0):
            b=dfs_scc(graph, adj[1], components_c, nodes_c, connected_components, visited_nodes)
            last=min(last, b)
        elif (connected_components[adj[1]]<0):
            last=min(last, -connected_components[adj[1]])
    if (last==-connected_components[node]):
        components_c+=1
        print('VISITED NODE QUEUE: ', list(visited_nodes), '; COMPONENTS COUNTER: ', components_c)
        while(visited_nodes[-1]!=node):
            w=visited_nodes.pop()
            connected_components[w]=components_c
        w=visited_nodes.pop()
        connected_components[w]=components_c
    return last

def main():
    g={0: [1, 2], 1: [6], 2: [4], 3: [], 4: [5], 5: [2, 7], 6: [0], 7: []}
    graph=Graph(g)
    # nodes=random.randint(1, 10)
    # for i in range(nodes): graph.add_node(i)
    # for i in range(0, nodes):
    #     for j in range(0, nodes):
    #         graph.add_edge((i, j))
    cc=scc(graph)
    print("CONNECTED COMPONENTS: ", cc)

Body:
The issue is that the modification that a function execution brings to components_c, nodes_c, must carry back to the caller's variables with the same name, but that is not happening, because these variables are local to their own function execution context. The caller's variables with those names will not be modified by the recursive calls it makes, but they should.

You can solve this in different ways. One way is to make dfs_scc a function that is defined within scc, and to only define the two variables mentioned above in the scope of scc. Then dfs_scc can reference those variables via the nonlocal keyword instead of getting them as arguments, and so modify them in a way that will be seen by all execution contexts in the recursion tree.

Here is how that looks:

def scc(graph):
    components_c=nodes_c=0

    # define the recursive function with the scope where the above variables are defined
    def dfs_scc(graph, node, connected_components, visited_nodes):
        nonlocal components_c, nodes_c # reference those variables

        nodes_c+=1
        connected_components[node]=-nodes_c
        visited_nodes.append(node)
        last=nodes_c
        for adj in graph.get_adj(node):
            if (connected_components[adj[1]]==0):
                b=dfs_scc(graph, adj[1], connected_components, visited_nodes)
                last=min(last, b)
            elif (connected_components[adj[1]]<0):
                last=min(last, -connected_components[adj[1]])
        if (last==-connected_components[node]):
            components_c+=1
            print('VISITED NODE QUEUE: ', list(visited_nodes), '; COMPONENTS COUNTER: ', components_c)
            while(visited_nodes[-1]!=node):
                w=visited_nodes.pop()
                connected_components[w]=components_c
            w=visited_nodes.pop()
            connected_components[w]=components_c
        return last
    #connected_components : {npde0: components, node1: components, node2: components, node3 : components, ...}
    connected_components={graph.get_nodes()[i]: 0 for i in range(len(graph.get_nodes()))}
    visited_nodes=deque()
    for node in graph.get_nodes():
        if (connected_components[node]==0):
            dfs_scc(graph, node, connected_components, visited_nodes)
    return connected_components


来源: stackexchange

问:
What is the difference between IAM and Azure AD on the azure cloud?
What is the difference between IAM and Azure AD on the azure cloud?

They don't make it clear.

答:
Azure AD is for Authentiction - User must prove who they are using a Username and Password
IAM (RBAC) is for Authorization - a User is assigned a role or permissions to use a specific resource.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Could not start rails server on Ubuntu 20.04
I can't start my rails app after installing Ubuntu 20.04

There is traceback.

Also, I have the same errors:

...rbenv/versions/2.6.3/lib/ruby/2.6.0/x86_64-linux/etc.so: warning: already initialized constant Etc::...

then I've checked my rails version.

After reinstall my OS via erase, I have restored my backup of /home from Ubuntu 18.04
and checked my version of ruby rails and nodejs. Ruby and rails were the same, but I have to install nodejs and some postgres packages. Now, after that I've tried to run rails s in my project folder and there errors from traceback were appeared. Also, the command

yarn install --check-files

can't finish successfully, cause

info There appears to be trouble with your network connection. Retrying... error.

What should I do to start my app successfully?

My gemfile:

```<code>source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.3'

gem "rails_12factor"
# gem "hashid-rails", "~> 1.0"
gem 'dotenv-rails', groups: [:development, :test]
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.2'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
# gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'pry'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails'
  gem 'database_cleaner'
  gem 'selenium-webdriver'
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
end

gem 'minitest-rails'

group :test do
  gem 'minitest-rails-capybara'
  gem 'capybara', '>= 2.15'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem "active_model_serializers"
</code>```

Ruby: ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]

Rails: Rails 6.0.2.2

Nodejs: v10.19.0

答:
```<code>run `gem uninstall etc`
</code>```

and then gem update etc --default

Body:
I can't start my rails app after installing Ubuntu 20.04

There is traceback.

Also, I have the same errors:

...rbenv/versions/2.6.3/lib/ruby/2.6.0/x86_64-linux/etc.so: warning: already initialized constant Etc::...

then I've checked my rails version.

After reinstall my OS via erase, I have restored my backup of /home from Ubuntu 18.04
and checked my version of ruby rails and nodejs. Ruby and rails were the same, but I have to install nodejs and some postgres packages. Now, after that I've tried to run rails s in my project folder and there errors from traceback were appeared. Also, the command

yarn install --check-files

can't finish successfully, cause

info There appears to be trouble with your network connection. Retrying... error.

What should I do to start my app successfully?

My gemfile:

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.3'

gem "rails_12factor"
# gem "hashid-rails", "~> 1.0"
gem 'dotenv-rails', groups: [:development, :test]
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.2'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
# gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'pry'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails'
  gem 'database_cleaner'
  gem 'selenium-webdriver'
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
end

gem 'minitest-rails'

group :test do
  gem 'minitest-rails-capybara'
  gem 'capybara', '>= 2.15'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem "active_model_serializers"

Ruby: ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]

Rails: Rails 6.0.2.2

Nodejs: v10.19.0

Body:
run `gem uninstall etc`

and then gem update etc --default


问:
Unity 2D animation only playing when moving right
This is my first time animating in unity. I am using a boolean titled "isRunning" which is set to true under each if statement for detecting input. This is supposed to trigger the 2D knight character's animation to run. However, this only works for the "d" key and not for any of the others (w a and s).
Here is the code:

```<code>private void TakeInput()
    {
        direction = Vector2.zero;

        if (Input.GetKey(KeyCode.W))
        {
            direction += Vector2.up;
            animator.SetBool("isRunning", true);
        }
        if (Input.GetKey(KeyCode.A))
        {
            direction += Vector2.left;
            animator.SetBool("isRunning", true);
        }
        if (Input.GetKey(KeyCode.S))
        {
            direction += Vector2.down;
            animator.SetBool("isRunning", true);
        }
        if (Input.GetKey(KeyCode.D))
        {
            direction += Vector2.right;
            animator.SetBool("isRunning", true);
        }
        else
        {
            animator.SetBool("isRunning", false);
        }
    }
</code>```

答:
The else is only connected to the last if.  It should be else if on some of the cases, like this</p>

```<code>{
    direction = Vector2.zero;

    if (Input.GetKey(KeyCode.W))
    {
        direction += Vector2.up;
        animator.SetBool("isRunning", true);
    }
    else if (Input.GetKey(KeyCode.A))
    {
        direction += Vector2.left;
        animator.SetBool("isRunning", true);
    }
    else if (Input.GetKey(KeyCode.S))
    {
        direction += Vector2.down;
        animator.SetBool("isRunning", true);
    }
    else if (Input.GetKey(KeyCode.D))
    {
        direction += Vector2.right;
        animator.SetBool("isRunning", true);
    }
    else
    {
        animator.SetBool("isRunning", false);
    }
}
</code>```

Body:
This is my first time animating in unity. I am using a boolean titled "isRunning" which is set to true under each if statement for detecting input. This is supposed to trigger the 2D knight character's animation to run. However, this only works for the "d" key and not for any of the others (w a and s).
Here is the code:

private void TakeInput()
    {
        direction = Vector2.zero;

        if (Input.GetKey(KeyCode.W))
        {
            direction += Vector2.up;
            animator.SetBool("isRunning", true);
        }
        if (Input.GetKey(KeyCode.A))
        {
            direction += Vector2.left;
            animator.SetBool("isRunning", true);
        }
        if (Input.GetKey(KeyCode.S))
        {
            direction += Vector2.down;
            animator.SetBool("isRunning", true);
        }
        if (Input.GetKey(KeyCode.D))
        {
            direction += Vector2.right;
            animator.SetBool("isRunning", true);
        }
        else
        {
            animator.SetBool("isRunning", false);
        }
    }

Body:
The else is only connected to the last if.  It should be else if on some of the cases, like this

{
    direction = Vector2.zero;

    if (Input.GetKey(KeyCode.W))
    {
        direction += Vector2.up;
        animator.SetBool("isRunning", true);
    }
    else if (Input.GetKey(KeyCode.A))
    {
        direction += Vector2.left;
        animator.SetBool("isRunning", true);
    }
    else if (Input.GetKey(KeyCode.S))
    {
        direction += Vector2.down;
        animator.SetBool("isRunning", true);
    }
    else if (Input.GetKey(KeyCode.D))
    {
        direction += Vector2.right;
        animator.SetBool("isRunning", true);
    }
    else
    {
        animator.SetBool("isRunning", false);
    }
}


问:
ifelse Declaration or statement expected
```<code>function resp (){
  if (distance<0);{
var para = document.createElement("p");
    var node = document.createTextNode("Yes");
    para.appendChild(node);
    var element = document.getElementById("inda");
    element.appendChild(para);}
else{
var para = document.createElement("p");
    var node = document.createTextNode("No, time left:");
    para.appendChild(node);
    var element = document.getElementById("inda");
    element.appendChild(para);}
}
</code>```

Why does it give me the error: Declaration or statement expected

答:
```<code>if (distance<0);{
</code>```

-->

```<code>if (distance<0) {
</code>```

It's easier to find such problem if you have an ide like webstorm or visual studio code.

Your code in pretty printed form:

```<code>function resp() {
    if (distance < 0) {
        var para = document.createElement("p");
        var node = document.createTextNode("Yes");
        para.appendChild(node);
        var element = document.getElementById("inda");
        element.appendChild(para);
    } else {
        var para = document.createElement("p");
        var node = document.createTextNode("No, time left:");
        para.appendChild(node);
        var element = document.getElementById("inda");
        element.appendChild(para);
    }
}
</code>```

Your code after little refactoring:

```<code>function resp() {
    const label = (distance < 0) ? 'Yes' : 'No, time left:';
    var para = document.createElement("p");
    var node = document.createTextNode(label);
    para.appendChild(node);
    var element = document.getElementById("inda");
    element.appendChild(para);
}
</code>```

Body:
function resp (){
  if (distance<0);{
var para = document.createElement("p");
    var node = document.createTextNode("Yes");
    para.appendChild(node);
    var element = document.getElementById("inda");
    element.appendChild(para);}
else{
var para = document.createElement("p");
    var node = document.createTextNode("No, time left:");
    para.appendChild(node);
    var element = document.getElementById("inda");
    element.appendChild(para);}
}

Why does it give me the error: Declaration or statement expected

Body:
if (distance<0);{

-->

if (distance<0) {

It's easier to find such problem if you have an ide like webstorm or visual studio code.

Your code in pretty printed form:

function resp() {
    if (distance < 0) {
        var para = document.createElement("p");
        var node = document.createTextNode("Yes");
        para.appendChild(node);
        var element = document.getElementById("inda");
        element.appendChild(para);
    } else {
        var para = document.createElement("p");
        var node = document.createTextNode("No, time left:");
        para.appendChild(node);
        var element = document.getElementById("inda");
        element.appendChild(para);
    }
}

Your code after little refactoring:

function resp() {
    const label = (distance < 0) ? 'Yes' : 'No, time left:';
    var para = document.createElement("p");
    var node = document.createTextNode(label);
    para.appendChild(node);
    var element = document.getElementById("inda");
    element.appendChild(para);
}


问:
split very large text into documents by matching regex in python
i have a very large file (~4 GB) which look like this:

```<code><P ID=000ajevz>
OBJECTIVE: Fludarabine, cyclophosphamide and rituximab (FCR) therapy for lymphoid malignancies has historically been associated with a low reported incidence of Pneumocystis jirovecii pneumonia (PJP). However, prophylaxis was routinely used in early studies,.............................
</P>
<P ID=000q5l5n>
SIMPLE SUMMARY: The role of rodents in the transmission of many diseases is widely known. Wild rats abundant in urban environments may transmit diseases to humans and other animals, including laboratory rodents used for biomedical research in research facilities,......
</P>
</code>```

I am trying to read the whole file at once and then split it using regex: '
(.*?)
'

to process the text of my file onto a posting list to apply tfidf.

My code looks like:

```<code>import time
import re
import json
import string
import numpy as np
import collections
from collections import Counter
from nltk.corpus import stopwords

filename = 'corpus3.txt'
text = open(filename, encoding ='utf8').read() #read all text of file at once

doc = re.finditer(r'<P ID=(\w+)>(.*?)</P>', text, re.S) #split text into documents by matching regular expression
STOPWORDS = set(stopwords.words('english')) #load stopwords from nltk

no_docs = 0 #number of processed documents
doc_freq = Counter() #document frequency of each term
col _freq = Counter() #collection frequency

doc_id = 0
id_dict = dict()

data = collections.defaultdict(list) #dictionary of key:word and values:(docid, termfrequency)
for (docid, text) in [(x.group(1), x.group(2)) for x in doc]:
    no_docs += 1
    text = text.lower()
    #wordcount = Counter(text.split())
    wordcount = Counter(re.split(r'\W+', text))
    #wordcount = Counter(word[:5] for word in text.split()) #5-stemming
    doc_id +=1
    id_dict[doc_id] = docid
    for (word, count) in wordcount.items():
        if word.isalpha():
            if not word in STOPWORDS:
                #word_stem = word[:5]
                doc_freq[word] += 1
                col_freq[word] += count
                data[word].append((doc_id, count))

flattend = (item for tag in data.values() for item in tag) #[(docid, tf)]
posting = (item  for tag in flattend for item in tag ) #[docid, tf]
posting_list = list(posting)
</code>```

But i keep getting memory error when it tries to read the whole file at once. I tried in google colab, my colab crashes out of memory.
I tried to slice my file and read only 1/4 of my file, it gives my memoryerror.
I also tried to read it line by line, but then i dont know how to iterate through those lines and split using regex to get a single iterator to process later.

答:
You can make a generator like this

def read_until(f, close_tag):
    line = f.readline()
    while not line.startswith(close_tag):
        yield line
        line = f.readline()

def get_docid(line):
    id_start = line.find("ID=") + 3
    id_end = line.find(">")
    return line[id_start:id_end]

def read_doc(f):
    """Split text into documents"""
    text = ""
    line = f.readline()
    while line:
        if line.startswith("<P"):
            docid = get_docid(line)
            # read until closing tag
            for rest_line in read_until(f, "</P"):
                text += rest_line
            yield (docid, text)
            text = ""
        line = f.readline()
```

<p>This lets you read line by line and still split it the way you want. It works because the <code><P></code> tags are always on their own lines. You can replace the for loop in your code with</p>

<pre class="lang-py prettyprint-override"><code>docfile = open(filename)
for docid, text in read_doc(docfile):
    ...
</code>```

Body:
i have a very large file (~4 GB) which look like this:

OBJECTIVE: Fludarabine, cyclophosphamide and rituximab (FCR) therapy for lymphoid malignancies has historically been associated with a low reported incidence of Pneumocystis jirovecii pneumonia (PJP). However, prophylaxis was routinely used in early studies,.............................

SIMPLE SUMMARY: The role of rodents in the transmission of many diseases is widely known. Wild rats abundant in urban environments may transmit diseases to humans and other animals, including laboratory rodents used for biomedical research in research facilities,......

I am trying to read the whole file at once and then split it using regex: '
(.*?)
'

to process the text of my file onto a posting list to apply tfidf.

My code looks like:

import time
import re
import json
import string
import numpy as np
import collections
from collections import Counter
from nltk.corpus import stopwords

filename = 'corpus3.txt'
text = open(filename, encoding ='utf8').read() #read all text of file at once

doc = re.finditer(r'
(.*?)
', text, re.S) #split text into documents by matching regular expression
STOPWORDS = set(stopwords.words('english')) #load stopwords from nltk

no_docs = 0 #number of processed documents
doc_freq = Counter() #document frequency of each term
col _freq = Counter() #collection frequency

doc_id = 0
id_dict = dict()

data = collections.defaultdict(list) #dictionary of key:word and values:(docid, termfrequency)
for (docid, text) in [(x.group(1), x.group(2)) for x in doc]:
    no_docs += 1
    text = text.lower()
    #wordcount = Counter(text.split())
    wordcount = Counter(re.split(r'\W+', text))
    #wordcount = Counter(word[:5] for word in text.split()) #5-stemming
    doc_id +=1
    id_dict[doc_id] = docid
    for (word, count) in wordcount.items():
        if word.isalpha():
            if not word in STOPWORDS:
                #word_stem = word[:5]
                doc_freq[word] += 1
                col_freq[word] += count
                data[word].append((doc_id, count))

flattend = (item for tag in data.values() for item in tag) #[(docid, tf)]
posting = (item  for tag in flattend for item in tag ) #[docid, tf]
posting_list = list(posting)

But i keep getting memory error when it tries to read the whole file at once. I tried in google colab, my colab crashes out of memory.
I tried to slice my file and read only 1/4 of my file, it gives my memoryerror.
I also tried to read it line by line, but then i dont know how to iterate through those lines and split using regex to get a single iterator to process later.

Body:
You can make a generator like this

def read_until(f, close_tag):
    line = f.readline()
    while not line.startswith(close_tag):
        yield line
        line = f.readline()

def get_docid(line):
    id_start = line.find("ID=") + 3
    id_end = line.find(">")
    return line[id_start:id_end]

def read_doc(f):
    """Split text into documents"""
    text = ""
    line = f.readline()
    while line:
        if line.startswith("<P"):
            docid = get_docid(line)
            # read until closing tag
            for rest_line in read_until(f, "</P"):
                text += rest_line
            yield (docid, text)
            text = ""
        line = f.readline()

This lets you read line by line and still split it the way you want. It works because the <P> tags are always on their own lines. You can replace the for loop in your code with

docfile = open(filename)
for docid, text in read_doc(docfile):
    ...


问:
Listview.setOnItemclicklistener with Searchview
I've a problem with my ListView onClick. I try to explain u by a particule of my code.

So when I'm filtering by
searching c for example
the ActivityA is opening, the
same with Activity B.
So during filtering
they taking the position 0.
Because without filtering
every click open the right Activity.
So, please how can I fix it?

```<code>
private SearchView sv;

Protected void onCreate........

String[] Values = {"a","b","c"};
listView = findViewById(R.id.liste);

sv=findViewById(R.id.searchview);

ArrayAdapter<String>......(.simple_list_item_2,android.R.id.text1,Values);
listView.setAdapter;
sv.setOnQueryTextListener........
//everything here is ok it's filtering well.
//After that,I've my listview.onClick
listview.setOnItemClickListener()
........(parent, View view, int position, long id){
   if(position == 0){
     Itent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
  }

  if(position == 1){
     Intent b = new Intent  (getApplicationContext(),AtivityB.class);
startActivity(b)
  }

 if(position == 2){
     Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
  }
}```
```

答:
I am not quite sure if this will help but I would use a switch instead of if statements. </p>

```<code>    switch (position) {
        case 0:
            Intent a = new Intent  (getApplicationContext(),AtivityA.class);
            startActivity(a)
            break;
        case 1:
            Intent b = new Intent  (getApplicationContext(),AtivityB.class);
            startActivity(b)
            break;
        case 2:
            Intent c = new Intent  (getApplicationContext(),AtivityC.class);
            startActivity(c)
            break;

    }
</code>```

Body:
I've a problem with my ListView onClick. I try to explain u by a particule of my code.

So when I'm filtering by
searching c for example
the ActivityA is opening, the
same with Activity B.
So during filtering
they taking the position 0.
Because without filtering
every click open the right Activity.
So, please how can I fix it?

private SearchView sv;

Protected void onCreate........

String[] Values = {"a","b","c"};
listView = findViewById(R.id.liste);

sv=findViewById(R.id.searchview);

ArrayAdapter<String>......(.simple_list_item_2,android.R.id.text1,Values);
listView.setAdapter;
sv.setOnQueryTextListener........
//everything here is ok it's filtering well.
//After that,I've my listview.onClick
listview.setOnItemClickListener()
........(parent, View view, int position, long id){
   if(position == 0){
     Itent a = new Intent (getApplicationContext(),AtivityA.class);
startActivity(a)
  }

  if(position == 1){
     Intent b = new Intent  (getApplicationContext(),AtivityB.class);
startActivity(b)
  }

 if(position == 2){
     Intent c = new Intent (getApplicationContext(),AtivityC.class);
startActivity(c)
  }
}```

Body:
I am not quite sure if this will help but I would use a switch instead of if statements.

    switch (position) {
        case 0:
            Intent a = new Intent  (getApplicationContext(),AtivityA.class);
            startActivity(a)
            break;
        case 1:
            Intent b = new Intent  (getApplicationContext(),AtivityB.class);
            startActivity(b)
            break;
        case 2:
            Intent c = new Intent  (getApplicationContext(),AtivityC.class);
            startActivity(c)
            break;

    }


问:
TemplateDoesNotExist : Template Not being detected on Django
Thanks to land at my concern.
I would be thankful if you will help me out.

Earlier i was doing same procedure to fetch the template, that time working. But recently i tried to make another project, now this time, getting "TemplateDoesNotExist" error.

```<code>technicalcourses/Courses.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.0.4
Exception Type: TemplateDoesNotExist
Exception Value:
technicalcourses/Courses.html
Exception Location: C:\Program Files\Python37\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable:  C:\Program Files\Python37\python.exe
Python Version: 3.7.4
Python Path:
['C:\\Users\\ravik\\Desktop\\Django_New_Project\\edureka',
 'C:\\Program Files\\Python37\\python37.zip',
 'C:\\Program Files\\Python37\\DLLs',
 'C:\\Program Files\\Python37\\lib',
 'C:\\Program Files\\Python37',
 'C:\\Program Files\\Python37\\lib\\site-packages',
 'C:\\Program Files\\Python37\\lib\\site-packages\\win32',
 'C:\\Program Files\\Python37\\lib\\site-packages\\win32\\lib',
 'C:\\Program Files\\Python37\\lib\\site-packages\\Pythonwin']
Server time:    Sun, 31 May 2020 19:54:29 +0000
</code>```

Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

```<code>django.template.loaders.filesystem.Loader: C:\Users\ravik\Desktop\Django_New_Project\edureka\template\technicalcourses\Courses.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Program Files\Python37\lib\site-packages\django\contrib\admin\templates\technicalcourses\Courses.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Program Files\Python37\lib\site-packages\django\contrib\auth\templates\technicalcourses\Courses.html (Source does not exist)
</code>```

****Here Below I have completed- Kindly attached images ****

答:
in your settings.py file you should have direction to your template path:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...
    },
]
```

https://docs.djangoproject.com/en/3.0/topics/templates/

Body:
Thanks to land at my concern.
I would be thankful if you will help me out.

Earlier i was doing same procedure to fetch the template, that time working. But recently i tried to make another project, now this time, getting "TemplateDoesNotExist" error.

technicalcourses/Courses.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.0.4
Exception Type: TemplateDoesNotExist
Exception Value:
technicalcourses/Courses.html
Exception Location: C:\Program Files\Python37\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable:  C:\Program Files\Python37\python.exe
Python Version: 3.7.4
Python Path:
['C:\\Users\\ravik\\Desktop\\Django_New_Project\\edureka',
 'C:\\Program Files\\Python37\\python37.zip',
 'C:\\Program Files\\Python37\\DLLs',
 'C:\\Program Files\\Python37\\lib',
 'C:\\Program Files\\Python37',
 'C:\\Program Files\\Python37\\lib\\site-packages',
 'C:\\Program Files\\Python37\\lib\\site-packages\\win32',
 'C:\\Program Files\\Python37\\lib\\site-packages\\win32\\lib',
 'C:\\Program Files\\Python37\\lib\\site-packages\\Pythonwin']
Server time:    Sun, 31 May 2020 19:54:29 +0000

Template-loader postmortem
Django tried loading these templates, in this order:

Using engine django:

django.template.loaders.filesystem.Loader: C:\Users\ravik\Desktop\Django_New_Project\edureka\template\technicalcourses\Courses.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Program Files\Python37\lib\site-packages\django\contrib\admin\templates\technicalcourses\Courses.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Program Files\Python37\lib\site-packages\django\contrib\auth\templates\technicalcourses\Courses.html (Source does not exist)

****Here Below I have completed- Kindly attached images ****

Body:
in your settings.py file you should have direction to your template path:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...
    },
]

https://docs.djangoproject.com/en/3.0/topics/templates/


问:
Print HTML table with header row from array which has rows with missing columns
I have an array with following format:

```<code>Array
(
    [0] => Array
        (
            [Push to Web] => Yes
            [attribute_set] => laminate_flooring
            [category] => Accessories/Underlay
            [name] => Under Pad Feather Light Foam
            [sku] => 123-1028
            [description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [image] => 123-1028.jpg
            [gallery_Image] => 9095307460638-424-424.jpg
            [price] => 0.24
            [qty_ca] => 16
            [weight] => 3
            [meta_description] => 51-1001
            [meta_title] => Under Pad Feather Light Foam
            [status] => 1
            [flooring_coverage] => 200
            [is_flooring_product] => 1
            [web_price_comparative] => 0.31
        )

    [1] => Array
        (
            [Push to Web] => Yes
            [category] => Accessories
            [name] => Vent Maple Flush 4x10
            [sku] => 089-1000
            [description] => Vent Flush Mount Maple 4 x 10
            [short_description] => Vent Flush Mount Maple 4 x 10
            [image] => 089-1000.jpg
            [price] => 17.05
            [qty_ca] => 63
            [qty_us] => 41
            [meta_description] => 10-1023
            [meta_title] => Vent Maple Flush 4x10
            [status] => 1
            [flooring_coverage] => 1
            [min_order_qty] => 400
            [web_price_comparative] => 22.16
        )
)
</code>```

I have to print the data in the table so that each key of array is printed as column header and the value as column data. That means Push to Web, attribute_set etc will be header and Yes, laminate_flooring will be data respectively.

I wrote the following but its not working.

```<code> $row = 0;
$table  = '<table border="1" id="datatable">';
foreach($data as $value){
    $table .= '<tr>';
    if ($row == 0) {
        foreach($value as $innerkey=>$innervalue){
            $table .= '<td>'.$innerkey.'</td>';
        }
    }
    $table .= '</tr><tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
    $row++;
}
$table .= '</table>';

 print_r($table);
</code>```

The output of the table should be as follows:

But is is showing like this

First problem is the header row is continue printing only upto avalable data in first data row. Secondly If any data cell is unavailable then it is filled by next cell data. but it is supposed to be remain bank cell.
Please help me to sort out the problem. Thanks in advance

答:
This assumes that all the child arrays use the same keys, which from the picture it looks like they do. </p>

<p>Also I've added htmlentities just to stop any rogue html breaking the table, but you can remove it if you know it's not needed. </p>

```<code>    $table  = '<table border="1" id="datatable"><tr>';

    // Get the headers from the first child array.
    $headers = array_keys($data[0]);
    foreach($headers as $header){
        $table .= '<th>'.htmlentities($header).'</th>';
    }

    foreach($data as $value){

        $table .= '</tr><tr>';
        foreach($value as $innerkey=>$innervalue){
            $table .= '<td>'.htmlentities($innervalue).'</td>';
        }
        $table .= '</tr>';
    }
    $table .= '</table>';
</code>```

Body:
I have an array with following format:

Array
(
    [0] => Array
        (
            [Push to Web] => Yes
            [attribute_set] => laminate_flooring
            [category] => Accessories/Underlay
            [name] => Under Pad Feather Light Foam
            [sku] => 123-1028
            [description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [image] => 123-1028.jpg
            [gallery_Image] => 9095307460638-424-424.jpg
            [price] => 0.24
            [qty_ca] => 16
            [weight] => 3
            [meta_description] => 51-1001
            [meta_title] => Under Pad Feather Light Foam
            [status] => 1
            [flooring_coverage] => 200
            [is_flooring_product] => 1
            [web_price_comparative] => 0.31
        )

    [1] => Array
        (
            [Push to Web] => Yes
            [category] => Accessories
            [name] => Vent Maple Flush 4x10
            [sku] => 089-1000
            [description] => Vent Flush Mount Maple 4 x 10
            [short_description] => Vent Flush Mount Maple 4 x 10
            [image] => 089-1000.jpg
            [price] => 17.05
            [qty_ca] => 63
            [qty_us] => 41
            [meta_description] => 10-1023
            [meta_title] => Vent Maple Flush 4x10
            [status] => 1
            [flooring_coverage] => 1
            [min_order_qty] => 400
            [web_price_comparative] => 22.16
        )
)

I have to print the data in the table so that each key of array is printed as column header and the value as column data. That means Push to Web, attribute_set etc will be header and Yes, laminate_flooring will be data respectively.

I wrote the following but its not working.

 $row = 0;
$table  = '
';
foreach($data as $value){
    $table .= '
';
    if ($row == 0) {
        foreach($value as $innerkey=>$innervalue){
            $table .= ''.$innerkey.'	';
        }
    }
    $table .= '

';
    foreach($value as $innerkey=>$innervalue){
        $table .= ''.$innervalue.'	';
    }
    $table .= '
';
    $row++;
}
$table .= '
';

 print_r($table);

The output of the table should be as follows:

But is is showing like this

First problem is the header row is continue printing only upto avalable data in first data row. Secondly If any data cell is unavailable then it is filled by next cell data. but it is supposed to be remain bank cell.
Please help me to sort out the problem. Thanks in advance

Body:
This assumes that all the child arrays use the same keys, which from the picture it looks like they do.

Also I've added htmlentities just to stop any rogue html breaking the table, but you can remove it if you know it's not needed.

    $table  = '<table border="1" id="datatable"><tr>';

    // Get the headers from the first child array.
    $headers = array_keys($data[0]);
    foreach($headers as $header){
        $table .= '<th>'.htmlentities($header).'</th>';
    }

    foreach($data as $value){

        $table .= '</tr><tr>';
        foreach($value as $innerkey=>$innervalue){
            $table .= '<td>'.htmlentities($innervalue).'</td>';
        }
        $table .= '</tr>';
    }
    $table .= '</table>';


问:
C compiler not noticing errors and correcting code itself
So I am a beginner in C and I have been following a book Primer Plus 6th edition.
While I was running my program I noticed something really strange, compiler is not working as it is supposed to, for example

```<code>int main(){
    one_three();
    getchar();
    return 0;
}

void one_three(void){
    printf("one\n");
    two();
    printf("three");
}

void two(void){
    printf("two\n");

}

</code>```

this is my code, there are many errors as no function prototype declarations and not including header files, but some how the output is produced only by giving warnings, i dont think this should happen
NOTE I HAVE INTENTIONALLY REMOVED FUNCTION PROTOTYPE DECLARTAIONS AND INCLUDING HEADER FILES

output is :

```<code>review1.c: In function 'main':
review1.c:2:5: warning: implicit declaration of function 'one_three' [-Wimplicit-function-declaration]
    2 |     one_three();
      |     ^~~~~~~~~
review1.c:3:5: warning: implicit declaration of function 'getchar' [-Wimplicit-function-declaration]
    3 |     getchar();
      |     ^~~~~~~
review1.c:1:1: note: 'getchar' is defined in header '<stdio.h>'; did you forget to '#include <stdio.h>'?
  +++ |+#include <stdio.h>
    1 | int main(){
review1.c: At top level:
review1.c:7:6: warning: conflicting types for 'one_three'
    7 | void one_three(void){
      |      ^~~~~~~~~
review1.c:2:5: note: previous implicit declaration of 'one_three' was here
    2 |     one_three();
      |     ^~~~~~~~~
review1.c: In function 'one_three':
review1.c:8:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
    8 |     printf("one\n");
      |     ^~~~~~
review1.c:8:5: warning: incompatible implicit declaration of built-in function 'printf'
review1.c:8:5: note: include '<stdio.h>' or provide a declaration of 'printf'
review1.c:9:5: warning: implicit declaration of function 'two' [-Wimplicit-function-declaration]
    9 |     two();
      |     ^~~
review1.c: At top level:
review1.c:13:6: warning: conflicting types for 'two'
   13 | void two(void){
      |      ^~~
review1.c:9:5: note: previous implicit declaration of 'two' was here
    9 |     two();
      |     ^~~
review1.c: In function 'two':
review1.c:14:5: warning: incompatible implicit declaration of built-in function 'printf'
   14 |     printf("two\n");
      |     ^~~~~~
review1.c:14:5: note: include '<stdio.h>' or provide a declaration of 'printf'
one
two
three

</code>```

those last three lines "one" two three is the output
Please help, i am using this compiler

I expect it to output errors when it has to and not add stuff itself, so that i could learn by my mistakes
using visual studio code with extensions : C/C++ by microsoft, Code runner

答: You need to declare methods that you are using in functions above the functions you are using them in. If you reorder the functions to be two, then one_three, then main. It should work.</p>

Body:
So I am a beginner in C and I have been following a book Primer Plus 6th edition.
While I was running my program I noticed something really strange, compiler is not working as it is supposed to, for example

int main(){
    one_three();
    getchar();
    return 0;
}

void one_three(void){
    printf("one\n");
    two();
    printf("three");
}

void two(void){
    printf("two\n");

}

this is my code, there are many errors as no function prototype declarations and not including header files, but some how the output is produced only by giving warnings, i dont think this should happen
NOTE I HAVE INTENTIONALLY REMOVED FUNCTION PROTOTYPE DECLARTAIONS AND INCLUDING HEADER FILES

output is :

review1.c: In function 'main':
review1.c:2:5: warning: implicit declaration of function 'one_three' [-Wimplicit-function-declaration]
    2 |     one_three();
      |     ^~~~~~~~~
review1.c:3:5: warning: implicit declaration of function 'getchar' [-Wimplicit-function-declaration]
    3 |     getchar();
      |     ^~~~~~~
review1.c:1:1: note: 'getchar' is defined in header '<stdio.h>'; did you forget to '#include <stdio.h>'?
  +++ |+#include <stdio.h>
    1 | int main(){
review1.c: At top level:
review1.c:7:6: warning: conflicting types for 'one_three'
    7 | void one_three(void){
      |      ^~~~~~~~~
review1.c:2:5: note: previous implicit declaration of 'one_three' was here
    2 |     one_three();
      |     ^~~~~~~~~
review1.c: In function 'one_three':
review1.c:8:5: warning: implicit declaration of function 'printf' [-Wimplicit-function-declaration]
    8 |     printf("one\n");
      |     ^~~~~~
review1.c:8:5: warning: incompatible implicit declaration of built-in function 'printf'
review1.c:8:5: note: include '<stdio.h>' or provide a declaration of 'printf'
review1.c:9:5: warning: implicit declaration of function 'two' [-Wimplicit-function-declaration]
    9 |     two();
      |     ^~~
review1.c: At top level:
review1.c:13:6: warning: conflicting types for 'two'
   13 | void two(void){
      |      ^~~
review1.c:9:5: note: previous implicit declaration of 'two' was here
    9 |     two();
      |     ^~~
review1.c: In function 'two':
review1.c:14:5: warning: incompatible implicit declaration of built-in function 'printf'
   14 |     printf("two\n");
      |     ^~~~~~
review1.c:14:5: note: include '<stdio.h>' or provide a declaration of 'printf'
one
two
three

those last three lines "one" two three is the output
Please help, i am using this compiler

I expect it to output errors when it has to and not add stuff itself, so that i could learn by my mistakes
using visual studio code with extensions : C/C++ by microsoft, Code runner


问:
Oracle SQL lead lag across different group
Suppose I have the below table. They key is just concat P1, P2, P3. I want to compare between key for each day. for example, from day 1 to day2, abc is removed and abe, aby is added.

```<code>P1  P2  P3  DAY KEY

a   b   c   1   abc
a   b   e   2   abe
a   b   y   2   aby
a   b   x   3   abx
a   b   c   3   abc
</code>```

Expected result set:

```<code>KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      3
abc  ADD      3
abe  REMOVE   3
aby  REMOVE   3
</code>```

And what if the day is not sequential. For example:

```<code>P1  P2  P3  DAY  KEY

a   b   c   1    abc
a   b   e   2    abe
a   b   y   2    aby
a   b   x   5    abx
a   b   c   5    abc
</code>```

And the expected result is:

```<code>KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      5
abc  ADD      5
abe  REMOVE   5
aby  REMOVE   5
</code>```

答:
Here is an approach using lag() and lead(). The idea is to compare the previous and following date value for each key, and use that to identify the date when a key was added or removed - this assumes that day is a number that increments sequentially, without gaps.

```<code>with cte as (
    select
        t.*,
        lag(day) over(partition by p1, p2, p3 order by day) lag_day,
        lead(day) over(partition by p1, p2, p3 order by day) lead_day
    from mytable t
)
select p1, p2, p3, day, 'add' event
from cte
where lag_day is null or lag_day <> day - 1
union all
select p1, p2, p3, day + 1, 'remove'
from cte
where lead_day is null or lead_day <> day + 1
order by day, p1, p2, p3
</code>```

With your sample data in this db fiddle, this produces:

```
P1 | P2 | P3 | DAY | EVENT
:- | :- | :- | --: | :-----
a  | b  | c  |   1 | add
a  | b  | c  |   2 | remove
a  | b  | e  |   2 | add
a  | b  | y  |   2 | add
a  | b  | c  |   3 | add
a  | b  | e  |   3 | remove
a  | b  | x  |   3 | add
a  | b  | y  |   3 | remove
a  | b  | c  |   4 | remove
a  | b  | x  |   4 | remove
```

This seems more complete that your expected results. Note that all records still available on the last date appear as removed on the following (hypothetical) day - this seems consistent with the fact that all new records appear as added on the first day.

I did not use the pseudo-key, because it don't see how it helps - and, if the values had more than one character, it could lead into trouble by creating "false" duplicates.

Body:
Suppose I have the below table. They key is just concat P1, P2, P3. I want to compare between key for each day. for example, from day 1 to day2, abc is removed and abe, aby is added.

P1  P2  P3  DAY KEY

a   b   c   1   abc
a   b   e   2   abe
a   b   y   2   aby
a   b   x   3   abx
a   b   c   3   abc

Expected result set:

KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      3
abc  ADD      3
abe  REMOVE   3
aby  REMOVE   3

And what if the day is not sequential. For example:

P1  P2  P3  DAY  KEY

a   b   c   1    abc
a   b   e   2    abe
a   b   y   2    aby
a   b   x   5    abx
a   b   c   5    abc

And the expected result is:

KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      5
abc  ADD      5
abe  REMOVE   5
aby  REMOVE   5

Body:
Here is an approach using lag() and lead(). The idea is to compare the previous and following date value for each key, and use that to identify the date when a key was added or removed - this assumes that day is a number that increments sequentially, without gaps.

with cte as (
    select
        t.*,
        lag(day) over(partition by p1, p2, p3 order by day) lag_day,
        lead(day) over(partition by p1, p2, p3 order by day) lead_day
    from mytable t
)
select p1, p2, p3, day, 'add' event
from cte
where lag_day is null or lag_day <> day - 1
union all
select p1, p2, p3, day + 1, 'remove'
from cte
where lead_day is null or lead_day <> day + 1
order by day, p1, p2, p3

With your sample data in this db fiddle, this produces:

P1 | P2 | P3 | DAY | EVENT
:- | :- | :- | --: | :-----
a  | b  | c  |   1 | add
a  | b  | c  |   2 | remove
a  | b  | e  |   2 | add
a  | b  | y  |   2 | add
a  | b  | c  |   3 | add
a  | b  | e  |   3 | remove
a  | b  | x  |   3 | add
a  | b  | y  |   3 | remove
a  | b  | c  |   4 | remove
a  | b  | x  |   4 | remove

This seems more complete that your expected results. Note that all records still available on the last date appear as removed on the following (hypothetical) day - this seems consistent with the fact that all new records appear as added on the first day.

I did not use the pseudo-key, because it don't see how it helps - and, if the values had more than one character, it could lead into trouble by creating "false" duplicates.


问:
DependencyService.Get returns null when setting is "Link All"
My Xamarin.iOS app (Xamarin.Forms) runs fine as long as I have the iOS project's properties -> iOS Build -> Linker Behavior set to "Don't Link" or "Link Framework SDKs only". But when it's set to "Link All" - DependencyService.Get<ISomething>(); returns null.

Why is that? / How do I fix that?

答:
the Linker can't tell that a class you only instantiate via DI is actually being used.  To get around that, add the Preserve attribute to your class</p>

```<code>[Preserve (AllMembers = true)]
</code>```

Body:
the Linker can't tell that a class you only instantiate via DI is actually being used.  To get around that, add the Preserve attribute to your class

[Preserve (AllMembers = true)]


问:
Stuck with Javascript! - How do I use an If statement to update an element and an array?
I am trying to build a shopping cart function for a project.

This is what I am being asked to do:

Inside the if statement, update the orderTotal element to display Total: $ and the sum of all the prices inside the cartItems array.

1) Under the IF statement I am then entering: orderTotal.innerHTML = "Total: $"
2) At this point I get stuck as I do not know how to add the sum of all prices in the array?

Please help!

var cartItems = [];
var isTotalHidden = true;

var backpack = {
 name: "Backpack",
 price: 400
}

var camera = {
 name: "Camera",
 price: 300
}

function addToCart(item) {
 cartItems.push(item);
 document.getElementById("itemCounter").innerHTML = cartItems.length;
 showTotal();
}

function clickCart() {
 isTotalHidden = !isTotalHidden;
 showTotal();
}

function showTotal() {
 var orderTotal = document.getElementById("orderTotal");
 orderTotal.innerHTML = "";

 if (isTotalHidden === false) {

 }
}```

答:
I assume you dont know how to access properties of objects?
As example:
to get the price of the camera (which is a JS objects) you need to either use the property-name like this objectName.propertyName so camera.price or this objectName["propertyName"] so camera["price"]

I think with this knowledge you can awnser the question yourself rather than copy/pasting someone elses code and learning nothing


问:
Is it possible to use VSCode language-server-protocol engine along with the Vim or NeoVim?
I have tried different code-analysis engines and tools (like tern_for_vim) for Vim, but they do not provide such a great autocompletion, goto and rename functionality as in VSCode.
As I know VSCode uses language-server-protocol technology to provide IDE functionality. So here is my question:

Is it possible to use VSCode language-server-protocol engine inside the Vim or NeoVim? In other words, it is possible to provide the same good quality of IDE-like functionality as VSCode do?

I have tried javascript-typescript-langserver with deoplete.vim, but the quality of autocompletion and goto-declaration was bad.

答:
Yes, you can use it via coc.nvim installing which is a fork of VSCode. You then apply one of its packages for a specific language eg coc-python.

This is the installation guide for coc.nvim. You then need to install the language package with this command in (Neo)Vim:

```<code>:CocInstall coc-python
</code>```

You can then use the default VS Code completion engine immediately (jedi) or upgrade to what will become its successor, MSPLS:

For MSPLS run the command :CocConfig and enter this in to the file which is opened:

```<code>{
    "python.jediEnabled": false
}
</code>```

Then run :CocRestart

There are other other engines like coc.nvim such as YouCompleteMe. They all have small variations / tailoring for specific languages.

Body:
Yes, you can use it via coc.nvim installing which is a fork of VSCode. You then apply one of its packages for a specific language eg coc-python.

This is the installation guide for coc.nvim. You then need to install the language package with this command in (Neo)Vim:

:CocInstall coc-python

You can then use the default VS Code completion engine immediately (jedi) or upgrade to what will become its successor, MSPLS:

For MSPLS run the command :CocConfig and enter this in to the file which is opened:

{
    "python.jediEnabled": false
}

Then run :CocRestart

There are other other engines like coc.nvim such as YouCompleteMe. They all have small variations / tailoring for specific languages.


问:
fetch multiple image source before render react native
I would like show image on my markers, but it works only when I use the icon attribute of the marker. I need to use the subview to manage the style. When I use the ICON attribute, the view image appear (so I have two image on the map) but not showing when it's in comment.

This how I fetch the data and update the state.

```<code>componentDidMount(){
  getmarkers().then(data => {
    let test = []
    data.forEach(element => {
      test.push(
        {
          latlng:
          {
            latitude: JSON.parse(element.latitude),
            longitude: JSON.parse(element.longitude)
          },
          name: JSON.parse(element.images)[0],
          id: element.id,
          image: JSON.parse(element.images)[0]
        }
      )
    });

    this.setState({ markers: test, loaded: true })

  })
}
</code>```

}

This is my view

```<code>            {this.state.markers.map((marker, i) => (
          <Marker
            key={i}
            coordinate={marker.latlng}
            title={marker.name}
            description={marker.name}
            tracksViewChanges={false}
          // icon={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image}}
          >

            <View>
              <Image source={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image }} style={{ width: 40, height: 40, borderRadius: 6 }} />
            </View>

          </Marker>
        ))}
</code>```

答:
const customMarkerImage = require("../../../customMarkerImage.png");
```

```<MapView.Marker>
  <View >
    <Image source={customMarkerImage} onLoad={() => this.forceUpdate()}>
    </Image>
  </View>
</MapView.Marker>
```

It is probably about this issue : https://github.com/react-native-community/react-native-maps/issues/924

Body:
I would like show image on my markers, but it works only when I use the icon attribute of the marker. I need to use the subview to manage the style. When I use the ICON attribute, the view image appear (so I have two image on the map) but not showing when it's in comment.

This how I fetch the data and update the state.

componentDidMount(){
  getmarkers().then(data => {
    let test = []
    data.forEach(element => {
      test.push(
        {
          latlng:
          {
            latitude: JSON.parse(element.latitude),
            longitude: JSON.parse(element.longitude)
          },
          name: JSON.parse(element.images)[0],
          id: element.id,
          image: JSON.parse(element.images)[0]
        }
      )
    });

    this.setState({ markers: test, loaded: true })

  })
}

}

This is my view

            {this.state.markers.map((marker, i) => (
          <Marker
            key={i}
            coordinate={marker.latlng}
            title={marker.name}
            description={marker.name}
            tracksViewChanges={false}
          // icon={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image}}
          >

            <View>
              <Image source={{ uri: 'https://www.testeed.com/uploads/minifiedplaces/' + marker.image }} style={{ width: 40, height: 40, borderRadius: 6 }} />
            </View>

          </Marker>
        ))}

Body:
const customMarkerImage = require("../../../customMarkerImage.png");

<MapView.Marker>
  <View >
    <Image source={customMarkerImage} onLoad={() => this.forceUpdate()}>
    </Image>
  </View>
</MapView.Marker>

It is probably about this issue : https://github.com/react-native-community/react-native-maps/issues/924


问:
How to get Last record from Sqlite?
I have a one table question_table and one ImageButton (Back). I need to get the last inserted record from the database after clicking on the Back.

My row contains the following columns: question, optionA, optionB, optionC, optionD, and I need the data for use on my Activity. I create one method in database but it's not working.

Here is code for reference:

MySQLiteHelper.java extract:

```<code>public List<ObjectiveWiseQuestion> getLastInsertQuestion()
{
    // long index = 0;
    List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
    db = getReadableDatabase();
    Cursor cursor = db.query(
            "sqlite_sequence",
            new String[]{"seq"},
            "name = ?",
            new String[]{TABLE_QUESTION},
            null,
            null,
            null,
            null );

    if (cursor.moveToFirst())
    {
        do {
            ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();

            owq.setQuestion(cursor.getString(2));
            owq.setOptionA(cursor.getString(3));
            owq.setOptionB(cursor.getString(4));
            owq.setOptionC(cursor.getString(5));
            owq.setOptionD(cursor.getString(6));
            owq.setCorrectOption(cursor.getString(7));
            LocwiseProfileList.add(owq);
        } while(cursor.moveToNext());

        db.close();
    }

    return LocwiseProfileList;
}
</code>```

OnClickListner from AddQuestionActivity.java

```<code>imgBack.setOnClickListener( new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        msg();
        emptyFormField();

        try {
            final List<ObjectiveWiseQuestion> LocWiseProfile =  db.getLastInsertQuestion();

            for (final ObjectiveWiseQuestion cn : LocWiseProfile)
            {
                db=new MySQLiteHelper(getBaseContext());
                db.getWritableDatabase();
                txtQuestion.setText(cn.getQuestion());
                txtOptionA.setText(cn.getOptionA());
                txtOptionB.setText(cn.getOptionB());
                txtOptionC.setText(cn.getOptionC());
                txtOptionD.setText(cn.getOptionD());
                txtCorrectOption.setText(cn.getCorrectOption());
                db.close();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
});
</code>```

Please give me some hint.

答:
Another option is to use SQLites LAST_VALUE() function in the following way.

Given this table:

```<code>+--------+---------+-------+
| OBJECT |  STATUS |  TIME |
+--------+---------+-------+
|        |         |       |
| 1      |  ON     |  100  |
|        |         |       |
| 1      |  OFF    |  102  |
|        |         |       |
| 1      |  ON     |  103  |
|        |         |       |
| 2      |  ON     |  101  |
|        |         |       |
| 2      |  OFF    |  102  |
|        |         |       |
| 2      |  ON     |  103  |
|        |         |       |
| 3      |  OFF    |  102  |
|        |         |       |
| 3      |  ON     |  103  |
+--------+---------+-------+
</code>```

You can get the last status of every object with the following query

SELECT
    DISTINCT OBJECT,             -- Only unique rows
    LAST_VALUE(STATUS) OVER (    -- The last value of the status column
        PARTITION BY OBJECT      -- Taking into account rows with the same value in the object column
        ORDER by time asc        -- "Last" when sorting the rows of every object by the time column in ascending order
        RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING    -- Take all rows in the patition
    ) as lastStatus
FROM
    TABLE
```

<p>The result would look like:</p>

```+--------+--------------+
| OBJECT |  LAST_STATUS |
+--------+--------------+
|        |              |
| 1      |  ON          |
|        |              |
| 2      |  ON          |
|        |              |
| 3      |  ON          |
+--------+--------------+
```

Title: How to get Last record from Sqlite?

Body:
I have a one table question_table and one ImageButton (Back). I need to get the last inserted record from the database after clicking on the Back.

My row contains the following columns: question, optionA, optionB, optionC, optionD, and I need the data for use on my Activity. I create one method in database but it's not working.

Here is code for reference:

MySQLiteHelper.java extract:

public List<ObjectiveWiseQuestion> getLastInsertQuestion()
{
    // long index = 0;
    List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
    db = getReadableDatabase();
    Cursor cursor = db.query(
            "sqlite_sequence",
            new String[]{"seq"},
            "name = ?",
            new String[]{TABLE_QUESTION},
            null,
            null,
            null,
            null );

    if (cursor.moveToFirst())
    {
        do {
            ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();

            owq.setQuestion(cursor.getString(2));
            owq.setOptionA(cursor.getString(3));
            owq.setOptionB(cursor.getString(4));
            owq.setOptionC(cursor.getString(5));
            owq.setOptionD(cursor.getString(6));
            owq.setCorrectOption(cursor.getString(7));
            LocwiseProfileList.add(owq);
        } while(cursor.moveToNext());

        db.close();
    }

    return LocwiseProfileList;
}

OnClickListner from AddQuestionActivity.java

imgBack.setOnClickListener( new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        msg();
        emptyFormField();

        try {
            final List<ObjectiveWiseQuestion> LocWiseProfile =  db.getLastInsertQuestion();

            for (final ObjectiveWiseQuestion cn : LocWiseProfile)
            {
                db=new MySQLiteHelper(getBaseContext());
                db.getWritableDatabase();
                txtQuestion.setText(cn.getQuestion());
                txtOptionA.setText(cn.getOptionA());
                txtOptionB.setText(cn.getOptionB());
                txtOptionC.setText(cn.getOptionC());
                txtOptionD.setText(cn.getOptionD());
                txtCorrectOption.setText(cn.getCorrectOption());
                db.close();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
});

Please give me some hint.

Body:
Another option is to use SQLites LAST_VALUE() function in the following way.

Given this table:

+--------+---------+-------+
| OBJECT |  STATUS |  TIME |
+--------+---------+-------+
|        |         |       |
| 1      |  ON     |  100  |
|        |         |       |
| 1      |  OFF    |  102  |
|        |         |       |
| 1      |  ON     |  103  |
|        |         |       |
| 2      |  ON     |  101  |
|        |         |       |
| 2      |  OFF    |  102  |
|        |         |       |
| 2      |  ON     |  103  |
|        |         |       |
| 3      |  OFF    |  102  |
|        |         |       |
| 3      |  ON     |  103  |
+--------+---------+-------+

You can get the last status of every object with the following query

SELECT
    DISTINCT OBJECT,             -- Only unique rows
    LAST_VALUE(STATUS) OVER (    -- The last value of the status column
        PARTITION BY OBJECT      -- Taking into account rows with the same value in the object column
        ORDER by time asc        -- "Last" when sorting the rows of every object by the time column in ascending order
        RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING    -- Take all rows in the patition
    ) as lastStatus
FROM
    TABLE

The result would look like:

+--------+--------------+
| OBJECT |  LAST_STATUS |
+--------+--------------+
|        |              |
| 1      |  ON          |
|        |              |
| 2      |  ON          |
|        |              |
| 3      |  ON          |
+--------+--------------+


问:
Opencart 3 disable date in title
I have a question about setting up a meta description in Opencart.
For some products, the current date is automatically copied to the meta description.

I tried google, but without effect.

I think there is a problem somewhere in the template, but I don't know exactly.

SEO plugin: https://www.opencart.com/index.php?route=marketplace/extension/info&token=1a815f591c29d028150b050f02915db4&extension_id=16633

thank you for the advice

答:
I think, your template is fine. Little correction, you have an issue with <title> tag, not meta description. All you have to check is SEO Extensions > SEO On-Page Tags Generator, tab Product Templates. Inspect META TITLE TEMPLATES for any suspicious templates with date. Then on tab Dashboard of a current module on Product Pages: Meta Title press Generate.

Hope this will help. If no - it's better to receive demo access to your website.

Title: Opencart 3 disable date in title


问:
(jQuery) Calc distance element inside DIV
I have element
 and inside second element
. I want calc distance element
 to the top first div in jQuery.

```<code><div id="container">

   <br><br><br><br><br><br><br><br>

  <div id="element"></div>

</div>
</code>```

How i can do this?

答:
You can use jQuery's position() to calculate the difference between the position of the two elements.

```<code>var dist = $('#element').position().top - $('#container').position().top;
</code>```

Here is a fiddle: https://jsfiddle.net/BenjaminRay/5ucvb91x/

Body:
I have element
 and inside second element
. I want calc distance element
 to the top first div in jQuery.

How i can do this?

Body:
You can use jQuery's position() to calculate the difference between the position of the two elements.

var dist = $('#element').position().top - $('#container').position().top;

Here is a fiddle: https://jsfiddle.net/BenjaminRay/5ucvb91x/


问:
If filename matches pattern do something (for-loop, case-statement)
The local file tree:

```<code>/pdf/Insurance.January.2020.pdf
/pdf/Insurance.February.2020.pdf
/pdf/Provider1.March.2020.pdf
/pdf/Provider2.April.2020.pdf
</code>```

The remote file tree:

```<code>/invoice/Insurance/2019/January/Insurance.January.2019.pdf
/invoice/Insurance/2020/February/Insurance.February.2020.pdf
/invoice/Provider1/.....
</code>```

What I want:
I want to (r)sync my local PDF-files with the remote folders by matching patterns like Name, Year and maybe Month.

I thought I can solve this with a for-loop and case-statements:

```<code>for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME=${FILE##*/}          # cut only filename
    case "$FILENAME" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done
</code>```

But now I think this is not the fastest way because I've to write a lot of lines to find a match. And I also need to "re-match" Year and Month.

Has someone another idea? Thanks!

答:
if your file names are always the same pattern you can use cut with delimiter -d . and read the column -f into separate variable

you don't even need case but if you want to sort month in right order you can do it like that

(run this script inside pdf/ folder)

```<code>#!/usr/bin/env bash

for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME="${FILE##*/}"         # cut only filename

    target="$(echo -e "$FILENAME" | cut -d. -f1)" # matching pattern in filename
    month="$(echo -e "$FILENAME" | cut -d. -f2)"
    year="$(echo -e "$FILENAME" | cut -d. -f3)"

    # delete this if not needed
    case "$month" in
        Jan*)
            month="01.$month"
            ;;
        Feb*)
            month="02.$month"
            ;;
        Mar*)
            month="03.$month"
            ;;
        Apr*)
            month="04.$month"
            ;;
        May*)
            month="05.$month"
            ;;
        Jun*)
            month="06.$month"
            ;;
        Jul*)
            month="07.$month"
            ;;
        Aug*)
            month="08.$month"
            ;;
        Sep*)
            month="09.$month"
            ;;
        Oct*)
            month="10.$month"
            ;;
        Nov*)
            month="11.$month"
            ;;
        Dec*)
            month="12.$month"
            ;;
    esac

    targetpath="../invoice/$target/$year/$month"
    mkdir -p "$targetpath"

    rsync -uxi --noatime "$FILE" "$targetpath"
done

exit 0
</code>```

use the separated variables for folder names.

create the folders with mkdir -p

finally call rsync <SRC> <DEST> with some options

-u only newer files

-x stay on filesystem

-i display file names

--noatime keep last access date

(see rsync --help for recommended options)

Body:
The local file tree:

/pdf/Insurance.January.2020.pdf
/pdf/Insurance.February.2020.pdf
/pdf/Provider1.March.2020.pdf
/pdf/Provider2.April.2020.pdf

The remote file tree:

/invoice/Insurance/2019/January/Insurance.January.2019.pdf
/invoice/Insurance/2020/February/Insurance.February.2020.pdf
/invoice/Provider1/.....

What I want:
I want to (r)sync my local PDF-files with the remote folders by matching patterns like Name, Year and maybe Month.

I thought I can solve this with a for-loop and case-statements:

for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME=${FILE##*/}          # cut only filename
    case "$FILENAME" in
        [Ii]nsurance*)             # matching pattern in filename
            rsync command
            ;;
        Provider1*)
            rsync command
            ;;
        ...
        ...
    esac
done

But now I think this is not the fastest way because I've to write a lot of lines to find a match. And I also need to "re-match" Year and Month.

Has someone another idea? Thanks!

Body:
if your file names are always the same pattern you can use cut with delimiter -d . and read the column -f into separate variable

you don't even need case but if you want to sort month in right order you can do it like that

(run this script inside pdf/ folder)

#!/usr/bin/env bash

for FILE in ./*.pdf; do
    [[ ! -f "$FILE" ]] && continue # check if $FILE is a file
    FILENAME="${FILE##*/}"         # cut only filename

    target="$(echo -e "$FILENAME" | cut -d. -f1)" # matching pattern in filename
    month="$(echo -e "$FILENAME" | cut -d. -f2)"
    year="$(echo -e "$FILENAME" | cut -d. -f3)"

    # delete this if not needed
    case "$month" in
        Jan*)
            month="01.$month"
            ;;
        Feb*)
            month="02.$month"
            ;;
        Mar*)
            month="03.$month"
            ;;
        Apr*)
            month="04.$month"
            ;;
        May*)
            month="05.$month"
            ;;
        Jun*)
            month="06.$month"
            ;;
        Jul*)
            month="07.$month"
            ;;
        Aug*)
            month="08.$month"
            ;;
        Sep*)
            month="09.$month"
            ;;
        Oct*)
            month="10.$month"
            ;;
        Nov*)
            month="11.$month"
            ;;
        Dec*)
            month="12.$month"
            ;;
    esac

    targetpath="../invoice/$target/$year/$month"
    mkdir -p "$targetpath"

    rsync -uxi --noatime "$FILE" "$targetpath"
done

exit 0

use the separated variables for folder names.

create the folders with mkdir -p

finally call rsync <SRC> <DEST> with some options

-u only newer files

-x stay on filesystem

-i display file names

--noatime keep last access date

(see rsync --help for recommended options)


问:
firestore returning null react native android
Im trying to display the contents of my firestore database, its working perfectly on ios but android is null, i've followed the instructions on https://rnfirebase.io/ for the android set up to the T and i've created multiple new apps to no avail.

Firebase is acknowledging that there are 2 apps connected but no matter what I do, nothing is being shown.

Ive updated the rules to accept any connections but still nothing.
Has anyone else run into this problem? Any information needed can be provided, but seeing as the app is working fine on ios i'm going crazy trying to figure out whats wrong

```<code>export default function Products(){
const [loading, setLoading] = useState(true);
const [products, setProducts] = useState([]);

useEffect(() => {
    const subscriber = firestore()
    .collection('products')
    .onSnapshot(querySnapshot => {
        const products = [];

        querySnapshot.forEach(documentSnapshot => {
            products.push({
                ...documentSnapshot.data(),
                key: documentSnapshot.id,
            });
        });
        setProducts(products);
        setLoading(false);
    });

    return () => subscriber();
}, []);

return(
    <View>
        <Text>Top</Text>
         <FlatList
        data={products}
        renderItem={({ item }) => (
        <View style={{height: 50, flex: 1, alignItems: 'center', justifyContent: 'center'}}>
            <Text>Product ID: {item.key}</Text>
            <Text>Product Name: {item.name}</Text>
        </View>

    )}
    />
    <Text>Bottom</Text>
    </View>
);
</code>```

}

答:
Damn, the internet on the android emulator wasn't working (can see in the picture the little x by the wifi cone), followed this post Android Studio - Android Emulator Wifi Connected with No Internet

Make sure to delete and reinstall the emulator and you'll be good to go

Body:
Im trying to display the contents of my firestore database, its working perfectly on ios but android is null, i've followed the instructions on https://rnfirebase.io/ for the android set up to the T and i've created multiple new apps to no avail.

Firebase is acknowledging that there are 2 apps connected but no matter what I do, nothing is being shown.

Ive updated the rules to accept any connections but still nothing.
Has anyone else run into this problem? Any information needed can be provided, but seeing as the app is working fine on ios i'm going crazy trying to figure out whats wrong

export default function Products(){
const [loading, setLoading] = useState(true);
const [products, setProducts] = useState([]);

useEffect(() => {
    const subscriber = firestore()
    .collection('products')
    .onSnapshot(querySnapshot => {
        const products = [];

        querySnapshot.forEach(documentSnapshot => {
            products.push({
                ...documentSnapshot.data(),
                key: documentSnapshot.id,
            });
        });
        setProducts(products);
        setLoading(false);
    });

    return () => subscriber();
}, []);

return(
    <View>
        <Text>Top</Text>
         <FlatList
        data={products}
        renderItem={({ item }) => (
        <View style={{height: 50, flex: 1, alignItems: 'center', justifyContent: 'center'}}>
            <Text>Product ID: {item.key}</Text>
            <Text>Product Name: {item.name}</Text>
        </View>

    )}
    />
    <Text>Bottom</Text>
    </View>
);

}


问:
Custom serialization in Kafka using CSharp
I want to write a custom serializer for kafka in CSharp. I've searched a lot and I couldn't find a good reference on how to write custom serializer for kafka in a dotnet language.

Any thoughts on how to write one with dotnet?

答:
I just find the answer to this question.
The library to use for kafka in dotnet is provided by confluent.

Kafka .NET Client

There should be a serialization class implementing the interface :

```<code>Confluent.Kafka.ISerializer<T>
</code>```

Normally we should create the producer via ProducerBuilder class :

```<code>Confluent.Kafka.ProducerBuilder<TKey, TValue>
</code>```

There is a method to this class to set serializers for both key and value.
It is a little different than the original documentation for custom serializer in Kafka which instructing to set the name of the custom serializer class in the producer configuration.

Following is the code to set the value serializer:

```<code>var config = new ProducerConfig
{
    BootstrapServers = "localhost:9092",
    ClientId = "thiPC"
};

var producerBuilder = new ProducerBuilder<Null, Customer>(config);
producerBuilder.SetValueSerializer(new CustomerSerializer());       // <------ The Magic Code
var producer = producerBuilder.Build();
</code>```

The sample code for the Serialization class is like this;

```<code>public class CustomerSerializer : Confluent.Kafka.ISerializer<Customer>
{
    public byte[] Serialize(Customer data, SerializationContext context)
    { ..........}
}
</code>```

There is nothing important for the Customer class in my example it is a normal class just to hold the customer properties.

In serialization class, you should return a byte[] in the Serialize method which is obvious!

I hope this would be useful for folks implementing Kafka with dotnet.

Body:
I just find the answer to this question.
The library to use for kafka in dotnet is provided by confluent.

Kafka .NET Client

There should be a serialization class implementing the interface :

Confluent.Kafka.ISerializer<T>

Normally we should create the producer via ProducerBuilder class :

Confluent.Kafka.ProducerBuilder<TKey, TValue>

There is a method to this class to set serializers for both key and value.
It is a little different than the original documentation for custom serializer in Kafka which instructing to set the name of the custom serializer class in the producer configuration.

Following is the code to set the value serializer:

var config = new ProducerConfig
{
    BootstrapServers = "localhost:9092",
    ClientId = "thiPC"
};

var producerBuilder = new ProducerBuilder<Null, Customer>(config);
producerBuilder.SetValueSerializer(new CustomerSerializer());       // <------ The Magic Code
var producer = producerBuilder.Build();

The sample code for the Serialization class is like this;

public class CustomerSerializer : Confluent.Kafka.ISerializer<Customer>
{
    public byte[] Serialize(Customer data, SerializationContext context)
    { ..........}
}

There is nothing important for the Customer class in my example it is a normal class just to hold the customer properties.

In serialization class, you should return a byte[] in the Serialize method which is obvious!

I hope this would be useful for folks implementing Kafka with dotnet.


问:
JavaScript URL Decode function
What's the best JavaScript URL decode utility?  Encoding would be nice too and working well with jQuery is an added bonus.</p>

答:
decodeURIComponent() is fine, but you never want ot use encodeURIComponent() directly.  This fails to escape reserved characters like *, !, ', (, and ).  Check out RFC3986, where this is defined, for more info on that.  The Mozilla Developer Network documentation gives both a good explanation and a solution.  Explanation...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

Solution...

```<code>function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}
</code>```

In case you're not sure, check out a good, working demo at JSBin.com.  Compare this with a bad, working demo at JSBin.com using encodeURIComponent() directly.

Good code results:

thing%2athing%20thing%21

Bad code results from encodeURIComponent():

thing*thing%20thing!

ContentLicense: CC BY-SA 2.5

Title: JavaScript URL Decode function

Body:
decodeURIComponent() is fine, but you never want ot use encodeURIComponent() directly.  This fails to escape reserved characters like *, !, ', (, and ).  Check out RFC3986, where this is defined, for more info on that.  The Mozilla Developer Network documentation gives both a good explanation and a solution.  Explanation...

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

Solution...

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

In case you're not sure, check out a good, working demo at JSBin.com.  Compare this with a bad, working demo at JSBin.com using encodeURIComponent() directly.

Good code results:

thing%2athing%20thing%21

Bad code results from encodeURIComponent():

thing*thing%20thing!


问:
I need some help trying to sort a list of strings but at a particular index on that list
I would appreciate some help with a python piece of code im having issues with.

I have a list which contains strings. Here is a snippet of the list. It is a lot longer though.

```<code>[['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]
</code>```

What i am trying to do is to sort the list at index 3 (so the values '155.04' , '118.6' etc). I have tried the following, which doesn't work since i have floats as string i presume.

```<code>sorted(list, key=itemgetter(3), reverse=True)
</code>```

I've looked into using sort() and sorted() but i cant seem to find a way to both sort ints as strings and also at a particular index.There are no error messages, its just not in the correct order.

答:
You can use a lambda to convert to float just for the comparison

```<code>values = [['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]
values = sorted(values, key=lambda x:float(x[3]), reverse=True)
# values stays the same the data is already reverse sorted by the 4th value
</code>```

Body:
I would appreciate some help with a python piece of code im having issues with.

I have a list which contains strings. Here is a snippet of the list. It is a lot longer though.

[['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]

What i am trying to do is to sort the list at index 3 (so the values '155.04' , '118.6' etc). I have tried the following, which doesn't work since i have floats as string i presume.

sorted(list, key=itemgetter(3), reverse=True)

I've looked into using sort() and sorted() but i cant seem to find a way to both sort ints as strings and also at a particular index.There are no error messages, its just not in the correct order.

Body:
You can use a lambda to convert to float just for the comparison

values = [['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]
values = sorted(values, key=lambda x:float(x[3]), reverse=True)
# values stays the same the data is already reverse sorted by the 4th value


问:
Non busy waiting for ZeroMQ?
I have some simple PUB/SUB code using the ZeroMQ library. Essentially just waiting infinitely for messages to be returned.

However, this seems to be busy waiting as while waiting to receive a message, pythons CPU usage raises dramatically.

Is there a better way to do this? I imagined this would be like on a socket when you call receive, it isn't constantly executing instructions and wasting CPU.

```<code>import sys
import zmq

port = "5556"
if len(sys.argv) > 1:
    port =  sys.argv[1]
    int(port)

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)

print "Collecting updates from weather server..."
socket.connect ("tcp://localhost:%s" % port)

# Subscribe to zipcode, default is NYC, 10001
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

# Process 5 updates
total_value = 0
for update_nbr in range (5):
    string = socket.recv()
    topic, messagedata = string.split()
    total_value += int(messagedata)
    print ('{} {}'.format(topic, message)
</code>```

答:
Q : "Non busy waiting for ZeroMQ?"

Sure.

```<code>...
for update_nbr in range( 5 ):
    print "{0:} A hunt for message started".format( time.ctime() )
    while True: # .............................................. poll() + wait
          if ( 0 == socket.poll( 1000 ) ):
               print "\n.",
          else:
               break # we've got a message .....................
    print "\n{0:} A message came".format( time.ctime() )
    #_________________________________________
    try:
        string = socket.recv( zmq.NOBLOCK )
        topic, messagedata = string.split()
        total_value += int( messagedata )
        print '{} {}'.format( topic, message )

    except:
        print 'EXC:...'

    finally:
        pass
    #_________________________________________
</code>```

Title: Non busy waiting for ZeroMQ?

Body:
I have some simple PUB/SUB code using the ZeroMQ library. Essentially just waiting infinitely for messages to be returned.

However, this seems to be busy waiting as while waiting to receive a message, pythons CPU usage raises dramatically.

Is there a better way to do this? I imagined this would be like on a socket when you call receive, it isn't constantly executing instructions and wasting CPU.

import sys
import zmq

port = "5556"
if len(sys.argv) > 1:
    port =  sys.argv[1]
    int(port)

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)

print "Collecting updates from weather server..."
socket.connect ("tcp://localhost:%s" % port)

# Subscribe to zipcode, default is NYC, 10001
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

# Process 5 updates
total_value = 0
for update_nbr in range (5):
    string = socket.recv()
    topic, messagedata = string.split()
    total_value += int(messagedata)
    print ('{} {}'.format(topic, message)

Body:
Q : "Non busy waiting for ZeroMQ?"

Sure.

...
for update_nbr in range( 5 ):
    print "{0:} A hunt for message started".format( time.ctime() )
    while True: # .............................................. poll() + wait
          if ( 0 == socket.poll( 1000 ) ):
               print "\n.",
          else:
               break # we've got a message .....................
    print "\n{0:} A message came".format( time.ctime() )
    #_________________________________________
    try:
        string = socket.recv( zmq.NOBLOCK )
        topic, messagedata = string.split()
        total_value += int( messagedata )
        print '{} {}'.format( topic, message )

    except:
        print 'EXC:...'

    finally:
        pass
    #_________________________________________


答:
Your sort-key has to convert the last element of each sublist to a float.

```<code>>>> sorted(lst, key=lambda sublist: float(sublist[-1]), reverse=True)
[['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]
</code>```

You could write that lambda function as a non-anonymous function for readability

```<code>def last_as_float(lst):
    return float(lst[-1])
</code>```

and then pass key=last_as_float.

Title: I need some help trying to sort a list of strings but at a particular index on that list

Body:
Your sort-key has to convert the last element of each sublist to a float.

>>> sorted(lst, key=lambda sublist: float(sublist[-1]), reverse=True)
[['AAPL', '1d', '58.82', '155.04'], ['MSFT', '1d', '63.16', '118.6']]

You could write that lambda function as a non-anonymous function for readability

def last_as_float(lst):
    return float(lst[-1])

and then pass key=last_as_float.


问:
Prevent negative animated value on scroll
I have header collapsed on scroll event. On ios scroll offset value can be negative and it cause problem.

Is there any way to prevent animated value being negative?

Here is my code

```<code>const ScrollYDiffClamp = Animated.diffClamp(positionY, 0, 60);

const headerTranslate = ScrollYDiffClamp.interpolate({
  inputRange: [0, 1],
  outputRange: [0, -1],
});

return (
 <>
   <Header style={{transform: [{translateY: headerTranslate}]}}/>
   <Animated.ScrollView
      onScroll={Animated.event([{nativeEvent: {contentOffset: {y: positionY}}}], {
     useNativeDriver: true,
   })}>

   </Animated.ScrollView>
 </>
</code>```

)

答:
Try adding this to your interpolation configuration.

extrapolate: "clamp"
```

Body:
I have header collapsed on scroll event. On ios scroll offset value can be negative and it cause problem.

Is there any way to prevent animated value being negative?

Here is my code

const ScrollYDiffClamp = Animated.diffClamp(positionY, 0, 60);

const headerTranslate = ScrollYDiffClamp.interpolate({
  inputRange: [0, 1],
  outputRange: [0, -1],
});

return (
 <>

   <Animated.ScrollView
      onScroll={Animated.event([{nativeEvent: {contentOffset: {y: positionY}}}], {
     useNativeDriver: true,
   })}>

   </Animated.ScrollView>
 </>

)