问:
How do I clean a dart build? And modify the g++ flags?
I'm cross-building dart for armel (a client hired me to solve problems there)

I'm building on ubuntu 14.04 (the armel gcc/g++ is 4.7.3).

I want to take out -Werror since I'm seeing:

```<code>  /usr/bin/arm-linux-gnueabi-g++ '-DDART_NO_SNAPSHOT' '-DDART_PRECOMPILER' '-DTARGET_ARCH_ARM' '-DNDEBUG' '-D_FORTIFY_SOURCE=2' -Iruntime  -Werror -Wall -Wextra -Wno-unused-parameter -Wnon-virtual-dtor -Wvla -Woverloaded-virtual -g3 -ggdb3 -fno-rtti -fno-exceptions -fstack-protector -Wa,--noexecstack -marm -mfpu=vfp -Wno-psabi -fno-strict-overflow -O3 -ffunction-sections -fno-omit-frame-pointer  -MMD -MF out/ReleaseXARM/.deps/out/ReleaseXARM/obj.target/libdart_vm_nosnapshot/runtime/vm/compiler.o.d.raw  -c -o out/ReleaseXARM/obj.target/libdart_vm_nosnapshot/runtime/vm/compiler.o runtime/vm/compiler.cc
In file included from runtime/vm/isolate.h:18:0,
                 from runtime/vm/growable_array.h:15,
                 from runtime/vm/compiler.h:9,
                 from runtime/vm/compiler.cc:5:
runtime/vm/thread.h: In static member function 'static dart::RawError* dart::Compiler::CompileClass(const dart::Class&)':
runtime/vm/thread.h:167:17: error: variable 'thread' might be clobbered by 'longjmp' or 'vfork' [-Werror=clobbered]
cc1plus: all warnings being treated as errors
make: *** [out/ReleaseXARM/obj.target/libdart_vm_nosnapshot/runtime/vm/compiler.o] Error 1
BUILD FAILED
</code>```

I'm working with this dart git tree:

```<code>commit 1d028eed8dfa00ac9d4ff685e61b01e6909dbeb4
Author: Paul Berry <paulberry@google.com>
Date:   Wed Nov 30 12:28:51 2016 -0800
</code>```

答: This is an actual bug in the code. One way to fix it would be to mark the thread variable volatile.

Body:
I'm cross-building dart for armel (a client hired me to solve problems there)

I'm building on ubuntu 14.04 (the armel gcc/g++ is 4.7.3).

I want to take out -Werror since I'm seeing:

  /usr/bin/arm-linux-gnueabi-g++ '-DDART_NO_SNAPSHOT' '-DDART_PRECOMPILER' '-DTARGET_ARCH_ARM' '-DNDEBUG' '-D_FORTIFY_SOURCE=2' -Iruntime  -Werror -Wall -Wextra -Wno-unused-parameter -Wnon-virtual-dtor -Wvla -Woverloaded-virtual -g3 -ggdb3 -fno-rtti -fno-exceptions -fstack-protector -Wa,--noexecstack -marm -mfpu=vfp -Wno-psabi -fno-strict-overflow -O3 -ffunction-sections -fno-omit-frame-pointer  -MMD -MF out/ReleaseXARM/.deps/out/ReleaseXARM/obj.target/libdart_vm_nosnapshot/runtime/vm/compiler.o.d.raw  -c -o out/ReleaseXARM/obj.target/libdart_vm_nosnapshot/runtime/vm/compiler.o runtime/vm/compiler.cc
In file included from runtime/vm/isolate.h:18:0,
                 from runtime/vm/growable_array.h:15,
                 from runtime/vm/compiler.h:9,
                 from runtime/vm/compiler.cc:5:
runtime/vm/thread.h: In static member function 'static dart::RawError* dart::Compiler::CompileClass(const dart::Class&)':
runtime/vm/thread.h:167:17: error: variable 'thread' might be clobbered by 'longjmp' or 'vfork' [-Werror=clobbered]
cc1plus: all warnings being treated as errors
make: *** [out/ReleaseXARM/obj.target/libdart_vm_nosnapshot/runtime/vm/compiler.o] Error 1
BUILD FAILED

I'm working with this dart git tree:

commit 1d028eed8dfa00ac9d4ff685e61b01e6909dbeb4
Author: Paul Berry <paulberry@google.com>
Date:   Wed Nov 30 12:28:51 2016 -0800


来源: stackexchange

问:
Calculating number of nodes in BST using recursion c++
I'm trying to find the number of nodes in a BST using recursion. Here is my code

```<code>struct Node{
    int key;
    struct Node* left;
    struct Node* right;

    Node(){
        int key = 0;
        struct Node* left = nullptr;
        struct Node* right = nullptr;
    }
};
</code>```

src_root is the address of the root node of the tree.

```<code>int BST::countNodes(Node* src_root, int sum){

        if((src_root==root && src_root==nullptr) || src_root==nullptr)
            return 0;
        else if(src_root->left==nullptr || src_root->right==nullptr)
            return sum;
        return countNodes(src_root->left, sum + 1) + countNodes(src_root->right, sum + 1) + 1;
        }
</code>```

However my code only seems to work if there are 3 nodes. Anything greater than 3 gives wrong answer. Please help me find out what's wrong with it. Thanks!

答:
It is a long time ago since I made anything in C/C++ so if there might be some syntax errors.

```<code>int BST::countNodes(Node *scr_root)
{
    if (scr_root == null) return 0;
    return 1 + countNodes(scr_root->left) + countNodes(scr_root->right);
}
</code>```

I think that will do the job.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find the number of nodes in a BST using recursion. Here is my code

struct Node{
    int key;
    struct Node* left;
    struct Node* right;

    Node(){
        int key = 0;
        struct Node* left = nullptr;
        struct Node* right = nullptr;
    }
};

src_root is the address of the root node of the tree.

int BST::countNodes(Node* src_root, int sum){

        if((src_root==root && src_root==nullptr) || src_root==nullptr)
            return 0;
        else if(src_root->left==nullptr || src_root->right==nullptr)
            return sum;
        return countNodes(src_root->left, sum + 1) + countNodes(src_root->right, sum + 1) + 1;
        }

However my code only seems to work if there are 3 nodes. Anything greater than 3 gives wrong answer. Please help me find out what's wrong with it. Thanks!

Body:
It is a long time ago since I made anything in C/C++ so if there might be some syntax errors.

int BST::countNodes(Node *scr_root)
{
    if (scr_root == null) return 0;
    return 1 + countNodes(scr_root->left) + countNodes(scr_root->right);
}

I think that will do the job.


问:
How to show confirm box before removing tag from select2
How to show confirm box before removing a tag from select2? I have a text box where I have two options selected on removing of any of them I want to display a warning message. Can anyone help me in this?
In HTML I have element as </p>

```<code>    <div class="form-group">
    <label for="name" class="col-lg-3 control-label required">Select Type</label>
    <div class="col-lg-9">
        <select id="typeselect" class="form-control" name="crm" required>
            <option value='0'>Select Type</option>
            <option value='1'>Type1</option>
            <option value='2'>Type2</option>
        </select>
    </div>
  </div>
</code>```

<p>And in the js file </p>

```<code>$("#typeselect").select2({
        placeholder: 'Select Type'
    });
</code>```

答:
Here is 2 ways of doing it:

Use a simple Confirm, like if (confirm("Are you sure?")) {// your deletion code}

Use Jquery-UI - Dialog see example below

$("#typeselect").select2({
  placeholder: 'Select Type'
});

$("#remove").click(function() {
  var selectedval = $("#typeselect option:selected").val();
  if (selectedval > 0) {
    $("#dialog-confirm").dialog({
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $("#typeselect option:selected").remove();
          $(this).dialog("close");
        },
        Cancel: function() {
          $(this).dialog("close");
        }
      }
    });
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dialog-confirm {
  display: none
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

  Select Type

    <select id="typeselect" class="form-control" name="crm" required>
            <option value='0'>Select Type</option>
            <option value='1'>Type1</option>
            <option value='2'>Type2</option>
        </select>
    <button id="remove">Remove selected value</button>

Do you wish to delete this option?

```

Body:
How to show confirm box before removing a tag from select2? I have a text box where I have two options selected on removing of any of them I want to display a warning message. Can anyone help me in this?
In HTML I have element as

    Select Type

        <select id="typeselect" class="form-control" name="crm" required>
            <option value='0'>Select Type</option>
            <option value='1'>Type1</option>
            <option value='2'>Type2</option>
        </select>

And in the js file

$("#typeselect").select2({
        placeholder: 'Select Type'
    });

Body:
Here is 2 ways of doing it:

Use a simple Confirm, like if (confirm("Are you sure?")) {// your deletion code}

Use Jquery-UI - Dialog see example below

$("#typeselect").select2({
  placeholder: 'Select Type'
});

$("#remove").click(function() {
  var selectedval = $("#typeselect option:selected").val();
  if (selectedval > 0) {
    $("#dialog-confirm").dialog({
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $("#typeselect option:selected").remove();
          $(this).dialog("close");
        },
        Cancel: function() {
          $(this).dialog("close");
        }
      }
    });
  }
})

#dialog-confirm {
  display: none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="form-group">
  <label for="name" class="col-lg-3 control-label required">Select Type</label>
  <div class="col-lg-9">
    <select id="typeselect" class="form-control" name="crm" required>
            <option value='0'>Select Type</option>
            <option value='1'>Type1</option>
            <option value='2'>Type2</option>
        </select>
    <button id="remove">Remove selected value</button>
    <div id="dialog-confirm" title="Delete option">
      <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>Do you wish to delete this option?</p>
    </div>
  </div>
</div>


问:
JITWatch assembly code generation
I am trying to use JITWatch to see how assembler code corresponds to original Java source code. However, JITWatch does not seem to see my assembly code and prints the following message:

Assembly not found. Was -XX:+PrintAssembly option used?

I am using Oracle's JRE 1.8.0_121 on Windows 10 Home. I've added dissembly dll's to my JRE. The dll's were downloaded from FCML project. I can confirm that assembly is generated when I run program with java -XX:+UnlockDiagnosticVMOptions  -XX:+PrintAssembly test.Test options.

I've configured JITWatch paths so that *.java and *.class files are visible to it. For JITWatch analysis I run my Java program with java -XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation -XX:+PrintAssembly test.Test and open the generated .log file with JITWatch. It can see the Java code and bytecode, but not the assembly. I suspect the problem is caused by the fact that assembly is printed to standard output (to the console) and not to log file. Is there an option I am missing?

答: It was a bug that occured when JITWatch was used together with FCML dissassembler. Thanks to prompt reaction by program developer it is fixed now.</p>

Title: JITWatch assembly code generation


问:
How to make Jsoup fetch the desktop version of a URL
I'm trying to scrape web-pages for their meta-data using JSoup in an Android app, but it's ending up downloading mobile versions for websites. Is there a way to make websites believe that the request is coming from a desktop client?</p>

答:
Use desktop user-agent, something like that:</p>

```<code>doc = Jsoup.connect("https://www.facebook.com/")
      .userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
      .referrer("http://www.google.com")
      .get();
</code>```

Body:
Use desktop user-agent, something like that:

doc = Jsoup.connect("https://www.facebook.com/")
      .userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
      .referrer("http://www.google.com")
      .get();


问:
Multiple row insert into two tables avoiding loops
I have a set of value which have to be inserted into two tables.Input has say 5 row and I have to insert these 5 rows into table A first.Table A has a identity column.Next i have to insert these 5 rows into table B with an extra column which is the identity from table A.
How this can be done with out using any loops?
Any help will be highly helpful.</p>

```<code>INSERT INTO TABLE_A(COL2,COL3)
SELECT COL2,COL3 FROM #TEMP_TAB

set @identityval=@@identity
INSERT INTO TABLE_B(COLA,COLB,COLC)
 SELECT @identityval,COL2,COL3,COL4 FROM #TEMP_TAB
</code>```

答:
What you want to do is not possible.
You can get only the value from the last insert using the @@identity variable. This way its possible to add to multiple tables setting the right foreign key without selecting the just inserted row again using a cursor. This approach is not useful when inserting multiple rows at once.

From the documentation:
Use the @@identity global variable to retrieve the last value inserted into an IDENTITY column. The value of @@identity changes each time an insert or select into attempts to insert a row into a table.

Here is a procedure which inserts a single row and you can use the return value to create a reference to the inserted data in another table:

```<code>create procedure reset_id as
    set identity_insert sales_daily on
    insert into sales_daily (syb_identity, stor_id)
         values (102, "1349")
    select @@identity
select @@identity

execute reset_id
</code>```

Body:
I have a set of value which have to be inserted into two tables.Input has say 5 row and I have to insert these 5 rows into table A first.Table A has a identity column.Next i have to insert these 5 rows into table B with an extra column which is the identity from table A.
How this can be done with out using any loops?
Any help will be highly helpful.

INSERT INTO TABLE_A(COL2,COL3)
SELECT COL2,COL3 FROM #TEMP_TAB

set @identityval=@@identity
INSERT INTO TABLE_B(COLA,COLB,COLC)
 SELECT @identityval,COL2,COL3,COL4 FROM #TEMP_TAB

Body:
What you want to do is not possible.
You can get only the value from the last insert using the @@identity variable. This way its possible to add to multiple tables setting the right foreign key without selecting the just inserted row again using a cursor. This approach is not useful when inserting multiple rows at once.

From the documentation:
Use the @@identity global variable to retrieve the last value inserted into an IDENTITY column. The value of @@identity changes each time an insert or select into attempts to insert a row into a table.

Here is a procedure which inserts a single row and you can use the return value to create a reference to the inserted data in another table:

create procedure reset_id as
    set identity_insert sales_daily on
    insert into sales_daily (syb_identity, stor_id)
         values (102, "1349")
    select @@identity
select @@identity

execute reset_id


问:
Linking shared libraries with gcc on Linux
I need to compile and, most importantly, link a C program that uses a proprietary function present in a shared library file. Because of lack of communication with the previous development team, there is no proper documentation. I declared a function prototype (because I know the number and type of arguments):

```<code>int CustomFunction(unsigned char *in, int size);
</code>```

Since that function name can be grepped from /customlibs/libcustom.so, I tried to compile the code and link it like this:

```<code>gcc -L/customlibs testing.c -o testing -lcustom
</code>```

Which throws a few error messages looking like this:

```<code>/customlibs/libcustom.so: undefined reference to `AnotherCustomFunction'
</code>```

Obviously, I need to tell linker to include other libraries as well, and, to make things worse, they need to be in certain order. I tried exporting LD_LIBRARY_PATH, using -Wl,-rpath=, -Wl,--no-undefined and -Wl,--start-group. Is there an easy way to give the linker all the .so files without the proper order?

答: You should also include all the header files of your shared library by adding the -I option of gcc, for example : gcc [...] -I/path/to/your/lib/header/files [...]

Body:
I need to compile and, most importantly, link a C program that uses a proprietary function present in a shared library file. Because of lack of communication with the previous development team, there is no proper documentation. I declared a function prototype (because I know the number and type of arguments):

int CustomFunction(unsigned char *in, int size);

Since that function name can be grepped from /customlibs/libcustom.so, I tried to compile the code and link it like this:

gcc -L/customlibs testing.c -o testing -lcustom

Which throws a few error messages looking like this:

/customlibs/libcustom.so: undefined reference to `AnotherCustomFunction'

Obviously, I need to tell linker to include other libraries as well, and, to make things worse, they need to be in certain order. I tried exporting LD_LIBRARY_PATH, using -Wl,-rpath=, -Wl,--no-undefined and -Wl,--start-group. Is there an easy way to give the linker all the .so files without the proper order?


问:
Previous month datetime pandas
I have a datetime instance declared as follows:

```<code>dtDate = datetime.datetime(2016,1,1,0,0)
</code>```

How do I get the previous month and previous year from dtDate?

e.g. something like:

```<code>dtDate.minusOneMonth()
# to return datetime.datetime(2015,12,1,0,0)
</code>```

答:
You can use:

```<code>dtDate = datetime.datetime(2016,1,1,0,0)

print (dtDate - pd.DateOffset(months=1))
2015-12-01 00:00:00

print (dtDate - pd.DateOffset(years=1))
2015-01-01 00:00:00
</code>```

Add s is important, because if use year only:

```<code>print (dtDate - pd.DateOffset(year=1))
0001-01-01 00:00:00
</code>```

Title: Previous month datetime pandas

Body:
I have a datetime instance declared as follows:

dtDate = datetime.datetime(2016,1,1,0,0)

How do I get the previous month and previous year from dtDate?

e.g. something like:

dtDate.minusOneMonth()
# to return datetime.datetime(2015,12,1,0,0)

Body:
You can use:

dtDate = datetime.datetime(2016,1,1,0,0)

print (dtDate - pd.DateOffset(months=1))
2015-12-01 00:00:00

print (dtDate - pd.DateOffset(years=1))
2015-01-01 00:00:00

Add s is important, because if use year only:

print (dtDate - pd.DateOffset(year=1))
0001-01-01 00:00:00


问:
Java 2d Array print out index at certain element
Lets say i got this :

```<code>int b[][];
b = new int[4][4];
for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b[i].length; j++) {
        b[i][j] = (Math.random() * 10);
    }
}
</code>```

And i want to print out at which [i][j] the value is < 5, how would i do this?

答: You already know how to iterate over the 2D array. Just put a if clause within the inner loop with your condition and call print with the indexes i and j

Body:
Lets say i got this :

int b[][];
b = new int[4][4];
for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b[i].length; j++) {
        b[i][j] = (Math.random() * 10);
    }
}

And i want to print out at which [i][j] the value is < 5, how would i do this?


问:
What’s the best way to load a JSONObject from a json text file?
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

```<code>XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));
</code>```

The output is:

```<code>Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)
</code>```

答:
With java 8 you can try this:</p>

```<code>import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}
</code>```

Body:
What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exception:

XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));

The output is:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)

Body:
With java 8 you can try this:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}


问:
Removing node when subnode meet a specific conditon
I'm trying to remove node from an xml file when the subnode "number" equals 0. Here what is look like.

```<code><deFac xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="baba_002.xsd">
  <fact>
    <refact>163620515-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>0</number>
      <brut>81.46</brut>
      <net>81.46</net>
    </demfact>
   </fact>
  <fact>
    <refact>163621197-02</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>11</number>
      <brut>61.44</brut>
      <net>61.44</net>
    </demfact>
  </fact>
  <fact>
    <refact>163621203-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>1</number>
      <brut>4.55</brut>
      <net>4.55</net>
    </demfact>
  </fact>
  <fact>
    <refact>163621198-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>0</number>
      <brut>1.71</brut>
      <net>1.71</net>
    </demfact>
  </fact>
</deFac>
</code>```

What I want is that

```<code><deFac xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="baba_002.xsd">
  <fact>
    <refact>163621197-02</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>11</number>
      <brut>61.44</brut>
      <net>61.44</net>
    </demfact>
  </fact>
  <fact>
    <refact>163621203-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>1</number>
      <brut>4.55</brut>
      <net>4.55</net>
    </demfact>
  </fact>
</deFac>
</code>```

This the xslt that I tried but it's not giving me the results that I wanted

First try:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 <xsl:template match="fact[number = !0]"/>
</xsl:stylesheet>
</code>```

Second try

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="deFac/fact"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="deFac/fact/[demfact/number != '0']">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
    </xsl:copy>
  </xsl:template>
  </xsl:stylesheet>
</code>```

Do you know where I made my mistake ? I'm really blocked and everything I tried seems to not work as excpected.

Thank you in advance for your help

答: In your first attempt, change <xsl:template match="fact[number = !0]"/> to <xsl:template match="fact[demfact/number = 0]"/>.

Body:
I'm trying to remove node from an xml file when the subnode "number" equals 0. Here what is look like.

<deFac xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="baba_002.xsd">
  <fact>
    <refact>163620515-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>0</number>
      <brut>81.46</brut>
      <net>81.46</net>
    </demfact>
   </fact>
  <fact>
    <refact>163621197-02</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>11</number>
      <brut>61.44</brut>
      <net>61.44</net>
    </demfact>
  </fact>
  <fact>
    <refact>163621203-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>1</number>
      <brut>4.55</brut>
      <net>4.55</net>
    </demfact>
  </fact>
  <fact>
    <refact>163621198-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>0</number>
      <brut>1.71</brut>
      <net>1.71</net>
    </demfact>
  </fact>
</deFac>

What I want is that

<deFac xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="baba_002.xsd">
  <fact>
    <refact>163621197-02</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>11</number>
      <brut>61.44</brut>
      <net>61.44</net>
    </demfact>
  </fact>
  <fact>
    <refact>163621203-01</refact>
    <date>2016-09-06</date>
    <demfact>
      <number>1</number>
      <brut>4.55</brut>
      <net>4.55</net>
    </demfact>
  </fact>
</deFac>

This the xslt that I tried but it's not giving me the results that I wanted

First try:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 <xsl:template match="fact[number = !0]"/>
</xsl:stylesheet>

Second try

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="deFac/fact"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="deFac/fact/[demfact/number != '0']">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
    </xsl:copy>
  </xsl:template>
  </xsl:stylesheet>

Do you know where I made my mistake ? I'm really blocked and everything I tried seems to not work as excpected.

Thank you in advance for your help


问:
Observable that emit items on demand
I want to create an Observable that will emit items on demand, that means I want a single subscribe to Observable and notify Observable that I need new item based on my request.

This is what I have done using PublishSubject:

```<code>public class RecognizeSubject {

PublishSubject<Bitmap> mSubject;

private Context mContext;
private FaceDetector mFaceDetecor;

public RecognizeSubject(Context mContext) {
    this.mContext = mContext;
    this.mSubject = PublishSubject.create();
}

public void detect(Bitmap btm){
    mSubject.onNext(btm);
}

public Flowable<SinglePhotoId> execute() {
    return mSubject.toFlowable(BackpressureStrategy.DROP)
            .observeOn(Schedulers.newThread())
            .map(bitmap1 -> recognize(bitmap1))
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(disposable -> initialize())
            .doFinally(() -> release());
}

private void initialize() {
    mFaceDetecor = new FaceDetector.Builder(mContext)
            .setTrackingEnabled(false)
            .setLandmarkType(FaceDetector.ALL_LANDMARKS)
            .build();
}

private void release() {
    if (mFaceDetecor != null)
        mFaceDetecor.release();
}

private SinglePhotoId recognize(Bitmap bitmap) {
    //SystemClock.sleep(3000);
   //make hard background work and return SinglePhotoId object
}
</code>```

}

and here is a usage in Activity class:

```<code>private void takeSubjectSnap() {
    if (mSubject == null)
        mSubject = new RecognizeSubject(getBaseContext());

    if (mDisposable == null || mDisposable.isDisposed()) {
        mDisposable = mSubject.execute()
                .subscribe(this::handleDetectionSuccess,
                        this::handleDetectionError,
                        this::handleDetectionCompleted);
    }

    mSnapshotButton.setProgress(true);
    mSubject.detect(myVideoView.getBitmap());
}
</code>```

So basically I subscribe to Flowable object and pass Bitmap object to my Subject class to proceed and return result via Flowable, is that solution right or can produce some memory leaks?

Is there any better solution to send an object to Observable to proceed and return result via a standard onNext() method?

答:
RxRelays can be handy in this situation

Create a PublishRelay subject.

Subscribe on it.

And pass on data using publishRelaySubject.call(your_object);

https://github.com/JakeWharton/RxRelay

Title: Observable that emit items on demand

Body:
I want to create an Observable that will emit items on demand, that means I want a single subscribe to Observable and notify Observable that I need new item based on my request.

This is what I have done using PublishSubject:

public class RecognizeSubject {

PublishSubject<Bitmap> mSubject;

private Context mContext;
private FaceDetector mFaceDetecor;

public RecognizeSubject(Context mContext) {
    this.mContext = mContext;
    this.mSubject = PublishSubject.create();
}

public void detect(Bitmap btm){
    mSubject.onNext(btm);
}

public Flowable<SinglePhotoId> execute() {
    return mSubject.toFlowable(BackpressureStrategy.DROP)
            .observeOn(Schedulers.newThread())
            .map(bitmap1 -> recognize(bitmap1))
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(disposable -> initialize())
            .doFinally(() -> release());
}

private void initialize() {
    mFaceDetecor = new FaceDetector.Builder(mContext)
            .setTrackingEnabled(false)
            .setLandmarkType(FaceDetector.ALL_LANDMARKS)
            .build();
}

private void release() {
    if (mFaceDetecor != null)
        mFaceDetecor.release();
}

private SinglePhotoId recognize(Bitmap bitmap) {
    //SystemClock.sleep(3000);
   //make hard background work and return SinglePhotoId object
}

}

and here is a usage in Activity class:

private void takeSubjectSnap() {
    if (mSubject == null)
        mSubject = new RecognizeSubject(getBaseContext());

    if (mDisposable == null || mDisposable.isDisposed()) {
        mDisposable = mSubject.execute()
                .subscribe(this::handleDetectionSuccess,
                        this::handleDetectionError,
                        this::handleDetectionCompleted);
    }

    mSnapshotButton.setProgress(true);
    mSubject.detect(myVideoView.getBitmap());
}

So basically I subscribe to Flowable object and pass Bitmap object to my Subject class to proceed and return result via Flowable, is that solution right or can produce some memory leaks?

Is there any better solution to send an object to Observable to proceed and return result via a standard onNext() method?


问:
Can I change what context is used to inject my handler?
Our e3/e4 RCP application consists of a bunch of components with model fragments. Before the upgrade to e4 we had Guice modules in each of the components to inject members into the class.

Currently we have set up a superclass to detect custom DoExecute and DoCanExecute annotations that uses the ContextInjectionFactory to invoke these methods with a custom context.

Example:

```<code>        IEclipseContext subContext = (IEclipseContext) context.get(contextName);
    return (T) ContextInjectionFactory.invoke(this, annotation, subContext);
</code>```

This succeeds in using a specific context to inject members while executing the methods we have created annotations for, but is a little ugly and will have to be done for all annotations that inject in e4.

What is the best way in e4 to define and use a custom context? Note: We do not want to use the IApplicationContext as it would go against the modular setup per component.

答:
The IEclipseContext is managed by the Eclipse4 framework in a hierarchic fashion. Usually, you have the ApplicationContext as parent context, and then a hierarchy of child contexts, for example Workbench > Window > Perspective > Part.

Given my experience in E4 development, in the case of a multi-module application, I would store my model objects in the ApplicationContext, using different keys.

Let me explain: the IEclipseContext is an hashtable where you can store multiple objects using different keys. So, each module (fragment, or bundle) in your system, can persist its model data into the IApplicationContext using a different key.

As an example, if you have threee modules, in your system where one is the platform and two are simply "module1" and "module2", you can store the data of each module, in the application context, as follows:

```<code>**KEY**                 **VALUE**
org.myapp.platform  Java Object representing data model of the platform
org.myapp.module1   Java Object representing data model of the module1
org.myapp.module2   Java Object representing data model of the module2
</code>```

By the way, if you are concerned about the data exposed in the context, you could delete a context object, by setting a null value in correspondence of a specific key.

Hope this helps.

You can dig deeper looking at the following references:

Interface IEclipseContext API

EclipseSource Eclipse4 Dependency Injection Basics

Eclipse Wiki Eclipse4 Dependency Injection

Vogella's Article on Eclipse 4 and DI

Brian's presentation on Advanced use of Eclipse4 DI Framework

Body:
Our e3/e4 RCP application consists of a bunch of components with model fragments. Before the upgrade to e4 we had Guice modules in each of the components to inject members into the class.

Currently we have set up a superclass to detect custom DoExecute and DoCanExecute annotations that uses the ContextInjectionFactory to invoke these methods with a custom context.

Example:

        IEclipseContext subContext = (IEclipseContext) context.get(contextName);
    return (T) ContextInjectionFactory.invoke(this, annotation, subContext);

This succeeds in using a specific context to inject members while executing the methods we have created annotations for, but is a little ugly and will have to be done for all annotations that inject in e4.

What is the best way in e4 to define and use a custom context? Note: We do not want to use the IApplicationContext as it would go against the modular setup per component.

Body:
The IEclipseContext is managed by the Eclipse4 framework in a hierarchic fashion. Usually, you have the ApplicationContext as parent context, and then a hierarchy of child contexts, for example Workbench > Window > Perspective > Part.

Given my experience in E4 development, in the case of a multi-module application, I would store my model objects in the ApplicationContext, using different keys.

Let me explain: the IEclipseContext is an hashtable where you can store multiple objects using different keys. So, each module (fragment, or bundle) in your system, can persist its model data into the IApplicationContext using a different key.

As an example, if you have threee modules, in your system where one is the platform and two are simply "module1" and "module2", you can store the data of each module, in the application context, as follows:

**KEY**                 **VALUE**
org.myapp.platform  Java Object representing data model of the platform
org.myapp.module1   Java Object representing data model of the module1
org.myapp.module2   Java Object representing data model of the module2

By the way, if you are concerned about the data exposed in the context, you could delete a context object, by setting a null value in correspondence of a specific key.

Hope this helps.

You can dig deeper looking at the following references:

Interface IEclipseContext API

EclipseSource Eclipse4 Dependency Injection Basics

Eclipse Wiki Eclipse4 Dependency Injection

Vogella's Article on Eclipse 4 and DI

Brian's presentation on Advanced use of Eclipse4 DI Framework


问:
Asp.net membership never logout
Im using forms authentication and SqlMembershipProvider, what do I need to do so the user never logout automatically?</p>

答: You can change your cookie's expiration date using timeout on your forms element in the web.config.</p>

ContentLicense: CC BY-SA 2.5

Title: Asp.net membership never logout


问:
Jenkins - can the “Execute Shell” execute SSH commands
I use 'Execute Shell' to run below command in Jenkins, but nothing happened in the remote server

```<code>ssh -v baiming.zhang@192.168.0.47 'pybot.bat --argumentfile E:\project\robot_framework\第一个测试项目\logs\argfile.txt E:\project\robot_framework\第一个测试项目'
</code>```

below are the output of the Jenkins

答:
Use the Double quote (") to execute the commands on remote system.

ssh -v baiming.zhang@192.168.0.47 "pybot.bat --argumentfile E:\project\robot_framework\第一个测试项目\logs\argfile.txt E:\project\robot_framework\第一个测试项目"

Body:
I use 'Execute Shell' to run below command in Jenkins, but nothing happened in the remote server

ssh -v baiming.zhang@192.168.0.47 'pybot.bat --argumentfile E:\project\robot_framework\第一个测试项目\logs\argfile.txt E:\project\robot_framework\第一个测试项目'

below are the output of the Jenkins


问:
PHP get object with specific key value
I am trying to get only these metafields objects with namespace="global", how can I do that in PHP ?</p>

```<code><?php $response = {"metafields":[{"id":30007223558,"namespace":"global"}, {"id":454872458451,"namespace":"local"}, {"id":154644565,"namespace":"global"}]} ?>
<?php $response = json_decode($response); ?>
</code>```

答:
```<code>$response = json_decode($response, true);

$filtered['metafields'] = array_filter($response['metafields'], function ($item) {
   return $item['namespace'] === 'global';
});

var_dump($filtered);

array(1) {
  ["metafields"]=>
  array(2) {
    [0]=>
    array(2) {
      ["id"]=>
      int(30007223558)
      ["namespace"]=>
      string(6) "global"
    }
    [2]=>
    array(2) {
      ["id"]=>
      int(154644565)
      ["namespace"]=>
      string(6) "global"
    }
  }
}
</code>```

Title: PHP get object with specific key value

Body:
I am trying to get only these metafields objects with namespace="global", how can I do that in PHP ?

<?php $response = {"metafields":[{"id":30007223558,"namespace":"global"}, {"id":454872458451,"namespace":"local"}, {"id":154644565,"namespace":"global"}]} ?>
<?php $response = json_decode($response); ?>


问:
How to add a image at the center of a TableLayout
I have a TableLayout with some tablerow like this:

I want to add a image over the above layout under the circular mark as mention below:

Here is my layout code:

```<code>   <TableLayout
        android:layout_width="wrap_content"
        android:id="@+id/table1"
        android:gravity="center"
        android:layout_height="wrap_content">

        <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_1"
        android:background="@drawable/button"
        android:layout_margin="3dp"
        />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_2"
        android:background="@drawable/button"
        android:layout_margin="3dp" />

    </TableRow>
    <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_3"
        android:background="@drawable/button"
        android:layout_margin="3dp"
   />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_4"
        android:background="@drawable/button"
        android:layout_margin="3dp" />
    </TableRow>

</TableLayout>
</code>```

So how to add a image over this layout at the center position?

答:
Something like this would work.

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="biw.myapplication.MainActivity">

<TableLayout
    android:layout_width="wrap_content"
    android:id="@+id/table1"
    android:layout_gravity="center"
    android:layout_height="wrap_content">

    <TableRow>

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_1"
            android:background="@drawable/button"
            android:layout_margin="3dp"
            />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_2"
            android:background="@drawable/button"
            android:layout_margin="3dp" />

    </TableRow>
    <TableRow>

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_3"
            android:background="@drawable/button"
            android:layout_margin="3dp"
            />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_4"
            android:background="@drawable/button"
            android:layout_margin="3dp" />
    </TableRow>
</TableLayout>

<ImageView
    android:layout_gravity="center"
    android:layout_width="70dp"
    android:layout_height="70dp" />

</FrameLayout>
</code>```

It's worth noting that you should look into the difference between gravity and layout_gravity, gravity assigns the alignment of the widget within the layout, whereas layout_gravity assigns the alignment to the layout itself.

Also, this code only works if you assign a static width and height to the image.

Result:

Body:
I have a TableLayout with some tablerow like this:

I want to add a image over the above layout under the circular mark as mention below:

Here is my layout code:

   <TableLayout
        android:layout_width="wrap_content"
        android:id="@+id/table1"
        android:gravity="center"
        android:layout_height="wrap_content">

        <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_1"
        android:background="@drawable/button"
        android:layout_margin="3dp"
        />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_2"
        android:background="@drawable/button"
        android:layout_margin="3dp" />

    </TableRow>
    <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_3"
        android:background="@drawable/button"
        android:layout_margin="3dp"
   />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_4"
        android:background="@drawable/button"
        android:layout_margin="3dp" />
    </TableRow>

</TableLayout>

So how to add a image over this layout at the center position?

Body:
Something like this would work.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="biw.myapplication.MainActivity">

<TableLayout
    android:layout_width="wrap_content"
    android:id="@+id/table1"
    android:layout_gravity="center"
    android:layout_height="wrap_content">

    <TableRow>

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_1"
            android:background="@drawable/button"
            android:layout_margin="3dp"
            />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_2"
            android:background="@drawable/button"
            android:layout_margin="3dp" />

    </TableRow>
    <TableRow>

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_3"
            android:background="@drawable/button"
            android:layout_margin="3dp"
            />

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/img1_4"
            android:background="@drawable/button"
            android:layout_margin="3dp" />
    </TableRow>
</TableLayout>

<ImageView
    android:layout_gravity="center"
    android:layout_width="70dp"
    android:layout_height="70dp" />

</FrameLayout>

It's worth noting that you should look into the difference between gravity and layout_gravity, gravity assigns the alignment of the widget within the layout, whereas layout_gravity assigns the alignment to the layout itself.

Also, this code only works if you assign a static width and height to the image.

Result:


问:
PHP how can I display cards in 2 columns?
I currently have a method which finds all cards using a SQL statement to find all results. It looks as follows:

```<code><?php $cards = find_all_cards();
foreach {$cards as $card} echo "card->username";
?>
</code>```

I can use it to list all cards one after another, but I can't do that if I have 2 columns, because I need to create a new row. Ideally, I'd populate 1st column with half of results, and 2nd with other half.

Also I'd like to be able to sort my results using a filter, is it done via php? So for example sort by ascending username (I have many more fields that I could sort by)

FUNCTIONS:

```<code>  public static function find_all() {
    return static::find_by_sql("SELECT * FROM ".static::$table_name);
  }

public static function find_by_sql($sql=""){

     global $database;
     $result_set = $database->query($sql);
     $object_array = array();
     while ($row = $database->fetch_array($result_set)) {
       $object_array[]=static::instantiate($row);
     }
     return $object_array;
   }

   private static function instantiate($record){
   $class_name = get_called_class();
   $object = new $class_name;

   foreach($record as $attribute=>$value) {
    if($object->has_attribute($attribute)) {
      $object->$attribute = $value;
    }

   }
</code>```

答: Can this be of any help ? [PHP doc modulo]: http://php.net/manual/fr/language.operators.arithmetic.php EDIT: after reading your last comment/edit, it seems that you can use % operator : your HTML gives < div class="container contclass" >< div class="card-box" >YOUR DATA< /div >< /div >, so count the results of your query, and if %2 then insert a line breaker/clearing in CSS</p>

Body:
I currently have a method which finds all cards using a SQL statement to find all results. It looks as follows:

<?php $cards = find_all_cards();
foreach {$cards as $card} echo "card->username";
?>

I can use it to list all cards one after another, but I can't do that if I have 2 columns, because I need to create a new row. Ideally, I'd populate 1st column with half of results, and 2nd with other half.

Also I'd like to be able to sort my results using a filter, is it done via php? So for example sort by ascending username (I have many more fields that I could sort by)

FUNCTIONS:

  public static function find_all() {
    return static::find_by_sql("SELECT * FROM ".static::$table_name);
  }

public static function find_by_sql($sql=""){

     global $database;
     $result_set = $database->query($sql);
     $object_array = array();
     while ($row = $database->fetch_array($result_set)) {
       $object_array[]=static::instantiate($row);
     }
     return $object_array;
   }

   private static function instantiate($record){
   $class_name = get_called_class();
   $object = new $class_name;

   foreach($record as $attribute=>$value) {
    if($object->has_attribute($attribute)) {
      $object->$attribute = $value;
    }

   }


问:
How to increase character lengh in blogger snippet instead of using limited length, 'data:post.snippet'?
I'm currently using 'data:post.snippet' for blogger mobile snippet.

```<code><div class='post-body' style='color:black;'>
  <b:if cond='data:post.snippet'><data:post.snippet/></b:if>
</div>
</code>```

But its character length(140) is too low, and it doesn't give a line break between the headings and paragraphs. When there's a heading at the very start line break is necessary. Can someone please suggest me a javascript code to replace above code to overcome those two issues.

答:
You can utilize the data:post.longSnippet data tag which has the limit of upto 300-400 character

```<code><div class='post-body' style='color:black;'>
    <b:if cond='data:post.snippet'><data:post.longSnippet/></b:if>
</div>
</code>```

Otherwise, if you want to control the exact amount of text that you want to be visible in the snippet, then you can utilize the newly launched operator in the new themes

```<code><div class='post-body' style='color:black;'>
    <b:eval expr='snippet(data:post.body, {length: 450, links: false})' />
</div>
</code>```

snippet(string, options)

Produces a short snippet from an HTML string.

options: Object specifying the snippeting options, which are:

links: boolean for whether to preserve anchors/links in the snippet.
  Defaults to true.

linebreaks: boolean for whether to preserve linebreaks (tags) in the
  snippet. Defaults to true.

ellipsis: boolean for whether to append an ellipsis (…) to the end of
  the snippet. Defaults to true.

length: Number specifying the maximum length of the snippet.

Body:
I'm currently using 'data:post.snippet' for blogger mobile snippet.

  <data:post.snippet/>

But its character length(140) is too low, and it doesn't give a line break between the headings and paragraphs. When there's a heading at the very start line break is necessary. Can someone please suggest me a javascript code to replace above code to overcome those two issues.

Body:
You can utilize the data:post.longSnippet data tag which has the limit of upto 300-400 character

<div class='post-body' style='color:black;'>
    <b:if cond='data:post.snippet'><data:post.longSnippet/></b:if>
</div>

Otherwise, if you want to control the exact amount of text that you want to be visible in the snippet, then you can utilize the newly launched operator in the new themes

<div class='post-body' style='color:black;'>
    <b:eval expr='snippet(data:post.body, {length: 450, links: false})' />
</div>

snippet(string, options)

Produces a short snippet from an HTML string.

options: Object specifying the snippeting options, which are:

links: boolean for whether to preserve anchors/links in the snippet.
  Defaults to true.

linebreaks: boolean for whether to preserve linebreaks (tags) in the
  snippet. Defaults to true.

ellipsis: boolean for whether to append an ellipsis (…) to the end of
  the snippet. Defaults to true.

length: Number specifying the maximum length of the snippet.


问:
WPF - DataBind TextBlock.Text to Integer
I know this a really simple question..

I have a Textblock who's text property I want to be databound to an integer I have in the codebehind.. right now I'm doing this

```<code><TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding}"></TextBlock>
</code>```

Then in c#..

```<code>            this.TextBlockCompeltedSongsNumber.DataContext = CompeltedTracks;
</code>```

Where CompletedTracks is a public int

What am I missing?

答:
In the end I just made a class that implemented INotifyPorpertyChange

```<code>    //Global Declaration
information info = new information();
</code>```

later...

```<code>            this.TextBlockCompeltedSongsNumber.DataContext = info;
</code>```

and the information class

```<code>public class information : INotifyPropertyChanged
{
    private int failedTracks = 0;
    public int FailedTracks { get { return failedTracks; } set { failedTracks = value; OnPropertyChanged("FailedTracks"); } }
    private int compeltedTracks = 0;
    public int CompeltedTracks { get { return compeltedTracks; } set { compeltedTracks = value; OnPropertyChanged("CompeltedTracks"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}
</code>```

and finally in the xaml

```<code>                    <TextBlock Name="TextBlockCompletedSongs" Margin="5,0,5,0">Completed Songs:</TextBlock>
                <TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding Path=CompeltedTracks}"></TextBlock>
                <TextBlock Name="TextBlockFailedSongs" Margin="5,0,5,0">Failed Songs:</TextBlock>
                <TextBlock Name="TextBlockFailedSongsNumber" Text="{Binding Path=FailedTracks}"></TextBlock>
</code>```

It seems like a lot of work for something that should be simple... but I couldnt get it to work any other way... I dunno what I was doing wrong :O

Body:
I know this a really simple question..

I have a Textblock who's text property I want to be databound to an integer I have in the codebehind.. right now I'm doing this

<TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding}"></TextBlock>

Then in c#..

            this.TextBlockCompeltedSongsNumber.DataContext = CompeltedTracks;

Where CompletedTracks is a public int

What am I missing?

Body:
In the end I just made a class that implemented INotifyPorpertyChange

    //Global Declaration
information info = new information();

later...

            this.TextBlockCompeltedSongsNumber.DataContext = info;

and the information class

public class information : INotifyPropertyChanged
{
    private int failedTracks = 0;
    public int FailedTracks { get { return failedTracks; } set { failedTracks = value; OnPropertyChanged("FailedTracks"); } }
    private int compeltedTracks = 0;
    public int CompeltedTracks { get { return compeltedTracks; } set { compeltedTracks = value; OnPropertyChanged("CompeltedTracks"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

and finally in the xaml

                    <TextBlock Name="TextBlockCompletedSongs" Margin="5,0,5,0">Completed Songs:</TextBlock>
                <TextBlock Name="TextBlockCompeltedSongsNumber" Text="{Binding Path=CompeltedTracks}"></TextBlock>
                <TextBlock Name="TextBlockFailedSongs" Margin="5,0,5,0">Failed Songs:</TextBlock>
                <TextBlock Name="TextBlockFailedSongsNumber" Text="{Binding Path=FailedTracks}"></TextBlock>

It seems like a lot of work for something that should be simple... but I couldnt get it to work any other way... I dunno what I was doing wrong :O


问:
SQL - Only show results for one column in first instance of a duplicated record
I am finding it difficult to explain exactly what I am trying to achieve so I think it best to show a visual representation.

Example of how my query results currently look

Example of how I want the results to look

The report I am running shows a list of every product within orders. Each product has its own cost assigned to it. Another column is a delivery charge, but this is a charge assigned to the order; not individual products. I want to be able to show the delivery charge against the first product in each order ONLY.

I have attempted, for far too long, to try and find an answer to this query but have had no luck. I don't know if it is even possible so assistance of any sort, or even just being pointed in the right direction, would be of great help.

Thanks

EDIT.

If it helps here is my query:

```<code>SELECT dbo.Orders.EncryptedOrderId,
       dbo.OrderProduct.ProductID,
       dbo.OrderProduct.QuantityPerRecipient,
       dbo.OrderProduct.NumRecipients,
       dbo.OrderProduct.TotalQuantity,
       dbo.DocType.Name AS [Product Type],
       dbo.ProductGroup_Culture.Name AS [Product Group],
       RIGHT(CatalogNo, CHARINDEX('_', REVERSE('_' + CatalogNo)) -1) AS [HamptonsType],
       FORMAT(dbo.Orders.DateOrderCreated, 'dd/MM/yyyy HH:mm:ss') AS 'DateOrderCreated',
       CAST(REPLACE(dbo.Orders.ClearingResult, 'utf-8', 'utf-16') AS XML ).value('(/UserData//CostCenter/node())[1]', 'nvarchar(max)') AS [Cost Center],
       dbo.Users.FirstName,
       dbo.Users.LastName,
       dbo.Users.CompanyName AS [Branch Name],
       dbo.Users.Department AS Subsidiary,
       dbo.Users.Custom1,
       dbo.Users.Custom2,
       dbo.Users.Custom3,
       dbo.Users.Custom4,
       dbo.Users.Custom5,
       dbo.OrderProduct.TotalPrice,
       dbo.Orders.ShippingCharges,
       dbo.OrderProduct.OrderProductID,
       dbo.FileSubmissionDocument.OriginalFileType,
       COALESCE (dbo.FileSubmissionDocument.Title, dbo.Product_Culture.Name) AS [Product Name],
       OPDV.FriendlyValue AS 'BCard Recipient'
FROM dbo.DocType
INNER JOIN dbo.Doc
    ON dbo.DocType.DocTypeID = dbo.Doc.DocTypeID
INNER JOIN dbo.OrderProduct
    ON dbo.Doc.ProductID = dbo.OrderProduct.ProductID
LEFT JOIN dbo.Product
    ON dbo.Product.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroupMembership
    ON dbo.ProductGroupMembership.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroup_Culture
    ON dbo.ProductGroup_Culture.ProductGroupID = dbo.ProductGroupMembership.ProductGroupID
INNER JOIN dbo.Orders
    ON dbo.OrderProduct.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Users
    ON dbo.Orders.UserID = dbo.Users.UserID
INNER JOIN dbo.Product_Culture
    ON dbo.OrderProduct.ProductID = dbo.Product_Culture.ProductID
INNER JOIN dbo.Store_Culture
    ON dbo.Store_Culture.StoreID = dbo.Users.AssignedToStoreID FULL OUTER
JOIN dbo.FileSubmissionDocument
    ON dbo.OrderProduct.OrderProductID = dbo.FileSubmissionDocument.SubOrderProductID - 1
LEFT JOIN (SELECT OP.OrderProductID,
                  OP.DialID,
                  OP.FriendlyValue
           FROM OrderProductDialValue OP
           LEFT JOIN Dial DI ON DI.DialID = OP.DialID
           LEFT JOIN OrderProduct OT ON OT.OrderProductID = OP.OrderProductID
           LEFT JOIN Product PR ON PR.ProductID = OT.ProductID
           WHERE PR.ExternalID = 'BCName'
           AND DI.UProduceDialName = 'Name') OPDV ON OPDV.OrderProductID = dbo.OrderProduct.OrderProductID
WHERE ('@CUSTOMERNAME' is null
        OR '@CUSTOMERNAME' = ''
        OR dbo.Store_Culture.Name LIKE '%' + '@CUSTOMERNAME' + '%')
        AND dbo.OrderProduct.IsDraft = 0
        AND dbo.Orders.IsCart=0
        AND dbo.Orders.IsSaveForLater=0
        AND (('@DATE' <= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
        AND ((DATEADD(day, 1, '@DATE') >= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
AND dbo.Users.LastName NOT LIKE '%TEST%'
ORDER BY  dbo.Orders.OrderID DESC, dbo.OrderProduct.OrderProductID DESC
</code>```

The query runs through a reporting system on an online portal so the values that show as @CUSTOMERNAME or @DATE are variables based on values given at the time when the report is run.

答:
this may help you    </p>

```<code>select orderid,
    productid,
    productvalue,
    case ROW_NUMBER() over (partition by orderid order by orderid)
    when 1 then deliverycharge
    else null end as 'deliverycharge'
     from ........
</code>```

Body:
I am finding it difficult to explain exactly what I am trying to achieve so I think it best to show a visual representation.

Example of how my query results currently look

Example of how I want the results to look

The report I am running shows a list of every product within orders. Each product has its own cost assigned to it. Another column is a delivery charge, but this is a charge assigned to the order; not individual products. I want to be able to show the delivery charge against the first product in each order ONLY.

I have attempted, for far too long, to try and find an answer to this query but have had no luck. I don't know if it is even possible so assistance of any sort, or even just being pointed in the right direction, would be of great help.

Thanks

EDIT.

If it helps here is my query:

SELECT dbo.Orders.EncryptedOrderId,
       dbo.OrderProduct.ProductID,
       dbo.OrderProduct.QuantityPerRecipient,
       dbo.OrderProduct.NumRecipients,
       dbo.OrderProduct.TotalQuantity,
       dbo.DocType.Name AS [Product Type],
       dbo.ProductGroup_Culture.Name AS [Product Group],
       RIGHT(CatalogNo, CHARINDEX('_', REVERSE('_' + CatalogNo)) -1) AS [HamptonsType],
       FORMAT(dbo.Orders.DateOrderCreated, 'dd/MM/yyyy HH:mm:ss') AS 'DateOrderCreated',
       CAST(REPLACE(dbo.Orders.ClearingResult, 'utf-8', 'utf-16') AS XML ).value('(/UserData//CostCenter/node())[1]', 'nvarchar(max)') AS [Cost Center],
       dbo.Users.FirstName,
       dbo.Users.LastName,
       dbo.Users.CompanyName AS [Branch Name],
       dbo.Users.Department AS Subsidiary,
       dbo.Users.Custom1,
       dbo.Users.Custom2,
       dbo.Users.Custom3,
       dbo.Users.Custom4,
       dbo.Users.Custom5,
       dbo.OrderProduct.TotalPrice,
       dbo.Orders.ShippingCharges,
       dbo.OrderProduct.OrderProductID,
       dbo.FileSubmissionDocument.OriginalFileType,
       COALESCE (dbo.FileSubmissionDocument.Title, dbo.Product_Culture.Name) AS [Product Name],
       OPDV.FriendlyValue AS 'BCard Recipient'
FROM dbo.DocType
INNER JOIN dbo.Doc
    ON dbo.DocType.DocTypeID = dbo.Doc.DocTypeID
INNER JOIN dbo.OrderProduct
    ON dbo.Doc.ProductID = dbo.OrderProduct.ProductID
LEFT JOIN dbo.Product
    ON dbo.Product.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroupMembership
    ON dbo.ProductGroupMembership.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroup_Culture
    ON dbo.ProductGroup_Culture.ProductGroupID = dbo.ProductGroupMembership.ProductGroupID
INNER JOIN dbo.Orders
    ON dbo.OrderProduct.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Users
    ON dbo.Orders.UserID = dbo.Users.UserID
INNER JOIN dbo.Product_Culture
    ON dbo.OrderProduct.ProductID = dbo.Product_Culture.ProductID
INNER JOIN dbo.Store_Culture
    ON dbo.Store_Culture.StoreID = dbo.Users.AssignedToStoreID FULL OUTER
JOIN dbo.FileSubmissionDocument
    ON dbo.OrderProduct.OrderProductID = dbo.FileSubmissionDocument.SubOrderProductID - 1
LEFT JOIN (SELECT OP.OrderProductID,
                  OP.DialID,
                  OP.FriendlyValue
           FROM OrderProductDialValue OP
           LEFT JOIN Dial DI ON DI.DialID = OP.DialID
           LEFT JOIN OrderProduct OT ON OT.OrderProductID = OP.OrderProductID
           LEFT JOIN Product PR ON PR.ProductID = OT.ProductID
           WHERE PR.ExternalID = 'BCName'
           AND DI.UProduceDialName = 'Name') OPDV ON OPDV.OrderProductID = dbo.OrderProduct.OrderProductID
WHERE ('@CUSTOMERNAME' is null
        OR '@CUSTOMERNAME' = ''
        OR dbo.Store_Culture.Name LIKE '%' + '@CUSTOMERNAME' + '%')
        AND dbo.OrderProduct.IsDraft = 0
        AND dbo.Orders.IsCart=0
        AND dbo.Orders.IsSaveForLater=0
        AND (('@DATE' <= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
        AND ((DATEADD(day, 1, '@DATE') >= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
AND dbo.Users.LastName NOT LIKE '%TEST%'
ORDER BY  dbo.Orders.OrderID DESC, dbo.OrderProduct.OrderProductID DESC

The query runs through a reporting system on an online portal so the values that show as @CUSTOMERNAME or @DATE are variables based on values given at the time when the report is run.

Body:
this may help you

select orderid,
    productid,
    productvalue,
    case ROW_NUMBER() over (partition by orderid order by orderid)
    when 1 then deliverycharge
    else null end as 'deliverycharge'
     from ........


问:
QWebException: "'NoneType' object has no attribute 'with_context'" while evaluating "doc.with_context({'lang':doc.partner_id.lang})"
I am new to odoo, I created a module by inheriting sales_order to create a custom report. I am getting the above error when I am printing the report. Need help please?

Here is the code snippets:

test/my_module.py:

```<code>class sale_order(models.Model):
   _name = 'sale.order'
   _description = 'Inheritance'
  _inherit = 'sale.order'
</code>```

test/views/report_template_view.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
    <openerp>
        <data>
            <template id="test_report">
                <t t-call="report.html_container">
                <t t-call="report.internal_layout">
                <t t-set="doc" t-value="doc.with_context({'lang':doc.partner_id.lang})"/>
                <div class="page">
                    <div class="oe_structure"/>
                        <div> <strong><left>User</left></strong>
                            <p t-field="doc.user_id"/>
                        </div>
                     </div>
            </t>
           </t>
   </template>
</data>
</code>```

How can I access records in custom_report_template?

答:
i know i'm late but the name of the variable containing the recordSet passed to the template is docs not doc.
and you are trying to get value from a variable that don't have anything.

```<code>doc.with_context({'lang':doc.partner_id.lang})
</code>```

i think you need to do docs not doc because doc is None
This why all template in loop docs :

```<code>   <t t-foreach="docs" t-as="o">
</code>```

Body:
I am new to odoo, I created a module by inheriting sales_order to create a custom report. I am getting the above error when I am printing the report. Need help please?

Here is the code snippets:

test/my_module.py:

class sale_order(models.Model):
   _name = 'sale.order'
   _description = 'Inheritance'
  _inherit = 'sale.order'

test/views/report_template_view.xml:

<?xml version="1.0" encoding="utf-8"?>
    <openerp>
        <data>
            <template id="test_report">
                <t t-call="report.html_container">
                <t t-call="report.internal_layout">
                <t t-set="doc" t-value="doc.with_context({'lang':doc.partner_id.lang})"/>

 <left>User</left>

            </t>
           </t>
   </template>
</data>

How can I access records in custom_report_template?

Body:
i know i'm late but the name of the variable containing the recordSet passed to the template is docs not doc.
and you are trying to get value from a variable that don't have anything.

doc.with_context({'lang':doc.partner_id.lang})

i think you need to do docs not doc because doc is None
This why all template in loop docs :

   <t t-foreach="docs" t-as="o">


问:
URLClassLoader finding X but not Y in same folder
General idea: I'm writing on a loader for java that allows dynamically reloading classes to allow for changing the implementation, without restarting the entire program to keep the main application running and minimize downtimes. Every external piece of code is grouped by "modules", each module has a main class with a "onEnable, postEnable, onDisable" entry/exit point and can consist of any amount of classes. To load a module, the class containing the entry point is specified, then loaded. I'll reference them as "modules" and "additional classes" in the following, "module" being the class containing the above mentioned functions by implementing the "public interface Module", "additional classes" refer to everything the module would use on runtime but isn't a Module by itself (e.g. we have a Module called "Car implements Module", and that module requires a class "Engine" to function -> "Car" is the module, "Engine" is an additional class")

Code of what I'm doing to load a module initially (name is a String containing the full classname including path, example given later):

```<code>Class<?> clazz = mainLoader.loadClass(name);
Module module = (Module) clazz.newInstance();
addLoadedModule(module);
enableLoadedModule(module);
</code>```

And here's how I reload the module when it's already existing, so that I can override the implementation. "m" is an instance of the current implementation of the Module that is supposed to be reloaded.

```<code>boolean differs = false;
Class<?> newClass = null;
try (URLClassLoader cl = new URLClassLoader(urls, mainLoader.getParent()))
{
    // Try to load the class and check if it differs from the already known one
    newClass = cl.loadClass(m.getClass().getName());
    differs = m.getClass() != newClass;
}
catch (IOException | ClassNotFoundException e)
{
    // Class couldn't be found, abort.
    e.printStackTrace();
    return;
}
if (!differs)
{
    // New class == old class -> no need to reload it
    return;
}
Module module = null;
try
{
    // Try to instantiate the class
    module = (Module) newClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
    // Can't instantiate, abort
    e.printStackTrace();
    return;
}
// Check versions, only reload if the new implementation's version differs from the current one. Version is a custom annotation, don't worry about that; the version check works fine
Version oldVersion = m.getClass().getAnnotation(Version.class);
Version newVersion = module.getClass().getAnnotation(Version.class);
if (oldVersion.equals(newVersion))
{
    return;
}
// And if everything went well, disable and remove the old module from the list, then add and enable the new module.
disableModule(m);
modules.remove(m);
modules.put(module, false);
enableLoadedModule(module);
</code>```

This is the mainLoader, urls is an URL[] pointing to the location containing the external classes to load:

```<code>mainLoader = new URLClassLoader(urls, this.getClass().getClassLoader());
</code>```

The problem arises when I try to RE-load an implementation, that requires multiple classes:

Module of class A requires class B to function. This is what happens when I try to dynamically load, then reload class A:

load A -> "Sure, but I'll need B with it." -> automatically loads B -> "Here ya go, A works fine now."
reload A -> "Sure, but I'll need B with it." -> crashes because B couldn't be found

Both classes are located in the exact same folder, structure like this:

Class A implements Module: com/foo/bar/A.class

Class B: com/foo/bar/B.class

urls: ["com/foo/bar/"]

I call the function with load("com.foo.bar.A"), which works when attempting to load it the first time, but fails when trying to reload it as described above.

It works fine when trying to load a "single class module", the problem arises when the module relies on an additional external class. I tried using different classloaders to use as the parent for the URLClassLoader in the reloading process, those being the sysloader, Module.class.getClassLoader(), mainLoader (using that one, it won't ever find the new class definition because it already knows about it and therefor won't even attempt to load it from the drive again) and the mainLoader.getParent(), the classloader of the old module, and the parent of the modules classloader.

I'm probably just overseeing something obvious, but I can't figure out why it would manage to load the "extra" classes the first time, but fail when I reload the base class...

If you need any debug outputs or exact errors let me know, I replaced the debug outputs with comments explaining what does what so I got a fairly detailed log of what's happening when, but I didn't seem it to be necessary as it goes through the entire "check and then load" process just fine, it crashes when trying to enable the module. The "onEnable" method of the module requires the additional class B, that's where it fails. As I said, if you need the implementation of the classes A and B, Module, any other code or the debug outputs let me know and I'll add them in as requested.

答:
There's a few things you can try:

Create an extension of UrlClassLoader so that you can track when it loads a class and what class loader is used to load the class.

Your other issue is make sure none of these classes are available on the "default" class path as that will cause that version to use. You are not overriding the default  class loading behaviour which is to check the parent for the class first.

The other issue you're probably facing relates to the way the VM caches classes - I'm not entirely sure how this works - but from what I've experienced it seems that once a class is loaded it puts it in a shared storage space so that it does not load the class again. This shared space class will not be unloaded until the class loader that loaded it goes unreachable.

Body:
General idea: I'm writing on a loader for java that allows dynamically reloading classes to allow for changing the implementation, without restarting the entire program to keep the main application running and minimize downtimes. Every external piece of code is grouped by "modules", each module has a main class with a "onEnable, postEnable, onDisable" entry/exit point and can consist of any amount of classes. To load a module, the class containing the entry point is specified, then loaded. I'll reference them as "modules" and "additional classes" in the following, "module" being the class containing the above mentioned functions by implementing the "public interface Module", "additional classes" refer to everything the module would use on runtime but isn't a Module by itself (e.g. we have a Module called "Car implements Module", and that module requires a class "Engine" to function -> "Car" is the module, "Engine" is an additional class")

Code of what I'm doing to load a module initially (name is a String containing the full classname including path, example given later):

Class<?> clazz = mainLoader.loadClass(name);
Module module = (Module) clazz.newInstance();
addLoadedModule(module);
enableLoadedModule(module);

And here's how I reload the module when it's already existing, so that I can override the implementation. "m" is an instance of the current implementation of the Module that is supposed to be reloaded.

boolean differs = false;
Class<?> newClass = null;
try (URLClassLoader cl = new URLClassLoader(urls, mainLoader.getParent()))
{
    // Try to load the class and check if it differs from the already known one
    newClass = cl.loadClass(m.getClass().getName());
    differs = m.getClass() != newClass;
}
catch (IOException | ClassNotFoundException e)
{
    // Class couldn't be found, abort.
    e.printStackTrace();
    return;
}
if (!differs)
{
    // New class == old class -> no need to reload it
    return;
}
Module module = null;
try
{
    // Try to instantiate the class
    module = (Module) newClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
    // Can't instantiate, abort
    e.printStackTrace();
    return;
}
// Check versions, only reload if the new implementation's version differs from the current one. Version is a custom annotation, don't worry about that; the version check works fine
Version oldVersion = m.getClass().getAnnotation(Version.class);
Version newVersion = module.getClass().getAnnotation(Version.class);
if (oldVersion.equals(newVersion))
{
    return;
}
// And if everything went well, disable and remove the old module from the list, then add and enable the new module.
disableModule(m);
modules.remove(m);
modules.put(module, false);
enableLoadedModule(module);

This is the mainLoader, urls is an URL[] pointing to the location containing the external classes to load:

mainLoader = new URLClassLoader(urls, this.getClass().getClassLoader());

The problem arises when I try to RE-load an implementation, that requires multiple classes:

Module of class A requires class B to function. This is what happens when I try to dynamically load, then reload class A:

load A -> "Sure, but I'll need B with it." -> automatically loads B -> "Here ya go, A works fine now."
reload A -> "Sure, but I'll need B with it." -> crashes because B couldn't be found

Both classes are located in the exact same folder, structure like this:

Class A implements Module: com/foo/bar/A.class

Class B: com/foo/bar/B.class

urls: ["com/foo/bar/"]

I call the function with load("com.foo.bar.A"), which works when attempting to load it the first time, but fails when trying to reload it as described above.

It works fine when trying to load a "single class module", the problem arises when the module relies on an additional external class. I tried using different classloaders to use as the parent for the URLClassLoader in the reloading process, those being the sysloader, Module.class.getClassLoader(), mainLoader (using that one, it won't ever find the new class definition because it already knows about it and therefor won't even attempt to load it from the drive again) and the mainLoader.getParent(), the classloader of the old module, and the parent of the modules classloader.

I'm probably just overseeing something obvious, but I can't figure out why it would manage to load the "extra" classes the first time, but fail when I reload the base class...

If you need any debug outputs or exact errors let me know, I replaced the debug outputs with comments explaining what does what so I got a fairly detailed log of what's happening when, but I didn't seem it to be necessary as it goes through the entire "check and then load" process just fine, it crashes when trying to enable the module. The "onEnable" method of the module requires the additional class B, that's where it fails. As I said, if you need the implementation of the classes A and B, Module, any other code or the debug outputs let me know and I'll add them in as requested.


问:
How to increase size limit for HTTP header value in request for Azure IIS?
Token is passed in Authorization header in GET request like this:

```<code>Authorization: Bearer <token here>
</code>```

Using trial and error I figured out that header value limit must be around 2048, because requests with tokens smaller than that are passed to my ASP.NET app without any changes and requests with larger tokens have Authorization header removed triggering 401 in my app.

App is published to Azure. It doesn't seem to matter whether request is GET or POST.

Limit looks similar to querystring limit so I've increased the allowed query string and it didn't help.

IIS version: 8.0 (from response headers)

答:
By default, the header length limit is 65536 which is set in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters registry.  I tested it both on my local machine and Azure Web App. Following is the code which I tested.

On server side I use

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        return Content(Request.Headers["Authorization"]);
    }
}
</code>```

On client side, I use

```<code>static async void SendRequest()
{
    HttpClient client = new HttpClient();
    string token = "";
    for (int i = 0; i < 2050; i++)
    {
        token = token + "0";
    }
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    HttpResponseMessage message = await client.GetAsync("http://xxx.azurewebsites.net/");
    string content = await message.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}
</code>```

I can get the Authorization parameter back.

Using trial and error I figured out that header value limit must be around 2048

Another way which would modified the limit is the headerLimits config section.  We could add length limit for specific header using this config section.

If I add following configuration to web.config. The request from my client was blocked and I got following error.

```<code><system.webServer>
  <security>
    <requestFiltering>
      <requestLimits>
        <headerLimits >
          <add header="Authorization" sizeLimit="2048" />
        </headerLimits>
      </requestLimits>
    </requestFiltering>
  </security>
</system.webServer>
</code>```

If I increase the sizeLimit to meet the length of request Authorization header, for example 2058. The request will be executed OK.

So please check whether you have modified the headerLimits config section in your web.config file. If yes, It will block your request if the length of this header is larger than the limit value. To solve it, we can increase the value of sizeLimit to modify the limit of Authorization header.

Body:
Token is passed in Authorization header in GET request like this:

Authorization: Bearer <token here>

Using trial and error I figured out that header value limit must be around 2048, because requests with tokens smaller than that are passed to my ASP.NET app without any changes and requests with larger tokens have Authorization header removed triggering 401 in my app.

App is published to Azure. It doesn't seem to matter whether request is GET or POST.

Limit looks similar to querystring limit so I've increased the allowed query string and it didn't help.

IIS version: 8.0 (from response headers)

Body:
By default, the header length limit is 65536 which is set in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters registry.  I tested it both on my local machine and Azure Web App. Following is the code which I tested.

On server side I use

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return Content(Request.Headers["Authorization"]);
    }
}

On client side, I use

static async void SendRequest()
{
    HttpClient client = new HttpClient();
    string token = "";
    for (int i = 0; i < 2050; i++)
    {
        token = token + "0";
    }
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
    HttpResponseMessage message = await client.GetAsync("http://xxx.azurewebsites.net/");
    string content = await message.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}

I can get the Authorization parameter back.

Using trial and error I figured out that header value limit must be around 2048

Another way which would modified the limit is the headerLimits config section.  We could add length limit for specific header using this config section.

If I add following configuration to web.config. The request from my client was blocked and I got following error.

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits>
        <headerLimits >
          <add header="Authorization" sizeLimit="2048" />
        </headerLimits>
      </requestLimits>
    </requestFiltering>
  </security>
</system.webServer>

If I increase the sizeLimit to meet the length of request Authorization header, for example 2058. The request will be executed OK.

So please check whether you have modified the headerLimits config section in your web.config file. If yes, It will block your request if the length of this header is larger than the limit value. To solve it, we can increase the value of sizeLimit to modify the limit of Authorization header.


问:
Delay ajax request for 3 seconds before processing
I have an ajax script to send data. I want to display .coin-flip for 3 seconds before the data is sent/processed. Once this 3 seconds are over the data will be sent to flip-process.php normally and then the return result will be displayed on success. But currently its so fast that I just can see the coin flipping here (the animation I want to display). Therefore, I want a delay of 3 seconds before processing the ajax request. How can I do so?

Here is my ajax script.

```<code><script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#coins").hide();
                $(".coin-flip").show();
      },
            success: function(html){
                $(".message").html(html).fadeIn();
                    $("#coins").show();
                    $(".coin-flip").hide();
            }
        });
        return false;
    });
});
</script>
</code>```

答:
Just use setTimeout inside your beforeSend block.

```<code><script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
            success: function(html){
                setTimeout(function(){

                    $(".message").html(html).fadeIn();
                    $("#coins").show();
                    $(".coin-flip").hide();

                },3000);
             }
        });
        return false;
    });
});
</script>
</code>```

Body:
Just use setTimeout inside your beforeSend block.

<script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
            success: function(html){
                setTimeout(function(){

                    $(".message").html(html).fadeIn();
                    $("#coins").show();
                    $(".coin-flip").hide();

                },3000);
             }
        });
        return false;
    });
});
</script>


问:
angular2 typescript $.cookie() is not a function
I installed @types/jquery.cookie@1.4.28, then in tsconfig.json I added jquery.cookie in types section. Visual Studio Code shows that $.cookie is available to use, but when I run my code I get error in console that $.cookie() is not a function. Where is the problem? Am I missing something? Should I reference it somewhere else?</p>

答:
Have you included the jquery.cookie package in your code? Or just the @types/jquery.cookie@1.4.28?

@types are just definition files for TypeScript, not the actual code it self. So we still need to install the code it self:

```<code>npm install --save jquery.cookie
</code>```

Then add it to your packaging, for instance for SystemJS:

```<code>SystemJS.config({
    'map': {
        'jquery.cookie': 'npm:jquery.cookie'
    },
    'paths': {
        'npm:': 'node_modules/'
    }
});
</code>```

To sum up:

@types are definitions to allow TypeScript understand code/packages written in JavaScript (as most of them are or at least compiled to). @types shouldn't be imported in the code it self. Only installed, the TypeScript compiler automatically looks for all defintions in node_modules/@types.

The package you want to use with TypeScript still needs to be installed with npm (or yarn). These hold the actual code.

Body:
Have you included the jquery.cookie package in your code? Or just the @types/jquery.cookie@1.4.28?

@types are just definition files for TypeScript, not the actual code it self. So we still need to install the code it self:

npm install --save jquery.cookie

Then add it to your packaging, for instance for SystemJS:

SystemJS.config({
    'map': {
        'jquery.cookie': 'npm:jquery.cookie'
    },
    'paths': {
        'npm:': 'node_modules/'
    }
});

To sum up:

@types are definitions to allow TypeScript understand code/packages written in JavaScript (as most of them are or at least compiled to). @types shouldn't be imported in the code it self. Only installed, the TypeScript compiler automatically looks for all defintions in node_modules/@types.

The package you want to use with TypeScript still needs to be installed with npm (or yarn). These hold the actual code.


问:
Quota calculator for live broadcasting and streaming
Anybody knows what is the quota for Broadcasting and Streaming insert and bind ? It looks that there isn't anything about that on youtube documentation.</p>

答:
The YouTube Live Streaming API is part of the YouTube Data API (in order to use it you need to enable the YouTube Data API).  This means the Live Streaming API uses the same quota from the YouTube Data API.

As far as bandwidth or how much you can stream goes, I do not think there are limitations.

ContentLicense: CC BY-SA 4.0


问:
SQL SELECT various names by various id's
I have this 3 tables:

main table:

```<code>  ID | OtherStuff1 | OtherStuff2 | IdProvince | IdTown
-----+-------------+-------------+------------+--------
   1 |   Stuff1    |   Stuff2    |      1     |   1
</code>```

province table:

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```

town table:

```<code>ID |   TownName
---+--------------
 1 |   TwName1
</code>```

Obviously the main table has foreign relationships with the province table and the town table.

The result I want is this one:

```<code>ID | OtherStuff1 | OtherStuff2 | IdProvince |   IdTown
---+-------------+-------------+------------+------------
 1 |   Stuff1    |   Stuff2    | ProvName1  |   TwName1
</code>```

I want to show the main table but with the names instead of the ID's.

I looked up other questions and I tried this one:

```<code>    SELECT *
        FROM main AS a
        INNER JOIN province AS b
        INNER JOIN town AS c
        WHERE a.IdProvince = b.ProvinceName
        AND a.IdTown = c.TownName

    AND Id=1; # this is added by me because I want to filter by id on the
              # main table, I don't want all the rows, just one filtered by ID.
</code>```

And this other one:

```<code> SELECT *
       FROM main AS a,
       INNER JOIN province AS b ON a.IdProvince = b.ProvinceName
       INNER JOIN town AS c ON a.IdTown = c.TownName
       WHERE Id=1;
</code>```

Also I would like that the query could be easy to use in the way that If I have the same problem, but instead of the main table and 2 tables, I have main table and 4 tables I could also use it just adding more "INNER JOINS" for example?

I'm trying to do this but I couldn't get it right, I get this Sql wrong every time and I don't find the correct way to do this, any ideas?

I'm using PDO and I show this on a web page.

"AND Id=1" --> this will be used like this --> "AND Id=:filterID".

I hope I explained myself right!

If you have any doubts just ask, I'll answer as fast as I can!

Thanks in advance!

---------------------------------------------------------------EDIT--------------------------------------------------------------

I already tryed the 3 answers I got and it doesn't work, I don't know why, I will add images to back up so you see.

This one works with no errors but I get no info back

```<code>SELECT a.Id, OtherStuff1, OtherStuff2, IdProvince, IdTown
 FROM main AS a
 INNER JOIN province AS b
 INNER JOIN town AS c
   WHERE a.IdProvince = b.ProvinceName
   AND a.IdTown = c.TownName
AND a.Id=1
</code>```

This is the result

This one the same and no info back, but anyways I get extra columns from the other tables that I don't need there.

```<code>SELECT *
 FROM main AS a ,province AS b , town AS c
  WHERE a.IdProvince = b.ProvinceName
  AND a.IdTown = c.TownName
AND a.Id=1
</code>```

This is the second result

I also tryed this one but I can't get it to work always shows me an error

```<code>SELECT *
   FROM
      (main AS a
      INNER JOIN province AS b ON a.IdProvince = b.ProvinceName) AS d
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1
</code>```

I can't post more than 2 photos because I don't have enough reputation but I paste the error here:

```<code>MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'd
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1 LI' at line 4
</code>```

And in case you ask or doubt, I did put the info in the tables, 1 row each so there is something in, but for some reason it doesn't gives me back that info.

-------------------------------------------------------LAST EDIT-------------------------------------------------------------

The 3 codes worked for me after trying them with a few edits, here are the 3 codes so people who might read this find this helpful.

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```0

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```1

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```2

Thanks a lot to the people who have helped me!

答:
Well, you are close, it's just that your join condition is wrong:</p>

```<code>SELECT  main.ID, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a
    INNER JOIN province AS b ON a.IdProvince = b.Id
    INNER JOIN town AS c ON a.IdTown = c.Id
    WHERE main.Id=1;
</code>```

Body:
I have this 3 tables:

main table:

  ID | OtherStuff1 | OtherStuff2 | IdProvince | IdTown
-----+-------------+-------------+------------+--------
   1 |   Stuff1    |   Stuff2    |      1     |   1

province table:

ID | ProvinceName
---+--------------
 1 |  ProvName1

town table:

ID |   TownName
---+--------------
 1 |   TwName1

Obviously the main table has foreign relationships with the province table and the town table.

The result I want is this one:

ID | OtherStuff1 | OtherStuff2 | IdProvince |   IdTown
---+-------------+-------------+------------+------------
 1 |   Stuff1    |   Stuff2    | ProvName1  |   TwName1

I want to show the main table but with the names instead of the ID's.

I looked up other questions and I tried this one:

    SELECT *
        FROM main AS a
        INNER JOIN province AS b
        INNER JOIN town AS c
        WHERE a.IdProvince = b.ProvinceName
        AND a.IdTown = c.TownName

    AND Id=1; # this is added by me because I want to filter by id on the
              # main table, I don't want all the rows, just one filtered by ID.

And this other one:

 SELECT *
       FROM main AS a,
       INNER JOIN province AS b ON a.IdProvince = b.ProvinceName
       INNER JOIN town AS c ON a.IdTown = c.TownName
       WHERE Id=1;

Also I would like that the query could be easy to use in the way that If I have the same problem, but instead of the main table and 2 tables, I have main table and 4 tables I could also use it just adding more "INNER JOINS" for example?

I'm trying to do this but I couldn't get it right, I get this Sql wrong every time and I don't find the correct way to do this, any ideas?

I'm using PDO and I show this on a web page.

"AND Id=1" --> this will be used like this --> "AND Id=:filterID".

I hope I explained myself right!

If you have any doubts just ask, I'll answer as fast as I can!

Thanks in advance!

---------------------------------------------------------------EDIT--------------------------------------------------------------

I already tryed the 3 answers I got and it doesn't work, I don't know why, I will add images to back up so you see.

This one works with no errors but I get no info back

SELECT a.Id, OtherStuff1, OtherStuff2, IdProvince, IdTown
 FROM main AS a
 INNER JOIN province AS b
 INNER JOIN town AS c
   WHERE a.IdProvince = b.ProvinceName
   AND a.IdTown = c.TownName
AND a.Id=1

This is the result

This one the same and no info back, but anyways I get extra columns from the other tables that I don't need there.

SELECT *
 FROM main AS a ,province AS b , town AS c
  WHERE a.IdProvince = b.ProvinceName
  AND a.IdTown = c.TownName
AND a.Id=1

This is the second result

I also tryed this one but I can't get it to work always shows me an error

SELECT *
   FROM
      (main AS a
      INNER JOIN province AS b ON a.IdProvince = b.ProvinceName) AS d
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1

I can't post more than 2 photos because I don't have enough reputation but I paste the error here:

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'd
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1 LI' at line 4

And in case you ask or doubt, I did put the info in the tables, 1 row each so there is something in, but for some reason it doesn't gives me back that info.

-------------------------------------------------------LAST EDIT-------------------------------------------------------------

The 3 codes worked for me after trying them with a few edits, here are the 3 codes so people who might read this find this helpful.

SELECT a.Id, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a
    INNER JOIN province AS b ON a.IdProvince = b.Id
    INNER JOIN town AS c ON a.IdTown = c.Id
    WHERE a.Id=1;

SELECT a.Id, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a
    INNER JOIN (province AS b, town AS c)
    ON (a.IdProvince = b.Id AND a.IdTown = c.Id)
    WHERE a.Id=1;

SELECT a.Id, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a ,province AS b , town AS c
    WHERE a.IdProvince = b.Id
    AND a.IdTown = c.Id
    AND a.Id=1;

Thanks a lot to the people who have helped me!

Body:
Well, you are close, it's just that your join condition is wrong:

SELECT  main.ID, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a
    INNER JOIN province AS b ON a.IdProvince = b.Id
    INNER JOIN town AS c ON a.IdTown = c.Id
    WHERE main.Id=1;