问:
Get a list of connected users
Using the shell, can I get a list of users connected?  I can get the number of connections using db.serverStatus().connections and I can get the host connection information using

```<code> db.currentOp(true).inprog.forEach(function(d){if (d.client)printjson(d.client)})
</code>```

However, I want to know if I can get the user that connected from the host as well?

答:
MongoDB 3.4.2

I've been hoping to find a command like MySQL's SHOW PROCESSLIST as well, to easily get just such information. Disappointingly, it looks like there is no function that will show you which users are currently connected, or, for a given past or present connection, which user initiated it. But with profiling enabled we can approximate some of that functionality by looking into the recent past.

In my case profiling is set to 2 globally (visible with db.getProfilingLevel()), so at some point in the life of each database a collection appears in it called "system.profile", which is a capped collection - i.e. records are only retained until the collection is full and then replaced on a first-in-first-out basis (see disclaimer below). This collection can be queried as usual and keeps a timestamp (ts) associated with each operation.

```<code>var all_dbs = db.runCommand({listDatabases:1});
var now = new Date();

// Modify the number of seconds for a larger or smaller time window
var just_now = new Date(now.getTime() - 1000);

all_dbs.databases.forEach(
    function(current_db) {

        // The condition there is to exclude internal commands executed by the user "__system"
        // To exclude this command itself, add  the condition "ns:{$not:/profile$/}"
        all_operations = db.getSiblingDB(current_db.name).system.profile.find({user:{$not:/^__/}});
        all_operations.forEach(
            function(operation) {
                if (operation.ts > just_now) {

                    // Remove the .substring(0,200) to unlimit output length
                    print(JSON.stringify(operation.ts),
                          JSON.stringify(operation.user),
                          JSON.stringify(operation.query||operation.command||operation.updateobj).substring(0,200));
}})});
</code>```

Output looks like this:

```<code>"1998-04-01T22:14:56.431Z" "<user>@admin" "<database>.<collection>" "{ insert: \"<collection>\", ordered: false, documents: ...
</code>```

Disclaimers:

I am sure this is not the best way to do this, and MongoDB is practically my only use for Javascript so I may have done things here that make real Javascript people clench their teeth. Teeth clenchers-- feel free to edit in better practices.

For instances with a lot of activity this does not work and instead this error is thrown. I guess find() returns results from system.profile and those results no longer exist by the time it finishes executing so it breaks. Executor error during find command: CappedPositionLost: CollectionScan died due to position in capped collection being deleted. Last seen record id: RecordId(19041841)

Title: Get a list of connected users

Body:
Using the shell, can I get a list of users connected?  I can get the number of connections using db.serverStatus().connections and I can get the host connection information using

 db.currentOp(true).inprog.forEach(function(d){if (d.client)printjson(d.client)})

However, I want to know if I can get the user that connected from the host as well?

Body:
MongoDB 3.4.2

I've been hoping to find a command like MySQL's SHOW PROCESSLIST as well, to easily get just such information. Disappointingly, it looks like there is no function that will show you which users are currently connected, or, for a given past or present connection, which user initiated it. But with profiling enabled we can approximate some of that functionality by looking into the recent past.

In my case profiling is set to 2 globally (visible with db.getProfilingLevel()), so at some point in the life of each database a collection appears in it called "system.profile", which is a capped collection - i.e. records are only retained until the collection is full and then replaced on a first-in-first-out basis (see disclaimer below). This collection can be queried as usual and keeps a timestamp (ts) associated with each operation.

var all_dbs = db.runCommand({listDatabases:1});
var now = new Date();

// Modify the number of seconds for a larger or smaller time window
var just_now = new Date(now.getTime() - 1000);

all_dbs.databases.forEach(
    function(current_db) {

        // The condition there is to exclude internal commands executed by the user "__system"
        // To exclude this command itself, add  the condition "ns:{$not:/profile$/}"
        all_operations = db.getSiblingDB(current_db.name).system.profile.find({user:{$not:/^__/}});
        all_operations.forEach(
            function(operation) {
                if (operation.ts > just_now) {

                    // Remove the .substring(0,200) to unlimit output length
                    print(JSON.stringify(operation.ts),
                          JSON.stringify(operation.user),
                          JSON.stringify(operation.query||operation.command||operation.updateobj).substring(0,200));
}})});

Output looks like this:

"1998-04-01T22:14:56.431Z" "<user>@admin" "<database>.<collection>" "{ insert: \"<collection>\", ordered: false, documents: ...

Disclaimers:

I am sure this is not the best way to do this, and MongoDB is practically my only use for Javascript so I may have done things here that make real Javascript people clench their teeth. Teeth clenchers-- feel free to edit in better practices.

For instances with a lot of activity this does not work and instead this error is thrown. I guess find() returns results from system.profile and those results no longer exist by the time it finishes executing so it breaks. Executor error during find command: CappedPositionLost: CollectionScan died due to position in capped collection being deleted. Last seen record id: RecordId(19041841)


来源: stackexchange

问:
How to set progressbar background
I have set the progressbar style using the below code.

I have declared the progressbar widget:

```<code> <ProgressBar
    android:id="@+id/loadProgress"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="20dip"
    android:max="100"
    android:progressDrawable="@drawable/load_progress"
    android:progress="0" />
</code>```

defined the "@drawable/load_progress"

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@android:id/background"
    android:drawable="@drawable/background_bk">
</item>
<item
    android:id="@android:id/progress"
    android:drawable="@drawable/progress_bk">
</item>

</layer-list>
</code>```

defined the "@drawable/background_bk" (it is red)

```<code><?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:angle="0"
    android:endColor="#ff0000"
    android:startColor="#ff0990" />

<stroke
    android:width="1dp"
    android:color="#ff0000" />

 </shape>
</code>```

defined the @drawable/progress_bk (it is green)

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:angle="0"
    android:endColor="#00ff00"
    android:startColor="#00ff00" />

<stroke
    android:width="1dp"
    android:color="#00ff00" />

</shape>
</code>```

The progressbar always shows totally green (which is how it should appear when the progress value is 100), even if I set the progress value to less than 100. Any input would be appreciated.

答:
Here is what I did to have a progress bar that was green with clear background:</p>

```<code>android:background="@color/white"
android:progressBackgroundTint="@color/white"
android:progressTint="@color/green_light"
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to set progressbar background

Body:
I have set the progressbar style using the below code.

I have declared the progressbar widget:

 <ProgressBar
    android:id="@+id/loadProgress"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="20dip"
    android:max="100"
    android:progressDrawable="@drawable/load_progress"
    android:progress="0" />

defined the "@drawable/load_progress"

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@android:id/background"
    android:drawable="@drawable/background_bk">
</item>
<item
    android:id="@android:id/progress"
    android:drawable="@drawable/progress_bk">
</item>

</layer-list>

defined the "@drawable/background_bk" (it is red)

<?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:angle="0"
    android:endColor="#ff0000"
    android:startColor="#ff0990" />

<stroke
    android:width="1dp"
    android:color="#ff0000" />

 </shape>

defined the @drawable/progress_bk (it is green)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
    android:angle="0"
    android:endColor="#00ff00"
    android:startColor="#00ff00" />

<stroke
    android:width="1dp"
    android:color="#00ff00" />

</shape>

The progressbar always shows totally green (which is how it should appear when the progress value is 100), even if I set the progress value to less than 100. Any input would be appreciated.

Body:
Here is what I did to have a progress bar that was green with clear background:

android:background="@color/white"
android:progressBackgroundTint="@color/white"
android:progressTint="@color/green_light"


问:
how to force subshell on level 2 be in own pgid?
Command below prints pid of subshell and subshell of subshell:

```<code>$ ( ( echo $BASHPID )& echo $BASHPID )& sleep 1
[1] 9885
9885
9887
[1]+  Done                    ( ( echo $BASHPID ) & echo $BASHPID )
</code>```

Now command below is more complicated, but it indicates that second subshell is in 'process group' of first subshell:

```<code>$ ( ( echo $$ $BASH_SUBSHELL $BASHPID ; export BBB=$BASHPID; ps -e -o pid,pgid,ppid,comm | grep -E "$$|$BBB|PGID" | grep -E "bash|PGID" )& echo $$ $BASH_SUBSHELL $BASHPID; sleep 1 )& sleep 1
[3] 9973
2787 1 9973
2787 2 9975
  PID  PGID  PPID COMMAND
 2787  2787  2769 bash
 9973  9973  2787 bash
 9975  9973  9973 bash
</code>```

Is there simple way to create similar command which will show unique number for last row in second column?

答:
There's no way to do that since you are detaching the subshells from the current process (PGID) with the & operator therefore will run on a separate process (new PGID).

Check this ones also: How to set process group of a shell script

Body:
Command below prints pid of subshell and subshell of subshell:

$ ( ( echo $BASHPID )& echo $BASHPID )& sleep 1
[1] 9885
9885
9887
[1]+  Done                    ( ( echo $BASHPID ) & echo $BASHPID )

Now command below is more complicated, but it indicates that second subshell is in 'process group' of first subshell:

$ ( ( echo $$ $BASH_SUBSHELL $BASHPID ; export BBB=$BASHPID; ps -e -o pid,pgid,ppid,comm | grep -E "$$|$BBB|PGID" | grep -E "bash|PGID" )& echo $$ $BASH_SUBSHELL $BASHPID; sleep 1 )& sleep 1
[3] 9973
2787 1 9973
2787 2 9975
  PID  PGID  PPID COMMAND
 2787  2787  2769 bash
 9973  9973  2787 bash
 9975  9973  9973 bash

Is there simple way to create similar command which will show unique number for last row in second column?


问:
How can I register methods to a class variable in Python?
I am writing a program to transform a collection of XML documents into HTML. The documents require similar but not identical transformations, so I am hoping to abstract most of the details into a generic BaseParser class and then write an single subclass for each document that encapsulates the document-specific transformations. I am using the Python standard library xml.etree.ElementTree package for event-based parsing.

I would like to be able to write code like this, where the logic of the function is bundled together with when it should be called.

```<code>class CustomParser(BaseParser):
    @on_tag('word', {'lang':'en'})
    def found_en_word(self, tag, attrs):
        # do something
</code>```

For this to work, the decorator needs register the found_en_word function in a class variable (or an instance variable, though it would be redundant for each instance to have its own copy), so that the control flow can be separated in the BaseParser class.

My current solution, shown below, is to use a metaclass to create a callbacks dictionary on the class.

```<code>class Meta(type):
    def __new__(cls, clsname, bases, dct):
        callbacks = {}
        for key, value in dct.items():
            if hasattr(value, '_on_tag'):
                callbacks[value._on_tag] = value
        ret = type(clsname, bases, dct)
        ret.callbacks = callbacks
        return ret

def on_tag(tag, attrs=None):
    def decorator(f):
        f._on_tag = (tag, attrs)
        return f
    return decorator

class BaseParser(metaclass=Meta):
    ...
</code>```

Unfortunately it doesn't look like the metaclass is inherited the way I had hoped: it seems that the metaclass is used to construct a modified BaseParser class, from which CustomParser just inherits normally.

Can this construction be implemented, with or without metaclasses, in Python?

答:
Your metaclass isn't constructing the class correctly.  As described in the docs, you actually need to call type.__new__(Meta, clsname, bases, dct).  By just calling type(clsname, bases, dct), you are constructing an ordinary class that is not an instance of your custom metaclass.

Once you fix that, you'll have another problem, which is that you're trying to use _on_tag as a dictionary key, but _on_tag contains a dictionary, and dictionaries aren't hashable.  That's somewhat tangential to your main question, but you'll have to figure out some way to handle it (perhaps by making the user do @on_tag('word', ('lang', 'en')) instead of @on_tag('word', {'lang': 'en'})).

Body:
I am writing a program to transform a collection of XML documents into HTML. The documents require similar but not identical transformations, so I am hoping to abstract most of the details into a generic BaseParser class and then write an single subclass for each document that encapsulates the document-specific transformations. I am using the Python standard library xml.etree.ElementTree package for event-based parsing.

I would like to be able to write code like this, where the logic of the function is bundled together with when it should be called.

class CustomParser(BaseParser):
    @on_tag('word', {'lang':'en'})
    def found_en_word(self, tag, attrs):
        # do something

For this to work, the decorator needs register the found_en_word function in a class variable (or an instance variable, though it would be redundant for each instance to have its own copy), so that the control flow can be separated in the BaseParser class.

My current solution, shown below, is to use a metaclass to create a callbacks dictionary on the class.

class Meta(type):
    def __new__(cls, clsname, bases, dct):
        callbacks = {}
        for key, value in dct.items():
            if hasattr(value, '_on_tag'):
                callbacks[value._on_tag] = value
        ret = type(clsname, bases, dct)
        ret.callbacks = callbacks
        return ret

def on_tag(tag, attrs=None):
    def decorator(f):
        f._on_tag = (tag, attrs)
        return f
    return decorator

class BaseParser(metaclass=Meta):
    ...

Unfortunately it doesn't look like the metaclass is inherited the way I had hoped: it seems that the metaclass is used to construct a modified BaseParser class, from which CustomParser just inherits normally.

Can this construction be implemented, with or without metaclasses, in Python?


问:
How to use tlb file in C?
tlb file(using regasm) is made from a dll(using c# code), and i can use this in c++ using #import. and everything is working fine.
Is there a way, i can use this in C language? I just found that #import is c++ specific. So, can someone please tell me how can i use in my C program?

my main intention is to use COM DLL developed in C# in my C program.

Thanks & Rgds,
~calvin

答:
COM programming in C is very painful, but not impossible.  The buck stops here though.  The point of a type library is to have a tool auto-generate the COM interface and co-class declarations so that you can use them in your code.  Quite similar to a .h file, but language independent.  The .NET equivalent is the metadata in an assembly.

Problem is, the tooling isn't available to convert a .tlb to C declarations.  I'm sure you are familiar with #import, that's what gets used in MSVC.  But it generates C++ code, smart pointers that help you create the COM object, call its interface methods and deal with errors.  If there is a tool available that generates C then it is a very well hidden secret.

One trick jumps to mind, you can use OleView.exe, File + View TypeLib to view the contents of the type library.  This view is decompiled into IDL, the interface definition language.  You can copy and paste this text into an .idl file and compile it with midl.exe with the /header command line option.  This generates a .h file that contains both C++ and the C declarations for the interfaces.  Ought to get you close, just make sure that the type library is reasonably stable so you don't have to do this very often.

ContentLicense: CC BY-SA 2.5

Title: How to use tlb file in C?


问:
How to find cash cycling circles of defined length in Neo4j?
I would like to find circles like this a1->a2->a3->a1 where each transaction differs by less than 20% from the previous one. The below query works well.

My question is: How do I make it more generic by parametrising circle length?

```<code>match p=(a1:Account { id:'123'})-[t1:Transaction]->(a2:Account)-[t2:Transaction]->(a3:Account)-[t3:Transaction]->(a1)
where a1<>a2<>a3<>a1
  and 0.8*t1.amount<t2.amount<1.2*t1.amount
  and 0.8*t2.amount<t3.amount<1.2*t2.amount
  and 0.8*t3.amount<t1.amount<1.2*t3.amount
return p
</code>```

答:
First, you can use variable-length path pattern:

```<code>match (a1:Account { id:'123'}) with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
return p
</code>```

Second, the condition can also be moved to the statement all:

```<code>match (a1:Account { id:'123'})
with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
with p,
     relationships(p) + head(relationships(p)) as txs
     where all( i in range(1,length(p))
                 where 0.8*txs[i-1].amount<txs[i].amount<1.2*txs[i-1].amount
           )
return p
</code>```

Upd. If you want to check for uniqueness nodes in the path (except for the first and last node):

```<code>match (a1:Account { id:'123'})
with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
with p,
     relationships(p) + head(relationships(p)) as txs,
     tail(nodes(p)) as nds
     where all( i in range(1,length(p))
                where (0.8*txs[i-1].amount<txs[i].amount<1.2*txs[i-1].amount) and
                       reduce(s=0, n in nds |
                              s + case when n = nds[i-1] then 1 else 0 end
                       ) = 1
           )
return p
</code>```

Or more simple with apoc collection function:

```<code>match (a1:Account { id:'123'})
with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
with p,
     relationships(p) + head(relationships(p)) as txs
     where all( i in range(1,length(p))
                 where (0.8*txs[i-1].amount<txs[i].amount<1.2*txs[i-1].amount)
           ) and
           apoc.coll.containsDuplicates(tail(nodes(p))) = false
return distinct p
</code>```

Body:
I would like to find circles like this a1->a2->a3->a1 where each transaction differs by less than 20% from the previous one. The below query works well.

My question is: How do I make it more generic by parametrising circle length?

match p=(a1:Account { id:'123'})-[t1:Transaction]->(a2:Account)-[t2:Transaction]->(a3:Account)-[t3:Transaction]->(a1)
where a1<>a2<>a3<>a1
  and 0.8*t1.amount<t2.amount<1.2*t1.amount
  and 0.8*t2.amount<t3.amount<1.2*t2.amount
  and 0.8*t3.amount<t1.amount<1.2*t3.amount
return p

Body:
First, you can use variable-length path pattern:

match (a1:Account { id:'123'}) with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
return p

Second, the condition can also be moved to the statement all:

match (a1:Account { id:'123'})
with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
with p,
     relationships(p) + head(relationships(p)) as txs
     where all( i in range(1,length(p))
                 where 0.8*txs[i-1].amount<txs[i].amount<1.2*txs[i-1].amount
           )
return p

Upd. If you want to check for uniqueness nodes in the path (except for the first and last node):

match (a1:Account { id:'123'})
with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
with p,
     relationships(p) + head(relationships(p)) as txs,
     tail(nodes(p)) as nds
     where all( i in range(1,length(p))
                where (0.8*txs[i-1].amount<txs[i].amount<1.2*txs[i-1].amount) and
                       reduce(s=0, n in nds |
                              s + case when n = nds[i-1] then 1 else 0 end
                       ) = 1
           )
return p

Or more simple with apoc collection function:

match (a1:Account { id:'123'})
with a1
match p = (a1)-[:Transaction*3..3]->(a1)
      where all( n in nodes(p) where 'Account' in labels(n) )
with p,
     relationships(p) + head(relationships(p)) as txs
     where all( i in range(1,length(p))
                 where (0.8*txs[i-1].amount<txs[i].amount<1.2*txs[i-1].amount)
           ) and
           apoc.coll.containsDuplicates(tail(nodes(p))) = false
return distinct p


问:
Transferring data between two computers connected with a switch from a high level language
I'll start with stating that I know very little about networking and the whole OSI model.

My goal is to create a tiny network(for now my laptop and a raspberry Pi) using an unmanaged network switch. On higher layer transmissions(level 3+) I would simply set the destination IP address for a packet. From what I've read on Wikipedia a network switch operates at the data link layer which means it uses MAC addresses.

How does one send data to a device on a local area network when it's connecting with something that only supports MAC addresses. More importantly, how does one do it from a high level language like Java or C#?

答:
Liam Kelly's answer provides great insight on abstraction of data sending. I will try to provide complementary information.

Network switch operation

While most switches operate at data level, there are some that can perform some operation at higher levels:

layer 3: Within the confines of the Ethernet physical layer, a layer-3 switch can perform some or all of the functions normally
performed by a router.

layer 4: [...] capability for network address translation, but then adds some type of load distribution based on TCP sessions.

layer 7: [...] distribute the load based on uniform resource locators (URLs), or by using some installation-specific technique to
recognize application-level transactions.

RAW sockets usage

As already specified, these require fairly advanced programming skills. They are also severely restricted in non-server versions of modern Windows Operating Systems (source) due to security concerns:

TCP data cannot be sent over raw sockets.

UDP datagrams with an invalid source address cannot be sent over raw sockets. The IP source address for any outgoing UDP datagram must
exist on a network interface or the datagram is dropped. This change
was made to limit the ability of malicious code to create
distributed denial-of-service attacks and limits the ability to send
spoofed packets (TCP/IP packets with a forged source IP address).

A call to the bind function with a raw socket for the IPPROTO_TCP protocol is not allowed.

Suggestion

If .NET is a viable option for you, I would take Pcap.Net for a spin, as it allows various operations at packet level using high level programming (including LINQ).


问:
Is each Javascript function of a webpage supposed to be defined in its own separate .js file?
I'm creating a website as a personal project to learn my way around the DOM and javascript. After several hours of annoyance, I discovered that if I comment out a portion of my HTML ("Animated Landing Page" in the HTML below) that has a javascript function (the btnEnter.addEventListener sequence in the JS) tied to it, anything after that function in my .js file ceases to work (such as the test.addEventListener sequence in the JS). Am I supposed to be separating my javascript functions into their own individual files? At the moment, I want to stick with javascript solutions, as I'd like to grasp the details of javascript before moving on to jQuery. I've included my HTML and JS below:

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>My Webpage</title>
<!-- Add Javascript for enabled browsers -->
<script>document.documentElement.className += " js";</script>
<!-- Latest Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Bootstrap optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest Bootstrap Javascript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Personal stylesheet -->
<link rel="stylesheet" type="text/css" href="MyStyle.css">
</head>
<body>

<!-- Animated landing page -->
<div id="cover-image">
    <button id="entry-btn">Enter</button>
</div>

<!-- Main site -->
<!-- Banner -->
<h1 class="center-content" id="banner">Banner</h1>

<!-- Navigation bar -->
<nav class="nav-bar">
    <div class="container-fluid">
        <ul class="nav-list">
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link1" href="#home">Home</a></li>
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link2" href="#page1">Page 1</a></li>
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link3" href="#page2">Page 2</a></li>
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link4" href="#page3">Page 3</a></li>
            <li class="divider-vertical"></li>
        </ul>
    </div>
</nav>

<!-- Content -->
<div id="home">HOME</div>
<br/>
<div id="page1">PAGE1</div>
<br/>
<div id="page2">PAGE2</div>
<br/>
<div id="page3">PAGE3</div>

<!-- Personal JavaScript file -->
<script src="MyScript.js"></script>
</body>
</html>
</code>```

JS

```<code>var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

btnEnter.addEventListener("click", coverFadeOut);

test.addEventListener("click", testFunc);

function coverFadeOut() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("fadeout");
    coverimg.addEventListener("transitionend", setTimeout(coverHide, 1000), false);
}

function coverHide() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("hide");
}

function testFunc(){
    alert("Test");
}
</code>```

To clarify, I'm asking why my testFunc is not working when I comment out the HTML section "Animated Landing Page"?

答:
The short answer is no, it's not necessary to separate each js function into different files, but for big applications it is convenient, it favour code reuse, testing, etc

This is broad topic and depends greatly on team conventions, best practices and design patterns.

For example, the way I see it, javascript functions must be separated following concepts souch as encapsulation and abstraction, i.e: modules should have only one reason of change and must handle specific responsibilities.

You can decide to separate your functions into modules (aka: separate js files) following this concept. So for example, you can have a navigation file handling all functions specific to navigation, and other modules abstracting another aspects of functionality.

Hope it helped!

Body:
I'm creating a website as a personal project to learn my way around the DOM and javascript. After several hours of annoyance, I discovered that if I comment out a portion of my HTML ("Animated Landing Page" in the HTML below) that has a javascript function (the btnEnter.addEventListener sequence in the JS) tied to it, anything after that function in my .js file ceases to work (such as the test.addEventListener sequence in the JS). Am I supposed to be separating my javascript functions into their own individual files? At the moment, I want to stick with javascript solutions, as I'd like to grasp the details of javascript before moving on to jQuery. I've included my HTML and JS below:

HTML

<!DOCTYPE html>

<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>My Webpage</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<link rel="stylesheet" type="text/css" href="MyStyle.css">

    <button id="entry-btn">Enter</button>

Banner

Home

Page 1

Page 2

Page 3

HOME

PAGE1

PAGE2

PAGE3

JS

var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

btnEnter.addEventListener("click", coverFadeOut);

test.addEventListener("click", testFunc);

function coverFadeOut() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("fadeout");
    coverimg.addEventListener("transitionend", setTimeout(coverHide, 1000), false);
}

function coverHide() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("hide");
}

function testFunc(){
    alert("Test");
}

To clarify, I'm asking why my testFunc is not working when I comment out the HTML section "Animated Landing Page"?


问:
Array: 4th dimension, isset return not reliable
Does anybody know, how it can be, that this code echoes yahoo? There is clearly no 4th array with the key 'something', but it keeps thinking it's like that. Bug? Feature?

```<code>$array = array('a' => array('b' => array('c' => 'test')));
echo '```';
var_dump($array);
echo '```';
if (isset($array['a']['b']['c']['something'])) {
    echo 'yahoo';
}
</code>```

答:
Because PHP thinks you are checking the 'something'th place of the string 'test'. Remember, strings are arrays of characters. try to echo $array['a']['b']['c']['something'].

::EDIT::

I Explained it, I didn't say it made sense. :P

Body:
Does anybody know, how it can be, that this code echoes yahoo? There is clearly no 4th array with the key 'something', but it keeps thinking it's like that. Bug? Feature?

$array = array('a' => array('b' => array('c' => 'test')));
echo '
';
var_dump($array);
echo '
';
if (isset($array['a']['b']['c']['something'])) {
    echo 'yahoo';
}


问:
How to sort documents in meteorhacks:aggregate output
This Meteor server code tries to group documents and sort them by the property "period" ascending but it is not doing it, any idea how to fix it? thx  </p>

```<code>let invoicePopulation = UsageCol.aggregate([
        {
          $match: {
            action: {$in: ['a', 'b', 'c']},
            userId: doc.userId
          }
        },
        {
          $group: {
            _id: {period: "$period"},
            count: {$sum: 1}
          }
        },
        {
          "$sort" : {
            "period" : 1
          }
        }
      ]);

      //output
      [{"_id":{"period":"42017"},"count":14},{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271}]

//needs to be
[{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271},{"_id":{"period":"42017"},"count":14}]
</code>```

答:
Your $group looks strange to me.  Typically you want to group on a specific field and that field would become your _id (since the field is now unique).

The way you have it in your code is setting a sub document as the value for _id.  If that is truly what you want, then your $sort should be this.

```<code>{
  $sort: {
    "_id.period": 1
  }
}
</code>```

If you are not trying to create an _id sub-document, then you should fix your $group like this.

```<code>let invoicePopulation = UsageCol.aggregate([
  {
    $match: {
      action: {$in: ['a', 'b', 'c']},
      userId: doc.userId
    }
  },
  {
    $group: {
      _id: "$period",
      count: {$sum: 1}
    }
  },
  {
    $sort : {
      "period" : 1
    }
  }
]);
</code>```

Body:
This Meteor server code tries to group documents and sort them by the property "period" ascending but it is not doing it, any idea how to fix it? thx

let invoicePopulation = UsageCol.aggregate([
        {
          $match: {
            action: {$in: ['a', 'b', 'c']},
            userId: doc.userId
          }
        },
        {
          $group: {
            _id: {period: "$period"},
            count: {$sum: 1}
          }
        },
        {
          "$sort" : {
            "period" : 1
          }
        }
      ]);

      //output
      [{"_id":{"period":"42017"},"count":14},{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271}]

//needs to be
[{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271},{"_id":{"period":"42017"},"count":14}]

Body:
Your $group looks strange to me.  Typically you want to group on a specific field and that field would become your _id (since the field is now unique).

The way you have it in your code is setting a sub document as the value for _id.  If that is truly what you want, then your $sort should be this.

{
  $sort: {
    "_id.period": 1
  }
}

If you are not trying to create an _id sub-document, then you should fix your $group like this.

let invoicePopulation = UsageCol.aggregate([
  {
    $match: {
      action: {$in: ['a', 'b', 'c']},
      userId: doc.userId
    }
  },
  {
    $group: {
      _id: "$period",
      count: {$sum: 1}
    }
  },
  {
    $sort : {
      "period" : 1
    }
  }
]);


问:
display mysql-table - wrong order displayed
php snippet:

```<code>mysqli_select_db($con,"dbtest");
$sql="SELECT * FROM w3school";
$result = mysqli_query($con,$sql);

echo "<ul id='myUL'>";
while($w3school = mysqli_fetch_array($result)) {
    echo "<li id='".$w3school['id']."'>" . $w3school['LastName'] . "</li>";
}
echo "<ul>";
</code>```

SCREEN OUTPUT looks like this:

```<code>id = 5;
id = 4;
id = 3;
id = 1;
id = 2;
</code>```

I don't see why its not 1,2,3,4 ...

Any suggestions? (any spec info just let me know)

答:
You need an order by for your query.

```<code>SELECT * FROM w3school order by id
</code>```

Body:
php snippet:

mysqli_select_db($con,"dbtest");
$sql="SELECT * FROM w3school";
$result = mysqli_query($con,$sql);

echo "
";
while($w3school = mysqli_fetch_array($result)) {
    echo "
" . $w3school['LastName'] . "
";
}
echo "
";

SCREEN OUTPUT looks like this:

id = 5;
id = 4;
id = 3;
id = 1;
id = 2;

I don't see why its not 1,2,3,4 ...

Any suggestions? (any spec info just let me know)

Body:
You need an order by for your query.

SELECT * FROM w3school order by id


问:
Connect 64bit Java with 32bit COM dll using Com4j or Jacob
I have the following configuration:

1) Windows 10 64-bit

2) An application that has only a 32-bit version and is available through COM.

I access the .dll file of the 32-bit application using the tlbimb.jar to generate the interfaces needed and I succeed.

Scenario 1:
I try to access the 32-bit application using the Java 8 32-bit installation. I can invoke the methods through COM succesfully without any problem.

Scenario 2:
I try to access the 32-bit application using a Java 8 64-bit installation. I get an error message:

```<code>Exception in thread "main" com4j.ExecutionException: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
</code>```

I searched for the exceptin on Stackoverflow/Google and I have done the following:

1) Registered the application's dll using both Sys64WOW/regsvr32.exe and the System32/regsvr32.exe

2) Registered the com4j dll (both 32 and 64 bit) using both Sys64WOW/regsvr32.exe and the System32/regsvr32.exe

3) Copied the dlls in the Sys64WOW and System32 folders.

I have done all the above separatelly, checking all the possible combinations. The afortementioned error using 64-bit Java still exists.

I have tried using another bridge (Jacob). On 32-bit Java it succeeds, on 64-bit Java it fails.

I have a question for someone that might knows: Is there any way to connect an app that, as far as I can tell, offers only a Win32 COM dll[1], using any of the available Java/COM bridges and Java 64bit? Or simply 32-bit COM + 64-bit Java are not connectable?

[1]: I checked the OLE/COM Viewer and under the Type Library there's is only one entry "0 Win32 = , so I implied that this means there's no Win64 COM dll, right?

答:
This won't work because the bitness of your client process and COM DLL don't match. When trying to create a new instance, CoCreateInstance tries to find related class information in the 64-bit hive of the registry. This fails because its actually located in the 32-bit hive, where you registered the DLL.

To remedy this, you have the option of using a surrogate process, which allows your CoClass to be instantiated in a distinct native process. Your client can then communicate with the surrogate via IPC (see here for further info).

As a quick start, you can mark your CoClass as a candidate for the default dllhost.exe surrogate process: OLE/COM Object Viewer (x86) as Admin > All Objects > [Your CoClass] > Implementation > Use Surrogate Process (leave path empty).

If you intend to distribute your application, you may place this information in a REG script or import your DLL into a COM+ server application.

Body:
I have the following configuration:

1) Windows 10 64-bit

2) An application that has only a 32-bit version and is available through COM.

I access the .dll file of the 32-bit application using the tlbimb.jar to generate the interfaces needed and I succeed.

Scenario 1:
I try to access the 32-bit application using the Java 8 32-bit installation. I can invoke the methods through COM succesfully without any problem.

Scenario 2:
I try to access the 32-bit application using a Java 8 64-bit installation. I get an error message:

Exception in thread "main" com4j.ExecutionException: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153

I searched for the exceptin on Stackoverflow/Google and I have done the following:

1) Registered the application's dll using both Sys64WOW/regsvr32.exe and the System32/regsvr32.exe

2) Registered the com4j dll (both 32 and 64 bit) using both Sys64WOW/regsvr32.exe and the System32/regsvr32.exe

3) Copied the dlls in the Sys64WOW and System32 folders.

I have done all the above separatelly, checking all the possible combinations. The afortementioned error using 64-bit Java still exists.

I have tried using another bridge (Jacob). On 32-bit Java it succeeds, on 64-bit Java it fails.

I have a question for someone that might knows: Is there any way to connect an app that, as far as I can tell, offers only a Win32 COM dll[1], using any of the available Java/COM bridges and Java 64bit? Or simply 32-bit COM + 64-bit Java are not connectable?

[1]: I checked the OLE/COM Viewer and under the Type Library there's is only one entry "0 Win32 = , so I implied that this means there's no Win64 COM dll, right?


问:
Unable to delete mysql record through PHP
i want to delete the record in mysql database by just clicking on a link but i am unable to accomplish it, i am unable to understand the error.
Here is my code

HTML

```<code><a href="processCategory.php?action=delete?id=(<?php echo $id; ?>);">Delete</a>
</code>```

processCategory.php

```<code>    <?php
    require_once '../library/config.php';
    require_once '../library/functions.php';

    checkUser();

    $action = isset($_GET['action']) ? $_GET['action'] : '';
    switch ($action) {

        case 'add' :
            addCategory();
            break;

        case 'delete' :
            deleteCategory();
            break;

        default :
            // if action is not defined or unknown
            // move to main category page
            header('Location: index.php');
    }

 function deleteCategory()
    {
        if (isset($_GET['id']) && (int)$_GET['id'] > 0) {
            $id = (int)$_GET['id'];
        } else {
            header('Location: index.php');
        }

        // delete the products
        $sql = "DELETE FROM tbl_vendors
                WHERE id = $id";
        dbQuery($sql);

        header('Location: ../vendor');
    }

    ?>
</code>```

答:
replace ? with & and remove "(" ")" and ; in your URL

```<code><a href="processCategory.php?action=delete?id=(<?php echo $id; ?>);">Delete</a>
</code>```

Your script processCategory.php Receives in the variable id this = (1) for example your out

```<code>echo (int) "(1)";
</code>```

output

```<code>0
</code>```

The correct code for the  tag should be as

```<code><a href="processCategory.php?action=delete&id=<?php echo $id; ?>">Delete</a>
</code>```

Body:
i want to delete the record in mysql database by just clicking on a link but i am unable to accomplish it, i am unable to understand the error.
Here is my code

HTML

<a href="processCategory.php?action=delete?id=(<?php echo $id; ?>);">Delete

processCategory.php

    <?php
    require_once '../library/config.php';
    require_once '../library/functions.php';

    checkUser();

    $action = isset($_GET['action']) ? $_GET['action'] : '';
    switch ($action) {

        case 'add' :
            addCategory();
            break;

        case 'delete' :
            deleteCategory();
            break;

        default :
            // if action is not defined or unknown
            // move to main category page
            header('Location: index.php');
    }

 function deleteCategory()
    {
        if (isset($_GET['id']) && (int)$_GET['id'] > 0) {
            $id = (int)$_GET['id'];
        } else {
            header('Location: index.php');
        }

        // delete the products
        $sql = "DELETE FROM tbl_vendors
                WHERE id = $id";
        dbQuery($sql);

        header('Location: ../vendor');
    }

    ?>

Body:
replace ? with & and remove "(" ")" and ; in your URL

<a href="processCategory.php?action=delete?id=(<?php echo $id; ?>);">Delete</a>

Your script processCategory.php Receives in the variable id this = (1) for example your out

echo (int) "(1)";

output

0

The correct code for the <a> tag should be as

<a href="processCategory.php?action=delete&id=<?php echo $id; ?>">Delete</a>


问:
How to create an Auto-complete combo-box or text box to filter text containing a string
How do I create an Auto-complete ComboBox or TextBox that filters text based on a string?

For example: if I type an "a" in a TextBox, I only get to see all strings containing an "a".

答:
If you mean show suggestions then it's a simple matter of changing a property when you have the TextBox selected in your IDE of choice:

The options shown in the picture allow you to change the rules for autocompleting text in the text box as well as the source for the suggestions. (Visual Studio 2010)

You can go to the following link to learn more about the TextBox control.

MSDN Text Box Control


问:
Javascript in Virtual Directory unaware of Virtual Directory
Say I have the site
    http://localhost/virtual
where virtual is the virtual directory

I have an Ajax request that is defined in a javascript file using JQuery

```<code>$.getJSON("/Controller/Action")
</code>```

When this is called, the client tries to find the url at the root level i.e.
    http://localhost/Controller/Action

If I add the tilde (~) symbol in, it turns into
    http://localhost/virtual/~/Controller/Action

It should (if it was to do what I wanted) resolve to
    http://localhost/virtual/Controller/Action

Any ideas on how to fix this?

答:
It is too late to answer this question. But may be useful to someone as I had same problem. Instead of doing all this steps mentioned in above answers, better way is to use

Url.Action('action','controller').

It'll generate url /VIRDIR/controller/action if it is running from virtual directory or generate /controller/action in other case.

Body:
Say I have the site
    http://localhost/virtual
where virtual is the virtual directory

I have an Ajax request that is defined in a javascript file using JQuery

$.getJSON("/Controller/Action")

When this is called, the client tries to find the url at the root level i.e.
    http://localhost/Controller/Action

If I add the tilde (~) symbol in, it turns into
    http://localhost/virtual/~/Controller/Action

It should (if it was to do what I wanted) resolve to
    http://localhost/virtual/Controller/Action

Any ideas on how to fix this?


问:
Uncaught TypeError: response is not a function
I am trying to get the response of this url. But when I check the console error message appears:

Uncaught TypeError: response is not a function

What is the possible problem?

```<code>var uri = pbxApi+"/conference/participants/"+circle+"/"+data.conference+"/"+data.uniqueid+'?jsonp=response';
getJsonData(uri, function(res){
});
</code>```

This is my function.

```<code>var getJsonData = function(uri,callback){
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        url: uri,
        jsonpCallback: 'response',
        cache: false,
        contentType: "application/json",
        success: function(json){
            callback(json);
        }
    });
}
</code>```

this is my response:

```<code>response({"_id":"56177d3b3f2dc8146bd8565c","event":"ConfbridgeJoin","channel":"SIP/192.168.236.15-0000005e","uniqueid":"1444379955.224","conference":"0090000293","calleridnum":"0090000290","calleridname":"0090000290","__v":0,"status":false,"sipSetting":{"accountcode":"0302150000","accountcode_naisen":"203","extentype":0,"extenrealname":"UID3","name":"0090000290","secret":"Myojyo42_f","username":"0090000290","context":"innercall_xdigit","gid":101,"cid":"0090000018"}})
</code>```

答:
just use this type of coding for return your callback data.

```<code> function getJsonData(uri,callback)
  {
     $.ajax({
       type: "GET",
       dataType: "json",
       url: uri,
       cache: false,
       success: function(json){
         callback(json);
                }
      });
  }
      getJsonData(function(resp)
         {
          console.log(resp);
         }
</code>```

Now you got the return data in console.log

Body:
I am trying to get the response of this url. But when I check the console error message appears:

Uncaught TypeError: response is not a function

What is the possible problem?

var uri = pbxApi+"/conference/participants/"+circle+"/"+data.conference+"/"+data.uniqueid+'?jsonp=response';
getJsonData(uri, function(res){
});

This is my function.

var getJsonData = function(uri,callback){
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        url: uri,
        jsonpCallback: 'response',
        cache: false,
        contentType: "application/json",
        success: function(json){
            callback(json);
        }
    });
}

this is my response:

response({"_id":"56177d3b3f2dc8146bd8565c","event":"ConfbridgeJoin","channel":"SIP/192.168.236.15-0000005e","uniqueid":"1444379955.224","conference":"0090000293","calleridnum":"0090000290","calleridname":"0090000290","__v":0,"status":false,"sipSetting":{"accountcode":"0302150000","accountcode_naisen":"203","extentype":0,"extenrealname":"UID3","name":"0090000290","secret":"Myojyo42_f","username":"0090000290","context":"innercall_xdigit","gid":101,"cid":"0090000018"}})

Body:
just use this type of coding for return your callback data.

 function getJsonData(uri,callback)
  {
     $.ajax({
       type: "GET",
       dataType: "json",
       url: uri,
       cache: false,
       success: function(json){
         callback(json);
                }
      });
  }
      getJsonData(function(resp)
         {
          console.log(resp);
         }

Now you got the return data in console.log


问:
equality test between childNodes(0).values and a string in javascript
I can't to work my code.

I have 3 files:

piante.xml

```<code> <?xml version="1.0" encoding="UTF-8" ?>
<FMPXMLRESULT
xmlns="http://www.filemaker.com/fmpxmlresult"><ERRORCODE>0</ERRORCODE><PRODUCT
BUILD="12-06-2016" NAME="FileMaker" VERSION="ProAdvanced 15.0.3"/><DATABASE
DATEFORMAT="D/m/yyyy" LAYOUT="" NAME="IndexHorti v3.12.fmp12" RECORDS="586"
TIMEFORMAT="k:mm:ss "/>

<METADATA><FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Gen Spe con spazio"
TYPE="TEXT"/><FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Localizzazione esemplare LAST"
TYPE="TEXT"/><FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Link WEB"
TYPE="TEXT"/></METADATA>

<RESULTSET FOUND="2">

<ROW MODID="56" RECORDID="20055">
<COL><DATA>Acanthus  mollisL.</DATA></COL>
<COL><DATA>01-02-01-23</DATA></COL>
<COL><DATA>www.corriere.it</DATA></COL></ROW>

<ROW MODID="12" RECORDID="20057">
<COL><DATA>Achillea  millefolium L.</DATA></COL>
<COL><DATA>01-05-01-16</DATA></COL>
<COL><DATA>www.repubblica.it</DATA></COL></ROW>
</RESULTSET>
</FMPXMLRESULT>
</code>```

then a function that parses the XML doc and return the third Child if the second child matches with the string "ulink"

```<code>function getLink(fname, ulink)

{

try //Internet Explorer
  {
  docname=new ActiveXObject("Microsoft.XMLDOM");

  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    docname=document.implementation.createDocument("","",null);

    }
  catch(e) {alert(e.message)}
  try
  {
  docname.async=false;
  docname.load(fname);

  }
catch(e) {alert(e.message)}

  }

var x=docname.getElementsByTagName("ROW");
document.write(x.length);
for (var i=0;i<x.length;i++){

  var y=x[i].getElementsByTagName("DATA");
  document.write(y[0].childNodes(0).nodeValue);
  document.write(y[1].childNodes(0).nodeValue);
  document.write(y[2].childNodes(0).nodeValue);
  if(y[1].childNodes(0).nodeValue == ulink){
      var z= y[2].childNodes[0].nodeValue;
     document.write(y[2].childNodes(0).nodeValue);
      return z;}
      else{document.write("not equal");}
     }
}
</code>```

and then the file provadef.html to testing

```<code><html>
<head>
<script type="text/javascript" src="byxml.js">
</script>
</head>

<body>

<div>
<script type="text/javascript">

document.write(getLink("piante.xml","01-02-01-23"));
</script>
</div>
</body>
</html>
</code>```

I insert some doument.write instructions to debug, but I can' t understand the error. can u help me please?

答:
Every time you write childNodes(0), you should be writing childNodes[0].

childNodes is an array, and array elements should be accessed using square brackets.

Parentheses are used for grouping expressions and for calling functions (the latter of which is the syntax you used).

Body:
I can't to work my code.

I have 3 files:

piante.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<FMPXMLRESULT
xmlns="http://www.filemaker.com/fmpxmlresult"><ERRORCODE>0</ERRORCODE><PRODUCT
BUILD="12-06-2016" NAME="FileMaker" VERSION="ProAdvanced 15.0.3"/><DATABASE
DATEFORMAT="D/m/yyyy" LAYOUT="" NAME="IndexHorti v3.12.fmp12" RECORDS="586"
TIMEFORMAT="k:mm:ss "/>

<METADATA><FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Gen Spe con spazio"
TYPE="TEXT"/><FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Localizzazione esemplare LAST"
TYPE="TEXT"/><FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Link WEB"
TYPE="TEXT"/></METADATA>

<RESULTSET FOUND="2">

<ROW MODID="56" RECORDID="20055">
<COL><DATA>Acanthus  mollisL.</DATA></COL>
<COL><DATA>01-02-01-23</DATA></COL>
<COL><DATA>www.corriere.it</DATA></COL></ROW>

<ROW MODID="12" RECORDID="20057">
<COL><DATA>Achillea  millefolium L.</DATA></COL>
<COL><DATA>01-05-01-16</DATA></COL>
<COL><DATA>www.repubblica.it</DATA></COL></ROW>
</RESULTSET>
</FMPXMLRESULT>

then a function that parses the XML doc and return the third Child if the second child matches with the string "ulink"

function getLink(fname, ulink)

{

try //Internet Explorer
  {
  docname=new ActiveXObject("Microsoft.XMLDOM");

  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    docname=document.implementation.createDocument("","",null);

    }
  catch(e) {alert(e.message)}
  try
  {
  docname.async=false;
  docname.load(fname);

  }
catch(e) {alert(e.message)}

  }

var x=docname.getElementsByTagName("ROW");
document.write(x.length);
for (var i=0;i<x.length;i++){

  var y=x[i].getElementsByTagName("DATA");
  document.write(y[0].childNodes(0).nodeValue);
  document.write(y[1].childNodes(0).nodeValue);
  document.write(y[2].childNodes(0).nodeValue);
  if(y[1].childNodes(0).nodeValue == ulink){
      var z= y[2].childNodes[0].nodeValue;
     document.write(y[2].childNodes(0).nodeValue);
      return z;}
      else{document.write("not equal");}
     }
}

and then the file provadef.html to testing

I insert some doument.write instructions to debug, but I can' t understand the error. can u help me please?


问:
Windows XP socket error with recv()
I'm having a strange behaviour with the recv() function.

My C++ (MFC) application with WinSock implements a simple HTTP client (non-blocking socket) for accessing HTML pages on a web server. Some of these pages are taking a few seconds for loading. On Windows 7 this is not a problem, because recv() also returns partial data. But on Windows XP the recv() function always returns SOCKET_ERROR and the error code is WSAEWOULDBLOCK. Only when the connection is finished the data is returned in one access.

Does anyone know this problem? How can I force Windows XP to also receive partial data?

I setted the buffer size (SO_RCVBUF) to 1000 Bytes. On Windows 7 this is also reflected to the TCP Window Size - on XP not.

The real problem which I have with this issue is, that I don't know how to check if the connection is still alive or not. How can I check if a connection is still alive? Or how can I specify a timeout (max time between two received packets from the server)?

答:
It's very strange.

Today I have changed my software to use blocking sockets. But it still doesn't work on Windows XP. Windows 7 is no problem.

So I thought: Let's try another PC. On this PC (also Windows XP) it does work. Now I tried a 3rd PC with Windows XP and here it also works.

I still don't know what the problem is but I think there must be a bug with the PC.

Title: Windows XP socket error with recv()


问:
Typescript has unions, so are enums redundant?
Ever since TypeScript introduced unions types, I wonder if there is any reason to declare an enum type. Consider the following enum type declaration:

```<code>enum X { A, B, C }
var x: X = X.A;
</code>```

and a similar union type declaration:

```<code>type X: "A" | "B" | "C"
var x: X = "A";
</code>```

If they basically serve the same purpose, and unions are more powerful and expressive, then why are enums necessary?

答:
There are few reasons you might want to use an enum

You can iterate over an enum.

You can use an enum as flags. Bit Flags

Here are some use cases. Enums TypeScript Deep
Dive.

I see the big advantages of using a union is that they provide a succinct way to represent a value with multiple types and they are very readable.
let x: number | string

EDIT: As of TypeScript 2.4  Enums now support strings.

```<code>enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Ever since TypeScript introduced unions types, I wonder if there is any reason to declare an enum type. Consider the following enum type declaration:

enum X { A, B, C }
var x: X = X.A;

and a similar union type declaration:

type X: "A" | "B" | "C"
var x: X = "A";

If they basically serve the same purpose, and unions are more powerful and expressive, then why are enums necessary?

Body:
There are few reasons you might want to use an enum

You can iterate over an enum.

You can use an enum as flags. Bit Flags

Here are some use cases. Enums TypeScript Deep
Dive.

I see the big advantages of using a union is that they provide a succinct way to represent a value with multiple types and they are very readable.
let x: number | string

EDIT: As of TypeScript 2.4  Enums now support strings.

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}


问:
How to Access Vue-Loader Components in an HTML File
I would like to use the modular style and file format of Vue Loader (i.e., where I have a template section, script section and style section in each .vue file).

What I can't figure out how to do (or if it is even possible to do) is use my custom templates in an html file.

For instance, in the App.vue file I can use the following code:

```<code><template>
  <div id="app">
    <message>Hello there</message>
  </div>
</template>
</code>```

This will work to display a custom message component on the home page.

What I would like to do instead is use my custom components in html files.  For instance, in the index.html file to use the following code:

```<code>  <div id="app">
    <message>Hello there</message>
  </div>
</code>```

Any idea how I can do this?  Thanks.

NOTE:  I am new to Vue Loader and semi-new to Vue (so I apologize in advance if the answer to this question is obvious).

答:
There are many ways you can compile a single file component and then use that component in a web page.

Use vue-cli

Vue released a command line interface tool called vue-cli that can initialize projects and build components with zero configuration. One option to build a component that you can use in your page is to use vue build.

```<code>vue build MyComponent.vue --prod --lib MyComponent
</code>```

This will compile a script that exposes MyComponent. If you include that script in your page and then add it globally,

```<code>Vue.component(MyComponent)
</code>```

That component will be available to you in any of your Vues.

Make a plugin

Here is a sample of a very basic framework for making a plugin.

myPluginDefinition.js

```<code>window.MyPlugin= {};

MyPlugin.install = function (Vue) {
    Vue.component('my-component', require('./my-component.vue'));
}
</code>```

webpack.config.js

```<code>module.exports = {
    entry: "./myPluginDefinition.js",
    output: {
        path: __dirname+'/dist',
        filename: "MyPlugin.js"
    },
    module: {
        loaders: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
        }
        ]
    }
};
</code>```

This will build a file called MyPlugin.js that will contain each of the single file components that you include in the install function. Include the script on your page and then call

```<code>Vue.use(MyPlugin)
</code>```

and you will have all of your components.

Use a custom webpack configuration

There are many ways you could configure webpack to build your single file components. You could build them all into a single file or build them separately. I suggest if you want to use one of these options you ask a separate question.

Body:
I would like to use the modular style and file format of Vue Loader (i.e., where I have a template section, script section and style section in each .vue file).

What I can't figure out how to do (or if it is even possible to do) is use my custom templates in an html file.

For instance, in the App.vue file I can use the following code:

<template>

    <message>Hello there</message>

</template>

This will work to display a custom message component on the home page.

What I would like to do instead is use my custom components in html files.  For instance, in the index.html file to use the following code:

    <message>Hello there</message>

Any idea how I can do this?  Thanks.

NOTE:  I am new to Vue Loader and semi-new to Vue (so I apologize in advance if the answer to this question is obvious).

Body:
There are many ways you can compile a single file component and then use that component in a web page.

Use vue-cli

Vue released a command line interface tool called vue-cli that can initialize projects and build components with zero configuration. One option to build a component that you can use in your page is to use vue build.

vue build MyComponent.vue --prod --lib MyComponent

This will compile a script that exposes MyComponent. If you include that script in your page and then add it globally,

Vue.component(MyComponent)

That component will be available to you in any of your Vues.

Make a plugin

Here is a sample of a very basic framework for making a plugin.

myPluginDefinition.js

window.MyPlugin= {};

MyPlugin.install = function (Vue) {
    Vue.component('my-component', require('./my-component.vue'));
}

webpack.config.js

module.exports = {
    entry: "./myPluginDefinition.js",
    output: {
        path: __dirname+'/dist',
        filename: "MyPlugin.js"
    },
    module: {
        loaders: [
        {
            test: /\.vue$/,
            loader: 'vue-loader',
        }
        ]
    }
};

This will build a file called MyPlugin.js that will contain each of the single file components that you include in the install function. Include the script on your page and then call

Vue.use(MyPlugin)

and you will have all of your components.

Use a custom webpack configuration

There are many ways you could configure webpack to build your single file components. You could build them all into a single file or build them separately. I suggest if you want to use one of these options you ask a separate question.


问:
Any faster, simpler alternative to php preg_match
I am using cakephp 1.3 and I have textarea where users submit articles. On submit, I want to look into the article for certain key words and and add respective tags to the article.

I was thinking of preg_match, But preg_match pattern has to be string. So I would have to loop through an array(big).

Is there a easier way to plug in the keywords array for the pattern.

I appreciate all your help.

Thanks.

答:
I suggest treating your array of keywords like a hash table. Lowercase the article text, explode by spaces, then loop through each word of the exploded array. If the word exists in your hash table, push it to a new array while keeping track of the number of times it's been seen.

I ran a quick benchmark comparing regex to hash tables in this scenario. To run it with regex 1000 times, it took 17 seconds. To run it with a hash table 1000 times, it took 0.4 seconds. It should be an O(n+m) process.

```<code>$keywords = array("computer", "dog", "sandwich");
$article = "This is a test using your computer when your dog is being a dog";
$arr = explode(" ", strtolower($article));
$tracker = array();

foreach($arr as $word){
    if(in_array($word, $keywords)){
        if(isset($tracker[$word]))
            $tracker[$word]++;
        else
            $tracker[$word] = 1;
    }
}
</code>```

The $tracker array would output: "computer" => 1, "dog" => 2. You can then do the process to decide what tags to use. Or if you don't care about the number of times the keyword appears, you can skip the tracker part and add the tags as the keywords appear.

EDIT: The keyword array may need to be an inverted index array to ensure the fastest lookup. I am not sure how in_array() works, but if it searches, then this isn't as fast as it should be. An inverted index array would look like

```<code>array("computer" => 1, "dog" => 1, "sandwich" => 1); // "1" can be any value
</code>```

Then you would do isset($keywords[$word]) to check if the word matches a keyword, instead of in_array(), which should give you O(1). Someone else may be able to clarify this for me though.

Body:
I suggest treating your array of keywords like a hash table. Lowercase the article text, explode by spaces, then loop through each word of the exploded array. If the word exists in your hash table, push it to a new array while keeping track of the number of times it's been seen.

I ran a quick benchmark comparing regex to hash tables in this scenario. To run it with regex 1000 times, it took 17 seconds. To run it with a hash table 1000 times, it took 0.4 seconds. It should be an O(n+m) process.

$keywords = array("computer", "dog", "sandwich");
$article = "This is a test using your computer when your dog is being a dog";
$arr = explode(" ", strtolower($article));
$tracker = array();

foreach($arr as $word){
    if(in_array($word, $keywords)){
        if(isset($tracker[$word]))
            $tracker[$word]++;
        else
            $tracker[$word] = 1;
    }
}

The $tracker array would output: "computer" => 1, "dog" => 2. You can then do the process to decide what tags to use. Or if you don't care about the number of times the keyword appears, you can skip the tracker part and add the tags as the keywords appear.

EDIT: The keyword array may need to be an inverted index array to ensure the fastest lookup. I am not sure how in_array() works, but if it searches, then this isn't as fast as it should be. An inverted index array would look like

array("computer" => 1, "dog" => 1, "sandwich" => 1); // "1" can be any value

Then you would do isset($keywords[$word]) to check if the word matches a keyword, instead of in_array(), which should give you O(1). Someone else may be able to clarify this for me though.


问:
Asp.net core url re-writing from middleware not working
I have a dot net core web application with some mvc controllers and an angular 2 app. I am trying to re-write request paths like "www.example.com/old/path" to "www.example.com/new/path" and then send it to the angular 2 app (which has routing setup only for "new/path"). But Angular keeps getting the old path even though re-writing seems to have worked (judging from breakpoints). I suspect this might reflect some kind of gap in my understanding of the order of middleware execution (but I have tried different orders and spamming the re-writing code everywhere to no avail).

This is how the url re-writing middleware looks like (UrlRewritingMiddleware.cs):

```<code>public sealed class UrlRewritingMiddleware
{
    private readonly RequestDelegate _next;

    private readonly string OldPathSegment= "/old/path/";
    private readonly string NewPathSegment= "/new/path/";

    public UrlRewritingMiddleware(RequestDelegate next)
    {
      this._next = next;
    }

    private void RewriteUrl(HttpContext context)
    {
      if (context.Request.Path.Value.IndexOf(OldPathSegment, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
      {
        context.Request.Path = new PathString(Regex.Replace(context.Request.Path.Value, OldPathSegment, NewPathSegment, RegexOptions.IgnoreCase));
      }
    }
    public async Task Invoke(HttpContext context)
    {
      RewriteUrl(context);
      await _next.Invoke(context);
      if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
      {
        context.Request.Path = "/app/root/index.html";
        context.Response.StatusCode = 200;
        await _next.Invoke(context);
        RewritePathsInContext(context);//spam
      }
      else
      {
        //spam
        RewritePathsInContext(context);
      }
    }
}
</code>```

And then this is how the Startup.cs Configure method looks like:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //putting in the beginning, I get error in angular
    //EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '/old/path'
    app.UseUrlRewritingMiddleware();
    app.AnotherCustomMiddleware();//I can see Path changed to new/path inside here
    app.UseDefaultFiles();
    app.UseMvc();
    app.UseStaticFiles();
    //putting this at the end gives me 404 in asp.net
    //app.UseUrlRewritingMiddleware();
}
</code>```

答:
After a good night's sleep I realized that server side re-writing of the request path is not going to change the url that shows up in the browser (which is what angular gets). So www.example.com/old/path is going to remain the same in the browser and only a redirect can change it to www.example.com/new/path (which is not what I want). To solve the issue I had to add redirects in the angular app itself. My angular app also calls some mvc controllers/ views but they are always in the /new/path format so I don't need server side re-writing at this point.

<s>Also, about the order of middlewares I suspect the reason putting it at the end gave me a 404 in asp.net might be because it comes after the UseMvc middleware (which already sets up routes?). Haven't tested it but as long as it comes before the UseMvc middleware, I think it should work.</s> EDIT: See ssmith's comment below. UseMvc is a terminal middleware so anything after it won't work.

If you do need server side url re-writing, asp.net core has a re-writing middleware that you can use and don't actually need to write your own:

```<code>var options = new RewriteOptions()
                 .AddRewrite(@"/old/path/", "/new/path/", skipRemainingRules: true);
app.UseRewriter(options);
</code>```

Body:
I have a dot net core web application with some mvc controllers and an angular 2 app. I am trying to re-write request paths like "www.example.com/old/path" to "www.example.com/new/path" and then send it to the angular 2 app (which has routing setup only for "new/path"). But Angular keeps getting the old path even though re-writing seems to have worked (judging from breakpoints). I suspect this might reflect some kind of gap in my understanding of the order of middleware execution (but I have tried different orders and spamming the re-writing code everywhere to no avail).

This is how the url re-writing middleware looks like (UrlRewritingMiddleware.cs):

public sealed class UrlRewritingMiddleware
{
    private readonly RequestDelegate _next;

    private readonly string OldPathSegment= "/old/path/";
    private readonly string NewPathSegment= "/new/path/";

    public UrlRewritingMiddleware(RequestDelegate next)
    {
      this._next = next;
    }

    private void RewriteUrl(HttpContext context)
    {
      if (context.Request.Path.Value.IndexOf(OldPathSegment, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
      {
        context.Request.Path = new PathString(Regex.Replace(context.Request.Path.Value, OldPathSegment, NewPathSegment, RegexOptions.IgnoreCase));
      }
    }
    public async Task Invoke(HttpContext context)
    {
      RewriteUrl(context);
      await _next.Invoke(context);
      if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
      {
        context.Request.Path = "/app/root/index.html";
        context.Response.StatusCode = 200;
        await _next.Invoke(context);
        RewritePathsInContext(context);//spam
      }
      else
      {
        //spam
        RewritePathsInContext(context);
      }
    }
}

And then this is how the Startup.cs Configure method looks like:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //putting in the beginning, I get error in angular
    //EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '/old/path'
    app.UseUrlRewritingMiddleware();
    app.AnotherCustomMiddleware();//I can see Path changed to new/path inside here
    app.UseDefaultFiles();
    app.UseMvc();
    app.UseStaticFiles();
    //putting this at the end gives me 404 in asp.net
    //app.UseUrlRewritingMiddleware();
}

Body:
After a good night's sleep I realized that server side re-writing of the request path is not going to change the url that shows up in the browser (which is what angular gets). So www.example.com/old/path is going to remain the same in the browser and only a redirect can change it to www.example.com/new/path (which is not what I want). To solve the issue I had to add redirects in the angular app itself. My angular app also calls some mvc controllers/ views but they are always in the /new/path format so I don't need server side re-writing at this point.

<s>Also, about the order of middlewares I suspect the reason putting it at the end gave me a 404 in asp.net might be because it comes after the UseMvc middleware (which already sets up routes?). Haven't tested it but as long as it comes before the UseMvc middleware, I think it should work.</s> EDIT: See ssmith's comment below. UseMvc is a terminal middleware so anything after it won't work.

If you do need server side url re-writing, asp.net core has a re-writing middleware that you can use and don't actually need to write your own:

var options = new RewriteOptions()
                 .AddRewrite(@"/old/path/", "/new/path/", skipRemainingRules: true);
app.UseRewriter(options);


问:
Edge/Vertex matrix from triangulation
I have to analyze some STL files with Matlab, and I import them successfully with an STL reader, but this function only returns vertices and faces (triangles).

This is the STL reader I am using, and this is an example STL file, generated by the gmsh tool with gmsh -2 -format stl -bin t4.geo. In case, the code for the STL function is at the end.

```<code>mesh = stlread("t4.stl");
</code>```

Is there a function I can use to obtain the vertex/edge adjacency matrix from such a triangulation?

```<code>function [F,V,N] = stlbinary(M)

    F = [];
    V = [];
    N = [];

    if length(M) < 84
        error('MATLAB:stlread:incorrectFormat', ...
              'Incomplete header information in binary STL file.');
    end

    % Bytes 81-84 are an unsigned 32-bit integer specifying the number of faces
    % that follow.
    numFaces = typecast(M(81:84),'uint32');
    %numFaces = double(numFaces);
    if numFaces == 0
        warning('MATLAB:stlread:nodata','No data in STL file.');
        return
    end

    T = M(85:end);
    F = NaN(numFaces,3);
    V = NaN(3*numFaces,3);
    N = NaN(numFaces,3);

    numRead = 0;
    while numRead < numFaces
        % Each facet is 50 bytes
        %  - Three single precision values specifying the face normal vector
        %  - Three single precision values specifying the first vertex (XYZ)
        %  - Three single precision values specifying the second vertex (XYZ)
        %  - Three single precision values specifying the third vertex (XYZ)
        %  - Two unused bytes
        i1    = 50 * numRead + 1;
        i2    = i1 + 50 - 1;
        facet = T(i1:i2)';

        n  = typecast(facet(1:12),'single');
        v1 = typecast(facet(13:24),'single');
        v2 = typecast(facet(25:36),'single');
        v3 = typecast(facet(37:48),'single');

        n = double(n);
        v = double([v1; v2; v3]);

        % Figure out where to fit these new vertices, and the face, in the
        % larger F and V collections.
        fInd  = numRead + 1;
        vInd1 = 3 * (fInd - 1) + 1;
        vInd2 = vInd1 + 3 - 1;

        V(vInd1:vInd2,:) = v;
        F(fInd,:)        = vInd1:vInd2;
        N(fInd,:)        = n;

        numRead = numRead + 1;
    end

end
</code>```

答:
Assuming your faces are in a n-by-3 array F:

```<code>% temporary array
T = [F(:,1) F(:,2) ; F(:,1) F(:,3) ; F(:,2) F(:,3)];

% get the edges
E = unique([min(T,[],2), max(T,[],2)],'rows');

% build the adjacency matrix
n = max(E(:,2));
A = sparse(E(:,1), E (:,2), ones(size(E,1),1), n, n);
A = A + A';
</code>```

NB: sparse arrays are often useful for such adjacency matrix, especially in the large limit.

Best,

Title: Edge/Vertex matrix from triangulation

Body:
I have to analyze some STL files with Matlab, and I import them successfully with an STL reader, but this function only returns vertices and faces (triangles).

This is the STL reader I am using, and this is an example STL file, generated by the gmsh tool with gmsh -2 -format stl -bin t4.geo. In case, the code for the STL function is at the end.

mesh = stlread("t4.stl");

Is there a function I can use to obtain the vertex/edge adjacency matrix from such a triangulation?

function [F,V,N] = stlbinary(M)

    F = [];
    V = [];
    N = [];

    if length(M) < 84
        error('MATLAB:stlread:incorrectFormat', ...
              'Incomplete header information in binary STL file.');
    end

    % Bytes 81-84 are an unsigned 32-bit integer specifying the number of faces
    % that follow.
    numFaces = typecast(M(81:84),'uint32');
    %numFaces = double(numFaces);
    if numFaces == 0
        warning('MATLAB:stlread:nodata','No data in STL file.');
        return
    end

    T = M(85:end);
    F = NaN(numFaces,3);
    V = NaN(3*numFaces,3);
    N = NaN(numFaces,3);

    numRead = 0;
    while numRead < numFaces
        % Each facet is 50 bytes
        %  - Three single precision values specifying the face normal vector
        %  - Three single precision values specifying the first vertex (XYZ)
        %  - Three single precision values specifying the second vertex (XYZ)
        %  - Three single precision values specifying the third vertex (XYZ)
        %  - Two unused bytes
        i1    = 50 * numRead + 1;
        i2    = i1 + 50 - 1;
        facet = T(i1:i2)';

        n  = typecast(facet(1:12),'single');
        v1 = typecast(facet(13:24),'single');
        v2 = typecast(facet(25:36),'single');
        v3 = typecast(facet(37:48),'single');

        n = double(n);
        v = double([v1; v2; v3]);

        % Figure out where to fit these new vertices, and the face, in the
        % larger F and V collections.
        fInd  = numRead + 1;
        vInd1 = 3 * (fInd - 1) + 1;
        vInd2 = vInd1 + 3 - 1;

        V(vInd1:vInd2,:) = v;
        F(fInd,:)        = vInd1:vInd2;
        N(fInd,:)        = n;

        numRead = numRead + 1;
    end

end

Body:
Assuming your faces are in a n-by-3 array F:

% temporary array
T = [F(:,1) F(:,2) ; F(:,1) F(:,3) ; F(:,2) F(:,3)];

% get the edges
E = unique([min(T,[],2), max(T,[],2)],'rows');

% build the adjacency matrix
n = max(E(:,2));
A = sparse(E(:,1), E (:,2), ones(size(E,1),1), n, n);
A = A + A';

NB: sparse arrays are often useful for such adjacency matrix, especially in the large limit.

Best,


问:
Jasmine-node expect not executed
I started testing today with Jasmine, which is new to me. Since I am working with a GraphQL-server, developed with NodeJS, I am using jasmine-node.

The following is my first spec I write myself, and I thought it was working:

```<code>const request = require('request');
const config = require('../sources/config');

const base_url = `http://localhost:${config.graphqlPort}/${config.graphqlRoute}`;

describe("GraphQLServer.", () => {
it("Should expect something.", () => {
    expect(1).not.toEqual(2);
    expect(1).toEqual(1);
    expect(true).toBe(true);
    expect(false).not.toBe(true);
});

describe('When request is made.', () => {
    it('Returns statuscode 200.', () => {
        request.get(base_url, (error, response, body) => {
            console.log('Error: ', error);
            console.log(base_url);
            console.log('StatusCode: ', response && response.statusCode);
            console.log('Body:', body);
            expect(true).toBe(true);
            expect(true).toBe(false);
            expect(response.statusCode).toBe(200);
            expect(response.statusCode).toBe(400);
            done();
            });
        });
    });
});
</code>```

This gives the following result:

```<code>    ..

Finished in 0.018 seconds
2 tests, 4 assertions, 0 failures, 0 skipped

Error:  null
http://localhost:8000/graphql
StatusCode:  400
Body: {"errors":[{"message":"Must provide query string."}]}
</code>```

A lot of this is exactly what I expect. I do a request without a query-string, so the errors in body are expected.

The problem is: the 4 useless (obvious) expects inside it("Should expect something") are working just fine. Those are the 4 assertions in the result. The other 4 expect's inside it("Returns statuscode 200.") are simply not in the result (they don't fail and they don't pass), but the console.log's are.

Every example I find online seems to do exactly what I do right here, yet I don't manage to get this to work.

答:
Kev is right, but the syntax in Jasmine involves putting your expect statement in the promise result, after async execution completion. It would look something like this:</p>

```<code>it ("should do a thing with promises", function(done) {
            myObject.doAThingWithPromises('')
                .then(function (promiseResult) {
                    expect(promiseResult).toBeDefined();
                    done();
                })
        });
</code>```

Title: Jasmine-node expect not executed

Body:
I started testing today with Jasmine, which is new to me. Since I am working with a GraphQL-server, developed with NodeJS, I am using jasmine-node.

The following is my first spec I write myself, and I thought it was working:

const request = require('request');
const config = require('../sources/config');

const base_url = `http://localhost:${config.graphqlPort}/${config.graphqlRoute}`;

describe("GraphQLServer.", () => {
it("Should expect something.", () => {
    expect(1).not.toEqual(2);
    expect(1).toEqual(1);
    expect(true).toBe(true);
    expect(false).not.toBe(true);
});

describe('When request is made.', () => {
    it('Returns statuscode 200.', () => {
        request.get(base_url, (error, response, body) => {
            console.log('Error: ', error);
            console.log(base_url);
            console.log('StatusCode: ', response && response.statusCode);
            console.log('Body:', body);
            expect(true).toBe(true);
            expect(true).toBe(false);
            expect(response.statusCode).toBe(200);
            expect(response.statusCode).toBe(400);
            done();
            });
        });
    });
});

This gives the following result:

    ..

Finished in 0.018 seconds
2 tests, 4 assertions, 0 failures, 0 skipped

Error:  null
http://localhost:8000/graphql
StatusCode:  400
Body: {"errors":[{"message":"Must provide query string."}]}

A lot of this is exactly what I expect. I do a request without a query-string, so the errors in body are expected.

The problem is: the 4 useless (obvious) expects inside it("Should expect something") are working just fine. Those are the 4 assertions in the result. The other 4 expect's inside it("Returns statuscode 200.") are simply not in the result (they don't fail and they don't pass), but the console.log's are.

Every example I find online seems to do exactly what I do right here, yet I don't manage to get this to work.

Body:
Kev is right, but the syntax in Jasmine involves putting your expect statement in the promise result, after async execution completion. It would look something like this:

it ("should do a thing with promises", function(done) {
            myObject.doAThingWithPromises('')
                .then(function (promiseResult) {
                    expect(promiseResult).toBeDefined();
                    done();
                })
        });


问:
<rich:listShuttle> usage
```<code><rich:listShuttle sourceValue="#{positionList.resultlist)}"

      targetValue="#{cvHome.instance.positions}"

       var="pos"
       sourceCaptionLabel="Current Positions"
       targetCaptionLabel="Interested Positions"
       sourceListWidth="300"
       targetListWidth="300"">
     <rich:column>
          <f:facet name="header">Positon Name</f:facet>
          <h:outputText value="#{pos.name}"/>
     </rich:column>
     <s:convertEntity/>
</rich:listShuttle>
</code>```

Error: javax.el.PropertyNotFoundException: /cvGiris.xhtml @526,48 sourceValue="#{positionList.resultList}": Property 'resultList' not writable on type java.util.List

How can i handle with this problem ???

答: But i have a seam entity with the name of Position. "#{positionList.resultlist)}" it returns me a resultlist from the database. "#{cvHome.instance.positions}" it is a Position arraylist. i think this problem stems from this difference :D</p>

Title: <rich:listShuttle> usage

Body:
<rich:listShuttle sourceValue="#{positionList.resultlist)}"

      targetValue="#{cvHome.instance.positions}"

       var="pos"
       sourceCaptionLabel="Current Positions"
       targetCaptionLabel="Interested Positions"
       sourceListWidth="300"
       targetListWidth="300"">
     <rich:column>
          <f:facet name="header">Positon Name</f:facet>
          <h:outputText value="#{pos.name}"/>
     </rich:column>
     <s:convertEntity/>
</rich:listShuttle>

Error: javax.el.PropertyNotFoundException: /cvGiris.xhtml @526,48 sourceValue="#{positionList.resultList}": Property 'resultList' not writable on type java.util.List

How can i handle with this problem ???


问:
Inserting DATETIME to SQL from PHP
I can't seem to store the datetime to the database.

```<code>public function add_post($username, $content) {
    date_default_timezone_set("Asia/Manila");
    $date = date("m/d/Y h:i A");
    $final = strtotime($date);
    $time_posted = date("m/d/Y h:i A", $final);

    $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";

        return $this->db->query($sql);
}
</code>```

It looks like this in the database
0000-00-00 00:00:00

Here is my posts table: Posts table

答:
The date-time field should be formatted as:</p>

```<code>$time_posted = date("Y-m-d H:i:s", $final);
</code>```

Title: Inserting DATETIME to SQL from PHP

Body:
I can't seem to store the datetime to the database.

public function add_post($username, $content) {
    date_default_timezone_set("Asia/Manila");
    $date = date("m/d/Y h:i A");
    $final = strtotime($date);
    $time_posted = date("m/d/Y h:i A", $final);

    $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";

        return $this->db->query($sql);
}

It looks like this in the database
0000-00-00 00:00:00

Here is my posts table: Posts table

Body:
The date-time field should be formatted as:

$time_posted = date("Y-m-d H:i:s", $final);


问:
UIImage from UIApplicationShortcutIcon
There are some great "Quick Action Icons" available at https://developer.apple.com/ios/human-interface-guidelines/graphics/system-icons/.

Is it possible to make a UIImage from one of these UIApplicationShortcutIcons to use on, say, a UIButton. For example, the mail icon:

```<code>let mailIcon = UIApplicationShortcutIcon(type: .mail)
let mailImage = UIImage( ... )
</code>```

Any help would be appreciated. Thanks.

答: These images are not available using normal API, but they are part of the UIKit bundle. You can use a tool, such as iOS-Artwork-Extractor, to extract the 1x, 2x and 3x variants of those images, and then you can add them to your project.</p>

Title: UIImage from UIApplicationShortcutIcon

Body:
There are some great "Quick Action Icons" available at https://developer.apple.com/ios/human-interface-guidelines/graphics/system-icons/.

Is it possible to make a UIImage from one of these UIApplicationShortcutIcons to use on, say, a UIButton. For example, the mail icon:

let mailIcon = UIApplicationShortcutIcon(type: .mail)
let mailImage = UIImage( ... )

Any help would be appreciated. Thanks.


问:
Best way to storage positions after click in button inside Recycler View
I have Recycler View like in this picture.
After click to button (B in picture) i want to get position id and storage this positions in best possible way to access and list data in other activity. After all I want to send all positions in ArrayList (for example) by Retrofit to backend.

Any solution?

答:
This is code from my working project hope will help you.

```<code>// all item click listener
private RowItemElementClickListener mListener;

public RowViewHolder(View itemView) {
    super(itemView);

    // constructor

    button.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
            if (getListener() != null) {
                getListener().onLayoutClick(view, RowViewHolder.this.getAdapterPosition());
            }
        }
    });
}
</code>```

Interface

```<code>import android.view.View;

/**
 * Created by Wasim on 17/06/16.
 */
public interface RowItemElementClickListener {

    void onLayoutClick(View v, int position);
    boolean onLayoutLongClick(View v, int position);

}
</code>```

Use this interface with recycler view to pass any object click event to activity or fragment. implement interface in that and you have full control over click and long click.

Body:
This is code from my working project hope will help you.

// all item click listener
private RowItemElementClickListener mListener;

public RowViewHolder(View itemView) {
    super(itemView);

    // constructor

    button.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
            if (getListener() != null) {
                getListener().onLayoutClick(view, RowViewHolder.this.getAdapterPosition());
            }
        }
    });
}

Interface

import android.view.View;

/**
 * Created by Wasim on 17/06/16.
 */
public interface RowItemElementClickListener {

    void onLayoutClick(View v, int position);
    boolean onLayoutLongClick(View v, int position);

}

Use this interface with recycler view to pass any object click event to activity or fragment. implement interface in that and you have full control over click and long click.


问:
It is possible to use Microsoft Azure Queue to replace Thread?
I am trying to use Microsoft Azure Queue to replace the Thread with a Queue in my progruma, I currently use the Thread to perform some functions, and I would like instead to use those Azure Queue to be able to manage and execute such functions, but studying a little The tool has seen that the CloudQueueMessage can only contain a String or a Byte [], someone knows if there would be a way to use Queue to perform these functions.

I'm currently using my Thread Like.

```<code>Thread thread = new Thread(new System.Threading.ThreadStart(timer.StartTimer));
thread.Name = "IdTipoConsulta=" + Convert.ToString(entityTipoConsulta.IdTipoConsulta) +
              ";" + entityTipoConsulta.Nome +
              ";" + DateTime.Now.ToString() +
              ";" + Guid.NewGuid().ToString();
thread.Start();
listThread.Add(thread);
</code>```

答: A Queue doesn't do work for you. You use a Queue to asynchronously send messages to another application or service that will then be triggered to do the necessary processing in the background. The best services to use for implementing the background processing code that is triggered by messages in a Queue are Azure Functions and Azure Web Jobs.</p>

Body:
I am trying to use Microsoft Azure Queue to replace the Thread with a Queue in my progruma, I currently use the Thread to perform some functions, and I would like instead to use those Azure Queue to be able to manage and execute such functions, but studying a little The tool has seen that the CloudQueueMessage can only contain a String or a Byte [], someone knows if there would be a way to use Queue to perform these functions.

I'm currently using my Thread Like.

Thread thread = new Thread(new System.Threading.ThreadStart(timer.StartTimer));
thread.Name = "IdTipoConsulta=" + Convert.ToString(entityTipoConsulta.IdTipoConsulta) +
              ";" + entityTipoConsulta.Nome +
              ";" + DateTime.Now.ToString() +
              ";" + Guid.NewGuid().ToString();
thread.Start();
listThread.Add(thread);


答:
This filters results based on user input. Optimizing for large lists, populating your own data and error handling left out for you to complete:

```<code>public partial class Form1 : Form
    {

        List<String> data;
        ListView lst = new ListView();
        TextBox txt = new TextBox();

        public Form1()
        {
            InitializeComponent();
            data = new List<string>("Lorem ipsum dolor sit amet consectetur adipiscing elit Suspendisse vel".Split());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Controls.Add(txt);
            lst.Top = 20;
            txt.TextChanged += new EventHandler(txt_TextChanged);
            lst.View = View.List;
            this.Controls.Add(lst);
            list_items("");
        }

        void txt_TextChanged(object sender, EventArgs e)
        {
            list_items(txt.Text);
        }

        void list_items(string filter)
        {
            lst.Items.Clear();
            List<string> results = (from d in data where d.Contains(filter) select d).ToList();
            foreach (string s in results)
            {
                lst.Items.Add(s);
            }
        }
    }
</code>```

To get the combobox to auto complete, set the AutoCompleteSource and AutoCompleteMode properties:

```<code>cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
</code>```

The ListItems source tells the combo to use it's items collection as the auto complete source.

Title: How to create an Auto-complete combo-box or text box to filter text containing a string

Body:
How do I create an Auto-complete ComboBox or TextBox that filters text based on a string?

For example: if I type an "a" in a TextBox, I only get to see all strings containing an "a".

Body:
This filters results based on user input. Optimizing for large lists, populating your own data and error handling left out for you to complete:

public partial class Form1 : Form
    {

        List<String> data;
        ListView lst = new ListView();
        TextBox txt = new TextBox();

        public Form1()
        {
            InitializeComponent();
            data = new List<string>("Lorem ipsum dolor sit amet consectetur adipiscing elit Suspendisse vel".Split());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Controls.Add(txt);
            lst.Top = 20;
            txt.TextChanged += new EventHandler(txt_TextChanged);
            lst.View = View.List;
            this.Controls.Add(lst);
            list_items("");
        }

        void txt_TextChanged(object sender, EventArgs e)
        {
            list_items(txt.Text);
        }

        void list_items(string filter)
        {
            lst.Items.Clear();
            List<string> results = (from d in data where d.Contains(filter) select d).ToList();
            foreach (string s in results)
            {
                lst.Items.Add(s);
            }
        }
    }

To get the combobox to auto complete, set the AutoCompleteSource and AutoCompleteMode properties:

cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

The ListItems source tells the combo to use it's items collection as the auto complete source.


问:
Why is gson library setting integer values to zero when converting json response to ArrayList<Object>?
I'm trying to convert a json format response from a web service into an ArrayList<Stop> object.

Before converting the json response into a java object I made sure the database is retreiving all the data in a proper manner, see the image below.

However after converting the json response and debugging the android app I realized that the value of all the integer fields has been set to zero.
The fields stopId and journeyId correspond to a PRIMARY_KEY and  FOREIGN_KEY respectively in the database.

This is the snipet of code I wrote to do this.

Thanks in advance for all your help.

答:
Try to change your model class according Camel Case Sensitive, change stop_id to stopId and journey_id to journeyId. Or configure your Gson according your necessities:

```<code>Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String jsonRepresentation = gson.toJson(someObject);
System.out.println(jsonRepresentation);
</code>```

Body:
Try to change your model class according Camel Case Sensitive, change stop_id to stopId and journey_id to journeyId. Or configure your Gson according your necessities:

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String jsonRepresentation = gson.toJson(someObject);
System.out.println(jsonRepresentation);


问:
spark rdd how to flat Key - Array(value) pair
I have a park paired rdd (key, Array(value1, value2, value3.....)).
what scala statement should I wrote?
How could I flat this rdd and creating a new rdd : (key, value1), (key, value2), (key, value3)....</p>

答:
As @moto said, it is simply

rdd.flatMapValues(v => v)

A more verbose but arguably more readable option:

```<code>rdd.flatMap {
   case (key, values) => values.map(v => key -> v)
}
</code>```

Body:
As @moto said, it is simply

rdd.flatMapValues(v => v)

A more verbose but arguably more readable option:

rdd.flatMap {
   case (key, values) => values.map(v => key -> v)
}